// Some Variables

var viewportwidth;															// set to the width of the browser viewport (visible screen)
var viewportheight;															// set to the height of the browser viewport (visible screen)
var myObj = false;

var message_box_fade_timeout_id = -1;
 
// END some variables

// CENTER DIV ON PAGE STUFF
	IE5=NN4=NN6=OPA=false
	if(navigator.userAgent.toLowerCase().indexOf("opera")+1)OPA=true
	else if(document.all)IE5=true
	else if(document.layers)NN4=true
	else if(document.getElementById)NN6=true
	
	onload=initialize   // call initialize() when page loads
	onresize=rePos      // call rePos() whenever page is resized
	onscroll=rePos
	
	// Opera doesn't have an onresize event so you have to call rePos all the time.
	if(OPA) setInterval("rePos()",500)
	
	function initialize() {
		// first we check if the centreDIv exists, if there isnt one we do do anything
		if (!document.getElementById("centerDiv")) { myObj = false; return false; }
		
		if(NN4) myObj=document.centerDiv
		else myObj=document.getElementById("centerDiv").style
		rePos()
	}
	
	w=300   // width of the div
	h=100   // height of the div
	function rePos() {
		// first we check if myObj exists (if there is a centre div), if there isnt one we do do anything
		if (!myObj) return false;
		
		// compute center coordinate
		if(NN4||NN6) {
			xc=Math.round((window.innerWidth/2)-(w/2))+getScrollX();
			yc=Math.round((window.innerHeight/2)-(h/2))+getScrollY();
		} else {
			xc=Math.round((document.body.clientWidth/2)-(w/2))+getScrollX();
			yc=Math.round((document.body.clientHeight/2)-(h/2))+getScrollY();
		}
		// reposition div
		if(this.NN4) {
			myObj.moveTo(xc,yc)
		} else {
			myObj.left = xc + "px"
			myObj.top = yc + "px"
		}
	}
// END CENTER DIV ON PAGE STUFF

// port of php function
function strpos( haystack, needle, offset){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
    // *     returns 1: 14
 
    var i = haystack.indexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}

// port of php function
 function in_array(needle, haystack, strict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
 
    var found = false, key, strict = !!strict;
 
    for (key in haystack) {
        if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
            found = true;
            break;
        }
    }
 
    return found;
}

function validate_form(form_id){
	valmessage = '';
	masterform = $(form_id);
	for(ff=0; ff<masterform.elements.length; ff++)
	{
		currelem = masterform.elements[ff];
		switch(currelem.type)
		{
			case 'select' :
			case 'select-one' :
				tmp = validateTypes(currelem, currelem.options[currelem.selectedIndex].value);
				if(tmp)
				{
					valmessage = valmessage + tmp+"\n";
				}
			break;
			case 'text':
				tmp = validateTypes(currelem, currelem.value);
				if(tmp)
				{
					valmessage = valmessage + tmp+"\n";
				}
			break;
			case 'file':
				tmp = validateTypes(currelem, currelem.value);
				if(tmp)
				{
					valmessage = valmessage + tmp+"\n";
				}
			break;
			case 'hidden':
				tmp = validateTypes(currelem, currelem.value);
				if(tmp)
				{
					valmessage = valmessage + tmp+"\n";
				}
			break;
			case 'password':
				tmp = validateTypes(currelem, currelem.value);
				if(tmp)
				{
					valmessage = valmessage + tmp+"\n";
				}
			break;
			case 'textarea':
				tmp = validateTypes(currelem, currelem.value);
				if(tmp)
				{
					valmessage = valmessage + tmp+"\n";
				}
			break;
		}
		
	}
	if(valmessage!="")
	{	
		alert("Please complete the below fields\n\n"+valmessage);
		return false;
	} else {
		return true;
	}
}

function validateTypes(fieldObj, theValue)
{
	if (!fieldObj.attributes['validate']) {  return false; }
	if(fieldObj.attributes['validate'].value)
	{
		vTypes = fieldObj.attributes['validate'].value.split('|');
	} else {
		return false;
	}
	if(vTypes.length == 1)
	{
		return false;
	}
	errors=0;	
	
	for(vt=1; vt<vTypes.length; vt++)
	{
		realTypes = vTypes[vt].split(':');
		switch(realTypes[0])
		{
			case 'OPTIONAL':
				if(theValue == "")
				{ 
					return false;
				}
			break;
			case 'NUM':
				if(!theValue.match(/\b\d+\b/))
				{
					errors++;
				}
			break;
			case 'LENGTH':
				if(theValue.length != parseInt(realTypes[1]))
				{
					errors++;
				}
			break;
			case 'MAXLENGTH':
				if(theValue.length > parseInt(realTypes[1]))
				{
					errors++;
				}
			break;
			case 'MINLENGTH':
				if(theValue.length < parseInt(realTypes[1]))
				{
					errors++;
				}
			break;
			case 'SAMEAS':
				if(theValue != $(realTypes[1]).value)
				{
					errors++;
				}
			break;
			case 'GREATERTHAN': // must reference another elements by id after the :
				if(!(theValue > $(realTypes[1]).value))
				{
					errors++;
				}
			break;
			case 'FILEEXTENSION': // after : should contain a commadelimited list of extensions
				extensions = realTypes[1].split(',');
				extension = theValue.split(".").pop();
				if (!in_array(extension.toLowerCase(), extensions) && theValue != '')
				{
					errors++;
				}
			break;
			case 'EMAIL':
				if (!theValue.match(/\b[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}\b/i))
				{
					errors++;
				}
			break;
			case 'DATE': // checks if the value is in the form yyyy-mm-dd
				var validformat=/^\d{4}-\d{2}-\d{2}$/; //Basic check for format validity
				if (!validformat.test(theValue)) { errors++; break;}
				
				var monthfield=theValue.split("-")[1];
				var dayfield=theValue.split("-")[2];
				var yearfield=theValue.split("-")[0];
				var dayobj = new Date(yearfield, monthfield-1, dayfield);
				if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield)) { errors++; }

			break;
			case 'NOTEMPTY':
				if(theValue == "")
				{
					errors++;
				}
			break;
			case 'NOTEMPTYIFEMPTY': // this value may not be empty if all the other fields specified are empty
				var found_non_empty_field = false;
				for(var i = 1; i < realTypes.length; i++) // i = 1 cos we skip the first element because that is the operator
				{
					if ($(realTypes[i]).value.length)
					{
						found_non_empty_field = true;
					}
				}
				if (!found_non_empty_field && theValue == "")
				{
					errors++;
				}
			break;
			case 'POSITIVE':
				if(parseInt(theValue) < 0 || theValue == "")
				{
					errors++;
				}
			break;
			default:
				//alert( vTypes[vt] + 'not recognized');
			break;
		}
	}
	if(errors > 0)
	{
		return 	"- "+vTypes[0];
	}
}

function crud(action_name, class_name, id_object ,post_perameters, after_success)
{
  new Ajax.Request('../global_includes/scripts/crud.php?class='+class_name+'&action='+action_name+"&id="+id_object,
  {
		method: 'post',
		parameters: post_perameters,
    onSuccess: function(response){
			var perameter_array = new Array();
			if (after_success != "")
			{
				resp = response.responseText;
				resp_array = resp.split("|");
				resp_code = resp_array[0];
				resp_text = resp_array[1];
				if (resp_code > 0)
				{
					eval(after_success);
				} else {
					alert(resp);
				}
			} else {
				if (post_perameters.indexOf("&") > 0)
				{
					perameter_array = post_perameters.split("&");
				} else {
					perameter_array[0] = post_perameters;
				}
				for (var x = 0; x < perameter_array.size(); x++)
				{
					sub_array = perameter_array[x].split("=");
					if($(sub_array[0]))
					{
						$(sub_array[0]).value = sub_array[1];
						$(sub_array[0]).innerHTML = sub_array[1];
					} else if (id_object+"_"+$(sub_array[0])) {
						$(id_object+"_"+sub_array[0]).value = sub_array[1];
						$(id_object+"_"+sub_array[0]).innerHTML = sub_array[1];
					}
				}
			}
    },
		onFailure: function(response)
			{
				alert('Error in CRUD.'+response.responseCode);
			}	
  });
}
function crud_front(action_name, class_name, id_object ,post_perameters, after_success)
{
  new Ajax.Request('global_includes/scripts/crud.php?class='+class_name+'&action='+action_name+"&id="+id_object,
  {
		method: 'post',
		parameters: post_perameters,
    onSuccess: function(response){
			var perameter_array = new Array();
			if (after_success != "")
			{
				resp = response.responseText;
				resp_array = resp.split("|");
				resp_code = resp_array[0];
				resp_text = resp_array[1];
				if (resp_code > 0)
				{
					eval(after_success);
				} else {
					alert(resp);
				}
			} else {
				if (post_perameters.indexOf("&") > 0)
				{
					perameter_array = post_perameters.split("&");
				} else {
					perameter_array[0] = post_perameters;
				}
				for (var x = 0; x < perameter_array.size(); x++)
				{
					sub_array = perameter_array[x].split("=");
					if($(sub_array[0]))
					{
						$(sub_array[0]).value = sub_array[1];
						$(sub_array[0]).innerHTML = sub_array[1];
					} else if (id_object+"_"+$(sub_array[0])) {
						$(id_object+"_"+sub_array[0]).value = sub_array[1];
						$(id_object+"_"+sub_array[0]).innerHTML = sub_array[1];
					}
				}
			}
    },
		onFailure: function(response)
			{
				alert('Error in CRUD.'+response.responseCode);
			}	
  });
}


// fills the centre div with a page of content and makes it appear
function populate_div(url_string, parameters)
{
	new Ajax.Updater('centerDiv', url_string, {
		method: 'post',
		parameters: parameters,
		evalScripts: true,
		onFailure: function ()
		{
			alert('Error Encountered.');
		},
		onSuccess: function ()
		{
			rePos();
			$('centerDiv').style.display = "block";
		}
	}
	);
}
// hides the center div
function hide_center_div()
{
	$('centerDiv').style.display = "none";
}

// fills a element.innerHTML with a page
function _populate(element_id, url_string, parameters, after_success, after_failure)
{
	 new Ajax.Updater(element_id, url_string, {
		method: 'post',
		parameters: parameters,
		evalScripts: true,
		onFailure: function ()
			{
				alert("Error encountered.");
				eval(after_failure);
			},
		onSuccess: function ()
			{
				eval(after_success);
			}
		}
	);
}

// same as message_box - but for a second message box
function message_2(message_content)
{
	// if the message_box element exists we use it, if not we just alert the text
	if ($('message_box_2'))
	{
//		if (message_box_fade_timeout_id_2) { clearTimeout(message_box_fade_timeout_id_2); }
		$('message_box_2').morph("background:#FFF9D7 none repeat scroll 0%;border:1px solid #E2C822;");
		$('message_box_2').style.display = "none";
		$('message_box_2').innerHTML = message_content;
		setTimeout ( "Effect.Appear('message_box_2');", 500 );
		Effect.Appear('message_box_2');
//		message_box_fade_timeout_id_2 = setTimeout ( "$('message_box_2').morph('background:#F0F0FA none repeat scroll 0%;border:1px solid #CCCCCC;')", 3000 );
	} else {
		alert(message_content);
	}
}

function getScrollY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
//  return [ scrOfX, scrOfY ];
		return scrOfY;
}
function getScrollX() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
//  return [ scrOfX, scrOfY ];
		return scrOfX;
}

// makes an ajax request
function ajax_request(url, parameters, after_success)
{
	new Ajax.Request(url, {
		method: 'post',
		parameters: parameters,
		evalScripts: true,
		onSuccess: function (response)
			{
				// only if the response status is something must we do anything
				// if its 0 then no response was recieved - I hope this doesnt cause bugs!
				if (parseInt(response.status) > 0)
				{
					resp = response.responseText;
					resp_array = resp.split("|");
					resp_code = resp_array[0];
					resp_text = resp_array[1];
					if (!resp_code) { alert("ERROR: No Code in resp: "+resp); }
					if (resp_code > 0)
					{
						eval(after_success);
					} else {
						alert(resp);
					}
				}
			},
		onFailure: function()
			{
				alert('Ajax Request Failed.');
			}
		}
	);
	return true;
}

// makes an ajax updater request
function ajax_updater(url, parameters, update_element_id, after_success)
{
	new Ajax.Updater(update_element_id, url, {
		method: 'post',
		parameters: parameters,
		evalScripts: true,
		onSuccess: function (response)
			{
				eval(after_success);
			},
		onFailure: function()
			{
				alert('Ajax Updater Failed.');
			}
		}
	);
	return true;
}

// makes an ajax updater request
function ajax_periodical_updater(url, parameters, update_element_id, period, after_success)
{
	new Ajax.PeriodicalUpdater(update_element_id, url, {
		method: 'post',
		parameters: parameters,
		evalScripts: true,
		frequency: period,
		decay: 1,
		onSuccess: function (response)
			{
				eval(after_success);
			},
		onFailure: function()
			{
				alert('Ajax Updater Failed.');
			}
		}
	);
	return true;
}

// submits a form via ajax
function submit_form(form_id,success_action)
{
	if (!$(form_id)) { alert('Form: '+form_id+' does not exist'); return false; }
	// validate the form, if it fails dont go further
	if (!validate_form(form_id)) { return false; }

	// now that we know that the form submission is valid
	// we toggle the loading image on if it exists
	toggle_image_load('on');

	parameters = "";
	
	elements = $(form_id).elements
	for(var i = 0; i < elements.length; i++)
	{
		type = elements[i].type;
		name = elements[i].name;
		value = elements[i].value;
		if (type != "button")
		{
			if (parameters == "")
			{
				parameters = name+"="+value;
			} else {
				parameters = parameters + "&"+name+"="+value;
			}
		}
	}
	new Ajax.Request($(form_id).action, {
		method: 'post',
		parameters: parameters,
		onSuccess: function (response)
			{
				// we set up some response values - the full response, and the code and text part (if they exist)
				resp = response.responseText;
				resp_array = resp.split("|");
				resp_code = resp_array[0];
				resp_text = resp_array[1];
				if (!resp_text) { resp_text = "Error Encountered"; }

				// toggles the loading image off if it exists
				// we do this before evaluating the success_action in case the success action includes some image toggling (in which case this would interfere)
				toggle_image_load('off');
				
				eval(success_action);

			},
		onFailure: function()
			{
				alert('Form Submission Failed\nForm ID:'+$(form_id).id+'\nForm Action:'+$(form_id).action);
				// toggles the loading image off if it exists
				toggle_image_load('off');
			}
		}
	);
	return true;
}
// unhides an element that has display:none
function unhide(element_id)
{
	$(element_id).style.display="block";
}

// cancels the propagation of javascript events
// need to make this function properly cross browser
function stopPropagation(evt)
{
	if (window.event)
	{
		window.event.cancelBubble = true; // IE
	} else {
		evt.stopPropagation();
	}
}

// function called from an onkeypress - if the event was the ENTER key then the evalcode will be run
// to use this add the following to an input field in any form: onKeyPress="return on_enter('alert(resp)',event)"
function on_enter(evalcode,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13)
  {
  	eval(evalcode);
  	return false;
  } else {
  	return true;
	}
}
// sets the focus on first element in the first form on the page
// usually called from the body tag: onload="first_element_focus()"
function first_element_focus()
{
	if (document.forms[0] && document.forms[0].elements[0])
	{
		document.forms[0].elements[0].focus()
	}
	return true;
}
// slides an element up or down based on its style.display
function toggle_slide(element_id)
{
	if ($(element_id).style.display == "none")
	{
		Effect.SlideDown(element_id,{duration:0.3});
	} else {
		Effect.SlideUp(element_id,{duration:0.3});
	}
}
// flips an elements baground colour between the two parameters
function toggle_bg_color(element, colour1, colour2)
{
	current_bg_colour = element.style.backgroundColor;
	if (current_bg_colour.compareColor(colour1) || current_bg_colour == "")
	{
		element.style.backgroundColor = colour2;
	} else {
		element.style.backgroundColor = colour1;
	}
}

// flips an elements class between the two parameters
function toggle_class(element, class1, class2)
{
	current_class = element.className;
	if (current_class == class1 || current_class == "")
	{
		element.className = class2;
	} else {
		element.className = class1;
	}
}

// two new functions below can be applied to colours to compare them
// the first function makes use of the second function.  Currently this function is used
// by the toggle_bg_colour function to switch an element between two background colours
String.prototype.compareColor = function(){
    if((this.indexOf("#") != -1 && arguments[0].indexOf("#") != -1) || 
      (this.indexOf("rgb") != -1 && arguments[0].indexOf("rgb") != -1)){
      return this.toLowerCase() == arguments[0].toLowerCase()
    }
    else{
      xCol_1 = this;
      xCol_2 = arguments[0];
      if(xCol_1.indexOf("#") != -1)xCol_1 = xCol_1.toRGBcolor();
      if(xCol_2.indexOf("#") != -1)xCol_2 = xCol_2.toRGBcolor();
      return xCol_1.toLowerCase() == xCol_2.toLowerCase()
    }
  }


  String.prototype.toRGBcolor = function(){
    varR = parseInt(this.substring(1,3), 16);
    varG = parseInt(this.substring(3,5), 16);
    varB = parseInt(this.substring(5,7), 16);
    return "rgb(" + varR + ", " + varG + ", " +  varB + ")";
  }
  
 // function takes a number of seconds and returns a human readable time length.  EG: 1 Hour 15 Min 6 Sec
function seconds_to_human_time(num_seconds) {
	
	seconds = num_seconds%60;
	minutes = (num_seconds/60)%60;
	hours = Math.floor(num_seconds/3600);
	
	return_value = "";
	if (hours > 0)
	{
		if (hours == 1)
		{
			return_value = hours + " Hour ";
		} else {
			return_value = hours + " Hours ";
		}
	}
	if (minutes > 0)
	{
		if (minutes == 1)
		{
			return_value = return_value+ minutes + " Min ";
		} else {
			return_value = return_value + minutes + " Min ";
		}
		
	}
	if (seconds > 0)
	{
		if (seconds == 1)
		{
			return_value = return_value+ seconds + " Sec ";
		} else {
			return_value = return_value + seconds + " Sec ";
		}
		
	}
	return return_value;
}


 // Code Below assigns values to the viewport variables defined at the top of the page
 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 
 if (typeof window.innerWidth != 'undefined')
 {
      viewportwidth = window.innerWidth,
      viewportheight = window.innerHeight
 }
 
// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

 else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0)
 {
       viewportwidth = document.documentElement.clientWidth,
       viewportheight = document.documentElement.clientHeight
 }
 
 // older versions of IE
 
 else
 {
       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
       viewportheight = document.getElementsByTagName('body')[0].clientHeight
 }
 // END defining viewport variables
 
 // submits a form to an associated invisible iframe
function _submit_form(form_id)
{
	if (!$(form_id)) { alert('Form: '+form_id+' does not exist'); return false; }
	// validate the form, if it fails dont go further
	if (!validate_form(form_id)) { return false; }

	// now that we know that the form submission is valid
	// we toggle the loading image on if it exists
	toggle_image_load('on');
	$(form_id).submit();
}

function _form_response(resp, resp_function)
{
	resp_array = resp.split("|");
	resp_code = resp_array[0];
	resp_text = resp_array[1];

	// if the resp function has a ( in it then it is an actual function call so we just run it
	if (strpos(resp_function,"(") > 0)
	{
		eval(resp_function);
	} else if (!resp_text) {
		alert("Error: Form did not return a valid response.");
	} else {
	
		eval_text = resp_function+"('"+resp_code+"','"+resp_text+"');";
		eval(eval_text);
	}

}

// toggles the loading image display (if it exists)
// we also change the cursor to an hourglass
function toggle_image_load(_switch)
{
	if ($('image_load'))
	{
		if (_switch == "on")
		{
			
			$('body_tag').style.cursor = "wait";
			$('image_load').style.display = "table-cell";
		} else {
			$('body_tag').style.cursor = "";
			$('image_load').style.display = "none";
		}
	}
}
function implode( glue, pieces ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: _argos
    // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'Kevin van Zonneveld'
 
    return ( ( pieces instanceof Array ) ? pieces.join ( glue ) : pieces );
}

// generic callback function for submitted forms, it refreshes the page
function generic_add(resp_code, resp_text)
{
	if (resp_code > 0)
	{
		window.location.reload();
	} else {
		alert("Error with CRUD.");
	}
}

function is_array( mixed_var ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   bugfixed by: Cord
    // *     example 1: is_array(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: is_array('Kevin van Zonneveld');
    // *     returns 2: false
 
    return ( mixed_var instanceof Array );
}

 function str_replace(search, replace, subject) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // -    depends on: is_array
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'    
    
    var f = search, r = replace, s = subject;
    var ra = is_array(r), sa = is_array(s), f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;
 
    while (j = 0, i--) {
        while (s[i] = s[i].split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
    };
     
    return sa ? s : s[0];
}

// this function is called by the default autocompleter input field
 function autocompleter_response(autocomplete_field, list_element)
 {
	// only if the li has an id, else we ignore it when it is clicked
	if (list_element.attributes['id'])
	{
		autocomplete_field.value = list_element.innerHTML;
		id_field = str_replace('_autocompleter', '', autocomplete_field.attributes['id'].value);
		$(id_field).value = list_element.attributes['id'].value;		// Populating hidden tariff ID field
		return true;
	} else {
		autocomplete_field.value = ""; // clearing the input box, if the li had no id - likely it is No matches
	}

 }
 
 //php port
 function isset(  ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: FremyCompany
    // *     example 1: isset( undefined, true);
    // *     returns 1: false
    // *     example 2: isset( 'Kevin van Zonneveld' );
    // *     returns 2: true
 
    var a=arguments; var l=a.length; var i=0;
    
    while ( i!=l ) {
        if (typeof(a[i])=='undefined') { 
            return false; 
        } else { 
            i++; 
        }
    }
    
    return true;
}