var first_url = 'lead_ssvc.php';
var second_url = 'lead_ssvc.php';
var thrid_url = 'auto.php';

var auto_transp_url = 'auto.php';

var aCityStates = sCityStates.split('|');

var aBadWords = decodeWords(sBadWords).split(",");

SubmitCounter = 0;
window.onError = handleError;

function handleError(sError, sURL, nLineNum) {
        alert("Error:" + sError + " at line " + nLineNum);
        return false;
}

function decodeWords(sWords) {
        var i;
        var nCharCode;
        var sReturn = "";

        for (i=0; i<sWords.length; ++i)
        {        if (sWords.charAt(i) != ",") {
                        nCharCode = sWords.charCodeAt(i) - 1;
                        sReturn += unescape('%' + nCharCode.toString(16));
                }
                else
                        sReturn += sWords.charAt(i);
        }

        return sReturn;
}

function addDays(myDate,days) {
    return new Date(myDate.getTime() + days*24*60*60*1000);
}

function setfutureDate() {
    return;
    var futureDate = addDays(new Date(),14);
        document.formContact.MoveMonth.selectedIndex = futureDate.getMonth();
        document.formContact.MoveDay.selectedIndex = futureDate.getDate() -1;
        document.formContact.MoveYear.options[document.formContact.MoveYear.selectedIndex].value = futureDate.getYear();
}

function setMoveType()
{

        var nMType = document.formContact.MType.value;

   if(nMType == '3' ){
                document.getElementById("divAuto").style.display='block';
                document.getElementById("divAuto").style.visibility='visible';
                document.getElementById("divCheckAuto").style.display='none';
                document.getElementById("divCheckAuto").style.visibility='hidden';
      document.formContact.action = thrid_url;
        }
        else{
                document.getElementById("divAuto").style.display='none';
                document.getElementById("divAuto").style.visibility='hidden';
      if(nMType == '2' )
         document.formContact.action = second_url;
      if(nMType == '1' )
         document.formContact.action = first_url;
        }

        if (nMType == '1' || nMType == '2') {
                document.getElementById("divCheckAuto").style.display='block';
                document.getElementById("divCheckAuto").style.visibility='visible';
        }
        else {
        }

}

function setDefaults()
{
  setMoveType();
  setfutureDate();
}


var dtCh= "/";
var minYear=1900;
var maxYear=3000;

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;
}



// Validate a phone number
// Expects a phone number. Makes sure the user doesn't just enter sequential numbers or identical characters
function checkPhone(phonenumber, lblPhone){
        var lastpart=phonenumber.substring(0,10);
        var sample=lastpart.substring(0,1);
        var sPhone = stripCharsInBag(phonenumber, "-");


        if (sPhone.length == 0)
                return true;

        if (sPhone.length < 10)
        {        alert("Please enter a valid 10 digit " + lblPhone + " Phone Number.");
                return false;
        }

        if ((sPhone=="0123456789") || (sPhone=="1234567890"))
        {
                alert("Please enter valid "+ lblPhone +" Phone Number.");
                return false;
        }
        else if (!isInteger(sPhone)) {
                alert("Please use only numbers in " + lblPhone + " Phone");
                return false;
        }
        else if (sAreaCodes.indexOf(phonenumber.substring(0,3)) < 1) {
                alert("Please enter valid "+ lblPhone +" Phone Area code.");
                return false;
        }
        else if (phonenumber.substring(3,6) == "555") {
                alert("Please enter valid "+ lblPhone +" Phone Number.");
                return false;
        }
        else {
                for(i=1;i<lastpart.length;i++)
                {
                        if ((lastpart.substring(i,i+1))!=sample) return true;
                }
                alert("Please enter valid "+ lblPhone +" Phone Number")
                return false;
        }
        return true;
}

function isValidEmail (strEmail) {
        return (strEmail.match(/^[^\/\#\,\^\*\\]+\@([A-Za-z0-9\-]{1,}\.)+([A-Za-z]{2,3})$/) ? true:false);
}

function setMonthDays()
{
        var optDay = document.formContact.MoveDay.options;
        var nMonth = parseInt(document.formContact.MoveMonth.options[document.formContact.MoveMonth.selectedIndex].value);
        var nYear = parseInt(document.formContact.MoveYear.options[document.formContact.MoveYear.selectedIndex].value);
        var nMaxDay;
        var i;
        var nCurrentDay = optDay.selectedIndex + 1;
   if (nYear < 1900)
      nYear += 1900;

        if (nMonth == 2)
        {        if (((nYear % 4 == 0) && (nYear % 100 != 0)) || (nYear % 400 == 0))
                        nMaxDay = 29;
                else
                        nMaxDay = 28;
        }
        else if (nMonth == 4 || nMonth == 30 || nMonth == 9 || nMonth == 11)
                nMaxDay = 30
        else
                nMaxDay = 31;

        if (nCurrentDay > nMaxDay)
                nCurrentDay = nMaxDay;

        optDay.length = 0;
        for (i=1; i<=nMaxDay; ++i)
        {        optDay[i-1] = new Option;
                optDay[i-1].text = i;
                optDay[i-1].value = i;
        }
        optDay.selectedIndex = nCurrentDay - 1;
}


function getMoveDate()
{
        var dMDate;
        var objForm;
        var nMonth;
        var nDay;
        var nYear;

        objForm = document.formContact;
        nYear = parseInt(objForm.MoveYear.options[objForm.MoveYear.selectedIndex].value);
        nMonth = parseInt(objForm.MoveMonth.options[objForm.MoveMonth.selectedIndex].value);
        nDay = parseInt(objForm.MoveDay.options[objForm.MoveDay.selectedIndex].value);
   if (nYear < 1900)
      nYear += 1900;
        dMDate = new Date(nYear, nMonth - 1, nDay);

        return dMDate;
}

// Verify required fields
function validate(objForm) {
        var nOpt;
   var isSelected = ""
   var objForm = document.formContact;
   var sErrorMsg = "";

        // Prevent multiple submissions
    if (countSubmit() == false) {
        return false
    }

    if (!isFieldValid(objForm.Zip, 5, "From Zip"))
                return false;

        if (!isFieldValid(objForm.ToState, 1, "To State"))
                return false;

        if (!isFieldValid(objForm.ToCity, 1, "To City"))
                return false;

        if (!isFieldValid(objForm.MType, 1, "Move Type"))
                return false;

        if (!isFieldValid(objForm.FirstName, 1, "First Name"))
                return false;

        if (!isFieldValid(objForm.LastName, 1, "Last Name"))
                return false;

        if(isValidEmail(objForm.EmailAddr.value) == false) {
                objForm.EmailAddr.focus();
                alert ("Please enter a valid Email address.")
                SubmitCounter = 0
                return false;
        }

        var strWorkPhone = objForm.txtWorkPhone1.value + objForm.txtWorkPhone2.value + objForm.txtWorkPhone3.value;
        var strHomePhone = objForm.txtHomePhone1.value + objForm.txtHomePhone2.value + objForm.txtHomePhone3.value;

        if ((strWorkPhone.length == 0) && (strHomePhone.length == 0)) {
                objForm.txtWorkPhone1.focus();
                alert ("Please enter at least one phone number.")
                SubmitCounter = 0
                return false;
        }
        if (checkPhone(strWorkPhone, "Work")==false) {
                objForm.txtWorkPhone1.focus();
                SubmitCounter = 0
                return false;
        }
        if (checkPhone(strHomePhone, "Home")==false) {
                objForm.txtHomePhone1.focus();
                SubmitCounter = 0
                return false;
        }
        if (!isFieldValid(objForm.ContactPref, 1, "Best Time To Call"))
                return false

/*        if (findBadWord(objForm.txtComment.value)) {
                alert("The contents of 'Additional Requests' cannot be accepted");
                objForm.txtComment.focus();
                SubmitCounter = 0;
                return false;
        }
        if (objForm.txtComment.value.length > 255) {

                alert ("Please enter less than 255 characters in 'Additional Requirements'. Please remove " + (document.formContact.txtComment.value.length - 255) + " characters.")
                objForm.txtComment.focus();
                SubmitCounter = 0;
                return false;
        }*/
        if (document.formContact.int_vehicle.checked == true && (objForm.MType.value == "1" || objForm.MType.value == "2") || objForm.MType.value == "3"){
                if (!isFieldValid(objForm.txtMake1, 1, "Please enter vehicle make."))
                        return false;

                if (!isFieldValid(objForm.txtModel1, 1, "Please enter vehicle model."))
                        return false;

                if (!isValidAutoYear(objForm.txtYear1, "Please enter a valid four digit vehicle year."))
                        return false;

        }

        return true;
}

function isFieldValid(objField, nMinLen, sFieldName) {
        var bSelectField = false

        if (objField.type == 'select-one')
                bSelectField = true;

        if ((bSelectField && objField.value < 1)
             || objField.value.length < nMinLen) {
                objField.focus();
                if (bSelectField)
                        alert("Please select a '" + sFieldName + "'");
                else
                        alert("Please enter '" + sFieldName + "'");

                SubmitCounter = 0;
                return false;
        }

        if (!bSelectField && findBadWord(objField.value)) {
                alert("Contents of '" + sFieldName + "' cannot be accepted");
                objField.focus();
                SubmitCounter = 0;
                return false;
        }
        return true;
}

function findBadWord(sText) {
        var nIndex;

        sText = sText.toLowerCase();
        for (nIndex=0; nIndex<aBadWords.length; ++nIndex) {
                if (sText.indexOf(aBadWords[nIndex]) >= 0)
                        return true;
        }

        return false;
}

function isValidAutoYear(objField, sErrorMsg) {
        if (objField.value.length != 4 || !isInteger(objField.value)
            || objField.value < 1900 || objField.value > 2100) {
                objField.focus();
                alert(sErrorMsg);
                SubmitCounter = 0;
                return false;
        }
        return true;
}

function countSubmit() {
    SubmitCounter++;
    if(SubmitCounter > 1) {
      return false;
    }
  return true;
}

function initState( formName, stateDropName, cityDropName, initialStateCode, initialCityId )
{
                var objForm = document.forms[formName];
                var stateDrop = objForm.elements[stateDropName];
                var cityDrop = objForm.elements[cityDropName];
                var selState;

                if (initialStateCode > 0)
                {
                        selState = initialStateCode-1;
                }
                else
                {
                        selState = stateDrop.selectedIndex;
                }
                for (i=0;i<aCityStates.length/3;i++)
                {
                        var stateName = aCityStates[i*3];
                        var stateCode = aCityStates[i*3+1];
                        stateDrop.options[i+1]=new Option(stateName,stateCode);
                        if (stateCode == initialStateCode)
                                {
                                        selState = i + 1;
                                }
                }
                stateDrop.selectedIndex=selState;
                if (selState>0)
                {
                        selCity = cityDrop.selectedIndex;
                        changedState( formName, stateDropName, cityDropName, selCity, initialCityId );
                }
                else
                {
                        stateDrop.selectedIndex=0;
                        cityDrop.selectedIndex=0;
                }
}

function changedState( formName, stateDropName, cityDropName, selCity, initialCityId )
{
                var objForm = document.forms[formName];
                var aCities
                stateDrop = objForm.elements[stateDropName];
                cityDrop = objForm.elements[cityDropName];
                selState = stateDrop.selectedIndex;

                if(selState>0)
                {
                        aCities=(aCityStates[(selState-1)*3+2]).split('/');
                        cityDrop.options.length=0;
                        cityDrop.options[0]=new Option('-- Select a City --','');
                        cityDrop.options[1]=new Option('-----------------','');
                        for (i=0;i<aCities.length/2;i++)
                        {
                                var cityName = aCities[i*2];
                                var cityId = aCities[i*2+1];
                                cityDrop.options[i+2]=new Option(cityName,cityId);
                                if ( cityId == initialCityId )
                                {
                                        selCity = i+2;
                                }
                        }
                }
                cityDrop.selectedIndex=selCity;
}


function frmSubmit(form)
{
   if(validate(form))
   {
      document.formContact.cmdContact.disabled=true;
      nVal = document.formContact.MType.value;
      if (document.formContact.int_vehicle.checked == true && (nVal == "1" || nVal == "2"))
      {
         frm = document.getElementById("iFrm").Document.formContact;
         frm.action = auto_transp_url;
//         frm.MType.value = document.formContact.MType.value;
         frm.MoveMonth.value = document.formContact.MoveMonth.value;
         frm.MoveDay.value = document.formContact.MoveDay.value;
         frm.MoveYear.value = document.formContact.MoveYear.value;
         frm.MDate.value = document.formContact.MDate.value;
         frm.GeoID.value = document.formContact.GeoID.value;
         frm.Zip.value = document.formContact.Zip.value;
         frm.ToState.value = document.formContact.ToState.value;
         frm.ToCity.value = document.formContact.ToCity.value;
         frm.FirstName.value = document.formContact.FirstName.value;
         frm.LastName.value = document.formContact.LastName.value;
         frm.EmailAddr.value = document.formContact.EmailAddr.value;
         frm.txtWorkPhone1.value = document.formContact.txtWorkPhone1.value;
         frm.txtWorkPhone2.value = document.formContact.txtWorkPhone2.value;
         frm.txtWorkPhone3.value = document.formContact.txtWorkPhone3.value;
         frm.txtWorkPhone4.value = document.formContact.txtWorkPhone4.value;
         frm.txtHomePhone1.value = document.formContact.txtHomePhone1.value;
         frm.txtHomePhone2.value = document.formContact.txtHomePhone2.value;
         frm.txtHomePhone3.value = document.formContact.txtHomePhone3.value;
         frm.txtHomePhone4.value = document.formContact.txtHomePhone4.value;
         frm.ContactPref.value = document.formContact.ContactPref.value;
//         frm.rCallYouAtWork.value = document.formContact.rCallYouAtWork.value;
         frm.txtMake1.value = document.formContact.txtMake1.value;
         frm.txtModel1.value = document.formContact.txtModel1.value;
         frm.txtYear1.value = document.formContact.txtYear1.value;
         frm.optRunningCond1.value = document.formContact.optRunningCond1.value;
         frm.txtComment.value = document.formContact.txtComment.value;
         document.formContact.txtMake1.value='';
         document.formContact.txtModel1.value='';
         document.formContact.txtYear1.value='';
         document.formContact.int_vehicle.value='';
         frm.submit();
      }
   }
   else
      return false;
}

function chAuto()
{
   if (document.formContact.int_vehicle.checked == true)
   {
      document.getElementById("divAuto").style.display='block';
      document.getElementById("divAuto").style.visibility='visible';
   }
   else
   {
      document.getElementById("divAuto").style.display='none';
      document.getElementById("divAuto").style.visibility='hidden';
   }
}