var first_url = 'leadcontact.php';
var second_url = 'leadcontact.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() {
    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("idMSize").style.display = 'block';
                document.getElementById("idMSize").style.visibility = 'visible';
                document.getElementById("divCheckAuto").style.display='block';
                document.getElementById("divCheckAuto").style.visibility='visible';
        }
        else {
                document.getElementById("idMSize").style.display = 'none';
                document.getElementById("idMSize").style.visibility = 'hidden';
        }
}

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
    }

        var now = new Date();
        var currDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        var moveDate = getMoveDate();
        sYear = parseInt(objForm.MoveYear.options[document.formContact.MoveYear.selectedIndex].value);
        if (sYear < 1900) { sYear+=1900; }
        objForm.MDate.value = objForm.MoveMonth.options[objForm.MoveMonth.selectedIndex].value + '/' + objForm.MoveDay.options[objForm.MoveDay.selectedIndex].value + '/' + sYear;
        objForm.MoveYear.options[objForm.MoveYear.selectedIndex].value = sYear;

        if (moveDate - currDate < 0) {
            alert ("Sorry we can't accept move dates earlier than current date. Please try again.");
            SubmitCounter = 0
            return false;
        }

        if (objForm.MType.value == 1 && moveDate.getTime()/(1000*60*60*24) - currDate.getTime()/(1000*60*60*24) < 1) {
            alert ("Please enter a date at least 1 days from the current date or select our Last Minute Move!.");
            SubmitCounter = 0
            return false;
        }

        if (moveDate.getTime()/(1000*60*60*24) - currDate.getTime()/(1000*60*60*24) > 6*31) {
            alert ("Sorry we can't accept move dates older than 6 months after current date. Please try again.");
            SubmitCounter = 0
            return false;
        }

        if (sErrorMsg.length > 0) {
            objForm.MoveMonth.focus();
            alert(sErrorMsg);
            SubmitCounter = 0;
            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(objForm.ToState.value > 0){
                objForm.GeoID.value = objForm.ToState.value
        }
        if(objForm.ToCity.value > 0){
                objForm.GeoID.value = objForm.ToCity.value
        }
        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;
}


var global_form;

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"))
      if (nVal < 0)
      {
         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();
         global_form = form;
         setTimeout('global_form.submit();', 2000);
         return false;
      }
   }
   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';
   }
}
