// Copyright Akash Thakural
// 	akash@pugmarksdesign.com
// 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

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();
	
	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(",");

	
	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")
					{
						alert("Please enter the "+theMessages[counter]+".");
						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;	
						}
					}
				}
				
				// 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;	
					}
				}
			// 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 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;
	}
}
