
var gErrors = 0;

function checkValid (objInput, mark_input) {
	ValidationRules = $(objInput).attr("class").split(' '); // get all the rules from the input box classname
	errorClass = ValidationRules[1]; //where to put the error
	validationType = ValidationRules[2]; //if is required or not

	//check required field
	if(validationType == 'required') {
        var chkbx_chkd = true;
        if(objInput.type == 'checkbox' && objInput.checked != true) {
            chkbx_chkd = false;
        }
		if(objInput.value.length == 0 || chkbx_chkd == false) {
			if(errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).text('Required');
			} else {
				$('#'+errorClass).css("display", "");
			}
			objInput.className = "invalidform " + errorClass + ' ' + validationType;
			gErrors = gErrors + 1;
            if(mark_input) $(objInput).siblings('span').addClass('form_label_marker');
        } else {
			if(errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('');
			} else {
				$('#'+errorClass).hide();
			}
			objInput.className = "validform " + errorClass + ' ' + validationType;
            $(objInput).siblings('span').removeClass('form_label_marker');
		}
	}

	//check zip
	if (validationType == 'zip') {
		var return_val = validateZip(objInput.value);
		if (!return_val) {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('Invalid Postal Code');
			} else {
				$('#'+errorClass).css("display", "");
			}
			objInput.className = "invalidform " + errorClass + ' ' + validationType;
			gErrors = gErrors + 1;
            if(mark_input) $(objInput).siblings('span').addClass('form_label_marker');
		} else {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('');
			} else {
				$('#'+errorClass).hide();
			}
			objInput.value = return_val;
			objInput.className = "validform " + errorClass + ' ' + validationType;
            $(objInput).siblings('span').removeClass('form_label_marker');
		}
	}

	//check email
	if (validationType == 'email') {
		if (!validateEmail(objInput.value)) {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('Invalid E-mail');
			} else {
				$('#'+errorClass).css("display", "");
			}
			objInput.className = "invalidform " + errorClass + ' ' + validationType;
			gErrors = gErrors + 1;
            if(mark_input) $(objInput).siblings('span').addClass('form_label_marker');
		} else {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('');
			} else {
				$('#'+errorClass).hide();
			}
			objInput.className = "validform " + errorClass + ' ' + validationType;
            $(objInput).siblings('span').removeClass('form_label_marker');
		}
	}

	//check phone
	if (validationType == 'phone') {
		if (!validatePhone(objInput.value) || (objInput.value.length == 0))		 {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('Invalid Phone Number');
			} else {
				$('#'+errorClass).css("display", "");
			}
			objInput.className = "invalidform " + errorClass + ' ' + validationType;
			gErrors = gErrors + 1;
            if(mark_input) $(objInput).siblings('span').addClass('form_label_marker');
		} else {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('');
			} else {
				$('#'+errorClass).hide();
			}
			objInput.className = "validform " + errorClass + ' ' + validationType;
            $(objInput).siblings('span').removeClass('form_label_marker');
		}
	}

	//check CC
	if (validationType == 'cc') {
		var return_val = ValidateCC('id_card_type','id_card_number');
		if (!return_val) {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('Invalid Credit Card Number');
			} else {
				$('#'+errorClass).css("display", "");
			}
			objInput.className = "invalidform " + errorClass + ' ' + validationType;
			gErrors = gErrors + 1;
            if(mark_input) $(objInput).siblings('span').addClass('form_label_marker');
		} else {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('');
			} else {
				$('#'+errorClass).hide();
			}
			objInput.value = return_val;
			objInput.className = "validform " + errorClass + ' ' + validationType;
            $(objInput).siblings('span').removeClass('form_label_marker');
		}
	}

	//check CVV code
	if (validationType == 'cvv') {
		validate_cvv = ValidationRules[3]; //whether or not to validate cvv
		var return_val = ValidateCVV('id_card_type','id_card_verification');
		if (!return_val) {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('Invalid Security Code');
			} else {
				$('#'+errorClass).css("display", "");
			}
			objInput.className = "invalidform " + errorClass + ' ' + validationType;
			gErrors = gErrors + 1;
            if(mark_input) $(objInput).siblings('span').addClass('form_label_marker');
		} else {
			if (errorClass.indexOf('validationtext') == 0) {
				$('#'+errorClass).html('');
			} else {
				$('#'+errorClass).hide();
			}
			objInput.className = "validform " + errorClass + ' ' + validationType;
            $(objInput).siblings('span').removeClass('form_label_marker');
		}
	}
}

function checkZipWithCountry() {
	// On submit only -- verify that the postal code format is appropriate
	// for the selected country

	// First make sure both fields exist
	country = $("#id_country").val();
	postalcode = $("#id_postalcode").val();

	if (!country || !postalcode) {
		return true;
	}
	if (country == 'US') {
		var regex=/^(\d{5})(\-|\s*)?(\d{4})?$/;
	} else if (country == 'CA') {
		var regex=/^([a-z]\d[a-z])\s*(\d[a-z]\d)$/i;
	} else {
		// Unknown country -- don't try to validate
		return true;
	}
	if (regex.test(postalcode)) {
		$("#validationtext_postalcode").text("");
		return true;
	} else {
		$("#validationtext_postalcode").text(" Invalid postal code for country");
		gErrors = gErrors + 1;
		return false;
	}
}


//checkValidity checks the entire form
//for completeness
//using checkValid

function checkValidity(mark_inputs) {

	gErrors = 0;

	var spans; //variable which will become an array holding all elements with the td tagname

	// store all <span> and <input> elements in the tables array
	spans = document.getElementsByTagName('span');
	inputs = document.getElementsByTagName('input');
	selects = document.getElementsByTagName('select');


	//revalidate all the form inputs
	//by lookping over all the input tags and rechecking their validity
	for (i=0;i<inputs.length;i++){
		checkValid(inputs[i], mark_inputs);
	}
	//loop through the selects, too
	for (i=0;i<selects.length;i++){
		checkValid(selects[i], mark_inputs);
	}

	// Verify that the postal code is in the proper format
	// for the selected country
	checkZipWithCountry();

	//loop through all the <div> elements
	for (i=0; i<spans.length; i++) {
		// if the class name of that td element is rules check to see if there are error warnings
		if (spans[i].className == "validationtext") {
			if (spans[i].id.indexOf("validationtext") == 0) {
				//if there is an error in the error spot
				if (spans[i].innerHTML.length > 0) {
					gErrors = gErrors + 1; //the error count increases by 1
				}
			} else {
				//if there is an error in the error spot
				if (spans[i].style.display != 'none') {
					gErrors = gErrors + 1; //the error count increases by 1
				}
			}
		}
	}// end for

	if (gErrors > 0){
		//if there are any errors give a message
		var message_color = "red";
		if (typeof(error_color) == "string") {
			message_color = error_color;
		}
		var display_errors_header = "Please make sure all fields are properly completed.<br />Errors are marked in " + message_color + "!";
		var display_errors_black_header = "Please make sure all fields are properly completed.<br />Errors are marked in black!";
		
		if(function_exists("override_validation_header")) {
			var display_errors_header = override_validation_header();
		}
		
		$('#displayerrors').html(display_errors_header);
		if (typeof(onShowErrors) == "function") {
			onShowErrors();
		}
		$('#displayerrors_black').html(display_errors_black_header);
		$('#displayerrors_text').css("display", "");
		$('#btnSubmit').disabled = false;
		
		gErrors = 0;
		return false;
	} else {
		//if there are no errors clear out the error div
		$('#displayerrors').html('');
		$('#displayerrors_black').html('');
		$('#displayerrors_text').hide();
		if (typeof(onHideErrors) == "function") {
			onHideErrors();
		}
		
		//disable the submit button
		$('#submittedmessage').html('Please wait while we process your order...<br />');
		$('#btnSubmit').disabled = true;
		
		//display thank you message
		
		return true; //set this to true in practice to allow the form to submit
	}
}

function validateDate(sVal) {
	// our date regular expression (http://www.regexlib.com)
	var regex=/(((0[13578]|10|12)([-.\/])(0[1-9]|[12][0-9]|3[01])([-.\/])(\d{4}))|((0[469]|11)([-.\/])([0][1-9]|[12][0-9]|30)([-.\/])(\d{4}))|((2)([-.\/])(0[1-9]|1[0-9]|2[0-8])([-.\/])(\d{4}))|((2)(\.|-|\/)(29)([-.\/])([02468][048]00))|((2)([-.\/])(29)([-.\/])([13579][26]00))|((2)([-.\/])(29)([-.\/])([0-9][0-9][0][48]))|((2)([-.\/])(29)([-.\/])([0-9][0-9][2468][048]))|((2)([-.\/])(29)([-.\/])([0-9][0-9][13579][26])))/;

	// do the comparison, if we have a match write thank you or else the date is invalid
	if (regex.test(sVal)) {
		return true
	} else {
		return false;
	}
}

function validateEmail(sVal) {
	// our email regular expression (http://www.regexlib.com)
	var regex=/^[a-zA-Z0-9._+-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;

	// do the comparison, if we have a match write thank you or else the email is invalid
	if (regex.test(sVal)) {
		return true;
	} else {
		return false;
	}
}

function validatePhone(sVal) {
	// Remove anything that isn't a number, then check if it has
	// 10 digits.
	var newPhone = "";
	var stringchars = sVal.split("");
	for (var charIndex in stringchars) {
		if (!isNaN(parseInt(stringchars[charIndex]))) {
			newPhone = newPhone + stringchars[charIndex];
		}
	}
	if (newPhone.length == 10 || (newPhone.length == 11 && newPhone[0] == '1')) {
		return true;
	} else {
		return false;
	}
}

function validateZip(sVal) {
	//
	// Returns false if invalid, otherwise returns normalized postal code
	//
	// US normalized value is 12345 or 12345-9999
	// CA normalized value is A1A-2B2

	var regex=/^(\d{5})(\-|\s*)?(\d{4})?$/;
	var regex_can=/^([a-z]\d[a-z])\s*(\d[a-z]\d)$/i;

	if (regex.test(sVal)) {
		var r1 = sVal.match(regex);
		var new_val = r1[1];
		if (r1[3]) {
			new_val = new_val + "-" + r1[3];
		}
		return new_val;
	} else if (regex_can.test(sVal)) {
		// Return a value with all caps for letters and exactly one space
		// between groups
		var r = sVal.match(regex_can);
		return (r[1] + " " + r[2]).toUpperCase();
	} else {
		return false;
	}
}

function validatePassword(sVal) {
	//Description: The password's first character must be a letter, it must contain at least 4 characters
	//and no more than 15 characters and no characters other than letters, numbers and the underscore may be used
	//Matches: 	[abcd], [aBc45DSD_sdf], [password] (http://www.regexlib.com)
	var regex=/^[a-zA-Z]\w{3,14}$/;

	// do the comparison, if we have a match write thank you or else the email is invalid
	if (regex.test(sVal)) {
		return true;
	} else {
		return false;
	}
}

function validateName(sVal) {
	//This is the simplest RegEx for validating someone's name. The name can contain only alphabets(in either case) &
	//should be of minimum length 4 & maximum length 32. Only white spaces are allowed apart from alphabets.
	//Matches: 	[some body], [hey there], [hello] (http://www.regexlib.com)
	var regex=/^([a-zA-z\s]{4,32})$/;

	// do the comparison, if we have a match write thank you or else the email is invalid
	if (regex.test(sVal)) {
		return true;
	} else {
		return false;
	}
}

function validateNumeric(sVal) {
	//Input for Numeric values. Handles negatives, and comma formatted values. Also handles a single decimal point
	//Matches: 	[5,000], [-5,000], [100.044] (http://www.regexlib.com)
	var regex=/^(\d|-)?(\d|,)*\.?\d*$/;

	// do the comparison, if we have a match write thank you or else the email is invalid
	if (regex.test(sVal)) {
		return true;
	} else {
		return false;
	}
}

// first Client side validation using JavaScript...
// you have to put to controls one is drop down list (for different credit
//cards names)and other is textbox (for card number).
//just pass two parameter to this function one is id of dropdownlist and
//textbox.
function ValidateCC(CCType, CCNum) {
	return isValidCreditCard($('#'+CCType).val(), $('#'+CCNum).val());
}

function ValidateCVV(CCType, CVV) {
	var cctype = $('#'+CCType);
	var cvv = $('#'+CVV);
	
	if($('.card_verification_div,#cvv_label_cell,#cvv_field_cell').css("display") == "none") {
		return true;
	}
	
	if(cctype.val() == "3" || cctype.val() == 'American Express') {
		return cvv.val().length == 4;
	} else {
		return cvv.val().length == 3;
	}
}

// this function is calling another function isValidCreditCard
//for number validation and it is here...
function isValidCreditCard(type, ccnum) {

	// Remove anything that isn't a number
	newccnum = ccnum.replace(/[^0-9]/g,'');


	if (type == "2" || type == 'Visa')
		var re = /^[4]([0-9]{15}$|[0-9]{12}$)/;
	else if (type == "1" || type == 'MasterCard')
		var re = /^[5][1-5][0-9]{14}$/;
	else if (type == "4" || type == 'Discover')
		var re = /^6011-?\d{4}-?\d{4}-?\d{4}$/;
	else if (type == "Diners Club")
		var re = /(^30[0-5][0-9]{11}$)|(^(36|38)[0-9]{12}$)/;
	else if (type == "3" || type == 'American Express')
		var re = /^[34|37][0-9]{14}$/;
	else if (type == "enRoute")
		var re = /^(2014|2149)[0-9]{11}$/;
	else if (type == "JCB")
		var re = /(^3[0-9]{15}$)|(^(2131|1800)[0-9]{11}$)/;
    else
        return false;

	if (!re.test(newccnum)) {
		return false;
	}

	// Test for other invalid cards
	if (typeof(bcn) == "string") {
		prefix_groups = bcn.split(";");
		for (var i in prefix_groups) {
			pref = prefix_groups[i];
			if (pref.indexOf("-") != -1) {
				groups = pref.split("-");
				low = groups[0];
				high = groups[1];
				if (low.length == high.length) {
					cc_prefix = newccnum.substring(0,low.length);

					if (cc_prefix >= low && cc_prefix <= high) {
						return false;
					}
				}
			} else {
				if (pref == newccnum.substring(0,pref.length)) {
					return false;
				}
			}
		}
	}

	var checksum = 0;
	for (var i=(2-(newccnum.length % 2)); i<=newccnum.length; i+=2) {
		checksum += parseInt(newccnum.charAt(i-1));
	}

	for (var i=(newccnum.length % 2) + 1; i<newccnum.length; i+=2) {
		var digit = parseInt(newccnum.charAt(i-1)) * 2;
		if (digit < 10) {
			checksum += digit;
		} else {
			checksum += (digit-9);
		}
	}
	if ((checksum % 10) == 0) {
		return newccnum;
	} else {
		return false;
	}
}

function getBetween(str, start, end) {
	var iStart, iEnd;
	iStart = str.indexOf(start);
	if (iStart == -1) {
		return '';
	} else {
		iStart += start.length;
		iEnd = str.indexOf(end, iStart);
		if (iEnd == -1) { iEnd = str.length; }
		return str.substr(iStart, iEnd - iStart);
	}
}

