<!--
/*
   This script validates all fields on a screen
   
   it is generalized by using the html class attribute to specify what validation
   is to be done for a given input or select tag.
   
   As each field is entered, individual validation is done on that field on the spot
   
   The submit button causes all fields to once again be validated (as the user might
   have skipped over a required field when doing the input).
   
   The submit button is coded with onclick=checkAllFields('funcname') where 'funcname' is
   the name of the javascript function to be performed when all fields have been determined
   to be valid.
   
   This function can do anything you like, but the most common use of it is to launch a
   php program using asynchronous Ajax which then processes the form data as needed
   
   An example is the credit card input form for processing thru authorize.net. It
   calls js function sendAuthNetTran which formats the fields on the input screen to
   be sent as $_POST data to the php program, just as if the action="xxx" attribute were used on the
   <form> tag, but in this case you get form validation before it is sent to php.
   
   The following are the "class" values currently recognized and what validation they cause to
   occur:
   
   class name value                description of validation
   
   reqd                            required field. Ensures something was entered
   optional                        field is optional, but if entered may have aditional
                                   validation to be performed (eq, )
   email                           ensures value entered is a valid e mail address format
   zip                             ensures it is a valid US zip code either as 12345 or 12345-1234
   cc                              ensures it is either 13 or 16 digit number and all numeric
                                   (note: logic to allow "-" format is there but commented out. If using
                                   this format you must add a '-' to the variable validChars)
   numeric                         field must be numeric
   fut                             future date - if date is say mm/yyyy format ensures this date is not in the
                                   past (eq, if today i Aug 27,2010, then 08/2010 would be valid, but 07/2010 would not)
   
   All are required (except for address line 2) and some have additional validation when
   entered. The validation that is needed for a given field is
   driven by the contents of the "class" field.
   
   Initially this function was set up to validate credit card information and had, as an example
   the following classes assigned to the following fields:
   
   The specifics are as follows:
   
   Field                     Required? (reqd)        Additional Validation Class
   
   First Name                 Yes
   Last Name                  Yes
   E mail Address             Yes                    email
   Address Line 1             Yes
   Address Line 2             ---
   City                       Yes
   State                      Yes                   (dropdown)
   Zip                        Yes                    zip (US only)
   Credit Card Number         Yes                    cc (format only)
   Expiration Month           Yes                   (dropdown) fut - must be in the future
   Expiration Year            Yes                   (dropdown) fut - must be in the future
   Security Code              Yes                    numeric - must be numeric
   
   
   There are up to 2 levels of validation on a given field:
   1) Required (coded on class as "reqd")or optional (coded as "optional")
   2) Specific validation for that field (also coded on the class
      attribute after "reqd" or "optional"). This drives all the validation.
   
   Notification to the user is done by use of the "invalid" CSS class which has the CSS for
   pointing out the field in error, as well as a span tag associated with the field,
   which has an ID equal to the ID of the field prefixed by an "s". This is how the Javascript
   knows where to place the error message.
   
   Both <input> tags and <select> tags are scanned and validated.
   
   It is invoked on a single field when leaving the field (onblur)
   and on all fields when form is submitted (as onblur will not catch
   those fields that were completely skipped)
   
   It loops through each type of tag, checking to see what validation is
   needed for that field (if any) based on the contents of the "class" attribute.
   
   When done with all validation, if any errors were found, Javascript
   returns "false" to prevent submitting the form until all errors are
   corrected
*/
//
//     Program constants that are changeable
//
var invalidClass = " invalid";
var goodMsg = "Congratulations! All fields were properly entered!";
var reqdMsg = "<img src=\"/images/cross.png\"/>";
var reqdMsgDealer = "Field is mandatory";
var numericMsg = " Field must be numeric";
var negnumMsg = " Field cannot be negative";
var emailMsg = " Invalid e mail format";
var zipMsg = " Invalid ZIP Code format";
var ccMsg = "Invalid credit card format";
var expMsg = "Expiration must be a valid date not in the past";
var expMonthMsg = "Expiration month is invalid";
var amtMsg = "Must be a valid dollar amount";
var lenMsg = "Length should not be more than 20 Characters!";
var validCardLengthOldVisa = 13;
var validCardLength = 16;
var validCardLengthAmex = 15;
var loginid_validation="Special characters '/:,;^!%#$&*(){}<>[]?'\"' and white space not allowed.";
//
//    this controls the return value of true or false
//    sent back by this routine when it terminates after
//    validating all fields.
//    true = no errors
//    false = one or more errors
//
var allGood = true;

//
//   once page is loaded, set up event handlers and
//   expiration year drop down
//
window.onload = setUp;
//
//
function setUp () {
/*
    var inputField = $$("input","select","textarea");
    for (var i=0;i<inputField.length;i++) {
        if (inputField[i].name !== "") {
            inputField[i].onblur = checkOneField;
        }
    }
*/
//    document.onsubmit = checkAllFields;

//
//   build drop down menu for expiration year for current
//   and next 10 years. This makes it easier for user to
//   enter and simplifies validation (as you know it is valid)
//
/*
    var now = new Date();
    var thisYear = now.getFullYear();
    var expYearSelect = $(expYearId);
    for (i=0;i<=10;i++) {
        addOption(expYearSelect,thisYear+i,thisYear+i);
    }
*/
}
//
//     this is the event handler for a single input or select field
//     and is triggered by the onblur event
//
function checkOneField(thisButton) {
// alert("Entering checkOneField");
    allGood = true;
    validField(thisButton);
//
//   if this field is in error, blank out the "good message"
//   in case it was just displayed and now it is no longer true
//
    if (!allGood) {
        $("goodmsg").innerHTML = "";
    }
    return allGood;
}
//
//    this is the event handler when the form is submitted
//    it uses the same routines that are used when an individual
//    field is triggered, but loops through all input and select tags
//    where a "name=" attribute is present (avoids trying to validate
//    things like the submit button)
//
//    it returns global variable allGood which determines if the
//    form should be submitted (true=no errors) or if there are one
//    or more errors (false) and the form is not to submitted
//
function checkAllFields(thisButton) {
 //  alert(thisButton+"inside check all fields two "+thisButton.form.name);
    allGood = true;
    var allTags = $$("input","select","textarea");

    for (j=0;j<allTags.length;j++) {
	
        if(allTags[j].form)
		{
		if (allTags[j].type !== "hidden" && allTags[j].name !== "" && allTags[j].disabled == "" && allTags[j].form.name == thisButton.form.name ) {
            validField(allTags[j]);
        }
		}
    }
    
//
//   if no errors at all when page submitted, display a message for user
//   to that effect
//
//   This code now disabled
/*

    if (allGood) {
        $("goodmsg").innerHTML = goodMsg;
//        eval(allGoodFunc +'()');
    }
    else {
        $("goodmsg").innerHTML = "";
    }
*/    
    return allGood;
}
//
//    this function does all the validation for a single field
//
//    first it checks to see if the field is required and does that
//    validation on the spot
//
//    if it is required and it is present, it proceeds to determine and
//    perform any further validation required for this field
//

function validField(thisTag) {
//    alert("Entering validField");
//
//   reset class and error message in case it was in error earlier and now is correct
//

    var thisFieldOk = true;

    var parentTag = $("l" + thisTag.id);
  //  alert("parent tag id = l" + thisTag.id);
    thisTag.className = thisTag.className.replace(invalidClass,"");
    parentTag.className = parentTag.className.replace(invalidClass,"");
    $("s" + thisTag.id).innerHTML = "";
//
//    check if required field based on class "reqdDealer"
//
 if (thisTag.className.indexOf("reqDealer") > -1) {
        if (thisTag.value == "" || thisTag.value.substr(0,1) == " ") {
            flagField(thisTag,reqdMsgDealer);
            thisFieldOk = false;
        }
    }
//    check if required field based on class "reqd"
   if (thisTag.className.indexOf("reqd") > -1) {
        if (thisTag.value == "" || thisTag.value.substr(0,1) == " ") {
            flagField(thisTag,reqdMsg);
            thisFieldOk = false;
        }
    }
	
    if (thisFieldOk) {
//
//    we have determined that the field is filled in, now check for any further criteria based on class
//
//           this switch statement uses the value of the 2nd (if any) class value
//           to see if further validation is to be done
//
//           it either does the validation (if it is simple) or
//           invokes the correct function for this type of
//           validation.
//
//           Based on the result of this, if the field is invalid,
//           it invokes the error handler which changes the class
//           to highlight the field and also displays an error message
//           regarding the specific error encountered
//
        var fieldType = thisTag.className.split(" ");
        switch (fieldType[1]) {
            case "numeric":
                if(isNaN(thisTag.value)) {
                    flagField(thisTag,numericMsg);
                }
                if(parseInt(thisTag.value) < 0) {
                    flagField(thisTag,negnumMsg);
                }
                break;
            case "email":
                if (!validEmail(thisTag.value)) {
                    flagField(thisTag,emailMsg);
                }
                break;
            case "zip":
                if (!validZIP(thisTag.value)) {
                    flagField(thisTag,zipMsg);
                }
                break;
            case "cc":
                if (!validCC(thisTag.value)) {
                    flagField(thisTag,ccMsg);
                }
                break;

			case "exp":
                if (!validFutureDate(thisTag.value)) {
                    flagField(thisTag,expMsg);
				}
				break;
			
			case "numlen":
				if(isNaN(thisTag.value)) {
                    flagField(thisTag,numericMsg);
                }
                if(parseInt(thisTag.value) < 0) {
                    flagField(thisTag,negnumMsg);
                }
                if (!maxlength(thisTag.value)) {
                    flagField(thisTag,lenMsg);
                }
                break;
				
			
            case "integer":
                if(isNaN(thisTag.value)) {
                    flagField(thisTag,numericMsg);
                }
                if(parseInt(thisTag.value) < 0) {
                    flagField(thisTag,negnumMsg);
                }
				var check_index=thisTag.value;
				if(check_index.indexOf('.') >=0) {
                    flagField(thisTag,numericMsg);
				}

                break;
				
				
			case "length":
                if (!maxlength(thisTag.value)) {
                    flagField(thisTag,lenMsg);
                }
                break;
				
			case "loginid_validation":
			if (!validateLogin(thisTag.value)) {
                    flagField(thisTag,loginid_validation);
                }
                break;
				
            default:
                break;
        }
    }
    return allGood;
}
//

//this function validates the login id for spaces, special characters
function validateLogin(login)
{

    var invalidChars = " /:,;^!%#$&*(){}<>[]?'\"";
	  for (var k=0; k<invalidChars.length; k++) {
                var badChar = invalidChars.charAt(k);
                if (login.indexOf(badChar) > -1) {
				
                        return false;
                }
        }
		return true;
}
//End

//        this function validates the format of the e mail address
//        it is basically a reasonableness test. It does not verify
//        that the email address exists, only that the format conforms
//        to the basic standards of an e mail address
//
function validEmail(email) {
        var invalidChars = " /:,;^!%#$&*(){}<>[]?'\"";
 //
 //     e mail is now optional - it is only validated if it was entered
 //
        if (email == "") {
            return true;
        }
		
		var at_count = email.split(/@/g).length - 1;
		if(at_count > 1 )
		return false;
		
        for (var k=0; k<invalidChars.length; k++) {
                var badChar = invalidChars.charAt(k);
                if (email.indexOf(badChar) > -1) {
                        return false;
                }
        }
        var atPos = email.indexOf("@",1);
        if (atPos == -1) {
                return false;
        }
        if (email.indexOf("@",atPos+1) != -1) {
                return false;
        }
        var periodPos = email.indexOf(".",atPos);
        if (periodPos == -1) {	
                return false;
        }
        if (periodPos+3 > email.length)	{
                return false;
        }
        return true;
}
//
//       this function validates the ZIP code
//
//       only a US zip code is validated here
//
//       allows both a 5 digit and a 9 digit zip code (with a "-" after
//       the first 5 digits)
//
function validZIP(field) {
    var valid = "0123456789-";
    var hyphencount = 0;

    if (field.length!=5 && field.length!=10) {
        return false;
    }
    for (var i=0; i < field.length; i++) {
        temp = "" + field.substring(i, i+1);
        if (temp == "-"){
            hyphencount++;
        }    
        if (valid.indexOf(temp) == "-1") {
            return false;
        }
        if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
            return false;
           }
    }
    return true;
}
//
//function to check max length of fields
//right now checking promo code field length 
//which should be less than 20
//
function maxlength(field)
{
if(field.length>20)
return false;
else
return true;
}


//
//             this function performs very rudimentary
//             checks on the credit card number
//
//             verifies that it is a 16 digit number with "-"
//             in the right places, that's all. No check digit
//             calculation is performed
//
function validCC(ccNum) {
        var validChars = "0123456789";
        var cardType;
        ccNumLength = ccNum.length;
        ccNumOne = parseInt(ccNum.substring(0,1),10);
        ccNumTwo = parseInt(ccNum.substring(0,2),10);
        ccNumFour = parseInt(ccNum.substring(0,4),10);
        ccNumLast = parseInt(ccNum.charAt(ccNumLength-1));
        if (ccNumOne == 4) {
            cardType = "visa";
        }
        else {
            if (ccNumTwo >= 51
                      &&
                ccNumTwo <= 55) {
                cardType = "mc";
            }
            else {
                if (ccNumTwo == 34 || ccNumTwo == 37) {
                    cardType = "amex";
                }
                else {
                    if (ccNumFour == 6011) {
                        cardType = "discover";
                    }
                    else {
                      return false;
                    }
                }
            }
        }
        switch (cardType) {
            case "mc":
            case "discover":
                if (ccNumLength != validCardLength) {
                    return false;
                }
                break;
            case "amex":
                if (ccNumLength != validCardLengthAmex) {
                    return false;
                }
                break;
            case "visa":
                if (ccNumLength != validCardLength
                              &&
                    ccNumLength != validCardLengthOldVisa) {
                    return false;
                }
                break;
            default:
                return false;
        }
        for (var k=0; k<ccNum.length; k++) {
                var thisChar = ccNum.charAt(k);
                if (validChars.indexOf(thisChar) == -1) {
                        return false;
                }
//    now calculate check digit and verify it is correct
//
        if(!checkDigit(ccNum)) {
            return false;
        }
                
/*                if ((thisChar == "-")
                      &&
                    !(k == 4 || k == 9 || k == 14 )) {
                    return false;
                }
                if ((k == 4 || k == 9 || k == 14)
                         &&
                     (thisChar !== "-")) {
                    return false;
                }
*/
        }
        return true;
}
//
//   function to calculate check digit for credit card validation
//
function checkDigit (strNum) 
{
   var nCheck = 0;
   var nDigit = 0;
   var bEven = false;
   
   for (n = strNum.length - 1; n >= 0; n--) 
   {
      var cDigit = strNum.charAt (n);
      if (isDigit (cDigit))
      {
         var nDigit = parseInt(cDigit, 10);
         if (bEven)
         {
            if ((nDigit *= 2) > 9)
               nDigit -= 9;
         }
         nCheck += nDigit;
         bEven = ! bEven;
      }
      else if (cDigit != ' ' && cDigit != '.' && cDigit != '-')
      {
         return false;
      }
   }
   return (nCheck % 10) == 0;
}
function isDigit (c)
{
   var strAllowed = "1234567890";
   return (strAllowed.indexOf (c) != -1);
}

//
//        the expiration date is entered separately as 2 fields: month
//        and 4 digit year.
//
//        they are entered by selecting an option from a drop down list so
//        it is guaranteed that they are valid, per se
//
//        the Year drop down is done by javascript which starts with the current
//        year and goes 10 years in the future (overkill just to be safe)
//
//        the only thing to check is if the date is in the past which can only happen
//        if the year is the current year and the month is earlier than the current month
//
//        that is what this function determines
//
function validFutureDate(inputDate) {
        var currDate = new Date();
        var inputMonth = parseInt(inputDate.substring(0,2),10);
        var inputSlash = inputDate.substring(2,3);
        var inputYear = parseInt(inputDate.substring(3),10);
        if ((inputYear == currDate.getFullYear() && inputMonth < (currDate.getMonth() + 1))
                                      ||
                                isNaN(inputMonth)
                                      ||
                                inputSlash != "/"
                                      ||
                                isNaN(inputYear)
                                      ||
                                inputYear < currDate.getFullYear()
                                      ||
                                inputMonth < 1
                                      ||
                                inputMonth > 12){
            return false;
        }
        else {
            return true;
        }
}
//
//       this function is called whenever a field is invalidly entered
//
//       it adds a class of "invalid" to the field in error
//       and to its <label> tag (html is set up so label
//       tag has id="l"+ id of the <input> or <select> tag)
//
//       the css for this class gives the input field a background color to highlight it
//       and makes the label bold and red
//
//       in addition, it places an error message passed to it in the <span> tag
//       associated with this field (they have the same "id=" except the span tag
//       has an "s" prefix added to it as "id" must be unique)
//
function flagField(errorField,errorMsg) {
    var errorId = errorField.id;
    errorField.className += invalidClass;
    $("l" + errorId).className += invalidClass;
    $("s" + errorId).innerHTML = errorMsg;
    allGood = false;
    return allGood;
}
//
//       utility function used to add <options> to a <select>
//       tag. Used to create the Expiration Year drop down menu
//

/* For tax from validation*/
function validate() {
// Checking if at least one period button is selected. Or not.
if (document.create_tax_form.region[0].checked){
//On check of state, zip field will hide,validation for zip also remove and validation for state will be added. 
document.getElementById('zip').style.display = "none";
document.getElementById('input10').removeAttribute("class");
document.getElementById('state').style.display = "";
document.getElementById('input6').removeAttribute("class");
document.getElementById('input6').setAttribute('class', 'reqd');
}//On check of zip, state field will hide,validation for state also remove and validation for zip will be added.
else if(document.create_tax_form.region[1].checked){
document.getElementById('state').style.display = "none";
document.getElementById('input6').removeAttribute("class");
document.getElementById('zip').style.display = "";
document.getElementById('input10').removeAttribute("class");
document.getElementById('input10').setAttribute('class', 'reqd zip');
}
else
return false;

}

function tax_rule() {
if (!document.create_tax_form.tax_shipping.checked && !document.create_tax_form.tax_fee.checked){
alert("Please Alteast One Tax Rule"); 
return false;
}
else if(document.create_tax_form.tax_shipping.checked){
document.getElementById('input8').value=1;
return true;
}
else if(document.create_tax_form.tax_fee.checked){
document.getElementById('input9').value=1;
return true;
}
}

//On submit this function will check for all validation
function CheckData(thisButton) {
	var msg = checkAllFields(thisButton);

	if(msg!=false){
		if($('signup_form'))
			$('signup_form').submit();

		if($('forgot_password_form'))
			$('forgot_password_form').submit();

		if($('form_auth_net'))
			$('form_auth_net').submit();

		if($('form_ups_track'))
			$('form_ups_track').submit();

		if($('form_ups_track_displayed'))
			$('form_ups_track_displayed').submit();

		if($('order_history_edit_form'))
			$('order_history_edit_form').submit();

		if($('order_history_search_form'))
			$('order_history_search_form').submit();

		if($('dealer_loginform'))
			$('dealer_loginform').submit();
	}
}

function ConfirmApprove(request) {

	if (request == "order_delete")
		$('request').value = "order_delete";
	else if (request == "order_approve")
		$('request').value = "order_approve";
	else if (request == "ups_tracking")
		$('request').value = "ups_tracking";

	if($('order_lkup_form'))
		$('order_lkup_form').submit();
}

/*
function addOption(selectBox,text,value ) { 
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectBox.options.add(optn);
}
*/
//-->
