// --------------------------------------------------------------------------------
/*
	todo
	@param todo.
*/
function submitAction(formName, action, params) {
	var form = document.forms[formName];
	form.action = action + "?" + params;
	form.submit();
}

// --------------------------------------------------------------------------------
/*
	Get value of the given element.
	@param element the source HTML element the value is retrieved for.
*/
function getValue(element) {
	return element.value;
}

// --------------------------------------------------------------------------------
/*
	Get value of the specified element.
	@param id an id of HTML element.
*/
function getValueById(id) {
	var el = document.getElementById(id);

	if (!el){
		return '';
	} else {
		return getValue(el);
	}
}

// --------------------------------------------------------------------------------
/*
	Submit the specified form.
	@param formName a form's name.
	@param params a map of parameters that are added to form
				  as "hidden" elements.
*/
function submitForm(formName, params) {
	var element;

	for (var paramName in params) {
		if (paramName != 'toJSONString'){
			element = document.createElement("input");
			element.type = 'hidden';
			element.name = paramName;
			element.value = params[paramName];
			if (!document.forms[formName].elements[paramName]){//double-click
				document.forms[formName].appendChild(element);
			}
		}
	}

	var onSubmit = document.forms[formName].onsubmit;
	if (onSubmit) {
		var onSubmitStr = document.forms[formName].onsubmit.toString();
		// Parse-out/Remove the surrounding function
		var newOnSubmit  = onSubmitStr.substring(onSubmitStr.indexOf('{')+1, onSubmitStr.length - 2) + ';';
		// Evaluate the new function
		eval(newOnSubmit);
	}
	document.forms[formName].submit();
}

// --------------------------------------------------------------------------------
/*
	Submit the specified upload form.
	@param formName a form's name.
	@param action an action to be set into the form.
*/
function submitFormWithAction(formName, action) {
	document.forms[formName].action = action;
	document.forms[formName].submit();
}

// --------------------------------------------------------------------------------
/*
	Redirect to the specified URL.
	@param url an URL the HTTP request is redirected to.
	@param params an array of parameters appended to the given URL.
*/
function redirect(url, params) {
	var paramStr = '?';

	for (var paramName in params) {
		if (paramName != 'toJSONString'){
			paramStr = paramStr + paramName;
			paramStr = paramStr + '=';
			paramStr = paramStr + params[paramName];
			paramStr = paramStr + '&';
		}
	}

	paramStr = paramStr.substr(0, paramStr.length - 1);

	//alert(url + paramStr);
	//document.location.href = url + paramStr;
	window.location = url + paramStr;
}

// --------------------------------------------------------------------------------
/*
	Open the date picker dialog window.
	@param fieldId an id of element the selected value is inserted into.
	@param pattern a pattern the selected date is parsed into.
*/
function openDatePicker(fieldId, pattern) {
	new CalendarPopup().select(document.getElementById(fieldId), fieldId, pattern);
}

// --------------------------------------------------------------------------------
/*
	Utility function to determine if the given
	list (select object) has an options array.
	@param list the list (select object) to be checked.
	@return true/false.
*/
function hasOptions(list) {
	if (list!=null && list.options!=null) {
		return true;
	} else {
		return false;
	}
}

// --------------------------------------------------------------------------------
/*
	Compare two options within a list by TEXT.
	@param a an option.
	@param b an other option.
*/
function compareOptionText(a, b) {
	// Radix 10: for numeric values
	// Radix 36: for alphanumeric values

	/*
	var sA = parseInt(a.text, 36);
	var sB = parseInt(b.text, 36);

	return sA - sB;
	*/
	var rv;

	if (a.text < b.text) {
		rv = -1;
	} else if (a.text == b.text) {
		rv = 0;
	} else {
		rv = 1;
	}

	return rv;
}

// --------------------------------------------------------------------------------
/*
	Move the elements (options) form one list (select) to the other.
	@param srcList the source list (the "select" html element).
	@param destList the destination list (the "select" html element).
	@param moveAll identify if whole list to be moved.
	@param sort indetify if the destination list should be sorted after
		   		new elemens has been appneded to it.
	@see compareOptionText(a, b)
	@see hasOptions(list)
*/
function moveDualList(srcList, destList, moveAll, sort) {
	if (!hasOptions(srcList)) {
		return;
	}

	// Do nothing if nothing is selected
	if ((srcList.selectedIndex == -1) && (moveAll == false)){
  		return;
  	}

	newDestList = new Array(destList.options.length);
	var len = 0;

	for(len = 0; len < destList.options.length; len++) {
		if (destList.options[len] != null ) {
			newDestList[len] = new Option(destList.options[len].text, destList.options[len].value, destList.options[len].defaultSelected, destList.options[len].selected);
		}

	}

	for(var i = 0; i < srcList.options.length; i++) {
		if (srcList.options[i] != null && (srcList.options[i].selected == true || moveAll))	{
     		// Statements to perform if option is selected
     		// Incorporate into new list
     		newDestList[len] = new Option(srcList.options[i].text, srcList.options[i].value, srcList.options[i].defaultSelected, srcList.options[i].selected);
			len++;
		}
	}

	if (sort) {
		newDestList.sort(compareOptionText);   // BY TEXT
		//newDestList.sort();   // BY TEXT
	}

	// Populate the destination with the items from the new array
	for (var j = 0; j < newDestList.length; j++) {
		if (newDestList[j] != null) {
			destList.options[j] = newDestList[j];
		}
	}

	// Erase source list selected elements
	for(var i = srcList.options.length - 1; i >= 0; i--) {
    	if (srcList.options[i] != null && (srcList.options[i].selected == true || moveAll)) {
			// Erase Source
			//srcList.options[i].value = "";
			//srcList.options[i].text  = "";
			srcList.options[i]       = null;
    	}
    }
}

// --------------------------------------------------------------------------------
/*
	Swap positions of two options in a select list.
	@param list the list (the "select" html element) the selected options
				are swapped in.
	@param i the position of an option in the list to be swapped.
	@param j the position of an other option in the list to be swapped.
*/
function swapOptions(list, i, j) {
	var o = list.options;
	var i_selected = o[i].selected;
	var j_selected = o[j].selected;
	var temp = new Option(o[i].text, o[i].value, o[i].defaultSelected, o[i].selected);
	var temp2= new Option(o[j].text, o[j].value, o[j].defaultSelected, o[j].selected);
	o[i] = temp2;
	o[j] = temp;
	o[i].selected = j_selected;
	o[j].selected = i_selected;
}

// --------------------------------------------------------------------------------
/*
	Move selected option in a select list UP one.
	@param list the list (the "select" html element) the selected
				option(s) are moved in.
	@see swapOptions(list, i, j)
	@see hasOptions(list)
*/
function moveOptionUp(list) {
	if (!hasOptions(list)) {
		return;
	}

	for (i=0; i<list.options.length; i++) {
		if (list.options[i].selected) {
			if (i != 0 && !list.options[i-1].selected) {
				swapOptions(list, i, i-1);
				list.options[i-1].selected = true;
			}
		}
	}
}

// --------------------------------------------------------------------------------
/*
	Move selected option in a select list DOWN one.
	@param list the list (the "select" html element) the selected
				option(s) are moved in.
	@see swapOptions(list, i, j)
	@see hasOptions(list)
*/
function moveOptionDown(list) {
	if (!hasOptions(list)) {
		return;
	}

	for (i=list.options.length-1; i>=0; i--) {
		if (list.options[i].selected) {
			if (i != (list.options.length-1) && !list.options[i+1].selected) {
				swapOptions(list, i, i+1);
				list.options[i+1].selected = true;
			}
		}
	}
}

// --------------------------------------------------------------------------------
/*
	Mark all "option" HTML elemets in the given list
	(select HTML element)as selected.
	@param list the "select" element containing the
				"option" elements to be marked.
*/
function selectAll(list){
	for(var i = 0; i < list.options.length; i++) {
		if (list.options[i] != null)	{
    			list.options[i].selected = "selected";
		}
	}
}

// --------------------------------------------------------------------------------
/*
	Execute "selectAll" function on every given
	element (select HTML element) of the given array.
	@param listArray the array of "select" HTML elements
				containing the  "option" elements to be marked.
*/
function selectAllOnArray(listArray){
    for(var i = 0; i < listArray.length; i++) {
		if (listArray[i] != null)	{
     		selectAll(listArray[i]);
		}
	}
}

// --------------------------------------------------------------------------------
/*
	Excecute "selectAllOnArray" function on every given list
	and submit the specified form afterwards.
*/
function submitFormWithSelects(formName, params, listArray) {
	selectAllOnArray(listArray);
	submitForm(formName, params);
}

// --------------------------------------------------------------------------------
/*
	Shows a confirmation dialog with the given message.
	@param message The message to be displayed.
	@return <code>true</code> if the message has been confirmed.
*/
function confirmDialog(message) {
	if (confirm(message)) {
		return true;
	} else {
		return false;
	}
}

// --------------------------------------------------------------------------------
/*
	If the given object is disabled it is enabled and vice versa.
	Switch the value of "disabled" attribute of the given object.
	@param obj the object to be disabled/enabled.
*/
function switchDisable(obj) {
	obj.disabled = !obj.disabled;
}

//---------------------------------------------------------------------------------
/*
    @return <code>true</code> if the value is not <code>null</code> and has length > 0.
*/
function isNotNull(value){
     if (value){
		 if (value == null || trim(value).length == 0){
		 	return false;
		 }
		 return true;
	 }
	 return false;
}


function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// --------------------------------------------------------------------------------
/*
	Enable the given element if the objA is equal
	to objB. Otherwise  the element is disabled.
	@param objA a first object.
	@param objB a second object.
	@param element the element to be disabled or enabled.
*/
function enable(objA, objB, element) {
	if (objA == objB) {
		element.disabled = false;
	} else {
		element.disabled = true;
	}
}

// --------------------------------------------------------------------------------
/**
	Enable the specified elements if the given checkbox is checked
	and check the first one.
	Otherwise the elements are disabled.
	@param checkbox identify if the specified elements should be enabled or disabled.
	@param name the name of elements to be disabled or enabled.
*/
function enableByCheckbox(checkbox, name) {
	var elements = document.getElementsByName(name);

	for (var i = 0; i < elements.length; i++) {
		elements[i].disabled = !checkbox.checked;
		if (i == 0 && checkbox.checked) {
			elements[i].checked = 'checked';
		} else {
			elements[i].checked = '';
		}
	}

}

// --------------------------------------------------------------------------------
/**
	Set value of the specified element.
	@param id idententify element that's value is being set.
	@param value a value to be set.
*/
function setElementValue(id, value) {
	document.getElementById(id).value = value;
}


// --------------------------------------------------------------------------------
/**
	Change the value of the specified element
	according to state (checked or not) of the
	given checkbox.
	If it is checked, the element's value is set to 'true'.
	Otherwise it's set to 'false.'
	@param checkbox the checkbox the value is changed according to.
	@param id idententify element that's value is changed.
	@see setElementValue(id, value)
*/
function changeValueByCheckbox(checkbox, id) {
	if (checkbox.checked){
		setElementValue(id, 'true');
	} else {
		setElementValue(id, 'false');
	}
}

// --------------------------------------------------------------------------------
/*
	If the objA equals to objB the given "select" element
	is enabled and the first empty  "option" element is removed
	from this "select" element. Otherwise the "select" element
	is disabled and an empty "option" element is prepended to
	this "select" element.
	@param objA a first object.
	@param objB a second object.
	@param select the select to be disabled or enabled and changed.
*/
function enableAndChangeSelect(objA, objB, select) {
	if (objA == objB) {
		if (select.options[0].value == ''){
			select.remove(select.options[0]);
		}

		// enable
		select.disabled = false;
	} else {
		if (select.options[0].value != ''){
			var emptyOption = new Option('', '', true, true);
			select.insertBefore(emptyOption, select.firstChild);
		}

		// disable
		select.disabled = true;
	}
}


// --------------------------------------------------------------------------------
/**
	Hide the "div" specified by the given ID.
	@param id the unique identifier for the "div" element to be hidden.
*/
function hideDiv(id) {
	if (!document.getElementById(id)){
		return;
	}

	//safe function to hide an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'none';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'none';
		}
		else { // IE 4
			document.all.id.style.display = 'none';
		}
	}
}

// --------------------------------------------------------------------------------
/**
	Show the "div" specified by the given ID.
	@param id the unique identifier for the "div" element to be shown.
*/
function showDiv(id) {
	if (!document.getElementById(id)){
		return;
	}

	//safe function to show an element with a specified id
	if (document.getElementById) { // DOM3 = IE5, NS6
		document.getElementById(id).style.display = 'block';
	}
	else {
		if (document.layers) { // Netscape 4
			document.id.display = 'block';
		}
		else { // IE 4
			document.all.id.style.display = 'block';
		}
	}
}

//---------------------------------------------------------------------
/**
	Reset all the fields in "extended search" form.
*/
function resetExtendedSearchForm() {
	document.projectSearchForm.searchString.value = "";
	document.projectSearchForm.projectTheme.value = "";
	document.projectSearchForm.projectSector.value = "";
	document.projectSearchForm.year.value = "";
	document.projectSearchForm.country.value = "";
	document.projectSearchForm.projectType.value = "";
	document.projectSearchForm.indivParticipate[2].checked="true";
	document.projectSearchForm.projectNumber.value = "";
	document.projectSearchForm.projectStatus.value = "";
	if (document.projectSearchForm.publishState) {
		document.projectSearchForm.publishState.value = "";
	}
	
	document.projectSearchForm.promoterOrganization.value = "";
	document.projectSearchForm.promoterCountry.value = "";
	document.projectSearchForm.promoterRegion.value = "";

	document.projectSearchForm.coordinatorOrganization.value = "";
	document.projectSearchForm.coordinatorCountry.value = "";
	document.projectSearchForm.coordinatorRegion.value = "";

	document.projectSearchForm.partnerOrganization.value = "";
	document.projectSearchForm.partnerCountry.value = "";
	document.projectSearchForm.partnerRegion.value = "";

	document.projectSearchForm.productLanguage.value = "";

	return false;
}

// --------------------------------------------------------------------------------
/*
	Submit the "projectEditForm" to navigate to other project edit page.
	@param fieldGroupOid an OID uniquely identifying the target page.
	@see submitForm(formName, params)
*/
function submitToProjectEditPage(fieldGroupOid) {
	var params = new Array(2);
	params['_eventId'] = 'changePage';
	params['fieldGroupOid'] = fieldGroupOid;

	if (document.forms['projectEditForm'].fileUploadPage) {
		params['_flowExecutionKey'] = document.forms['projectEditForm']._flowExecutionKey.value;
		params['descriptionEditNI'] = escape(document.forms['projectEditForm'].descriptionEditNI.value);
		redirect('/adam/project/edit.htm', params);
	} else {
		document.forms['projectEditForm'].enctype = '';
		submitForm('projectEditForm', params);
	}
}

//--------------------------------------------------------------------------------
/*	
	Insert the "dynamic help text" in the given "input" if the input is empty and 
	it does not already contain the "dynamic help text". 
	Otherwise remove CSS class "dynamicHelpText" only.
*/
function insertDynamicHelpText(input,dynamicHelpText) {
	if (!input.value) {
		// Insert dynamic help text + css class
		input.value = dynamicHelpText;
		if (input.className.indexOf("dynamicHelpText") == -1) {
			input.className += " dynamicHelpText";
		}
	} else if (input.value == dynamicHelpText) {
		// Do nothing
	} else {
		// Remove css class
		if (input.className) {
			input.className = input.className.replace(/dynamicHelpText/ig, "");
			console.log("className=" + input.className);
		}
	}
}

//--------------------------------------------------------------------------------
/*	
	Remove a "dynamic help text" from the given "input" 
	inclusive corresponding CSS class.
*/
function removeDynamicHelpText(input) {
	// Remove css class and value
	if (input.className && input.className.indexOf("dynamicHelpText") > -1) {
		input.className = input.className.replace(/dynamicHelpText/ig, "");
		input.value = '';
	}
}

//--------------------------------------------------------------------------------
/*
	Remove values of all "input" HTML elements containing CSS class "dynamicHelpText". 
	@param form the "form" HTML element to update elements in.
*/
function removeAllDynamicHelpTexts() {
	// Remove dynamic help texts from textArea
	var dynamicHelpTextsInTextArea = getElementsByTagNameAndClassName("textarea", "dynamicHelpText");
	for (var index = 0; index < dynamicHelpTextsInTextArea.length; index++) {
		dynamicHelpTextsInTextArea[index].value = '';
	}
	// Remove dynamic help texts from input
	var dynamicHelpTextsInInput = getElementsByTagNameAndClassName("input", "dynamicHelpText");
	for (var index = 0; index < dynamicHelpTextsInInput.length; index++) {
		dynamicHelpTextsInInput[index].value = '';
	}
}

//--------------------------------------------------------------------------------
/*
	Return all HTML elements matching specified tag name and CSS class.
	@param tagName matching tag name.
	@param className matching CSS class name.
	@return found HMTL elements in an array.
*/
function getElementsByTagNameAndClassName(tagName, className) {
	var elementsMatchingTagName = document.getElementsByTagName(tagName);
	var resultArray = [];
	for(var index=0; index < elementsMatchingTagName.length ; index++) {
		var classNameArray = elementsMatchingTagName[index].className.split(" ");
		if(hasClass(elementsMatchingTagName[index], className)) {
			resultArray.push(elementsMatchingTagName[index]);
		}
	}
	return resultArray;
}

//--------------------------------------------------------------------------------
/*
	Check if the given element contains the specified CSS class.
	@param element A HTML element the CSS class attribute is checked by.
	@param className Checking CSS class name.
	@return <code>true</code> or <code>false</code>.
*/
function hasClass(element, className) {
	if (!element.className) return false;
	var classNameArray = element.className.split(" ");
	for (index in classNameArray) {
		if (classNameArray[index] == className) {
			return true;
		}
	}
	return false;
}

//--------------------------------------------------------------------------------
/*
	Append the specified CSS class into the given element if it does not exist in this element yet.
	@param element A HTML element the CSS class attribute is appended into.
	@param className Appending CSS class name.
*/
function addClass(element, className) {
	if (!element.className || hasClass(element, className)) return;
	
	element.className = element.className + " " + className;
}

//--------------------------------------------------------------------------------
/*
	Remove the specified CSS class from the given element if it exists in this element.
	@param element A HTML element the CSS class attribute is removed from.
	@param className Removing CSS class name.
*/
function removeClass(element, className) {
	if (!element.className || !hasClass(element, className)) return;
	
	var classNameArray = element.className.split(" ");
	var newClassName = "";
	for (index in classNameArray) {
		if (classNameArray[index] != className) {
			newClassName += " " + classNameArray[index]; 
		}
	}
	element.className = newClassName;
}