// Copyright Hardeep Singh Salh
// 	hardeepsingh@sebiz.net
// Usage is as follows
//<form name='frm' method='post' action=''
//onSubmit='return theValidator(this,"Input1,Input3,temp,ta,rad","Name,Zip Code,Template,Comments,University/Non-University",",Y,,,",",,,,",",,,,");'>


//The parameters
// 0) The instance of the form , use 'this' rather than name
// 1) The name of the controls separated by comma, only add name of controls which you want to be validated.
// 2) The Message i.e if you write Name, then the msg would be 'Name cannot be blank!'
// 3) If you want any control to be validated for numeric value, then specify 'Y'
//    exactly in the same order if the 1st parameter has values Input1,Input2,temp,.. if you want to validate the Input2
//    control for numeric value the ,Y,,....
// 4) Email parameter - order as point 3
// 5) URL parameter - order as point 3
// TODO:
//	Email Validation - Done
//	URL Validation	- Done
// Declaring valid date character, minimum year and maximum year

function theValidator(theForm,theControl,theMessage,theBlank,theAlphabetic,theAlphanumeric,theNumeric,theFloat,theEMail,theURL,theZip,thePhone,theFax)
{
	// This function is used to validate that all text
	// fields in a given form contain some value
	//Split the controls + Messages + Numerics by comma ,
	var theControls = new Array();
	var theMessages = new Array();
	var theBlanks = new Array();
	var theAlphabetics = new Array();
	var theAlphanumerics = new Array();
	var theNumerics = new Array();
	var theFloats = new Array();
	var theEMails = new Array();
	var theURLs = new Array();
	var theZips = new Array();
	var thePhones = new Array();
	var theFaxs = new Array();
	var theSplCharacters = new Array();

	theControls=theControl.split(",");
	theMessages=theMessage.split(",");
	theBlanks=theBlank.split(",");
	theAlphabetics=theAlphabetic.split(",");
	theAlphanumerics=theAlphanumeric.split(",");
	theNumerics=theNumeric.split(",");
	theFloats=theFloat.split(",");
	theEMails=theEMail.split(",");
	theURLs=theURL.split(",");
	theZips=theZip.split(",");
	thePhones=thePhone.split(",");
	theFaxs=theFax.split(",");
	theSplCharacters=theSplCharacter.split(",");


	for (var i=0; i < theForm.elements.length; i++){
		//alert("Type: " + theForm.elements[i].type + " \n\nName: "+ theForm.elements[i].name)
		for(var counter=0;counter < theControls.length; counter++)
		{
			if (theForm.elements[i].name == theControls[counter])
			{
				var eok;
				if(theBlanks[counter] == "Y")
					eok=false;
				else
					eok=true;

				//Text Box validation
				if (theForm.elements[i].type == 'text' || theForm.elements[i].type == 'password')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '' && theBlanks[counter] == "Y" && !theForm.elements[i].disabled)
					{
						alert("Please enter the "+theMessages[counter]+".");
						theForm.elements[i].value = "";
						theForm.elements[i].focus();
						return false;
					}
					// Numeric value check
					if (trim(theForm.elements[i].value) != '' && theNumerics[counter] == "Y")
					{
						if(!isInteger(trim(theForm.elements[i].value), eok))
						{
							alert(theMessages[counter] + " is invalid.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Float value check
					if (trim(theForm.elements[i].value) != '' && theFloats[counter] == "Y")
					{
						if(!isFloat (theForm.elements[i].value ,eok) )
						{
							alert(theMessages[counter] + " is invalid.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Alphabetic value check
					if (trim(theForm.elements[i].value) != '' && theAlphabetics[counter] == "Y")
					{
						if(!isAlphabetic (theForm.elements[i].value ,eok) )
						{
							alert(theMessages[counter] + " contains invalid characters.");
							theForm.elements[i].focus();
							return false;
						}
					}


					// Alphanumeric value check
					if (trim(theForm.elements[i].value) != '' && theAlphanumerics[counter] == "Y")
					{
						if(!isAlphanumeric(theForm.elements[i].value ,eok) )
						{
							alert(theMessages[counter] + " contains invalid characters.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Email value check
					if (trim(theForm.elements[i].value) != '' && theEMails[counter] == "Y")
					{
						if(!validateEmail(trim(theForm.elements[i].value)))
						{
							alert(" Invalid Email Address\n Should be user@domain.com");
							theForm.elements[i].focus();
							return false;
						}
					}
					// URL value check
					if (trim(theForm.elements[i].value) != '' && theURLs[counter] == "Y")
					{
						if(!validateURL(trim(theForm.elements[i].value)))
						{
							alert(" Invalid URL \n Should be http://www.domain.com");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Zip value check
					if (trim(theForm.elements[i].value) != '' && theZips[counter] == "Y")
					{
						if(!checkZIPCode(theForm.elements[i],eok))
						{
							//alert(theMessages[counter] + " is invalid.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Phone value check
					if (trim(theForm.elements[i].value) != '' && thePhones[counter] == "Y")
					{
						if(!checkUSPhone(theForm.elements[i], eok))
						{
							//alert(theMessages[counter] + " is invalid.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Fax value check
					if (trim(theForm.elements[i].value) != '' && theFaxs[counter] == "Y")
					{
						if(!checkUSPhone(theForm.elements[i], eok))
						{
							alert(theMessages[counter] + " is invalid.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Special Character value check
					if (trim(theForm.elements[i].value) != '' && theSplCharacters[counter] == "Y")
					{
						if(!isSplCharacter (theForm.elements[i].value ,eok) )
						{
							alert(theMessages[counter] + " contains invalid characters.");
							theForm.elements[i].focus();
							return false;
						}
					}

				}

				// Password Validation
				if (theForm.elements[i].type == 'password')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '')
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;
					}
				}

				//Select box validation
				if (theForm.elements[i].type == "select-one" && theBlanks[counter] == "Y")
				{
					var selIndex,selValue;
					selIndex=theForm.elements[i].selectedIndex;
					var theObject=theForm.elements[i];
					selValue = theObject[selIndex].value;
					if( trim(selValue) == "" || trim(selValue) == "0")
					{
						alert("You must select " + theMessages[counter] + ".");
						theForm.elements[i].focus();
						return false;
					}
				}

			// File Box Validation

				if (theForm.elements[i].type == "file")
				{
					var fileValue;
					fileValue=theForm.elements[i].value;
					if( trim(fileValue) == "")
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;
					}
					if(!imageCheck(theForm.elements[i].value))
					{
						alert('You can only upload images of type jpg, jpeg, gif');
						theForm.elements[i].focus();
						return false;
					}

				}

			function imageCheck(img) {
			  //making sure the user only uploads jpeg, jpg, gif files.
			  var testStr = '.jpeg.jpg.gif.pjpg.JPEG.JPG.GIF.PJPG';
			  var txt = img;
			 // alert(txt.substring(txt.lastIndexOf('.'))) //just for illustration!
			  if (testStr.indexOf(txt.substring(txt.lastIndexOf('.'))) == -1) {
			  return false;
			  }
			  return true;
			}
			// Hidden Box Validation

				if (theForm.elements[i].type == "hidden")
				{
					var hiddenValue;
					hiddenValue=theForm.elements[i].value;
					if( trim(hiddenValue) == "")
					{
						alert("Must select atleast one " + theMessages[counter] + ".");
						return false;
					}
				}

			// Text Area Validation

				if (theForm.elements[i].type == "textarea")
				{
					var txtAreaValue;
					txtAreaValue=theForm.elements[i].value;
					if( trim(txtAreaValue) == "")
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;
					}
				}

			// Radio Button Validation
			// This radio button validation is buggy so I am commneting it out
			/*	if(theForm.elements[i].type == "radio")
				{
					//alert(theForm.elements[i].value);
					if(getRadioButtonValue(theForm.elements[i],theForm.elements[i].name) == "-1")
					{
						alert("You must select " + theMessages[counter] + "!");
						return false;
					}
				}*/
			}

		}
	}
	return true;
}


function theDataValidator(theForm,theControl,theMessage,theNumeric,theText)
{
	// This function is used to validate that all text
	// fields in a given form contain some value
	//Split the controls + Messages + Numerics by comma ,

	var theControls = new Array();
	var theMessages = new Array();
	var theNumerics = new Array();
	var theTexts = new Array();

	theControls=theControl.split(",");
	theMessages=theMessage.split(",");
	theNumerics=theNumeric.split(",");
	theTexts=theText.split(",");

//	alert(theControl);
	for (var i=0; i < theForm.elements.length; i++)
	{
		//alert("Type: " + theForm.elements[i].type + " \n\nName: "+ theForm.elements[i].name)
		for(var counter=0;counter < theControls.length; counter++)
		{
			if (theForm.elements[i].name == theControls[counter])
			{
			//Data Type
				if (theForm.elements[i].type == 'text')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) != '' && theTexts[counter] == "Y")
					{
						if(!is_alpha(trim(theForm.elements[i].value)))
						{
							alert(theMessages[counter] + " cannot contain numeric values.");
							theForm.elements[i].focus();
							return false;
						}
					}
					// Numeric value check
					if (trim(theForm.elements[i].value) != '' && theNumerics[counter] == "Y")
					{
						if(isNaN(trim(theForm.elements[i].value)))
						{
							alert(theMessages[counter] + " should be numeric.");
							theForm.elements[i].focus();
							return false;
						}
					}
				}
			// Text Area Validation

				if (theForm.elements[i].type == "textarea")
				{
					var txtAreaValue;
					txtAreaValue=theForm.elements[i].value;
					if( trim(txtAreaValue) == "")
					{
						alert(theMessages[counter] + " cannot be blank.");
						theForm.elements[i].focus();
						return false;
					}
				}
			}// if of control name match
		} // end of for(var counter=0;counter < theControls.length; counter++)
	}// end of for (var i=0; i < theForm.elements.length; i++)
	return true;
}


function getRadioButtonValue(theForm,theControl)
{
	var i;
	alert("Hello " + theForm + " control.length: " + theControl.length);
	for( i=0; i< theControl.length; ++i)
	{
alert(theForm[i].checked);
		if( theControl[i].checked)
		{

			return theControl[i].value;
		}
	}

	// default (non selected)
	return -1;
}

function ltrim ( s )
{

	return s.replace( /^\s*/, "" )
}

function rtrim ( s )
{
	return s.replace( /\s*$/, "" );
}

function trim ( s )
{
	return rtrim(ltrim(s));
}


function validateEmail(email){

	// This function is used to validate a given e-mail
	// address for the proper syntax
	//alert ("in email check");
	if (email == ""){
		return false;
	}
	badStuff = ";:/,' \"\\";
	for (i=0; i<badStuff.length; i++){
		badCheck = badStuff.charAt(i)
		if (email.indexOf(badCheck,0) != -1){
			return false;
		}
	}
	posOfAtSign = email.indexOf("@",1)
	if (posOfAtSign == -1){
		return false;
	}
	if (email.indexOf("@",posOfAtSign+1) != -1){
		return false;
	}
	posOfPeriod = email.indexOf(".", posOfAtSign)
	if (posOfPeriod == -1){
		return false;
	}
	if (posOfPeriod+2 > email.length){
		return false;
	}
	return true
}

function isSplCharacter(email){

	// This function is used to validate a given e-mail
	// address for the proper syntax
	//alert ("in email check");
	if (email == ""){
		return false;
	}
	badStuff = ";:/,'\"\\+-%&*^#@$";
	for (i=0; i<badStuff.length; i++){
		badCheck = badStuff.charAt(i)
		if (email.indexOf(badCheck,0) != -1){
			return false;
		}
	}
	return true
}


function validateURL(url){

	// This function is used to validate a given
	// address for the proper syntax
	url="http://"+url;
	var re;
	re = new RegExp("(http|ftp|https)://[-A-Za-z0-9._/]+");
	if (re.test(url)==false)
		return false;

	posOfAtSign = url.indexOf(".")

	if (posOfAtSign == -1){
		return false;
	}
	return true;
}
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function confirmdelete(theform,str,startelement,endelement)
{
	 var count=theform.elements.length;
	 var flag=0;
	 for(i=startelement;i<count-endelement;i++)
	 {

			if (theform.elements[i].checked == true)
				flag=1;
	}
	if(flag==0)
	{
		alert("Please select the "+str+" you want to delete.");
		return false;
	}
	else
	{
		if (confirm("Are you sure you want to delete the selected "+str+"?"))
			return true;
		else
			return false;
	}

}
function confirmation2(theform,startelement,endelement)
{
	 var count=theform.elements.length;
	 var flag=0;
	 for(i=startelement;i<count-endelement;i++)
	 {

			if (theform.elements[i].checked == true)
				flag=1;
	}
	if(flag==0)
	{
		alert("Please select the checkbox");
		return false;
	}
	return true;

}

function is_alpha(str)
{
	var alphaCount=0;
	var alph_valid="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	var sizechar=str.length;

    for (var i=0; i<sizechar; i++) {
        if (alph_valid.indexOf(str.charAt(i)) < 0) {
            alphaCount++
        }
    }

    if(alphaCount>0)
    	return false;
    else
    	return true;

}


function changestate(countryCtl,stateCtl,state1Ctl)
{
	//alert(countryCtl.selectedIndex);
	x=countryCtl.selectedIndex;
	isuid=countryCtl[x].text;

	if(isuid=="United States")
	{
		state1Ctl.value="";
		state1Ctl.disabled=true;
		stateCtl.disabled=false;
	}
	else
	{
		stateCtl.disabled=true;
		state1Ctl.disabled=false;
	}
}
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
}
