
//<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
 //implementation
/*
function check(theform)
{
	thecontrols="vchAttorneyName,vchFirmName,vchAddress1,vchAddress2,vchStateName,vchCity,vchZipCode,vchPhone,vchFax,vchEmailAddress,intFormatID";
	themessages="Attorney name,Firm name,Address,Address,State,City,Zipcode,Phone,Fax,Email address,Format";
	theNumeric=",,,,,,,,,,";
	theEmail=",,,,,,,,,Y,";
	theURL=","
	theConfirmPassword=",";
	thebadstuff="1,1,,,,,,,,,";
	theinteger=",,,,,,,,,,";
	thepercent=",";
	thesize=",,,,,,,,,,";
	thedecimal=",,,,,,,,,,";
	theimage=",";
	theempty="Y,Y,Y,,Y,Y,Y,Y,,Y,Y";
	themin=",";
	themax=",";
	thecheckboxlength=",,,,,,,,,,";
	thephoneno=",,,,,,,Y,Y,,";
	
	if(!theValidator(theForm,theControl,theMessage,theNumeric,theEMail,theURL,theConfirmPassword,thebadstuff,theinteger,thepercent,thesize,thedecimal,theimage,theempty,themin,themax,thecheckboxlength,thephoneno))
		return false;

	return true;
}
*/

//	*************************************  theValidator **********************************************************

function theValidator(theForm,theControl,theMessage,theNumeric,theEMail,theURL,theConfirmPassword,thebadstuff,theinteger,thepercent,thesize,thedecimal,theimage,theempty,themin,themax,thecheckboxlength,thephoneno)
{
	// 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 theMessages = new Array();
	var theNumerics = new Array();
	var theEMails = new Array();
	var theURLs = new Array();
	var theConfirmPasswords = new Array();

	theControls=theControl.split(",");
	theMessages=theMessage.split(",");
	theNumerics=theNumeric.split(",");
	theEMails=theEMail.split(",");
	theURLs=theURL.split(",");
	thebadstuffs=thebadstuff.split(",");
	theintegers=theinteger.split(",");
	thepercents=thepercent.split(",");
	thesizes=thesize.split(",");
	thedecimals=thedecimal.split(",");
	theimages=theimage.split(",");
	theemptys=theempty.split(",");
	themins=themin.split(",");
	themaxs=themax.split(",");
	thecheckboxlengths=thecheckboxlength.split(",");
	theConfirmPasswords=theConfirmPassword.split(",");
	thephonenos=thephoneno.split(",");
	//alert(thecheckboxlength);
	//alert(theForm.elements.length);

//	alert(theControl);
	for (var i=0; i < theForm.elements.length; i++)
	{
//		alert("Type: " + theForm.elements[i].type);

		for(var counter=0;counter < theControls.length; counter++)
		{
			if (theForm.elements[i].name == theControls[counter])
			{
				if (theForm.elements[i].type == 'file')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '' && theemptys[counter] == "Y" )
					{
//						alert(theMessages[counter] + " cannot be blank.");
						alert("Please upload the "+theMessages[counter].toLowerCase()+".");
						theForm.elements[i].focus();
						return false;	
					}
					else
					{
						if (theimages[counter] == "Y")
						{
							var s=theForm.elements[i].value;
						
							if (s!="")
							{
								array=s.split("\\");
								len=array.length;
								filename=array[len-1];
								array1=filename.split(".");
								if (array1.length == 1)
								{
									alert("Files with extensions .gif, .jpg, .jpeg, .jpe can only be uploaded.");
									theForm.elements[i].focus();
									return false;									
								}
								//if(array1[1].toLowerCase()!="jpg" && array1[1].toLowerCase()!="jpeg" && array1[1].toLowerCase()!="gif" && array1[1].toLowerCase()!="png")
								if(array1[1].toLowerCase()!="jpg" && array1[1].toLowerCase()!="jpeg" && array1[1].toLowerCase()!="gif" && array1[1].toLowerCase()!="jpe")
								{
									alert("Files with extensions .gif, .jpg, .jpeg, .jpe can only be uploaded.");
									theForm.elements[i].focus();
									return false;
								}
							}
						}
						if (theimages[counter] == "C")
						{
							var s=theForm.elements[i].value;
							if (s!="")
							{
								array=s.split("\\");
								len=array.length;
								filename=array[len-1];
								array1=filename.split(".");
								len1 = array1.length;
								len1 = len1-1;
								if (array1.length == 1)
								{
									alert("Files with extensions .txt, .doc, .pdf can only be uploaded.");
									theForm.elements[i].focus();
									return false;									
								}
								if(array1[len1].toLowerCase()!="txt" && array1[len1].toLowerCase()!="doc" && array1[len1].toLowerCase()!="pdf")
								{
									alert("Files with extensions .txt, .doc, .pdf can only be uploaded.");
									theForm.elements[i].focus();
									return false;
								}
							}
						}
						if (theimages[counter] == "YC")
						{
							var s=theForm.elements[i].value;
							if (s!="")
							{
								array=s.split("\\");
								len=array.length;
								filename=array[len-1];
								array1=filename.split(".");
								len1 = array1.length;
								len1 = len1-1;
								if (array1.length == 1)
								{
									alert("Files with extensions .gif, .jpg, .jpeg, .txt, .doc, .pdf can only be uploaded.");
									theForm.elements[i].focus();
									return false;									
								}
								if(array1[len1].toLowerCase()!="jpg" && array1[len1].toLowerCase()!="jpeg" && array1[len1].toLowerCase()!="gif" && array1[len1].toLowerCase()!="txt" && array1[len1].toLowerCase()!="doc" && array1[len1].toLowerCase()!="pdf")
								{
									alert("Files with extensions .gif, .jpg, .jpeg, .txt, .doc, .pdf can only be uploaded.");
									theForm.elements[i].focus();
									return false;
								}
							}
						}

					}

				}

				if (theForm.elements[i].type == 'text')
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '' && theemptys[counter] == "Y")
					{
//						alert(theMessages[counter] + " cannot be blank.");
						alert("Please enter the "+theMessages[counter].toLowerCase()+".");
						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.");
							alert("Please enter numeric values for "+theMessages[counter].toLowerCase()+".");
							theForm.elements[i].focus();
							return false;	
						}
						if(trim(theForm.elements[i].value)<= 0 )
						{
//							alert(theMessages[counter] + " should be greater than 0.");
							alert("Please enter "+theMessages[counter].toLowerCase()+" greater than  0 (zero).");
							theForm.elements[i].focus();
							return false;	
						}					
					}

					if  (trim(theForm.elements[i].value) != '' && theintegers[counter] == "Y")
					{
							if(isNaN(trim(theForm.elements[i].value)))
								{
		//							alert(theMessages[counter] + " should be numeric.");
									alert("Please enter numeric values for "+theMessages[counter].toLowerCase()+".");
									theForm.elements[i].focus();
									return false;	
								}
							if(parseInt(trim(theForm.elements[i].value))< 0 )
								{
								alert("Please enter "+theMessages[counter].toLowerCase()+" greater than or equal to 0 (zero).");
								theForm.elements[i].focus();
								return false;
								}
					}

					
					if (trim(theForm.elements[i].value) != '' && thebadstuffs[counter] != "")
					
					//////////////
					{
						if (thebadstuffs[counter]==1 || thebadstuffs[counter]==7)
								badStuff = "~`!@#$%^&*()=+|<>?;:/\"\\";
							else if(thebadstuffs[counter]==2)
								badStuff="~`!@$%^&*()=+|<>?;:/\"\\";
							else if(thebadstuffs[counter]==3)
							{
								badStuff="~`!@#$%^&*()=+|<>?;:/\"\\";//spl chars & spaces (username)
								badStuff+=" ";
							}
							else if(thebadstuffs[counter]==4)
								badStuff="0123456789~`!@#$%^&*()=+|<>?;:/\"\\";
							else if (thebadstuffs[counter]==8)
								badStuff = "~`!@#$%^&()=+|<>?;:/\"\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
							else
								badStuff='"';
							chkstring = trim(theForm.elements[i].value);
							if(thebadstuffs[counter]==3) //username - first char shud be alphabet
							{
								alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
								//reg=/^([a-zA-Z])+$/
								firstchar=chkstring.substring(0,1);
								if(alphabets.search(firstchar)==-1)
								{
									alert("The first character of the "+theMessages[counter]+" should be an alphabet.");
									theForm.elements[i].focus();
									return false;
								}
							}
							for (x=0; x<badStuff.length; x++)
							{
								badCheck = badStuff.charAt(x);
								
								if (chkstring.indexOf(badCheck,0) != -1)
								{							
									if(badStuff=='"')
									alert("Please replace double quotes with single quotes for "+theMessages[counter].toLowerCase()+".");
									else
									{
										abc=theMessages[counter].replace(theMessages[counter],theMessages[counter].charAt(0).toUpperCase());
										//alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+ " should be greater than 0.");
										if(thebadstuffs[counter]==1)
											alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have special characters.");

										/*else if (thebadstuffs[counter]==5 || thebadstuffs[counter]==7)
											alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have all the numbers.");*/
										else if (thebadstuffs[counter]==3)
											alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have special characters or spaces.");

										else if (thebadstuffs[counter]==8) 
											alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have special characters or alphabets.");
										else
											alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have special characters or numerics.");
									}
									theForm.elements[i].focus();
									return false;
								}
							}
							
							badStuff="";
							flg=0;
							if (thebadstuffs[counter]==5 || thebadstuffs[counter]==7)
								badStuff = "0123456789";
							else if (thebadstuffs[counter]==6)
								badStuff ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
							if(badStuff != "")
							{
								for (x=0; x<badStuff.length; x++)
								{
									badCheck = badStuff.charAt(x);
									
									if (chkstring.indexOf(badCheck,0) == -1)
										flg=1;
									else {
										flg=0;
										break;
									}
									
								}
								if (flg == 1)
								{							
									abc=theMessages[counter].replace(theMessages[counter],theMessages[counter].charAt(0).toUpperCase());
									//alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+ " should be greater than 0.");
									if (thebadstuffs[counter]==5 || thebadstuffs[counter]==7)
										alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have all characters as alphabets.");
									else 
										alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have all the numbers.");
								
									theForm.elements[i].focus();
									return false;
								}
							}
						
							

						} // end if badstuff
					////////////////
					if (trim(theForm.elements[i].value) != '' && thepercents[counter] == 'Y')
					{			
								if (parseInt(theForm.elements[i].value)<0 || parseInt(theForm.elements[i].value)>100)
								{							
									abc=theMessages[counter].replace(theMessages[counter],theMessages[counter].charAt(0).toUpperCase());
																
									alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" should have value between 0 to 100.");
									theForm.elements[i].focus();
									return false;
								}
					}

					
					if (trim(theForm.elements[i].value) != '' && thesizes[counter] != "")
					{
								if (trim(theForm.elements[i].value).length>thesizes[counter])
								{							
																
//									alert(theMessages[counter]+" cannot have more than "+thesizes[counter]+" characters.");	
									alert("Maximum characters allowed are "+ thesizes[counter] +". Entered are "+ theForm.elements[i].value.length +" characters.");	
									theForm.elements[i].focus();
									return false;
								}
					}
					
					if (trim(theForm.elements[i].value) != '' && thedecimals[counter] == "Y")
					{
								var str=theForm.elements[i].value;
									 if (str.indexOf('.')!=-1)
										{
										   alert("No decimals allowed for "+theMessages[counter].toLowerCase()+".");
										    theForm.elements[i].focus();
											return false;
										}
					}

					if (trim(theForm.elements[i].value) != '' && thephonenos[counter] == "Y")
					{
						var regexp=/^(\d{3}-\d{3}-\d{4}|\d{10}|\(\d{3}\)\d{3}-\d{4}|\d{6}|\d{7}|\d{8})$/;
						x = trim(theForm.elements[i].value);
						
						/*aaa=/^[a-zA-Z]+$/;
						if(!aaa.test(x))
						{
							alert("Please enter numeric values for "+theMessages[counter].toLowerCase()+".");
							return false;
						};
						alert("HI");
						alert(c);
						return false;*/
						if(!(regexp.test(x)))
						{
							var msg = "";
							msg = "Please enter the correct "+theMessages[counter].toLowerCase();
							msg = msg +  "\n The correct forms are : ";
							msg = msg + "\n xxx-xxx-xxxx";
							msg = msg + "\n (xxx)xxx-xxxx";
							msg = msg + "\n xxxxxxxxxx (10 digited Mobile no)";
							msg = msg + "\n xxxxxx (6 digits no)";
							msg = msg + "\n xxxxxxx (7 digits no)";
							msg = msg + "\n xxxxxxxx (8 digits no)";

							alert(msg);
						    theForm.elements[i].focus();
							return false;
						}
					}

					// Email value check
					if (trim(theForm.elements[i].value) != '' && theEMails[counter] == "Y")
					{
						if(!emailcheck(theForm.elements[i],"Please enter valid email address."))  return false;
						//{
						//	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");
							alert("Please enter valid url. \n http://www.domain.com");
							theForm.elements[i].focus();
							return false;	
						}
					}
					
					if (trim(theForm.elements[i].value) !='' && themins[counter]!='' && themaxs[counter]!='')
					{
						if(parseInt(theForm.elements[i].value)<themins[counter] || parseInt(theForm.elements[i].value)>themaxs[counter])
						{
							alert("Please enter value for "+theMessages[counter].toLowerCase()+" between "+themins[counter]+" and "+themaxs[counter]+".");
							theForm.elements[i].focus();
							return false;
						}
					}
					if (trim(theForm.elements[i].value) !='' && themins[counter]!='' && themaxs[counter]=='')
					{
						if((theForm.elements[i].value.length)<themins[counter])
						{
							alert("Please enter valid "+theMessages[counter].toLowerCase()+".");
							theForm.elements[i].focus();
							return false;
						}
					}
					if (trim(theForm.elements[i].value) !='' && themaxs[counter]!='')
					{
						if( parseInt(theForm.elements[i].value)>themaxs[counter])
						{
							alert("Please enter value for "+theMessages[counter].toLowerCase()+" less than "+themaxs[counter]+".");
							theForm.elements[i].focus();
							return false;
						}
					}
				
				}
				// Password Validation
				if (theForm.elements[i].type == 'password' && theConfirmPasswords[counter]!="Y")
				{
					//Blank value check
					if (trim(theForm.elements[i].value) == '')
					{
//						alert(theMessages[counter] + " cannot be blank.");
						alert("Please enter the "+theMessages[counter].toLowerCase()+".");
						theForm.elements[i].focus();
						return false;	
					}
					if(theForm.elements[i].name=="vchCVCCode")
					{
						chkstring = trim(theForm.elements[i].value);
						//if (thebadstuffs[counter]==8)
							badStuff ="~`!@#$%^&()=+|<>?;:/\"\\ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
							for (x=0; x<badStuff.length; x++)
							{
								badCheck = badStuff.charAt(x);
								
								if (chkstring.indexOf(badCheck,0) != -1)
								{	
									abc=theMessages[counter].replace(theMessages[counter],theMessages[counter].charAt(0).toUpperCase());
									alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have special characters or alphabets.");
									theForm.elements[i].focus();
									return false;
								}
							}
					}//cvc code
					else
					{
						if(theForm.elements[i].value.length > 14)
						{
							alert("Password cannot have more than 14 characters.");	
							theForm.elements[i].focus();
							return false;
						}


							if(theForm.elements[i].value.length < 6)
						{
							alert("Password cannot be less than 6 characters.");	
							theForm.elements[i].focus();
							return false;
						}
						badStuff="~`!@#$%^&*()=+|<>?;:/\"\\";
						badStuff+=" ";
						chkstring = theForm.elements[i].value;
						for (x=0; x<badStuff.length; x++)
						{
							badCheck = badStuff.charAt(x);
							if (chkstring.indexOf(badCheck,0) != -1)
							{	
								abc=theMessages[counter].replace(theMessages[counter],theMessages[counter].charAt(0).toUpperCase());	alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have special characters or spaces.");

								theForm.elements[i].focus();
								return false;
							}
						}
					}
				}	

				// Confirm Password Validation
				//alert(theForm.elements[i].type);
				//alert(theConfirmPassword[counter]);
				if (theForm.elements[i].type=='password' && theConfirmPasswords[counter]=="Y")
				{
					//alert("mandeep");
					//alert(theForm.elements[i].value);
					//alert(theForm.elements[i-1].value);

					//Blank value check
					if (trim(theForm.elements[i].value) == '')
					{
//						alert(theMessages[counter] + " cannot be blank.");
						alert("Please retype the "+theMessages[counter].toLowerCase()+".");
						theForm.elements[i].focus();
						return false;	
					}
					

						if(theForm.elements[i].value.length > 14)
					{
						alert("Password cannot have more than 14 characters.");	
						theForm.elements[i].focus();
						return false;
					}


						if(theForm.elements[i].value.length < 6)
					{
						alert("Password cannot be less than 6 characters.");	
						theForm.elements[i].focus();
						return false;
					}
					badStuff="~`!@#$%^&*()=+|<>?;:/\"\\";
					badStuff+=" ";
					chkstring = theForm.elements[i].value;
					for (x=0; x<badStuff.length; x++)
					{
						badCheck = badStuff.charAt(x);
						if (chkstring.indexOf(badCheck,0) != -1)
						{	
							abc=theMessages[counter].replace(theMessages[counter],theMessages[counter].charAt(0).toUpperCase());	alert(abc+theMessages[counter].substring(1,theMessages[counter].length)+" can not have special characters or spaces.");

							theForm.elements[i].focus();
							return false;
						}
					}
					if (theForm.elements[i].value!=theForm.elements[i-1].value)
					{
//						alert(theMessages[counter] + " is not same.");
						alert("Passwords do not match.");
						theForm.elements[i].focus();
						return false;	
					}

				}	
				

			//Select box validation
				if (theForm.elements[i].type == "select-one")
				{
					var selIndex,selValue;
					selIndex=theForm.elements[i].selectedIndex;
					var theObject=theForm.elements[i];
					selValue = theObject[selIndex].value;
					if( trim(selValue) == "" || trim(selValue) == "0")
					{
						alert("Please select the " + theMessages[counter].toLowerCase() + ".");
						theForm.elements[i].focus();
						return false;	
					}
				}
			//Check box validation
				//alert(theForm.elements[i].type);
				//alert(theemptys[counter]);
				if (theForm.elements[i].type == "checkbox" && theemptys[counter] == "Y" )
				{ 
					var flagchecked="0";	
					
//					theControls[counter]=theControls[counter].substr(0,theControls[counter].length-2);
//					checkboxname=eval("theForm."+theControls[counter]);
					if (parseInt(thecheckboxlengths[counter]) > 1)
					{				
//						for (j=0;j<parseInt(thecheckboxlengths[counter]);j++)
						for (j=i;j<i+parseInt(thecheckboxlengths[counter]);j++)

						{	
//							checkbox1=eval(checkboxname[j]);				
//							if(checkbox1.checked==true)
							checkbox1=eval(theForm.elements[j]);				
							if(checkbox1.checked==true)
							{	
								flagchecked="1";
								break;
							}
						}
					}
					else
					{
						if(theForm.checkboxname.checked==true)
						{	
							flagchecked="1";
						}				
					}
					if (flagchecked=="0")
					{
						alert("Please select the " + theMessages[counter].toLowerCase() + ".");
						theForm.elements[i].focus();
						return false;	
					}
					i=i+parseInt(thecheckboxlengths[counter])-1;
				}
			
			// Text Area Validation
				if (theForm.elements[i].type == "textarea")
				{
					var txtAreaValue;
					txtAreaValue=theForm.elements[i].value;
					if( trim(txtAreaValue) == "" && theemptys[counter] == "Y")
					{
//						alert(theMessages[counter] + " cannot be blank.");
						alert("Please enter the "+theMessages[counter].toLowerCase()+".");
						theForm.elements[i].focus();
						return false;	
					}
					if (trim(theForm.elements[i].value) != '' && thesizes[counter] != "")
					{
								if (trim(theForm.elements[i].value).length>thesizes[counter])
								{							
										//Maximum characters allowed are n. Entered are m characters.						
									//alert(theMessages[counter]+" cannot have more than "+thesizes[counter]+" characters.");	
									
									alert("Maximum characters allowed are "+ thesizes[counter] +". Entered are "+ theForm.elements[i].value.length +" characters.");	
									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;
}



//	************************************	End theValidator *****************************************************


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

		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(str)
{
//	return rtrim(ltrim(str));
	return( (""+str).replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,'$1') );
}

function validateEmail(email)
{
	// This function is used to validate a given e-mail 
	// address for the proper syntax
	
	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;
	}
	//alphabets="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
		firstchar=email.substring(0,1);
		if(firstchar=="_")
		{
			return false;
		}
	return true
}

function validateURL(myobject)
{
	var re;
	var checkend=/\w\.[a-zA-Z]{2,3}/;
//	url=myobject.value;	
	url=myobject;
	
	if(url.search(checkend) == -1)
	{
//		alert("Please enter valid url. \n http://www.domain.com");
		return false;
	}
	return true;
}


function validateURL1(myobject)
{
	var re;
	var checkend=/\w\.[a-zA-Z]{2,3}$/;
	url=myobject.value;
	
	if(url.search(checkend) == -1)
	{
		alert("Please enter valid url. \n http://www.domain.com");
		return false;
	}
	return true;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function confirmation(theform,startElement,endElement,confirmaction)
{
	var flag=0;
	for(i=startElement;i<theform.length-endElement;i=i+1)		  //confirmation message for delete
	{
		if(theform.elements[i].checked==true)
		{
			 flag=1;
			 if (confirm("Are you sure you want "+confirmaction+" this record?"))
				return true;
			else
				return false;
		}
	}
	if(flag==0)
	{
		alert("Please select the checkbox before pressing the "+confirmaction+" button.");
		return false;
	}
}


function checkQuantity(theform)			//shopingcart.php
{
	var flag=0;
	for(i=0;i<theform.length;i=i+2)		  //confirmation message for delete
	{
		if(theform.elements[i].checked==true)
		{
			 flag=1;
			 if (confirm("Are you sure you want delete this record?"))
				return true;
			else
				return false;
		}
	}
	if(flag==0)
	{
		for(i=1;i<theform.length;i=i+2)  //numeric value for quantity if user wants to update quantity
		{
			if(isNaN(theform.elements[i].value))
			{
				alert("Quantity should be numeric.");
				theform.elements[i].focus();
				return false;
			}
			if(theform.elements[i].value < 0)
			{
				alert("Quantity should be greater than 0.");
				theform.elements[i].focus();
				return false;
			}
		}
		return true;
	}
}
 
 
  

function validate (field, maxlen, str)
{	
	if (field.value.length > maxlen)
	{
//		alert ("Field length exceeded.\nAllowed: "+maxlen+" characters,\nEntered: "+field.value.length+" characters.");
		alert(str+" cannot have more than "+maxlen+" characters.");	
		field.focus();
		return  false;
	}
	return true;
}

function validate_min_len (field, minlen, str)
{	
	if (field.value.length < minlen)
	{

		alert(str+" cannot be less than "+minlen+" characters.");	
		field.focus();
		return  false;
	}
	return true;
}

function fileextension(object,str)
{
	var s=object.value;
	if (s!="")
	{
		array=s.split("\\");
		len=array.length;
		filename=array[len-1];
		array1=filename.split(".");
		if(array1[1]!="jpg" && array1[1]!="jpeg" && array1[1]!="gif")
		{
			alert(str);
			object.focus();
			return false;
		}
	}
	
	return true;
}
function emailcheck(object,str)
{
var email=object.value;
//var matcharray=email.match(^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)¦(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}¦[0-9]{1,3})(\]?)$) 
var matcharray=email.match(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) 
	if(matcharray==null){
	alert(str)
	 	object.focus();
		object.select();
	return false;
	}
	firstchar=email.substring(0,1);
	if(firstchar=="_")
	{
		alert(str)
		object.focus();
		object.select();
		return false;
	}
	else return true
}

function yearcheck(number)
{ 
	if (number < 1000)
	{
		 number = number + 1900;
	}
 
 return number; 
}

function changedate(theform,i)
{	
	if (i==0)
	{
	theformdd=eval(theform.dd1);
	theformmm=eval(theform.mm1);
	theformyy=eval(theform.yy1);
	}
	else
	{
	theformdd=eval(theform.dd2);
	theformmm=eval(theform.mm2);
	theformyy=eval(theform.yy2);
	}

	day1=theformdd.options[theformdd.selectedIndex].value;
//	alert(theform.elements[i].options[theform.elements[i].selectedIndex].value);
	month1=theformmm.options[theformmm.selectedIndex].value;
	month1=month1-1;
	year1=theformyy.options[theformyy.selectedIndex].value;
	var test = new Date(year1,month1,day1);

	aday=test.getDate();
	if ( (parseInt(yearcheck(test.getYear())) == parseInt(year1)) && (parseInt(month1) == parseInt(test.getMonth())) && (parseInt(day1) == parseInt(test.getDate())) )
	{
		newdate=new Date(year1,month1,aday);
		dayNew=eval("theformdd.options[theformdd.selectedIndex]");
		dayNew.value=newdate.getDate();
		optionNumber=newdate.getDate();
		aku=eval("theformdd.options[optionNumber-1]");
		aku.selected=true;
		monthNew=eval("theformmm.options[theformmm.selectedIndex]");
		if (newdate.getMonth()==0 && newdate.getDate()==1 && newdate.getFullYear()>year1 )
			{
			monthNew.value=1;
			opmonth=1;
			}
		else
			{
			monthNew.value=newdate.getMonth()+1;
			opmonth=newdate.getMonth()+1;
			}
		amu=eval("theformmm.options[opmonth-1]");
		amu.selected=true;
		
		yearNew=eval("theformyy.options[theformyy.selectedIndex]");
		yearNew.value=newdate.getFullYear();
		opyear=newdate.getFullYear();
		abc=eval("theformyy");
		for( var u=0;u<abc.options.length;u++)
		{
			if(yearNew.value==abc.options[u].text)
			{
				ayu=eval("theformyy.options[u]");
				ayu.selected=true;
			}	
		}
	}
	else
	{
		alert("Please enter valid date.");
		theformdd.focus();
		return false;
	}    
		return true;
}

/*
* This function will not return until (at least)
* the specified number of milliseconds have passed.
* It does a busy-wait loop.
*/
function pause(numberMillis)
{
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true)
	{
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

/*  To ask for confirmation before deleting a FAQ */


function textCounter(field,maxlimit) 
{
	if (field.value.length > maxlimit) 
		field.value = field.value.substring(0, maxlimit);
}

function del(str)
{
	if(!confirm("Are you sure you want to delete this "+str+"?"))
		return false;

		return true;
}

function add_group(src,dst)
{	
	var selectone=src;
	var selecttwo=dst;

	var i=0;
	while(i<selectone.length)
	{
		
	if(selectone.options[i].selected==true)
	{
	
		var selecttwolength=selecttwo.length;
		selecttwo.options[selecttwolength]=new Option(selectone.options[i].text);
		selecttwo.options[selecttwolength].value=selectone.options[i].value;
		selectone.options[i]=null;
		i=i-1;
	}
	i=i+1;
	}
}

function remove_group(src,dst)
{
	var selectone=src;
	var selecttwo=dst;

	k=(selecttwo.length-1);
	var i=k;		
	while(i>=0)
	{
	
	if(selecttwo.options[i].selected==true)
	{
	var selectonelength=selectone.length;
	var selectoneOption=new Option(selecttwo.options[i].text);
	selectone.options[selectonelength]=selectoneOption;
	selecttwo.options[i]=null;
	k=k-1;
	}
	i=i-1;
	
	}
	
}
 /*'--- ---------------------------------------------------------
'Name   : CheckFromToDate
'Developer  : Ekansh
'Create Date : 20/06/2003  (dd/mm/yyyy)  
'Purpose  : This will check the valid date and from date 
'     should be less than equal to to date 
'Input Parameter       
 ' theform : Name of the form
  dd  : Name of the fromday form element
  mm  : Name of the frommonth form element
  yy  : Name of the fromyear form element
  dd1  : Name of the today form element
  mm1  : Name of the tomonth form element
  yy1  : Name of the toyear form element
 
'ModifiedDate ModifiedBy  Comments
'-------------------------------------------------------------
*/
 function CheckFromToDate(theform,fromday,frommonth,fromyear,today,tomonth,toyear)
 {
 
 if(!CheckDate1(theform,fromday,frommonth,fromyear)) return false; if(!CheckDate1(theform,today,tomonth,toyear))  return false;  day1=parseInt(eval("theform."+fromday+".options[theform."+fromday+".selectedIndex].value"));
 month1=eval("theform."+frommonth+".options[theform."+frommonth+".selectedIndex].value");
 month1=parseInt(month1-1);
 year1=parseInt(eval("theform."+fromyear+".options[theform."+fromyear+".selectedIndex].value")); 
 day2=parseInt(eval("theform."+today+".options[theform."+today+".selectedIndex].value"));
 month2=eval("theform."+tomonth+".options[theform."+tomonth+".selectedIndex].value");
 month2=parseInt(month2-1);
 year2=parseInt(eval("theform."+toyear+".options[theform."+toyear+".selectedIndex].value"));
 var fromdate = new Date(year1,month1,day1); 
 var todate=new Date(year2,month2,day2); 
 if(fromdate >todate)
 {  
  alert("Start date cannot be greater than end date."); 
  return false;
 }
 return true;
}

function CheckDate1(theform,dd,mm,yy)
{ 
 day1=parseInt(eval("theform."+dd+".options[theform."+dd+".selectedIndex].value"));
 month1=eval("theform."+mm+".options[theform."+mm+".selectedIndex].value");
 month1=parseInt(month1-1);
 year1=parseInt(eval("theform."+yy+".options[theform."+yy+".selectedIndex].value"));
 var test = new Date(year1,month1,day1);
 if (!((yearcheck(test.getYear()) == year1) && (month1 == test.getMonth()) && (day1 == test.getDate())) )
  {
   alert("Please enter valid date.");
   return false;
  }
 return true; 
 }
 /*'--- ---------------------------------------------------------
'Name   : IsValidTime
'Developer  : Mini
'Create Date : 11/10/2004  (dd/mm/yyyy)  
'Purpose  : Checks if input for time is !empty and in HH:MM:SS  format.
---------------------------------------------------------------------------*/
function IsValidTime(timeStr) 
{

if(timeStr=="")
{
		alert("Please enter time.")
		return false;
}
var time=timeStr.split(":");
if(time.length!=3)
{
	alert("Invalid time.");
	return false;
}
hour=time[0];
minute=time[1];
second=time[2];
if (hour < 0  || hour > 23 || hour.length!=2) 
{
	alert("Invalid time.");
	return false;
}
if (minute<0 || minute > 59 || minute.length!=2) 
{
	alert ("Invalid time.");
	return false;
}
if (second<0 || second > 59 || second.length!=2) 
{
	alert ("Invalid time.");
	return false;
}
return true;
}

function checkForm(theform,arrFields,arrMessage,arrType)
{

var arrFields=arrFields;
  var arrMessage =arrMessage;
	var arrType =arrType;
 for(var j=0;j < arrFields.length;j++)
 {
  var theEle = arrFields[j];
  var theMesg=arrMessage[j];
  var theType=arrType[j];
  for(var i=0; i< theform.elements.length;i++)
  {
   if(theform.elements[i].name == theEle)
   {
    
    switch(theType)
    {
     case 'T':
       // text Validations
       var theVal = trim(theform.elements[i].value);
       if(theVal.length <=0)
       {
        alert(''+theMesg+'.');
        theform.elements[i].focus();
        return false;
       }
       var pattern=/[A-Za-z]*/;
       if(!pattern.test(theVal))
       {
        alert('Only alphabets are allowed for '+theMesg+'.');
        theform.elements[i].select();
        return false;
       }
       break;
     case 'E':
       // text Validations
       var theVal = trim(theform.elements[i].value);
       if(theVal.length <=0)
       {
        alert(''+theMesg+'.');
        
        return false;
       }
       var pattern=/[A-Za-z]*/;
       if(!pattern.test(theVal))
       {
        alert('Only alphabets are allowed for '+theMesg+'.');
        theform.elements[i].select();
        return false;
       }
       break;
     case 'A':
       // alphanumeric validations
       var theVal = trim(theform.elements[i].value);
       if(theVal.length <=0)
       {
        alert('Please enter a value for '+theMesg+'.');
        theform.elements[i].focus();
        return false;
       }
       var pattern=/\w*/;
       if(!pattern.test(theVal))
       {
        alert('Only alphabets and numbers are allowed for '+theMesg+'.');
        theform.elements[i].select();
        return false;
       }
       break;
       
     case 'N':
       // numeric validations
       var theVal = trim(theform.elements[i].value);
       if(theVal.length <=0)
       {
        alert('Please enter a value for '+theMesg+'.');
        theform.elements[i].focus();
        return false;
       }
       if(isNaN(theVal))
       {
        alert('Please enter a numeric value for '+theMesg+'.');
        theform.elements[i].select();
        return false;
       }
       if(parseInt(theVal) <=0)
       {
        alert('Please enter a positive value greater than zero for '+theMesg+'.');
        theform.elements[i].select();
        return false;
       }
        
       break;
     case 'S': 
       // select box
       if(theform.elements[i].options[0].value=='0')
       {
        if(theform.elements[i].options[theform.elements[i].selectedIndex].value=='0' || theform.elements[i].options[theform.elements[i].selectedIndex].value=='')
        {
         alert('Please select the options for '+ theMesg + '.');
         theform.elements[i].focus();
         return false;
        }
       }
       break;
    
	case 'F':
	//filetype
	val=theform.elements[i].value;
	if(val.length <=0)
	{
		alert(''+ theMesg + '.');

	    theform.elements[i].focus();
		 return false;

	} //end of if
	break;
   }
   }
  }
 }
 return true;
}

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var dat1=new Date();
var maxYear=dat1.getYear();

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
}

function Validatedate(dt){
	
	if (isDate(dt)==false){
		dt.focus()
		return false
	}
    return true
 }

function checkValidCCNumber(CCType,CCNumber)
{
	cardLen=CCNumber.length;
	firstdig=CCNumber.charAt(0);
	seconddig=CCNumber.charAt(1);
	switch (CCType)
	{
		case "Visa":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "American Express":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "Master Card":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	if(result==false)
	{
		alert("Please enter valid credit card number for "+CCType+".");
		return false;
	}
	else
		return true;
	
}


function isValidCreditCardNumber(formField,ccType,fieldLabel,required)
{
	var result = true;
 	var ccNum = formField.value;

	if (result && (formField.value.length>0))
 	{ 
 		if (result)
 		{  			
 			if (!LuhnCheck(ccNum) || !validateCCNum(ccType,ccNum))
 			{
 				alert('Please enter a valid card number for the "' + fieldLabel +'" field.');
				formField.focus();
				result = false;
			}	
		} 
	} 	
	return result;
}

function doConfirm(str)
{
	if(confirm('Are you sure you want to '+str))
		return true;
	else
		return false;
}

function LuhnCheck(str) 
{
  var result = true;

  var sum = 0; 
  var mul = 1; 
  var strLen = str.length;
  
  for (i = 0; i < strLen; i++) 
  {
    var digit = str.substring(strLen-i-1,strLen-i);
    var tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
  if ((sum % 10) != 0)
    result = false;
    
  return result;
}

function validateCCNum(cardType,cardNum)
{
	var result = false;
	var cardLen = cardNum.length;
	var firstdig = cardNum.substring(0,1);
	var seconddig = cardNum.substring(1,2);
	var first4digs = cardNum.substring(0,4);
	
//enRouteCard JCBCard
	switch (cardType)
	{
		case "VisaCard":
			result = ((cardLen == 16) || (cardLen == 13)) && (firstdig == "4");
			break;
		case "AmExCard":
			var validNums = "47";
			result = (cardLen == 15) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
		case "MasterCard":
			var validNums = "12345";
			result = (cardLen == 16) && (firstdig == "5") && (validNums.indexOf(seconddig)>=0);
			break;
		case "DiscoverCard":
			result = (cardLen == 16) && (first4digs == "6011");
			break;
		case "X":
			if (cardNum==9451123100000004)
				result = true;
			break;		
		case "DinersClubCard":
			var validNums = "068";
			result = (cardLen == 14) && (firstdig == "3") && (validNums.indexOf(seconddig)>=0);
			break;
	}
	return result;
}

function isValidccCardCode(formField,fieldLabel)
{
	var result = true;
 	var ccCardCode = formField.value;

  	if (result)
 	{ 
		if (formField.value.length<3)
		{
 			alert('Please enter 3 digit number for the "' + fieldLabel +'" field.');
			formField.focus();
			result = false;
		}
	} 
	return result;
}



function validCCForm(theform,ccTypeField,ccNumField)
{	
	var result = isValidCreditCardNumber(ccNumField,ccTypeField.value,"Credit Card Number") && checkCardExpiry() && isValidccCardCode(theform.vchCVCCode,"Card Verification Code");
	return result;
}

/*
	function: fnCalculateTotalPrice()
	purpose: calculate amount, coupon price amount and net amount of the plan purchased, on selecting monthly/annual duration.
	files using: register-next.php,register-next1.php

*/
function fnCalculateTotalPrice(theform,decAmountStr,decValueStr,enmType)
{
	var decAmount=parseFloat(decAmountStr);
	var decValue=parseFloat(decValueStr);
	var form_length=theform.elements.length;
	for(var i=15;i<form_length;i++)
	{
		if(theform.elements[i].checked)
		{
			var interval=theform.elements[i].value;
			break;
		}
	}
	if(interval=="A")
		decAmount=decAmount*12;
	if(enmType=="")
	{
		decAmount=decAmount.toFixed(2);
		theform.couponPrice.value=0;
		theform.decAmount.value=decAmount;
		theform.decNetAmount.value=decAmount;
	}
	else
	{
		if(enmType=="F") //FLAT
		{
			decAmount=decAmount.toFixed(2);
			decValue=decValue.toFixed(2);
			var decNetAmount=decAmount-decValue;
			decNetAmount=decNetAmount.toFixed(2);
			theform.decAmount.value=decAmount;
			theform.couponPrice.value=decValue;
			theform.decNetAmount.value=decNetAmount;
		}
		else	//PERCENTAGE 
		{
			decValue=(decAmount*decValue)/100;
			decAmount=decAmount.toFixed(2);
			decValue=decValue.toFixed(2);
			var decNetAmount=decAmount-decValue;
			decNetAmount=decNetAmount.toFixed(2);
			theform.decAmount.value=decAmount;
			theform.couponPrice.value=decValue;
			theform.decNetAmount.value=decNetAmount;

		}
	}
	return true;	
}
