/*
    This is a generic code to validate any form.  To use this the following has to be on the form
    1) The form field must have a id and name and it is the first variable in the validate javascript function
       i.e. <form id="frmMain" name="frmMain" action="formprocess.php" method="POST">
    2) All variables must have and id set and the field name must have an id tag that is the same with a suffix of "name"
       i.e. <tr><td id="EMAILname">Email:</td><td><input type="text" name= "EMAIL" id= "EMAIL" value=""></td></tr>
    3) Textfields and textareas can have extra checks done, there is three possible ones, to do this create an
       array and add the field name and the type of check you want.   Key of array is id of field and value is type
       of check to do:  i.e.
           var variables = new Array()
           variables["ZIPPOSTAL"]="PostalCode";    -- postal code check
           variables["EMAIL"]="Email";   -- email field check
           variables["HPHONE"]="Numeric";   -- numeric check
    4) Checkboxes are not validated unless added to the variable array, in checkbox case, key is variable name and value is checkbox
       i.e.     variables["attr_chkInterests[]"]="Checkbox";   -- numeric check
    5)  To make fields not be check, add them to the optional array
            var optional = new Array();
            optional["prop_1036"]="prop_1036";
    6) To get the validation to work, add the validation function to the submit button
       i.e. <input type="submit" name="submit" value="submit" onclick="return validate('frmMain',variables,optional)">    
*/  


    var RE_EMAIL = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
    var RE_CA_POSTAL_CODE = /([A-Za-z]\d[A-Za-z]\d[A-Za-z]\d)/;
    var matchs = new Array();
    var matchfind = new Array();
    var clickedcheck = new Array();
    var clickedline = "~~";
    var conditionalcheck = new Array();
    var conditionalline = "~~";
    var labelchange = new Array();
    var agecheck = new Array();
    var errorchange = new Array();
    
    errorColour = "#0000FF";
    preError = "-";
    requiredText = " is required.\n";
    postalCodeText = " is not a valid Postal Code.\n";
    emailText = " is not a valid Email.\n";
    matchText = " do not match.\n";
    numberText = " is not a valid number.\n";
    errorText = "The following errors were encountered:\n\n";
    atleastText = "At least one of the following is required: ";
    ageText = " is not a valid age, the age must be at least ";

    function isFrench() {
        requiredText = " Obligatoire.\n";
        postalCodeText = " n'est pas un Code Postal valide .\n";
        emailText = " n'est pas un E-mail valide.\n";
        matchText = " ne pas égaler.\n";
        numberText = " n'est pas un nombre valide.\n";
        errorText = "Les erreurs suivantes ont été rencontrées:\n\n";
        atleastText = "Au moins un des suivre est exigé: ";
    }


    function setMatch(match1,match2) {
        matchs[match1 + "~~" + match2] = match1 + "~~" + match2;
        matchfind[match1] = match1;
    }

    //must be select boxes
    function setAgeCheck(dayfield,monthfield,yearfield,age) {
    	agecheck[yearfield] = monthfield + "!!" + dayfield + "!!" + yearfield + "!!" + age;
    }

    function setLabel(checkfield,labelfield) {
    	labelchange[checkfield] = labelfield;
    }

    function setError(checkfield,errorfield) {
    	errorchange[checkfield] = errorfield;
    }

    //at least one checkbox clicked
    function oneclicked(clickvalues) {   
        if (clickvalues.length > 0) {
            clickedcheck[clickvalues[0]] = clickvalues[0];
            currclickedline = "";    
            for(var i = 0; i < clickvalues.length; i++) {
                if (currclickedline != "") {
                    currclickedline += "!!"
                }
                currclickedline += clickvalues[i];        
            }
            clickedline += currclickedline + "~~";
        }
    }


    function conditional(field,condition,conditionvalue,conditiontype) {
        conditionalcheck[field] = field;
        conditionalline += field + "!!" + condition + "!!" + conditionvalue + "!!" + conditiontype + "~~";
    }

    function validate(frmName, variables, optional) {
        var elem = document.getElementById(frmName).elements;
        error = 0;
        errorList = "";
        errorListCheck = "";
        for(var i = 0; i < elem.length; i++) {

   	    labelfield = elem[i].name;
	    if (elem[i].name in labelchange) {
		labelfield = labelchange[elem[i].name];
	    }

   	    errorfield = "";
	    if (elem[i].name in errorchange) {
		errorfield = errorchange[elem[i].name];
	    }

            //check conditional
            cmustcheck = 0;
            if (elem[i].name in conditionalcheck) {
                splitstring = conditionalline.split("~~");
                for(j = 0; j < splitstring.length; j++) {
                    if (splitstring[j] != "") {
           	        cc = splitstring[j];
                        ccsplit = cc.split("!!");
                        if (ccsplit[0] == elem[i].name) {
                        	checkfield = ccsplit[1];
                        	checkvalue = ccsplit[2];
                        	checktype = ccsplit[3];
                                if (checktype == "select-one") {
                                    for ( k =0; k < document.getElementById(checkfield).options.length; k++) {
                                        if (document.getElementById(checkfield).options[k].selected) {
                                         	if (document.getElementById(checkfield).options[k].value == checkvalue) {
                                         	    cmustcheck = 1;
                                         	}
                                        }
                                    }
                                } else if (checktype == "text" || checktype == "textarea") {
                                	if (document.getElementById(checkfield).value == checkvalue) {
                                         	    cmustcheck = 1;
                                        }
                                } else if (checktype == "radio" || checktype == "checkbox") {
			                for ( k =0; k < document.getElementsByName(checkfield).length; k++) {	
			                    if (document.getElementsByName(checkfield)[k].checked) {
                                         	if (document.getElementsByName(checkfield)[k].value == checkvalue) {
                                         	    cmustcheck = 1;
                                         	}
			                    }
			                }
                                }
                                
                                if (cmustcheck == 0) {
                                	
       			                origtitle = document.getElementById(labelfield + "name").innerHTML;
                  	                if (origtitle.indexOf("<span") >= 0 || origtitle.indexOf("<SPAN") >= 0) {
			                    num1 = origtitle.indexOf(">");
			                    if (num1 > 20 && num1 < 40) {
			                        origtitle = origtitle.substr(num1+1);
			                    }
			                }
			                origtitle = origtitle.replace("</span>","")
			                origtitle = origtitle.replace("</SPAN>","")
	                                if (errorListCheck.search(origtitle) == -1) {
		                            document.getElementById(labelfield + "name").innerHTML = origtitle;
		                        }
                                }
                        }
                    }
                }
            }
        
            if (elem[i].name in optional == false || cmustcheck == 1) {
        
	            if (elem[i].type == "text" || elem[i].type == "textarea") {
	                origtitle = document.getElementById(labelfield + "name").innerHTML;
	                if (origtitle.indexOf("<span") >= 0 || origtitle.indexOf("<SPAN") >= 0) {
	                    num1 = origtitle.indexOf(">");
	                    if (num1 > 20 && num1 < 40) {
	                        origtitle = origtitle.substr(num1+1);
	                    }
	                }
	                origtitle = origtitle.replace("</span>","")
	                origtitle = origtitle.replace("</SPAN>","")
	            	if (elem[i].value == "") {
	                    error = 1;
	                    if (errorfield != "") {
	                        if (errorList.search(errorfield) == -1) {
	                             errorList += preError+errorfield + "\n";
	                             errorListCheck += origtitle + "\n";
                                     errorListCheck = errorListCheck.replace(/\*/gi,"");
	                        }
	                    } else {
	                        if (errorList.search(origtitle) == -1) {
	                             errorList += preError+origtitle + requiredText;
	                             errorListCheck += origtitle + "\n";
                                     errorListCheck = errorListCheck.replace(/\*/gi,"");
	                        }
	                    }
	                    document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
	                } else {
	                    //check if in array
	                    if (elem[i].id in variables) {
	                        if (variables[elem[i].id] == "PostalCode") {
	                            if (!isValidCAPostalCode(removeSpaces(elem[i].value))) {
	                                error = 1;
	                                if (errorList.search(origtitle) == -1) {
	                                    errorList += preError+origtitle + postalCodeText;
 	                                    errorListCheck += origtitle + "\n";
                                            errorListCheck = errorListCheck.replace(/\*/gi,"");
	                                }                            
	                                document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
	                            } else {
                 		        if (errorListCheck.search(origtitle) == -1) {
  	                                    document.getElementById(labelfield + "name").innerHTML = origtitle;
  	                                }
	                            }
	                        }
	                        if (variables[elem[i].id] == "Email") {
	                            if (!isValidEmailAddress(elem[i].value)) {
	                                error = 1;
	                                if (errorList.search(origtitle) == -1) {
	                                    errorList += preError+origtitle + emailText;
           	                            errorListCheck += origtitle + "\n";
	                                    errorListCheck = errorListCheck.replace(/\*/gi,"");
	                                }                            
	                                document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
	                            } else {
              		                if (errorListCheck.search(origtitle) == -1) {
 	                                    document.getElementById(labelfield + "name").innerHTML = origtitle;
 	                                }
	                            }
	                        }
	                        if (variables[elem[i].id] == "Numeric") {
	                            if (!isNumeric(elem[i].value)) {
	                                error = 1;
	                                if (errorList.search(origtitle) == -1) {
	                                    errorList += preError+origtitle + numberText;
              	                            errorListCheck += origtitle + "\n";
	                                    errorListCheck = errorListCheck.replace(/\*/gi,"");
	                                }                            
	                                document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
	                            } else {
               		                if (errorListCheck.search(origtitle) == -1) {
    	                                    document.getElementById(labelfield + "name").innerHTML = origtitle;
    	                                }
	                            }
	                        }
	                    }
	                    else {
                                if (errorListCheck.search(origtitle) == -1) {
                                    document.getElementById(labelfield + "name").innerHTML = origtitle;
                                }
	                    }

                        if (elem[i].id in matchfind) {
                            for(var matchfull in matchs) {
                                matchstring = matchfull.split("~~");
                                match1 = matchstring[0];                            
                                match2 = matchstring[1];                            
                                origtitle1 = document.getElementById(match2 + "name").innerHTML;
                                if (origtitle.indexOf("<span") >= 0 || origtitle.indexOf("<SPAN") >= 0) {
  		                    num1 = origtitle1.indexOf(">");
		                    if (num1 > 20 && num1 < 40) {
		                        origtitle1 = origtitle1.substr(num1+1);
		                    }
		                }
		                origtitle1 = origtitle1.replace("</span>","")
		                origtitle1 = origtitle1.replace("</SPAN>","")

                                if (elem[i].value != document.getElementById(match2).value) {
	                                error = 1;
	                                if (errorList.search(origtitle + ", " + origtitle1) == -1) {
	                                    errorList += preError+origtitle +", " + origtitle1 +  matchText;
 	                                    errorListCheck += origtitle + ", " + origtitle1 + "\n";
	                                }                            
	                                document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
	                            } else {
 	                                if (errorListCheck.search(origtitle) == -1) {
                                            document.getElementById(labelfield + "name").innerHTML = origtitle;
                                        }
	                            }
	                        }
                        } 

	            	}
	            } else if (elem[i].type == "select-one") {
	            	
	            	//age check
	            	if (elem[i].name in agecheck) {

			    origtitle = document.getElementById(labelfield + "name").innerHTML;
    	                    if (origtitle.indexOf("<span") >= 0 || origtitle.indexOf("<SPAN") >= 0) {
		                num1 = origtitle.indexOf(">");
		                if (num1 > 20 && num1 < 40) {
		                    origtitle = origtitle.substr(num1+1);
		                }
		            }
		            origtitle = origtitle.replace("</span>","")
		            origtitle = origtitle.replace("</SPAN>","")

	            	    agevalues = agecheck[elem[i].name];	
                            agesplit = agevalues.split("!!");
                            monthfield = agesplit[0];
                            dayfield = agesplit[1];
                            yearfield = agesplit[2];
                            age = agesplit[3];
                            for ( k =0; k < document.getElementById(monthfield).options.length; k++) {
                                if (document.getElementById(monthfield).options[k].selected) {
                                    month = document.getElementById(monthfield).options[k].value;
                                }
                            }
                            for ( k =0; k < document.getElementById(dayfield).options.length; k++) {
                                if (document.getElementById(dayfield).options[k].selected) {
                                    day = document.getElementById(dayfield).options[k].value;
                                }
                            }
                            for ( k =0; k < document.getElementById(yearfield).options.length; k++) {
                                if (document.getElementById(yearfield).options[k].selected) {
                                    year = document.getElementById(yearfield).options[k].value;
                                }
                            }
                            if(getAge(month,day,year) < age) {
	                        error = 1;

			        errorfieldage = "";
			        fa = elem[i].name + "age";
				if (fa in errorchange) {
					errorfieldage = errorchange[fa];
				}
				if (errorfieldage != "") {
		                        if (errorList.search(errorfieldage) == -1) {
		                             errorList += preError+errorfieldage + "\n";
               	                             errorListCheck += origtitle + "\n";
	                                     errorListCheck = errorListCheck.replace(/\*/gi,"");
		                        }
		                } else {
	                        	if (errorList.search(origtitle) == -1) {
	                              	    errorList += preError+origtitle + ageText + age + "\n";
	                                    errorListCheck += origtitle + "\n";
                                            errorListCheck = errorListCheck.replace(/\*/gi,"");
	                        	}
	                        }
	                        document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
                            } else {
	                        if (errorListCheck.search(origtitle) == -1) {
	                            document.getElementById(labelfield + "name").innerHTML = origtitle;
	                        }
  	                    } 
                 
	            		
	            	}
	            	
	                for ( j =0; j < elem[i].options.length; j++) {
	                    if (elem[i].options[j].selected) {
		                origtitle = document.getElementById(labelfield + "name").innerHTML;
 	                        if (origtitle.indexOf("<span") >= 0 || origtitle.indexOf("<SPAN") >= 0) {
		                    num1 = origtitle.indexOf(">");
		                    if (num1 > 20 && num1 < 40) {
		                        origtitle = origtitle.substr(num1+1);
		                    }
		                }
		                origtitle = origtitle.replace("</span>","")
		                origtitle = origtitle.replace("</SPAN>","")
	                        if (elem[i].options[j].value == "") {
	                            error = 1;

		                    if (errorfield != "") {
		                        if (errorList.search(errorfield) == -1) {
		                             errorList += preError+errorfield + "\n";
	                                     errorListCheck += origtitle + "\n";
	                                     errorListCheck = errorListCheck.replace(/\*/gi,"");
		                        }
		                    } else {
		                        if (errorList.search(origtitle) == -1) {
		                             errorList += preError+origtitle + requiredText;
	                                     errorListCheck += origtitle + "\n";
	                                     errorListCheck = errorListCheck.replace(/\*/gi,"");
		                        }
		                    }
	                            document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
	                        } else {

	                            if (errorListCheck.search(origtitle) == -1) {
	                                document.getElementById(labelfield + "name").innerHTML = origtitle;
	                            }
	                        }
	                    }
	                }
	            } else if (elem[i].type == "radio" || elem[i].type == "checkbox") {
	                mustcheck = 0;
	                if (elem[i].type == "radio") {
	                    mustcheck = 1;                
	                } else {
		                if (elem[i].name in variables) {
		                    if (variables[elem[i].name] == "Checkbox") {
	                                mustcheck = 1;                
		                    }
	                        }
	                }


	                if (mustcheck == 1 || cmustcheck == 1) {
		                checked = 0;
		                for ( j =0; j < document.getElementsByName(elem[i].name).length; j++) {	
		                    if (document.getElementsByName(elem[i].name)[j].checked) {
		                    	checked = 1;
		                    }
		                }
		                origtitle = document.getElementById(labelfield + "name").innerHTML;
 	                        if (origtitle.indexOf("<span") >= 0 || origtitle.indexOf("<SPAN") >= 0) {
 		                    num1 = origtitle.indexOf(">");
		                    if (num1 > 20 && num1 < 40) {
		                        origtitle = origtitle.substr(num1+1);
		                    }
		                }
		                origtitle = origtitle.replace("</span>","")
		                origtitle = origtitle.replace("</SPAN>","")
		                if (checked == 0) {
		                    error = 1;
		                    if (errorfield != "") {
		                        if (errorList.search(errorfield) == -1) {
		                             errorList += preError+errorfield + "\n";
	                                     errorListCheck += origtitle + "\n";
	                                     errorListCheck = errorListCheck.replace(/\*/gi,"");
		                        }
		                    } else {
		                        if (errorList.search(origtitle) == -1) {
		                             errorList += preError+origtitle + requiredText;
	                                     errorListCheck += origtitle + "\n";
	                                     errorListCheck = errorListCheck.replace(/\*/gi,"");
		                        }
		                    }
		                    document.getElementById(labelfield + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
		                } else {
    		                    if (errorListCheck.search(origtitle) == -1) {
 		                        document.getElementById(labelfield + "name").innerHTML = origtitle;
 		                    }
		                }
	                }

                        //check if at least one clicked in group
	                if (elem[i].name in clickedcheck) {
	                        splitstring = clickedline.split("~~");
	    	                for(j = 0; j < splitstring.length; j++) {
	    	                    if (splitstring[j] != "") {
	                   	        cc = splitstring[j];
	                                ccsplit = cc.split("!!");
	                                if (ccsplit[0] == elem[i].name) {
	                                    onefound  = 0;
	     	                            for(k = 0; k < ccsplit.length; k++) {
	      	                                if (ccsplit[k] != "") {
					                for ( l =0; l < document.getElementsByName(ccsplit[k]).length; l++) {	
					                    if (document.getElementsByName(ccsplit[k])[l].checked) {
					                    	onefound = 1;
					                    }
					                }
	                                        }
	                                    }
	                                    if (onefound == 0) {
	                                          errorList += preError + atleastText;
	                                    }
	     	                            for(k = 0; k < ccsplit.length; k++) {
	      	                                if (ccsplit[k] != "") {
				                    origtitle = document.getElementById(ccsplit[k] + "name").innerHTML;
 	                                            if (origtitle.indexOf("<span") >= 0 || origtitle.indexOf("<SPAN") >= 0) {
				                        num1 = origtitle.indexOf(">");
				                        if (num1 > 20 && num1 < 40) {
				                            origtitle = origtitle.substr(num1+1);
				                        }
				                    }
				                    origtitle = origtitle.replace("</span>","")
				                    origtitle = origtitle.replace("</SPAN>","")
	                                            if (onefound == 0) {
				                        error = 1;
				                        errorList += origtitle;
				                        if (k < (ccsplit.length -1)) {
				                            errorList += ",";
				                        }
                  	                                errorListCheck += origtitle + "\n";
 	                                                errorListCheck = errorListCheck.replace(/\*/gi,"");
					                document.getElementById(ccsplit[k] + "name").innerHTML = "<span style='color:"+ errorColour  + "'>" + origtitle + "</span>";
					            } else {
            		                                    if (errorListCheck.search(origtitle) == -1) {
					                        document.getElementById(ccsplit[k] + "name").innerHTML = origtitle;
					                    }
					            }
		                                }
	                                    }
	                                    if (onefound == 0) {
	                                          errorList += "\n";
	                                    }
	    	                        }
                  	        }
	                    }        
	                }

	            }
            }
        } 
        if (error == 1) {
            errorList = errorList.replace(/:/g,"");
            errorList = errorList.replace(/\*/g,"");
            errorList = errorList.replace(/<B[^>]*?>/ig,"");
            errorList = errorList.replace(/<\/B>/ig,"");
            errorList = errorList.replace(/&amp;/ig,"&");

            errorfield = errorText;
	    if ("error" in errorchange) {
		errorfield = errorchange["error"];
	    }
            alert(errorfield + errorList);
        	return false;
        } else {
            return true;
        }
	}
	
	function isEmpty( str ) {   
        return ( ( str == null ) || ( str.length == 0 ) );
    }
	
	function lTrim( str ) {
        return str.replace( /^\s+/, '' );
    }

    function rTrim( str ) {
        return str.replace( /\s+$/, '' );
    }

    function trim( str ) {
        return rTrim( lTrim( str ) );
    }
	
	function isValidEmailAddress( str ) {
        return RE_EMAIL.test( trim( str ) );
    }

    function isValidCAPostalCode( str ) {
        return RE_CA_POSTAL_CODE.test( trim( str ) );
    }
	
    function isNumeric(sText) {
        var ValidChars = "0123456789%-()";
        var IsNumber=true;
        var Char;

        for (i = 0; i < sText.length && IsNumber == true; i++) { 
            Char = sText.charAt(i); 
            if (ValidChars.indexOf(Char) == -1) {
                IsNumber = false;
            }
        }
        return IsNumber;
    }
    
    function removeSpaces(string) {
    	var tstring = "";
	    string = '' + string;
    	splitstring = string.split(" ");
  	    for(i = 0; i < splitstring.length; i++)
  	        tstring += splitstring[i];
	    return tstring;
    }
    
	
	
    function getAge(dob_month, dob_day, dob_year) {

        var yearNow;
        var monthNow;
        var dob_year;

        var now = new Date();
        var today = new Date(now.getYear(),now.getMonth(),now.getDate());

        yearNow = now.getYear();
        if (yearNow < 200) {
            yearNow += 1900;
        }
        if (dob_year < 200) {
            dob_year += 1900;
        }

        monthNow = now.getMonth();
        dateNow = now.getDate();

        dob_month = parseInt(dob_month);
        dob_day   = parseInt(dob_day);
        dob_year  = parseInt(dob_year);

        var age = yearNow-dob_year;
        if((dob_month >= monthNow)&&(dob_day > dateNow)) {
          age--;
        }
        return age;
    }

    function checkDate(month, day, year) {

       var originalDate = month + "/" + day + "/" + year;
       var checkDate = new Date(originalDate);

       if((checkDate.getMonth()+1) == month) {
         return true; 
       } else {
         return false;
       }
    }
	
	

	
	