 //Check if any of the the specified checkboxes has been ticked
 //Terry Bhatti 16/11/2001
 function isCheckboxTicked(form, namePrefix) {

     for(var i=0; i<form.elements.length; i++) {
         if ((form.elements[i].type == "checkbox") && (form.elements[i].checked)) {
             if (form.elements[i].name.indexOf(namePrefix) > -1) {
                 return true;
             }
         }
     }
     return false;
 }

  //Check if any value is selected in pull down list (ie. other than default value)
 //Terry Bhatti 16/11/2001
 function isValueSelected(form, namePrefix, defaultValue) {

     for (var i=0; i<form.elements.length; i++) {
         if ((form.elements[i].type == "select-one") && (form.elements[i].name.indexOf(namePrefix) > -1)) {
                if (getValue(form.elements[i]) != defaultValue) {
                 return true;
             }
         }
     }
     return false;
 }

//Check if any of the text box are populated
//Terry Bhatti 28/2/2006
function isValueEntered(form, namePrefix) {
     for (var i=0; i<form.elements.length; i++) {
         if ((form.elements[i].type == "text") && (form.elements[i].name.indexOf(namePrefix) > -1)) {
                if (trim(getValue(form.elements[i])) != "") {
                 return true;
             }
         }
     }
     return false;
}

//return true if form field exists with given name
function isFormFieldExist(form, fieldName) {
    
     for (var i=0; i<form.elements.length; i++) {
        if (form.elements[i].name == fieldName) {
            return true;
        }
    }
    return false;
}

  var AUSTRALIA_CODE = '1100';
  var AUSTRALIA_NAME = 'AUSTRALIA';
  var AUSTRALIA_NAME_DISPLAY = 'Australia';

  function isAustralia(country) {
    if (country != null) {
      country = trim(country);
      if ((country == AUSTRALIA_CODE) || (country.toUpperCase() == AUSTRALIA_NAME)) {
        return true;
      }
    }
    return false;
  }

  /* Returns true if the specified String contains a number, otherwise false.  */
  var NUMERALS = "0123456789";
  function containsNumber(pString) {
      if (pString == null) {
          return false;
      }
      pString = trim(pString);
      if (pString == "") {
          return false;
      }
      var nextChar;
      for (var i = 0; i < pString.length; i++) {
          nextChar = pString.charAt(i);
          if (NUMERALS.indexOf(nextChar) > -1) {
              return true;
          }
      }
      return false;
  }

  /* Returns true if the specified String contains a letter, otherwise false.  */
  var LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  function containsLetter(pString) {
      if (pString == null) {
          return false;
      }
      pString = trim(pString);
      if (pString == "") {
          return false;
      }
      var nextChar;
      pString = pString.toUpperCase();
      for (var i = 0; i < pString.length; i++) {
          nextChar = pString.charAt(i);
          if (LETTERS.indexOf(nextChar) > -1) {
              return true;
          }
      }
      return false;
  }
  
  /* Return true if password is atleast 6 characters long and contains atleast 1 digit and 1 letter */
  function isValidPassword(pPassword) {

	if (pPassword == null) {
		return false;
	}
	pPassword = trim(pPassword);
	if (pPassword == "") {
		return false;
	}

	pPassword = pPassword.toLowerCase();
	len = pPassword.length;
	hasLetter = false;
	hasDigit = false;

	if (len >=6 && len <= 10) {
	    for (var i=0; i<len; i++) {
	        ch = pPassword.charAt(i);

	        if (ch >= 'a' && ch <= 'z') {
	            hasLetter = true;
	         }
	        if (ch >= '0' && ch <= '9') {
	            hasDigit = true;
	        }
	        if (hasLetter && hasDigit) {
	            return true;
	        }
	    }
	 }

	 return false;
  }
  
  /* Country names can't contain numbers, but nulls and blanks are OK */
  function isValidCountryName(pCountry) {
    if (pCountry == null) {
        return true;
    }
    pCountry = trim(pCountry);
    if (pCountry == "") {
        return true;
    }
    return !containsNumber(pCountry);
  }

  function validateState(invokingObject, country, state, stateOther) {
      if (invokingObject == 'country') {
          if (isAustralia(getValue(country))) {
              setValue(stateOther, '');
              if (getValue(state) == "OTHER") {
                  setValue(state, '');
              }
          } else if (getValue(country) == '') {
              setValue(state, '');
              setValue(stateOther, '');
          } else {
              setValue(state, 'OTHER');
          }
      } else if (invokingObject == 'state') {
          if (getValue(state) != '' && getValue(state) != 'OTHER') {
              setValue(country, AUSTRALIA_NAME_DISPLAY);
          } else {
             setValue(country, '');
          }
      }
      return false;
  }


//if email entered, make sure it is in correct format.
function validateEmail(email, emailRepeated) {
    if (email != '' || emailRepeated != '') {
        if (!isValidEmailAddr(email)) {
        	alert('Your e-mail address is not valid. Please enter\na single correct email address or clear it.');
        	return false;
      } else if (email != emailRepeated) {
          alert('Your e-mail and repeated e-mail addresses do not match.\nPlease clear or enter same e-mail address in both fields.');
          return false;
      }
    }
    return true;
}

//Validate email and only allow a single email address.
function isValidEmailAddr(email) {

		emailAddr = trim(email);
    if (emailAddr.length==0) {
        return true;
    }
    if (emailAddr.indexOf("@") < 1) { //  must contain @, and it must not be the first character
        return false;
    } else if (emailAddr.lastIndexOf(".") <= emailAddr.indexOf("@")) {  // last dot must be after the @
        return false;
    } else if (emailAddr.lastIndexOf("@") == emailAddr.length-1) {  // @ must not be the last character
        return false;
    } else if (emailAddr.indexOf("..") >=0) { // two periods in a row is not valid
    	return false;
    } else if (emailAddr.lastIndexOf(".") == emailAddr.length-1) {  // . must not be the last character
        return false;
		} else if (getStringCount(emailAddr, '@') > 1) {		//allow a single email address.
			return false;
		} else if (!containsLetter(emailAddr.substring(emailAddr.length-1))) {		//last character must be an alpha character.
			return false;
		}
    return true;
}

function getStringCount(sourceString, searchString) {
    	
	  srcString = sourceString;
		count = 0;
		i = srcString.indexOf(searchString);
		
		while(i >= 0) {
		    count++;
		    srcString = srcString.substring(i+1);
		    i = srcString.indexOf(searchString);
		}
		return count;
	}


// Added TL 2002-03-15

function daysInMonth(month, year) {
	switch (month) {
		case  4 :
		case  6 :
		case  9 :
		case 11 :
			return 30;
		case  2 :
			return (isLeap(year)) ? 29 : 28;
		default :
			return 31;
	}
}

function isLeap(year) {
	return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0);
}

function checkMandatoryDateField(form, name) {
	return checkDateField(form, name, true);
}

function checkDateField(form, name, mandatory) {
	var day = getValue(eval(form + '.' + name + '_Day'));
	var month = getValue(eval(form + '.' + name + '_Month'));
	var year = getValue(eval(form + '.' + name + '_Year'));
	if (day == '' && month == '' && year == '') {
		if (mandatory == null || !mandatory) {
			return true;
		} else {
			alert('Please enter a date');
			focusOn(eval(form + '.' + name + '_Day'));
			return false;
		}
	}
	var opt = (mandatory == null || !mandatory) ? ' or leave the entire date blank' : '';
	if (day == '') {
		alert('Please enter a day' + opt);
		focusOn(eval(form + '.' + name + '_Day'));
		return false;
	} else if (month == '') {
		alert('Please select a month' + opt);
		eval(form + '.' + name + '_Month').focus();
		return false;
	} else if (year == '') {
		alert('Please select a year' + opt);
		focusOn(eval(form + '.' + name + '_Year'));
		return false;
	}

	var iDay = parseInt(day, 10);
	var iMonth = parseInt(month, 10);
	var iYear = parseInt(year, 10);
	if (isNaN(iDay) || iDay < 1 || iDay > daysInMonth(iMonth, iYear)) {
		alert('Please enter a valid date');
		focusOn(eval(form + '.' + name + '_Day'));
		return false;
	} else if (isNaN(iYear) || iYear < 1800 || iYear > 2100) {
		alert('Please enter a valid year after 1800');
		focusOn(eval(form + '.' + name + '_Year'));
		return false;
	}
	return true;
}

// validation for optional groups that must be validated as a group
function Group(name_, mandatory_, error_) {
    this.name = name_;
    this.mandatory = mandatory_;
    this.error = error_;
}
function validateGroup(group, suffix) {
    var any = false;
    var i;
    for (i = 0; i < group.length; i++) {
        if (getValue(eval(group[i].name + suffix)).length > 0) {
            any = true;
        }
    }
    if (any) {
        for (i = 0; i < group.length; i++) {
            if (group[i].mandatory) {
                if (!checkMandatoryField(eval(group[i].name + suffix), group[i].error)) return false;
            }
        }
    }
    return true;
}
function isEmptyGroup(group, suffix) {
    var any = false;
    var i;
    for (i = 0; i < group.length; i++) {
        if (getValue(eval(group[i].name + suffix)).length > 0) {
            any = true;
        }
    }
    if (any) {
        for (i = 0; i < group.length; i++) {
            if (eval(group[i].name + suffix) != '') return false;
        }
    }
    return true;
}
function clearGroupValues(group, suffix) {
    for (i = 0; i < group.length; i++) {
        setValue(eval(group[i].name + suffix), "");
    }
}

function SaveField(name_, value_) {
    this.name = name_;
    this.oldValue = value_;
}

function saveValues(fields) {
    for (var i = 0; i < fields.length; i++) {
        fields[i].oldValue = getValue(eval(fields[i].name));
        setValue(eval(fields[i].name), "");
    }
}


function restoreValues(fields) {
    for (var i = 0; i < fields.length; i++) {
        setValue(eval(fields[i].name), fields[i].oldValue);
    }
}

function suffixNumber(value) {
  var result = '';
  if ((value != null) && (value.length > 0)) {
    var number = parseInt(value);
    var lastDigit = parseInt(value.charAt(0))
    switch(lastDigit) {
      case 1: {
        if ((number % 100) == 1) {
          return value + 'st';
        } else {
          return value + 'th';
        }
        break;
      }
      case 2: {
        return value + 'nd';
        break;
      }
      case 3: {
        return value + 'rd';
        break;
      }
      default: {
        return value + 'th';
        break;
      }
    }
  }
  return result;
}

function isOtherInstitution(pInstitutionID) {
    if (otherInstitutionsIDs.indexOf(pInstitutionID) > -1) {
      return true;
    } else {
      return false;
    }
}

function checkInstitution(pInstitutionID, pInstitutionName) {
  	var institutionId = pInstitutionID.options[pInstitutionID.options.selectedIndex].value;
    if ((institutionId != null) && (institutionId != "")) {
      if (isOtherInstitution (institutionId)) {
  		if ((pInstitutionName.value == null) || (pInstitutionName.value == '')) {
      		alert ('Please enter the name of the institution.');
      		focusOn(pInstitutionName);
      		return false;
  		}
      }
    }
  	return true;
}

/**
 * The following function assumes that there are 3 date entry fields (for day, month and year)
 * and a hidden "whole date" field.  The assumed naming convention is that the whole date field
 * has the name specified in pDateFieldName and that the individual component field parts have
 * names made up of the name specified in pDateFieldName with _Day or _Month or _Year appended.
 * The function takes the values in the component fields and uses them to construct a string
 * that is loaded into the "whole date" field.  No validation is done as this is assumed to be
 * performed by the checkDateField() function.
 */
function loadDate(pFormName, pDateFieldName) {
	var day   = getValue(eval(pFormName + '.' + pDateFieldName + '_Day'));
	var month = getValue(eval(pFormName + '.' + pDateFieldName + '_Month'));
	var year  = getValue(eval(pFormName + '.' + pDateFieldName + '_Year'));
	setValue(eval(pFormName + '.' + pDateFieldName), day + '/' + month + '/' + year);
}

/**
 * The following function assumes that there are 3 date entry fields (for day, month and year).
 * The assumed naming convention is that the whole date field has the name specified in
 * pDateFieldName and that the individual component field parts have names made up of the name
 * specified in pDateFieldName with _Day or _Month or _Year appended.
 * The function takes the values in the component fields and simply checks that each one is
 * numeric.  The function returns true if this process succeeds, false otherwise.
 */
function validateDate(pFormName, pDateFieldName, pErrorMsg) {
	var day   = getValue(eval(pFormName + '.' + pDateFieldName + '_Day'));
	var month = getValue(eval(pFormName + '.' + pDateFieldName + '_Month'));
	var year  = getValue(eval(pFormName + '.' + pDateFieldName + '_Year'));
	var number = new Number(day);
	if (number == 0) {
	    alert(pErrorMsg);
	    focusOn(eval(pFormName + '.' + pDateFieldName + '_Day'));
	    return false;
	}
	number = new Number(month);
	if (number == 0) {
	    alert(pErrorMsg);
	    focusOn(eval(pFormName + '.' + pDateFieldName + '_Month'));
	    return false;
	}
	number = new Number(year);
	if (number == 0) {
	    alert(pErrorMsg);
	    focusOn(eval(pFormName + '.' + pDateFieldName + '_Year'));
	    return false;
	}
	return true;
}

//TB 18-Aug-2003 - added  
function validAusPostcode(ausPostcode) {

    if ((!isAllDigits(ausPostcode)) || (ausPostcode.length != 4)) {
        alert("Please enter a valid 4 digit Australian postcode.");
        return false;
    }
    return true;
}

//retruns the value of parameter
function getQueryParameter(param) {

  var queryString = window.location.search.substring(1);
  var params = queryString.split("&");
  for (var i=0;i<params.length;i++) {
    var pair = params[i].split("=");
    if (pair[0] == param) {
      return pair[1];
    }
  }
  return "";
}

//TB 24-Apr-2007
//Show hide document element, does not work with div
function show_hide(id) {
	element = document.getElementById(id);
	element.style.display = (('none'== element.style.display) ? '' : 'none');
}

//Show document element, does not work with div
function show(id) {
	element = document.getElementById(id);
	element.style.display = '';
}

//Hide document element, does not work with div
function hide(id) {
	element = document.getElementById(id);
	element.style.display = 'none';
}

//validate that str is a positive numeric number.
//also check that only one decimal exists.
function isNumber(str) { 

	numdecs = 0; 
	for (i = 0; i < str.length; i++) {  
	
		mychar = str.charAt(i); 
		
		if ((mychar >= "0" && mychar <= "9") || mychar == ".") { 
			if (mychar == ".") {
				numdecs++; 
			}
		} else {
			return false; 
		}	
	} 

	if (numdecs > 1) {
		return false;
	}

	return true; 
} 
