// JavaScript Document


function validateZIP(field, label, action) {
	  //console.log('validateZip');
    var valid = "0123456789-";
    var hyphencount = 0;

    label = document.getElementById(label);
    field = document.getElementById(field);
    fieldVal = field.value;
    
    if((fieldVal.length == 0) && (action!="submit")) {
        //console.log('validateZip: 1 ' + field + ' - ' + action);
        label.className = '';
        field.focus();
        return false;
    } else {
        if ((fieldVal.length!=0) && (fieldVal.length!=5 && fieldVal.length!=10)) {
            //console.log('2');
            label.className = 'error';
            field.focus();
            return false;
        }
        for (var i=0; i < fieldVal.length; i++) {
            //console.log('3');
            temp = "" + fieldVal.substring(i, i+1);
            if (temp == "-") hyphencount++;
            if (valid.indexOf(temp) == "-1") {
                label.className = 'error';
                field.focus();
                return false;
            }
            if ((hyphencount > 1) || ((fieldVal.length==10) && ""+fieldVal.charAt(5)!="-")) {
                //console.log('4');
                label.className = 'error';
                field.focus();
                return false;
           }
        }
        label.className = 'valid';
        return true;
    }
}

function validateDate(field, label, action, showAlert)
{
    label = document.getElementById(label);
    field = document.getElementById(field);
    var fieldVal = field.value;
    var date;
    
    try
    {
        date = new Date(fieldVal);
    }
    catch(ex) {
        if (showAlert)
            alert("Invalid date format.");
        return false;
    }
    
    if (isNaN(date))
    {
        label.className = 'error';
        field.focus();
        if (showAlert)
            alert("Invalid date format.");
        return false;
    }
    else 
    {
        label.className = 'valid';
        return true;
    }
}    

function validateNumber(field, label, action)
{
    label = document.getElementById(label);
    field = document.getElementById(field);
    var fieldVal = field.value;

    if (!isInteger(fieldVal))
    {
        label.className = 'error';
        field.focus();
        return false;
    }
    else 
    {
        label.className = 'valid';
        return true;
    }
}

function validateNoHtml(field, label, errorMessage, action){
    label = document.getElementById(label);
    field = document.getElementById(field);
    errorMessage = document.getElementById(errorMessage);
    var fieldVal = field.value;  

    var regexString = '</?\\\w+((\\\s+\\\w+(\\\s*=\\\s*(?:".*?"|\'.*?\'|[^\'">\\\s]+))?)+\\\s*|\\\s*)/?>';

    var re = new RegExp(regexString);

    if (re.exec(fieldVal) && (action=="submit"))
    {
        label.className = 'error';
        errorMessage.style.display = 'inline';
        field.focus();
        return false;
    }
    else if (re.exec(fieldVal) && (action!="submit"))
    {
        label.className = 'error';
        errorMessage.style.display = 'inline';
        return false;
    }
    else
    {
        label.className = 'valid';   
        errorMessage.style.display = 'none';
        return true;
    }
}  


//
function validateRequired(field, label, action, showAlert) {
    //console.log('validateRequired');
    label = document.getElementById(label);
    field = document.getElementById(field);
    fieldVal = field.value;

    if((fieldVal.length == 0) && (action=="submit")) {
        //console.log('validateRequired: 1 '+ field.id + ' - ' + action);
        //label.className = 'error';
        if (!field.className.match('error'))
            field.className += ' error';
        field.focus();
        if (showAlert)
            alert("Missing required field.");
        return false;
    } else if((fieldVal.length == 0) && (action!="submit")) {
        //label.className = '';
        if(!field.className.match('error'))
            field.className += ' error';
        return false;
    } else {
        //label.className = 'valid';
        field.className = field.className.replace(' error', '');
        return true;
    }
}

function validatePhoneRequired(field, label, action, showAlert) {
    //console.log('validateRequired');
    label = document.getElementById(label);
    field = document.getElementById(field);
    fieldVal = field.value;
    
    if(((fieldVal.length == 0)||(fieldVal=='XXX-XXX-XXXX')) && (action=="submit")) {
        //console.log('validateRequired: 1 '+ field.id + ' - ' + action);
        label.className = 'error';
        field.focus();
        if (showAlert)
            alert("Phone number is not in the required format.");
        return false;
    } else if(((fieldVal.length == 0)||(fieldVal=='XXX-XXX-XXXX')) && (action!="submit")) {
        label.className = '';
        return false;
    } else {
        label.className = 'valid';
        return true;
    }
}

function validateSelectRequired(field, label, action) {
    //console.log('validateSelectRequired');
    label = document.getElementById(label);
    field = document.getElementById(field);
    fieldVal = field.options[field.selectedIndex].value;
    
    if((fieldVal == '-') && (action=="submit")) {
        //console.log('validateSelectRequired: 1 '+ field.id + ' - ' + action);
        label.className = 'error';
        field.focus();
        return false;
    } else if((fieldVal == '-') && (action!="submit")) {
        label.className = '';
        return false;
    } else {
        label.className = 'valid';
        return true;
    }
}


function validateEmail(field, label, action, showAlert) {
    //console.log('validateEmail');
    label = document.getElementById(label);
    field = document.getElementById(field);
    emailStr = field.value;

    /* The following variable tells the rest of the function whether or not
    to verify that the address ends in a two-letter country or well-known
    TLD.  1 means check it, 0 means don't. */

    var checkTLD=1;

    /* The following is the list of known TLDs that an e-mail address must end with. */

    var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;

    /* The following pattern is used to check if the entered e-mail address
    fits the user@domain format.  It also is used to separate the username
    from the domain. */

    var emailPat=/^(.+)@(.+)$/;

    /* The following string represents the pattern for matching all special
    characters.  We don't want to allow special characters in the address. 
    These characters include ( ) < > @ , ; : \ " . [ ] */

    var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";

    /* The following string represents the range of characters allowed in a 
    username or domainname.  It really states which chars aren't allowed.*/

    var validChars="\[^\\s" + specialChars + "\]";

    /* The following pattern applies if the "user" is a quoted string (in
    which case, there are no rules about which characters are allowed
    and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
    is a legal e-mail address. */

    var quotedUser="(\"[^\"]*\")";

    /* The following pattern applies for domains that are IP addresses,
    rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
    e-mail address. NOTE: The square brackets are required. */

    var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;

    /* The following string represents an atom (basically a series of non-special characters.) */

    var atom=validChars + '+';

    /* The following string represents one word in the typical username.
    For example, in john.doe@somewhere.com, john and doe are words.
    Basically, a word is either an atom or quoted string. */

    var word="(" + atom + "|" + quotedUser + ")";

    // The following pattern describes the structure of the user

    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");

    /* The following pattern describes the structure of a normal symbolic
    domain, as opposed to ipDomainPat, shown above. */

    var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");

    /* Finally, let's start trying to figure out if the supplied address is valid. */

    /* 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. */

                    field.className += ' error';
                    field.focus();
                    return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];

    // Start by checking that only basic ASCII characters are in the strings (0-127).

    for (i=0; i<user.length; i++) {
    if (user.charCodeAt(i)>127) {
                    field.className += ' error';
                    field.focus();
                    return false;
       }
    }
    for (i=0; i<domain.length; i++) {
    if (domain.charCodeAt(i)>127) {
                    field.className += ' error';
                    field.focus();
                    return false;
       }
    }

    // See if "user" is valid 

    if (user.match(userPat)==null) {

    // user is not valid

                    field.className += ' error';
                    field.focus();
                    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) {
                    field.className += ' error';
                    field.focus();
                    return false;
       }
    }
    return true;
    }

    // Domain is symbolic name.  Check if it's valid.
     
    var atomPat=new RegExp("^" + atom + "$");
    var domArr=domain.split(".");
    var len=domArr.length;
    for (i=0;i<len;i++) {
    if (domArr[i].search(atomPat)==-1) {
                    field.className += ' error';
                    field.focus();
                    return false;
       }
    }

    /* domain name seems valid, but now make sure that it ends in a
    known top-level domain (like com, edu, gov) or a two-letter word,
    representing country (uk, nl), and that there's a hostname preceding 
    the domain or country. */

    if (checkTLD && domArr[domArr.length-1].length!=2 && 
    domArr[domArr.length-1].search(knownDomsPat)==-1) {
                    field.className += ' error';
                    field.focus();
                    return false;
    }

    // Make sure there's a host name preceding the domain.

    if (len<2) {
                    field.className += ' error';
                    field.focus();
                    return false;
    }

    // If we've gotten this far, everything's valid!
                    field.className = field.className.replace(' error', '');
                    return true;
}

function validatePhone(field, label, action, showAlert) {
    //console.log('validatePhone');
    label = document.getElementById(label);
    field = document.getElementById(field);
    fieldVal = field.value;
    
    
    if(((fieldVal.length == 0)||(fieldVal=='XXX-XXX-XXXX')) && (action=="required")) {
        //console.log('validatePhone : 1 - ' + field + ' - ' + action);
        //label.className = 'error';
        if (!field.className.match('error'))
            field.className += ' error';
        field.focus();
        if (showAlert)
            alert("Phone number is not in the required format.");
        return false;
    } else if(((fieldVal.length == 0)||(fieldVal=='XXX-XXX-XXXX')) && (action!="required")) {
       //console.log('validatePhone : 2 - ' + field + ' - ' + action);
        //label.className = '';
        if (!field.className.match('error'))
            field.className += ' error';
        return true;
    } else {
        if (checkPhone(fieldVal)==false){
            //console.log('validatePhone : 1 - ' + field + ' - ' + action);
            //label.className = 'error';
            if (!field.className.match('error'))
                field.className += ' error';
            field.focus();
            return false;
	    } else {
	        //label.className = 'valid';
	        field.className = field.className.replace(' error', '');
            return true;
        }
    }
 
}


var digits = "0123456789";
var phoneNumberDelimiters = "()- ";
var minDigitsInIPhoneNumber = 10;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkPhone(strPhone){
    s=stripCharsInBag(strPhone,phoneNumberDelimiters);
    return (isInteger(s) && ((s.length >= minDigitsInIPhoneNumber)||(s.length == 0)));
}

function validatePhoneBlur(field, label) {
	//console.log('validatePhoneBlur');
	if((validatePhoneRequired(field, label)) && (validatePhone(field, label))){

		}	
		field = document.getElementById(field);
		fieldVal = field.value;
		if (fieldVal==''){
				field.value='XXX-XXX-XXXX';
				return false;
		}		

}
///////////////////////////////
//  THE FORMS  
///////////////////////////////

function validateLocation(thisForm) {
    //validate required
    if(validateRequired('locZipCode', 'locZipCodeLabel', 'submit')) {
        //validate individuals
        if(validateZIP('locZipCode', 'locZipCodeLabel', 'submit')) {
            console.log('VALID');
		    thisForm.action = '';
            thisForm.submit();
        } else {
            //console.log('NOT VALID');
            return false;
        }
    } else {
        return false;
    }
}

function validateCustomerCare(thisForm) {
    //validate required
    if(validateRequired('ReportZipCode', 'ReportZipCodeLabel', 'submit')) {
        //validate individuals
        if(validateZIP('ReportZipCode', 'ReportZipCodeLabel', 'submit')) {
            //console.log('VALID');
		    thisForm.action = '/locations/branches.aspx?zip=' + document.getElementById('ReportZipCode').value;
            thisForm.submit();
            return true;
        } else {
            //console.log('NOT VALID');
            return false;
        }
    } else {
        return false;
    }
}

function validatePresentationForm(thisForm) {
    //validate required
	//console.log('validatePresentationForm');
    if((validateRequired('schoolteacher', 'schoolteacherLabel', 'submit', true)) &&
       (validateRequired('schoolname', 'schoolnameLabel', 'submit', true)) &&
       (validateRequired('schooladdr', 'schooladdrLabel', 'submit', true)) &&
       (validateRequired('schoolcity', 'schoolcityLabel', 'submit', true)) &&
       (validateSelectRequired('schoolstate', 'schoolstateLabel', 'submit', true)) &&
       (validateRequired('schoolzip', 'schoolzipLabel', 'submit', true)) &&
       (validateRequired('schoolphone', 'schoolphoneLabel', 'submit', true)) &&
       (validateRequired('schoolemail', 'schoolemailLabel', 'submit', true)) &&
       (validateRequired('students', 'studentsLabel', 'submit', true)) &&
       (validateRequired('requestdate', 'requestdateLabel', 'submit', true)) &&
       (validateSelectRequired('requesttime', 'requesttime', 'submit', true)) &&
       (validateRequired('requestdate2', 'requestdate2Label', 'submit', true)) &&
       (validateSelectRequired('requesttime2', 'requesttime2', 'submit', true))) {
        //validate individuals
        if ((validateZIP('schoolzip', 'schoolzipLabel', 'submit', true)) &&
           (validateEmail('schoolemail', 'schoolemailLabel', 'submit', true)) &&
           (validateDate('requestdate', 'requestdateLabel', 'submit', true)) &&
           (validateDate('requestdate2', 'requestdate2Label', 'submit', true)) &&
           (validateNumber('students', 'studentsLabel', 'submit', true)) &&
           (validatePhone('schoolphone', 'schoolphoneLabel', 'required', true)) &&
           (validateNoHtml('Comments', 'Comments', 'nohtml', 'submit', true))) {
           //console.log('VALID');
		   thisForm.action = 'schedule_school_presentation_confirm.aspx';
           thisForm.submit();
        } else {
           //console.log('NOT VALID');
            return false;
        }
    } else {
		//console.log('NOT VALID');
        return false;
    }
}

function validateDiscountForm(thisForm) {
    //validate required
	//console.log('validatePresentationForm');
    if((validateRequired('firstNameTextBox2', 'firstNameTextBoxLabel2', 'submit')) && 
       (validateRequired('lastNameTextBox2', 'lastNameTextBoxLabel2', 'submit')) && 
       (validateRequired('address1TextBox2', 'address1TextBoxLabel2', 'submit')) && 
       (validateRequired('cityTextBox2', 'cityTextBoxLabel2', 'submit')) && 
       (validateSelectRequired('stateDropDown2', 'stateDropDownLabel2', 'submit')) && 
       (validateRequired('zipCodeTextBox2', 'zipCodeTextBoxLabel2', 'submit')) && 
       (validateRequired('phone1TextBox2', 'phone1TextBoxLabel2', 'submit')) && 
       (validateRequired('emailAddressTextBox2', 'emailAddressTextBoxLabel2', 'submit'))) {
        	//validate individuals
        	if((validateZIP('zipCodeTextBox2', 'zipCodeTextBoxLabel2', 'submit')) && 
           		(validateEmail('emailAddressTextBox2', 'emailAddressTextBoxLabel2', 'submit')) && 
           		(validatePhone('phone1TextBox2', 'phone1TextBoxLabel2', 'required'))) {
          	 	//console.log('VALID');
		   		thisForm.action = 'schedule_school_presentation_confirm.aspx';
           		thisForm.submit();
        	} else {
           		//console.log('NOT VALID');
           		return false;
       		}
    } else {
		//console.log('NOT VALID');
        return false;
    }
}


function validateSurveyForm(thisForm) {
    thisForm.action= "school_presentation_survey_confirm.aspx";
    thisForm.submit();
}
