///////////////////////////////////////////////////////
// JavaScript form validation functions script.  
///////////////////////////////////////////////////////
function isBlank(Ctrl) {  // returns true if blank   
   if (Ctrl.value.length < 1) return true;
   else if (isEmpty(Ctrl.value)) return true;
   return false; }
function isEmpty(s) { // prevents entering empty strings
   for (var i = 0; i < s.length; i++) {
      var c = s.charAt(i);
      if ((c != ' ') && (c != '\n') && (c != '\t')) return false; 
   }
   return true; }
function isSpacey(Ctrl) { // true if string has spaces, return, or tab
    var s = Ctrl.value;
   for (var i = 0; i < s.length; i++) { var c = s.charAt(i);
      if ((c == ' ') || (c == '\n') || (c == '\t')) return true; }
   return false; }
function isTooShort(Ctrl,num) {
   if (Ctrl.value.length < num) return true;
   return false; }
function isTooLong(Ctrl,num) {
   if (Ctrl.value.length > num) return true;
   return false; }
function isIndexOf(Ctrl,str) { // returns true if substring found in string
   if (Ctrl.value.indexOf(str) > -1) return true;
   return false; }
function isNotANumber(Ctrl) {  // returns true if not a number
   if (isNaN(Ctrl.value)) return true;
   return false; }
function isChecked(Ctrl) {
   if (Ctrl.checked) return true;
   return false; }
function isCheckedByLength(Ctrl) {   // for multiple checkboxes with same name
   var boxIsChecked = false;
   for (i=0; i < Ctrl.length; i++) { if (Ctrl[i].checked) { boxIsChecked = true; break; }}
   return boxIsChecked; }
function isSelected(Ctrl, index){  // returns true if the index indicated is selected
   if (Ctrl.options[index].selected) return true;
   return false; }
function isSelectedOrHigher(Ctrl, upLimit){ // works with numerically-valued select options only!
   var ctrlValue = Ctrl.options[Ctrl.selectedIndex].value;
   if (ctrlValue == 0) return true;
   else if (ctrlValue > upLimit) return true;
   return false; }
function isSelectedRange(Ctrl, loLimit, upLimit){ // works with select options
   if ((Ctrl.selectedIndex >= loLimit && Ctrl.selectedIndex < upLimit)) return true;
   return false; }
function checkZip(Ctrl) {  // returns true if *not* properly formatted zip code
   zipString = Ctrl.value;
   if (zipString.length == 5) {
      if (isNaN(zipString)) return true;
   } else if (zipString.length < 5) {
      return true;
   } else if ( 
      zipString.length < 10 ||
      isNaN( zipString.substring(0,5) ) || 
      isNaN( zipString.substring(6,10) ) ||
      (zipString.substring(5,6) != '-') ) {
         return true;
   } 
   return false;
}   // end checkZip()
function checkUSPhone(Ctrl) {  // returns true if properly formatted US phone number - 7 digits
	phoneString = Ctrl.value;
	if (phoneString.length == 7) {
		if (isNaN(phoneString)) return true;
	}else return true;	
	//var s = onlyNumbers(Ctrl.value);
	//return (s.length == 7);
}   // end checkUSPhone()

function checkUSAreaCode(Ctrl) {  // returns true if properly formatted US areacode - 3 digits
	areacodeString = Ctrl.value;
	if (areacodeString.length == 3) {
		if (isNaN(areacodeString)) return true;
	}else return true;
	//var s = onlyNumbers(Ctrl.value);
	//return (s.length == 3);
}   // end checkUSAreaCode()

function testSimpleEmail(Ctrl){  // returns true if invalid email
   var err=0;
   emailString = Ctrl.value;
   if (window.RegExp) {
      var regexEmail = /^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/;
      return !regexEmail.test(emailString);
   } else {
      if (emailString.indexOf("@",1) == -1) err=1;  // need @ symbol
      if (emailString.indexOf("@",1) != emailString.lastIndexOf("@")) err=1;  // only one @ symbol
      if (emailString.indexOf(".",3) == -1) err=1;  // need at least one "."
      if (emailString.lastIndexOf(".") == (emailString.length-1)) err=1;  // can't end with a "."
      // check length
      if (err==0) {
         var at = (emailString.indexOf("@"))+1;
         var lastDot = (emailString.lastIndexOf("."))+1;
         // test to make sure there's at least one character between "at" and "lastDot"
         if (lastDot - at == 1) err=1;
      }
   }
   if (err==1) return true;
   return false;
}   // end testSimpleEmail()

function isCCNumber(Ctrl) {
   var cnum = onlyNumbers(Ctrl.value);
   var lgth = cnum.length;

   if (lgth > 19) return false;
   else if (lgth < 15) return false;
   else {
      // validate number
      tally = 0; multTemp = 0; 
      lengthCheck = lgth % 2;
      if (lengthCheck == 0) { counter = 2; } else { counter = 1; }
      
      for (i = 0; i < lgth; i++) {
         tempNumb = parseInt(cnum.charAt(i));
         multTemp = tempNumb * counter;
         if (multTemp >= 10) {
            multTemp2 = parseInt(multTemp.charAt(0)) + parseInt(multTemp.charAt(multTemp.length));
            multTemp = multTemp2;
         }
         tally += multTemp; multTemp = 0;
         if (counter == 1) counter = 2; else counter = 1;
      }
      if (tally % 10 != 0) return false;
   } 
   return true;
}     
function onlyNumbers(str) {
	// clean number
	if (window.RegExp) return str.replace(/[^0-9]*/g,"");
	else {
		var a = '';  var allnum =  '1234567890';
		for (var i = 0; i < str.length; i++) {
			var c = str.charAt(i);
			if (allnum.indexOf(c) > -1) a += c;
		}
	}
	return a;
}

function checkDateWSlash(Ctrl) {
   var err=0;
   a = Ctrl.value;
   var firstSlash=(a.indexOf("/")) + 1;
   var secondSlash=(a.lastIndexOf("/")) + 1;   
   if (a.length != secondSlash+4) err=1;         // four-digit year
   if (err == 0) {
      // set date variables for testing
      b = a.substring(0, firstSlash-1);             // month
      c = a.substring(firstSlash-1, firstSlash);    
      d = a.substring(firstSlash, secondSlash-1);    // day      
      e = a.substring(secondSlash-1, secondSlash); 
      f = a.substring(secondSlash, secondSlash+4); // year      
      if (isNaN(b)) err=1;
      if (isNaN(d)) err=1;
      if (isNaN(f)) err=1;      
      if (d.indexOf("/") != -1) err=1;
      if (b<1 || b>12) err=1;
      if (c != '/') err=1;
      if (d<1 || d>31) err=1;
      if (e != '/') err=1;
      if (f<1800 || f>2500) err=1;  // valid year range
      if ((b==4 || b==6 || b==9 || b==11) && d==31)  err=1;
      if (b==2) {                     // February
          var g=parseInt(f/4);
          if (isNaN(g)) err=1;
          else if (d>29) err=1;
          else if (d==29) {
            /* Leap year rules: the year is a leap year if it is divisible by 4, e.g. 1960 
               UNLESS divisible by 100 - it is not a leap year, e.g. 1900
               UNLESS divisible by 400 - it is a leap year, e.g. 2000 */
            var isDivBy4   = (f %   4 == 0) ? true : false;
            var isDivBy100 = (f % 100 == 0) ? true : false;
            var isDivBy400 = (f % 400 == 0) ? true : false;
            if (!isDivBy4) err = 1;
            if (isDivBy100 && !isDivBy400) err = 1;
          } 
      }
   }
   if (err==1) return true;
   return false; 
} // end checkDateWSlash()

function errorAlert(e) {
    // If ErrorString "e" has content, there was at least one error; let them know.
   if (e.length > 0) {
      msg  = "____________________________________________________\n\n";
      msg += "  The form was not submitted for the following reason(s): \n";
      msg += "____________________________________________________\n";
      alert(msg + e);
      return false;
   } 
   return true;
} // end errorAlert()



/*function Verify(f) {
   // set up params
   var ErrorString  = "";
	if (isBlank(f.companyname)) ErrorString += "\n - Your Company Name is required";
	
	if (isBlank(f.meetingobjective)) ErrorString += "\n - Your Meeting Objective is required";
	
	if (isBlank(f.name)) ErrorString += "\n - Your Name is required";
	
	if (isBlank(f.address)) ErrorString += "\n - Your Address is required";
	
	if (isBlank(f.city/state/zip)) ErrorString += "\n - Your City, State, and Zipcode are required";
	
	if (isBlank(f.phone)) ErrorString += "\n - Your Phone is required";
	
	if (isBlank(f.email)) ErrorString += "\n - Your e-mail address is required";
    else if (!isBlank(f.email) && testSimpleEmail(f.email)) ErrorString += "\n - Your e-mail address is formatted improperly";
   
	
   return errorAlert(ErrorString);
}*/


function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);
 
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
 
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
 
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}
 
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_validateForm() { //v4.0
  var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
      if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
        if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
      } else if (test!='R') { num = parseFloat(val);
        if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
        if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
          min=test.substring(8,p); max=test.substring(p+1);
          if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
    } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  } if (errors) alert('The following error(s) occurred:\n'+errors);
  document.MM_returnValue = (errors == '');
}

function Verify(f) {
   // set up params
   var ErrorString  = "";

	if (isBlank(f.companyname)) ErrorString += "\n - Your Company Name is required";
	if (isBlank(f.meetingobjective)) ErrorString += "\n - Your Meeting Objective is required";
	if (isBlank(f.name)) ErrorString += "\n - Your Name is required";
	if (isBlank(f.address)) ErrorString += "\n - Your Address is required";
	if (isBlank(f.city)) ErrorString += "\n - Your City is required";
	if (isBlank(f.state)) ErrorString += "\n - Your State is required";
	if (isBlank(f.zip)) ErrorString += "\n - Your Zipcode is required";
	 else if (!isBlank(f.zip) && checkZip(f.zip)) ErrorString += "\n - Your zip code is formatted improperly";
	if (isBlank(f.phone)) ErrorString += "\n - Your Phone is required";
	if (isBlank(f.email)) ErrorString += "\n - Your e-mail address is required";
     else if (!isBlank(f.email) && testSimpleEmail(f.email)) ErrorString += "\n - Your e-mail address is formatted improperly";

    if (isBlank(f.howhear) || (f.howhear.value == "Other" && isBlank(f["howhear-other"]))) {
        ErrorString += "\n - Please tell us how you heard about us";
    }
    
    if (!isBlank(f.date1) && checkDateWSlash(f.date1)) {
        ErrorString += "\n - Please enter a valid date";
    }
    if (!isBlank(f.date2) && checkDateWSlash(f.date2)) {
        ErrorString += "\n - Please enter a valid date";
    }
    if (!isBlank(f.date3) && checkDateWSlash(f.date3)) {
        ErrorString += "\n - Please enter a valid date";
    }
   return errorAlert(ErrorString);
}

$(document).ready(function() {
    function howHearOther() {
        if ($("#howhear").val() == "Other") {
            $("#howhear-other").css("display", "block");
        } else {
            $("#howhear-other").css("display", "none");
        }
    }
    $("#howhear").change(function() {
        howHearOther();
    });

    howHearOther();
});


