$(document).ready(function() {
   $("select").sexyCombo();
   $(window).unload( function () { SaveFormData(document.appform); } );
   LoadFormData(document.appform);
});

function validateFormOnSubmit(theForm) {
   var reason = "";
   reason += validateName(theForm.firstname, "first name");
   reason += validateName(theForm.lastname, "last name");
   reason += validateEmpty(theForm.address, "address");
   reason += validateName(theForm.city, "city");
   reason += validateZip(theForm.zip);

   //at least home phone or cell phone must be filled in
   var phone1 = validatePhone(theForm.cellphone);
   var phone2 = validatePhone(theForm.homephone);
   highlightField(theForm.cellphone, !((phone1==0 || phone2==0) && phone1!=2));
   highlightField(theForm.homephone, !((phone1==0 || phone2==0) && phone2!=2));
   if (phone1==1 && phone2==1) 
   {
      reason += "<li>Missing phone number.</li>";
      highlightField(theForm.cellphone, true);
      highlightField(theForm.homephone, true);
   }
   if (phone1==2)
   {
      reason += "<li>Cell phone number invalid. Make sure area code (e.g. <u>415</u>-555-1212) is included.</li>";
      highlightField(theForm.cellphone, true);
   }
   if (phone2==2)
   {
      reason += "<li>Home phone number invalid. Make sure area code (e.g. <u>415</u>-555-1212) is included.</li>";
      highlightField(theForm.homephone, true);
   }
   reason += validateEmail(theForm.email);

   //If either ememgency contact name or phone is populated, then BOTH MUST be populated
   var econtact = validateEmpty(theForm.econtact, "Emergency Contact Name");
   var ephone = validatePhone(theForm.ephone);
   if (econtact!="" && ephone==1)
   {
      highlightField(theForm.econtact, false);
      highlightField(theForm.ephone, false);
   }
   if (econtact!="" && (ephone==0 || ephone==2))
   {
      reason += econtact;
   }
   if (econtact=="" && ephone==1)
   {
      reason += "<li>Missing Emergency Contact Phone number.</li>";
      highlightField(theForm.ephone, true);
   }
   if (ephone==2)
   {
      reason += "<li>Emergency Contact number invalid. Make sure area code (e.g. <u>415</u>-555-1212) is included.</li>";
      highlightField(theForm.ephone, true);
   }
   if (econtact=="" && ephone==0)
   {
      highlightField(theForm.ephone, false);
   }

   //If either curent employer name or phone is populated, then BOTH MUST be populated
   var jobname = validateEmpty(theForm.jobname, "Current Employer Name");
   var jobphone = validatePhone(theForm.jobphone);
   if (jobname!="" && jobphone==1)
   {
      highlightField(theForm.jobname, false);
      highlightField(theForm.jobphone, false);
   }
   if (jobname!="" && (jobphone==0 || jobphone==2))
   {
      reason += jobname;
   }
   if (jobname=="" && jobphone==1)
   {
      reason += "<li>Missing Current Employer Phone number.</li>";
      highlightField(theForm.jobphone, true);
   }
   if (jobphone==2)
   {
      reason += "<li>Current Employer number invalid. Make sure area code (e.g. <u>415</u>-555-1212) is included.</li>";
      highlightField(theForm.jobphone, true);
   }
   if (jobname=="" && jobphone==0)
   {
      highlightField(theForm.jobphone, false);
   }

   if (reason != "") { jAlert("<p style='font-weight:bold;'>Some required fields need correction</p><ul>" + reason+"</ul>", "Validation Error"); return false; }
   return true;
}

function validateEmpty(fld, label) {
   var error = "";
   fld.value = trim(fld.value);
   if (fld.value.length == 0) error = "<li>Missing "+label+".</li>";
   highlightField(fld, error.length!=0);
   return error;  
}

function validateName(fld, label) {
   var error = "";
   var validChars = /^[a-z \.-]+$/i;
   fld.value = trim(fld.value);
   if (fld.value.length == 0) error = "<li>Missing "+label+".</li>";
   else if (!validChars.test(fld.value)) error = "<li>The "+label+" field contains illegal characters. Only A-Z, space, hyphen, and period are allowed.</li>";
   highlightField(fld, error.length!=0);
   return error;
}

function validateZip(fld) {
   var error = "";
   var validChars = /^[0-9]{5}(-[0-9]{4})?$/;    //U.S. zip codes are precisely 12345 or 12345-1234
   fld.value = trim(fld.value);
   if (fld.value.length == 0) error = "<li>Missing ZIP code.</li>";
   else if (!validChars.test(fld.value)) error = "<li>The zipcode is invalid. It must be in the form of the US Postal service zip+4 format where the last 4 digits are optional (e.g. 12345<span style='color:gray'>-1234</span>).</li>";
   highlightField(fld, error.length!=0);
   return error;
}

function validateEmail(fld) {
   var error="";
   var tfld = trim(fld.value);  // strip leading and trailing whitespace
   var validChars = /^[a-z0-9._-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i;
   if (fld.value.length == 0) error = "<li>Missing email address.</li>";
   else if (!validChars.test(tfld)) error = "<li>Email address invalid.</li>";
   highlightField(fld, error.length!=0);
   return error;
}

function validatePhone(fld) {
   var error = "";
   var stripped = fld.value.replace(/[^0-9]/g, '');  //remove ALL delimiters (e.g. non-numeric chars)
   stripped = stripped.replace(/^[10]+/, '');  //U.S. phone numbers NEVER begin with a zero or one
   if (stripped.length==0) return 1;
   else if (stripped.length != 10) return 2;  //All U.S. phone# (with area code) contain exactly 10 numeric chars
   fld.value = stripped.replace(/(.{3,3})(.{3,3})(.{4,4})/, '($1) $2-$3');  //reformat nicely
   return 0;
}

function trim(s) { return s.replace(/^\s+|\s+$/, ''); }
function highlightField(fld,enabled) { fld.style.borderColor = (enabled ? 'Red': ''); }
function capAllWords(obj) {    //<INPUT TYPE="TEXT" NAME="TESTER" onChange="capAllWords(this)"> onChange executes when focus is lost
   var val = trim(obj.value);
   if (val=='') { obj.value=val; return; }    //nothing to do
   if (obj.capped) { obj.value=val; return; } //capitalize only once
   obj.capped=true;
   val = val.split(' ');
   var newVal = '';
   for(var c=0; c < val.length; c++) {
      newVal += val[c].substring(0,1).toUpperCase() + val[c].substring(1,val[c].length).toLowerCase() + ' ';
   }
   obj.value = trim(newVal);
}

function FixPhone(fld) {
   var error = "";
   var stripped = fld.value.replace(/[^0-9]/g, '');  //remove ALL delimiters (e.g. non-numeric chars)
   stripped = stripped.replace(/^[10]+/, '');  //U.S. phone numbers NEVER begin with a zero or one
   if (stripped.length==0) { fld.value = ""; return; } //contains nothing
   if (stripped.length != 10) return;
   fld.value = stripped.replace(/(.{3,3})(.{3,3})(.{4,4})/, '($1) $2-$3');  //reformat nicely
}

//Agreement checkbox.

function OnAccepted(theForm) {
   if (theForm.accept.checked) theForm.accept.checked = validateFormOnSubmit(theForm);
   theForm.action = "Application_submit.php";
   theForm.submitapp.disabled = !(theForm.accept.checked);
}


function SaveFormData(form) {
   var v = $(form).serialize();
	Cookie("form_"+form.id, $(form).serialize());  //let cookie expire at end of browser session
}

function LoadFormData(form) {
	var formData = Cookie("form_"+form.id);
	if (formData != null)
	{
      $(form).deserialize(formData);
	}
} 

function Cookie(name, value, days) {
	// add cookie
	if (value)
	{
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+encodeURIComponent(value)+expires+"; path=/";
	}
	// delete cookie
	else if (days == -10000)
	{
		var date = new Date();
		date.setTime(date.getTime()-1);
		document.cookie = name+"=; expires="+date.toGMTString()+"; path=/";
	}
	// get cookie
	else
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return decodeURIComponent(c.substring(nameEQ.length,c.length));
		}
		return null;
	}
}


