//a quick check whether user is using GECKO or IE based navigator

var nav = window.browser.code;

if(document.captureEvents) {
//		window.captureEvents(Event.Click | Event.Change);
//		document.captureEvents(Event.Click | Event.Change);
//		
//		window.onchange = getEvent;
//		window.onclick = getEvent;
//		window.onload = getEvent;	
//		window.onmouseover = getEvent;
//		window.onmouseout = getEvent;
//		
//		document.onchange = getEvent;
//		document.onload = getEvent;
//		document.onclick = getEvent;
//		document.onmouseover = getEvent;
//		document.onmouseout = getEvent;
//		
	window.addEventListener('click', getEventClick, true);
	window.addEventListener('change', getEventChange, true);
	window.addEventListener('mouseover', getEventMover, true);
	window.addEventListener('mouseout', getEventMout, true);
	window.addEventListener('load', getEventLoad, true);
	
	document.addEventListener('click', getEventClick, true);
	document.addEventListener('change', getEventChange, true);
	document.addEventListener('mouseover', getEventMover, true);
	document.addEventListener('mouseout', getEventMout, true);
	document.addEventListener('load', getEventLoad, true);
	
} else {

	window.onchange = getEvent;
	window.onclick = getEvent;
	window.onload = getEvent;	
	window.onmouseover = getEvent;
	window.onmouseout = getEvent;
	
	document.onchange = getEvent;
	document.onload = getEvent;
	document.onclick = getEvent;
	document.onmouseover = getEvent;
	document.onmouseout = getEvent;
	
}

window.onerror = catchError;

//*********************************************************************************************//

function getEvent(e) {

	myevent = (window.event)?window.event:e;
	
	myevent.element = (window.event)?window.event.srcElement:myevent.target;
	
	return myevent;
}

function getEventClick(e) {

	getEvent(e);
	
}

function getEventChange(e) {

	getEvent(e);
	
}

function getEventMover(e) {

	getEvent(e);
	
}

function getEventMout(e) {

	getEvent(e);
	
}

function getEventLoad(e) {

	getEvent(e);
	
}

//*********************************************************************************************//

function catchError(msg,url,l) {

	txt="There was an error on this page.\n\n"
	txt+="Error: " + msg + "\n"
	txt+="URL: " + url + "\n"
	txt+="Line: " + l + "\n\n"
	txt+="Click OK to continue.\n\n"
	alert(txt)
	return true
	
}

//*********************************************************************************************//

function getElement(id) {
	
	if(typeof id == 'undefined') {
		return null;
	}
	
	var obj = document.getElementById(id);
	
	if(obj == null || typeof obj == 'undefined') {//try get the element by name
		obj = document.getElementsByName(id);
		if(obj.length > 0) {			
			obj = obj[0];
		}
		
	}
	
	return obj;
	
}

//*********************************************************************************************//

function duplicateNode_tmp(nodeObj, insertAfter, inputs2array) {
	
	if(typeof nodeObj == 'undefined') {
		alert('duplicateNode()::node "'+nodeObj+'" is undefined');	
		return false;
		
	}
	
	var node = (typeof nodeObj != 'object')?getElement(nodeObj):nodeObj;
	var dnode = node.cloneNode(true);
	var suffix = '_'+node.parentNode.childNodes.length;
//	alert(dnode.innerHTML.replace(, '$2'+suffix));return;
	
	var html = dnode.innerHTML;
	
	var reg = /(for|id|name)\s*?=\s*?[\'\"]?([^\s\'\">]*)[\'\"]?/gi;
	var reg_rep = /(for|id|name)\s*?=\s*?[\'\"]?([^\'\"\s>]*)[\'\"]?/i;
	
	if(dnode.innerHTML.match(reg)) {
		
		var len = dnode.innerHTML.match(reg);
		
		for(var l in len) {
			if (l != 'input') {
				var re = new RegExp(reg);
		  	var m = re.exec(len[l]);
//		  	alert(m);
				if(m != null) {
					var repl = len[l].replace(m[2], m[2]+suffix);
					dnode.innerHTML = dnode.innerHTML.replace(len[l], repl);
				}
			}
		}
		
//		dnode.innerHTML = '';
		
	}

	
//	dnode.innerHTML = html;
	
	var last_child = node.parentNode.childNodes[node.parentNode.childNodes.length-1];
	node.parentNode.insertBefore(dnode, last_child);
	node.parentNode.insertBefore(last_child, dnode);
	
	return true;
}

function duplicateNode(nodeObj, insertAfterBool, inputs2arrayBool) {

	if(typeof nodeObj == 'undefined') {
		alert('duplicateNode()::node "'+nodeObj+'" is undefined');	
		return false;
		
	}

	var node = (typeof nodeObj != 'object')?getElement(nodeObj):nodeObj;
	
	var arr = new Array();

	var parentnode = node.parentNode;
	
	var siblings_counter = parentnode.parentNode.getElementsByTagName(node.tagName).length;

	var insertAfter = (typeof insertAfterBool == 'undefined')?true:insertAfterBool;
	
	var inputs2array = (typeof inputs2arrayBool == 'undefined')?true:inputs2arrayBool;
	
	var idsuffix = '_' + siblings_counter;//duplicateNodeCounter;// parentnode.childNodes.length;
	
	var previous_idsuffix = siblings_counter-1;//(duplicateNodeCounter == 1)?'_' + (duplicateNodeCounter-1):'';//(parentnode.childNodes.length - 1);
	
	var inputs_idsuffix = '[]';
	
	var node_id = (typeof node.id == 'undefined' || node.id == '')?'':node.id;
	
	var node_name = (typeof node.name == 'undefined' || node.name == '')?'':node.name;
	
	//duplicate the node
	var dnode = node.cloneNode(true);
	
	if(node_id != '') {
		dnode.id = node.id + idsuffix;
	} 
	
	if(node_name != '') {
		dnode.name = node.name + idsuffix;
	} 
	
	//get all childnodes in a 1 dimensioned array
	var nodes_arr = getChildNodes (dnode);
	
	for (var i in nodes_arr) {
		
		var child = nodes_arr[i];
		
		var child_id = (typeof child.id == 'undefined' || child.id == '')?'':child.id;
	
		var child_name = (typeof child.name == 'undefined' || child.name == '')?'':child.name;
		
		var is_form_element = (typeof child.tagName != 'undefined' && (in_array(child.tagName.toLowerCase(), ['input', 'textarea', 'select'])));

		if(child_name != '' && inputs2array == true) {//if child is a form element - make it an array so after submitting it'll be easier to wirk with them
			
			var new_name = (child_name.indexOf('[') == -1)?child_name:child_name.substr(0, child_name.indexOf('['));
			new_name = (is_form_element == true)?new_name+'['+(parseInt(siblings_counter)-1)+']':new_name + idsuffix;
//			new_name = (is_form_element == true)?new_name+'['+new_name + idsuffix+']':new_name + idsuffix;
			child.name = new_name;				
			
			if(child_name.indexOf('[') == -1){
				var original_node = getElement(child_name);			
				original_node.name = (is_form_element == true)?child_name+'[0]':child_name + idsuffix;;			
//				original_node.name = (is_form_element == true)?child_name+'['+child_name+']':child_name + idsuffix;;			
//				original_node.name = child_name+'[]';			
			}
//			
			if(child_id != '') {
				child.id = child_id + '_' + idsuffix;					
			} 
			
	//		if(is_form_element == true && child.type.toLowerCase() == 'text') {
			if(is_form_element == true) {
				var ctype = child.type;//.toString().toLowerString();				
				switch (ctype) {//clear the entered values
					case 'checkbox':						
						child.checked = false;
//						child.name = child.name.replace(/\[\]/, '') +'['+parseInt(siblings_counter)+']';
						
						if(is_numeric(child.value)) {
							child.value = parseInt(child.value)+(parseInt(siblings_counter)-1);
						}
						break;					
					case 'select-one':
					case 'select-multiple':
						child.selectedIndex = 0;
						break;					
					default:						
						//cannot clear file value
						if(child.type.toLowerCase() != 'file') {
							child.value = '';	
						}
						break;	
				}//end clearing entered values
							
			}
			
		} else if(child_name != '' && inputs2array == false) {
			
			var new_name;
			
			if(child_name.indexOf(idsuffix) == -1 && child_name.indexOf(previous_idsuffix) == -1) {				
				new_name = child_name;				
			} else {
				new_name = child_name.substr(0, child_name.lastIndexOf(previous_idsuffix));
			}
			
			if(typeof getElement(new_name).defval != 'undefined') {			
				var child_original = getElement(new_name);
				var repl = child_original.defval;				
				var r = /{@([^@]+)@}/gi;
				child.defval = repl.replace(r, '{@$1'+idsuffix+'@}');		
				child.required = child_original.required;
				child.title = child_original.title;
				child.order = child_original.order;
			}

			child.name = new_name + idsuffix;
			
			if(child_id != '') {
				child.id = child_id + '_' + idsuffix;					
			} 
			
//			if(is_form_element == true && child.type.toLowerCase() == 'text') {
			if(is_form_element == true) {
				var ctype = child.type;//.toString().toLowerString();				
				switch (ctype) {//clear the entered values
					case 'checkbox':						
						child.checked = false;											
						break;					
					case 'select-one':
					case 'select-multiple':
						child.selectedIndex = 0;
						break;					
					default:
						child.value = '';	
						break;	
				}//end clearing entered values
							
			}
		
		}
		
	}
	

	if(insertAfter == false) { //insert the new node before the pattern node
		parentnode.insertBefore(dnode, node);
	} else {
		var last_child = parentnode.childNodes[parentnode.childNodes.length-1];
		parentnode.insertBefore(dnode, last_child);
		parentnode.insertBefore(last_child, dnode);
//		alert(node.innerHTML);
	}
	return true;
}//end function duplicateNode


//*********************************************************************************************//

//a recursive function for getting all childrenNodes of a node and their childrenNodes
//recurse is true or false; returns an array of childNodes
function getChildNodes (nodeObj, recurse) {

	if(typeof nodeObj == 'undefined') {
		alert('getChildNodes()::node "'+nodeObj+'" is undefined');	
		return false;
		
	}
	
	if(typeof recurse == 'undefined') {
		recurse = false;		
	}
	
	//the returned array
	var ret_array = new Array();
	
	var node = (typeof nodeObj != 'object')?getElement(nodeObj):nodeObj;
	
	//cycle through the node's childNodes and change their id ot name so they are unique
	var loop = node.childNodes;
	
	for(var i in loop) {
	
		var child = loop[i];
		var child_id = (typeof child.id == 'undefined' || child.id == '')?child.name:child.id;
		
//		if(child_id != '' && typeof child_id != 'undefined') {
		if(typeof child == 'object') {
			
			//options of a select are omitted
			if(typeof child.tagName != 'undefined' && child.tagName.toLowerCase() == 'option') {				
				continue;
			}
			
			
			if(child_id != '' && typeof child_id != 'undefined') {				
				ret_array[child_id] = child;
			} else {
				ret_array.push(child);
			}
			//alert(child);
			if(child.childNodes.length > 0) {
				var tmp = getChildNodes (child, true);
				for (var c in tmp) {
					//the name or id
					var cid = (typeof tmp[c].id == 'undefined' || tmp[c].id == '')?tmp[c].name:tmp[c].id;
					if(cid != '' && typeof cid != 'undefined') {
						ret_array[cid] = tmp[c];
					} else {
						ret_array.push(tmp[c]);
					}					
				}
			}
		}
	}
	
	return ret_array;
	
}//end function getChildNodes


//*********************************************************************************************//

//same as in PHP
function in_array (variable, array) {

	var is_in_array  = false;

	for (var i in array) {
	
		if(array[i] == variable) {
						
			is_in_array = true;
			break;
		
		}
	
	}
	
	return is_in_array;
	
}//end function in_array


//*********************************************************************************************//

//same as in PHP
function is_array (variable) {

	var is_an_array = (typeof variable == 'object' && variable.constructor.toString().toLowerCase().indexOf('array') != -1)?true:false;
	
	return is_an_array;
	
}//end function is_array


//*********************************************************************************************//

//same as in PHP
function is_string (variable) {

//	var is_a_string = ((typeof variable == 'object' && variable.constructor.toString().toLowerCase().indexOf('string') != -1) || isNaN(variable))?true:false;
	var is_a_string = ((typeof variable == 'object' && variable.constructor.toString().toLowerCase().indexOf('string') != -1))?true:false;
	
	if(!is_a_string) {
		is_a_string = (isNaN(variable));
	}
	
	return (is_a_string);
	
}//end function is_array


//*********************************************************************************************//

//same as in PHP
function is_null (variable) {

	if(arguments.length == 0) {
		alert('is_null::Please provide a variable');
		return false;
	}
	
	var is_null = (typeof variable != 'undefined' && variable != null)?false:true;
	
	return is_null;
	
}//end function is_null

//*********************************************************************************************//

function linkedDd(targetDd, iframe, paramsStr) {

	var f = (typeof iframe == 'object')?iframe:getElement(iframe);
	
	f = (f == null)?document.createElement('IFRAME'):f;
	
	var target = (typeof targetDd == 'object')?targetDd:getElement(targetDd);

	var params = (!isset(paramsStr))?global_SITE_URL+'/lib/linked_dd.php?':paramsStr;

	if (typeof target.defval != 'undefined' && target.defval != null && target.defval != '') {

		target.disabled = true;
		
		var query = target.defval;
//		alert(query);
		if(query.match(/{@([^@]+)@}/gi)) {
			
			while(query.match(/{@([^@]+)@}/gi)) {
			
				var re = new RegExp(/{@([^@]+)@}/gi);
			  var m = re.exec(query);
			  
			  if (m != null) {
			    for (i = 0; i < m.length; i++) {
			      
			    	if(i % 2 == 0) {
			      	continue;
			      }
			    	
			      query = query.replace(/{@([^@]+)@}/i, getElement(m[i]).value);
			    	
			    }
			    
			  }
				
			}
			
		}//end if(query.match(/{@([^@]+)@}/gi))

		if (!params.match(/\?/)) {		
			params = global_SITE_URL+'/lib/linked_dd.php?';	
		}
		
		f.src = params+'q='+escape(query)+'&target='+((typeof target.id != 'undefined' && target.id != '')?target.id:target.name);
		
	}
	
}


function linkedDd2(targetDd, iframe, paramsStr) {

	var f = (typeof iframe == 'object')?iframe:getElement(iframe);
	
	if(f == null) {

		f = document.createElement('IFRAME');
		
		//insert the iframe after the body tag
		document.body.insertBefore(f, document.body.childNodes[0]);
		
	}
	
	var target = (typeof targetDd == 'object')?targetDd:getElement(targetDd);

	var params = (!isset(paramsStr))?global_SITE_URL+'/lib/linked_dd.php?':paramsStr;

	if (!params.match(/\?/)) {		
		params = global_SITE_URL+'/lib/linked_dd.php?';	
	}
	
	f.src = params+'&target='+((typeof target.id != 'undefined' && target.id != '')?target.id:target.name);
	
}


//Same as in PHP
function isset(variable) {

	var is_set = (variable != null && typeof variable != 'undefined');
	return is_set;

}

//Same as in PHP
function empty(variable) {

	var empty = (isset(variable) && variable != '' && parseInt(variable) != 0);
	return !empty;

}

//same as in PHP
function range(from, to) {

	var array = new Array();
	
	for (var i=from; i <= to; i++) {
		
		array.push(i);
	
	}
	
	return array;
	
}


function changeType(objObj, type) {

	var obj = (typeof objObj == 'object')?objObj:getElement(objObj);

	var loop = obj.attributes;
	
	var params = '';
	
	for(var i=0;i<loop.length;i++){
	    if(loop[i].specified){
	    	params += ' '+loop[i].nodeName+'="'+loop[i].nodeValue+'"';
	    }
		
	 }
	
	var html = '';
	 
	switch(type) {
		case 'textarea':
			html = '<textarea '+params+'>'+obj.value+'</textarea>';
			break;
		case 'select':
			html = '<span id="select_options_dub"><input '+params+'>&nbsp; <a href="javascript:void(0);" onclick="duplicateNode(this.parentNode, true, true);">add</a>|<a href="javascript:void(0);" onclick="if(this.parentNode.parentNode.childNodes.length > 1) {var test=this.parentNode.parentNode.removeChild(this.parentNode);}">remove</a><br><br></span>';
			break;
		default:
			html = '<input '+params+'>';
			break;
	}
	
	obj.parentNode.innerHTML = html;
	
}

//This function sets the focus to the first INPUT element in the first form of a document
function focusFirst(form_name) {

	if(document.forms.length > 0) {
	
		//the first form
		var f = (is_null(form_name))?document.forms[0]:document.forms[form_name];
		
		var inputs = f;//getElementsByTagName('INPUT');

		//find the first textfield in the form and set the focus on it
		for (var i =0; i < inputs.length; i++) {
		
			if(typeof inputs[i].type != 'undefined' && inputs[i].type.toLowerCase() == 'text') {
				inputs[i].focus();				
				break;
				
			}
			
		}
		
	}
	
}//end function focusFirst

/**
 * Checks wheter $variable is an object
 *
 * @param mixed variable
 */
function is_object (variable) {

	return (typeof variable == 'object');
	
}


/**
 * Sends an option from select1 to select2
 *
 * @param mixed select1 - the select from which the option is taken
 * @param mixed select2 - the select to which the option goes
 * @param bool leaveoption - whether to leave the option in select1
 */
function switchoption(select1Obj, select2Obj, leaveoptionBool, nooptionstextStr, nooptionsvalueMixed, duplicateInHiddensBools) {

	var select1 = (is_object(select1Obj))?select1Obj:getElement(select1Obj);
	var select2 = (is_object(select2Obj))?select2Obj:getElement(select2Obj);
	var leaveoption = (is_null(leaveoptionBool))?false:leaveoptionBool;
	var nooptionstext = (is_null(nooptionstextStr))?'------------------':nooptionstextStr;
	var nooptionsvalue = (is_null(nooptionsvalueMixed))?'NULL':nooptionsvalueMixed;
	var dub = (is_null(duplicateInHiddensBools) || !is_bool(duplicateInHiddensBools))?false:duplicateInHiddensBools;
	
	var loop = select1.options;
	var to_remove = new Array();
	
	if(select1.length == 1 && select1.options[0].text == nooptionstext && select1.options[0].value == nooptionsvalue) {
		return true;
	} 
	if(select2.selectedIndex == -1 && select1.selectedIndex == -1) {
		return true;
	} else if(select2.length >= 1 && select2.options[0].text == nooptionstext && select2.options[0].value == nooptionsvalue) {
		select2.removeChild(select2.options[0]);
	}
	
	for (var i = 0; i < loop.length; i++) {

		if(loop[i].text == nooptionstext) {
			continue;
		}
		
	  if (loop[i].selected == true) {
	  	
			select2.options[select2.length] = new Option (loop[i].text, loop[i].value);					

			if(leaveoption != true) {			
				to_remove.push(loop[i]);
			} else {
				loop[i].selected=false;
			}
			
	  }
	}
	
	if(to_remove.length != 0) {
	
		for (var i = 0; i < to_remove.length; i++) {
	
			var tst = select1.removeChild(to_remove[i]);
			
		}
		
	}
	
	if(select1.length == 0) {
		select1.options[0] = new Option (nooptionstext, nooptionsvalue);
	}
  
  if(select2.length == 0) {
		select2.options[0] = new Option (nooptionstext, nooptionsvalue);
	}
	
	
	if(dub) {
		
		var hidden_suffix = '_hidden_val';
		
		var select1hidden = getElement(select1.name+hidden_suffix);
		var select2hidden = getElement(select2.name+hidden_suffix);
		
		if(is_null(select1hidden)) {
			
			select1hidden = document.createElement('INPUT');
			select1hidden.name = select2.name+hidden_suffix;
			select1hidden.type = hidden;
			
		}
		
		if(is_null(select2hidden)) {
			
			select2hidden = document.createElement('INPUT');
			select2hidden.name = select2.name+hidden_suffix;
			select2hidden.type = hidden;
			
		}
		
	}
	
	
	return true;
}//end function switchoption

/**
 * Sends an option from select1 to select2
 *
 * @param mixed select1 - the select from which the option is taken
 * @param mixed select2 - the select to which the option goes
 * @param bool leaveoption - whether to leave the option in select1
 */
function switchoptions(select1Obj, select2Obj, leaveoptionBool, nooptionstextStr, nooptionsvalueMixed) {

	var select1 = (is_object(select1Obj))?select1Obj:getElement(select1Obj);
	var select2 = (is_object(select2Obj))?select2Obj:getElement(select2Obj);
	var leaveoption = (is_null(leaveoptionBool))?false:leaveoptionBool;
	var nooptionstext = (is_null(nooptionstextStr))?'------------------':nooptionstextStr;
	var nooptionsvalue = (is_null(nooptionsvalueMixed))?'NULL':nooptionsvalueMixed;
	
	var loop = select1.options;
	
	var to_remove = new Array();
	
//	if(select1.length == 1 && select1.options[0].text == nooptionstext && select1.options[0].value == nooptionsvalue) {
//		return true;
//	} 
//	if(select2.selectedIndex == -1 && select1.selectedIndex == -1) {
//		return true;
//	} else if(select2.length >= 1 && select2.options[0].text == nooptionstext && select2.options[0].value == nooptionsvalue) {
//		select2.removeChild(select2.options[0]);
//	}
//	
	for (var i = 0; i < loop.length; i++) {
	
		if(loop[i].text == nooptionstext) {
			continue;
		}	
		
		select2.options[select2.length] = new Option (loop[i].text, loop[i].value);
		
		if(leaveoption != true) {			
			to_remove.push(loop[i]);
		} else {
			loop[i].selected=false;
		}

	}
	
	if(to_remove.length != 0) {
	
		for (var i = 0; i < to_remove.length; i++) {
	
			var tst = select1.removeChild(to_remove[i]);
			
		}
		
	}
	
	if(select1.length == 0) {
		select1.options[0] = new Option (nooptionstext, nooptionsvalue);
	}
  
  if(select2.length == 0) {
		select2.options[0] = new Option (nooptionstext, nooptionsvalue);
	}
	
}//end function switchoption

// removes the node from HTML
//var node - the node to be romoved. if want to remove self call like this:  removeChildNode(thid,..)
//var confirmMsg - selfexplanatory. if not set - 'Are you sure?'
//var noremove - the id of the node, that SHOULD NOT  be removed ( e.g. - the first entry )

function removeChildNode(nodeObj, confirmMsgStr, noremoveStr) {

	var node = (typeof nodeObj == 'object')?nodeObj:getElement(nodeObj);
	
	var noremove = (typeof noremoveStr == 'object')?noremoveStr:getElement(noremoveStr);

	if(!is_null(noremove) && noremove == node) {
		alert ('You can not remove this!');

		return false;
	
	}
	
	var confirmMsg = (is_null(confirmMsgStr))?'Are you sure?':confirmMsgStr;

	if(node.parentNode.length <= 1) {
		return false;
	}
	
	if(confirm(confirmMsg) ==  true) {

		var tst=node.parentNode.removeChild(node); 
		return tst;
		
	} else {
	
		return false;
	
	}

	
}

//swaps 2 rows of a table.
function swapRowsCommon(rowObj, directionStr, hiddenStr) {

	var row = (is_object(rowObj))?rowObj:getElement(rowObj);

	var hidden = (is_null(hiddenStr))?'order':hiddenStr;
	
	var direction = (!in_array(directionStr, ['up', 'down']))?'down':directionStr;

	var table = row.parentNode;

	while (table.tagName.toLowerCase() != 'table') {
		
		table = table.parentNode;
		
	}
	
	var rows_coll = table.rows;
	
	var loop = rows_coll.length;

	var first_row = rows_coll[0];
	
	var last_row = rows_coll[loop-1];
	
	if(direction == 'up' && row == first_row) {
		
		return true;
		
	} 
	
	if(direction == 'down' && row == last_row) {

		return true;
		
	}
	
	var i = row.rowIndex;
	
	var swap = (direction == 'up')?i-1:i+1;			
	var row2swap = rows_coll[swap].parentNode.removeChild(rows_coll[swap]);
	row.parentNode.insertBefore(row2swap, rows_coll[i]);
	
	//change the hidden fields values
	var order_row = getElement(hidden+'['+row.id.substr(row.id.lastIndexOf('_')+1, row.id.length)+']');
	var order_swap = getElement(hidden+'['+row2swap.id.substr(row2swap.id.lastIndexOf('_')+1, row2swap.id.length)+']');
			
	var row_order = parseInt(order_row.value);
	var swap_order = parseInt(order_swap.value);

	order_row.value = (direction == 'up')?row_order-1:row_order+1;
	order_swap.value = (direction == 'up')?swap_order+1:swap_order-1;
	
	//change the hidden fields values
	var order_row = getElement(hidden+'['+row.id.substr(row.id.lastIndexOf('_')+1, row.id.length)+']');
	var order_swap = getElement(hidden+'['+row2swap.id.substr(row2swap.id.lastIndexOf('_')+1, row2swap.id.length)+']');
			
	var row_order = parseInt(order_row.value);
	var swap_order = parseInt(order_swap.value);

	order_row.value = (direction == 'up')?row_order-1:row_order+1;
	order_swap.value = (direction == 'up')?swap_order+1:swap_order-1;
	
	return true;
}


/**
 * Gets all options of a multiple select and stores them in a hidden fields
 *
 * @param array|string|object elementsarray - an array of multiple selects or a name of a ultiple select or a multiple select object
 * 
 * @return bool - true on successfull thumb creation, false otherwise
 */
function getAllOptions(elementsarray) {
	
	if(is_array(elementsarray)) {
	
		for(var i = 0; i < elementsarray.length; i++) {
		
			getAllOptions(elementsarray[i]);
			
		}
		
	} else {
	
		var select = (is_object(elementsarray))?elementsarray:getElement(elementsarray);
		
		//if the element is not a select - return
		if(!isset(select.type) || !in_array(select.type, ['select-multiple', 'select'])) {
		
			return;
			
		}
		
		var loop = select.options;
		
		for(var i = 0; i < loop.length; i++) {
		
			loop[i].selected = true;
			
		}
		
	}
	
	return false;
}//end function getAllOptions


/**
 * Makes a set of checkboxes act like a radio group
 * All checkboxes in the set have to have the same name. E.g. name="checkbox[0]", name="checkbox[1]"
 *
 * @param string|object obj - the currently checked checkbox
 * 
 * @return bool - true on successfull thumb creation, false otherwise
 */
function checkboxGroup(obj, pattern_name) {

	var chkbox = (is_object(obj))?obj:getElement(obj);
	
	var constr = (isset(chkbox.form))?'':'form';
	
	var ch_name = (!empty(chkbox.name))?chkbox.name:chkbox.id;
	
	var pattern = (isset(pattern_name))?pattern_name:'';
	
	//the object is a form
	if(constr.indexOf('form') != -1) {
	
		var loop = chkbox.getElementsByTagName('INPUT');
		
		var skip = myevent.element;
		
		var name_pattern = (!empty(pattern))?pattern:'';

		for (var i=0; i < loop.length; i++) {
			if((loop[i] != skip && empty(name_pattern)) || (!empty(name_pattern) && loop[i].name.indexOf(name_pattern) != -1 && loop[i] != skip)){// && loop[i].checked == true) {
				loop[i].checked = false;
			} else if(loop[i] == skip) {
				loop[i].checked = true;
			}
		}//end for
		
	} else {
	
		var name_pattern = (!empty(pattern))?pattern:chkbox.name.substr(0, chkbox.name.indexOf('['));
		
		var checkboxes = (!is_null(chkbox.form))?chkbox.form.getElementsByTagName('INPUT'):document.getElementsByTagName('INPUT');
		
		var loop = checkboxes;
		
		for (var i=0; i < loop.length; i++) {
		
			if(!is_null(loop[i].name) && loop[i].name.indexOf(name_pattern+'[') != -1) {
				if(loop[i] != chkbox && loop[i].checked == true) {
					loop[i].checked = false;
				}
			}
			
		}//end for
	
	}
	
	return;
	
	
	
}//function checkboxGroup(obj) 



function showHideTag(pTagName, pImg) {

	var menu = (is_object(pTagName))?pTagName:getElement(pTagName);
	
	var arrow;
	
	if(!empty(pImg)) {
	
		arrow = (is_object(pImg))?pImg:getElement(pImg);
	
		//get the event element and change it's onmouseover and onmouse out		
		var srcEl = (nav == 'NS')?window.myevent.target.parentNode:window.event.srcElement.parentNode;
	
		var imgDir = global_SITE_URL+'/lib/images/treeMenu/';
		
	}
	
	if(menu.style.display == 'none') {
		
		menu.style.display = '';
		
		if(!empty(pImg)){
			arrow.src = imgDir+'minus.gif';
		}

	} else {
	
		menu.style.display = 'none';
		
		if(!empty(pImg)){
			arrow.src = imgDir+'plus.gif';
		}
		
	}
	
}

//checks all chekboxes in a form
function checkAllBoxes (trigger, chboxnames, form) {

	//get the checked object
	var obj = (is_object(trigger))?trigger:getElement(trigger);
	
	//get the eventual ids by which to check the checkboxes
	var ids = (!empty(chboxnames))?chboxnames:'';
	
	//the form the checkboxes belong to
	var frm = (isset(form) && is_object(form))?form:((empty(form))?obj.form:document.forms[form]);
	
	var loop = frm;
	
	for (var i=0; i < loop.length; i++) {
	
		var chkbox = loop[i];
		
		if(isset(chkbox.id) && chkbox.id.indexOf(ids) != -1) {
		
			if(obj.type.toLowerCase() == 'checkbox') {
			
				chkbox.checked = obj.checked;

			} else {
				
				if(chkbox.checked == true) {
					chkbox.checked = false;
				} else {
					chkbox.checked = true;
				}
				
			}
			
		}
		
	}
	
}//end function checkAllBoxes


function getFileName(string) {

		if(empty(string)) {
			return '';
		}
	
		var delimiter = (window.navigator.platform.indexOf('Win') != -1)?'\\':'/';
		
		var file = string.substr(string.lastIndexOf(delimiter)+1, string.length);

		file = (file.indexOf('.') != -1)?file.substr(0, file.lastIndexOf('.')):file;
		
		return file;
}

function printPage(target) {

	var print_page = (!isset(target))?window:((is_object(target))?target:getElement(target));

	
	
	window.print();
	
}

function showHideMenu(pMenuTable, pImg) {

	menu = document.getElementById(pMenuTable);
	arrow = document.getElementById(pImg);
	
	//get the event element and change it's onmouseover and onmouse out
	srcEl = (nav == 'NS')?window.myevent.target.parentNode:window.event.srcElement.parentNode;

	imgDir = global_SITE_URL+'/lib/images/';
	
	if(menu.style.display == 'none') {
		
		menu.style.display = '';
		
		arrow.src = imgDir+'arrow_1.gif';

		newImgOver = function (){arrow.src = imgDir+'arrow_1_on.gif';};
		newImgOut = function (){arrow.src = imgDir+'arrow_1.gif';};
		
	} else {
	
		menu.style.display = 'none';
		
		arrow.src = imgDir+'arrow_2.gif';
		
		newImgOver = function (){arrow.src = imgDir+'arrow_2_on.gif';};
		newImgOut = function (){arrow.src = imgDir+'arrow_2.gif';};
	}
	
//	alert(srcEl.tagName);
	srcEl.onmouseover = newImgOver;
	srcEl.onmouseout = newImgOut;
	
}

//next two funcs are the same as in PHP
function urlencode(str) {
	
	if(empty(str)) {
		return str;
	}
	
	var result = "";
	
	var pieces = str.split("&");
	
	if(pieces.length > 0) {
	
		for(var i=0; i < pieces.length; i++) {
		
			var piece = pieces[i];
			var key = piece.substr(0, piece.lastIndexOf('='));
			var value = piece.substr(piece.lastIndexOf('=')+1, piece.length);
			
			var prefix = (empty(result))?"":"&";			
			result += prefix + escape(key) + "=" + escape(value);
		}
		
	}
	
	return result;
}

function urldecode(str) {
 if(empty(str)) {
		return str;
	}
	
	var result = "";
	
	var pieces = str.split("&");
	
	if(pieces.length > 0) {
	
		for(var i=0; i < pieces.length; i++) {
		
			var piece = pieces[i];
			var key = piece.substr(0, piece.lastIndexOf('='));
			var value = piece.substr(piece.lastIndexOf('=')+1, piece.length);
			var prefix = (empty(result))?"":"&";
			
			result += prefix + unescape(key) + "=" + unescape(value);
		}
		
	}
	
	return result;
}

function toggleTagVisibility(tag) {

	var node = (is_object(tag))?tag:getElement(tag);
	
	if(node.style.display == '') {
		node.style.display = 'none';
	} else {
		node.style.display = '';
	}
	
}


//Fixes the innerHTML issue for "COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR" in IE 

function setInnerHTML(objObj, strHtml) {

	var probTags = ['col', 'colgroup', 'frameset', 'html', 'style', 'table', 'tbody', 'tfoot', 'thead', 'title', 'tr'];

	var node = (is_object(objObj))?objObj:getElement(objObj);
	
	var html = strHtml.toString();
	
	if(!in_array(node.tagName.toLowerCase(), probTags) || nav != 'IE') {
	
		node.innerHTML = html;
		
	} else {
	
		var doc = node.document;
		
		//remove children from Node, so it's innerHTML is empty
		if(!empty(node.innerHTML)) {
		
			for (var c=0; c < node.childNodes.length; c++) {
				
				var rem_child = node.removeChild(node.childNodes[c]);
				
			}
			
		}
		
		//reach an element that supports writing to innerHTML
		var normal = node.parentElement;

		if(is_null(normal)) {//probably a newly created element
		
			var doc = node.document;
		
			html = html.replace(/\r\n/gim, '');
		
			//get all tags
			while(matches = html.match(/<([a-zA-Z]*)([^<]*?)>(.*?)<\/\1>/im)) {
				
				if(empty(matches)) {
					continue;
				}
				
				var new_node = doc.createElement('<'+matches[1]+' '+matches[2]+'>');
				
				if(in_array(new_node.tagName.toLowerCase(), probTags)) {				
					
					setInnerHTML(new_node, matches[3]);
					
				} else {
				
					new_node.innerHTML = matches[3];
				}
				
				node.appendChild(new_node);
				html = html.replace(matches[0], '');
			}
			
			return;
			
		}
	
		
		
		//this will stop the while loop if no elements that support writing to innerHTML are reached
		var stop = 0;
		
		while (in_array(normal.tagName.toLowerCase(), probTags) && stop < 999) {
		
			normal = normal.parentElement
			
			stop++;
			
		}
		
		if(stop >= 999) {
			alert('Cannot perform setInnerHTML in this document.\r\nNo tags that support writing to innerHTML are found.');
			return;
		}
		
		//the whole HTML forming node
		var nodeReg = node.outerHTML.replace('><', '>'+node.innerHTML+'<');
		var newHTML = node.outerHTML.replace('><', '>'+html+'<');
		
		normal.innerHTML = normal.innerHTML.replace(nodeReg, newHTML);
		
	}//end while	
	
}


//same as in PHP
function is_numeric (val) {

	return (parseInt(val) != 'NaN');
	
}

//same as in PHP
function is_bool (val) {

	return in_array(val, [true, false]);
	
}


//does a reset of a list of form elements
function filterReset (elArr, reset) {

	if(!is_array(elArr) || empty(elArr)) {
	
		return true;
		
	}
	
	//check whether to reset the elements from the elArr or to skip them
	
	reset = (isset(reset) && !is_bool(reset))?reset.toLowerCase():((!isset(reset))?null:reset);
	
	var action = (!is_null(reset) && in_array(reset, ['skip', 'reset', true, false]))?reset:'reset';
	
	action = (is_bool(action))?((action == true)?'reset':'skip'):action.toLowerCase();
	
	var el = (is_object(elArr[elArr.length-1]))?elArr[elArr.length-1]:getElement(elArr[elArr.length-1]);

	//check if elArr contains objects or strings
	var got_by;
	
	if(el == elArr[elArr.length-1]) {
	
		got_by = 'obj';
		
	} else {
	
		//check to see if getting by name of id
		got_by = 'string';
		
		var by_id = (!empty(el.id))?'id':'name';
	}
	
	var loop = el.form;

	for (var i=0; i < loop.length; i++) {
	
		var element = loop[i];

		if(!is_null(element)){

			if(got_by == 'string') {
			
				var str = (by_id == 'id')?element.id:element.name;
				
				if(action == 'skip' && in_array(str, elArr)) {
					continue;
				} 
				
				if (action == 'reset' && !in_array(str, elArr)) {
					continue;
				}
				
			} else {
			
				if(action == 'skip' && in_array(element, elArr)) {
					continue;
				} 
				
				if (action == 'reset' && !in_array(element, elArr)) {
					continue;
				}
				
			} 

			var fire_event = true;
			
			if(element.tagName.toLowerCase() == 'input') {
				switch (element.type.toLowerCase()) {
					case 'checkbox':
					case 'radio':
						element.checked = false;
						break;
					case 'file':
						element.innerHTML = '';
						break;
					case 'button':
					case 'image':
					case 'submit':
					case 'reset':
						fire_event = false;
						continue;
					default:
						element.value = '';
						break;
				}//end switch
				
			} else if(element.tagName.toLowerCase() == 'select') {
			
				element.value = element.options[0].value;
				
			} else if (element.tagName.toLowerCase() == 'textarea') {
			
				element.innerText = '';
				
			}
			
		}//end if(!is_null(element))
		
		
		if(!empty(element.attributes) && fire_event == true) {
				
			var atl = element.attributes;
			
			for (var at=0; at < atl.length; at++) {
			
				if(atl[at].name.match(/on(click|change|load)/i)) {

					var event = atl[at].name.substr(2, atl[at].name.length);
					
					if(element.fireEvent) {
						
						element.fireEvent(atl[at].name);
						
					} else {
						
						var event_type = "";
						
						if(in_array(event, ['click', 'over'])) {
							event_type = "MouseEvents";
						} else if(in_array(event, ['change'])) {
							event_type = "UIEvents";
						} else {
							event_type = "KeyEvents";
						}
						
						var evt = document.createEvent("MouseEvents");
						var tst = element.dispatchEvent(evt);
					}
					
				}
				
			}
			
		}

	}//end for loop
	
}//end function filterReset

function slideToggleVisibility (obj) {

	var tag = (is_object(obj))?obj:getElement(obj);

	var repl = tag.parentNode.innerHTML;
	
	var tst = tag.innerHTML;
	
	alert(tst);
	
//	if(nav == 'IE') {
//	
//	} else {
//	
//		repl = repl.replace
//	
//	}
	
}


//same as in PHP
function setcookie (name, value, days_lifetime, path) {

	var cookie_string = name;
	
	cookie_string += "="+((isset(value) && !empty(value))?value:"");

	if (days_lifetime) {
		var date = new Date();
		date.setTime(date.getTime()+(days_lifetime*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	} else {
		var expires = "";
	}
	
	cookie_string += expires+"; path="+((isset(path) && !empty(path))?path:'/');
	
	document.cookie = cookie_string;


}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
//	alert(getcookie(name));
	alert(name+"="+value+expires+"; path=/");
}

function getcookie(name){
	
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function erasecookie(name){
	setcookie(name,"",-1);
}

function dupHiddenNode(nodeObj, insertAfterBool, inputs2arrayBool) {

	if(typeof nodeObj == 'undefined') {
		alert('duplicateNode()::node "'+nodeObj+'" is undefined');	
		return false;
		
	}

	var node = (typeof nodeObj != 'object')?getElement(nodeObj):nodeObj;
	
	var arr = new Array();

	var parentnode = node.parentNode;
	
	var siblings_counter = parentnode.parentNode.getElementsByTagName(node.tagName).length;

	var insertAfter = (typeof insertAfterBool == 'undefined')?true:insertAfterBool;
	
	var inputs2array = (typeof inputs2arrayBool == 'undefined')?true:inputs2arrayBool;
	
	var idsuffix = '_' + siblings_counter;//duplicateNodeCounter;// parentnode.childNodes.length;
	
	var previous_idsuffix = siblings_counter-1;//(duplicateNodeCounter == 1)?'_' + (duplicateNodeCounter-1):'';//(parentnode.childNodes.length - 1);
	
	var inputs_idsuffix = '[]';
	
	var node_id = (typeof node.id == 'undefined' || node.id == '')?'':node.id;
	
	var node_name = (typeof node.name == 'undefined' || node.name == '')?'':node.name;
	
	//duplicate the node
	var dnode = node.cloneNode(true);
	
	if(node_id != '') {
		dnode.id = node.id + idsuffix;
	} 
	
	if(node_name != '') {
		dnode.name = node.name + idsuffix;
	} 
	
	//get all childnodes in a 1 dimensioned array
	var nodes_arr = getChildNodes (dnode);
	
	for (var i in nodes_arr) {
		
		var child = nodes_arr[i];
		
		var child_id = (typeof child.id == 'undefined' || child.id == '')?'':child.id;
	
		var child_name = (typeof child.name == 'undefined' || child.name == '')?'':child.name;
		
		var is_form_element = (typeof child.tagName != 'undefined' && (in_array(child.tagName.toLowerCase(), ['input', 'textarea', 'select'])));

		if(child_name != '' && inputs2array == true) {//if child is a form element - make it an array so after submitting it'll be easier to wirk with them
			
			var new_name = (child_name.indexOf('[') == -1)?child_name:child_name.substr(0, child_name.indexOf('['));
			
			var element_exists = (is_form_element == true && document.getElementsByName(new_name+'['+(parseInt(siblings_counter)-1)+']').length > 0);

				var tmp_ex = true;
				
				var cnt = parseInt(siblings_counter)-1;
				
				var tmp_name = "";
				
				for (var s = 100; s >= cnt; s--) {
					
					tmp_name = new_name+'['+s+']';
					tmp_ex = (is_form_element == true && document.getElementsByName(tmp_name).length > 0);
					var chkbox_val = s;
					
					if (tmp_ex) {
					
						tmp_name = new_name+'['+(s+1)+']';
						chkbox_val = s+1;
						break;
					}
				}

				new_name = tmp_name;
				
//			} else {
//				new_name = (is_form_element == true)?new_name+'['+(parseInt(siblings_counter)-1)+']':new_name + idsuffix;
//			}
			
//			new_name = (is_form_element == true)?new_name+'[]':new_name + idsuffix;
//			new_name = (is_form_element == true)?new_name+'['+new_name + idsuffix+']':new_name + idsuffix;
			child.name = new_name;				
			
			if(child_name.indexOf('[') == -1){
//				original_node.name = (is_form_element == true)?child_name+'['+child_name+']':child_name + idsuffix;;			
//				original_node.name = child_name+'[]';			
			}
			
			if(child_id != '') {
				child.id = child_id + '_' + idsuffix;					
			} 
			
	//		if(is_form_element == true && child.type.toLowerCase() == 'text') {
			if(is_form_element == true) {
				var ctype = child.type;//.toString().toLowerString();				
				switch (ctype) {//clear the entered values
					case 'checkbox':						
						child.checked = false;
//						child.name = child.name.replace(/\[\]/, '') +'['+parseInt(siblings_counter)+']';
						
						if(is_numeric(child.value)) {
							child.value = chkbox_val;//parseInt(child.value)+(parseInt(siblings_counter)-1);
						}
						break;					
					case 'select-one':
					case 'select-multiple':
						child.selectedIndex = 0;
						break;					
					default:						
						//cannot clear file value
						if(child.type.toLowerCase() != 'file') {
							child.value = '';	
						}
						break;	
				}//end clearing entered values
							
			}
			
		} else if(child_name != '' && inputs2array == false) {
			
			var new_name;
			
			if(child_name.indexOf(idsuffix) == -1 && child_name.indexOf(previous_idsuffix) == -1) {				
				new_name = child_name;				
			} else {
				new_name = child_name.substr(0, child_name.lastIndexOf(previous_idsuffix));
			}
			
			if(typeof getElement(new_name).defval != 'undefined') {			
				var child_original = getElement(new_name);
				var repl = child_original.defval;				
				var r = /{@([^@]+)@}/gi;
				child.defval = repl.replace(r, '{@$1'+idsuffix+'@}');		
				child.required = child_original.required;
				child.title = child_original.title;
				child.order = child_original.order;
			}

			child.name = new_name + idsuffix;
			
			if(child_id != '') {
				child.id = child_id + '_' + idsuffix;					
			} 
			
//			if(is_form_element == true && child.type.toLowerCase() == 'text') {
			if(is_form_element == true) {
				var ctype = child.type;//.toString().toLowerString();				
				switch (ctype) {//clear the entered values
					case 'checkbox':						
						child.checked = false;											
						break;					
					case 'select-one':
					case 'select-multiple':
						child.selectedIndex = 0;
						break;					
					default:
						child.value = '';	
						break;	
				}//end clearing entered values
							
			}
		
		}
		
	}
	

	if(insertAfter == false) { //insert the new node before the pattern node
		parentnode.insertBefore(dnode, node);
	} else {
		var last_child = parentnode.childNodes[parentnode.childNodes.length-1];
		parentnode.insertBefore(dnode, last_child);
		parentnode.insertBefore(last_child, dnode);
//		alert(node.innerHTML);
	}
	
	if(dnode.style.display == 'none') {
		dnode.style.display = '';
	}
	
	return true;	
	
}

function __do_nothing() {
	return true;
}


//Print Page
function printIt(target) { 
  var macprint;
  
  var frame = (!isset(target) || !in_array(target, window.frames))?window:window.frames[target];
  
  macprint = "Unfortunately this functionality is not available in your browser.\r\nPlease click the page you would like to print a select print from your browser menu.";

  if (!window.print) { 
    alert(macprint);
  } else {
  	frame.print();
  }
}


function implode(glue, array) {

	if(!is_array(array)) {
		return false;
	}
	
	return array.join(glue);
	
}

function explode(delimiter, string) {

	if(!is_string(string)) {
		return false;
	}
	
	string = new String(string);
	
	return string.split(delimiter);
	
}


function popup(url, w, h, l, t) {

	var opts = (arguments[5])?((is_array(arguments[5]))?implode(',', arguments[5]):arguments[5]):'';
	
	if(empty(opts)) {
	
		opts = "location=0,menubar=0,resizable=0,scrollbars=1,status=0,toolbar=0";
		
	}
	
	if(isset(h)) {
		opts += ((!empty(opts))?',':'')+"height="+h;
	}
	
	if(isset(w)) {
		opts += ((!empty(opts))?',':'')+"width="+w;
	}
	
	if(isset(l)) {
		opts += ((!empty(opts))?',':'')+"left="+l;
	}
	
	if(isset(t)) {
		opts += ((!empty(opts))?',':'')+"top="+t;
	}
	
	return window.open(url, null, opts);
	
}

function getSel(win_obj) {
		
	var txt = '';
	
	var win = window;
	
	if(isset(win_obj)) {
	
		win = (is_object(win_obj))?win_obj:win;
		
	}
	
	if (win.getSelection) {
		txt = win.getSelection();
	} else if (win.document.getSelection)	{
		txt = win.document.getSelection();
	} else if (win.document.selection) {
		txt = win.document.selection.createRange().text;
	} 
	
	return txt;
}

function insertAtCursor(txt_field, insert_text, win_obj) {
	
	var win = window;
	
	if(isset(win_obj)) {
	
		win = (is_object(win_obj))?win_obj:win;
		
	}
	
//	alert(txt_field.selectionStart);return;
	
	//IE support
	if (win.document.selection) {
		sel = win.document.selection.createRange();		
		sel.text = insert_text;
	
	} else if (win.getSelection) {
	
		var sel = win.getSelection();

		var doc = win.document;
		
		var range = sel.getRangeAt(0);
	
		var start = range.startOffset;
		var end = range.endOffset;
		
		sel.anchorNode.nodeValue = sel.focusNode.nodeValue = sel.anchorNode.nodeValue.substring(0, ((start == 0)?1:start))
									+ insert_text
									+ sel.focusNode.nodeValue.substring(end, sel.focusNode.nodeValue.length);
			
		range.deleteContents();

	}  else {
		
		txt_field.value += insert_text;
		
	}
}
