// VARIABLE DECLARATIONS

var digits = "0123456789";
var whitespace = " \t\n\r";				// whitespace characters

var decimalPointDelimiter = ",.";		 // decimal point character 
var currencyDelimiters = "$,.";          // currency delimiters
var phoneNumberDelimiters = "()- ";		
var ZIPCodeDelimiters = "-";
	
//Required Field Messages
var sRequired_Prefix = "Please enter a "
var sRequired_SelectPrefix = "You must select a  "

// Invalid Entry Messages
var InvalidZIPCode = " must be a 5 or 9 digit U.S. ZIP Code (e.g.,  94043)"
var InvalidPhone = " must be a valid phone number (e.g.,  (304) 555-1212)"
var InvalidEmail = " must be a valid email address (e.g., anybody@emailprovider.com)"
var InvalidNumber = " must be a valid numerical value"
var InvalidDate = "The end date cannot be earlier than the start date"
var InvalidPassword = "The Passwords you entered do not match"

var defaultEmptyOK = true

// Check whether string s is empty.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

// Returns true if string s is empty or whitespace characters only.
function isWhitespace (s)
{   var i;
    if (isEmpty(s)) return true;
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }
    return true;
}

// Removes all characters which appear in string bag from string s.
function stripCharsInBag (s, bag)

{   var i;
    var returnString = "";
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

//Searches for a given character (c) in s
function charInString (c, s)
{  
	for (i = 0; i < s.length; i++)
    {   if (s.charAt(i) == c) return true;
    }
    return false
}

// Returns true if character c is a digit 
function isDigit (c)
{   return ((c >= "0") && (c <= "9"))
}

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);
    for (i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);

        if (!isDigit(c)) return false;
    }
    return true;
}

//Returns true if s is a validPhone Number
function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == 10)
}

//Returns true if s is a valid Phone Number
function isPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isPhoneNumber.arguments[1] == true);
    return (isPositiveInteger(s))
}

//Returns true if s is a valid US Zip Code
function isZIPCode (s)
{  if (isEmpty(s)) 
       if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) && 
            ((s.length == 5) ||
             (s.length == 9)));
}

//Returns true if s is a valid Email Address
function isEmail (s)
{   if (isEmpty(s)) 
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);
       
    if (isWhitespace(s)) return false;

	if (charInString("'",s)) return false;

    var i = 1;
    var sLength = s.length;

    while ((i < sLength) && (s.charAt(i) != "@"))
    { i++
    }

    if ((i >= sLength) || (s.charAt(i) != "@")) return false;
    else i += 2;

    while ((i < sLength) && (s.charAt(i) != "."))
    { i++
    }
    
    if ((i >= sLength - 1) || (s.charAt(i) != ".")) return false;
    else return true;
}

function isChecked(sField, iCount)
{  
	var i=0;  
	while(i < iCount)
	{
		var sFieldName = sField + i
		var chkBox = document.all? document.all[sFieldName] : document.getElementById? document.getElementById(sFieldName) : ""
		i++
		if(chkBox.checked)
			return true;
	}   
	return false; 
} 

// Check that string oField.selected index is not 0
function checkSelect (oField, s, emptyOK)
{  
	if (checkSelect.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null)) return true;
	if (oField==null) return warnSelect (oField, s);
    if ((emptyOK == true) && (oField.selectedIndex == 0)) return true;
    if (oField.selectedIndex == 0) 
		{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnSelect (oField, s);
		}
    else return true;
}

// Check that string oField.selected index is not 0 --warn user to create
function checkCreate (oField, ochkField, s, emptyOK)
{   
	if (checkCreate.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null) && (ochkField.checked ==true)) return true;
	if (oField==null) return warnCreate (oField, s);
    if ((emptyOK == true) && (oField.selectedIndex == 0) && (ochkField.checked ==true))return true;
    if (oField.selectedIndex == 0) 
		{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnSelect (oField, s);
		}
    else return true;
}

// Check that string oField.value is not all whitespace.
function checkString (oField, s, emptyOK)
{   
	if (checkString.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null)) return true;
	if (oField==null) return warnEmpty (oField, s);
    if ((emptyOK == true) && (isEmpty(oField.value))) return true;
    if (isWhitespace(oField.value)) 
		{
			document.getElementById('divSave').style.visibility = 'hidden'
			return warnEmpty (oField, s);
		}
    else return true;
}

// Check that user has selected a checkbox value
function checkCheckbox (sField, iCount, s)
{   
    if (!isChecked(sField, iCount)) 
		{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnCheck (s);
		}
    else return true;
}

// Check that string oField.value is not all whitespace.
function checkDate (oField, s, emptyOK)
{   
	if (checkDate.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null)) return true;
	if (oField==null) return warnEmpty (oField, s);
    if ((emptyOK == true) && (isEmpty(oField.value))) return true;
    if (isWhitespace(oField.value))
		{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnEmpty (oField, s);
		}
    else return true;
}

// Check that string contains only whole numerical values
function checkInteger (oField,sType,emptyOK)
{   
	if (checkInteger.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null)) 
		{
		return true;
		}
    if ((emptyOK == true) && (isEmpty(oField.value)))
		{
		 return true;
}
    else
    { var normalizedNumber = stripCharsInBag(oField.value, currencyDelimiters)
    if (!isInteger(normalizedNumber)) 
    	{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnInvalid(oField,sType,InvalidNumber);
		}
    else return true;
    }
}

// Check that string contains only numerical values
function checkNumber (oField,sType,emptyOK)
{   
	if (checkNumber.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null)) 
		{		return true;
		}
    if ((emptyOK == true) && (isEmpty(oField.value))) 
    {		return true;
	}
    else
    { var normalizedNumber = stripCharsInBag(oField.value, decimalPointDelimiter)
		if (!isInteger(normalizedNumber,false))
    		{
			document.getElementById('divSave').style.visibility = 'hidden'
			return warnInvalid(oField,sType,InvalidNumber);
			}
		return true;
	}
}

// Check that string oField.value is not all whitespace.
function checkCurrency (oField, sType,emptyOK)
{   
	if (checkCurrency.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null)) 
		{		return true;
		}
    if ((emptyOK == true) && (isEmpty(oField.value))) 
    {		return true;
	}
    else
    { var normalizedCurrency = stripCharsInBag(oField.value, currencyDelimiters)
		if (!isInteger(normalizedCurrency,false))
    		{
			document.getElementById('divSave').style.visibility = 'hidden'
			return warnInvalid(oField,sType,InvalidNumber);
			}
		return true;
	}
}

// Check that string oField.value is a valid ZIP code.
function checkZIPCode (oField, sType, emptyOK)
{   
	if (checkZIPCode.arguments.length == 1) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField == null))return true;
    if ((emptyOK == true) && (isEmpty(oField.value)))return true;
    else
    { var normalizedZIP = stripCharsInBag(oField.value, ZIPCodeDelimiters)
      if (!isZIPCode(normalizedZIP, false))
    	{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnInvalid(oField,sType,InvalidZIPCode);
		} 
      else 
      {  // if you don't want to insert a hyphen, comment next line out
         oField.value = reformatZIPCode(normalizedZIP)
         return true;
      }
    }
}

// Check that string oField.value is a valid Phone.
function checkPhone (oField, sType,emptyOK)
{  	if (checkPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField == null))return true;
    if ((emptyOK == true) && (isEmpty(oField.value))) return true;
    else
    {  var normalizedPhone = stripCharsInBag(oField.value, phoneNumberDelimiters)
       if ((!isUSPhoneNumber(normalizedPhone, false))&& (!isPhoneNumber(oField.value, false)))
           	{
			document.getElementById('divSave').style.visibility = 'hidden'
			return warnInvalid(oField,sType,InvalidPhone);
			} 
       else 
       {  // if you don't want to reformat as (123) 456-789, comment next line out
          if (isUSPhoneNumber(normalizedPhone, false))
			oField.value = reformatUSPhone(normalizedPhone);
            return true;
       }
    }
}

// Check that string oField.selected index is not 0
function checkExtension (oField, sType,emptyOK)
{	
	if (checkExtension.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField==null)) return true;
    if ((emptyOK == true) && (isEmpty(oField.value))) return true;
    if (!isInteger(oField.value, false)) 
    	{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnInvalid(oField,sType,InvalidNumber);
		}
    else return true;
}

// Check that string oField.value is a valid Email.
function checkEmail (oField, sType,emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (oField == null))return true;
    if ((emptyOK == true) && (isEmpty(oField.value))) return true;
    if (oField == 'undefined') return true;
    else if (!isEmail(oField.value, false)) 
        {
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnInvalid(oField,sType,InvalidEmail);
		}
    else return true;
}

// Check that string oField1.value = oField2.value
function verifyPassword (oField1, oField2)
{   if (isEmpty(oField1.value))
    	{
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnEmpty (oField1,"Password");
		}
	else if (isEmpty(oField2.value))
	    {
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnEmpty(oField2,"Password Verification");
		}
		
    else if (oField1.value!=oField2.value) 
        {
		document.getElementById('divSave').style.visibility = 'hidden'
		return warnPassword (oField2, InvalidEmail);
		}
    else return true;
}

//Reformat string values for valid input format
function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

// takes USPhone, a string of 10 digits and reformats as (123) 456-789
function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}

// takes ZIPString, a string of 5 or 9 digits; if 9 digits, inserts separator hyphen
function reformatZIPCode (ZIPString)
{   if (ZIPString.length == 5) return ZIPString;
    else return (reformat (ZIPString, "", 5, "-", 4));
}

/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */

// Notify user that required field oField is empty.
function warnEmpty (oField, s)
{  
	if (oField == undefined) return true;
	oField.focus();
    alert(sRequired_Prefix + s);
    return false;
}

// Notify user that contents of field oField are invalid.
function warnInvalid (oField, sType, s)
{   oField.focus()
    oField.select()
    alert("The " + sType + s)
    return false
}

// Notify user that a null entry requires selection
function warnSelect (oField, s)
{   oField.focus()
    alert(sRequired_SelectPrefix + s)
    return false
}

// Notify user that a null entry requires selection or new entry 
function warnCreate (oField, s)
{   oField.focus()
    alert(sRequired_SelectPrefix + s)
    return false
}

function warnCheck (s)
{	
	alert(sRequired_SelectPrefix + s)
	return false
}

function warnDate ()
{	alert(InvalidDate)
	return false
}

function warnPassword (oField)
{	oField.focus()
	oField.value = ""
	alert(InvalidPassword)
	return false
}

function warnLogin (oField)
{	oField.focus()
	alert(InvalidLogin)
	return false
}

//Global Validation functions
function validateCompany (bValidate)
{  
	var oName =document.all? document.all["ctlCompany_txtCompanyName"] : document.getElementById? document.getElementById("ctlCompany_txtCompanyName") : ""
	var oCity =document.all? document.all["ctlCompany_txtCity"] : document.getElementById? document.getElementById("ctlCompany_txtCity") : ""
	var oState =document.all? document.all["ctlCompany_ddlState"] : document.getElementById? document.getElementById("ctlCompany_ddlState") : ""
	var oZip =document.all? document.all["ctlCompany_txtZipcode"] : document.getElementById? document.getElementById("ctlCompany_txtZipcode") : ""

    if (bValidate == true) 
     {
        return (
       			checkString(oName,"Company Name", false)&&
				checkString(oCity,"Company City", false)&&
				checkSelect(oState,"Company State", false)&&
				checkZIPCode(oZip, "Company Zipcode", true)&&
				checkCheckbox("ctlCompany_cblCompanyType_", 10, "Company Type")
			  );
	}
    else 
    {
		return true;
	}
}
	
function validateContact (bValidate, bEmail)
{
    	var oFirst =document.all? document.all["ctlContact_txtFirstName"] : document.getElementById? document.getElementById("ctlContact_txtFirstName") : ""
    	var oLast = document.all? document.all["ctlContact_txtLastName"] : document.getElementById? document.getElementById("ctlContact_txtLastName") : ""
		var oEmail =document.all? document.all["ctlContact_txtEmail"] : document.getElementById? document.getElementById("ctlContact_txtEmail") : ""
		var oState =document.all? document.all["ctlContact_ddlState"] : document.getElementById? document.getElementById("ctlContact_ddlState") : ""
		var oZip =document.all? document.all["ctlContact_txtZipcode"] : document.getElementById? document.getElementById("ctlContact_txtZipcode") : ""
		var oPhone =document.all? document.all["ctlContact_txtPhone"] : document.getElementById? document.getElementById("ctlContact_txtPhone") : ""
        var oExtension =document.all? document.all["ctlContact_txtExtension"] : document.getElementById? document.getElementById("ctlContact_txtExtension") : ""
  
		if (bValidate==true)
		{ 
			return (
				checkString(oFirst,"Contact 'First' Name", false)&&
				checkString(oLast,"Contact 'Last' Name", false)&&
				checkEmail(oEmail, "Contact E-Mail", bEmail)&&
				checkSelect(oState,"Contact State", false)&&
				checkZIPCode(oZip, "Contact Zipcode", true)&& 
				checkPhone(oPhone, "Contact Phone Number", true)&&  
				checkExtension(oExtension, "Contact Phone Extension", true)
			  );
		
		
		}
    else 
    {
		return true;
	}
}

function validateDate()
{
    	var oSYear =document.all? document.all["startDateyearBox"] : document.getElementById? document.getElementById("startDateyearBox") : ""
    	var oSMonth=document.all? document.all["startDatemonthBox"] : document.getElementById? document.getElementById("startDatemonthBox") : ""
    	var oSDay=document.all? document.all["startDatedayBox"] : document.getElementById? document.getElementById("startDatedayBox") : ""
    	var oEYear =document.all? document.all["endDateyearBox"] : document.getElementById? document.getElementById("endDateyearBox") : ""
    	var oEMonth=document.all? document.all["endDatemonthBox"] : document.getElementById? document.getElementById("endDatemonthBox") : ""
    	var oEDay=document.all? document.all["endDatedayBox"] : document.getElementById? document.getElementById("endDatedayBox") : ""
    	if ((parseInt(oSYear.options[oSYear.selectedIndex].value) > parseInt(oEYear.options[oEYear.selectedIndex].value)) ||
			(parseInt(oSYear.options[oSYear.selectedIndex].value) == parseInt(oEYear.options[oEYear.selectedIndex].value) && parseInt(oSMonth.options[oSMonth.selectedIndex].value) > parseInt(oEMonth.options[oEMonth.selectedIndex].value)) ||
			(parseInt(oSYear.options[oSYear.selectedIndex].value) == parseInt(oEYear.options[oEYear.selectedIndex].value) && parseInt(oSMonth.options[oSMonth.selectedIndex].value) == parseInt(oEMonth.options[oEMonth.selectedIndex].value) && parseInt(oSDay.options[oSDay.selectedIndex].value) > parseInt(oEDay.options[oEDay.selectedIndex].value)))
		{
			document.getElementById('divSave').style.visibility = 'hidden'
			return warnDate();
		}
		else
		{
			return true;
		}
}

//Check to ensure one item has been selected or entered
function checkDupFields (oSelectField, oTextField, s)
{
    if ((oSelectField.selectedIndex <= 0) && (isWhitespace(oTextField.value)))
     {
		alert(s)
		return false;
     }
}
