var digits = "0123456789";
var digitsInUSPhoneNumber = 10;

// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";


// characters which are allowed in US phone numbers
var validUSPhoneChars = digits + phoneNumberDelimiters;

// Possible lengths for US zip codes
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9
var zipCodeDelimiters = ".-/";

// whitespace characters
var whitespace = " \t\n\r";

// non-digit characters which are allowed in dates
var dateDelimiters = "/-(),.";


//-------------------------------------------------------------------
// ValidControl(ctl, msg)
//   Returns true if ctl does contain a value
//	 ...will work for textbox,selectbox,textarea and password
//-------------------------------------------------------------------
function ValidControl(ctl, msg)
{

	var bResult = true;

	if ( !isEmpty(ctl.value) )
	{
		if (ctl.type=='text'||ctl.type=='textarea' || ctl.type=='password' || ctl.type=='file')
		{
			if (ctl.value.length==0) bResult=false;
		}
		else
		{
			if (ctl.type.indexOf('select')==0)
			{
				if (
					ctl.options[ctl.selectedIndex].value==-1 ||
					ctl.options[ctl.selectedIndex].value=='NULL' ||
					(
					 ctl.options[ctl.selectedIndex].value.length==0 &&
					 ctl.options[ctl.selectedIndex].text.length==0
					)
				   )
				{
					bResult=false;
				}
			}
		}
	}
	else
	{
		bResult = false;
	}

	if (!bResult)
	{
		if (msg!=null)
			alert(msg);
		else
			alert('Please make sure all required fields are filled in.');
			ctl.focus();
	}

	return bResult;
}


//-------------------------------------------------------------------
// isEmail(value)
//   Returns true if value contains correctly formated email address
//-------------------------------------------------------------------
function isEmail(ctl)
{
	var email = ctl.value;
	if ( email == "" )
	{
		return (true)
	}else{
		if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email))
		{
			return (true)
		}

		alert("Invalid E-mail Address! Please re-enter.")
		ctl.focus();
		return false;
	}
}

//-------------------------------------------------------------------
// isValidCompanyName(value)
//   Returns true if value contains correctly formated company name
//-------------------------------------------------------------------
function isValidCompanyName(ctl)
{
	var email = ctl.value;

	if (!(/[!@#$%]+/.test(email)))
	{
		return (true)
	}

	alert("Invalid Company Name.  Only letters, numbers, spaces, and underscores are allowed.")
	return false;
}


//-------------------------------------------------------------------
// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.
//-------------------------------------------------------------------
function stripWhitespace (s)
{
	return stripCharsInBag (s, whitespace)
}


//-------------------------------------------------------------------
// Check whether string s is empty.
//	Returns true if it is empty or all white space
//-------------------------------------------------------------------
function isEmpty(s)
{
	s = stripWhitespace(s)

	return ((s == null) || (s.length == 0))
}




//-------------------------------------------------------------------
// isInteger(value)
//   Returns true if value contains all digits
//-------------------------------------------------------------------
function isInteger(value)
{
	if ( isEmpty(value) ) return false;

	var val = value;

	for (var i=0; i < val.length; i++)
	{
		if (!isDigit(val.charAt(i)))
		{
			return false;
		}
	}
	return true;
}

//-------------------------------------------------------------------
// isDigit(value)
//   Returns true if value is a 1-character digit
//-------------------------------------------------------------------
function isDigit(num)
{
	var string="1234567890";
	if (string.indexOf(num) != -1)
	{
		return true;
	}

	return false;
}




//-------------------------------------------------------------------
// checkUSPhone (TEXTFIELD ctl)
//
// Check that string ctl.value is a valid US Phone.
//-------------------------------------------------------------------
function checkUSPhone (ctl, msg)
{
    var digitsInPhone = 10
    var bResults = true;

    // is it empty
    //if ( bResults ) bResults = ValidControl( ctl, msg );
    var phn = ctl.value;

    if ( phn != "" )
    {
		var normalizedPhone = stripCharsInBag(ctl.value, phoneNumberDelimiters)

	if (!isUSPhoneNumber(normalizedPhone, false))
	{
	   alert('Invalid number format entered. ex.###-###-####');
	   ctl.focus();
	   bResults = false;
	}
	else
	{  // if you don't want to reformat as (123) 456-7899, comment next line out
	   ctl.value = reformatUSPhone(normalizedPhone);
	   bResults = true;
	}
    }

    return bResults;

}


//-------------------------------------------------------------------
// isUSPhoneNumber (s)
//	Returns true if s is all digits and the length is correct
//-------------------------------------------------------------------
function isUSPhoneNumber (s)
{
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}

//-------------------------------------------------------------------
// takes USPhone, a string of 10 digits
// and reformats as (123) 456-789
//-------------------------------------------------------------------
function reformatUSPhone (USPhone)
{
	return (reformat (USPhone, 3, "-", 3, "-", 4))
}

//-------------------------------------------------------------------
// Removes all characters which appear in string bag from string s.
//-------------------------------------------------------------------
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++)
    {
	// Check that current character isn't whitespace.
	var c = s.charAt(i);
	if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}

//-------------------------------------------------------------------
// isZipCode(ctl)
//   Returns true if value contains correctly formated zip code
//-------------------------------------------------------------------
function isZipCode (ctl)
{

	var bResults = true;
	var zip = ctl.value;

	if ( zip != "" )
	{

	   var val = stripCharsInBag(ctl.value, zipCodeDelimiters)


	   if ( (val.length == digitsInZIPCode1) ||
		(val.length == digitsInZIPCode2) )
	   {
		for ( var i=0; i < val.length; i++ )
			if ( !isDigit(val.charAt(i)) )
				bResults = false;
	   }
	   else
	   {
		bResults = false;
	   }

	   if (!bResults)
	   {
		alert( 'Please enter either a 5 or 9 numeric zip code.' );
		ctl.focus();
	   }
	   else
	   {
		//Formats zip code into 1111-1111 if it is 9 chars long
		if ( val.length == digitsInZIPCode2 )
			ctl.value = reformat (val, '',5, "-", 4);
		else
			ctl.value = val;
	   }

	}
   return bResults;

}

//-------------------------------------------------------------------
//-------------------------------------------------------------------
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;
}

//-------------------------------------------------------------------
// checkDate(ctl)
//	Returns true if the ctl.value is a valid date
//-------------------------------------------------------------------
function checkDate(ctl)
{
	var bResults = true;

	//Check that it has a value
	if (bResults) bResults = ValidControl( ctl, "Please enter a valid date (mm/dd/yy)." );

	//Strip out possible delimiters ( / - ) and check to make sure only digits have been entered
	if ( bResults )
	{
	   var normalizedDate = stripCharsInBag(ctl.value, dateDelimiters);
	   if ( !isInteger(normalizedDate) )
	   {
		alert('Invalid date format. Try again. (mm/dd/yy)');
		ctl.focus();
		bResults = false;
	   }
	   else
	   {
		if (chkdate(ctl) == false)
		{
			alert("That date is invalid.  Please try again.");
			ctl.focus();
			bResults = false;
		}
	   }
	}

	return bResults
}

//-------------------------------------------------------------------
// chkdate(objName)
//	Returns true if the objName.value is a valid date
//-------------------------------------------------------------------
function chkdate(objName)
{
	var strDatestyle = "US"; //United States date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intday;
	var intMonth;
	var intYear;
	var booFound = false;
	var datefield = objName;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array(12);
	strMonthArray[0] = "Jan";
	strMonthArray[1] = "Feb";
	strMonthArray[2] = "Mar";
	strMonthArray[3] = "Apr";
	strMonthArray[4] = "May";
	strMonthArray[5] = "Jun";
	strMonthArray[6] = "Jul";
	strMonthArray[7] = "Aug";
	strMonthArray[8] = "Sep";
	strMonthArray[9] = "Oct";
	strMonthArray[10] = "Nov";
	strMonthArray[11] = "Dec";
	strDate = datefield.value;


	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++)
	{
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1)
		{
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);

			if (strDateArray.length != 3)
			{
				err = 1;
				return false;
			}
			else
			{
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}

			booFound = true;
		}
	}

	if (booFound == false)
	{
		if (strDate.length>5)
		{
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
	}

	if (strYear.length == 2)
	{
		strYear = '20' + strYear;
	}

	// US style
	if (strDatestyle == "US")
	{
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}

	intday = parseInt(strDay, 10);

	if (isNaN(intday))
	{
		err = 2;
		return false;
	}

	intMonth = parseInt(strMonth, 10);

	if (isNaN(intMonth))
	{
		for (i = 0;i<12;i++)
		{

			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase())
			{
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}

		if (isNaN(intMonth))
		{
			err = 3;
			return false;
		}
	}

	intYear = parseInt(strYear, 10);

	if (isNaN(intYear))
	{
		err = 4;
		return false;
	}

	if (intMonth>12 || intMonth<1)
	{
		err = 5;
		return false;
	}

	if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1))
	{
		err = 6;
		return false;
	}

	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1))
	{
		err = 7;
		return false;
	}

	if (intMonth == 2)
	{
		if (intday < 1)
		{
			err = 8;
			return false;
		}

	if (leapYear(intYear) == true)
	{
		if (intday > 29)
		{
			err = 9;
			return false;
		}
	}
	else
	{
		if (intday > 28)
		{
			err = 10;
			return false;
		}
	}
     }
	/*
	if (strDatestyle == "US")
	{
		datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
	}
	*/
   return true;
}


//-------------------------------------------------------------------
// leapYear(intYear)
//	Returns true if the intYear is a Leap Year
//-------------------------------------------------------------------
function leapYear(intYear)
{
	if (intYear % 100 == 0)
	{
		if (intYear % 400 == 0) { return true; }
	}
	else
	{
		if ((intYear % 4) == 0) { return true; }
	}
    return false;
}

//Form validator for "Sign Up" form
function validateForm()
{
	var frm = document.form1;
	var bResults = true;


	//first name
	if ( bResults ) bResults = ValidControl(frm.client_firstname, "First name is required.");
	
	//last name
	if ( bResults ) bResults = ValidControl(frm.client_lastname, "Last name is required.");

	//email
	if ( bResults ) bResults = ValidControl(frm.client_email, "Email is required.");

	//valid email
	if ( bResults ) bResults = isEmail(frm.client_email);

	//email matched
	if ( bResults )
	{
		if ( frm.client_email.value != frm.confirm_email.value  )
		{
			alert( "Email and Confirmation Email do not match." )
			frm.client_email.focus();
			bResults = false;
		}
	}

	//valid phone
	//if ( bResults ) bResults =  checkUSPhone (frm.client_phone, "Incorrect phone format.  FORMAT:  111-111-1111.");

	//valid street
	//if ( bResults ) bResults = ValidControl(frm.client_street, "Street is required.");

	//valid city
	if ( bResults ) bResults = ValidControl(frm.client_city, "City is required.");

	//valid state
	if ( bResults )
	{
		if ( frm.client_state[frm.client_state.selectedIndex].text == '- Select -')
		{
			alert('State is required');
			frm.client_state.focus();
			bResults = false;
		}

	}

	//valid city
	//if ( bResults ) bResults = ValidControl(frm.client_zip, "Zip is required.");

	//valid zip
	//if ( bResults ) bResults =  isZipCode ( frm.client_zip );

	//valid phone
	//if ( bResults ) bResults =  checkUSPhone (frm.client_agent_phone, "Incorrect phone format.  FORMAT:  (111) 111-1111.");

	//valid email
	//if ( bResults ) bResults = isEmail(frm.client_agent_email)  ;
	
	//how heard about point at city center
	//if ( bResults ) bResults = ValidControl(frm.client_inquiry, "Please include a question/inquiry for our Agents.");

	return bResults;

}

