var isNN = (navigator.appName.indexOf("Netscape")!=-1);
if(isNN)
  document.captureEvents(Event.KEYPRESS);
function autoTab(input,len, e){
  var keyCode = (isNN)?e.which:e.keyCode; 
  var filter = (isNN)?[0,8,9]:[0,8,9,16,17,18,37,38,39,40,46];
  if(input.value.length >= len && !containsElement(filter,keyCode)){
    input.value = input.value.slice(0,len);
    input.form[(getIndex(input)+1)%input.form.length].focus();
  }
  function containsElement(arr, ele){
    var found = false, index = 0;
    while(!found && index < arr.length)
      if(arr[index]==ele)
        found = true;
      else
        index++;
    return found;
  }
  function getIndex(input){
    var index = -1, i = 0, found = false;
    while (i < input.form.length && index==-1)
      if (input.form[i] == input)index = i;
      else i++;
    return index;
  }
  return true;
}




function onError( error_message)
{
	alert(error_message);
       	return false;
}
    
function hasValue(obj, obj_type)
{
    if (obj_type == "TEXT" || obj_type == "PASSWORD")
	{
    	if (obj.value.length == 0) 
      		return false;
    	else 
      		return true;
	}
    else if (obj_type == "SELECT")
	{
        for (i=0; i < obj.length; i++)
	    {
			if (obj.options[i].selected)
				if (obj.options[i].value.length == 0)
					return false;
				else
					return true;
		}

       	return false;	
	}
    else if (obj_type == "SINGLE_VALUE_RADIO" || obj_type == "SINGLE_VALUE_CHECKBOX")
	{

		if (obj.checked)
			return true;
		else
       		return false;	
	}
    else if (obj_type == "RADIO" || obj_type == "CHECKBOX")
	{

        for (i=0; i < obj.length; i++)
	    {
			if (obj[i].checked)
				return true;
		}
       	return false;	
	}
}

function  Form_1Validator()

{
    if  (!hasValue(window.document.Form_1.ADDR_PRIMARY_NO, "TEXT" )) 
    {
       onError("Please enter a House or Building number")
            return false; 
    }
    if  (!hasValue(document.Form_1.STREET_NAME, "TEXT" )) 
    {
		onError("Please enter a Street Name")
            return false; 
    }     
    if  (!hasValue(document.Form_1.STATE_ABBREV, "SELECT" )) 
    {
		onError("Please enter a State")
            return false; 
    }     
    if  (!hasValue(document.Form_1.ZIP_CODE, "TEXT" )) 
    {
        onError("Please enter a Zip Code")
            return false; 
    }   
    if  (hasValue(document.Form_1.ADDR_SECONDARY_ABBREV, "SELECT" ) && !hasValue(document.Form_1.ADDR_SECONDARY_NO,"TEXT")) 
    {
        onError("Please enter Values for Both the Apartment/Suite Type and Apartment/Suite Number")
            return false; 
    }       
    if  (!hasValue(document.Form_1.ADDR_SECONDARY_ABBREV, "SELECT" ) && hasValue(document.Form_1.ADDR_SECONDARY_NO,"TEXT")) 
    {
        onError("Please enter Values for Both the Apartment/Suite Type and Apartment/Suite Number")
            return false; 
    }         
    
    return true;
}

function  Form_2Validator()
{

    if  (!hasValue(document.Form_2.CUSTOMER_NAME, "TEXT" )) 
    {
        onError("Please enter a name")
            return false; 
    }
    
    //is the email address valid?
    if (!isEmailValue(document.Form_2.CUSTOMER_EMAIL.value, false)) 
    {
    		return false;
    }
    
    //is the Requested Install Time selected?
    if (document.Form_2.REQUESTED_INSTALL_TIME.selectedIndex == 0) 
    {
    		onError("Please select a requested install time")
    		return false;
    }
    
    //is the Requested Install Day selected?
	if (document.Form_2.REQUESTED_INSTALL_DAY.selectedIndex == 0) 
    {
    		onError("Please select a requested install day")
    		return false;
    }   
    
    //concatenate the part of the phone number to a phone number
	document.Form_2.CUSTOMER_HOME_PHONE.value = document.Form_2.CUSTOMER_HOME_PHONE_AC.value 
		+ document.Form_2.CUSTOMER_HOME_PHONE_P.value 
		+ document.Form_2.CUSTOMER_HOME_PHONE_S.value;
		
    
    //concatenate the part of the phone number to a phone number
	document.Form_2.CUSTOMER_WORK_PHONE.value = document.Form_2.CUSTOMER_WORK_PHONE_AC.value 
		+ document.Form_2.CUSTOMER_WORK_PHONE_P.value 
		+ document.Form_2.CUSTOMER_WORK_PHONE_S.value; 

	
	// is the phone number valid	
    if (!validatePhone(document.Form_2.CUSTOMER_HOME_PHONE.value)){
		onError("Please enter a 10 digit numeric home phone number.");
		return false;
    }
    
    //is the phone number valid
    if (!validatePhone(document.Form_2.CUSTOMER_WORK_PHONE.value)){
		onError("Please enter a 10 digit numeric work phone number.");
		return false;
    }
    
    // check if extension is a valid integer
    if (!isEmpty(document.Form_2.CUSTOMER_WORK_PHONE_X.value )){
		if (!isPosInteger(document.Form_2.CUSTOMER_WORK_PHONE_X.value)) {
			onError("Please enter only numbers for the work phone number extension.");
			return false;
		}
		
	}
    
    //is there at least one phone number?    
    if  (!hasValue(document.Form_2.CUSTOMER_HOME_PHONE, "TEXT" )) 
    {
		if (!hasValue(document.Form_2.CUSTOMER_WORK_PHONE, "TEXT" )) 
		{
			onError("Please enter at least one Phone Number")
            return false; 
        }  
     }
    
    //add extension to work phone if it exist
    if (!isEmpty(document.Form_2.CUSTOMER_WORK_PHONE_X.value )){
        document.Form_2.CUSTOMER_WORK_PHONE.value = document.Form_2.CUSTOMER_WORK_PHONE.value
		+ " X" + document.Form_2.CUSTOMER_WORK_PHONE_X.value ;
    }
    
    return true;
}

function validatePhone(Phone) {
	
	if (!isEmpty(Phone)) {
		if (!isPhone(Phone)) {
			return false;
		}
	}
	return true
}


var PatternsDict = new Object();

PatternsDict.Currency = /(\$)*\d{1,3}(,\d{3})*(\.\d{2})*/;
PatternsDict.Date = /^((0?[1,3,5,7,8]|1[0,2])(\/|\-)*([1-9]|[0-2][0-9]|3[0-1])|(0?2(\/|\-)*([1-9]|[0-2][0-9]))|(0?[4,6,9]|11)(\/|\-)*([1-9]|[0-2][0-9]|30))((\/|\-)*([1-2][0-9])*[0-9][0-9])*$/;
//PatternsDict.Email = /[A-Za-z]+\@[A-Za-z]+\.[A-Za-z]+/;
PatternsDict.Email = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
PatternsDict.Exists = /([A-Za-z]|[0-9])+/;
PatternsDict.Postal = /^((\w{3} \w{3})|(\w{6}))$/;
PatternsDict.Time = /^([1-9]|1[0-2]):[0-5]\d$/;
PatternsDict.Zip = /^\d{5}(-\d{4})*$/;
PatternsDict.DNS_Octet = /^\d*\d*\d$/;
PatternsDict.Phone = /^(\()*\d{3}(\))*( )*\d{3}(\-| )*\d{4}$/;
PatternsDict.PhoneNPA = /\d{3}/;
PatternsDict.PhoneNXX = /\d{3}/;
PatternsDict.PhoneSuffix = /\d{4}/;

//is the phone number valid
function isPhone(inputStr) {

	var thePat = PatternsDict["Phone"];
	var gotIt = thePat.exec(inputStr);
	
	if (!gotIt) {
		return false;
	}
	return true;
}

//function isEmail(strEmail) {

//	if(strEmail.length < 5)		{ return false }
//	if(strEmail.indexOf('@') == -1)	{ return false	}
//	if(strEmail.indexOf('.') == -1)	{ return false	}
//	if(strEmail.indexOf(':') > -1)	{ return false	}
//	if(strEmail.indexOf(';') > -1)	{ return false	}
//	if(strEmail.indexOf('\\') > -1)	{ return false	}
//	if(strEmail.indexOf('/') > -1)	{ return false	}
//	return true;
//}

// general purpose function to see if an input value has been entered at all 
function isEmpty(inputStr) { 
	if (inputStr == null || inputStr == "") { 
		return true; 
	} 
	return false; 
}

// general purpose function to see if a suspected numeric input is a positive integer 
function isPosInteger(inputVal) {
	var num = parseInt(inputVal);
	var strNum = String(num);
	if (isNaN(num)) {
		return false
	}
	if (num < 0) {
		return false
	}
	if (strNum != inputVal) {
		return false
	}
	
	return true
} 

//function to validate an email address if a value has been entered
function isEmailField (emailField, blnRequired) {

	var strErrorMsg = "The e-mail address is not correctly formatted.  Please correct the address before continuing.";
	if (blnRequired){
		if (isEmpty(emailField.value)){
			alert(strErrorMsg);
			emailField.select();
			emailField.focus();
			return false;			
		}
	}
	
	strErrorMsg = "The e-mail address is not correctly formatted.  Please correct the address before continuing.";
	if (!isEmpty(emailField.value) ) {
		if (!isEmailValid(emailField.value)){
			alert(strErrorMsg);
			emailField.select();
			emailField.focus();
			return false;
		}
	}
	
	//alert ('ok');
	return true
}

function isEmailValue (emailValue, blnRequired) {

	var strErrorMsg = "The e-mail address is not correctly formatted.  Please correct the address before continuing.";
	if (blnRequired){
		if (isEmpty(emailValue)){
			alert(strErrorMsg);
			return false;			
		}
	}
	
	strErrorMsg = "The e-mail address is not correctly formatted.  Please correct the address before continuing.";
	if (!isEmpty(emailValue) ) {
		if (!isEmailValid(emailValue)){
			alert(strErrorMsg);
			return false;
		}
	}
	
	//alert ('ok');
	return true
}

function isEmailValid (emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
//	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    //alert("The username doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        //alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	//alert("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   //alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   //alert(errStr)
   return false
}

// Make sure the string is at least 8 char long
if (emailStr.length < 8 ) {
   var errStr="This address is to short!"
   //alert(errStr)
   return false	
}


// Make sure the user is at least 2 char long zz in zz@xx.yy
if (user.length < 2 ) {
   var errStr="The user is to short!"
   //alert(errStr)
   return false	
}

// Make sure the domain is at least 5 char long xx.yy in zz@xx.yy
if (domain.length < 5 ) {
   var errStr="The user is to short!"
   //alert(errStr)
   return false	
}


// If we've gotten this far, everything's valid!
return true;
}

