$(document).ready(function () {

    PageMethod('GetManufacturers', [], ManuAjaxSucceeded, AjaxFailed);
    PageMethod('GetCountries', [], CountriesAjaxSucceeded, AjaxFailed);
    PageMethod('GetAddressCountries', [], AddressCountriesAjaxSucceeded, AjaxFailed);
    PageMethod('GetTitles', [], TitlesAjaxSucceeded, AjaxFailed);

    setVehicleOfInterest();

});

function PageMethod(fn, paramArray, successFn, errorFn) {
    var pagePath = "http://www.astonmartin.com/newsletter/newsletterws.asmx",
		paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    //Call the page method   
    $.ajax({
        type: "POST",
        url: pagePath + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

function CountriesAjaxSucceeded(result) {
    var options = '<option value="0">-- Please select --</option>';
    for (var i = 0; i < result.d.length; i++) {
        if (result.d[i] != null && result.d[i] != '') {
            options += '<option value="' + result.d[i] + '">' + result.d[i] + '</option>';
        }
    }
    $("#countryDealer").html(options);
}

function ManuAjaxSucceeded(result) {
    var options = '<option value="0">-- Please select --</option>';
    for (var i = 0; i < result.d.length; i++) {
        options += '<option value="' + result.d[i].ID + '">' + result.d[i].Manufacturer + '</option>';
    }
    $("#currentCarMake").html(options);
}

function AddressCountriesAjaxSucceeded(result) {
    var options = '<option value="0">-- Please select --</option>';
    for (var i = 0; i < result.d.length; i++) {
        if (result.d[i] != null && result.d[i] != '') {
            options += '<option value="' + result.d[i].Id + '">' + result.d[i].Name + '</option>';
        }
    }
    $("#country").html(options);
}

function AddressCountriesAjaxSucceeded(result) {
    var options = '<option value="0">-- Please select --</option>';
    for (var i = 0; i < result.d.length; i++) {
        if (result.d[i] != null && result.d[i] != '') {
            options += '<option value="' + result.d[i].Id + '">' + result.d[i].Name + '</option>';
        }
    }
    $("#country").html(options);
}

function TitlesAjaxSucceeded(result) {
    var options = '<option value="0">-- Please select --</option>';
    for (var i = 0; i < result.d.length; i++) {
        options += '<option value="' + result.d[i].Id + '">' + result.d[i].English + '</option>';
    }
    $("#titleSelect").html(options);
}

function CountrySelected() {
    if ($("#countryDealer").val() != "0") {
        $("#dealerDetailsText").val('');
        PageMethod('GetDealersForCountry', ['country', $("#countryDealer").val()], DealerGetAjaxSucceeded, AjaxFailed);
    }
    else {
        $("#dealerDetailsText").val('');
        $("#dealer").html('');
    }
}

function DealerGetAjaxSucceeded(result) {
    var options;
    options = '<option value="0">-- Please select --</option>';
    for (var i = 0; i < result.d.length; i++) {
        options += '<option value="' + result.d[i].Id + '">' + result.d[i].Location + '</option>';
    }
    $("#dealer").html(options);
}

function AjaxFailed(result) {
    alert("There was an error. Please try again later.");
}

function CountrySelected() {
    if ($("#countryDealer").val() != "0") {
        $("#dealerDetailsText").val('');
        PageMethod('GetDealersForCountry', ['country', $("#countryDealer").val()], DealerGetAjaxSucceeded, AjaxFailed);
    }
    else {
        $("#dealerDetailsText").val('');
        $("#dealer").html('');
    }
}

function SubmitNewVehicleInterestLead() {

    $("#submit").attr("disabled", "true");

    // Validate the lead entry page
    var email = $("#emailAddressLead").val();
    var isValid = isValidEmailAddress(email);

    if ($("#currentCarMake").val() == "1") {

        if ($("#astonModel").val() == "0") {
            isValid = false;
            $("#astonModelLabel").addClass("invalid");
        }
        else {
            $("#astonModelLabel").removeClass("invalid");
        }
        $("#modelLabel").removeClass("invalid");
    }
    else {
        $("#astonModelLabel").removeClass("invalid");

        if (jQuery.trim($("#model").val()) == "") {
            $("#modelLabel").addClass("invalid");
        }
        else {
            $("#modelLabel").removeClass("invalid");
        }
    }

    if (!isValid || !isValidEmailAddress(email) || $("#titleSelect").val() == "0" || jQuery.trim($("#firstNameLead").val()) == "" || jQuery.trim($("#lastNameLead").val()) == "" || jQuery.trim($("#address1").val()) == "" || jQuery.trim($("#town").val()) == "" || $("#country").val() == "0" || jQuery.trim($("#telephone").val()) == "" || $("#countryDealer").val() == "0" || $("#dealer").val() == "0" || $("#currentCarMake").val() == "0") {

        $("#requiredLeadMessage").html('<span style="border: 1px solid #000;background-color:#cccccc;height:25px;width:100%;display:block;text-align:center;padding-top:10px;">Please enter all of the required fields</span>');
        $("#cont").animate({ scrollTop: 400 }, 100);

        if (!isValidEmailAddress(email)) {
            $("#emailLeadLabel").addClass("invalid");
        }
        else {
            $("#emailLeadLabel").removeClass("invalid");
        }

        if ($("#titleSelect").val() == "0") {
            $("#titleLeadLabel").addClass("invalid");
        }
        else {
            $("#titleLeadLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#firstNameLead").val()) == "") {
            $("#firstNameLeadLabel").addClass("invalid");
        }
        else {
            $("#firstNameLeadLabel").removeClass("invalid");
        }

        if (jQuery.trim($("#lastNameLead").val()) == "") {
            $("#lastNameLeadLabel").addClass("invalid");
        }
        else {
            $("#lastNameLeadLabel").removeClass("invalid");
        }

        if (jQuery.trim($("#address1").val()) == "") {
            $("#address1LeadLabel").addClass("invalid");
        }
        else {
            $("#address1LeadLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#town").val()) == "") {
            $("#townCityLeadLabel").addClass("invalid");
        }
        else {
            $("#townCityLeadLabel").removeClass("invalid");
        }
        if ($("#country").val() == "0") {
            $("#countryLeadLabel").addClass("invalid");
        }
        else {
            $("#countryLeadLabel").removeClass("invalid");
        }
        if ($("#countryDealer").val() == "0") {
            $("#countryDealerLeadLabel").addClass("invalid");
        }
        else {
            $("#countryDealerLeadLabel").removeClass("invalid");
        }
        if ($("#dealer").val() == "0") {
            $("#dealerLeadLabel").addClass("invalid");
        }
        else {
            $("#dealerLeadLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#telephone").val()) == "") {
            $("#telephoneLeadLabel").addClass("invalid");
        }
        else {
            $("#telephoneLeadLabel").removeClass("invalid");
        }

        if ($("#currentCarMake").val() == "0") {
            $("#currentCarMakeLabel").addClass("invalid");
        }
        else {
            $("#currentCarMakeLabel").removeClass("invalid");
        }

        $("#submit").attr("disabled", "");
    }
    else {
        var model;
        if ($("#currentCarMake").val() == "1") {
            model = $("#astonModel").val();
        }
        else {
            model = $("#model").val();
        }
        PageMethod('CreateDealerLead5', ['campaignId', 66, 'title', $("#titleSelect").val(), 'firstName', $("#firstNameLead").val(), 'lastName', $("#lastNameLead").val(), 'address1', $("#address1").val(), 'address2', $("#address2").val(), 'address3', $("#address3").val(), 'townCity', $("#town").val(), 'countyState', $("#county").val(), 'country', $("#country").val(), 'postCode', $("#postcode").val(), 'dealerId', $("#dealer").val(), 'currentCarMake', $("#currentCarMake").val(), 'currentCarModel', model, 'emailAddress', $("#emailAddressLead").val(), 'telephone', $("#telephone").val(), 'ageRange', $("#age").val(), 'profession', $("#profession").val(), 'interestRapide', $("#rapideInterest").is(':checked'), 'interestDbs', $("#dbsInterest").is(':checked'), 'interestDb9', $("#db9Interest").is(':checked'), 'interestV12', $("#v12Interest").is(':checked'), 'interestV8', $("#v8Interest").is(':checked'), 'interestCygnet', false, 'yearOfReg', $("#regYear").val(), 'yearOfPurchase', $("#purchaseYear").val(), 'notesForDealer', $("#comments").val(), 'interestPreOwned', false, 'interestNew', true, 'isApproved', true, 'customerTypeId', 4, 'canPost', $("#privacyAcceptPost").is(':checked'), 'canPhone', $("#privacyAcceptPhone").is(':checked'), 'canSMS', $("#privacyAcceptSMS").is(':checked'), 'canEmail', $("#privacyAcceptEmail").is(':checked'), 'drivingExperienceXml', ''], LeadSubmitAjaxSucceeded, AjaxFailed);
    }
}

function SubmitCygnetInterestLead() {

    $("#submit").attr("disabled", "true");

    // Validate the lead entry page
    var email = $("#emailAddressLead").val();
    var isValid = isValidEmailAddress(email);

    if ($("#currentCarMake").val() == "1") {

        if ($("#astonModel").val() == "0") {
            isValid = false;
            $("#astonModelLabel").addClass("invalid");
        }
        else {
            $("#astonModelLabel").removeClass("invalid");
        }
        $("#modelLabel").removeClass("invalid");
    }
    else {
        $("#astonModelLabel").removeClass("invalid");

        if (jQuery.trim($("#model").val()) == "") {
            $("#modelLabel").addClass("invalid");
        }
        else {
            $("#modelLabel").removeClass("invalid");
        }
    }

    if (!isValid || !isValidEmailAddress(email) || $("#titleSelect").val() == "0" || jQuery.trim($("#firstNameLead").val()) == "" || jQuery.trim($("#lastNameLead").val()) == "" || jQuery.trim($("#address1").val()) == "" || jQuery.trim($("#town").val()) == "" || $("#country").val() == "0" || jQuery.trim($("#telephone").val()) == "" || $("#countryDealer").val() == "0" || $("#dealer").val() == "0" || $("#currentCarMake").val() == "0") {

        $("#requiredLeadMessage").html('<span style="border: 1px solid #000;background-color:#cccccc;height:25px;width:100%;display:block;text-align:center;padding-top:10px;">Please enter all of the required fields</span>');
        $("#cont").animate({ scrollTop: 400 }, 100);

        if (!isValidEmailAddress(email)) {
            $("#emailLeadLabel").addClass("invalid");
        }
        else {
            $("#emailLeadLabel").removeClass("invalid");
        }

        if ($("#titleSelect").val() == "0") {
            $("#titleLeadLabel").addClass("invalid");
        }
        else {
            $("#titleLeadLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#firstNameLead").val()) == "") {
            $("#firstNameLeadLabel").addClass("invalid");
        }
        else {
            $("#firstNameLeadLabel").removeClass("invalid");
        }

        if (jQuery.trim($("#lastNameLead").val()) == "") {
            $("#lastNameLeadLabel").addClass("invalid");
        }
        else {
            $("#lastNameLeadLabel").removeClass("invalid");
        }

        if (jQuery.trim($("#address1").val()) == "") {
            $("#address1LeadLabel").addClass("invalid");
        }
        else {
            $("#address1LeadLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#town").val()) == "") {
            $("#townCityLeadLabel").addClass("invalid");
        }
        else {
            $("#townCityLeadLabel").removeClass("invalid");
        }
        if ($("#country").val() == "0") {
            $("#countryLeadLabel").addClass("invalid");
        }
        else {
            $("#countryLeadLabel").removeClass("invalid");
        }
        if ($("#countryDealer").val() == "0") {
            $("#countryDealerLeadLabel").addClass("invalid");
        }
        else {
            $("#countryDealerLeadLabel").removeClass("invalid");
        }
        if ($("#dealer").val() == "0") {
            $("#dealerLeadLabel").addClass("invalid");
        }
        else {
            $("#dealerLeadLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#telephone").val()) == "") {
            $("#telephoneLeadLabel").addClass("invalid");
        }
        else {
            $("#telephoneLeadLabel").removeClass("invalid");
        }

        if ($("#currentCarMake").val() == "0") {
            $("#currentCarMakeLabel").addClass("invalid");
        }
        else {
            $("#currentCarMakeLabel").removeClass("invalid");
        }

        $("#submit").attr("disabled", "");
    }
    else {
        var model;
        if ($("#currentCarMake").val() == "1") {
            model = $("#astonModel").val();
        }
        else {
            model = $("#model").val();
        }
        PageMethod('CreateDealerLead5', ['campaignId', 66, 'title', $("#titleSelect").val(), 'firstName', $("#firstNameLead").val(), 'lastName', $("#lastNameLead").val(), 'address1', $("#address1").val(), 'address2', $("#address2").val(), 'address3', $("#address3").val(), 'townCity', $("#town").val(), 'countyState', $("#county").val(), 'country', $("#country").val(), 'postCode', $("#postcode").val(), 'dealerId', $("#dealer").val(), 'currentCarMake', $("#currentCarMake").val(), 'currentCarModel', model, 'emailAddress', $("#emailAddressLead").val(), 'telephone', $("#telephone").val(), 'ageRange', $("#age").val(), 'profession', $("#profession").val(), 'interestRapide', false, 'interestDbs', false, 'interestDb9', false, 'interestV12', false, 'interestV8', false, 'interestCygnet', true, 'yearOfReg', $("#regYear").val(), 'yearOfPurchase', $("#purchaseYear").val(), 'notesForDealer', $("#comments").val(), 'interestPreOwned', false, 'interestNew', true, 'isApproved', false, 'customerTypeId', 4, 'canPost', $("#privacyAcceptPost").is(':checked'), 'canPhone', $("#privacyAcceptPhone").is(':checked'), 'canSMS', $("#privacyAcceptSMS").is(':checked'), 'canEmail', $("#privacyAcceptEmail").is(':checked'), 'drivingExperienceXml', ''], LeadSubmitAjaxSucceeded, AjaxFailed);
    }
}

function LeadSubmitAjaxSucceeded(result) {
    if (result.d == true) {
        $("#LeadForm").hide('slow');
        $("#SubmitLeadSuccess").show('slow');
    }
}

function DealerCountrySelected() {
    if ($("#countryDealer").val() == "0") {
        var country = $('#country :selected').text();
        if (country == "United Arab Emirates" || country == "Bahrain" || country == "Kuwait" || country == "Oman" || country == "Qatar" || country == "Saudi Arabia" || country == "Yemen" || country == "Lebanon" || country == "Iraq" || country == "Israel" || country == "Jordan" || country == "Syria" || country == "Iran") {
            country = "Middle East";
        }
        $("#countryDealer").val(country);
        if ($("#countryDealer").val() != "0") {
            CountrySelected();
        }
    }
}

function isValidEmailAddress(emailAddress) {
    emailAddress = jQuery.trim(emailAddress);
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function MakeSelected() {
    if ($('#currentCarMake :selected').text() == "Aston Martin") {
        $('#astonModelLabel').show();
        $('#modelLabel').hide();
        $('#AstonModelRow2').show();
        $('#OtherModelRow2').hide();
        $("#model").val('');
    }
    else if ($('#currentCarMake :selected').text() == "-- Please select --") {
        $('#astonModelLabel').hide();
        $('#modelLabel').hide();
        $('#AstonModelRow2').hide();
        $('#OtherModelRow2').hide();
        $("#astonModel").val('0');
        $("#model").val('');
    }
    else {
        $('#astonModelLabel').hide();
        $('#modelLabel').show();
        $('#AstonModelRow2').hide();
        $('#OtherModelRow2').show();
        $("#astonModel").val('0');
    }
}

function DealerChanged() {
    if ($("#dealer").val() != "0") {
        PageMethod('GetDealerForId', ['dealerId', $("#dealer").val()], DealerChangedAjaxSucceeded, AjaxFailed);
    }
    else {
        $("#DealerDetailsText").val('');
    }
}

function DealerChangedAjaxSucceeded(result) {
    $("#DealerDetailsText").val(result.d.Name + '\n' + result.d.Telephone);
}

function setVehicleOfInterest() {
    var sPath = window.location.pathname;

    if (sPath.indexOf('rapide', 0) > -1) {
        $("#rapideInterest").attr('checked', true);
    }
    else {
        $("#rapideInterest").attr('checked', false);
    }
    if (sPath.indexOf('dbs', 0) > -1) {
        $("#dbsInterest").attr('checked', true);
    }
    else {
        $("#dbsInterest").attr('checked', false);
    }
    if (sPath.indexOf('db9', 0) > -1) {
        $("#db9Interest").attr('checked', true);
    }
    else {
        $("#db9Interest").attr('checked', false);
    }
    if (sPath.indexOf('v12vantage', 0) > -1) {
        $("#v12Interest").attr('checked', true);
    }
    else {
        $("#v12Interest").attr('checked', false);
    }
    if (sPath.indexOf('v8vantage', 0) > -1) {
        $("#v8Interest").attr('checked', true);
    }
    else {
        $("#v8Interest").attr('checked', false);
    }
    $("#cygnetInterest").attr('checked', false);
}