//Global variables
var errmsg = "";
var isFocused = 0;
var fFld;

var msgEmpty = "Field can not be left blank.";
var msgEmptyName = "Name is required.";
var msgEmptyFirstName = "First Name is required.";
var msgEmptyLastName = "Last Name is required.";
var msgEmptyAddress = "Street address is required.";
var msgEmptyCity = "City is required.";
var msgEmptyState = "State is required.";
var msgEmptyZip = "Zip Code is required.";
var msgEmptyEmail = "Email is required.";
var msgEmptyPhone = "Phone is required.";
var msgEmptyPrimaryPhone = "Primary phone number is required.";
var msgEmptyHomePhone = "Home phone number is required.";
var msgEmptyAreaCode = "Area Code is required and should be 3 digits.";
var msgEmptyPhonePrefix = "Phone prefix should be 3 digits.";
var msgEmptyPhoneSuffix = "Phone suffix should be 4 digits.";
var msgEmptyCounty = "County is required.";
var msgEmptySSN = "Social Security Number is required.";
var msgEmptyDescription = "Description is required.";
var msgEmptyDirections = "Directions are required.";
var msgEmptyBlocksOfEnergy = "You must enter how many blocks of energy you wish to sign up for.";

var msgInvalid = "Field is invalid.";
var msgInvalidAddress = "Address is invalid.";
var msgInvalidCity = "City is invalid.";
var msgInvalidState = "State is invalid.";
var msgInvalidZip = "Zip code is invalid.";
var msgInvalidEmail = "Email address is invalid.";
var msgInvalidSSN = "Social Security Number is invalid.";
var msgInvalidPhone = "Phone number is invalid.";
var msgInvalidAreaCode = "Area Code must be a 3 digit number.";
var msgInvalidCounty = "County is invalid.";
var msgInvalidNumber = "Invalid character, only numbers are valid.";

var msgIncompletePhone = "Phone number is incomplete.";
	
//Functions	
function validTextField(textfld) {
//Only allow letters of alphabet and certain special characters.
	return (textfld.value.search(/^[a-z,\-]+$/)==-1)? false: true;
}
function validPhoneNumber(numberfld) {
	return (numberfld.value.search(/^[0-9,\-,(,),\s]+$/)==-1)? false: true;
}
function validZipCode(zipfld) {
	return (zipfld.value.search(/^[0-9,\-]+$/)==-1)? false: true;
}
function validSSN(textfld) {

	if (textfld.value.search(/^[0-9]{3}\-*[0-9]{2}\-*[0-9]{4}$/)==-1) {
		return false;
	} 

	if (textfld.value.length == 9 || textfld.value.length == 11) {
		return true;
	}
	return false;
}

function validLongPhone(phonefld){
	if (phonefld.value.search(/^[0-9,\-,(,),\s]+$/)==-1) return false;
	if (trimString(phonefld.value).length < 10) return false;
	return true;
}
function emptyField(field) {
	return  (trimString(field.value).length == 0) ? true : false;
}
function questionAnswered(userResponse){
	var answer;
	for (var i = 0; i < userResponse.length; i++) {     	
		if ( userResponse[i].checked) {
			return true; 			  
		}
	}
	return false;
}
function setFocus(focusFld) {
	if ( ! isFocused ) {
	     fFld = focusFld;
	     isFocused = 1;
	}
}
function trimString(userInput){      
	var iStart, iEnd;      
	var sTrimmed;      
	var cChar;      
	iEnd = userInput.length;      
	iStart = 0;      
	bLoop = true;      
	cChar = userInput.charAt(iStart);      
//alert(userInput)		
	while ((iStart < iEnd) && 
				((cChar == "\n") || 
				(cChar == "\r") ||                                
				(cChar == "\t") || 
				(cChar == " "))) {     
//alert("cChar " + cChar)				    
		iStart ++;      
		cChar = userInput.charAt(iStart);      
	}      
		
	cChar = userInput.charAt(iEnd); 
	while ((iEnd >= 0) && 
				((cChar == "\n") || 
				(cChar == "\r") ||                            
				(cChar == "\t") || 
				(cChar == " "))) {         
//alert("cChar " + cChar)				    
		iEnd --;         
		cChar = userInput.charAt(iEnd);      
	}      
		
	if (iStart < iEnd){         
		sTrimmed = userInput.substring(iStart, iEnd + 1);      
	} else {         
		sTrimmed = "";      
	}      
//alert(sTrimmed.length);
	sTrimmed = ltrim(sTrimmed)
	sTrimmed = rtrim(sTrimmed)
//alert(sTrimmed.length);
	return sTrimmed;   
}
function cancel(strLocation) {
	if (confirm("Are you sure you wish to cancel?\nAll of your changes will be lost.\n\nClick OK to discard changes or Cancel to continue entering data.")) {
		window.document.location = strLocation;
	}
}

function rtrim(argvalue) {

  while (1) {
    if (argvalue.substring(argvalue.length - 1, argvalue.length) != " ")
      break;
    argvalue = argvalue.substring(0, argvalue.length - 1);
  }

  return argvalue;
}

function ltrim(argvalue) {

  while (1) {
    if (argvalue.substring(0, 1) != " ")
      break;
    argvalue = argvalue.substring(1, argvalue.length);
  }

  return argvalue;
}

	
function validateZIP(field) {
var valid = "0123456789-";
var hyphencount = 0;

if (field.length!=5 && field.length!=10) {
	alert("Please enter your 5 digit zip code.");
	return false;
}
for (var i=0; i < field.length; i++) {
	temp = "" + field.substring(i, i+1);
	if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			alert("The hyphen character should not be used with your zip code.   Please try again.");
			return false;
   		}
	}
	return true;
}
	
function isValidEmail(emailStr) {
var emailPat=/^(.+)@(.+)$/
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
var validChars="\[^\\s" + specialChars + "\]"
var quotedUser="(\"[^\"]*\")"
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
var atom=validChars + '+'
var word="(" + atom + "|" + quotedUser + ")"
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	return false;
}
var user=matchArray[1]
var domain=matchArray[2]
// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
   return false;
}
/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	       return false;
	    }
    }

}
// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
        return false;
}
/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   return false;
}
// Make sure there's a host name preceding the domain.
if (len<2) {
   return false;
}
// If we've gotten this far, everything's valid!
   return true;
}


function isAlphaOnly(curtext) {
		  var valtext = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .-";
		  var tvar;

		  curtext = "" + curtext;
		  for ( var i = 0 ; i < curtext.length ; i++ ) {
		    tvar = "" + curtext.substring(i,i+1); 
		    if ( valtext.indexOf(tvar) < 0 ) {
		      return true;
		    }
		  }
		  return false;
		}  	

var isNN = (navigator.appName.indexOf("Netscape")!=-1);

function autoTab(input,len, e) {
	var keyCode = (isNN) ? e.which : e.keyCode; 
	var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
	if(input.value.length >= len && !containsElement(filter,keyCode)) {
		input.value = input.value.slice(0, len);
		input.form[(getIndex(input)+1) % input.form.length].focus();
}

function containsElement(arr, ele) {
var found = false, index = 0;
while(!found && index < arr.length)
if(arr[index] == ele)
found = true;
else
index++;
return found;
}

function getIndex(input) {
var index = -1, i = 0, found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input)index = i;
else i++;
return index;
}
return true;
}

function dateValid(objName) {
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	//strDate = datefield.value;
	strDate = objName;
	if (strDate.length < 1) {
		return true;
	}
	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) {
				err = 1;
				return false;
			}else{
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
		}
	}
	if (booFound == false) {
		if (strDate.length>5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
	}
	//Adjustment for short years entered
	if (strYear.length == 2) {
		strYear = '20' + strYear;
	}
	strTemp = strDay;
	strDay = strMonth;
	strMonth = strTemp;
	intday = parseInt(strDay, 10);
	if (isNaN(intday)) {
		err = 2;
		return false;
	}
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) {
			err = 3;
			return false;
	   }
	}
	intYear = parseInt(strYear, 10);
	if (isNaN(intYear)) {
		err = 4;
		return false;
	}
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
		err = 6;
		return false;
	}
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
		err = 7;
		return false;
	}
	if (intMonth == 2) {
		if (intday < 1) {
			err = 8;
			return false;
		}
		if (LeapYear(intYear) == true) {
			if (intday > 29) {
				err = 9;
				return false;
			}
		}else{
			if (intday > 28) {
				err = 10;
				return false;
			}
	   }
	}
	return true;
}

function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	}else {
		if ((intYear % 4) == 0) { return true; }
	}
	return false;
}
// Scott Wilson 06-20-2003 Added these three functions below as part of fix to not
// allow periods in phone numbers

function isBlank(val){
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
		}
	return true;
	}
function isDigit(num) {
	if (num.length>1){return false;}
	var string="1234567890";
	if (string.indexOf(num)!=-1){return true;}
	return false;
	}

function isInteger(val){
	if (isBlank(val)){return false;}
	for(var i=0;i<val.length;i++){
		if(!isDigit(val.charAt(i))){return false;}
		}
	return true;
	}

