
function catchError(msg,url,l) {
//return true;
	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;

}

if(DEBUG_MODE) {
	window.onerror = catchError;
}


function phoneFormat(e,id) {
  if (id == 'undefined') {
	  var keynum; var keychar; var numcheck;
	  if(window.event) // IE
	  { keynum = e.keyCode }
	  else if(e.which) // Netscape/Firefox/Opera
	  { keynum = e.which }
	  else { return true; } // do not work
	  if ( keynum < 32 || keynum > 127 ) { return true; } // keep functional keys active
	  keychar = String.fromCharCode(keynum); 
	  numcheck = /\d/;
	  if ( numcheck.test(keychar) ) { 
		  ssNumber = document.getElementById('work'); 
		  if ( !ssNumber ) { return false; }
		  if ( ssNumber.value.length >= 14  ) { return false; }
		  if ( ssNumber.value.length == 3 ) { ssNumber.value = '(' + ssNumber.value + ')-'; }
		  else if ( ssNumber.value.length ==9 ) { ssNumber.value += '-'; }
		  return true;
	  }
  }
  else if ( id == 1) {
	  var keynum; var keychar; var numcheck;
	  if(window.event) // IE
	  { keynum = e.keyCode }
	  else if(e.which) // Netscape/Firefox/Opera
	  { keynum = e.which }
	  else { return true; } // do not work
	  if ( keynum < 32 || keynum > 127 ) { return true; } // keep functional keys active
	  keychar = String.fromCharCode(keynum); 
	  numcheck = /\d/;
	  if ( numcheck.test(keychar) ) { 
		  ssNumber = document.getElementById('phone'); 
		  if ( !ssNumber ) { return false; }
		  if ( ssNumber.value.length >= 14  ) { return false; }
		  if ( ssNumber.value.length == 3 ) { ssNumber.value = '(' + ssNumber.value + ')-'; }
		  else if ( ssNumber.value.length ==9 ) { ssNumber.value += '-'; }
		  return true;
	  }
  }
  else if ( id == 2) {
	  var keynum; var keychar; var numcheck;
	  if(window.event) // IE
	  { keynum = e.keyCode }
	  else if(e.which) // Netscape/Firefox/Opera
	  { keynum = e.which }
	  else { return true; } // do not work
	  if ( keynum < 32 || keynum > 127 ) { return true; } // keep functional keys active
	  keychar = String.fromCharCode(keynum); 
	  numcheck = /\d/;
	  if ( numcheck.test(keychar) ) { 
		  ssNumber = document.getElementById('home'); 
		  if ( !ssNumber ) { return false; }
		  if ( ssNumber.value.length >= 14  ) { return false; }
		  if ( ssNumber.value.length == 3 ) { ssNumber.value = '(' + ssNumber.value + ')-'; }
		  else if ( ssNumber.value.length ==9 ) { ssNumber.value += '-'; }
		  return true;
	  }
  }
  else if ( id == 3) {
	  var keynum; var keychar; var numcheck;
	  if(window.event) // IE
	  { keynum = e.keyCode }
	  else if(e.which) // Netscape/Firefox/Opera
	  { keynum = e.which }
	  else { return true; } // do not work
	  if ( keynum < 32 || keynum > 127 ) { return true; } // keep functional keys active
	  keychar = String.fromCharCode(keynum); 
	  numcheck = /\d/;
	  if ( numcheck.test(keychar) ) { 
		  ssNumber = document.getElementById('cell'); 
		  if ( !ssNumber ) { return false; }
		  if ( ssNumber.value.length >= 14  ) { return false; }
		  if ( ssNumber.value.length == 3 ) { ssNumber.value = '(' + ssNumber.value + ')-'; }
		  else if ( ssNumber.value.length ==9 ) { ssNumber.value += '-'; }
		  return true;
	  }
  	
  }
  else if ( id == 4) {
	  var keynum; var keychar; var numcheck;
	  if(window.event) // IE
	  { keynum = e.keyCode }
	  else if(e.which) // Netscape/Firefox/Opera
	  { keynum = e.which }
	  else { return true; } // do not work
	  if ( keynum < 32 || keynum > 127 ) { return true; } // keep functional keys active
	  keychar = String.fromCharCode(keynum); 
	  numcheck = /\d/;
	  if ( numcheck.test(keychar) ) { 
		  ssNumber = document.getElementById('fax'); 
		  if ( !ssNumber ) { return false; }
		  if ( ssNumber.value.length >= 14  ) { return false; }
		  if ( ssNumber.value.length == 3 ) { ssNumber.value = '(' + ssNumber.value + ')-'; }
		  else if ( ssNumber.value.length ==9 ) { ssNumber.value += '-'; }
		  return true;
	  }
  	
  }
  else if ( id == 'current') {
	  var keynum; var keychar; var numcheck;
	  if(window.event) // IE
	  { keynum = e.keyCode }
	  else if(e.which) // Netscape/Firefox/Opera
	  { keynum = e.which }
	  else { return true; } // do not work
	  if ( keynum < 32 || keynum > 127 ) { return true; } // keep functional keys active
	  keychar = String.fromCharCode(keynum); 
	  numcheck = /\d/;
	  if ( numcheck.test(keychar) ) { 
		  ssNumber = document.getElementById('current_phone'); 
		  if ( !ssNumber ) { return false; }
		  if ( ssNumber.value.length >= 14  ) { return false; }
		  if ( ssNumber.value.length == 3 ) { ssNumber.value = '(' + ssNumber.value + ')-'; }
		  else if ( ssNumber.value.length ==9 ) { ssNumber.value += '-'; }
		  return true;
	  }
  	
  }
  else if ( id == 'previous') {
	  var keynum; var keychar; var numcheck;
	  if(window.event) // IE
	  { keynum = e.keyCode }
	  else if(e.which) // Netscape/Firefox/Opera
	  { keynum = e.which }
	  else { return true; } // do not work
	  if ( keynum < 32 || keynum > 127 ) { return true; } // keep functional keys active
	  keychar = String.fromCharCode(keynum); 
	  numcheck = /\d/;
	  if ( numcheck.test(keychar) ) { 
		  ssNumber = document.getElementById('previous_phone'); 
		  if ( !ssNumber ) { return false; }
		  if ( ssNumber.value.length >= 14  ) { return false; }
		  if ( ssNumber.value.length == 3 ) { ssNumber.value = '(' + ssNumber.value + ')-'; }
		  else if ( ssNumber.value.length ==9 ) { ssNumber.value += '-'; }
		  return true;
	  }
  	
  }
    
  return false;
}

function loadBanner( socketId, timeForReload, url )
{

  if( !window.banRealod )
   window.banRealod = new Array();

  try
  {
     clearTimout(  window.banRealod[ socketId ] );     
  }
  catch( e ){}
  

  new Ajax.Updater( $( socketId ).parentNode.id , url, {} );
     
  window.banRealod[ socketId ] = setTimeout( function(){  loadBanner( socketId, timeForReload, url )  }, timeForReload );

}

//*********************************************************************************************//

function getElement(id) {

	if(typeof id == 'undefined' || empty(id)) {
		return null;
	} else if(typeof id == 'object') {

		if(typeof id.tagName != 'undefined') {

			return id;

		} else {

			return null;
		}

	}

	var obj = $(id);

	if(obj == null || typeof obj == 'undefined') {//try get the element by name
		obj = document.getElementsByName(id);
		if(obj.length > 0) {
			obj = obj[0];
		} else {
			obj = null;
		}

	}

	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')?$(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')?$(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 = $(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 $(new_name).defval != 'undefined') {
				var child_original = $(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')?$(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:$(iframe);

	f = (f == null)?document.createElement('IFRAME'):f;

	var target = (typeof targetDd == 'object')?targetDd:$(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, $(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:$(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:$(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:$(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) {

	var select1 = (is_object(select1Obj))?select1Obj:$(select1Obj);
	var select2 = (is_object(select2Obj))?select2Obj:$(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;
		}

	  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);
	}
	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:$(select1Obj);
	var select2 = (is_object(select2Obj))?select2Obj:$(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:$(nodeObj);

	var noremove = (typeof noremoveStr == 'object')?noremoveStr:$(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:$(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 = $(hidden+'['+row.id.substr(row.id.lastIndexOf('_')+1, row.id.length)+']');
	var order_swap = $(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 = $(hidden+'['+row.id.substr(row.id.lastIndexOf('_')+1, row.id.length)+']');
	var order_swap = $(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:$(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:$(obj);

	var constr = (isset(chkbox.form))?'':'form';

	var ch_name = (!empty(chkbox.name))?chkbox.name:chkbox.id;

	var pattern = (isset(pattern_name))?pattern_name:'';

	obj.checked = true;

	//the object is a form
	if(constr.indexOf('form') != -1) {

		var loop = chkbox.getElementsByTagName('INPUT');

		var skip = Event.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:$(pTagName);

	var arrow;

	if(!empty(pImg)) {

		arrow = (is_object(pImg))?pImg:$(pImg);

		//get the event element and change it's onmouseover and onmouse out
		var srcEl = Event.element().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 = $(trigger);

	//get the eventual ids by which to check the checkboxes
	chboxnames = chboxnames || [];

	switch (typeof chboxnames) {
		case 'string': //split the string in an array
			chboxnames = chboxnames.replace(/\s/gim).split(',');
			break;
		case 'number':
			chboxnames = [];
			break;
		default:
			if (typeof chboxnames.join != 'function') {//an array
			
				chboxnames = $A(chboxnames);
			
			} 
			break;
		
	}
	
	//the form the checkboxes belong to
	var frm = getElementsByAttributes('type=checkbox', $(form || obj.form));

	var loop = frm;

	for (var i=0; i < loop.length; i++) {

		var chkbox = loop[i];

		try {
			
			if(chkbox.type.toLowerCase() == 'checkbox') {

				var checkIt;
			
				if(chboxnames.length) {//check if the checkbox is in the array of names/ids
				
					if(chkbox.id != '' && chboxnames.indexOf(chkbox.id) > -1) {
						checkIt = true;
					} else if(chboxnames.indexOf(chkbox.name) > -1) {
						checkIt = true;
					} else {
						checkIt = false;
					}
				
				} else {
					checkIt = true;
				}
				
				if(checkIt) {
				
					chkbox.checked = obj.checked;
	
				} else if(!chboxnames.length) {
	
					if(chkbox.checked == true) {
						chkbox.checked = false;
					} else {
						chkbox.checked = true;
					}
	
				}
			}
		} catch (e) {
		
		}

	}

}//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:$(target));



	window.print();

}

function showHideMenu(pMenuTable, pImg) {

	menu = $(pMenuTable);
	arrow = $(pImg);

	//get the event element and change it's onmouseover and onmouse out
	srcEl = Event.element().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, collapse_others, collapse_collection) {

	var node = (is_object(tag))?tag:$(tag);

	if(node.style.display == 'none') {

	    collaps_others = (isset(collapse_others))?collapse_others:false;

    	if(collapse_others) {

    	   if(!isset(collapse_collection)) {

    	       collapse_collection = [];

    	       var risky_find = true;

    	       var html = document.body.innerHTML;

    	       var matches = html.match(/((onclick=|javascript:)['"]?(.*?)toggleTagVisibility\(['"])([^'"]*?)(['"]([^'"]*?)['"]?)/gim);

    	       //find the onclick="toggleTagVisibility" in the doc
               if(matches && matches.length) {

                   for(var i=0; i < matches.length; i++) {

//                       var reg =

                       var id = matches[i].search(/toggleTagVisibility\(('|")/gim);
                       id = matches[i].substr(id+21);//21 is the length of toggleTagVisibility("
                       id = id.substr(0, id.search(/('|")/gim));
//'
                       id = $(id);

                       if(id && typeof id.tagName != 'undefined' && typeof id.tagName != 'undefined' && id.tagName == node.tagName) {
                            collapse_collection.push(id);
                       }

                   }

               }

    	   }

    	   //define whether to collapse the objects or not
    	   var collapse;

    	   for(var i=0; i < collapse_collection.length; i++ ) {

    	       var obj = collapse_collection[i];

    	       if(isset(risky_find)) {

    	           collapse = (is_object(obj) && obj != node && obj.style.display == '');

    	       } else {

    	           collapse = (obj.style.display == '');

    	       }

    	       if(collapse) {
                    obj.style.display = 'none';
               }

    	   }

    	}

		node.style.display = '';
	} else {
		node.style.display = 'none';
	}

}


//Fixes the innerHTML issue for "COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR" in IE

function setInnerHTML(objObj, strHtml) {

	var probTags = ['script', 'col', 'colgroup', 'frameset', 'html', 'style', 'table', 'tbody', 'tfoot', 'thead', 'title', 'tr'];

	var node = (is_object(objObj))?objObj:$(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]:$(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:$(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')?$(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 $(new_name).defval != 'undefined') {
				var child_original = $(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;

	}
}


function triggerEvent(el, ev_type) {

	var element = (is_object(el))?el:$(el);

	var event_type = ev_type.toLowerCase();

	if(event_type.indexOf('on') == 0 && !element.fireEvent) {

		event_type = event_type.substring(2, event_type.length);

	}

	if(element.fireEvent) {

		element.fireEvent(event_type);

	} else {

		if(in_array(event_type, ['click', 'over'])) {
			event_type = "MouseEvents";
		} else if(in_array(event_type, ['change'])) {
			event_type = "UIEvents";
		} else {
			event_type = "KeyEvents";
		}

		var evt = document.createEvent("MouseEvents");
//		var evt = document.createEvent(event_type);
		var tst = element.dispatchEvent(evt);
	}

}


function trim(TRIM_VALUE, charlist){

	if(TRIM_VALUE.length < 1){
		return"";
	}

	var rem = (isset(charlist))?charlist:'';

	TRIM_VALUE = rtrim(TRIM_VALUE, rem);

	TRIM_VALUE = ltrim(TRIM_VALUE, rem);

	if(TRIM_VALUE==""){
		return "";
	}	else {
		return TRIM_VALUE;
	}
} //End Function

function rtrim(VALUE, charlist){

	var w_space = (isset(charlist))?charlist:String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";

	if(v_length < 0){
		return"";
	}

	var iTemp = v_length -1;

	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space){

		} else {
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}

		iTemp = iTemp-1;

	} //End While

	return strTemp;

} //End Function

function ltrim(VALUE, charlist){
	var w_space = (isset(charlist))?charlist:String.fromCharCode(32);

	if(v_length < 1){
		return"";
	}

	var v_length = VALUE.length;
	var strTemp = "";

	var iTemp = 0;

	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){

		} else {
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}

		iTemp = iTemp + 1;

	} //End While

	return strTemp;
} //End Function



function emulateHover(object, color) {

	var obj = (is_object(object))?object:$(object);

	if(typeof color != 'undefined') {
		var is_color = (trim(color).indexOf('#') == 0);
	} else {
		var is_color = (typeof myOldColor != 'undefined');
	}

	if(is_color) {

		if(typeof myOldColor == 'undefined' || myOldColor == null) {

			myOldColor = obj.style.backgroundColor;

			obj.style.backgroundColor = color;
		} else {
			obj.style.backgroundColor = myOldColor;
			myOldColor = null;
		}

	} else {

		if(typeof myOldClassName == 'undefined' || myOldClassName == null) {

			myOldClassName = obj.className;

			obj.className = color;

		} else {

			obj.className = myOldClassName;
			myOldClassName = null;

		}

	}

}


function include(file) {//same as in PHP

	if(typeof file == 'undefined' || file == null || file == '') {

		return;

	}

	var all = document.getElementsByTagName('SCRIPT');

	file = trim(file);

	var do_inc = true;

	for(var i=0; i < all.length; i++) {

		if(typeof all[i].src != 'undefined' && all[i].src == file) {
			//this file has already been included
			do_inc = false;
			break;
		}

	}

	if(do_inc){

		var inc = document.createElement('SCRIPT');

		if(typeof document.getElementsByTagName('HEAD')[0] != 'undefined') {

			document.getElementsByTagName('HEAD')[0].appendChild(inc);

		} else if(typeof document.body != 'undefined') {

			document.body.appendChild(inc);

		} else {

			document.appendChild(inc);

		}

		inc.src = file;

	}

}

function reloadJS () {

	var all = document.getElementsByTagName('SCRIPT');

	for(var i=0; i < all.length; i++) {

		if(isset(all[i].src) && !empty(all[i].src)) {

			var src = all[i].src.toString();

			all[i].src = null;

			all[i].src = src;
		}

	}

}

function runScripts(html, include_head) {

	var e;

	if(html && document.all) {//IE runs scripts on innerHTML

		return;

	}

	var in_head = (typeof include_head == 'undefined')?false:((in_array(include_head, [true, false]))?include_head:false);

//	var run_in = (typeof html == 'undefined')?document:'span';

	if(typeof html != 'undefined') {

		var tmp = document.createElement('SPAN');

		tmp.innerHTML = '&nbsp;' + html;

		e = tmp.getElementsByTagName("SCRIPT");

	} else {

		e = document.getElementsByTagName("SCRIPT");
	}

	var scr_holder = document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0] || document;

	if(in_head) {

		var head_scr = document.getElementsByTagName('HEAD')[0].getElementsByTagName("SCRIPT")

		var srcs = [];

		for(var i=0;i<head_scr.length;i++) {

			if(!empty(head_scr[i].src) && !in_array(head_scr[i].src, srcs)) {
				include(head_scr[i].src.toString());
				srcs.push(head_scr[i].src.toString());

			} else if(!empty(head_scr[i].innerHTML)) {

				eval(head_scr[i].innerHTML);

			}
		}

	}



	for(var i=0;i<e.length;i++) {

		if(!empty(e[i].src) && !in_array(e[i].src, srcs)) {

			if(e[i].parentNode.tagName.toUpperCase() == 'HEAD') {

				continue;

			}

		}

		if(!empty(e[i].innerHTML)) {

			var scr = document.createElement('SCRIPT');

			scr.setAttribute('language', 'javascript');

			scr.setAttribute('type', 'text/javascript');

			//IE send an "Unknown runtime error" error, so we need to pass it
			try {

				scr.innerHTML = e[i].innerHTML;

			} catch(err) {

				var send = encodeURIComponent(e[i].innerHTML);

				scr.src = './lib/js/js.php?script='+send;

			}

			scr_holder.insertBefore(scr, scr_holder.childNodes[0]);

		}

	};
}


function interceptSubmit(formObj, callback) {

	var form = (is_object(formObj))?formObj:$(formObj);

	if(typeof form.submit == 'undefined') {//formObj is not a form

		return true;
	}

	if(typeof callback == 'undefined') {//just submit the form

		eval('form.submit = function() { return false;}');
		request(form, null, window.location.toString());
		return false;
	}

	if(trim(callback).indexOf('function') == 0) {
		//if just a func reference is provided - create a function
		eval('form.submit = '+callback);
		eval('form.onsubmit = '+callback);
	} else {

		eval('form.submit = function() { return false;}');
		eval('form.onsubmit = function() { return '+callback+'}');
	}

}

function getSubmit() {

	gSubmitButton = Event.element();

}

function getScroll() {
	var x=0,y=0;

	if (window.pageYOffset) // all except Explorer
	{
		x = window.pageXOffset;
		y = window.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
		// Explorer 6 Strict
	{
		x = document.documentElement.scrollLeft;
		y = document.documentElement.scrollTop;
	}
	else if (document.body) // all other Explorers
	{
		x = document.body.scrollLeft;
		y = document.body.scrollTop;
	}

	var scroll = [x,y];

	scroll['x'] = x;
	scroll['y'] = y;

	return scroll;

}

function parseUrl(url){

	url = (isset(url))?trim(url):window.location.toString();

	//var parsed_url = url.split(/([^:]*?):\/\/([^\/]{0,})/gim);
	var parsed_url = url.split(/\//gim);

	var parsed = [];

	if(parsed_url.length > 0) {

		parsed['url'] = url;
		parsed['schema'] = parsed_url[0].replace(/\:/gim, '');
		parsed['host'] = (empty(parsed_url[1]))?parsed_url[2]:parsed_url[1];
		parsed['path'] = '';
		parsed['query'] = '';

		for(var i=((document.all)?2:3); i < parsed_url.length; i++) {

			if(parsed_url[i].indexOf('?') != -1) {//reached the query
				parsed['query'] = parsed_url[i].substr(parsed_url[i].indexOf('?')+1, parsed_url[i].length);
				break;
			}

			if(parsed_url[i]) {
				parsed['path'] += "/"+parsed_url[i];
			}

		}
	}

	return parsed;

}

function include(file_path) {

	var scr = document.createElement('SCRIPT');

	scr.setAttribute('language', 'javascript');

	scr.setAttribute('type', 'text/javascript');

	scr.src = file_path;

	var scr_holder = document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0] || document;

	scr_holder.insertBefore(scr, scr_holder.childNodes[0]);

}

function require(file_path) {

	include(file_path);

}

//prints an alternative document
function printAlt(doc, addCss) {

	if(empty(doc)) {//assume we're printing the current page
		window.print();
		return;
	}

	var file = trim(doc);

	if(nav=='IE') {

		var style_tag = document.createElement('LINK');

		style_tag.media = 'print';

		style_tag.rel = 'alternate';

		style_tag.href = file;

		var style_parent = document;

		if(typeof document.getElementsByTagName('HEAD')[0] != 'undefined') {

			style_parent = document.getElementsByTagName('HEAD')[0];

		}

		style_parent.appendChild(style_tag);

		window.print();

		return;

	}


	if(AjaxObj.readyState == AJAX_NOT_STARTED) {

		var css = (typeof addCss == 'string')?addCss:'';

		request(null, 'GET', doc, null, 'printAlt("'+file+'", "'+css+'")');

	} else if(AjaxObj.readyState == AJAX_READY) {

		if(AjaxObj.status != '404') {

		var printer_id = '__altPrinter';

		var print_holder = $(printer_id);

		if(is_null(print_holder)) {

			print_holder = document.createElement('DIV');

			print_holder.id = printer_id;

			var parent = document;

			var style_parent = document;

			if(document.body) {

				parent = document.body;

				style_parent = document.body;

			}

			var passed_tags = [];

			if(typeof addCss == 'string' && !empty(addCss)) {

				//check if providing a className or inline style
				if(addCss.split(':').length > 0) {//an inline style

					print_holder.setAttribute('style', addCss);

				} else {//a className

					print_holder.className = addCss;

				}

			}

			var style_tagInnerHTML = '@media print {\r\n';

			style_tagInnerHTML += 'BODY{\r\nbackground-color:#FFFFFF;\r\n}\r\n';

			var canCSS = (typeof document.styleSheets != 'undefined');


			for(var i=0; i < parent.childNodes.length; i++) {

				if(typeof parent.childNodes[i].tagName != 'undefined' && !in_array(parent.childNodes[i].tagName, passed_tags)) {

						if(typeof parent.childNodes[i].id == 'undefined' || parent.childNodes[i].id == '') {
							parent.childNodes[i].id = 'printing_'+i;
					}
					style_tagInnerHTML += '\r\n'+parent.childNodes[i].tagName.toString().toUpperCase()+'#'+parent.childNodes[i].id;

					style_tagInnerHTML += '{\r\ndisplay:none;\r\n}';

				}

			}

			style_tagInnerHTML += '\r\nDIV#'+printer_id+'\r\n{\r\n display:block;\r\n}\r\n}\r\n';
			style_tagInnerHTML += '@media screen {\r\nDIV#'+printer_id+'\r\n{\r\n display:none;\r\n}\r\n}';

			var theRules = new Array();

			if (document.styleSheets[1].cssRules)
				theRules = document.styleSheets[1].cssRules
			else if (document.styleSheets[1].rules)
				theRules = document.styleSheets[1].rules
			alert(theRules);
			theRules[theRules.length-1].style.backgroundColor = '#FFFFFF';

			var style_tag = document.createElement('STYLE');

			style_tag.innerHTML = style_tagInnerHTML;

			style_parent.appendChild(style_tag);

			parent.appendChild(print_holder);

		}

			var content = AjaxObj.getResponseHeader('Content-type');

			switch(content.substr(0, content.lastIndexOf('/'))) {
				case 'image':
					content = '<img src='+file+'>';
					break;
				default:
					content = AjaxObj.responseText;
					break;
			}

			print_holder.innerHTML = content;

		AjaxObj.abort();

		window.print();

		} else {

			AjaxObj.abort();

			//var file_name = parseUrl(file).path;

			//file_name = file_name.substr(file_name.lastIndexOf('/')+1, file_name.length);

			alert('The file:\r\n"'+file+'"\r\nwas not found');

		}

	}

}


function adEv(t,ev,fn)
{

	ev = trim(ev).toLowerCase();

	ev = (ev.indexOf('on') == 0)?ev.substring(2, ev.length):ev;

	if (typeof document.addEventListener != 'undefined')
	{
		t.addEventListener(ev,fn,false);
	}
	else
	{

		var f = trim(fn.toString());

		if(f.match(/function[^\(\b]+\(/i)) {
			f = trim(f.substring(f.indexOf(' ')+1, f.indexOf('(')));
		}

		t.attachEvent('on' + ev, fn);
		eval('t.on' + ev + '= ' + f +';');
	}

}

function rmEv(t,ev,fn)
{
	ev = trim(ev).toLowerCase();

	ev = (ev.indexOf('on') == 0)?ev.substring(2, ev.length):ev;

	if (typeof document.removeEventListener != 'undefined')
	{
		t.removeEventListener(ev,fn,false);
	}
	else
	{
		t.detachEvent('on ' + ev, fn);
	}

//	eval('delete(t.on' + ev + ');');
}


function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

function getElementsByAttributes(list,obj, deep) {

	obj = ($(obj) || document);

	var tagNames = (list.join)?list:list.split(',');
//alert(tagNames)
	var resultArray = new Array();

	deep = [true, false, 1,0].indexOf(deep) != -1?deep:true;

	var attribute;

	for (var i=0;i<tagNames.length;i++) {

		var tags = (obj == document)?document.getElementsByTagName('BODY')[0].childNodes:obj.childNodes;

		var tagName = tagNames[i];

		var tagVal;

		if((attribute = tagName.split('=')).length == 2) {//an "attribute=attributeValue" couple
			 tagName = attribute.first().trim(' ');

			 tagVal = attribute.last().trim(' ');
		}

		for (var j=0; j < tags.length; j++) {

			if(tags[j].nodeType != 1) {
				continue;
			}

			if(tags[j].getAttribute && (attribute = tags[j].getAttribute(tagName)) != null) {

				if(typeof tagVal == 'undefined') {
					resultArray.push(tags[j]);
				} else if(attribute == tagVal) {
					resultArray.push(tags[j]);
				}

			}

			if(deep && tags[j].childNodes && tags[j].childNodes.length > 0) {

				resultArray = resultArray.concat(getElementsByAttributes(list, tags[j]));

			}

		}
	}

	var testNode = resultArray[0];
	if (typeof testNode == 'undefined') return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}

	return resultArray;
}

function getElementsById(id, obj) {

	var resultArray = [];

	if (!obj) var obj = document;

	var tags = (obj == document)?((document.all)?document.all:document.getElementsByTagName('BODY')[0].childNodes):obj.childNodes;

	for (var j=0;j< tags.length; j++) {

		if(tags[j].id && tags[j].id == id) {
			resultArray.push(tags[j]);
		}

		if(!document.all && tags[j].childNodes && tags[j].childNodes.length > 0) {

			resultArray = resultArray.concat(getElementsById(id, tags[j]));

		}

	}

	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}

	return resultArray;
}


function orderBySourceIndex(arrayWithNodes) {

	if(!arrayWithNodes.join) {//not an array
		throw({message:'Argument is not an array'});
		return [];
	}

	var testNode = arrayWithNodes.first();
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		arrayWithNodes.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		arrayWithNodes.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}

}

function _dumpScripts() {
	var jsArray = document.getElementsByTagName('script');
	var theWinref;
	var theHTML;
	var scriptObj;
	var frameURL;
	var frameObj;
	if(jsArray.length > 0) {
	 if(!(theWinref = window.open('','_blank','width="320px",height="500px",toolbar=no,location=no,directories=no,status=yes,menubar=no,resizeable=yes'))) {

	 	alert('Popup blocker')
	 	return;

	 }
	 theWinref.document.write('<html><head><title>' + window.location.href + '</title></head><body>'+ jsArray.length+' Script(s) Found:');
	 theWinref.resizeTo(600,200);
	 theWinref.moveTo(0,0);
	}
	for (var i = 0; i < jsArray.length; i++) {
	 scriptObj = jsArray[i];
	 if(scriptObj.hasAttribute('src')){
			frameURL = scriptObj.getAttribute('src');
	 		theWinref.document.write('<p style=\'background-color:#999933;\'>Script '+eval(i+1)+' via ' + frameURL + '<br><iframe height=\'100%\' width=\'100%\' id=\'url'+ i + '\' src=\'' + frameURL + '\'></iframe></p>');
	 		frameObj = theWinref.document.getElementById('url' + i);
		} else {
	 		theHTML = scriptObj.innerHTML;
	 		theWinref.document.write('<p style=\'background-color:#999933;\'>Script '+eval(i+1)+':<br><pre>' + theHTML + '</pre></p>');
		}
	}
	if(jsArray.length > 0) {
		theWinref.document.write('</body></html>');
	}

}


function makeEditableField (where, fieldType, onFinishEditOptions, setSaveButton) {
return true;
	if(where.push) {//if an array

		for(var i=0; i < where.length; i++) {

			var type = (fieldType.push)?(fieldType[i] || 'text'):fieldType;

			var callback = (onFinishEditOptions && onFinishEditOptions.push)?(onFinishEditOptions[i] || Prototype.emptyFunction):onFinishEditOptions;

			makeEditableField (where[i], type, ((i > 0 && typeof onFinishEditOptions == 'function')?Prototype.emptyFunction:callback), i==(where.length-1));
//			makeEditableField (where[i], type, callback, i==(where.length-1));

		}

		return;
	}

	if(!(where = $(where))) {

		return;

	}

	fieldType = (fieldType || '').toString().toLowerCase();

//	if(['textarea', 'text'].indexOf(fieldType) == -1) {
//
//		return;
//
//	}

	setSaveButton = (typeof setSaveButton == 'boolean')?setSaveButton:true;

	var restoreHtml = where.innerHTML;

	var text = where.innerHTML;

	var input;

	if(!text.match(/<(textarea|input)/gim)) {

		text = text.stripTags();

		switch(fieldType) {
			case 'textarea':
				Element.update(where, '<textarea id="'+where.id+'.Editable" editable="1">'+text+'</textarea>');
				break;
			case 'text':
				Element.update(where, '<input editable="1" id="'+where.id+'.Editable" type="text" value="'+text+'">');
				break;
			default:

				Element.update(where, fieldType);

				input = where.childNodes[0];

				input.id = where.id+'.Editable';

				input.value = text;

				input.setAttribute('editable', 1);

				break;
		}

	}

	input = (input || $(where.id+'.Editable'));

	input.onUpdate = function(){(onFinishEditOptions || function() {})();};

	input.onAfterAllUpdated = function(){Element.update(where, restoreHtml.replace(text.stripTags(), this.value))};

	if(setSaveButton) {

//		Element.update(where, where.innerHTML + '<br><input type="button" value="Save" onclick="updateEditables();">');

	}

	Event.listen(input, 'blur', function() {updateEditables();})

}

function updateEditables () {

	var editables = getElementsByAttributes('editable');

	for(var i=0; i < editables.length; i++) {

		if(editables[i].onUpdate) {

			editables[i].onUpdate();

		}

	}

	for(var i=0; i < editables.length; i++) {

		if(editables[i].onAfterAllUpdated) {

			editables[i].onAfterAllUpdated();

		}

	}

}


function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}
