﻿//0 means disabled; 1 means enabled;
var popupStatus = 0, popupStatus2 = 0,
    spacer = null, curObj = null;

var isChineese = false;
var isJapanese = false;

//loading popup with jQuery magic!
function loadPopup() {
    //loads popup only if it is disabled
    if (popupStatus == 0) {
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("fast");
        $("#popupContact").fadeIn("fast");
        popupStatus = 1;
    }
}

//disabling popup with jQuery magic!
function disablePopup() {
    //disables popup only if it is enabled
    if (popupStatus == 1) {
        $("#backgroundPopup").fadeOut("fast");
        $("#popupContact").fadeOut("fast");
        ResetForm();
        $("#rapideForm").removeClass("hidden");
        $("#rapideSubscribeSuccess").addClass("hidden");
        popupStatus = 0;
    }
}

//centering popup
function centerPopup() {
    //request data for centering
    var windowWidth = document.documentElement.clientWidth,
    windowHeight = document.documentElement.clientHeight,
    popupHeight = $("#popupContact").height(),
     popupWidth = $("#popupContact").width();

    $("#popupContact").css({
        "position": "absolute",
        "top": windowHeight / 2 - popupHeight / 2 + $("#cont").scrollTop(),
        "left": windowWidth / 2 - popupWidth / 2
    });
    //only need force for IE6
    $("#backgroundPopup").css({
        "height": windowHeight
    });
}

function disablePopup2() {
    if (popupStatus2 == 1) {
        $("#backgroundPopup").fadeOut("fast");
        $("#popupContact2").fadeOut("fast");
        ResetLeadForm();
        $("#rapideLeadForm").removeClass("hidden");
        $("#rapideLeadSuccess").addClass("hidden");
        popupStatus2 = 0;
    }
}

function centerPopup2() {
    //request data for centering
    var windowWidth = document.documentElement.clientWidth,
    windowHeight = document.documentElement.clientHeight,
    popupHeight = $("#popupContact2").height(),
    popupWidth = $("#popupContact2").width();

    $("#popupContact2").css({
        "position": "absolute",
        "top": (windowHeight / 2 - popupHeight / 2) + $("#cont").scrollTop(),
        "left": windowWidth / 2 - popupWidth / 2
    });
    //only need force for IE6
    $("#backgroundPopup").css({
        "height": windowHeight
    });

}

$(document).ready(function() {

    $("#email").blur(function() {
        var email = $("#email").val(); if (email != 0) {
            if (isValidEmailAddress(email)) {
                $("#validEmail").css({
                    "background-image": "url('content/astonmartin/images/validYes.png')"
                }
            ); $("#emailLabel").removeClass("invalid");
            }
            else {
                $("#validEmail").css({
                    "background-image": "url('content/astonmartin/images/validNo.png')"
                }
            ); $("#emailLabel").addClass("invalid");
            }
        }
        else {
            $("#validEmail").css({
                "background-image": "none"
            }
         );
        }
    }
   );

    $("#button").click(function() {

        PageMethod('GetTitles', [], NewsLetterTitlesAjaxSucceeded, AjaxFailed);
        centerPopup();
        loadPopup();
        return false;
    });

    $("#buttoncn").click(function() {

        PageMethod('GetMandarinTitles', [], NewsLetterTitlesCnAjaxSucceeded, AjaxFailed);
        centerPopup();
        loadPopup();
        return false;
    });
	
	$("#buttonjp").click(function() {

        PageMethod('GetTitles', [], NewsLetterTitlesJnAjaxSucceeded, AjaxFailed);
        centerPopup();
        loadPopup();
        return false;
    });

    $("#popupContactClose").click(function() {

        disablePopup();
    });

    $("#backgroundPopup").click(function() {
        disablePopup();
        disablePopup2();
    });

    $(document).keyup(function(e) {
        if (e.keyCode == 27) {
            if (popupStatus == 1) {
                disablePopup();
            }
            else if (popupStatus2 == 1) {
                disablePopup2();
            }
        }
    });

    $("#emailAddressLead").blur(function() {
        var email = $("#emailAddressLead").val(); if (email != 0) {
            if (isValidEmailAddress(email)) {
                $("#validEmailLead").css({
                    "background-image": "url('content/astonmartin/images/validYes.png')"
                }
            ); //$("#emailLabel").removeClass("invalid"); 
            }
            else {
                $("#validEmailLead").css({
                    "background-image": "url('content/astonmartin/images/validNo.png')"
                }
            ); //$("#emailLabel").addClass("invalid"); 
            }
        }
        else {
            $("#validEmailLead").css({
                "background-image": "none"
            }
         );
        }
    }
   );
	
    // Lead popup functions
    $("#button3").click(function() {

        // Build the URL to query
        //var url = "http://ipinfodb.com/ip_query.php?output=json&callback=?";

		isChineese = false;
		isJapanese = false;

        // Utilize the JSONP API
        //$.getJSON(url, function(data) {
        //    if (data['Status'] == 'OK') {
        //        if (data['CountryCode'] == 'US' || data['CountryCode'] == 'CA') {
        //            window.location = 'http://www.myastonmartindealer.com';
        //        }
        //        else {
                    PageMethod('GetManufacturers', [], ManuAjaxSucceeded, AjaxFailed);
                    PageMethod('GetCountries', [], CountriesAjaxSucceeded, AjaxFailed);
                    PageMethod('GetAddressCountries', [], AddressCountriesAjaxSucceeded, AjaxFailed);
                    PageMethod('GetTitles', [], TitlesAjaxSucceeded, AjaxFailed);
                    centerPopup2();
                    loadPopup2();	            
        //        }
        //    }	    
        //});
	return false;
    });

	$("#buttonCygnet").click(function() {

		isChineese = false;
		isJapanese = false;

		PageMethod('GetManufacturers', [], ManuAjaxSucceeded, AjaxFailed);
		PageMethod('GetDealerCountries', [], CountriesAjaxSucceeded, AjaxFailed);
		PageMethod('GetAddressCountries', [], AddressCountriesAjaxSucceeded, AjaxFailed);
		PageMethod('GetTitles', [], TitlesAjaxSucceeded, AjaxFailed);
		centerPopup2();
		loadPopup2();	            

		return false;
    });
	
 	$("#button3jp").click(function() {

        // Build the URL to query
        //var url = "http://ipinfodb.com/ip_query.php?output=json&callback=?";

		isJapanese = true;

        // Utilize the JSONP API
        //$.getJSON(url, function(data) {
        //    if (data['Status'] == 'OK') {
        //        if (data['CountryCode'] == 'US' || data['CountryCode'] == 'CA') {
        //            window.location = 'http://www.myastonmartindealer.com';
        //        }
        //        else {
                    PageMethod('GetManufacturers', [], ManuJpAjaxSucceeded, AjaxFailed);
                    PageMethod('GetCountries', [], CountriesJpAjaxSucceeded, AjaxFailed);
                    PageMethod('GetAddressCountries', [], AddressJpCountriesAjaxSucceeded, AjaxFailed);
                    PageMethod('GetTitles', [], TitlesJpAjaxSucceeded, AjaxFailed);
                    centerPopup2();
                    loadPopup2();	            
        //       }
        //    }	    
        //});
	return false;
    });

    $("#button3cn").click(function() {

        // Build the URL to query
        //var url = "http://ipinfodb.com/ip_query.php?output=json&callback=?";

		isChineese = true;

        // Utilize the JSONP API
        //$.getJSON(url, function(data) {
        //    if (data['Status'] == 'OK') {
        //        if (data['CountryCode'] == 'US' || data['CountryCode'] == 'CA') {
        //            window.location = 'http://www.myastonmartindealer.com';
        //        }
        //        else {
                    PageMethod('GetManufacturers', [], ManuCnAjaxSucceeded, AjaxFailed);
                    PageMethod('GetCountries', [], CountriesCnAjaxSucceeded, AjaxFailed);
                    PageMethod('GetAddressCountries', [], AddressCnCountriesAjaxSucceeded, AjaxFailed);
                    PageMethod('GetMandarinTitles', [], TitlesCnAjaxSucceeded, AjaxFailed);
                    centerPopup2();
                    loadPopup2();	            
        //        }
        //    }	    
        //});
	return false;
    });

    $("#popupContact2Close").click(function() {
        disablePopup2();
    });

});

function loadPopup2() {
    if (popupStatus2 == 0) {
        $("#backgroundPopup").css({
            "opacity": "0.7"
        });
        $("#backgroundPopup").fadeIn("fast");
        $("#popupContact2").fadeIn("fast");
        popupStatus2 = 1;

	setVehicleOfInterest();
    }
}

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);
	}
}

function AjaxFailed(result) {
	alert("There was an error. Please try again later.");
}
function AjaxSucceeded(result) {
    if (result.d == true) {
        $("#rapideForm").addClass("hidden");
        $("#rapideSubscribeSuccess").removeClass("hidden");
    }
}

function FriendAjaxSucceeded(result) {
	$("#rapideForm").addClass("hidden");
	$("#rapideSubscribeSuccess").removeClass("hidden");
}

function SubmitSubscriber() {
    $("#submitEmailSub").attr("disabled", "true");
    var email = $("#email").val();
    if (!isValidEmailAddress(email) || $("#newsTitleSelect").val() == "0" || jQuery.trim($("#firstName").val()) == "" || jQuery.trim($("#lastName").val()) == "" || jQuery.trim($("#email").val()) == "") {
        $("#requiredMessage").addClass("invalid");
        if (!isValidEmailAddress(email)) {
            $("#emailLabel").addClass("invalid");
        }
        else {
            $("#emailLabel").removeClass("invalid");
        }
        if ($("#newsTitleSelect").val() == "0") {
            $("#titleLabel").addClass("invalid");
        }
        else {
            $("#titleLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#firstName").val()) == "") {
            $("#firstnameLabel").addClass("invalid");
        }
        else {
            $("#firstnameLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#lastName").val()) == "") {
            $("#lastnameLabel").addClass("invalid");
        }
        else {
            $("#lastnameLabel").removeClass("invalid");
        }
        $("#submitEmailSub").attr("disabled", "");
    }
    else {
        // Register the subscriber in the db and email them
        PageMethod('RegisterSubscriber', ['title', $("#newsTitleSelect").val(), 'firstName', $("#firstName").val(), 'lastName', $("#lastName").val(), 'email', $("#email").val()], AjaxSucceeded, AjaxFailed);
    }
}
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 ResetForm() {
    $("#submitEmailSub").attr("disabled", "");
    $("#newsTitleSelect").val('0');
    $("#firstName").val('');
    $("#lastName").val('');
    $("#email").val('');
    $("#requiredMessage").removeClass("invalid");
    $("#titleLabel").removeClass("invalid");
    $("#firstnameLabel").removeClass("invalid");
    $("#lastnameLabel").removeClass("invalid");
    $("#emailLabel").removeClass("invalid");
    $("#validEmail").css({
        "background-image": "none"
    });
}

function PageMethod(fn, paramArray, successFn, errorFn) {
    var pagePath = "http://www.astonmartin.com/newsletter/newsletterws.asmx",
        paramList = '';
    //window.location.pathname;   
    //Create list of parameters in the form:   
    //{"paramName1":"paramValue1","paramName2":"paramValue2"}   
    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 ManuJpAjaxSucceeded(result) {
    var options = '<option value="0">-- お選び下さい --</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 ManuCnAjaxSucceeded(result) {
    var options = '<option value="0">-- 清选择 --</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 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 AddressJpCountriesAjaxSucceeded(result) {
    var options = '<option value="0">-- お選び下さい --</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 AddressCnCountriesAjaxSucceeded(result) {
    var options = '<option value="0">-- 清选择 --</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);
	$("#country").val('China');
}

function AddressJpCountriesAjaxSucceeded(result) {
    var options = '<option value="0">-- お選び下さい --</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);
	$("#country").val('Japan');
}

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 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 CountriesJpAjaxSucceeded(result) {
    var options = '<option value="0">-- お選び下さい --</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);
    $("#countryDealer").val('Japan');
    CountrySelected();
}

function CountriesCnAjaxSucceeded(result) {
    var options = '<option value="0">-- 清选择 --</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);
    $("#countryDealer").val('China');
    CountrySelected();
}

function CountrySelected() {
    if ($("#countryDealer").val() != "0") {
        $("#dealerDetailsText").val('');
        PageMethod('GetDealersForCountry', ['country', $("#countryDealer").val()], DealerGetAjaxSucceeded, AjaxFailed);
    }
    else {
        $("#dealerDetailsText").val('');
        $("#dealer").html('');
    }
}

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 DealerGetAjaxSucceeded(result) {
    var options;
    if(isChineese) {
    	options = '<option value="0">-- 清选择 --</option>';
    }
	else if(isJapanese) {
		options = '<option value="0">-- お選び下さい --</option>';
	}
    else {
    	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 DealerAjaxSucceeded(result) {
    $("#dealerDetailsText").val(result.d.Name + '\n' + result.d.Telephone);
}

function DealerSelected() {
    if ($("#dealer").val() != "0") {
        PageMethod('GetDealerForId', ['dealerId', $("#dealer").val()], DealerAjaxSucceeded, AjaxFailed);
    }
    else {
        $("#dealerDetailsText").val('');
    }
}

function MakeSelected() {
	if($("#currentCarMake").val() == "1") {
		$("#AstonDetails").show('fast');
		$("#OtherMakeDetails").hide('fast');
	}
	else {
		$("#OtherMakeDetails").show('fast');
		$("#AstonDetails").hide('fast');
	}	
}

function NewsLetterTitlesJnAjaxSucceeded(result) {
    var options = '<option value="0">-- お選び下さい --</option>';
    for (var i = 0; i < result.d.length; i++) {
        options += '<option value="' + result.d[i].English + '">' + result.d[i].English + '</option>';
    }
    $("#newsTitleSelect").html(options);
}

function NewsLetterTitlesCnAjaxSucceeded(result) {
    var options = '<option value="0">-- 清选择 --</option>';
    for (var i = 0; i < result.d.length; i++) {
        options += '<option value="' + result.d[i].English + '">' + result.d[i].English + '</option>';
    }
    $("#newsTitleSelect").html(options);
}

function NewsLetterTitlesAjaxSucceeded(result) {
    var options = '<option value="0">-- Please select --</option>';
    for (var i = 0; i < result.d.length; i++) {
        options += '<option value="' + result.d[i].English + '">' + result.d[i].English + '</option>';
    }
    $("#newsTitleSelect").html(options);
}

function TitlesCnAjaxSucceeded(result) {
    var options = '<option value="0">-- 清选择 --</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 TitlesJpAjaxSucceeded(result) {
    var options = '<option value="0">-- お選び下さい --</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 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 SubmitLead() {
    $("#submit").attr("disabled", "true");
    // Validate the lead entry page
    var email = $("#emailAddressLead").val();

    if (!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" || !$("#privacyAccept").is(':checked')) {
        $("#requiredLeadMessage").addClass("invalid");
        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 (!$("#privacyAccept").is(':checked')) {
            $("#privacyAcceptLabel").addClass("invalid");
            $("#privacyLink").addClass("invalid");
        }
        else {
            $("#privacyAcceptLabel").removeClass("invalid");
            $("#privacyLink").removeClass("invalid");
        }
        $("#submit").attr("disabled", "");
    }
    else {
        PageMethod('CreateDealerLead2', ['title', $("#titleSelect").val(), 'firstName', $("#firstNameLead").val(), 'lastName', $("#lastNameLead").val(), 'address1', $("#address1").val(), 'address2', $("#address2").val(), 'address3', $("#address3").val(), 'townCity', $("#town").val(), 'countyState', $("#state").val(), 'country', $("#country").val(), 'postCode', $("#postcode").val(), 'dealerId', $("#dealer").val(), 'currentCarMake', $("#currentCarMake").val(), 'currentCarModel', $("#model").val(), 'emailAddress', $("#emailAddressLead").val(), 'telephone', $("#telephone").val(), 'ageRange', $("#age").val(), 'profession', $("#profession").val(), 'acceptTermsAndConditions', $("#marketingOptOut").is(':checked'), 'interestRapide', $("#rapideInterest").is(':checked'), 'interestDbs', $("#dbsInterest").is(':checked'), 'interestDb9', $("#db9Interest").is(':checked'), 'interestV12', $("#v12Interest").is(':checked'), 'interestV8', $("#v8Interest").is(':checked') ], LeadSubmitAjaxSucceeded, AjaxFailed);
    }
}

function ResetLeadForm() {
    $("#submit").attr("disabled", "");
    $("#requiredLeadMessage").removeClass("invalid");
    $("#emailLeadLabel").removeClass("invalid");
    $("#titleLeadLabel").removeClass("invalid");
    $("#firstNameLeadLabel").removeClass("invalid");
    $("#lastNameLeadLabel").removeClass("invalid");
    $("#address1LeadLabel").removeClass("invalid");
    $("#townCityLeadLabel").removeClass("invalid");
    $("#countryLeadLabel").removeClass("invalid");
    $("#countryDealerLeadLabel").removeClass("invalid");
    $("#dealerLeadLabel").removeClass("invalid");
    $("#telephoneLeadLabel").removeClass("invalid");
    $("#privacyAcceptLabel").removeClass("invalid");
    $("#privacyLink").removeClass("invalid");
	$("#yearOfPurchaseLabel").removeClass("invalid");
	$("#yearOfRegLabel").removeClass("invalid");
	$("#currentCarMakeLabel").removeClass("invalid");
	$("#modelLabel").removeClass("invalid");
	$("#astonModelLabel").removeClass("invalid");	
    $("#titleSelect").val('0');
    $("#firstNameLead").val('');
    $("#lastNameLead").val('');
    $("#address1").val('');
    $("#address2").val('');
    $("#address3").val('');
    $("#town").val('');
    $("#state").val('');
    $("#country").val('0');
    $("#postcode").val('');
    $("#countryDealer").val('0');
    $("#dealer").html('');
    $("#dealerDetailsText").val('');
    $("#currentCarMake").val('0');
    $("#profession").val('0')
    $("#age").val('0')
    $("#model").val('');
    $("#emailAddressLead").val('');
    $("#telephone").val('');
    $("#marketingOptOut").attr('checked', false);
    $("#privacyAccept").attr('checked', false);
	$("#commentsTxt").val('');
	$("#regYear").val('0')
	$("#purchaseYear").val('0')
	$("#astonModel").val('0') 
    setVehicleOfInterest();
    $("#validEmailLead").css({
        "background-image": "none"
    });
}

function LeadSubmitAjaxSucceeded(result) {
    if (result.d == true) {
        $("#rapideLeadForm").addClass("hidden");
        $("#rapideLeadSuccess").removeClass("hidden");
    }
}

function openIt(obj) {
    if (spacer) return;
    spacer = document.createElement("select");
    spacer.style.width = obj.offsetWidth;
    spacer.style.height = obj.offsetHeight;
    spacer.style.display = "none";
    obj.parentNode.insertBefore(spacer, obj);

    obj.style.right = "33px";
    obj.style.position = "absolute";
    obj.style.width = obj.scrollWidth + 23;
    obj.focus();
    spacer.style.display = "inline";
    curObj = obj;
}

function closeIt() {
    if (spacer) {
        spacer.parentNode.removeChild(spacer);
        spacer = null;
    }
    if (curObj) {
        curObj.style.width = "155px";
        curObj.style.position = "static";
    }
}

function hideServices() {
	$("#V8VantageService").slideUp('slow');
	$("#V12VantageService").slideUp('slow');
	$("#DB9Service").slideUp('slow');
	$("#DBSService").slideUp('slow');
	$("#VanquishService").slideUp('slow');
	$("#DB7VService").slideUp('slow');
	$("#DB7I6Service").slideUp('slow');

}

function getQuerystring(key, default_)
{
  if (default_==null) default_=""; 
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

function SubmitFriendSubscriber() {
	
	$("#submitEmailSub").attr("disabled", "true");
    var email = $("#email").val();
	var referrerId = getQuerystring("id","");
	
	if (!isValidEmailAddress(email)) {
		$("#emailLabel").addClass("invalid");
    }
    else {
		$("#emailLabel").removeClass("invalid");
    }
	
    if (!isValidEmailAddress(email) || $("#newsTitleSelect").val() == "0" || jQuery.trim($("#firstName").val()) == "" || jQuery.trim($("#lastName").val()) == "" || jQuery.trim($("#email").val()) == "") {
        $("#requiredMessage").addClass("invalid");
        if ($("#newsTitleSelect").val() == "0") {
            $("#titleLabel").addClass("invalid");
        }
        else {
            $("#titleLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#firstName").val()) == "") {
            $("#firstnameLabel").addClass("invalid");
        }
        else {
            $("#firstnameLabel").removeClass("invalid");
        }
        if (jQuery.trim($("#lastName").val()) == "") {
            $("#lastnameLabel").addClass("invalid");
        }
        else {
            $("#lastnameLabel").removeClass("invalid");
        }
        $("#submitEmailSub").attr("disabled", "");
    }
    else {
        // Register the subscriber in the db and email them
        PageMethod('RegisterFriendSubscriber', ['referrerId', referrerId,'message', $("#friendMessage").val(),'friendTitle', $("#newsTitleSelect").val(), 'friendFirstName', $("#firstName").val(), 'friendLastName', $("#lastName").val(), 'friendEmail', $("#email").val()], FriendAjaxSucceeded, AjaxFailed);
    }	
}

function ResetFriendForm() {
	$("#titleLabel").removeClass("invalid");
	$("#emailLabel").removeClass("invalid");
	$("#firstnameLabel").removeClass("invalid");
	$("#lastnameLabel").removeClass("invalid");
	$("#friendMessage").val('');
	$("#newsTitleSelect").val('0');	 
	$("#firstName").val(''); 
	$("#lastName").val(''); 
	$("#email").val('');
}

function ServiceSelected() {

    if ($("#vehicle").val() == "0") {
		hideServices();
	}
	
	if ($("#vehicle").val() == "1") {
		hideServices();
		$("#DB7I6Service").slideDown('slow');
	}
	
	if ($("#vehicle").val() == "2") {
		hideServices();
		$("#DB7VService").slideDown('slow');
	}
	
	if ($("#vehicle").val() == "3") {
		hideServices();
		$("#DB9Service").slideDown('slow');
	}
	
	if ($("#vehicle").val() == "4") {
		hideServices();
		$("#DBSService").slideDown('slow');
	}
	
	if ($("#vehicle").val() == "5") {
		hideServices();
		$("#V12VantageService").slideDown('slow');
	}
	
	if ($("#vehicle").val() == "6") {
		hideServices();
		$("#V8VantageService").slideDown('slow');
	}
	
	if ($("#vehicle").val() == "7") {
		hideServices();
		$("#VanquishService").slideDown('slow');
	}	
}

function SubmitGenevaLead() {
    $("#submit").attr("disabled", "true");
    // Validate the lead entry page
    var email = $("#emailAddressLead").val();
	var yearOfReg = $("#regYear").val();
	var yearOfPurchase = $("#purchaseYear").val();
	var isValid = true;
	
	if($("#currentCarMake").val() == "1") {
		if(yearOfReg == "0") {
			isValid = false;
			$("#yearOfRegLabel").addClass("invalid");
		}
		else {
			$("#yearOfRegLabel").removeClass("invalid");
		}
		if(yearOfPurchase == "0") {
			isValid = false;
			$("#yearOfPurchaseLabel").addClass("invalid");
		}
		else {
			$("yearOfPurchaseLabel").removeClass("invalid");
		}
		
		if($("#astonModel").val() == "0") {
			isValid = false;
			$("#astonModelLabel").addClass("invalid");
		}
		else {
			$("#astonModelLabel").removeClass("invalid");
		}
	}
	else {
		if(jQuery.trim($("#model").val()) == "") {
			isValid = false;
			$("#modelLabel").addClass("invalid");
		}
		else {
			$("#modelLabel").removeClass("invalid");
		}
	}
	
    if ($("#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" || !$("#privacyAccept").is(':checked') || $("#currentCarMake").val() == "0") {
        $("#requiredLeadMessage").addClass("invalid");
        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 (!$("#privacyAccept").is(':checked')) {
            $("#privacyAcceptLabel").addClass("invalid");
            $("#privacyLink").addClass("invalid");
        }
        else {
            $("#privacyAcceptLabel").removeClass("invalid");
            $("#privacyLink").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('CreateDealerLead4', ['campaignId', 70,'title', $("#titleSelect").val(), 'firstName', $("#firstNameLead").val(), 'lastName', $("#lastNameLead").val(), 'address1', $("#address1").val(), 'address2', $("#address2").val(), 'address3', $("#address3").val(), 'townCity', $("#town").val(), 'countyState', $("#state").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(), 'acceptTermsAndConditions', $("#marketingOptOut").is(':checked'), 'interestRapide', $("#rapideInterest").is(':checked'), 'interestDbs', $("#dbsInterest").is(':checked'), 'interestDb9', $("#db9Interest").is(':checked'), 'interestV12', $("#v12Interest").is(':checked'), 'interestV8', $("#v8Interest").is(':checked'), 'interestCygnet', $("#cygnetInterest").is(':checked'), 'yearOfReg', yearOfReg, 'yearOfPurchase', yearOfPurchase, 'notesForDealer',  $("#commentsTxt").val()], LeadSubmitAjaxSucceeded, AjaxFailed);
    }
}

function SubmitCygnetLead() {

	$("#submit").attr("disabled", "true");
    // Validate the lead entry page
    var email = $("#emailAddressLead").val();
	var yearOfReg = $("#regYear").val();
	var yearOfPurchase = $("#purchaseYear").val();
	var isValid = true;
			
	if($("#currentCarMake").val() == "1") {
		if(yearOfReg == "0") {
			isValid = false;
			$("#yearOfRegLabel").addClass("invalid");
		}
		else {
			$("#yearOfRegLabel").removeClass("invalid");
		}
		if(yearOfPurchase == "0") {
			isValid = false;
			$("#yearOfPurchaseLabel").addClass("invalid");
		}
		else {
			$("yearOfPurchaseLabel").removeClass("invalid");
		}
		
		if($("#astonModel").val() == "0") {
			isValid = false;
			$("#astonModelLabel").addClass("invalid");
		}
		else {
			$("#astonModelLabel").removeClass("invalid");
		}
	}
	else {
		if(jQuery.trim($("#model").val()) == "") {
			isValid = false;
			$("#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" || !$("#privacyAccept").is(':checked') || $("#currentCarMake").val() == "0") {
        $("#requiredLeadMessage").addClass("invalid");
        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 (!$("#privacyAccept").is(':checked')) {
            $("#privacyAcceptLabel").addClass("invalid");
            $("#privacyLink").addClass("invalid");
        }
        else {
            $("#privacyAcceptLabel").removeClass("invalid");
            $("#privacyLink").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('CreateDealerLead4', ['campaignId', 66,'title', $("#titleSelect").val(), 'firstName', $("#firstNameLead").val(), 'lastName', $("#lastNameLead").val(), 'address1', $("#address1").val(), 'address2', $("#address2").val(), 'address3', $("#address3").val(), 'townCity', $("#town").val(), 'countyState', $("#state").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(), 'acceptTermsAndConditions', $("#marketingOptOut").is(':checked'), 'interestRapide', false, 'interestDbs', false, 'interestDb9', false, 'interestV12', false, 'interestV8', false, 'interestCygnet', true, 'yearOfReg', yearOfReg, 'yearOfPurchase', yearOfPurchase, 'notesForDealer', $("#commentsTxt").val() ], LeadSubmitAjaxSucceeded, AjaxFailed);
    }
}
