////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//checkform.js
//
//By Thomas Foster, Serob Terzyan
//Created: July 19, 2001
//For LampsPlus.com
//
//This file includes functions used throughout the site for form data validation. This file was created to provide 
//continuity throughout the site as well as reducing development time. The following functions are included:
//
//checkValue -			Takes in a form element object and returns a boolean value. Used for general value checking. 
//checkZip -			Takes in a text input object and returns a boolean value. Used to check zip codes for length and 
//						only numeric values
//validate_email -		Takes in a text input object and returns a boolean value. Used to check email addresses. Checks 
//						for invalid characters, presence and location of '@' and '.' characters
//numericOnly -			Takes in a text input object, and an event object and returns a boolean. Used with the onKeydown
//						event to allow only numbers to be entered into a text or textarea input
//onFocusNumericOnly -	Takes in a text input object.  Used to trim a text inputs value of all non-numeric characters
//						Used with numericOnly and formatPhone to standardize phone number inputs
//formatPhone -			Takes in a text input object. Used with the onBlur event to format phone numbers. Formats phone 
//						numbers in the following format: (AAA)PPP-NNNNxTTT 
//						This function also strips off the "1" character and only formats the phone number if the length
//						is at least 10 characters. There is built in length for the extension.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//The following variables are used as flags in the function calls to determine where alerts are to be called
var ALERTSOFF = 0
var ALERTSON = 1


 function checkName(name)
{
     if (name.value.length == 0)
          return;

     for (var i=0; i < name.value.length; i++)
     {
          var ch = name.value.substring(i, i+1);
          if ((ch >= "A" && ch <= "Z") || 
               (ch >= "a" && ch <= "z")||
               (ch == "'")||(ch == "-")||
               (ch == " ")||(ch == "."))
          {
               continue;
          }
          else
          {
			
               alert("Invalid name.  Please re-enter");
              
               name.value="";
               name.focus ();
               return;
          }
     }
}

function checkName2(name){
	if (name.value.length == 0)
          return false;

     for (var i=0; i < name.value.length; i++)
     {
          var ch = name.value.substring(i, i+1);
          if ((ch >= "A" && ch <= "Z") || 
               (ch >= "a" && ch <= "z")||
               (ch == "'")||(ch == "-")||
               (ch == " ")||(ch == "."))
          {
			
               continue;
          }
          else
          {
			  return false;
          }
     }
     return true;
}



//This function checks an input object to see if it has a value. It returns true if it has a value, otherwise
//it returns false
function checkValue(oInput){
	if(oInput.value == ""){
		return false;
	}else{
		return true;
	}
}


//This function is used to check a text input for a five digit zip code value. It checks for both the proper length 
//and that the value is numeric. 
function checkZip(oZip, usealerts){
	if(oZip.value == "" && usealerts==1){
		return true;
	}
	
	if(oZip.value.length != 5){
		if(usealerts == 1){
			alert("Please enter a valid 5 digit zip code.");
			oZip.value = "";
			oZip.focus();
		}
		return false;
	}
	if(!isNumeric(oZip)){
		if(usealerts == 1){
			alert("Please enter a valid 5 digit zip code.");
			oZip.value = "";
			oZip.focus();
		}
		return false;
	}
	
	return true;
}

//This function is used to check if a text input's value is numeric. This function will work in current versions
//of IE and Netscape, but may not work in future versions
function isNumeric(oInput){
	for (i=0;i<oInput.value.length;i++) {
		if (oInput.value.charCodeAt(i) < 48 || oInput.value.charCodeAt(i) > 57) {
			return false;
		}
	}
	return true;
}

//This function is used to check if a text value is numeric. This function will work in current versions
//of IE and Netscape, but may not work in future versions
function isNumericText(value){
	if(value.length == 0)return false;
	for (i=0;i<value.length;i++) {
		if (value.charCodeAt(i) < 48 || value.charCodeAt(i) > 57) {
			return false;
		}
	}
	return true;
}

function isCurrency(this_value)
{
	for(i=0;i<this_value.length;i++)
	{
		if((this_value.charCodeAt(i) < 48 || this_value.charCodeAt(i) > 57) && this_value.substr(i,1) != '.' && this_value.substr(i,1) != '$')
		{
			return false;
		}
	}
	return true;
}

//
//
function validate_email(email, usealerts) {

	var str = email.value; // email string
	var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
	var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,10}|[0-9]{1,10})(\]?)$/; // valid
	if (!(!reg1.test(str) && reg2.test(str))) { // if syntax is valid
	    if(usealerts && str.length != 0){
			alert("\"" + str + "\" is an invalid e-mail address."); // this is also optional
			email.focus();
		}
		return false;
	}
	
    
    // define a list of invalid characters
    invalidCharsList = " /:,;~#'%&*$()[]{}<>!\|=?`";
	
	if (email.value=="" && usealerts == 1){
		return true;
	} 		
	predot = email.value.indexOf('.',0);	
   at=email.value.indexOf('@',0);
   dot=email.value.indexOf('.',at);
   afterdot=email.value.length-dot;
    if (at==-1 ||
       at==0 ||
       dot==-1 ||
       dot-at<2 ||
       afterdot<3 ||
       (at-predot<2 && at-predot>0)) {
       if(usealerts == 1){ 
	        alert("The e-mail address appears to be invalid!");      
		    //email.value = "";
			email.focus();
		}
		return false;
   }
    for (i = 0; i < invalidCharsList.length; i++) {
        errorChar = invalidCharsList.charAt(i);
        if (email.value.indexOf(errorChar,0) != -1) {
			if(usealerts == 1){
	            alert("The e-mail address appears to be invalid!");
	            //email.value = "";
	            email.focus();
	        }
            return false;
        }
    }
    return true;
}



//This function will only allow numeric entries into an input. It also allows a user to move around and delete 
//To use this function, include the following in your <input id=text1 name=text1> tag: onKeyDown="return numericOnly(this,event)"
function numericOnly(oTextbox,evt) {
	if (window.event) { // IE
		if (evt.keyCode == 13){
			return true;
		}
		if (((evt.keyCode < 48 || evt.keyCode > 57) && (evt.keyCode < 96 || evt.keyCode > 105) && evt.keyCode != 8 && evt.keyCode != 9 && evt.keycode != 13 && evt.keyCode != 37 && evt.keyCode != 39 && evt.keyCode != 46) || evt.shiftKey == 1) {
			return false;
		} else {
			return true;
		}
	} else { // Netscape
		if ((evt.which < 48 || evt.which > 57)  && evt.which != 8 && evt.which != 13) {
			return false;
		} else {
			return true;
		}
	}
}



//This function will only allow numeric and dash(-) entries into an input. It also allows a user to move around and delete 
//To use this function, include the following in your <input id=text1 name=text1> tag: onKeyDown="return numericOnly(this,event)"
function dashNumericOnly(oTextbox,evt) {
	if (window.event) { // IE
		if (evt.keyCode == 13){
			return true;
		}
		if (((evt.keyCode < 48 || evt.keyCode > 57) && (evt.keyCode < 96 || evt.keyCode > 105) && evt.keyCode != 189 && evt.keyCode != 109 && evt.keyCode != 8 && evt.keyCode != 9 && evt.keycode != 13 && evt.keyCode != 37 && evt.keyCode != 39 && evt.keyCode != 46) || evt.shiftKey == 1) {
			return false;
		} else {
			return true;
		}
	} else { // Netscape
			
			
		if ((evt.which < 96 || evt.which > 57)  && evt.which != 8 && evt.which != 13) {
			return false;
		} else {
			return true;
		}
	}
}



//This function will only allow numeric entries into an input. It also allows a user to move around and delete 
//To use this function, include the following in your <input id=text1 name=text1> tag: onKeyDown="return numericOnly(this,event)"
function decimalsOnly(oTextbox,evt) {
	if (window.event) { // IE
		if (evt.keyCode == 13){
			return true;
		}
		if (((evt.keyCode < 48 || evt.keyCode > 57) && (evt.keyCode < 96 || evt.keyCode > 105) && evt.keyCode != 8 && evt.keyCode != 9 && evt.keycode != 13 && evt.keyCode != 37 && evt.keyCode != 39 && evt.keyCode != 46 && evt.keyCode != 110 && evt.keyCode != 190) || evt.shiftKey == 1) {
			return false;
		} else {
			return true;
		}
	} else { // Netscape
		if ((evt.which < 48 || evt.which > 57)  && evt.which != 8 && evt.which != 13 && evt.which != 46) {
			return false;
		} else {
			return true;
		}
	}
}

/* This function is not completed...
//This function prevents users from submitting a form by using the enter key.
function noEnter(evt){
	if(window.event){	// IE
		alert(evt.keyCode);
		//if(evt.keyCode ==  )return false;
	}else{ // Netscape
		alert(evt.which);
		//if(evt.which == )return false;
	}
	return true;
}
*/

//This function strips an input of any values that are not numeric
//To use this function, include the following in your <input id=text1 name=text1> tag: onFocus="onFocusNumericOnly(this)"
function onFocusNumericOnly(oTextbox) {
	var sReturnValue;
	sReturnValue = '';
	var i;
	for (i=0;i<oTextbox.value.length;i++) {
		if (oTextbox.value.charCodeAt(i) >= 48 && oTextbox.value.charCodeAt(i) <= 57) {
			sReturnValue = sReturnValue + oTextbox.value.charAt(i);
		}
	}
	oTextbox.value = sReturnValue;
	return true;
}

//This function returns the value passed in with only the numeric characters left

function onFocusNumericOnlyString(oValue) {
	var sReturnValue;
	sReturnValue = '';
	var i;
	for (i=0;i<oValue.length;i++) {
		if (oValue.charCodeAt(i) >= 48 && oValue.charCodeAt(i) <= 57) {
			sReturnValue = sReturnValue + oValue.charAt(i);
		}
	}
	
	return sReturnValue;
}

//This function formats an inputs value into a phonenumber format. It is best to use the numericOnly function with this function.
//To use this function, include the following in your <input id=text1 name=text1> tag: onBlur="formatPhone(this)"
function formatPhone(oTextbox) {
	var sReturnValue;
	
	sReturnValue = '';
	oTextbox.value.replace(" ","");
	if (oTextbox.value.length > 0) {
		while(oTextbox.value.substr(0,1) == "1" || oTextbox.value.substr(0,1) == "0"){
			oTextbox.value = oTextbox.value.substr(1,(oTextbox.value.length-1))
		}
		if (oTextbox.value.length < 10) {
			alert('Please enter your area code and phone number in the following format: 8007821967\nIf your phone number includes an extension,\nadd it to the end like this: 8007821967111\nPlease do not include the "1" prefix.\n\nThis page will automatically reformat the phone number for you.');
			oTextbox.value="";
			oTextbox.focus();
		} else {
			sReturnValue = '(' + oTextbox.value.substr(0,3) + ')' + oTextbox.value.substr(3,3) + '-' + oTextbox.value.substr(6,4);
			if (oTextbox.value.length > 10) {
				sReturnValue = sReturnValue + 'x' + oTextbox.value.substr(10);
			}
			oTextbox.value = sReturnValue;
		}
	}
	return true;
}

function checkAddress(address,usealerts){
	var str = address.value;
	if (str == "" && usealerts == 1){
		return true;
	}else{
		if(str == "" && usealerts == 0){
			return false;
		}
	}			
	if((str.indexOf(';')!= -1)||(str.indexOf(',')!= -1)){
		if(usealerts){
			alert("Please enter a valid address without commas(,) or semicolons(;)in the field provided.");
			address.focus();
		}
		return false;
	}
	return true;
}

function checkState(state,usealerts){
	if(state.value == "" && usealerts == 1){
		return true;
	}else{
		if(state.value == "" && usealerts == 0){
			return false;
		}
	}
	
	var states = new Array('AL','AK','AR','AZ','CA','CO','CT','DC','DE','FL','GA','HI','IA','ID','IL','IN','KS','KY',
	'LA','MA','MD','ME','MI','MN','MO','MS','MT','NC','ND','NE','NH','NJ','NM','NV','NY','OH','OK','OR','PA','RI','SC',
	'SD','TN','TX','UT','VA','VT','WA','WI','WV','WY');

	state.value = state.value.toUpperCase();
	
//	for(i=0;i<states.length;i++){
//		if(state.value == states[i]){
//			return true;
//		}
//	}
//	if(usealerts){
//		alert("Please enter a valid state.");
//		state.focus();
//	}
	return true;
}

function checkCity(city,usealerts){
	var str = city.value;
	if (str == "" && usealerts == 1){
		return true;
	}else{
		if(str == "" && usealerts == 0){
			return false;
		}
	}			
	if((str.indexOf(';')!= -1)||(str.indexOf(',')!= -1)){
		if(usealerts){
			alert("Please enter a valid city without commas(,) or semicolons(;)in the field provided.");
			city.focus();
		}
		return false;
	}
	return true;
}

// This function will validate that a date is entered in a short date format mm/dd/yyyy.
// It does require that the /'s be entered, but it does not require that leading zeros
// be entered for the day and month.  It will also accept the either 2-digit or 4-digit 
// year values. This function does not accurately handle century and milleniums so it is 
// only valid thru the year 2099. This function returns true for valid dates and false
// for invalid dates.
function isValidDate(date){
	if(date != ''){
		var i;
		var aryDate = date.split('/');
		// check to see if two /'s were entered
		if(aryDate.length != 3)return false;
		// check that the day, month, and year fields are the correct length
		if(aryDate[1].length < 1 || aryDate[1].length > 2)return false;
		if(aryDate[0].length < 1 || aryDate[0].length > 2)return false;
		if(aryDate[2].length != 2 && aryDate[2].length != 4)return false;
		
		// parse out any possible leading non-numeric characters
		for(i=0;i<3;i++){
			aryDate[i] = parseInt(aryDate[i],10);
		}
		
		// ensure the day entered is valid for the month entered
		if(aryDate[0] == 1 || aryDate[0] == 3 || aryDate[0] == 5 || aryDate[0] == 7 || aryDate[0] == 8 || aryDate[0] == 10 || aryDate[0] == 12 ){
			if(aryDate[1] < 1 || aryDate[1] > 31)return false;
		}
		if(aryDate[0] == 4 || aryDate[0] == 6 || aryDate[0] == 9 || aryDate[0] == 11){
			if(aryDate[1] < 1 || aryDate[1] > 30)return false;
		}
		if(aryDate[0] == 2){
			// check for leap year
			if(aryDate[2] % 4 != 0){
				if(aryDate[1] < 1 || aryDate[1] > 28)return false;
			}else{
				if(aryDate[1] < 1 || aryDate[1] > 29)return false;
			}
		}
	}
	
	return true;
}

// This function can be used to validate that a credit card input is valid for a credit card type
function checkccnumber(ccnumber,cctype)
{
	var ctype, cclength, ccprefix, prefixes, lengths, number, prefixvalid, lengthvalid;
	var result, qsum, x, ch, sum, prefix, length;
  
	//alert('cctype = ' + cctype + '\nccnumber = ' + ccnumber); 
  
	ctype = cctype.substr(0,1);
	ctype = ctype.toUpperCase();
  
	switch(ctype)
	{
		case "V":
			cclength="13;16";
			ccprefix="4";
			break;
		case "M":
			cclength="16";
			ccprefix="51;52;53;54;55";
			break;
		case "A":
			cclength="15";
			ccprefix="34;37";
			break;
		case "C":
			cclength="14";
			ccprefix="300;301;302;303;304;305;36;38";
			break;
		case "D":
			cclength="16";
			ccprefix="6011";
			break;
		case "E":
			cclength="15";
			ccprefix="2014;2149";
			break;
		case "J":
			cclength="15;16";
			ccprefix="3;2131;1800";
			break;
		default:
			cclength=""
			ccprefix=""
			break;
	}
	
	prefixes=ccprefix.split(";");
	lengths=cclength.split(";");
	number=onFocusNumericOnlyString(ccnumber);
  
	prefixvalid=false;
	lengthvalid=false;
  
	for(var i=0; i<prefixes.length;i++)
	{
		if(number.indexOf(prefixes[i]) == 0)
		{
			prefixvalid=true;
		}
	}
   
	for(var i=0; i<lengths.length;i++)
	{
		if(number.length == lengths[i])
		{
			lengthvalid=true;
		}
	}
  
	result=0;
  
	if(!prefixvalid)
	{
		result=result+1;
	}
    
	if(!lengthvalid)
	{
		result=result+2;
	}  
	
	qsum=0;
  
	for(var x=1;x<=number.length;x++)
	{
		ch = number.substr(number.length - (x),1);
		if(x % 2 == 0)
		{
			sum = 2 * parseInt(ch);
			qsum = qsum + (sum % 10);
			
			if(sum > 9)
			{
				qsum = qsum + 1;
			}
		}
		else
		{
			qsum = qsum + parseInt(ch);
		}
	}
  
	if(qsum % 10 != 0)
	{
		result = result + 4;
	}
	  
	if(cclength == "")
	{
		result = result + 8;
	}
	
	return result;
  
}

/********************************************************************************************************
The following function will clear the value for all text inputs in a given form. The form is taken in as
a parameter. This function is useful when you have a reset button on a page that may have default values 
entered in the text boxes at load time. 
For example: The form submits to another page which redirects back to the form page if an input is 
	not valid. The form page stuffs the original values back into the inputs. A reset button will
	reset the values back to the values at load time and will not clear the values. 
********************************************************************************************************/
function clearTextInputs(form)
{
	for( var i=0; i < document.form.length; i++ )
	{
		if(document.form.elements[i].type == "text")
		{
			document.form.elements[i].value = "";
		}
	}
}