//initialization
var message = "";
var message1 = "ALERT: Some of the information you have entered on this form is<br>not valid or incomplete. Please check the following information and<br>re-submit:\n\n";
var message2 = "\nIf you need further assistance, please call Customer<br> Service at 1-800-720-1765.\n";


var focusObject = null;

var ccErrorNo = 0;
var ccErrors = new Array ();

ccErrors [0] = "Unknown credit card type\n";
ccErrors [1] = "No credit card number provided\n";
ccErrors [2] = "Credit card number is in invalid format\n";
ccErrors [3] = "Credit card number is invalid\n";
ccErrors [4] = "Credit card number has an inappropriate number of digits\n";

function checkChars(param)
{
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var combined = lwr + upr;
 	
	for (i=0; i<param.length; i++) {
		if (combined.indexOf(param.charAt(i),0) == -1) return 0;
	}
	return true;
}

function checkNum(param)
{
	var num = '0123456789';
	
 	
	for (i=0; i<param.length; i++) {
		if (num.indexOf(param.charAt(i),0) == -1) return 0;
	}
	return true;
}

function checkAlphaNum(param)
{
	var num = '0123456789';
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

	var combined = lwr + upr + num;	
 	
	for (i=0; i<param.length; i++) {
		if (combined.indexOf(param.charAt(i),0) == -1) return 0;
	}
	return true;
}

function checkAlphaSpace(param)
{
	var sp = ' ';
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

	var combined = lwr + upr + sp;	
 	
	for (i=0; i<param.length; i++) {
		if (combined.indexOf(param.charAt(i),0) == -1) return 0;
	}
	return true;
}

function checkFirstName(param)
{
	var sp = '.- ';
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

	var combined = lwr + upr + sp;
	if(param.charAt(0)=='-'|| param.charAt(0)=='.') return 0;
	if(param.charAt(param.length-1)=='-' || param.charAt(param.length-1)=='.') return 0;
 	
	for (i=0; i<param.length; i++) {
		if (combined.indexOf(param.charAt(i),0) == -1) return 0;
	}
	return true;
}

function checkLastName(param)
{
	var sp = '\'.- ';
	var lwr = 'abcdefghijklmnopqrstuvwxyz';
	var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

	var combined = lwr + upr + sp;	
	if(param.charAt(0)=='-'|| param.charAt(0)=='.') return 0;
	if(param.charAt(param.length-1)=='-' || param.charAt(param.length-1)=='.') return 0;
 	
	for (i=0; i<param.length; i++) {
		if (combined.indexOf(param.charAt(i),0) == -1) return 0;
	}
	return true;
}

function validValue(fld)
{
  with(fld) 
  {
    if (selectedIndex <= 0 && options[selectedIndex].value == "")
    {
      return false;
    }
    else
    {
    	return true;
    }	
  }
}

function checkCreditCard (cardnumber, cardname) {
     
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "VISA", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MASTERCARD", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DINERS", 
               length: "14,", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "AMEX", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "DISCOVER", 
               length: "16", 
               prefixes: "6011",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "Enroute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
  
  // Check that the number is numeric, although we do permit a space to occur  
  // every four digits. 
  var cardNo = cardnumber
  var cardexp = /^([0-9]{4})\s?([0-9]{4})\s?([0-9]{4})\s?([0-9]{1,4})$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardexp.exec(cardNo);
  cardNo = RegExp.$1 + RegExp.$2 + RegExp.$3 + RegExp.$4;
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    // Process each digit one by one starting at the right
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      // Extract the next digit and multiply by 1 or 2 on alternative digits.
      calc = Number(cardNo.charAt(i)) * j;
    
      // If the result is in two digits add 1 to the checksum total
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      // Add the units element to the checksum total
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    // All done - if checksum is divisible by 10, it is a valid modulus 10.
    // If not, report an error.
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  // The following are the card-specific checks we undertake.
  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  // We use these for holding the valid lengths and prefixes of a card type
  var prefix = new Array ();
  var lengths = new Array ();
    
  // Load an array with the valid prefixes for this card
  prefix = cards[cardType].prefixes.split(",");
      
  // Now see if any of them match what we have in the card number
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  // If it isn't a valid prefix there's no point at looking at the length
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }
    
  // See if the length is valid for this card
  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  // See if all is OK by seeing if the length was valid. We only check the 
  // length if all else was hunky dory.
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

function validateEmail(addr,db) 
{
	var invalidChars = '\/\\ ";:?!()[]\{\}^|#%&*+';
	for (i=0; i<invalidChars.length; i++) 
	{
		if (addr.indexOf(invalidChars.charAt(i),0) > -1) 
		{
			return false;
	   	}
	   	//alert('email address contains invalid characters');
	}
	for (i=0; i<addr.length; i++) 
	{
 	  if (addr.charCodeAt(i)>127) 
 	  {
      		//if (db) //alert("email address contains non ascii characters.");
	       return false;
	   }
	}

	var atPos = addr.indexOf('@',0);
	if (atPos == -1) 
	{
 	  //	if (db) //alert('email address must contain an @');
   			return false;
	}
	if (atPos == 0) 
	{
   		//if (db) //alert('email address must not start with @');
	    return false;
	}
	if (addr.indexOf('@', atPos + 1) > - 1) 
	{
   		//if (db) //alert('email address must contain only one @');
	   return false;
	}
	if (addr.indexOf('.', atPos) == -1) 
	{
   		//if (db) //alert('email address must contain a period in the domain name');
	   return false;
	}
	if (addr.indexOf('@.',0) != -1) 
	{
   		//if (db) //alert('period must not immediately follow @ in email address');
	   return false;
	}
	if (addr.indexOf('.@',0) != -1)
	{
 	  	//if (db) //alert('period must not immediately precede @ in email address');
	   return false;
	}
	if (addr.indexOf('..',0) != -1) 
	{
   		//if (db) //alert('two periods must not be adjacent in email address');
   		return false;
	}
	var suffix = addr.substring(addr.lastIndexOf('.')+1).toLowerCase();
	if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') 
	{
   		//if (db) //alert('invalid primary domain in email address');
	   return false;
	}
	for (i=0; i<suffix.length; i++) 
	{
		if(suffix.length == 2 && (suffix.charAt(i) > 0 && suffix.charAt(i) < 9))
		{
		  return false;
		}
	}
	return true;
}

function validateAddress(address)
{
	var flag = true;
	var validchars = "abcdefghijklmnopqrstuvwxyz1234567890' ./#()-";
	for (var i=0; i < address.length; i++) 
	{
		var letter = address.charAt(i).toLowerCase();
		if (validchars.indexOf(letter) != -1)
			continue;
		else
		{
			flag = false;
			break;
		}
	}
	if(flag)
		return true;
	else
		return false;
}

function validateCity(city)
{
	var flag = true;
	var validchars = "abcdefghijklmnopqrstuvwxyz' .-";
	for (var i=0; i < city.length; i++) 
	{
		var letter = city.charAt(i).toLowerCase();
		if (validchars.indexOf(letter) != -1)
			continue;
		else
		{
			flag = false;
			break;
		}
	}
	if(flag)
		return true;
	else
		return false;
}

function expired( month, year ) 
{
	today = new Date();
	expiry = new Date(year, month);
	if (today.getTime() > expiry.getTime())
		return false;
	else
		return true;
}

function checkPostalCode(postalCode)
{
	var num = '0123456789';
	var length = postalCode.length;
	
	if(length == 5)
	{
		for (i=0; i < 5; i++)
		{
			if (num.indexOf(postalCode.charAt(i),0) == -1) return 0;
		}
	}
	else if(length == 10)
	{
		for (i=0; i < 5; i++)
		{
			if (num.indexOf(postalCode.charAt(i),0) == -1) return 0;
		}
		if(postalCode.charAt(5) == '-')
		{
			for (i=6; i < 10; i++)
			{
				if (num.indexOf(postalCode.charAt(i),0) == -1) return 0;
			}
		}
		else
		{
			return 0;
		}
	}
	else
	{
		return 0;
	}

	return true;
}
//function for checking Canadian Postal code
function checkCanPostalCode(postalCode)
{
	

	var num = '0123456789';
	var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	var length = postalCode.length;
	
	if(length == 7)
	{
		for (i=0; i < 3; i=i+2)
		
		{
		
			if(alpha.indexOf(postalCode.charAt(i),0) == -1) return 0;
		}
		
		if(num.indexOf(postalCode.charAt(1),0)== -1) return 0;
		
		if(postalCode.charAt(3) == " ")
		{
			
			for (i=4; i < 7; i=i+2)
			{
			  if (num.indexOf(postalCode.charAt(i),0) == -1) return 0;
			  
			}
			
			if(alpha.indexOf(postalCode.charAt(5),0) == -1) return 0;
			
		}
		else
		{
			return 0;
		}
	}
	
	else
	{
		return 0;
	}
	
	return true;
	
}



/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

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 checkDate(dtStr)
{
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strYear=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strDay=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 : yyyy-MM-dd")
		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 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
}

//checkDate ends


function trimSpace(obj)
{
	while(obj.value.charAt(0)==' ')
		obj.value=obj.value.substring(1,obj.value.length);
	while(obj.value.charAt(obj.value.length-1)==' ')
		obj.value=obj.value.substring(0,obj.value.length-1);
}

function toUpper(obj)
{
	obj.value=obj.value.toUpperCase();
}

function showMessage(message)
{
	while(1)
	{
		var indexOfNewline = message.indexOf("\n");
		if(indexOfNewline>=0)
		{
			message = message.substring(0,indexOfNewline) + "<br>&nbsp;" + message.substring(indexOfNewline+1);
		}
		else
		{
			break;
		}
	}

	while(1)
	{
		var indexOfSpace = message.indexOf(' ');
		if(indexOfSpace>=0)
		{
			message = message.substring(0,indexOfSpace) + "&nbsp;" + message.substring(indexOfSpace+1);
		}
		else
		{
			break;
		}
	}

	message = "<br>" + message + "<br>";
	
	var id = "errorArea";
	var tdBody = document.getElementById(id);
	tdBody.innerHTML = message;
}