//    THIS FILE CONTAINS THE COMMON VALIDATION JAVASCRIPT FUNCTIONS USED BY FORMS
//    IT HAS A VERSION NUMBER IN THE FILE NAME, IF YOU CHANGE THIS FILE CHANGE ITS 
//    NAME BY UPDATING THE VERSION NUMBER AND UPDATE THE ServletUtils OBJECT WITH
//    ITS NEW NAME. YOU WILL THEN ENSURE THAT THE BROWSERS PICK UP YOUR CHANGES AND
//    DO NOT USED OLD CACHED VERSIONS OF THIS FILE.


function openAbnLookup(value) {
  var url = 'http://www.abr.business.gov.au/search.aspx?StartSearch=True&SearchText='+ value;
  window.open(url, null, 'height=400,width=600,resizable=yes,scrollbars=true'); 
}

var requestSubmitted = false;   
function checkSubmit() {
  if(requestSubmitted == true) {
    alert('You have already submitted the request.. Please wait');
    return;
  }
  requestSubmitted = true;
}

function nnv(v) {
	if (v == null) {
		return '';
	} else {
		return v;
	}
}

function isChecked(element) {
	if (element) {
		return element.checked;
	} else {
		return false;
	}
}

function isRadioChecked(element) {
  for(var i = 0; i <  element.length; i++) {
    if(element[i].checked) {
      return true;
    }
  }
  return false;
}

function notChecked(element) {
	return !isChecked(element);
}

function notEmpty(element) {
	if (element.value == '') {
		return false;
	} else {
		return true;
	}
}

function isEmpty(element) {
	if (element.value == '') {
		return true;
	} else {
		return false;
	}
}

function validText(element, elementName) {
	if (element.value=='') {
		alert(elementName + ' is a required field.');
		element.focus();
		return false;
	}
  
  
  var spaces = 0
  for(i = 0; i < element.value.length; i++) {
    if(element.value.charAt(i) == ' ') {
      spaces = spaces + 1;
    }
  }
  
  if(spaces == element.value.length) {
    alert(elementName + ' is a required field.');
		element.focus();
		return false;
  } else {
		return true;
	}
}

function validNonNumericText(element, elementName) {
	if (element.value=='') {
		alert(elementName + ' is a required field.');
		element.focus();
		return false;
	} else {
    // test for number values
    var numRegex = /[0-9]/;
    cnt = element.value.search(numRegex);
    if(cnt != -1) {
      alert(elementName + ' cannot contain numeric values.');
      element.focus();
      return false;  
    }
    
    var spaces = 0;
    for(i = 0; i < element.value.length; i++) {
      if(element.value.charAt(i) == ' ') {
        spaces = spaces + 1;
      }
    }
    if(spaces == element.value.length) {
      alert(elementName + ' is a required field.');
      element.focus();
      return false;
    } 
    
		return true;
	}
}

function isSpaces(element) {
	if(element.value != '') {
		var spaces = 0;
		for(i = 0; i < element.value.length; i++) {
			if(element.value.charAt(i) == ' ') {
				space +=1;
			}	
		}
		
		if(spaces == element.value.length) {
			return true;
		}
	}
	
	return false;
}

function trim(str) {
	while(str.charAt(str.length -1) == ' ') {
		str = str.substring(0, str.length -1);
	}
	
	while(str.charAt(0) == ' ') {
		str = str.substring(1, str.length);
	}
	
	return str;
}

function hasNumericsInText(element, elementName) {
    if(element.value != '') {
      var numRegex = /[0-9]/;
      cnt = element.value.search(numRegex);
      if(cnt != -1) {
        alert(elementName + ' cannot contain numeric values.');
        element.focus();
        return false;  
      }
    }
    return true;
}


function emptyText(element, message) {
	if (element.value!='') {
		alert(message);
		element.focus();
		return false;
	} else {
		return true;
	}
}

function validTextOption(element1, element2, txt) {
	if (element1.value=='' && element2.value=='') {
		alert(txt);
		element1.focus();
		return false;
	} else {
		return true;
	}
}

function validInteger(element, elementName, mandatory) {
	if (mandatory) {
		if (!validText(element, elementName)) {
			return false;
		}
	}
	
	// use regex to check for a decimal place
	var numRegex = /[.]/;
    cnt = element.value.search(numRegex);
	
	if (isNaN(element.value) || element.value <= 0 || cnt != -1) {
		alert(elementName + ' must be a whole positive number.');
		element.focus();
		return false;
	} else {
		return true;
	}
}

function isValidList(element) {
  if(element.options[0].selected) {
    return false;
  } else {
    return true;
  }
}

function validList(element, elementName) {
	if (element.options[0].selected) {
		alert('Please select an option from ' + elementName);
		element.focus();
		return false;
	} else {
		return true;
	}
}

function isValidEmailAddr(email){
	var result = true
	var theStr = new String(email.value)
	if (theStr=='') {
		alert('You must enter an email address');
		email.focus();
		return false;
	}
	if (theStr.indexOf(" ")>=0) {
		alert('You cannot have white space in an email address');
		email.focus();
		return false;
	}
    var index = theStr.indexOf("@");
	if (index<1) {
		alert('You must have an @ symbol in an email address');
		email.focus();
		return false;
	}
    var rest = theStr.substring(index);
    if (rest.length < 1) {
		alert('You must specify a location after the @ in an email address');
		email.focus();
		return false;
    }
  	return result;
}

function validDate(day, month, year, fieldName) {
    if (isNaN(day.value) || day.value < 1 || day.value > 31) {
        alert('Invalid '+fieldName+' day must be between 1 and 31');
        day.focus();
        return false;
    }
    if (month.options[0].selected) {
        alert('Invalid '+fieldName+' month - You must select a month');
        month.focus();
        return false;
    }
    if (isNaN(year.value) || year.value < 10) {
        alert('Invalid '+fieldName+' year - Please enter a 4 digit year e.g. 2002');
        year.focus();
        return false;
    }
    
    if (isNaN(year.value) || year.value < 1900 || year.value.length > 4) {
        alert('Invalid '+fieldName+' year is too old - Please enter a 4 digit year e.g. 2002');
        year.focus();
        return false;
    }
    return true;
}

function validDateTime(min, hour, day, month, year, fieldName) {
    if (!validDate(day, month, year, fieldName)) return false;
    if (hour.value=='') {
        alert('Please enter '+fieldName+' hour - value between 0 and 23');
        hour.focus();
        return false;
    }
    if (min.value=='') {
        alert('Please enter '+fieldName+' minute - value between 0 and 59');
        min.focus();
        return false;
    }
    if (isNaN(hour.value) || hour.value < 0 || hour.value > 23) {
        alert('Invalid '+fieldName+' hour must be between 0 and 23');
        hour.focus();
        return false;
    }
    if (isNaN(min.value) || min.value < 0 || min.value > 59) {
        alert('Invalid '+fieldName+' minute must be between 0 and 59');
        min.focus();
        return false;
    }
    return true;
}

function getBrowserVersion() {
    var ver = parseInt(navigator.appVersion);
    
    // Note: IE5 returns 4
    if (ver == 4) {
        var agt = navigator.userAgent.toLowerCase();
        if (agt.indexOf("msie 5") >= 0) ver = 5;
        if (agt.indexOf("msie 6") >= 0) ver = 6;
        if (agt.indexOf("msie 7") >= 0) ver = 7;
    }
    
    return ver;
}

function printForm() {
    var version = getBrowserVersion();
    if (version > 4) {
    	window.print();
    } else {
    	alert('Your browser is too old - please use the browser menu');
    }
}

var ns4 = (document.layers)? true:false;

function init() {
    if (ns4) {document.captureEvents(Event.MOUSEMOVE);}
}

function openWindowWithFullURL(url, title, options) {
    // Opening a popup from with in popup seem to reuse the popup window in the URL used is a local
    // URL (e.g. index.jsp or CalendarPopup.jsp). To fix this problem I need to url a complete URL!
    var fullUrl = 'http://'+window.location.host+'/eli/'+url;
    //alert(fullUrl);
    return window.open(fullUrl, null, options, true); 
}

function openCalendar(x,y,dayField, monthField, yearField) {
    return openCalendar(x,y,dayField, monthField, yearField, null);
}

function openCalendar(x,y,dayField, monthField, yearField, onchange) {
   var dayFieldName = dayField.name;
   var monthFieldName = monthField.name;
   var yearFieldName = yearField.name;
   
   var day = dayField.value;
   var month = monthField.value;
   var year = yearField.value;
   
   var onchangeParam = '';
   if (onchange != null) {
      onchangeParam = '&onchange='+onchange;
   }
   var url = 'CalendarPopup.jsp?day='+day+'&month='+month+'&year='+year+'&dayFieldName='+dayFieldName+'&monthFieldName='+monthFieldName+'&yearFieldName='+yearFieldName+onchangeParam;
   //alert('left='+x+',top='+y);
   var options='height=200,width=225,status=no,toolbar=no,menubar=no,location=no,titlebar=no,reasizable=no,left='+x+',top='+y; 
   top.open(url, null, options);
}

function openIncidentLookup() {
	openIncidentLookup(null, null);
}

function openIncidentLookup(eventId, incidentId) {
	var x = window.screenLeft;
	var y = window.screenTop+event.y-30;
    var url = 'EventSearchPopup.jsp?EventId='+nnv(eventId)+'&IncidentId='+nnv(incidentId);
    var options = 'height=400,width=600,status=yes,toolbar=no,menubar=no,location=no,titlebar=yes,resizable=yes,scrollbars=yes,left='+x+',top='+y;
    window.open(url, '_blank', options);
}

function openOfficerLookup() {
	openOfficerLookup(null, null, null);
}

function openOfficerLookup(region, district, officer) {
	var x = window.screenLeft;
	var y = window.screenTop+event.y-30;
    var url = 'OfficerSearchPopup.jsp?LocationRegion='+nnv(region)+'&LocationDistrict='+nnv(district)+'&LocationOfficer='+nnv(officer);
    //alert('left='+x+',top='+y);
    window.open(url, null, 'height=400,width=600,status=no,toolbar=no,menubar=no,location=no,titlebar=no,resizable=yes,left='+x+',top='+y); 
}

// Given a post code and a street, renders a popup allowing the user to search for an
// employer location. The lookup type allows the windows to specify classification
// of location, e.g. particular roles. NB the street type is ignored.
// valid values for type is address and elo.
function openLocationLookup(roleCode, postcode, suburb, street, streetNo, searchType) {
	var x = window.screenLeft;
	var y = window.screenTop+event.y-30;
	var roleParam = "";
	if (roleCode != null && roleCode != '') {
		roleParam = "&RoleCode="+roleCode;
	}
    var suburbParam = "";
	if (suburb != null && suburb != '') {
		suburbParam = "&Suburb="+suburb;
	}
    var postcodeParam = "";
	if (postcode != null && postcode != '') {
		postcodeParam = "&PostCode="+postcode;
	}
    var streetParam = "";
	if (street != null && street != '') {
		streetParam = "&Street="+street;
	}
    var streetNoParam = "";
	if (streetNo != null && streetNo != '') {
		streetNoParam = "&StreetNo="+streetNo;
	}
    var typeParam = "";
	if (searchType != null && searchType != '') {
		typeParam = "&SearchType="+searchType;
	}
    var url = "LocationSearchPopup.jsp?faction=render"+roleParam+postcodeParam+suburbParam+streetParam+streetNoParam+typeParam;
    var options = 'height=500,width=600,status=yes,toolbar=no,menubar=no,location=no,titlebar=yes,resizable=yes,scrollbars=yes,left='+x+',top='+y;
    //alert('RoleCode='+roleCode+', PostCode='+postcode+', Street='+street);
    window.open(url, '_blank', options);
}

// renders a popup to search for postcodes matching a locality
function openLocalityLookup(localityField, postcodeField) {
	var x = window.screenLeft;
	var y = window.screenTop+event.y-30;
	openLocalityLookup(x, y, localityField, postcodeField);
}

// renders a popup to search for postcodes matching a locality
function openLocalityLookup(x,y, localityField, postcodeField) {
   var localityFieldName = localityField.name;
   var postcodeFieldName = postcodeField.name;
   var locality = localityField.value;
   var postcode = postcodeField.value;
   var url = 'LocalityPopup.jsp?locality='+locality+'&postcode='+postcode+'&localityFieldName='+localityFieldName+'&postcodeFieldName='+postcodeFieldName;
   //alert('left='+x+',top='+y);
   var options='height=250,width=600,status=no,toolbar=no,menubar=no,location=no,titlebar=no,reasizable=yes,left='+x+',top='+y;
   top.open(url, null, options);
}

// renders a popup to search for postcodes matching a locality
function openFullLocalityLookupFull(localityField, postcodeField, stateField, countryField) {
	var x = window.screenLeft;
	var y = window.screenTop+event.y-30;
	openLocalityLookupFull(x, y, localityField, postcodeField);
}

// renders a popup to search for postcodes matching a locality
function openFullLocalityLookup(x,y, localityField, postcodeField, stateField, countryField) {
   var localityFieldName = localityField.name;
   var postcodeFieldName = postcodeField.name;
   var stateFieldName = stateField.name;
   var countryFieldName = countryField.name;
   var locality = localityField.value;
   var postcode = postcodeField.value;
   var state = stateField.value;
   var country = countryField.value;
   
   var url = 'LocalityPopup.jsp?locality='+locality+'&postcode='+postcode+'&state='+state+'&localityFieldName='+localityFieldName+'&postcodeFieldName='+postcodeFieldName
   	+'&stateFieldName='+stateFieldName+'&countryFieldName='+countryFieldName;
   //alert('left='+x+',top='+y);
   var options='height=250,width=600,status=no,toolbar=no,menubar=no,location=no,titlebar=no,reasizable=yes,left='+x+',top='+y;
   top.open(url, null, options);
}

function openHelpWindow(url) {
   window.open(url, null, 'height=300,width=400,status=no,toolbar=no,menubar=no,location=no,titlebar=no,scrollbars=yes,resizable=yes'); 
}

// common method to clear mail address fields
// called when pobox field is entered
function clearMailAddress() {

  if (document.form.MailingPOBox.value != null && document.form.MailingPOBox.value != '') {

    document.form.MailingShopNo.value = '';
    document.form.MailingBuilding.value = '';
    document.form.MailingStreetNo.value = '';
    document.form.MailingStreetName.value = '';
    document.form.MailingStreetType.value = '';
  }
}
