
message = new Array()
message[0] = "Please enter required information";
message[1] = "Please enter an email address";
message[2] = "You have invalid characters in the information you've entered";
message[3] = "Email address should contain exactly one @ character";
message[4] = "Please enter email address in the format: name@domain.com";
message[5] = "Entered passwords did not match";
message[6] = "Please make your selection";
message[7] = "Please enter information as a whole number";
message[8] = "Please indicate your selection by checking one of the radio buttons";
message[9] = "Please enter a number with the exact number of digits required";
message[10] = "Please indicate your selection by checking one of the checkboxes";
message[11] = "Please enter a number (with decimal places) in the correct format (e.g. 354.99)";
message[12] = "Please enter only two digits for cents";
message[13] = "Please enter date in the format mm/dd/yyyy";
message[14] = "Please enter a date in the present or near term future";
message[15] = "You have entered a date that does not exist - invalid month";
message[16] = "You have entered a date that does not exist - number of days";
message[17] = "Please enter a string with the exact number of characters required";
message[18] = "Please enter valid hexadecimal numbers (0-F)";
message[19] = "Please make sure the range is two numbers separated by - (e.g. 25-54.99)";
message[20] = "message for testing";
message[21] = "Please remove leading spaces from your entry";
message[22] = "Please enter value greater than 0";
message[23] = "The text you've entered exceeds the limit";
message[24] = "Please remove any non letter characters";
message[25] = "Please enter price as a number";

var custMsgs	= new Array();
custMsgs[0]		= "{0} field is required.";
custMsgs[7]		= "{0} field must be a whole number.";
custMsgs[9]		= "{0} field requires the exact number of digits.";
custMsgs[2] 	= "{0} field contains invalid characters.";
custMsgs[4] 	= "{0} has to be in the format: name@domain.com.";
custMsgs[6] 	= "{0} requires a selection.";
custMsgs[11]	= "Please enter a number (with decimal places) in the correct format (e.g. 354.99)";
custMsgs[12] 	= "Please enter only two digits for cents for {0}";
custMsgs[13] 	= "{0} must be in the format mm/dd/yyyy.";
custMsgs[14] 	= "(0} must be a date in the present or near term future";
custMsgs[17] 	= "{0} requires a string with the exact number of characters required.";
custMsgs[21] 	= "Please remove leading spaces from your entry in the {0} field.";
custMsgs[22] 	= "{0} requires a value greater than 0";
custMsgs[23] 	= "{0} value exceeds the limit allowed";
custMsgs[24] 	= "{0} can not have any non letter characters.";


var FormName;
function getMessage ( result, fieldData )
{
	var i	= result;
	var msg	= msg	= message[result];
	
	if ( fieldData.length >= 3 )
	{
		alert ( i + " " +custMsgs[i])
		if ( i < custMsgs.length && custMsgs[i] )
		{

			msg	= custMsgs[i].replace ( '{0}', fieldData[2]);
		}
	}
	return msg;
}
function showMessage(msg, j){
	  window.alert(msg);
	  document.forms[FormName].elements[j].focus();
}
//end message handling bloc

//below are checkFieldType functions
function getFieldValue(ind,val,fType)
 {
  //window.alert(FormName)
  if(ind != "none")
   {
    fValue = (FormName)? document.forms[FormName].elements[ind].value : document.forms[1].elements[ind].value
      if(fType == "SL")
       {
         qchoice = document.forms[FormName].elements[ind].selectedIndex;
	     fValue = document.forms[FormName].elements[ind].options[qchoice].value
       }
   }
  if(val)
   {
    fValue = (FormName)? document.forms[FormName].elements[val].value : document.forms[1].elements[val].value
      if(fType == "SL")
       {
        qchoice = document.forms[FormName].elements[val].selectedIndex;
	    fValue = document.forms[FormName].elements[val].options[qchoice].value
       }
   }


  if (fValue)
  	return trim(fValue);
  else
  	return fValue;
 }//end getFieldValue
function checkSpace(val)//checks for leading space
{
 if(val.charAt(0) == " ")
     {
	  return false;
	 }
	 else return true;
}//end checkSpace()

function checkTextField(i,val)
{
fieldValue = (i!="none")? getFieldValue(i):val
if(fieldValue=="")
     {
	   return 0;//0 is a message number from message array
	 }
if(!checkSpace(fieldValue)) return 21;
var result = checkChar(fieldValue)
 if(result > 0) return 24;

	 else return "OK";
}//end checkTextField()


function checkTextField(i,val,from,to)
{
fieldValue = (i!="none")? getFieldValue(i):val
if(fieldValue=="")
     {
	   return 0;//0 is a message number from message array
	 }
if(fieldValue.length<from ||fieldValue.length>to)
{
	return 9;
}
if(!checkSpace(fieldValue)) return 21;
var result = checkChar(fieldValue)
 if(result > 0) return 24;

	 else return "OK";
}//end checkTextField()


function checkTextAria(val)
 {
   if(!val)
    {
	 return 0
	}
  if(!checkSpace(val)) return 21;
//two lines below commented to prevent spesial characters detection for text boxes
 //var result = checkCharTA(val)
 //if(result > 0) return 24;
   if(val.length > 4000)
    {
	 return 23
	}
 else return "OK"
 }//end check text aria

function checkCharTA(fieldValue)
{
 var isInvalid = 0;
 var invalidChars = new Array("~", "+", "=", "@", "!", "?", "%", "$", "#", "&", "*", "(", ")", "<", ">", "\\", "[", "]", "{", "}", "|");
 for(i=0; i<fieldValue.length; i++)
   {
     for(j=0; j<invalidChars.length; j++)
	    {
		 if(fieldValue.charAt(i)==invalidChars[j])
		 isInvalid ++
		}//end for j
   }//end for i

return isInvalid;
}//end checkChar


function checkChar(fieldValue)
{
 var isInvalid = 0;
 var invalidChars = new Array("~", "+", "=", ":", ",", ";", "@", "!", "?", "%", "$", "#", "&", "*", "(", ")", "<", ">", "\\", "[", "]", "{", "}", "|");
 for(i=0; i<fieldValue.length; i++)
   {
     for(j=0; j<invalidChars.length; j++)
	    {
		 if(fieldValue.charAt(i)==invalidChars[j])
		 isInvalid ++
		}//end for j
   }//end for i

return isInvalid;
}//end checkChar
function checkUserName(i,val)
{
fieldValue = (i!="none")? getFieldValue(i):val
if(!fieldValue)
     {
	   return 0;//0 is a message number from message array
	 }
if(!checkSpace(fieldValue)) return 21;

if(fieldValue)
  {
 //  var invalidChars = new Array(" ", "/", ":", ",", ";",".","@","!","?","%","$","#","&","*","(",")","<",">","\","[","]","{","}","|");
   var invalidChars = new Array(" ", ":", ",", ";",".","@","!","?","%","$","#","&","*","(",")","<",">","\\","[","]","{","}","|","'","\"");

   var isinvalid = "0"
   //window.alert("here it is " + invalidChars[4])
   var addresses = new Array();
   var k = 0;

        oneline = fieldValue;
		for(i=0; i<oneline.length; i++)
		  {
		   addresses[k] = oneline.charAt(i);
		   k++;
		  }

		//window.alert("value split by char: " + addresses)
		for (d=0; d<addresses.length; d++)
		 {  // check addresses 1 by 1
			for (j=0; j<invalidChars.length; j++)
			  {	// does it contain any invalid characters?

				if (addresses[d]==invalidChars[j])
				 {
				   isinvalid ++
				 }//end if

			   }//end for j

          }	//end for d
	 if(isinvalid > 0)
	   {
	    return 2;
	    }
	  else return "OK"
	 }

}//end checkUsername()

function checkHexField(i) {
	if (document.forms[FormName].elements[i].value.length != 6)
		return 17;
	for (var j=0; j<6; j++) {
		if ((document.forms[FormName].elements[i].value.charAt(j) < '0' || document.forms[FormName].elements[i].value.charAt(j) > '9')
		&& (document.forms[FormName].elements[i].value.charAt(j) < 'A' || document.forms[FormName].elements[i].value.charAt(j) > 'F')
		&& (document.forms[FormName].elements[i].value.charAt(j) < 'a' || document.forms[FormName].elements[i].value.charAt(j) > 'f'))
			return 18;
	}
	return "OK";
}

// Is this a number?
//	depending on 'type', 'i' can either be the index of the string that'll be checked or
//	the string itself

function isIntNum(fieldValue)
 {
   //window.alert(fieldValue)
   if(!fieldValue || fieldValue == "")
   {
    return 0;
   }
   if(!checkSpace(fieldValue)) return 21;
   var i=0;
   for (i=0; i<fieldValue.length; i++) {
		//window.alert(fieldValue.charAt(i))
	  if ((fieldValue.charAt(i) < "0") || (fieldValue.charAt(i) > "9")) {
			return 7//message # 7
		}
	}
	return "OK";
}

function isPrice(fieldValue)
{
  if(!fieldValue) return 0//checks if entry is blank
  if(!checkSpace(fieldValue)) return 21;//checks if there is leading space

  var price = fieldValue.split(".")
 // if(!price[1]) price[1]="0"
  for(i=0; i<price[0].length; i++)
     {
       if (price[0].charAt(i) < "0" || price[0].charAt(i) > "9") return 25//message # 7
	 }//end for
if(price[1])
 {
	for(j=0; j<price[1].length; j++)
     {
       if (price[1].charAt(j) < "0" || price[1].charAt(j) > "9") return 25//message # 7
	 }//end for
  }
     return "OK";
}//end of isPrice()

function isNum(i, numOfDigits, type, val) {
 var passedVal="";
 if(i!="none")
  {
	if (type == "index" || type == null)
		passedVal = document.forms[FormName].elements[i].value;
	else if (type == "number"){
		passedVal = i;
		}
    }
  if(i=="none") passedVal=val;

    if (passedVal == "") {
		return 0;//0 is a message number from message array
	}
	if (numOfDigits == 'N') {
		numOfDigits = passedVal.length;
	}
	//else {
		//window.alert(numOfDigits)
		//window.alert(passedVal.length)
		if (numOfDigits != passedVal.length) return 9;
	  //  }
	for (j=0; j<numOfDigits; j++) {
		/*
	   if (parseFloat(passedVal,10) == "0") {
		   return 22 //message # 22
	   }	*/
		if (passedVal.charAt(j) < "0") {
			return 7//message # 7
		}

		if (passedVal.charAt(j) > "9") {
			return 7//message # 7
		}
	}
	return "OK";
}//end isNum()



//	depending on 'type', 'i' can either be the index of the string that'll be checked or
//	the string itself
function isNumWithDPs(i, type) {		//  is it a Num (With exactly 2 decimal places)
	if (type == "index" || type == null)
		var passedVal = document.forms[FormName].elements[i].value;
	else if (type == "number")
		var passedVal = i;

	if (passedVal == "") {
		return 0;
	}
	else {
		var dotPos = passedVal.indexOf(".");
		if (dotPos == -1)
			return isNum(passedVal, 'N', "number");
		else {
			if (passedVal.indexOf(".", dotPos+1) != -1) return 11;   // multiple dots
			ms = passedVal.substring(0, dotPos);	//  More Significant
			ls = passedVal.substring(dotPos+1, passedVal.length);  //  Less Significant

			if (ms.length == 0 || ls.length == 0) return 11;
			if (ls.length > 2)  return 12;
			for (j=0; j<ms.length; j++) {
				if (ms.charAt(j) < "0") {
					return 11
				}
				if (ms.charAt(j) > "9") {
					return 11
				}
			}
			for (j=0; j<ls.length; j++) {
				if (ls.charAt(j) < "0") {
					return 11
				}
				if (ls.charAt(j) > "9") {
					return 11
				}
			}
		}  // end else
	} // end else
	return "OK";
}

function isNDorRangeInND(i) {
	var passedVal = document.forms[1].elements[i].value;

	//	"-" not present, should just be a num (with DPs)
	if (passedVal.indexOf("-") == -1) {
		return isNumWithDPs(i, "index");
	}

	limits = passedVal.split("-");
	if (limits.length > 2)
		return 19;	//	more than 1 "-" is entered

	//	"-" is present only once, now check if two numbers on each side
	var from = isNumWithDPs(limits[0], "number");
	if (from == 0) return 19;
	if (from != "OK") return from;
	var to	 = isNumWithDPs(limits[1], "number");
	if (to == 0) return 19;
	if (to != "OK") return to;

	return "OK";
}

function checkDate(i) {		// The date format checked is mm/dd/yyyy
	var passedVal = document.forms[FormName].elements[i].value
	//window.alert(passedVal)
	if (passedVal == "") {
		return 13;
	}
	if (passedVal.length > 10) {
		return 13;
	}
	else {
		var month = passedVal.substring(0, 2);
		var day = passedVal.substring(3, 5);
		var year = passedVal.substring(6, 10);
		if (passedVal.substring(2, 3) != "/" && passedVal.substring(5, 6) != "/")
			return 13;
		if (month < 1 || month > 12) return 15;
		// no dates in the past by more than a month
		if (day < 0 || year < 2000) return 13;
		if (year == 2000 && month < 7) return 14;
		// number of days must be reasonable
		if (month == 2 && day > 29) return 16;
		if (month == 4 || month == 6 || month == 9 || month == 11)
		{
			if (day > 30) return 16;
		}
		else if (day > 31) return 16;
		if (year > 2000) return 14;
	}
	return "OK";
}

function compareTwoNumbers(ind1, comparator, ind2)
{
	num1 = parseFloat(document.forms[FormName].elements[ind1].value)
	num2 = parseFloat(document.forms[FormName].elements[ind2].value)

	if (comparator == '>')
		return num1 > num2;
	else if (comparator == '=')
		return num1 == num2;
	else if (comparator == '<')
		return num1 < num2;
	else
		return false;
}

function checkPassword(i){
   if(document.forms[FormName].elements[i].value == "")
     {
	   return 0;//0 is a message number from message array
	 }
   if (document.forms[FormName].elements[i].value != document.forms[FormName].elements[i-1].value)
	 {
	   return 5;//message 5 from message array
	 }
	  else return "OK";
}//end checkPassword()

function checkPassword(i,val, prevVal){
	fieldValue = (i!="none")? getFieldValue(i):val
	if(!fieldValue)
	{
		return 0;//0 is a message number from message array
	}

   	if (val != prevVal)
	{
		return 5;//message 5 from message array
	}
	  else return "OK";
}//end checkPassword()

function checkSelection(i,val){
  if(i!="none")
   {
	qchoice = document.forms[FormName].elements[i].selectedIndex;
	if (document.forms[FormName].elements[i].options[qchoice].value == "00")
    {
	   return 6;//message 6 from message array
	 }
	}//end if i!=none
  if(i=="none")
   {
     if(val == "-1")
	 return 6;
   }
return "OK";
}//end checkSelection(i)


	function checkEmail(i,val) {
		invalidChars = " /:,;"
		fieldvalue = (i !="none")? document.forms[FormName].elements[i].value : val
		oneline = fieldvalue;

		if (oneline == "")  // cannot be empty
			return 1;
		addresses = oneline.split(",");

		for (d=0; d<addresses.length; d++) {  // check addresses 1 by 1
			for (j=0; j<invalidChars.length; j++) {	// does it contain any invalid characters?
				badChar = invalidChars.charAt(j);
				if (addresses[d].indexOf(badChar,0) > -1) {
					return 2
				}
			}//end for
			atPos = addresses[d].indexOf("@",1)	// there must be one "@" symbol
			if (atPos == -1) {
				return 3
			}
			if (addresses[d].indexOf("@",atPos+1) != -1) {	// and only one "@" symbol
				return 3
			}
			periodPos = addresses[d].indexOf(".",atPos)
			if (periodPos == -1) {					// and at least one "." after the "@"
			    return 4
			}
	        if (periodPos+3 > addresses[d].length)	{		// must be at least 2 characters after the "."
				return 4
			}
		}
		return "OK"
	}//end Email validation

function checkSelectionList(i){
ind = document.forms[FormName].elements[i].selectedIndex;
	if (document.forms[FormName].elements[i].options[ind].value == "00")
	    {
      return false;
	 }
	  else return true;
	}//end checkSelectionList()
//end checkField functions

function checkRadioOrCheckbox(type, i, val){
    var count = 0;
	for(j=0; j<val; j++)
	{
//		window.alert("i="+i+", j="+j+", i+j="+(i+j));
	  var CheckedButton = (type=="RB")? document.forms[FormName].elements[i-j].checked : document.forms[FormName].elements[i+j].checked
	  if(CheckedButton == true)
    	 {
	    	count++;
		   //rbut = j+1;//use it to find out which radio button was checked
		 }
	 }//end for
	if(count == "0")
	{
		if (type == "RB") return 8   //message number 8
		else if (type == "CB") return 10;
		else window.alert("UNKNOWN INPUT TYPE!");
	}
	else return "OK"
}

function checkRadioWithTextfield(i) {
	if (true == document.forms[FormName].elements[i].checked) {
		if ("OK" == checkTextField(i+1))
			return "OK";
		else return 0;
	}
	else return "OK"
}

function checkRadioWithNumberfield(i) {
	if (true == document.forms[FormName].elements[i].checked) {
		var tmp = isNum(i+1, "N", "index");
		if (tmp == "OK")
			return "OK";
		else return tmp;
	}
	else return "OK"
}

function checkTextareaLimit(i, maxsize) {
	if (document.forms[FormName].elements[i].value.length > maxsize)
		return maxsize;
	else return "OK"
}

function checkShippingModule()//since shipping options are dynamic this function finds first how many options are available, and then if any is checked
 {
  var ind = 0;
  var optionchecked = 0
  for(i=0; i<document.forms[FormName].elements.length; i++)
    {
	  if(document.forms[FormName].elements[i].name =="shipping")
	    {
		  ind ++
		}//end if
	}//end for

 if(ind > 0)
   {
     for(j=0; j<ind; j++)
      {
	    if(document.forms[FormName].shipping[j].checked == true)
		  {
		   optionchecked ++;
		  }
	}//end for (j...

        if(optionchecked == 0)
      {
	    return "notchecked"
	  }
	 }//end if(ind > 0)

 }
String.prototype.trim = function() {
   return this.replace(/^\s+|\s+$/g,"");
}
function validateByname(FName,FormString, aggregate)
{
	FormName = FName;
	formdata = FormString.split("|");
	var result	= "";
	var i=0;
	var msg	= "";
	var firstWrong	= "";
	for(i=0; i<formdata.length; i++)
	{
		result 		=  "";
		fielddata = formdata[i].split(":")
		
		fval = getFieldValue('none', fielddata[0], fielddata[1])
		if ( fielddata.length > 3){
			//Required value = 0 i.e. not required{
			if ( fielddata[3] == "o"  || fielddata[3] == "O" ){
				if ( !fval || fval.trim().length == 0) continue;
			}
		}
		if(fielddata[1] == "TF"){
		   result = checkTextField('none',fval);
		}//end if - TFs

		else if(fielddata[1] == "PWD"){
		   result = checkTextField('none',fval,4,15);

		}//end if - TFs

		else if(fielddata[1] == "VPWD")
		{
		   prevPwdData = formdata[i-1].split(":")
		   prevPwdVal = getFieldValue('none', prevPwdData[0], prevPwdData[1])

		   
		   result = checkPassword('none', fval, prevPwdVal);
		}

		else if(fielddata[1] == "UN")
		{
		   
		   result = checkUserName('none',fval);
		}//end if - TF
		else if(fielddata[1] == "email")
		{
		  
		   result = checkEmail('none',fval);
		}//end email
		else if(fielddata[1] == "TA")
		{
		   
		   result = checkTextAria(fval);
		}//end if - TA
		else if(fielddata[1] == "PR")
		{
		   result = isPrice(fval);
		}//end if - Price
		else if(fielddata[1] == "Nint")
		{
		   //window.alert(fval)
		   result = isIntNum(fval);
		}//end if - Price
	  	else if(fielddata[1] == "SL")
		{
		   result = checkSelection('none',fval);
		}//end if - SL
		else  if(fielddata[1].indexOf("NV") != -1)
		{
			if (fielddata[1].length < 4 )
				dnum = fielddata[1].substring(fielddata[1].length-1)
			else
				dnum = fielddata[1].substring(2, fielddata[1].length)
			result = isNum("none", dnum, "index",fval);

		}
		else if(fielddata[1].indexOf("RB") != -1)
		{
		   var  dnum = fielddata[1].substring(2)
		   var	Ind = getInd(fielddata[0])
		   result = checkRadioOrCheckbox("RB", Ind, dnum);

	    }
		else if(fielddata[1].indexOf("CB") != -1)
		{
		   var  dnum = fielddata[1].substring(2)
		   var	Ind = getInd(fielddata[0])
		   result = checkRadioOrCheckbox("CB", Ind, dnum);

		}
		else if (fielddata[1].indexOf("DF") != -1)
		{
			Ind = getInd(fielddata[0])
			result = checkDate(Ind);
		}

		if(result != "OK")
		{
			if ( fielddata.length>=4 ) //check if it is optional
			{
				if ( fielddata[3] == 'O' || fielddata[3] == 'o')
				{
					if (fval == '' ) //ignore
						continue;
				}
			}
			if ( firstWrong == "" ) firstWrong	= fielddata[0];
			if ( aggregate )
			{
				msg	= msg + "\r\n" + getMessage(result, fielddata);
			}
			else
			{
		 		showMessage(getMessage(result, fielddata),fielddata[0]);
		 		return false;
		 	}
		}
	}// end for
	if ( msg != "" )
	{
		showMessage(msg,firstWrong);
		return false;
	}
	return true
 } //end validateByname()

 function getInd(fname)//finds index of the element by field name
 {
  //window.alert("Field Name is: " + fname)
  var Ind;
  //window.alert(document.forms[FormName].length)
  for(i=0; i<document.forms[FormName].length; i++)
    {
	  if(document.forms[FormName].elements[i].name == fname)
	    {
		  Ind = i;
		}
	}//end for
 //window.alert("Index for that field is :" + Ind)
 return Ind;
 }
 
 function trim(str)
{
    return str.replace(/^\s+/,'').replace(/\s+$/,'');
}
