//create global control array
// array will contain subarray with 1) control i
// and 2) control check.
controlArray=new Array();

function validateForm(){
	var i,checkObj,theMessage,tempMessage; 
	var errorMessage=new Array();
	theMessage="";
	for(i=0;i<controlArray.length;i++){
		checkObj=getObjectFromID(controlArray[i][0]);
		switch (controlArray[i][1]){

			case "required":
				if(!checkObj.value){
					tempMessage=(errorMessage.length +1)+ ". ";
					if(controlArray[i][2]!="")
						tempMessage+=controlArray[i][2]+" is required.";
					else
						tempMessage+=controlArray[i][3]					
					errorMessage[errorMessage.length]=tempMessage;
				}
			break;
			
			case "phone":			
				if(checkObj.value && !validatePhone(checkObj.value)) {
					tempMessage=(errorMessage.length +1)+ ". ";
					if(controlArray[i][2]!="")
						tempMessage+=controlArray[i][2]+" needs to be a valid phone number.";
					else
						tempMessage+=controlArray[i][3]					
					errorMessage[errorMessage.length]=tempMessage;
				}
			break;
			
			case "email":			
				if(checkObj.value && !validateEmail(checkObj.value)) {
					tempMessage=(errorMessage.length +1)+ ". ";
					if(controlArray[i][2]!="")
						tempMessage+=controlArray[i][2]+" needs to be a valid e-mail address.";
					else
						tempMessage+=controlArray[i][3]					
					errorMessage[errorMessage.length]=tempMessage;
				}
			break;

			case "webpage":			
				if(checkObj.value!="" && checkObj.value!="http://" && !validateWebpage(checkObj.value)) {
					tempMessage=(errorMessage.length +1)+ ". ";
					if(controlArray[i][2]!="")
						tempMessage+=controlArray[i][2]+" needs to be a valid web address (including http://).";
					else
						tempMessage+=controlArray[i][3]					
					errorMessage[errorMessage.length]=tempMessage;
				}
			break;

			case "integer":			
				if(!validateInteger(checkObj.value)) {
					tempMessage=(errorMessage.length +1)+ ". ";
					if(controlArray[i][2]!="")
						tempMessage+=controlArray[i][2]+" needs to be a valid integer (whole number).";
					else
						tempMessage+=controlArray[i][3]					
					errorMessage[errorMessage.length]=tempMessage;
				}
			break;

			case "real":			
				if(checkObj.value && !validateReal(checkObj.value)) {
					tempMessage=(errorMessage.length +1)+ ". ";
					if(controlArray[i][2]!="")
						tempMessage+=controlArray[i][2]+" needs to be a real number (example: 4.3).";
					else
						tempMessage+=controlArray[i][3]					
					errorMessage[errorMessage.length]=tempMessage;
				}
			break;
			
			case "ccnumber":
				if(!validateCreditCard(checkObj.value)){
					tempMessage=(errorMessage.length +1)+ ". ";
					if(controlArray[i][2]!="")
						tempMessage+=controlArray[i][2]+" needs to be a valid credit card number.";
					else
						tempMessage+=controlArray[i][3]					
					errorMessage[errorMessage.length]=tempMessage;					
				}				
			break;
		}
	}

	//check to see if any errors occured... if so display and return 
	if (errorMessage.length>0){
		theMessage="The Form could not be submitted:\n================================\n\n";					
		for(i=0;i<errorMessage.length;i++)
			theMessage+=errorMessage[i] + "\n\n";
		alert(theMessage);
		return false;
	}
	else
		return true;
}

// validate phone number
function validatePhone(thevalue){
	var pattern= /^(?:[\+]?(?:[\d]{1,3})?(?:\s*[\(\.-]?(\d{3})[\)\.-])?\s*(\d{3})[\.-](\d{4}))(?:(?:[ ]+(?:[xX]|(?:[eE][xX][tT][\.]?)))[ ]?[\d]{1,5})?$/;
	if (!(pattern.exec(thevalue)==null))
		return !(parseInt(thevalue)=="555")		
	return false;
}

//look for a valid email address
// this is a loose validation
function validateEmail(thevalue){
  var result = false
  var theStr = new String(thevalue)
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
	result = true;
  }
  return result;
}

//validate web page... make sure there is a http:// and at least one "."
function validateWebpage(thevalue){
  var theaddress=thevalue.substring(8,thevalue.length-1);
  if(thevalue.substring(0,7)=="http://" && theaddress.indexOf(".",0) !=-1 ) return true;
  else return false;
}

//validate integer
function validateInteger(thevalue){
		while(thevalue.charAt(0)=="0") thevalue=thevalue.substring(1,thevalue.length);
		if (thevalue=="") thevalue="0";
		var newnum=parseInt(thevalue).toString();
		if(!(thevalue.length==newnum.length && newnum != "NaN")) return false; else return true;
}

//validate realnumber
function validateReal(thevalue){
	while(thevalue.charAt(thevalue.length-1)=="0" && thevalue.indexOf(".")!=-1) thevalue=thevalue.substring(0,thevalue.length-1);
	if(thevalue.charAt(thevalue.length-1)==".") thevalue=thevalue.substring(0,thevalue.length-1);

	if (thevalue.charAt(0)==".") thevalue="0"+thevalue;
	if (isNaN(parseFloat(thevalue)) || thevalue.length!=((parseFloat(thevalue)).toString()).length) return false; else return true;
}

// checks and formats a field to dollars
function validateDollar(theitem){
	var thedollar=theitem.value;
	var i;
	var thenumber="";
	var newdollar;
	
	for(i=0;i<thedollar.length;i++){
		if (thedollar.charAt(i)!="$" && thedollar.charAt(i)!="+" && thedollar.charAt(i)!=",") thenumber=thenumber+thedollar.charAt(i);
	}
	//if the first number is a ".", add a 0
	if (thenumber.charAt(0)==".") thenumber="0"+thenumber;

	//get rid of trailing zeros and possibly "."
	while(thenumber.charAt(thenumber.length-1)=="0" && thenumber.indexOf(".")!=-1) thenumber=thenumber.substring(0,thenumber.length-1);
	if(thenumber.charAt(thenumber.length-1)==".") thenumber=thenumber.substring(0,thenumber.length-1);
	
	//check for number		
	if (isNaN(parseFloat(thenumber)) || thenumber.length!=((parseFloat(thenumber)).toString()).length) thenumber="0.00";
	
	// add the dollar sign... remember that if it is a negative number, the minus sign goes in front
	if(thenumber.charAt(0)=="-") {
			newdollar="-$";
			thenumber=thenumber.substring(1,thenumber.length);
		} else newdollar="$";

	var big_string = ""+(Math.round(100*(Math.abs(thenumber))))  //rounding the absolute value times 100
	var biglen = big_string.length                            //how the string gets handled depends on its length
	if (biglen == 0)                   //null
		{retval = "0.00"} 
	else if (biglen == 1)              //1 to 9 (.01 to .09 cents)
		{retval = "0.0"+big_string}
	else if (biglen == 2)              //10 to 99 (.10 to .99 cents)
		{retval = "0."+big_string}
	else  { 						  //all cases above 100 ($1.00)
			//The substring method returns all characters in the string
			// starting with and including the the first argument,
			// up to but not including the second argument.  
			var hundredths_digit = big_string.substring(biglen-1,biglen)  
			var tenths_digit = big_string.substring(biglen-2,biglen-1)    
			var integer_digits = big_string.substring(0,biglen-2)
			// commafy,  borrowed from Danny Goodman, "Javascript Bible"
			var re = /(-?\d+)(\d{3})/
			while (re.test(integer_digits))  {
				integer_digits = integer_digits.replace(re, "$1,$2")
			}
			retval = integer_digits + "." + tenths_digit + hundredths_digit
	}  
    newdollar = newdollar+retval

	theitem.value=newdollar;
}


function validateCreditCard(object_value)
    {
	var white_space = " -";
	var creditcard_string="";
	var check_char;


    if (object_value.length == 0)
        return false;
		
	// squish out the white space
	for (var i = 0; i < object_value.length; i++)
	{
		check_char = white_space.indexOf(object_value.charAt(i));
		if (check_char < 0)
			creditcard_string += object_value.substring(i, (i + 1));
	}	

	// if all white space return error
    if (creditcard_string.length == 0)
        return false;	 	

	// make sure number is a valid integer
	if (creditcard_string.charAt(0) == "+")
        return false;
	
	if (!validateInteger(creditcard_string))
		return false;

    // now check mod10

	var doubledigit = creditcard_string.length % 2 == 1 ? false : true;
	var checkdigit = 0;
	var tempdigit;

	for (var i = 0; i < creditcard_string.length; i++)
	{
		tempdigit = eval(creditcard_string.charAt(i))

		if (doubledigit)
		{
			tempdigit *= 2;
			checkdigit += (tempdigit % 10);

			if ((tempdigit / 10) >= 1.0)
			{
				checkdigit++;
			}

			doubledigit = false;
		}
		else
		{
			checkdigit += tempdigit;
			doubledigit = true;
		}
	}	
	return (checkdigit % 10) == 0 ? true : false;

    }
