/*
*
* This software, any associated files, and any derivative works are
* the intellectual property and Copyright 2010 of SDDI (&copy 2010 SDDI).  
*
* All rights are reserved.  Any use or  modification is prohibited without
* the express written consent of SDDI.
*
* Contact SDDI through http://www.sddi.com with any questions concerning
* the use of this software and any associated files.
* 
* Version 1.0 - 01/25/2010 - required fields have non-empty values
* Version 1.1 - 01/30/2010 - validation of numeric, date, email and phone types
* Version 1.2 - 01/31/2010 - beef up validation and add decimal type
*
*/

// basic use instructions:
// include this on the page, preferably in the head area
// <script type="text/javascript" src="javascripts/validate.js"></script>
//
// then:
// name input fields appropriately - they will be displayed to user
// use class to identify required fields and field types
// use - onSubmit="return validateForm(this)"
//
// examples:
// <input name="email" type="text" class="required email" value="" />
// <input name="phone" type="text" class="required phone" value="" />

// verify that required form elements are filled in and
// validate numeric, date, email, and phone number formats
function validateForm(form){
// variables used to confirm email/password same when have to enter twice
var mail1="";
var pass1="";
//loop each element in the form
for(var i=0;i<form.elements.length;i++){
	var field=form.elements[i]
	var req=(field.className.indexOf("notrequired") == -1 && field.className.indexOf("required") >= 0)?true:false
	var num=(field.className.indexOf("numeric") >= 0)?true:false
	var dec=(field.className.indexOf("decimal") >= 0)?true:false
	var dat=(field.className.indexOf("date") >= 0)?true:false
	var email=(field.className.indexOf("email") >= 0)?true:false
	var phon=(field.className.indexOf("phone") >= 0)?true:false
	var name=(field.className.indexOf("name") >= 0)?true:false
	var nolenchk=(field.className.indexOf("nolenchk") >= 0)?true:false
	//field.value=field.value.trim()
	
	// check if required fields filled in
	if(req){  // if field is required
		if((field.type=="text" || field.type=="textarea" || field.type=="password") && field.value==""){
			alert("Please fill in a value for the '"+field.name+ "' field.");
			field.focus();
			return false;
		}
		if(field.type=="select-one" && field.selectedIndex <= 0){
			alert("Please select an option in the '"+field.name+ "' list.");
			field.focus();
			return false;
		}
		if(field.type=="select-multiple"){	
			var cnt=0;
			for(var j=0;j<field.options.length;j++){
				if(field.options[j].selected){
					cnt++;
					break;
				}
			}
			if(!cnt){
				alert("Please select one or more options in the '"+field.name+ "' list.");
				field.focus();
				return false;
			}			
		}
		if(field.type=="radio"){
			var cnt=0;
			while(form.elements[i].type == field.type && form.elements[i].name==field.name){
				if(form.elements[i].checked){
					cnt++;
				}
				i++;
			}
			if(!cnt){
				alert("Please select one of the options for the '"+field.name+ "' radio button group");
				field.focus();
				return false;
			}
			i--;  // we went past the end, so point to the last one
		}
		if(field.type=="checkbox"){
			var cnt=0;
			while(form.elements[i].type == field.type && form.elements[i].name==field.name){
				if(form.elements[i].checked){
					cnt++;
				}
				i++;
			}
			if(!cnt){
				alert("Please select at least one of the options for the '"+field.name.slice(0,-2)+ "' check box group");
				field.focus();
				return false;
			}
			i--;  // we went past the end, so point to the last one
		}
	}//end required
	
	// now check if values are valid
	if(field.type!='checkbox' && field.value!=''){  // if not blank
		if(num){ // numeric field - e.g. zip code
			var val=field.value.replace(/[0-9-]/g, '')
			if (val!=''){
				alert("The '"+field.name+ "' field is not numeric.")
				field.focus()
				return false
			}
		} //end numeric
		if(dec){ // decimal field - e.g. dollars and cents
			var val=field.value.replace(/[\$\.,0-9]/g, '')
			if (val!=''){
				alert("The '"+field.name+ "' field is not a decimal number.")
				field.focus()
				return false
			}
		} //end decimal
		if(email){ // email address field
			var a=field.value.indexOf("@");
			var d=field.value.lastIndexOf(".");
			if (a<1 || d-a<2){
				alert("The '"+field.name+ "' field does not contain a valid email address.")
				field.focus()
				return false
			}
		} //end email address
		if(dat){ // date field
			if(!isDate(field.value)){
				alert("The '"+field.name+ "' date field must be a valid date entered in MM/DD/YYYY format.")
				field.focus()
				return false
			}
		} // end date field
		if(phon){ // phone number field
			if(field.value!="Your Phone" && !isPhone(field.value)){
				alert("The '"+field.name+ "' field should be entered in a standard '(555) 555-5555' or international format.")
				field.focus()
				return false
			}
		} // end phone field
		if(req && name){ // required name field
			if(field.value=="First & Last Name"){
				alert("Please fill in a value for the '"+field.name+ "' field.")
				field.focus()
				return false
			}
		} // end phone field
	} // end if not blank
	
	// now check if email/password same when must enter twice
	// if using this feature, fields must be named email/email2 and password/password2
	if(field.name == 'email'){
		mail1=field.value
	}
	if(field.name == 'password'){
		pass1=field.value
		if(field.value.length < 8 && !nolenchk){
			alert("The password is too short.  It must be at least 8 characters long.")
			field.focus()
			return false
		}
		if(field.value == mail1){
			alert("The password cannot be the same as your email address.")
			field.focus()
			return false
		}
	}
	if(field.name == 'email2'){
		if(field.value != mail1){
			alert("The two email addresses do not match.")
			field.focus()
			return false
		}
	}
	if(field.name == 'password2'){
		if(field.value != pass1){
			alert("The two passwords do not match.")
			field.focus()
			return false
		}
	}
	
	// now check if license field - if so, must check box before continuing
	if(field.name == 'license'){
		if(!field.checked){
			alert("You must accept the license statement to continue.")
			field.focus()
			return false
		}
	}
}//end for
return true
} // end function


// prompt before resetting form	
function resetForm(form){
	return confirm("Are you sure you want to reset the form?")
}	

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1969;
var maxYear=2100;

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++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}

/**
 * DHTML phone number validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */

// Declaring required variables
var digits = "0123456789";
// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()-. ";
// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";
// Minimum no of digits in an international phone no.
var minDigitsInIPhoneNumber = 10;

function trim(s)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not a whitespace, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (c != " ") returnString += c;
    }
    return returnString;
}

function isPhone(strPhone){
var bracket=3
strPhone=trim(strPhone)
if(strPhone.indexOf("+")>1) return false
if(strPhone.indexOf("-")!=-1)bracket=bracket+1
if(strPhone.indexOf("(")!=-1 && strPhone.indexOf("(")>bracket)return false
var brchr=strPhone.indexOf("(")
if(strPhone.indexOf("(")!=-1 && strPhone.charAt(brchr+4)!=")")return false
if(strPhone.indexOf("(")==-1 && strPhone.indexOf(")")!=-1)return false
s=stripCharsInBag(strPhone,validWorldPhoneChars);
return (isInteger(s) && s.length >= minDigitsInIPhoneNumber);
}

