// VARIABLE DECLARATIONS
var getGNServiceURL = function(service) {
	return Env.locService+"/"+service;
};

function init() {}

// Read a cookie
function get_cookie ( cookie_name )
{
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );

  if ( results )
    return ( unescape ( results[1] ) );
  else
    return null;
}

// New browser windows
	function popNew(a)
	{
		msgWindow=window.open(a,"displayWindow","location=no, toolbar=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600")
		msgWindow.focus()
	}

	function openPage(what,type)
	{
		msgWindow=window.open(what,type,"location=yes, toolbar=yes, directories=yes, status=yes, menubar=yes, scrollbars=yes, resizable=yes, width=800, height=600")
		msgWindow.focus()
	}

	function popFeedback(a)
	{
		msgWindow=window.open(a,"feedbackWindow","location=no, toolbar=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600")
		msgWindow.focus()
	}

	function popWindow(a)
	{
		msgWindow=window.open(a,"popWindow","location=no, toolbar=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600")
		msgWindow.focus()
	}

	function popInterMap(a)
	{
		msgWindow=window.open(a,"InterMap","location=no, toolbar=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600")
		msgWindow.focus()
	}

// Forms
	function goSubmit(form_name) {
		document.forms[form_name].submit();
	}

	function goReset(form_name)
	{
		document.forms[form_name].reset();
	}

	function entSub(form_name) {
		if (window.event && window.event.keyCode == 13)
			goSubmit(form_name);
		else
			return true;
	}
    
// Navigation
	function goBack()
	{
		history.back();
	}

	function processCancel() {
		document.close();
	}

	function load(url)
	{
		document.location.href = url;
	}

	function doConfirm(url, message)
	{
		if(confirm(message))
		{
			load(url);
			return true;
		}
		return false;
	}

	function processSimpleMetadataSubmit(service)
	{
		var f = $('simplemetadata');
		
		if (isWhitespace(f.Depositor_individualName.value) || isWhitespace(f.Depositor_organisationName.value) || isWhitespace(f.Depositor_Address_deliveryPoint.value) || isWhitespace(f.Depositor_Address_administrativeArea.value) || isWhitespace(f.Depositor_Address_postalCode.value) || isWhitespace(f.Depositor_Address_country.value) || isWhitespace(f.Depositor_Address_electronicMailAddress.value) || isWhitespace(f.titleDS.value) || isWhitespace(f.abstractDS.value)) {
			alert(i18n('simpleMetadataMandatoryFields'));
			return;
		}
		
		if (!isEmail(f.Depositor_Address_electronicMailAddress.value)) {
			alert(i18n('simpleMetadataDepositorEmailInvalid'));
			return;
		}
		
		if (!isEmail(f.DS_Address_electronicMailAddress.value, true)) {
			alert(i18n('simpleMetadataDSEmailInvalid'));
			return;
		}
		
		Modalbox.show(getGNServiceURL(service),{height: 400, width: 600, params: f.serialize(true)});
	}

	function idxOperation(service, wait, btn){
		if (!confirm(i18n('doYouReallyWantToDoThis'))) return;

	  $(wait).style.display = 'block';
	  $(btn).style.display = 'none';
	  var http = new Ajax.Request(
		getGNServiceURL(service), 
	    {
	      method: 'get', 
	      parameters: null,
	      onComplete: function(originalRequest){},
	      onLoaded: function(originalRequest){},
	      onSuccess: function(originalRequest){                                       
	        // get the XML root item
		        var root = originalRequest.responseXML.documentElement;
	
	        var resp = root.getElementsByTagName('status')[0].firstChild.nodeValue;
	        $(wait).style.display = 'none';
	        $(btn).style.display = 'block';
	        if (resp == "true")
		          alert (i18n('metadata.admin.index.success'));
	        else
		          alert(i18n('metadata.admin.index.failed'));
	      },
	      onFailure: function(originalRequest){
	        $(wait).style.display = 'none';
	        $(btn).style.display = 'block';
	        alert(i18n('metadata.admin.index.failed'));
	      }
	    }
	  );
	}

	function feedbackSubmit()
	{
		var f = $('feedbackf');
		if (isWhitespace(f.comments.value)) {
			f.comments.value = 'No comment';
		}

		if (isWhitespace(f.name.value) || isWhitespace(f.org.value)) {
			alert("Please fill in a Name or Organization");
			return;
		} else if (!isEmail(f.email.value)) {
			alert("Please fill correct E-mail Address");
			return;
		} 

		Modalbox.show(getGNServiceURL('file.download'),{height: 400, width: 600, params: f.serialize(true)});
	}

	function doDownload(id, all) {
		var list = $('downloadlist').getElementsByTagName('INPUT');
		var pars = '&id='+id+'&access=private';

		var selected = false;
		for (var i=0; i<list.length; i++) {
			if (list[i].checked || all != null) {
				selected = true;
				var name = list[i].getAttribute('name');
				pars += '&fname='+name;
			}
		}

		if (!selected) {
			alert("You'd better select at least one file to download!");
			return;
		}

		Modalbox.show(getGNServiceURL('file.disclaimer') + "?" + pars, {height: 400, width: 600});
	}

	function massiveOperation(service, title, width, height, message)
	{

		if (message != null) {
			if(!confirm(message))
				return;
		}

		var url = Env.locService +'/' + service;
		if (height != null && height > 0) {
			Modalbox.show(url,{title: title, width: width, height: height, afterHide: function() { $('search-results-content').hide();}});
		} else {
			Modalbox.show(url,{title: title, width: width, afterHide: function() { $('search-results-content').hide();}});
		}
	}

/**********************************************************
***
***		SELECT ACTIONS
***
**********************************************************/

	function oActionsInit(name,id) {
   if (id === undefined) {
     id = "";
   }
   $(name+'Ele'+id).style.width = $(name+id).getWidth();
   $(name+'Ele'+id).style.top = $(name+id).positionedOffset().top + $(name+id).getHeight();
   $(name+'Ele'+id).style.left = $(name+id).positionedOffset().left;
	}

	function oActions(name,id) {
		if (id === undefined) {
			id = "";
  	}
		if (!$(name+'Ele'+id).style.top)
			oActionsInit (name, id);

  	if ($(name+'Ele'+id).style.display == 'none') {
    	$(name+'Ele'+id).style.display = 'block';
    	$(name+'Img'+id).src = off;
  	} else {
    	$(name+'Ele'+id).style.display = 'none';
    	$(name+'Img'+id).src = on;
  	}
	}

	function actionOnSelect(msg) {
		if ($('nbselected').innerHTML == 0 && $('oAcOsEle').style.display == 'none') {
			alert(msg);
		} else {
			oActions('oAcOs');
		}
	}

 	/*
   *Check and uncheck selected things
   */
	function check(selectdiv) {
		var checks = $(selectdiv).getElementsByTagName('INPUT');
		var checksLength = checks.length;				
		for (var i = 0; i < checksLength; i++) {
			checks[i].checked = true;
		}
	}

	function uncheck(selectdiv) {
		var checks = $(selectdiv).getElementsByTagName('INPUT');
		var checksLength = checks.length;				
		for (var i = 0; i < checksLength; i++) {
			checks[i].checked = false;
		}
	}

	function selectobject(service, selectdiv, id, selected){
		if (selected===true)
			selected='add';
		else if (selected===false)
			selected='remove';
		var param = 'id='+id+'&selected='+selected;
		var http = new Ajax.Request(
    	getGNServiceURL(service), 
			{
				method: 'get',
				parameters: param,
				onComplete: function(originalRequest){
					// console.log('onComplete');
				},
				onLoaded: function(originalRequest){
					// console.log('onLoaded');
				},
				onSuccess: function(originalRequest){
					var xmlString = originalRequest.responseText;
					
					// convert the string to an XML object
					var xmlobject = (new DOMParser()).parseFromString(xmlString, "text/xml");
					// get the XML root item
					var root = xmlobject.getElementsByTagName('response')[0];
					var nbSelected = root.getElementsByTagName('Selected')[0].firstChild.nodeValue;
					var item = document.getElementById('nbselected');
					item.innerHTML = nbSelected;
			},
			onFailure: function(originalRequest){
				alert('ERROR JAVASCRIPT '+service);
			}
		});
		if (selected=='remove-all') {
			uncheck(selectdiv);
		};
		if (selected=='add-all') {
			check(selectdiv);
		};
	}

/**********************************************************
***
***		BANNER MENU ACTIONS INCLUDING LOGIN/LOGOUT
***
**********************************************************/

	var adminWindow;

	function doBannerButton(url, title, width, height)
	{
		if (height != null && height > 0) {
			Modalbox.show(url,{title: title, height: height, width: width});
		} else {
			Modalbox.show(url,{title: title, width: width});
		}
		return true;
	}

	// Same as doBannerButton but afterhide we close adminWindow 
	function doAdminBannerButton(url, title, width)
	{
		Modalbox.show(url,{title: title, width: width, afterHide: function() { if (adminWindow) adminWindow.close(); }});
		return true;
	}

	var ViewEditWindow = Class.create({
		initialize: function(pane, id) {
			this.pane = pane;
			this.id = id;
		},
		editing: function() {
			if (this.pane && this.pane.closed) return false;
			if (this.pane.$('editForm')) return true;
			else return false;
		},
		focus: function() {
			this.pane.focus();
		},
		close: function() {
			this.pane.close();
		}
	});

	var viewEditWindows = [];

	function findWindow(id) {
		for (var i = 0, len = viewEditWindows.length; i < len; ++i) {
			var item = viewEditWindows[i];
			if (item.id == id) return item;
		}
		return null;
	}

	function popEditorViewer(a, id)
	{
		var viewEdit = findWindow(id);
		if (viewEdit && viewEdit.editing()) {
			viewEdit.focus();
			alert(i18n('editorInUse'));
			return;
		} 

		var addToArray = false;
		if (viewEdit == null) addToArray = true;

		viewEdit = new ViewEditWindow(window.open(a,"MetadataEditorViewer"+id,"location=no, toolbar=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600"),id);
		viewEdit.focus();
		if (addToArray) viewEditWindows.push(viewEdit);

	}

	function checkEditorAndClose() {
		for (var i = 0, len = viewEditWindows.length; i < len; ++i) {
			var item = viewEditWindows[i];
			if (item.editing()) {
				item.focus()
				alert(i18n('editorInUse'));
				return false;
			}
			item.close();
		}
		return true;
	}

	function checkReset() {
		if (confirm(i18n('resetWarning'))) {
			if (checkEditorAndClose()) return true;
		} 
		return false;
	}
	
	function doCreateCheck(service, form, closeCurrent) {
		descs = $('groups').getValue();
		if (descs.length == 0) {
			alert("Please select at least one group!");
			return;
		}
		doCreate(service, form, closeCurrent);
	}

	function doCreate(action, form, closeCurrent) {
		// serialize form, submit to action 
		var myAjax = new Ajax.Request(
			getGNServiceURL(action),
			{
				method: 'post',
				parameters: $(form).serialize(true),
				onSuccess: function(req) {
					// get uuid of created metadata
					var node = req.responseXML;
					if (node == null) {
						alert("Create metadata failed: "+node);
						return;
					}
					var id = xml.evalXPath(node, 'response/id');
					if (id == null) {
						alert("Create metadata failed: "+node);
						return;
					}
					// popEditorViewer with the metadata id in it
					popEditorViewer(getGNServiceURL('metadata.edit?id='+id), id);
					if (closeCurrent) self.close();
				},
				onFailure: function(req) {
					alert("ERROR: could not create new metadata from server ("+action+")");
				}
			}
		);
	}

	function popCreateWindow(a)
	{
		createWindow=window.open(a,"CreateMetadataWindow","location=no, toolbar=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600")
		createWindow.focus()
	}

	function doLogout(action) {
		if (checkReset()) {
			viewEditWindows.clear();
			goSubmit(action);
		} else {
		    location.replace(getGNServiceURL("main.home"));
		}
	}

	function checkLogin() {
		if (checkEditorAndClose()) {
			viewEditWindows.clear();
			return true;
		}
		return false;
	}

	function popAdminWindow(a)
	{
			
		adminWindow=window.open(a,"AdminWindow","location=no, toolbar=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=800, height=600")
		adminWindow.focus()
	}

	/*
   * Update the featureMap/recent additions if on simple search tab
   */
	function gn_updateRecentAdditions() 
	{
		timeval = setTimeout('doUpdateRecentAdditions()',200);
	}

	function doUpdateRecentAdditions()
	{

		clearNode('featuredMap');
		var myAjax = new Ajax.Updater(
			'featuredMap',
			getGNServiceURL('metadata.recent.additions.embedded'), 
			{
				method: 'get',
				onComplete: function() {},
				onFailure: function(req) {
					alert("ERROR: get recent additions failed: "+req.responseText);
				}
			}
		);
	}
		
/**********************************************************
***
***		USER-REGISTRATION ACTIONS
***
**********************************************************/

	function processRegSub(url)
	{
		// check start
		var invalid = " "; // Invalid character is a space
		var minLength = 6; // Minimum length
            
		if (document.userregisterform.name.value.length == 0) {
			alert(i18n('firstNameMandatory'));
			return;
		} 
		if (isWhitespace(document.userregisterform.name.value)) {
			alert(i18n('firstNameMandatory'));
			return;
		}    
		if (document.userregisterform.name.value.indexOf(invalid) > -1) {
			alert(i18n('spacesNot'));
			return;
		}	
			
		if (document.userregisterform.surname.value.length == 0) {
			alert(i18n('lastNameMandatory'));
			return;
		}  
		if (isWhitespace(document.userregisterform.surname.value)) {
			alert(i18n('lastNameMandatory'));
			return;
		}
		if (document.userregisterform.surname.value.indexOf(invalid) > -1) {
			alert(i18n('spacesNot'));
			return;
		}
			
		if (!isEmail(document.userregisterform.email.value)) {
			alert(i18n('emailAddressInvalid'));
			return;
		}
			
		var myAjax = new Ajax.Request(
			getGNServiceURL(url), 
				{
					method: 'post',
					parameters: $('userregisterform').serialize(true), 
						onSuccess: function(req) {
            	var output = req.responseText;
        			Modalbox.show(output,{title: "Your registration..", width: 300});
						},
						onFailure: function(req) {
            	alert("ERROR: registration failed: "+req.responseText+" status: "+req.status+" - Try again later?");
						}
				}
		);
	}
		
/**********************************************************
***
***	FEEDBACK ACTIONS	
***
**********************************************************/
       			
	function processFeedbackSubmit(url) {

		var f = $('feedbackf');
		if (isWhitespace(f.comments.value)) {
			alert("You'd better give us some feedback/comments!");
			return false;
		}
		if (isWhitespace(f.name.value) || isWhitespace(f.org.value)) {
			alert("Please fill in a Name or Organization");
			return false;
		} else if (!isEmail(f.email.value)) {
			alert("Please fill correct E-mail Address");
			return false;
		}

		Modalbox.show(getGNServiceURL(url),{title: "Thanks...", width: 300, params: f.serialize(true)});
  }
  
  
	/**********************************************************
	***
	***	FORGOTTEN PASSWORD ACTIONS	
	***
	**********************************************************/
	       			
		function processForgottenPwdSubmit(url) {

			var f = $('forgottenpwd');
			if (isWhitespace(f.username.value)) {
				alert(i18n("usernameMandatory"));
				return false;
			}

			Modalbox.show(getGNServiceURL(url),{title: i18n('changePassword'), width: 300, params: f.serialize(true)});
	  }
	  
	  
/**********************************************************
***
***	SIMPLE METADATA REGISTRATION 	
***
**********************************************************/

	function displaySelectedForm() {
		if ($('rbRegistered').checked) {
			$('existinguserdetails').show();
			$('newuserdetails').hide();
		} else {
			$('existinguserdetails').hide();
			$('newuserdetails').show();
		}
	}
	
	function reset(form) {
		goReset(form);
	}

	function resetSimpleRegistration() {
		reset('selectionform');
		reset('userregisterform');
		reset('existinguserform');
		displaySelectedForm();
	}
	
	function submitExistingRegistration(url) {
		if (isWhitespace($('existinguserform').username.value)) {
			alert(i18n('usernameMandatory'));
			return;
		}    
		
		if (isWhitespace($('existinguserform').password.value)&&isWhitespace($('existinguserform').email.value)) {
			alert(i18n('passwordOrEmail'));
			return;
		}
		
		if (!isWhitespace($('existinguserform').email.value) && !isEmail($('existinguserform').email.value)) {
			alert(i18n('emailAddressInvalid'));
			return;
		}
		
		var myAjax = new Ajax.Request(
			getGNServiceURL(url), 
			{
				method: 'post',
				parameters: $('existinguserform').serialize(true), 
					onSuccess: function(req) {
        				var output = req.responseText;
        				if (output.indexOf('user-not-found')>-1) {
    						alert(i18n('registrationNotFound'));
    					} else {
    						Modalbox.show(output,{title: i18n('simpleMetadataTitle'), width: 800, height: 600});
    					}
					},
					onFailure: function(req) {
        				alert("ERROR: registration lookup failed: "+req.responseText+" status: "+req.status);
					}
			}
		);
	}
	
	function submitSimpleRegistration()	{
		if ($('rbNotRegistered').checked) {
			processRegSub('user.register.submit');
		} else {
			var service = 'simplemetadata.registration.submit';
			var url = getGNServiceURL(service);
			submitExistingRegistration(url);
		}
	}
  

/**
 * Toggle visibility of an element
 * updating button icon.
 * 
 * @param btn   The button with downBt or rightBt css class icon
 * @param elem  The element to display or not
 */
function toggleFieldset(btn, elem) {
        Element.extend(btn);
		
        if (btn.hasClassName('downBt')) {
                btn.removeClassName('downBt');
                elem.style.display='none';
                btn.addClassName('rightBt');            
        } else {
                btn.removeClassName('rightBt');
                elem.style.display='';
                btn.addClassName('downBt');
        }
}
