/* JavaScript functions file
 * File to store the JavaScript functions
 * Author: T Coskey
 * Created: 2005/05/12
 */

// Detect Browser JavaScript version
var isIE = document.all?true:false;	// Detect is browser is Internet Explorer (true, false)


/*-------------------------------FUNCTION open_link --------------------------------------*/
// Function that redirects to another page bu using the URL variable
function open_link(url) {

	window.location.href = url;
}


/*-------------------------------FUNCTION only_numbers -----------------------------------*/
// Function that only allows numbers to be pressed
// Nothing will happen if any other keys are pressed
// If the key code is below 48 (for 0) and 57 for (for 9)
function only_numbers(evt) {

	evt = (evt) ? evt : event;
	var charCode = (evt.charCode) ? evt.charCode :
    	((evt.which) ? evt.which : evt.keyCode);

	if( charCode != 16 && (charCode > 48 && charCode < 58) || charCode == 8 || charCode == 9 || charCode == 12 || ( charCode > 32 && charCode < 41) || charCode == 43 || charCode == 45 || charCode == 190 || charCode == 48 || (charCode > 95 && charCode < 106)) {
		return; }
	else {
		return false; }
}
/*-------------------------------FUNCTION verifyNumeric ----------------------------------------*/
/*
 * A function that checks a field's content for non-alphanumeric characters
 * If a non-numeric character is found, a message is displayed, and the non-numeric character is cleared
 */
function verifyNumeric(txtField, message)
{
	 // regular expression to match alphanumeric characters only
  	var regExp = /^[\d]*$/;
  	var fieldVal = getById(txtField).value;

  	if(!regExp.test(fieldVal))
  	{
  	  // If a non-numeric character is found, simply remove that character
  	  regExp = /[\D]*/g;

  	  var newVal = fieldVal.replace(regExp,"");

  	  //alert(fieldVal + " " + newVal);
      getById(txtField).value = newVal;
	  alert("Error: "+message);
  	  getById(txtField).focus();
  	  return false;
  	}
  	else
  		return true;
}
/*-------------------------------FUNCTION verifyAlphaNumeric ----------------------------------------*/
/*
 * A function that checks a field's content for non-alphanumeric characters
 * If a non-alpha numeric character is found, a message is displayed, and the invalid characters in the field are cleared
 */
function verifyAlphaNumeric(txtField, message)
{
	 // regular expression to match alphanumeric characters only
  	var regExp = /^[\w]*$/;

  	fieldVal = getById(txtField).value;

  	if(!regExp.test(fieldVal))
  	{
   	  // Remove the non-alpha-numeric character that was found
   	   regExp = /[\W]*/g;

 	  var newVal = fieldVal.replace(regExp,"");
  	  getById(txtField).value = newVal;

	  alert("Error: "+message);
  	  getById(txtField).focus();
  	  return false;
  	}
  	else
  		return true;
}
/**------------------------------------ function verifyDate ------------------------------------------------------------------------------------------
//* Adapted from JavaScriptKit.com
* Checks date format as well as if the date is valid
* Allows a date value that uses the correct value, but where all values are 0 ie. 0000-00-00
*/
function verifyDate(input)
{
	var validformat = /^\d{4}-\d{2}-\d{2}$/; //Basic check for format validity

	var returnval = false;

	// Retrieve date from form
	inputDate  = getById(input).value;
	if (!validformat.test(inputDate))
	{
		alert("Invalid Date Format. Please correct and submit again.");
	}
	else
	{
		 //Detailed check for valid date ranges
		var yearfield= inputDate.split("-")[0];
		var monthfield= inputDate.split("-")[1];
		var dayfield= inputDate.split("-")[2];
		var dayobj = new Date(yearfield, monthfield-1, dayfield);

		// allow a 'zero' value to slip through
		if((yearfield == 0) && (monthfield == 0) && (dayfield == 0))
			returnval = true;
		else if ((dayobj.getMonth()+1!=monthfield)||(dayobj.getDate()!=dayfield)||(dayobj.getFullYear()!=yearfield))
			alert("Invalid Day, Month, or Year range detected. Please correct and submit again.");
		else
			returnval = true;
	}
	if (returnval == false)
		getById(input).select();
	return returnval
}
/*
 * Checks time format as well as if the time is valid
 * Allows a time value that uses the correct value, but where all values are 0 ie. 00:00:00
 */

function verifyTime(input)
{
	var validformat = /^\d{2}:\d{2}:\d{2}$/; //Basic check for format validity

	var returnval = false;

	// Retrieve date from form
	inputTime  = getById(input).value;
	if (!validformat.test(inputTime))
	{
		alert("Invalid Time Format. Please use the format 'hh:mm:ss' and submit again.");
	}
	else
	{
		 //Detailed check for valid time ranges
		var hr = inputTime.split(":")[0];
		var min = inputTime.split(":")[1];
		var sec = inputTime.split(":")[2];

		// allow a 'zero' value to slip through
		if((hr == 0) && (min == 0) && (sec == 0))
			returnval = true;
		else if ((hr > 23)||(min > 59)||(sec > 59))
			alert("Invalid hour, minute, or second detected. Please correct and submit again.");
		else
			returnval = true;
	}
	if (returnval == false)
		getById(input).select();
	return returnval
}
/*-------------------------------FUNCTION getById ----------------------------------------*/
// Used to process form document.getElementById elements
// Modified 30 July 2008 Added a line to make this function browser independant
function getById(id) {

	return (document.getElementById(id));
//	return (document.getElementById(id) ? document.getElementById(id) : document.all[id]);
}
function getValById(id) {

	return (document.getElementById(id).value);
}
/*-------------------------------FUNCTION update_textfield_text ----------------------------------------*/
// Special function to update the text in a text field for a sub project and
//   not the value
function update_textfield_text(txtform, txttextfield, txthiddentextfield,txtdropdown) {
	with(document.forms[txtform]) {
		var myindex = getById(txtdropdown).selectedIndex;
		var selected_item =getById(txtdropdown).options[myindex].text;
		getById(txttextfield).value = selected_item;	// Assign the displayable text box
		getById(txthiddentextfield).value = getById(txtdropdown).value; // Assign the hidden text box
	}
}

/*-------------------------------FUNCTION update_textfield_text ----------------------------------------*/
// Special function to update the text in a text field for a sub project and
//   not the value
function update_textfield_text_old(txtform, txttextfield, txtdropdown) {
	with(document.forms[txtform]) {
		var myindex = getById(txtdropdown).selectedIndex;
		var selected_item =getById(txtdropdown).options[myindex].text;
		getById(txttextfield).value = selected_item;
	}
}


/*-------------------------------FUNCTION test -----------------------------------------*/
// Test function to test if the pages can read this function
function test(id) {
	alert(id);
}

function displayMsgBog(txt)
{
	alert(txt);
}

/*-------------------------------FUNCTION update_textfield ----------------------------------------*/
// Function to append the value from a drop down list into a textbox field when the user selects an option
// from the drop down list
function update_textfield(txtform, txttextfield, txtdropdown) {
	with(document.forms[txtform]) {
		var text = getById(txtdropdown).value;
		getById(txttextfield).value = text;
	}
}
/*-------------------------------FUNCTION update_textfield ----------------------------------------*/
// Function to append the 'property' property of the selected option in a drop down list into a textbox field when the user selects an option
// from the drop down list
// Note - Differs from update_textfield which uses the 'value' property of an option
// This function is more generic
// Author Naseera Ally
// Date 10 July 2008
function update_textfield_display(txtform, txttextfield, txtdropdown,property) {
	with(document.forms[txtform]) {
		var ix = getById(txtdropdown).selectedIndex;
		var text = "";

		switch(property)
			{
				case "name":
					text = getById(txtdropdown).options[ix].name;
				break;
				case "value":
							text = getById(txtdropdown).options[ix].value;
				break;
				case "innerHTML":
					text = getById(txtdropdown).options[ix].innerHTML;
				break;
				default:
					text = getById(txtdropdown).options[ix].value;
				break;
			}

		getById(txttextfield).value = text;
	}
}
/*-------------------------------FUNCTION update_textfield_forms ----------------------------------------*/
// Function to append the value from a drop down list into a textbox field when the user selects an option
// from the drop down list .. when text box and drop-down are on different forms
// Adapted original method above - Naseera Ally
// 10 April 2008
function update_textfield_forms(txtform, txttextfield, txtform2, txtdropdown) {
	with(document.forms[txtform])
		var text = getById(txtdropdown).value;
	with(document.forms[txtform2])
		getById(txttextfield).value = text;


}


/*-------------------------------FUNCTION type_search---------------------------------*/
// Update all the text fields if the user types a partial name
// Fixed bugs - Naseera Ally
// changed variable name from "name" tp optionName (name is a reserved word)
// Access "value" property of option[i] instead of "name" property - which was not working
function type_search(txtform, txttextfield, txtdropdown) {
	with(document.forms[txtform]) {

		/* Declare variables */
		var i = 0;
		var text = "";
		var best_match = "";
		var linker = 0;
		var optionName = "";

		/* Get the value of the text field in which the user is typing in */
		/* and store it in a variable */
		text = getById(txttextfield).value;
		text = text.toUpperCase();

		/* Loop through the drop down lists to find the best match */
		for (i = 0; i < getById(txtdropdown).options.length; i++)  {
			optionName = getById(txtdropdown).options[i].value;
			optionName = optionName.substring(0, text.length);
			optionName = optionName.toUpperCase();

			/* Store the items in the drop down list in variables */
			if(optionName.match(text)) {
				best_match = text;
				linker = i;
			 	//if (typeof((optionName.match(text)) == 'object')) alert('yes');
 			}
 		}

		/*  Change the drop down list values to match the best match value */
		if(best_match) {
			getById(txtdropdown).value = getById(txtdropdown).options[linker].value;

			// Invoke event handler for txtdropdown's onchange event
			getById(txtdropdown).onchange();
			// limit options on drop-down list according to text in textbox
			// TODO
			return getById(txtdropdown).options[linker].id;
		}
	}
}
/*-------------------------------FUNCTION type_search_display---------------------------------*/
// Update all the text fields if the user types a partial name
// Differs from type_search() which searches the 'value' property of an option
// This function accepts an extra parameter which specifies which propery of an option to use
// defaults to values

function type_search_display(txtform, txttextfield, txtdropdown,property) {

	if (property != "name" && property != "value" && property != "innerHTML")
		property = "value";

	with(document.forms[txtform]) {

		/* Declare variables */
		var i = 0;
		var text = "";
		var best_match = "";
		var linker = 0;
		var optionName = "";

		/* Get the value of the text field in which the user is typing in */
		/* and store it in a variable */
		text = getById(txttextfield).value;
		text = text.toUpperCase();

		/* Loop through the drop down lists to find the best match */
		for (i = 0; i < getById(txtdropdown).options.length; i++)  {

			switch(property)
			{
				case "name":
					optionName = getById(txtdropdown).options[i].name;
				break;
				case "value":
					optionName = getById(txtdropdown).options[i].value;
				break;
				case "innerHTML":
					optionName = getById(txtdropdown).options[i].innerHTML;
				break;
			}

			optionName = optionName.substring(0, text.length);
			optionName = optionName.toUpperCase();

			/* Store the items in the drop down list in variables */
			if(optionName.match(text)) {
				best_match = text;
				linker = i;
			 	//if (typeof((optionName.match(text)) == 'object')) alert('yes');
 			}
 		}

		/*  Change the drop down list values to match the best match value */
		if(best_match) {

			getById(txtdropdown).value = getById(txtdropdown).options[linker].value;
			// Invoke event handler for txtdropdown's onchange event
			getById(txtdropdown).onchange();
			// limit options on drop-down list according to text in textbox
			// TODO
			return getById(txtdropdown).options[linker].id;
		}
	}
}
function replaceCharsFromElement(element,findStr,replaceStr)
{
	(element.value.replace(findStr,replaceStr));

}
/*-------------------------------FUNCTION showSite -----------------------------------------
 * Author Naseera Ally
 * @param target string
           The name of the element to whose 'value' property the ouput text will be assigned
*/
function showSiteTextBox(txtform, txttextfield, txtdropdown,siteUrl,target){
	var id = type_search(txtform, txttextfield, txtdropdown);

	if (typeof(id) == 'undefined')
		id = "";
	getById(target).value = id;

	// set url using id of selected element
	setUrlFromDropDown(txtdropdown,siteUrl);
}

/*
 * A function that sets the value of a given target element to the id property
 * of the selected item of a givem dropdown menu
*/
function showSiteDropDown(txtdropdown,target){
	// find selected  option id
	var index = getById(txtdropdown).selectedIndex;

	// retrieve id from selected option
	var id = getById(txtdropdown).options[index].id;

	if (typeof(id) == 'undefined')
		id = "";
	getById(target).value = id;
	// Update the anchor tag with the id of the selected element
	if (getById('updateUrl') == true)
		getById('updateUrl').href = getById('updateUrl').href + id;
}

/**
  * This function is called when a drop down menu item is selected
  * Its associated text box will be set to the same value (not anymore
  *       as typing in this box becomes difficult, as typing here caues the dropdown to be updated,
  *		  which will cause the textbox to be updated,hence typing becomes difficult)

  * The other 2 dropdown menus parameters are updated to select the same option corresponding to the "id" of selected option,
  * and their associated textboxes are updated in the same manner
  * All drop=down menus (txtDropDown, as well as the target dropDowns) must have same number of elements
  * This function is useful when 2 arrays correspond to each other are then individually sorted, and assigned to a select element.
  * IMPORTANT: "id" property of each option must correspond to the ix in the original array
  */
  function updateTxtDropDown(txtdropdown,targettxt,targetdropdown1,targettxt1,targetdropdown2,targettxt2){
  	// find selected  option id
	var index = getById(txtdropdown).selectedIndex;

	var selectedId = getById(txtdropdown).options[index].id;

	// Find which index in each in each dropDown has id=selectedId

	var index1 = -1,
		index2 = -1;
	for (i = 0; i < getById(txtdropdown).options.length; i++)  {
		option1Id = getById(targetdropdown1).options[i].id;
		option2Id = getById(targetdropdown2).options[i].id;

		if(option1Id == selectedId) {
			index1 = i;
		}
		if(option2Id == selectedId) {
			index2 = i;
		}
			// terminate loop, as soon as both matching indices have been found
			if (index1 > -1 && index2 > -1)
				break;
	}

	// 1. update the targetdropdowns to select the approp index that corresponds to the id of the selected index of the first drop down
    // 2. update each textbox to display the text of the selected option
	// update only if a selection was made
	if (index1 > -1){
		getById(targetdropdown1).selectedIndex = index1;
		getById(targettxt1).value = getById(targetdropdown1).options[index1].value;
	}
	else
		getById(targettxt1).value = null;

	if (index2 > -1){
		getById(targetdropdown2).selectedIndex = index2;
		getById(targettxt2).value = getById(targetdropdown2).options[index2].value;
	}
	else
		getById(targettxt2).value = null;

	// Don't update the textbox belonging to the select box that was changed, circular effect - difficult to type further in txtbox thereafter,
	// if it is updated each type a character is typed
	//	getById(targettxt).value = getById(txtdropdown).options[index].value;

	// Rather, grey it out, as text in here may not be correct
	getById(targettxt1).style.color="black";
	getById(targettxt2).style.color="black";
	getById(targettxt).style.color="grey";
  }
  /**
   * This function updates a text box each time it is called. (typically, its called when a drop-down changes)
   * It simply populates the textbox with an element of the array that is passed in.
   * The ix of the array element that is used, is simply the 'id' field of the selectedindex item of the drop-down
   *
   */
  function updatetxtFromArray(dropdown,txtArr,txtbox)
  {
	// find selected  index
	var index = getById(dropdown).selectedIndex;
	// find id of the selected element
	var selectedId = getById(dropdown).options[index].id;

	// assign array element to textbox
	getById(txtbox).value = txtArr[selectedId];
  }
  /*-------------------------------FUNCTION updateHiddenTxtFromDropDown -----------------------------------------
  /**
  * Update a hidden element with the text value of the selected item of a drop-down menu
  * This function is called when a drop down menu item is selected
  */
  function updateHiddenTxtFromDropDown(txtdropdown,targettxt){

  	// find selected  index
	var index = getById(txtdropdown).selectedIndex;
	// find value of the selected drop-down item
	var val = getById(txtdropdown).options[index].innerHTML;
	// assign this value to the hidden lement
	getById(targettxt).value = val;
	//alert(targettxt+" " + getById(targettxt).value);
  }

/*-------------------------------FUNCTION setUrlFromDropDown -----------------------------------------
 * Author Naseera Ally
 * set url using id of selected element
*/
function setUrlFromDropDown(txtdropdown,siteUrl){
	// find selected  option id
	var index = getById(txtdropdown).selectedIndex;

	// ! do this only during debug
	siteUrl = "?id=";

	// asssign to url variable
	siteUrl =  siteUrl + getById(txtdropdown).options[index].id;
	//location.href = siteUrl;
}
/*-------------------------------FUNCTION filter_search -----------------------------------------*/
// Function to filter elements from a drop down search
// This function uses the name, value and text elements
// Name contains the service, Value contains the status ID, Text contains the drop down text
function filter_search(theform, mainlist, filterlist) {

	with(document.forms[theform]) {

	  	/* Original Author: Justin Whitford
  	   Source Adapted from : www.evolt.org */

		/* Retrieve the current item in the list */
		var myindex =getById(mainlist).selectedIndex;
		var selected_item = getById(mainlist).options[myindex].value;

		/* Create an array with the current elements */
		if(!getById(filterlist).bak) {
			getById(filterlist).bak = new Array();
		    for (n = 0; n < getById(filterlist).length; n++) {
		    	getById(filterlist).bak[getById(filterlist).bak.length] = new Array(getById(filterlist)[n].name, getById(filterlist)[n].value, getById(filterlist).options[n].text); }
	    }

	    /* Create a new list */
	  	match = new Array();
	  	for (n = 0; n < getById(filterlist).bak.length; n++){
	    	if(getById(filterlist).bak[n][0].toLowerCase().indexOf(selected_item.toLowerCase())!=-1){
	      		match[match.length] = new Array(getById(filterlist).bak[n][0],getById(filterlist).bak[n][1], getById(filterlist).bak[n][2]); }
	   	}

		/* Re-write the drop down list */
		for (n = 0; n < match.length; n++){
			getById(filterlist)[n].name = match[n][0];
		    getByIdd(filterlist)[n].value = match[n][1];
		    getById(filterlist)[n].text = match[n][2]; }

	    /* Ensure the first matched item is selected */
	    // LOOK AT this is the problem below for some reason
	    getById(filterlist).length=match.length
	    getById(filterlist).selectedIndex=0;

	      /* Set the statusid textbox */
	    getById("statusid").value = getById(filterlist).value
	}
}


/*-------------------------------FUNCTION isblank -----------------------------------------*/
// A utility function that returns true if a string contains only whitespace characters.
function isblank(s) {
    for(var i = 0; i < s.length; i++) {
        var c = s.charAt(i);
        if ((c != ' ') && (c != '\n') && (c != '\t')) return false;
    }
    return true;
}

/*-------------------------------FUNCTION verifyFields -----------------------------------------*/
// This is the function that performs form verification. It is invoked
// from the onsubmit event handler. The handler should return whatever
// value this function returns.
// Same as function verify() except that this function accepts 2 additional parameters
// The additional parameters are 3 form elements which are both not compulsory,
// but at least one of them needs to have a value
// TODO: Make this more generic: substitute 2 form element parameters with an array of form elements
function verifyFields(f,reqdElt1,reqdElt2) {
    var msg;
    var empty_fields = "",
    	optional_required = ""; // msg for fields where at least one of which must have a value

    var errors = "";
    var count = 0;

    // Loop through the elements of the form, looking for all
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // verify that they are numbers and in the right range.
    // If the element has a "numeric" property defined, verify that
    // it is a number, but don't check its range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];

        if (((e.type == "text") || (e.type == "textarea") || (e.type == "password")) && !e.optional) {
            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
             	if (e == reqdElt1 || e == reqdElt2|| e == reqdElt3)
             		count++;
             	else{
		                empty_fields += "\n          " + e.name;
		                // Highlight the empty field box yellow
		                if(!isIE) e.setAttribute("style","background-color:red;") // For Mozilla
		                if (isIE) e.style.backgroundColor="red"; // For IE
	               }
	                continue;
            }

	        // Now check for fields that are supposed to be numeric.
	        if (e.numeric || (e.min != null) || (e.max != null)) {
	            var v = parseFloat(e.value);
	            if (isNaN(v) ||
	                ((e.min != null) && (v < e.min)) ||
	                ((e.max != null) && (v > e.max))) {
	                errors += "- The field " + e.name + " must be a number";
	                if (e.min != null)
	                    errors += " that is greater than " + e.min;
	                if (e.max != null && e.min != null)
	                    errors += " and less than " + e.max;
	                else if (e.max != null)
	                    errors += " that is less than " + e.max;
	                errors += ".\n";
	            }
	         }

	       // Now check if the field is an email address
	        if(e.name == "email") {
	        	if(!checkMail(e.value)) { errors += "\nPlease enter in a valid email address! "; }
	   		}
		}
    }

    // Now check how many of the at-least-one-required fields were empty
    if (count > 1){
	    optional_required += "\n          " + reqdElt1.name + "\n          " + reqdElt2.name + "\n          " + reqdElt3.name;
         // Highlight the empty field box yellow
         if(!isIE) reqdElt1.setAttribute("style","background-color:red;") // For Mozilla
         if(!isIE) reqdElt2.setAttribute("style","background-color:red;")
         if(!isIE) reqdElt3.setAttribute("style","background-color:red;")
         if (isIE) reqdElt1.style.backgroundColor="red"; // For IE
         if (isIE) reqdElt2.style.backgroundColor="red";
         if (isIE) reqdElt3.style.backgroundColor="red";
    }

    // Now, if there were any errors, display the messages, and
    // return false to prevent the form from being submitted.
    // Otherwise return true.
    if (!empty_fields && !errors && !optional_required) return true;

    msg  = "______________________________________________________\n\n"
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "______________________________________________________\n\n"

	if (optional_required)
        msg += "- Enter a value for at least one of:"
                + optional_required + "\n";


    if (empty_fields) {
        msg += "- The following required field(s) are empty:"
                + empty_fields + "\n";
        if (errors) { msg += "\n"; }
    }
    msg += errors;
    alert(msg);
    return false;
}

/*-------------------------------FUNCTION verify -----------------------------------------*/
// This is the function that performs form verification. It is invoked
// from the onsubmit event handler. The handler should return whatever
// value this function returns.
function verify(f) {
    var msg;
    var empty_fields = "";
    var errors = "";

    // Loop through the elements of the form, looking for all
    // text and textarea elements that don't have an "optional" property
    // defined. Then, check for fields that are empty and make a list of them.
    // Also, if any of these elements have a "min" or a "max" property defined,
    // verify that they are numbers and in the right range.
    // If the element has a "numeric" property defined, verify that
    // it is a number, but don't check its range.
    // Put together error messages for fields that are wrong.
    for(var i = 0; i < f.length; i++) {
        var e = f.elements[i];
        if (((e.type == "text") || (e.type == "textarea") || (e.type == "password")) && !e.optional) {
            // first check if the field is empty
            if ((e.value == null) || (e.value == "") || isblank(e.value)) {
                empty_fields += "\n          " + e.name;
                // Highlight the empty field box yellow
                if(!isIE) e.setAttribute("style","background-color:red;") // For Mozilla
                if (isIE) e.style.backgroundColor="red"; // For IE
                continue;
            }

            // Now check for fields that are supposed to be numeric.
            if (e.numeric || (e.min != null) || (e.max != null)) {
                var v = parseFloat(e.value);
                if (isNaN(v) ||
                    ((e.min != null) && (v < e.min)) ||
                    ((e.max != null) && (v > e.max))) {
                    errors += "- The field " + e.name + " must be a number";
                    if (e.min != null)
                        errors += " that is greater than " + e.min;
                    if (e.max != null && e.min != null)
                        errors += " and less than " + e.max;
                    else if (e.max != null)
                        errors += " that is less than " + e.max;
                    errors += ".\n";
                }
             }

           // Now check if the field is an email address
            if(e.name == "email") {
            	if(!checkMail(e.value)) { errors += "\nPlease enter in a valid email address! "; }
       		}

          }
      }

    // Now, if there were any errors, display the messages, and
    // return false to prevent the form from being submitted.
    // Otherwise return true.
    if (!empty_fields && !errors) return true;

    msg  = "______________________________________________________\n\n"
    msg += "The form was not submitted because of the following error(s).\n";
    msg += "Please correct these error(s) and re-submit.\n";
    msg += "______________________________________________________\n\n"

    if (empty_fields) {
        msg += "- The following required field(s) are empty:"
                + empty_fields + "\n";
        if (errors) { msg += "\n"; }
    }
    msg += errors;
    alert(msg);
    return false;
}
/*-------------------------------FUNCTION confirmChangeValueElement -----------------------------------------*/
/**
 * confirmChangeValueElement
 * A function that is typically an event-handler that is invoked when a form element loses focus, or changes its value
 * The values of the 2 elements passed in as parameters are compared.
 * If the values differ, a confirmation is displayed.
 * If the change is confirmed no action is taked, and the element retains the new value
 * If the confirmation is negative, the form element is re-assigned the old value
 *
 * Usage: Typically, the "old" value is stored in a hidden element on the form, to be passed in and its value compared for a change
 *
 */
function confirmChangeValueElement(oldValElement,newValElement,msg)
{
	if (getById(oldValElement).value != getById(newValElement).value)
	{
		var response = confirm(msg);

		if(response)
		{
			//alert('Changing value of old element to ->'+ getById(newValElement).value);
			getById(oldValElement).value = getById(newValElement).value;
		}
		else
		{
			// If the user cancel the action, change the element's value back to the old value
			//alert('Changing new element value to ->'+ getById(oldValElement).value);
			getById(newValElement).value = getById(oldValElement).value;
		}
	};
}
/*-------------------------------FUNCTION validateConfirmSubmit -----------------------------------------*/
/**
 * validateConfirmSubmit()
 *
 * Validates a form's elements, and prompts for a confirmation before submitting the form
 * If the form contains invalid data, then this function returns false
 *
 * Form is validated with a function call to verify(f)
 *
 * Example of how to call this function from a php  form:
 * onsubmit = "return validateConfirmSubmit(this,formName,elementName,confirmStr)"
 */
function validateConfirmSubmit(f,formName, actionElement,confirmMsg)
{
 	if(verify(f))
 		return confirmSubmitForm(formName, actionElement,confirmMsg);
 	else
 		return false;
}
/*-------------------------------FUNCTION checkPasswords -----------------------------------------*/
/*
 * function checkPasswords
 *
 * A function that compares 2 password strings and checks for the ff:-
 *	1) Passwords must match
 *	2) Password must have > minLen characters
 *	3) Password must have < maxLen characters
 *
 * Returns true if passwords match, and satisfy above criteria, otherwise
 * return false
 *
 */
function checkPasswords(pwd,confirmPwd,minLen,maxLen)
{
	var pwd1 = "";
	var pwd2 = "";

	pwd1 = getById(pwd).value;
	pwd2 = getById(confirmPwd).value;

	// 1) Check if passwords match
	if (!pwd1.match(pwd2))// && !pwd.match("")
	{
		alert('Warning: Passwords do not match! Please re-enter passwords carefully');
		getById(pwd).value = "";
		getById(confirmPwd).value = "";

		return false;
	}

	// Check password length
	if (pwd1.length > 0 && (pwd1.length < minLen || pwd1.length > maxLen))
	{
		alert('Warning: Please ensure password is between 6-8 characters, and re-enter');
		getById(pwd).value = "";
		getById(confirmPwd).value = "";
		return false;
	}

	return true;
}
/*-------------------------------FUNCTION groupChars -----------------------------------------*/
/*
 * @param txtBox
 * @param len numeric - number of digits to group output by
 *
 * A function that adds a space between groups of characters in a textbox
 */
function groupChars(txtBox,len)
{
	// Get contents of edit box
	var data = getById(txtBox).value;
	var numChars = data.length;

	// If there are only enough characters for 1 group, then no action is required
	if(numChars <= len)
		return;

	var newStr = "";
	var count = 0;
	var joinStr = "";
	for(var i =0;i < numChars;i++)
	{
		if (data[i] != " ")
		{
			// reset group counter
			if(count == len)
			{
				count = 0;
				joinStr = " ";
			}
			newStr = newStr + joinStr + data[i];
			count ++;
			joinStr = "";
		}
	}

	// Replace text of textbox with new, formatted string
	getById(txtBox).value = newStr;
}
function ungroupChars(txtBox)
{
	// Get contents of edit box
	var data = getById(txtBox).value;
	var numChars = data.length;

	var newStr = "";
	var count = 0;
	var joinStr = "";
	for(var i =0;i < numChars;i++)
	{
		if (data[i] != " ")
		{
			newStr = newStr + data[i];
		}
	}

	// Replace text of textbox with new, formatted string
	getById(txtBox).value = newStr;
}
/*-------------------------------FUNCTION remove_formatting -----------------------------------------*/
// Function to remove the formatting (background colours) on a text field
// This function is used when the user has not completed some fields and they reclick or tab on the field
// to complete the field
function remove_formatting(evt) {
		if (document.all) {
			source = evt.srcElement;
		}
		else {
			source = evt.target;
		}
		if(source.type == "text" || source.type == "textarea" || source.type == "password") {
			if(!isIE) source.setAttribute("style","background-color:white;"); // For Mozilla
			if (isIE) source.style.backgroundColor="white"; 		// For IE
		}
}


/*-------------------------------FUNCTION checkMail -----------------------------------------*/
// Function to check if the email address supplied is valid
function checkMail(email_address)
{
	var x = email_address;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(x)) { return true; }
	else { return false; }
}

/*-------------------------------FUNCTION verifyEmailField -----------------------------------------*/
// Function to check if the email address supplied is valid
function verifyEmailField(emailField)
{
	var emailAddress = getById(emailField).value;
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

	//alert('Email ' + emailAddress);

	// Allow a blank value  or a valid email address
	if (emailAddress == "" || filter.test(emailAddress))
	{
		 return true;
	}
	else
	{
		// Clear field and display appropriate error message
		getById(emailField).value = "";
		alert('This email address is not valid');
		getById(emailField).focus();
		return false;
	}
}

/*-------------------------------FUNCTION populate_postal_address -----------------------------------------*/
// Function to populate the postal address field and copy the details from the residential fields
// if the user selects the checkbox that indicates 'Postal same as residential?'
function populate_postal_address(txtForm) {
	with(document.forms[txtForm]) {
		if(chkSameAddress.checked) {
			postal.value = physical.value;
			postal2.value = physical2.value;
			zipPostalCode.value = zipCode.value;
			// For Mozilla
			if (!isIE) postal.setAttribute("style","background-color:white;");
			if (!isIE) postal2.setAttribute("style","background-color:white;");
			if (!isIE) zipPostalCode.setAttribute("style","background-color:white;");
			// If browser is IE
			if (isIE) postal.style.backgroundColor="white";
			if (isIE) postal2.style.backgroundColor="white";
			if (isIE) zipPostalCode.style.backgroundColor="white";

		}
		else {
			postal.value = "";
			postal2.value = "";
			zipPostalCode.value = "";
		}
	}
}


/*-------------------------------FUNCTION change_field -----------------------------------------*/
// Function to submit a form from an event on the web page
function submitForm(txtform)
{
	document.forms[txtform].submit();
}
/*-------------------------------FUNCTION exportToExcel -----------------------------------------*/
/**
 * This function does not work in mozilla. TODO - revisist and modify
*/

function _exportToExcel(table,saveLocation)
{
	alert('In exportToExcel()');
	var oExcel = new ActiveXObject("Excel.Application");
	var oBook = oExcel.Workbooks.Add;
	var oSheet = oBook.Worksheets(1);
	var numRows = getById(table).rows.length;
	var rowLen; // variable used in nested for-loop

	for (var y=0;y < numRows; y++)
	{
		// detailsTable is the table where the content to be exported is
		rowLen = detailsTable.rows[y].cells.length;
	    for (var x=0; x < rowLen;x++)
	    {
	        oSheet.Cells(y+1,x+1) =
			detailsTable.rows[y].cells[x].innerText;
	    }
	}
	oExcel.Visible = true;
	oExcel.UserControl = true;
	// try saving worksheet or otherwise excelsheet
	oExcel.SaveAs(saveLocation);
	// Quit the application
	oExcel.Quit();
}
function exportToExcel(table,saveLocation)
{
	var dataArr =[];
	var numRows = getById(table).rows.length;
	var rowLen; // variable used in nested for-loop

	for (var y=0;y < numRows; y++)
	{
		// detailsTable is the table where the content to be exported is
		rowLen = getById(table).rows[y].cells.length;
	    for (var x=0; x < rowLen;x++)
	    {
	       dataArr[y] = dataArr[y] + ',' + getById(table).rows[y].cells[x].innerHTML;
	    }
	}
	//alert(dataArr);

	return dataArr;
}

/*-------------------------------FUNCTION exportToExcel -----------------------------------------*/

/*-------------------------------FUNCTION extractId_submit -----------------------------------------*/
// This function will extract the ID from the FIRST column of the table
// And then submit the form. If the action is to delete an item then
// a confirmation box will be displayed for the user to confirm.
// myElement is the row element itself
// txtbox is the id string of a typically hidden element, whose value will be set acording to the value of the
// 2ND column in the table. This value will be posted to the form
function extractId_submit(txtform, txtbox, myElement, mytable)
{
//"selectEventSession","tranIdHigh",row,"SelectEventSession"
	var myAction = ""
	// Extract the users action from the action textbox on the form
	if( getById("Action") ) { myAction = getById("Action").value; }

	// Extract the ID from the row selected
	var thisrow = myElement.rowIndex + 1;
	var mycell = getById(mytable).rows[thisrow-1].cells;
	with(document.forms[txtform]) {
		getById(txtbox).value = mycell[1].innerHTML;
		// If the action is delete then display a confirmation dialogue box
		// Only submit the form is the user clicks on okay
		if( myAction.match("delete") ) {
			 if( confirm("Are you sure you want to delete this item?") ) { submitForm(txtform); }
		}
		else {submitForm(txtform);}
	}
}

function extractId_submitPopup(txtform, txtbox, myElement, mytable,url,paramList)
{
//"selectEventSession","tranIdHigh",row,"SelectEventSession"
	var myAction = ""
	// Extract the users action from the action textbox on the form
	if( getById("Action") ) { myAction = getById("Action").value; }

	// Extract the ID from the row selected
	var thisrow = myElement.rowIndex + 1;
	var mycell = getById(mytable).rows[thisrow-1].cells;
	with(document.forms[txtform]) {
		getById(txtbox).value = mycell[1].innerHTML;
		// If the action is delete then display a confirmation dialogue box
		// Only submit the form is the user clicks on okay
		if( myAction.match("delete") ) {
			 if( confirm("Are you sure you want to delete this item?") ) { popUp(url,paramList); }
		}
		else {popUp(url,paramList);}
	}
}


/*-------------------------------FUNCTION update_textfield_disp ----------------------------------------*/

function update_textfield_disp(txtform, txttextfield, txtdropdown,txtdisplay) {
/* Used to process form document.getElementById elements */
	with(document.forms[txtform]) {
		var text = getById(txtdropdown).value;
		var myindex = getById(txtdropdown).selectedIndex;
		getById(txttextfield).value = text;
		getById(txtdisplay).value = getById(txtdropdown).options[myindex].text;
	}
}

/*-------------------------------FUNCTION highlight_row -----------------------------------------*/
// Function to highlight a table row
function highlight_row(myElement)
{
  saved = new Object();
  saved.element = myElement;
  saved.className = myElement.className;
  saved.backgroundColor = myElement.style["backgroundColor"];
  myElement.style["backgroundColor"] = "lightsteelblue"
  myElement.style["cursor"] = "pointer";
}

/*-------------------------------FUNCTION unhighlight_row -----------------------------------------*/
// Function to dehighlight a table row
function unhighlight_row(myElement)
{
  myElement.style["backgroundColor"] = saved.backgroundColor;
  myElement.style["cursor"] = "default";
}

/*-------------------------------FUNCTION change_priority -----------------------------------------*/
// Function to change a unit priority
function change_priority(txtform, txtdropdown) {
	with(document.forms[txtform]) {
		var myindex = getById(txtdropdown).selectedIndex;
		var selected_item =getById(txtdropdown).options[myindex].text;
		alert(selected_item);
	}
}

/*-------------------------------FUNCTION focus_textbox ----------------------------------------*/
// Function to put the focus on a specific html form text box
function focus_textbox(txtform, txttextfield) {
	with(document.forms[txtform]) {
		getById(txttextfield).focus();
	}
}

/*-------------------------------FUNCTION clear_textbox ----------------------------------------*/
// Function to put the focus on a specific html form text box
function reset_web_user_customer(txtform, txtdisptextfield, txthiddentextfield) {
	with(document.forms[txtform]) {
		getById(txtdisptextfield).value = "";
		getById(txthiddentextfield).value = "";
	}
}

/*-------------------------------FUNCTION list_sitesearch---------------------------------*/

function list_sitesearch(txtForm, txtElement, product) {
/* Display the site information if the user uses the drop down list */

with(document.forms[txtForm]) {

	/* Variable declarations */
	var txtItem = 0;

	/* Get the element number of the site in the drop down list and store it in a variable */
	var txtItem = getById("selectsite"+txtElement).selectedIndex;
	/* Change the drop down lists with the new sites details */
	selectsitename.value = selectsitename.options[txtItem].value;
	selectsiteid.value = selectsiteid.options[txtItem].value
	if(product.match("vv"))
		selectsiteno.value = selectsiteno.options[txtItem].value; }
}
/*-------------------------------FUNCTION enableElementValSelected-----------------------------------------*/
/**
 * Enables both form elements, if they exist when a certain option is selected from a drop-down
 * txtElement2, val2 are OPTIONAL parameters.
 * If passed in, the specified form element/s is enabled when Either value or val2 option is selected
 */
function enableElementValSelected(txtDropDown,value,txtElement,txtElement2,val2){

	// initialise val2 if it was not passed in
	if (typeof(val2) == 'undefined')
		var val2 = -1;

	var ix = getById(txtDropDown).selectedIndex;

	if (ix == value || ix == val2)
	{
		getById(txtElement).disabled = false;
		if (typeof(txtElement2) != 'undefined')
			getById(txtElement2).disabled = false;
	}
	else
	{
		getById(txtElement).disabled = true;
		if (typeof(txtElement2) != 'undefined')
			getById(txtElement2).disabled = true;
	}
}
/*-------------------------------FUNCTION uncheck -----------------------------------------*/
function uncheck(checkbox)
{
	getById(checkbox).checked = false;
	getById(checkbox).value = 0;
}
/*-------------------------------FUNCTION enableElementChkSelected-----------------------------------------*/
/**
 * (Enables/Disables) a list of parameters, passed in as a comma seperated string, if checkbox is checked
 */
function enableElementChkSelected(checkbox,paramList)
{
	// Retrieve parameters from comma seperated list
	var params = paramList.split(',');

	var disable;

	// Check state of checkbox
	if(checkbox.checked == true)
	{
		disable = false;
		checkbox.value = 1;//true

	}
	else
	{
		disable = true;
		checkbox.value = 0; // false
	}

	// Iterate through parameters setting disabled property as required
	for(i = 0;i< params.length; i++)
	{
		getById(params[i]).disabled = disable;
	}
}
/**
 * Modifies 'readonly' attribute of form elements when the checkbox is checked
 */
function editElementChkSelected(checkbox,paramList)
{
	// Retrieve parameters from comma seperated list
	var params = paramList.split(',');

	var readonly;

	// Check state of checkbox
	if(checkbox.checked == true)
	{
		readonly = false;
		checkbox.value = 1;//true

	}
	else
	{
		readonly = true;
		checkbox.value = 0; // false
	}

	// Iterate through parameters setting disabled property as required
	for(i = 0;i< params.length; i++)
	{
		getById(params[i]).readOnly = readonly;
		//alert(getById(params[i]).readOnly);
	}
}
/*-------------------------------FUNCTION enableOptionValSelected-----------------------------------------*/
/**
 * Enables a drop-down option, when a certain option is selected from another drop-down
 * Enable val2 of txtDropDown2 only when value is the selected option in txtDropDown1
 * val1, val2 are (0-based) array indices
 */
function __enableOptionValSelected(txtDropDown1,value,txtDropDown2,val2){

	var ix = getById(txtDropDown1).selectedIndex;
	alert(getById(txtDropDown1).options.length);
	// mutually exclusive - disable other option, when enabling the specified option
	 for (i = 0; i < getById(txtDropDown1).options.length; i++)
	 {
		 if (ix == value)
		 {
		 	// enable the specified option, as 'value' option was selected
		 	if (i = val2)
				getById(txtDropDown2).options[val2].disabled = false;
			// disable all others
			else
				getById(txtDropDown2).options[i].disabled = true;
		}
		else
		{
		 	// disable the specified option, as 'value' option was not selected
		 	if (i = val2)
				getById(txtDropDown2).options[val2].disabled = true;
			// enable others
			else
				getById(txtDropDown2).options[i].disabled = false;
		}//else
	}// for
}
/*-------------------------------FUNCTION type_sitesearch---------------------------------*/

function type_sitesearch(txtForm, txtElement, product) {
/* Update all the text fields if the user types a partial name */
with(document.forms[txtForm]) {

		/* Declare variables */
		var i = 0;
		var text = "";
		var option = "";
		var best_match = "";
		var site_name = "";
		var site_id = "";
		var site_no = 0;
		var linker = 0;

		/* Get the value of the text field in which the user is typing in */
		/* and store it in a variable */
		ename = "site"+txtElement.toString();
		selectname = "selectsite"+txtElement.toString();
		text = getById(ename).value;
		text = text.toUpperCase();

			  /* Loop through the drop down lists to find the best match */
		  	  for (i = 0; i < getById(selectname).options.length; i++)  {
		  	  		option = getById(selectname).options[i].value;
					option = option.substring(0, text.length);
					option = option.toUpperCase();

					/* Store the items in the drop down list in variables */
					if(option.match(text)) {
						best_match = text;
						site_name = selectsitename.options[i].value;
						site_id = selectsiteid.options[i].value;
						if(product.match("vv"))
							site_no = selectsiteno.options[i].value;
						linker = i; }
			}

			/*  Change the drop down list values to match the best match value */
			if(best_match) {
				selectsitename.value = selectsitename.options[linker].value;
				selectsiteid.value = selectsiteid.options[linker].value;
				if(product.match("vv"))
					selectsiteno.value = selectsiteno.options[linker].value;
			}
	}
}
/*-------------------------------FUNCTION isEmpty---------------------------------*/
/* A function to test if a user has not entered any input
 * NOT TESTED
 */
// If the length of the element's string is 0 then display helper message
function isEmpty(elem, helperMsg){
	if(getById(elem).value.length == 0){
		alert(helperMsg);
		getById(elem).focus(); // set the focus to this input
		return true;
	}
	return false;
}
/*------------------------------- FUNCTION ajaxPassQueryStr ---------------------------------*/
/**
 * Example of this function call: ajaxPassQueryStr('voucherSerialNumber','voucherType','/voucher/lookup','formAction=filterSerial','queryVoucher')
 *
 */
function ajaxPassQueryStr(param1,param2,targetStr,formActionStr,formName){

var ajaxRequest;
var queryString = "";
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Ajax not supported");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var combo = document.getElementById('selectVoucherSN');
			combo.options.length = 0;
			var response = ajaxRequest.responseText;
			var items = response.split(";");
			var count = items.length;
			var pos = 0;
			document.getElementById('filterResult').innerHTML = '';
			for (var i=0;i<count;i++){
				if (items[i].indexOf("serial") == 0){
					combo.options[pos] = new Option(items[i].substr(6),items[i].substr(6));
					pos++;
				}
				else if (items[i].indexOf("error") == 0){
					document.getElementById('filterResult').innerHTML = items[i].substr(5);
				}
				else if (items[i].indexOf("total") == 0){
					document.getElementById('filterResult').innerHTML = items[i].substr(5);
				}

			}
		}
	}

	with (document.forms[formName]){
		var getParam1 = document.getElementById(param1).value;
		var getParam2 = document.getElementById(param2).value;
		var queryString = "?" + formActionStr + "&" + param1 + "=" + getParam1 + "&" + param2 + "=" + getParam2;
	}
	// Post to here, when this event-handler is invoked
	ajaxRequest.open("GET", targetStr + queryString, true);
	ajaxRequest.send(null);

}
/*------------------------------- FUNCTION ajaxPassQueryStr ---------------------------------*/
/**
 * A function that uses ajax tosend a request and displays the response to that request as an alert message
 * @param targetStr specify a relative url for this eventhandler to post to when it is invoked
 * @parm param1,param2 names of form elements whose values will be retrieved, appended to and posted with targetstr
 * @param formName
 */
function ajaxAlert(param1,param2,targetStr,formName,prefix){

var ajaxRequest;
var queryString = "";
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Ajax not supported");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	// This function will simply display the request's response text in an alert msg
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var response = ajaxRequest.responseText;

			// Response text will contain header information etc. Retrieve only the text enclosed by text of prefix variable

			// The form that genereates output for this event needs to enclose the output with the value of 'prefix' variable
			var startIx = response.indexOf(prefix) + prefix.length;
			var endIx = response.lastIndexOf(prefix);
			var alertTxt = response.substring(startIx,endIx);
			alert(alertTxt);
		}
	}

	var getParam1 = document.getElementById(param1).value;
	var getParam2 = document.getElementById(param2).value;
	var queryString = "?" + param1 + "=" + getParam1 + "&" + param2 + "=" + getParam2;

	//alert(targetStr + queryString);

	// Post to here, when this event-handler is invoked
	ajaxRequest.open("GET", targetStr + queryString, true);
	ajaxRequest.send(null);

}
/**
 *
 * @param pathStr Relative url that ajax will pass request to
 * @param flagParam Name of parameter, whose value will be set to TRUE
 * @param paramStr A comma seperated list of parameters whose values will be set
 * 		when data is received from the server
 *
 */
function ajaxPopulateFields(pathStr,flagParam,param1,dropdown,paramStr)
{
var ajaxRequest;
var queryString = "";
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Ajax not supported");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{
		if(ajaxRequest.readyState == 4)
		{
			var response = ajaxRequest.responseText;

			// Reftrieve contact details from response
			var tag = "CONTACTARRAY";
			var startIx = response.indexOf(tag) + tag.length;
			var endIx = response.lastIndexOf(tag);
			var contactStr = response.substring(startIx,endIx);

			//alert(contactStr);

			// split string into contactarray
			var contact = contactStr.split(':');

			//alert(paramStr);

			// Split input parameter paramString into an array of parameters
			params = paramStr.split(',');

			alertTxt = "";
			// Iterate through values from response, and assign to form parameters
			for(i = 0; i < contact.length;i++)
			{
				var parameter = params[i];
				//alertTxt = alertTxt + " " + params[i] + " - " + contact[i] + "\n";
				if(params[i].name !== "")
				{
					getById(params[i]).value = contact[i];
					//alert(getById(params[i]).name+ "  " + getById(params[i]).value);
				}
			}
			//alert((alertTxt));
		}
	}//function()
	//alert(paramStr);
	pathStr = pathStr + "?" + flagParam + "=TRUE";
	var paramVal = getById(param1).value;
	pathStr = pathStr + "&" + param1 + "=" + paramVal;
	// retrieve the id of the selected drop-down
	var ix = getById(dropdown).selectedIndex;
	//alert(getById(dropdown).name);
	var id = getById(dropdown).options[ix].value;
	// append to path string
	pathStr = pathStr + "&" + "selectedContact=" + id;
	//alert(pathStr);
	ajaxRequest.open("GET", pathStr, true);
	ajaxRequest.send(null);
}

/*------------------------------- FUNCTION ajaxSubmitSiteOwingForm ---------------------------------*/
/**
 *
 * @param pathStr Relative url that ajax will pass request to
 * @param flagParam Name of parameter, whose value will be set to TRUE
 * @param paramStr A comma seperated list of parameters whose values will be set
 * 		when data is received from the server
 *
 */
function myFcn(pathStr,displParam,siteIdParam)
{

	var ajaxRequest;
	var queryString = "";
	try
	{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer Browsers
		try
		{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				// Something went wrong
				alert("Ajax not supported");
				return false;
			}
		}
	}

	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function()
	{
		if(ajaxRequest.readyState == 4)
		{
			var response = ajaxRequest.responseText;

			//alert(response);

			// Reftrieve contact details from response
			var tag = "MARKER";
			var startIx = response.indexOf(tag) + tag.length;
			var endIx = response.lastIndexOf(tag);
			var owing = response.substring(startIx,endIx);

			//alert( "Owing amt " + 	owing);
			getById(displParam).value = owing;
			document.getElementById(displParam).value = owing;
		}
	}//function()

	//alert(pathStr + " : " + displParam + " - " + getById(displParam).value + siteIdParam);

	pathStr = pathStr + "?siteId=" + getById(siteIdParam).value;
	//alert(pathStr);
	ajaxRequest.open("GET", pathStr, true);
	ajaxRequest.send(null);
}

/*------------------------------- FUNCTION ajaxSubmitForm ---------------------------------*/
function ajaxSubmitForm(param1,param2,param3,targetStr,formActionParam,submitParam,formName){

var ajaxRequest;
var queryString = "";
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Ajax not supported");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var response = ajaxRequest.responseText;
			var items = response.split(";");
			var count = items.length;
			document.getElementById('voucherDisplayFieldset').innerHTML = '';
			for (var i=0;i<count;i++){
				if (items[i].indexOf("voucherDisplay") == 0){
					document.getElementById('voucherDisplayFieldset').innerHTML =  items[i].substr(12);
				}
			}
		}
	}//function()

	with (document.forms[formName]){
		var getParam1 = document.getElementById(param1).value;
		var getParam2 = document.getElementById(param2).value;
		var getParam3 = document.getElementById(param3).value;
		var getSubmitParam = document.getElementById(submitParam).value;
		var getFormActionParam = document.getElementById(formActionParam).value;
		var queryString = "?" + formActionParam + "=" + getFormActionParam + "&" + submitParam + "=" + getSubmitParam + "&" + param1 + "=" + getParam1 + "&" + param2 + "=" + getParam2 + "&" + param3 + "=" + getParam3;
	}
	alert(targetStr + queryString);
	ajaxRequest.open("GET", targetStr + queryString, true);
	ajaxRequest.send(null);

}
/* **************************** Functions for SiteBlock.php TODO - generalise fcns below ********************************************** */
// This function finds the selected index of the drop-down that has been changed
// Retrieves the id property of the selected index
// Retrieve the value at the position 'id' of a hidden input's text (blocked)
// This indicates the blocked status
// Set the appropriate radio button according to this value
function assignSiteBlockRadioBtn(dropDownIdStr)
{
	var val = getSiteBlockedVal(dropDownIdStr);

	if (val == '1')
	{
		getById('blocked').checked = 1;
		getById('unblocked').checked = 0;
		getById('newBlockedVal').value = 1;
	}
	else
	{
		getById('unblocked').checked = 1;
		getById('blocked').checked = 0;
		getById('newBlockedVal').value = 0;
	}

}
// A function used internally to determine which is the currently selected site,
// and uses the position of that site in selectSite drop-down to index into a blockedStatus string in a hidden field
// on the Block Site form see: assignSiteBlockRadioBtn()
function getSiteBlockedVal(dropDownIdStr)
{
// Find index of selected item
	var index = getById(dropDownIdStr).selectedIndex;

	// Get the id value of the selected option
	var id = getById(dropDownIdStr).options[index].id;

	// Get text of hidden input element
	var str = getById('blockedStr').value;

	// get character at position id
	var val = str[id];

	return val;

}
  /** This function is called when user clicks 'Submit' on site block form
	* This function will :-
	*		1. retrieve blocked status of currently selected site on form
	*		2. See if user has changed blocked status of currently selected site
	*		3. Display a confirmation msg to user
	*		4. If user is changing blocked staus, and confirms then submit form
	* 		Modified this - 30/07/08
	*		5. If user is blocking a site,check if there is a comment in the specified text box.
	*			Only then confirm and proceed, otherwise display msg
	*	    6. Even if site's blockedstatus has not changed, will still submit form if user confirms
	*			This has changed to allow user to submit changes to the txtbox, even if blocked status is not changed
	*/

// @param url, paramList - parameters to invoke popUp function from this function
function confirmSubmitSiteUnBlock(url,paramList,txtBox,msg)
{
	// Retrieve blocked status of currently selected site
	// pass in id of the any of the drop-downs on the form, as each option of each dropdown's 'id' property is the its siteid
	var siteStatusInt = getSiteBlockedVal('SelectSiteName');

	// Retrieve status of radio button, which indicates user selection
	var userBlockedSiteBool;

	// 'proceed' is checked before this function confirms&submits form. proceed will be false, if the isempty returns false
	var confirmMsg, proceed = 1;

	// action variable used to be set to true when the sites blocked status changed, since this fcn used to only submit form then
	//var action = 0;

	if (getById('blocked').checked == 1)
		userBlockedSiteInt = 1;
	else
		userBlockedSiteInt = 0;

	//alert("Radio button says blocked? " + userBlockedSiteInt +"\nSite is blocked? "+siteStatusInt);

	// If radio btn reads true (form says block it)
	if (userBlockedSiteInt == 1)
	{
		// Determine if site's blocked status is also true(blocked)
		if (siteStatusInt == 1)
			// NO change has been made
			var confirmMsg = "The site is already blocked.\n"+
							 "\nNo Change to Blocked Status:\n"+
						   "Are you sure you want to continue?";
		else
		{
			// User wants to block site
			// Check if textbox is empty
			var noText = isEmpty(txtBox,msg);
			if (noText)
			{
				proceed = 0;
			}
			else
			{
				var confirmMsg = "Are you sure you want to block this site?";
				// set this true if form will be submitted, and user confirmation is required
				//action = 1;
			}

		}

	}
	else // If radio btn reads false(form says unblock it)
	{
		// Determine if site's blocked status is True(blocked)
		if (siteStatusInt == 1)
		{
			// User wants to unblock site
			var confirmMsg = "Are you sure you want to unblock this site?";
			// set this true if form will be submitted, and user confirmation is required
			//action = 1;
		}
		else
		{
			// NO change has been made
			var confirmMsg ="The site is already unblocked.\n"+
							"\nNo Change to Blocked Status:\n"+
						  "Are you sure you want to continue?";
		}
	}

	// if blockedstatus has changed, confirm action with user, then invoke popUp()
	if (proceed == 1)
	{
		// If user confirms, then submit form
		if (confirm(confirmMsg))
		{
			popUp(url,paramList);
		}
	}
}
/* ****************** function updateHiddenInputRadio ********************************************************************************************
 * A generic funcion that updates the 'value' of a hidden element, according to whether a radio button is selected or not
*/
function updateHiddenInputRadio(IdTargetElement,IdHiddenInput)
{
	if(getById(IdTargetElement).checked == true)
		getById(IdHiddenInput).value = 1;
	else
		getById(IdHiddenInput).value = 0;
}
function updateHiddenInputRadioVal(IdTargetElement,IdHiddenInput,trueVal,falseVal)
{
	if(getById(IdTargetElement).checked == true)
		getById(IdHiddenInput).value = trueVal;
	else
		getById(IdHiddenInput).value = falseVal;
}
/* ****************** function updateHiddenInput ********************************************************************************************
 * A generic funcion that changes the 'value' of a hidden element,
   according to the given newValue parameter
*/
function updateHiddenInput(idStrhiddenElt,newValue)
{
	//alert("old value: " + getById(idStrhiddenElt).value + "new value: " +newValue);
	getById(idStrhiddenElt).value = newValue;
}
/* ****************** function updateFormElements ********************************************************************************************
 * A generic funcion that changes the 'value' of a given element in the opening window of a popup window,
   according to the given value parameter
*/
function updateFormElements(txtForm,element,value)
{
	//alert('BEFORE: ' +element + ' has value ' + opener.document.getElementById(element).value);

	opener.document.getElementById(element).value = value;

	//alert(opener.location + ' ' +element + ' has value ' + opener.document.getElementById(element).value);
}
/** A generic funcion that populates a drop-down menu's items on a form in the parent of a popup window,
   according to the given value parameter
*/
function updateFormDropdownElements(txtForm,dropdown,valArr,idArr)
{
	with (opener.document)
	{
		// Delete current drop-down options
		getElementById(dropdown).options.length = 0;

		// Add first element
		getElementById(dropdown).options[0] = new Option('--No contact required--',"null",true);
		getElementById(dropdown).options[0].id = "null";

		var defaultSelected = false;
		// Iterate through valArr
		for (var i=1;i<valArr.length;i++)
		{
			var val = valArr[i];
			var id = idArr[i];

			// new Option syntax - new Option([text[, value[, defaultSelected[, selected]]]])
			getElementById(dropdown).options[i] = new Option(val,id,defaultSelected);
			getElementById(dropdown).options[i].id = id;
		}
	}

	//alert(opener.location + ' ' +element + ' has value ' + opener.document.getElementById(element).value);
}
/** A generic funcion that creates and adds a new option to a drop-down menu's items on a form in the parent of a popup window,
   according to the given value parameter
*/
function appendFormDropdownElements(txtForm,dropdown,val,id)
{
	with (opener.document)
	{
		var items = getElementById(dropdown).options.length;
		// Add first element
		getElementById(dropdown).options[items -1] = new Option(val,id,true);
		getElementById(dropdown).options[items -1].id = id;
	}

	//alert(opener.location + ' ' +element + ' has value ' + opener.document.getElementById(element).value);
}
/**
 * updateFormDropDown
 * A function that can be called form a popup window to update the drop-down element's value of the page that opened the popup.
 * Same as updateFormElements but special handling for a drop-down element,
 * ie. the value of the drop-down is not simply set, but its selectedindex property is set
 */
function updateFormDropDown(txtForm,dropdown,value)
{
	with (opener.document)
	{
		//alert('BEFORE: ' +dropdown + ' has value ' + opener.document.getElementById(dropdown).selectedIndex);

		// Initialise value that will be assigned to selected index of dropdown
		ix = 0;

		// Find index of the given value in options array
		i = 0;
		while ((i < getElementById(dropdown).options.length) && (getElementById(dropdown).options[i].id != value))
		{
			i++;
		}

		if (getElementById(dropdown).options[i].id == value)
			ix = i;
		opener.document.getElementById(dropdown).selectedIndex = ix;
	}
	//alert(opener.location + ' ' +element + ' has value ' + getById(element).value);
}
/* **************************** Functions for SalesController.php TODO - generalise fcns below ********************************************** */
// A function that enables 2 controls, based on the selected value of a drop-down menu
// The function can be called to act upon a minimum of 1 control, simply leave set value = -1
// 'formName' is a string corresponding to the 'name' property of the form
// input parameters are strings that correspond to the 'id' property of a control
function enableControl(formName,dropDownIdStr,txtIdStr,value1,txt2IdStr, value2,txt3IdStr,value3,txt4IdStr,value4,txt5IdStr,value5,txt6IdStr,value6,txt7IdStr,value7){

	// find selected  option id
	var index = getById(dropDownIdStr).selectedIndex;

	// disable all controls
	if (typeof(txtIdStr) !== 'undefined')
		getById(txtIdStr).disabled = true;
	if (typeof(txt2IdStr) !== 'undefined')
		getById(txt2IdStr).disabled = true;
	if (typeof(txt3IdStr) !== 'undefined')
		getById(txt3IdStr).disabled = true;
	if (typeof(txt4IdStr) !== 'undefined')
		getById(txt4IdStr).disabled = true;
	if (typeof(txt5IdStr) !== 'undefined')
		getById(txt5IdStr).disabled = true;
	if (typeof(txt6IdStr) !== 'undefined')
		getById(txt6IdStr).disabled = true;
	if (typeof(txt7IdStr) !== 'undefined')
		getById(txt7IdStr).disabled = true;

	// enable certain controls, based on selected value
	if (index == value1){
		getById(txtIdStr).disabled = false;
	}
	if (typeof(txt2IdStr) !== 'undefined' && index == value2){
			getById(txt2IdStr).disabled = false;
	}
	if (typeof(txt3IdStr) !== 'undefined' && index == value3){
			getById(txt3IdStr).disabled = false;
	}
	if (typeof(txt4IdStr) !== 'undefined' && index == value4){
			getById(txt4IdStr).disabled = false;
	}
	if (typeof(txt5IdStr) !== 'undefined' && index == value5){
			getById(txt5IdStr).disabled = false;
	}
	if (typeof(txt6IdStr) !== 'undefined' && index == value6){
			getById(txt6IdStr).disabled = false;
	}
	if (typeof(txt7IdStr) !== 'undefined' && index == value7){
			getById(txt7IdStr).disabled = false;
	}

}
/*
 * A function that dynamically changes label text, based on the selected item of a drop-down
 * Specific to the labels:idStartReceipt,idEndReceipt (this method can be generalised by passing in parameters)
 * 				   drop-down:selectConfine
 *				   selectedItem						label						new-text
 *				   [1]"receipt no range"			id='idStartNo',id='idEndNo' 'Start Receipt No.','End Receipt No.'
 *				   [2]"receipt no. and end date"	id='idStartNo' 				'Start Receipt No.'
 *				   [3]"invoice no.s"				id='idStartNo',id='idEndNo'	 'Start Invoice No.','End Invoice No.'
*/
function updateReceiptNoLabels()
{
	// get index of selected item
	var ix = getById('selectConfine').selectedIndex;

	// Choose action based on which item of select is selected
	switch (ix)
	{
		case 1:
			getById('idStartNo').innerHTML = 'Start Receipt No.';
			getById('idEndNo').innerHTML = 'End Receipt No.';
			break;
		case 2:
			getById('idStartNo').innerHTML = 'Start Receipt No.';
			break;
		case 3:
			getById('idStartNo').innerHTML = 'Start Invoice No.';
			getById('idEndNo').innerHTML = 'End Invoice No.';
			break;
	}

}
/**
 *
 * A function that updates the text of 2 form label elements, based on the selected valur of a drop-down
 * This function was written for global sales report, but is somewhat generic
 * The value of the labels is changed if the specified index value is selected in the drop-down
 * For any other selection made from the drop-down, the label text defaults to the provided default values
 *
 */
 function updateReceiptNoDateLabels(dropDownIdStr,selectedIx,idElt1,idElt2,newTxt1,newTxt2,oldTxt1,oldTxt2,idInput1,idInput2,dateStr)
{
	// get index of selected item
	var ix = getById(dropDownIdStr).selectedIndex;

	// Choose action based on which item of select is selected
	switch (ix)
	{
		case selectedIx:
			getById(idElt1).innerHTML = newTxt1;
			getById(idElt2).innerHTML = newTxt2;
			getById(idInput1).value = 0;
			getById(idInput2).value = 0;
			break;
		default:
			getById(idElt1).innerHTML = oldTxt1;
			getById(idElt2).innerHTML = oldTxt2;
			getById(idInput1).value = dateStr;
			getById(idInput2).value = dateStr;
	}

}
/**
 * This function closes the window it is called from
 * (Convenient to be called from a pop-up window)
 * It accepts 2 parameters that define the way the window is closed
 * @param focusOpener boolean Should the window that opened the current window be focused therafter?
 * @param reloadOpener boolean Should the window that opened the current window be refreshed therafter?
 *
 * @author Naseera Ally
 * 14 August 2008
 */
function closeWindow(focusOpener,reloadOpener)
{
		// IF this popup was opened from another popup, then do not close the pop up window just yet
		//if(typeof(opener.opener) != 'undefined')
		//{
		//alert('this window was opened from a popup window');//window.opener.location.href = history.back(-2);
		//}

		// Close window
		if (window)
			window.close();

	if(!opener.closed)
	{
		// Focus on window that opened this window when this window is closed
		if(focusOpener)
		{
			opener.focus();
		}
		// Refresh the window that opened this window when this window is closed
		if(reloadOpener)
		{
			window.opener.location.reload();
		}
	}
}
/*
 * function that creates a new pop-up window, using the url specified as input parameter to this method
 * paramList is a coma seperated string of parameters
 * If paramList is not empty, the 'url' parameter must not provide any parameters, as the first parameter is prefixed with a '?'
 */

function popUp(url, paramList) {
	// Retrieve parameters and store in an array
	var params = paramList.split(",");
	var numParams = params.length;

	//alert(url);

	// Iterate through parameter list and build up url
	var append = '?';
	for (var i=0;i<numParams;i++)
	{
		//alert(i + '.' + params[i] + '=' + getById(params[i]).value);
		var paramValue = getById(params[i]).value;

		//alert(document.getElementById(params[i]).name + " " + document.getElementById(params[i]).value);//test

		url = url + append + params[i] + '=' + escape(paramValue);
		append = '&';
	}

//	alert(url);
	// Initialise new window object
	var newwindow = null;

	newwindow=window.open(url,'name','resizable=1 ,scrollbars=1 height=800,width=800');
	if (window.focus) {newwindow.focus()}
	return false;
}
/*
 * function that creates a new pop-up window, using the url specified as input parameter to this method
 * formName is a string passed in as the name of the form whose elements are to be looked up and passed
 * To omit any form elements, do not assign the 'name' property of the element
 */

function popUpFormName(url, formName) {
	// Retrieve parameters and store in an array
	var form = getById(formName);
	var numElts = form.elements.length;

	//alert(url);

	// Iterate through form's elements and build up url
	var append = '?';
	for (var i=0;i<numElts;i++)
	{
		//alert(i + '.' + params[i] + '=' + getById(params[i]).value);
		var element = form.elements[i];

		// Omit elements that do not hav a name property defined
		if(element.name != "")
		{
			url = url + append + element.name + '=' + escape(element.value);
			append = '&';
		}
	}

	//alert(url);

	newwindow=window.open(url,'name','resizable=1 ,scrollbars=1 height=800,width=800');
	if (window.focus) {newwindow.focus()}
	return false;
}
/**
 * Same as popUp(), but accepts an extra string parameter thatis used as the title of the window
 * Not tested - works with errors. This function is not called / used.
 */
function popUpTitle(url, paramList,windowTitleString) {
	// Retrieve parameters and store in an array
	var params = paramList.split(",");
	var numParams = params.length;

	//alert(url);

	// Iterate through parameter list and build up url
	var append = '?';
	for (var i=0;i<numParams;i++)
	{
		//alert(i + '.' + params[i] + '=' + getById(params[i]).value);

		url = url + append + params[i] + '=' + escape(getById(params[i]).value);
		append = '&';
	}

//	alert(url);

	newwindow=window.open(url,'name','resizable=1 ,scrollbars=1 height=800,width=800');
	if (window.focus) {newwindow.document.write("<title>",windowTitleString,"</title>");newwindow.focus()}
	return false;
}

function ajaxPollFunction()
{
var ajaxRequest;
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	}
	catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){
				// Something went wrong
				alert("Ajax not supported");
				return false;
			}
		}
	}

	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			// Get server response
			var response = ajaxRequest.responseText;

			// Find index of start of "content" div : look for this div
			searchText = "<div id = 'realtimecallactivity'>";
			start = response.indexOf(searchText);

			// Find end of content div tag - look for this label
			searchText = "<label id='EndOfRealTimeCallActivity'></label>";
			end = response.indexOf(searchText);

			// if text was not found
			if (end == -1)
				end = response.length - 1;

			// Remove text up to that point, ie removing header, so it is not re-rendered on page
			response = response.slice(start,end);

			setTimeout('ajaxPollFunction()',15000)
			ajaxRequest = null;
			// Render server's response, excluding header,menu,footer to page, so that refreshed data is displayed
			document.getElementById('content').innerHTML = response;
		}
	}// END function()

	ajaxRequest.open("GET", '/report/callactivity', true);
	ajaxRequest.send(null);
}
/**
 * confirmSubmitForm()
 * A function that can be used for a form's submit event handler
 * It will :-
 *    1) set the value of the 'actionElement' to "TRUE"
 *    2) Display a confirmation msg
 *    3) Submit the form if the user confirms the action
 *
 * These input parameters are strings representations of the id propety of each element that it respresents.<b>
 *  txtform
 *  actionElement - The element whose value will be set to "true"
 * This input parameter is the text that will be displayed to confirm if a form is submitted.
 *  confirmMsg

*/
function confirmSubmitForm(txtform, actionElement,confirmMsg)
{
	// Extract the users action from the action textbox on the form
	if( getById(actionElement) )
	{
		 getById(actionElement).value = "TRUE";
	}

	// Only submit the form is the user clicks on okay
	 if( confirm(confirmMsg) )
	 {
	  	submitForm(txtform);
	 }
	 return false;
}
/**
 * confirmForm()
 * A function that can be used for a form's submit event handler
 * It will :-
 *    1) set the value of the 'actionElement' to "TRUE"
 *    2) Display a confirmation msg
 *    3) Return true if the user confirms the action
 *
 * These input parameters are strings representations of the id propety of each element that it respresents.<b>
 *  txtform
 *  actionElement - The element whose value will be set to "true"
 * This input parameter is the text that will be displayed to confirm if a form is submitted.
 *  confirmMsg
*/
function confirmForm(txtform, actionElement,confirmMsg)
{
	// Extract the users action from the action textbox on the form
	if( getById(actionElement) )
	{
		 getById(actionElement).value = "TRUE";
	}
	// Only submit the form is the user clicks on okay
	 if( confirm(confirmMsg) )
		return true;
	 else
		 return false;
}
/**
 * submitFormVal
 * A function that can be used for a form's submit event handler
 * It will :-
 *    1) set the value of the 'actionElement' to actionMsg
 *
 * These input parameters are strings representations of the id propety of each element that it respresents.<b>
 *  txtform
 *  actionElement - The element whose value will be set to the value of actionVal
 */
 function submitFormVal(txtform, actionElement,actionVal)
{
	// Extract the users action from the action textbox on the form
	if( getById(actionElement) )
	{
		 getById(actionElement).value = actionVal;
	}
}
/**
 * confirmForm()
 * A function that can be used for a form's submit event handler
 * It will :-
 *    1) set the value of the 'actionElement' to actionMsg
 *    2) Display a confirmation msg
 *    3) Return true if the user confirms the action
 *
 * These input parameters are strings representations of the id propety of each element that it respresents.<b>
 *  txtform
 *  actionElement - The element whose value will be set to "true"
 * This input parameter is the text that will be displayed to confirm if a form is submitted.
 *  confirmMsg
*/
function confirmFormVal(txtform, actionElement,actionMsg,confirmMsg)
{
	// Extract the users action from the action textbox on the form
	if( getById(actionElement) )
	{
		 getById(actionElement).value = actionMsg;
	}
	// Only submit the form is the user clicks on okay
	 if( confirm(confirmMsg) )
		return true;
	 else
		 return false;
}
function confirmFormPopUp(txtform, actionElement,confirmMsg,url,paramList)
{
	// Extract the users action from the action textbox on the form
	if( getById(actionElement) )
	{
		 getById(actionElement).value = "TRUE";
	}

	// Only submit the form is the user clicks on okay
	 if( confirm(confirmMsg) )
		popUp(url,paramList);
	 else
		 return false;
}
/**
 */
function test(txtform, actionElement,confirmMsg)
{
	alert('test function');
	return false;
}