﻿
function DeleteMyAllVehicles() {
    AjaxDeleteMyAllVehicles(
    function(){window.location.href=BuildJSUrl() + 'myshowroom/saved-cars';},displayGenericError);
}
function DeleteMyCompare(id) {
    if (!confirm("Are you sure you want to delete this comparison")) return;
    AjaxDeleteMyCompare(id,
    function() { window.location.href = BuildJSUrl() + 'myshowroom/saved-comparisons'; }
    ,displayGenericError);
}
function DeleteMyVehicle(id) {
    if (!confirm("Are you sure you want to delete this vehicle")) return;
    AjaxDeleteMyVehicle(id,
    function() { window.location.href = BuildJSUrl() + 'myshowroom/saved-cars'; }, displayGenericError);
}
function DeleteMySearch(id) {
    if (!confirm("Are you sure you want to delete this saved search")) return;
    AjaxDeleteMySearch(id,
    function() { window.location.href = BuildJSUrl() + 'myshowroom/saved-searches'; }, displayGenericError)
}
function printCarDetails(id) {

  //  var mileage = GetDotNetDomCtrl('annualMileageSelect').value;
  //  AjaxDisplayPrintedDetails(id)
     window.open(BuildJSUrl() + 'car-brochure/' +id );
}

function SaveCar(vid) {

    SaveMyVehicle(vid, window.location.href, SaveCar_CBSuccess, displayGenericError);
}

function UpdateLoginSummary(val1, val2, val3,firstname) {
    //update the 3 numbers
    var anchor = $get("ctl00_ctl00_Membership2_RegisterLoginView");
    var contents = '<div id="wbhold"><p>Hi, ';
    contents += firstname + '</p><a onclick="doUserLogout();" href="javascript:void(0)">logout</a> ';
    contents += '<p><span class="icon car"></span> <a id="LoginStatusParkedCars" href="' + BuildJSUrl() + 'myshowroom/saved-cars">my saved cars (';
    contents += val1 + ')</a></p><p><span class="icon"></span> <a id="A1" href="' + BuildJSUrl() + 'myshowroom/saved-searches">saved searches (';
    contents += val2 + ')</a></p><p><span class="icon recent"></span> <a id="A2" href="' + BuildJSUrl() + 'myshowroom/recently-viewed-cars">recently viewed (';
    contents += val3 + ')</a></p></div>';

    anchor.innerHTML = contents;
}

function SaveCar_CBSuccess(results) {
    if (results.success) {
        DisplayLightBox('carsaved', '485', '162', 'true');
        $get("a_" + results.vid).innerHTML = "saved";
        //return update status in results
        UpdateLoginSummary(results.val1, results.val2, results.val3, results.name);
    }
    else {
        if (results.loggedin) {
            displayGenericError();
        //    $get("a_" + results.vid).innerHTML = ("<img src='" + StaticContentRoot + "images/save_this_car_icon.gif' border='0' align='absmiddle' />save car");
        }
        else {
            window.location.href = results.loginurl;
        }
    }
}

function SaveCompareLoggedInResult(results) {
    if (results.loggedin) { saveComparison(); }
    else {

     window.location.href = results.loginurl;
}
 }

function SaveCompare() {
    IsLoggedInRedirect(window.location.href, "savecompare", GetCompareCarsAsParams(), SaveCompareLoggedInResult, displayGenericError);
}

function SaveSearch() {
    SaveSearchUrl = window.location.href;
    IsLoggedInRedirect(window.location.href, "savesearch", window.location.href, SaveSearchLoggedInResult, displayGenericError);
}

function SaveSearchLoggedInResult(results) {
    if (results.loggedin) {
        DisplayLightBox('savesearchdescriptionlightbox', '600', '300', 'true');
    }
    else {
        window.location.href = results.loginurl;
    }
}

function doSearchSave(description) {
    SaveSearchUrl = window.location.href;
    AjaxSaveSearch(description, SaveSearchUrl, CB_SaveSearchSuccess, displayGenericError);
}

function CB_SaveSearchSuccess(results) {
    UpdateLoginSummary(results.val1, results.val2, results.val3, results.name);
    if (results.success) {
        DisplayLightBox('savedsearch', '485', '162', 'true');
    } else {
        displayGenericError
    }
}

function ProcessActionCookie() {
    var actioncookie = ReadCookie("MYSAVE");
    RemoveCookie("MYSAVE");
    if (IsStringValid(actioncookie)) {
        var items = actioncookie.split("|");
        var type = items[0];
        var data = items[1];
        switch (type) {
            case "car":
                SaveCar(data);
                break;
            case "compare":
                var itemsCompare = data.split(",");
                var car1 = itemsCompare[0] == 0 ? null : itemsCompare[0];
                var car2 = itemsCompare[1] == 0 ? null : itemsCompare[1];
                var car3 = itemsCompare[2] == 0 ? null : itemsCompare[2];
                var car4 = itemsCompare[3] == 0 ? null : itemsCompare[3];
                SaveCompare()
                break;
            case "search":
                SaveSearchUrl = data;
                SaveSearch();
                break;
        }
       // alert(actioncookie);
    }
}

var SaveSearchUrl;

var car1 = null;
var car2 = null;
var car3 = null;
var car4 = null;


var emailAdd = 'Your email address ...';


function callDescriptionLightbox(state, email) {
    if (state) {
        emailAdd = email;
        DisplayLightBox('savesearchdescriptionlightbox', '600', '300', 'true');
    } else {
        emailAdd = 'Your email address ...';
        tb_remove();
    }
}

var showingSaved = false;

var comparisonType = null;

function comparisonSaveLightbox() {
    callComparisonDescriptionLightbox(true);
}

function doComparisonSave(title) {

    AjaxSaveComparison(title,  car1, car2, car3, car4, CB_CompareSuccess, CB_CompareFail);
}


function CB_CompareSuccess(id, desc) {
    var btn = $get('save_compare_button');
    if (btn != null) {
        btn.innerHTML = "comparison saved";
    }
    //update the comparison accordion if necessary

    var now = new Date();

    var div = document.createElement("div");
    div.id = id;
    div.innerHTML = '<div class="ainfo"><p><a href="' + BuildJSUrl() + 'myshowroom/saved-vehicle-comparison?id=' + id + '"><span class="date">' + (now.getDate() < 10 ? '0' : '') + now.getDate() + '/' + now.getMonth() + 1 + '/' + now.getFullYear() + '</span> ' + desc + '</a></p></div>';
    div.innerHTML += '<div class="delete"><a href="Javascript:void(0);" onclick="doComparisonRemove(\'' + id + '\');"><img border="0" alt="Delete comparison" src="' + StaticContentRoot + 'images/delete.gif" /></a></div>';
    div.innerHTML += '<div class="facetclear" />';

    $('#ComparisonItem div.ainfo:first').parent().before(div);

    DisplayLightBox('comparisonsaved', '485', '162', 'true');
}
function CB_CompareFail(results) {
    $get('save_compare_button').innerHTML = "save comparison";
    callComparisonDescriptionLightbox(false);
}

function doComparisonRemove(comparisonId, comparisonTypeDesc) {
    RemoveComparison(comparisonId, comparisonTypeDesc, onRemoveComparisonSuccess, onRemoveComparisonFailure);
}

function onRemoveComparisonSuccess(id, comparisonTypeDesc) {
    //update count
    amendSummaryValue("savedcomparisons", -1);
    amendSummaryValue(comparisonTypeDesc, -1);

    //remove item from accordion
    $('#' + id).remove();
}

function onRemoveComparisonFailure() {
    displayGenericError();
}

function callComparisonDescriptionLightbox(state) {
    if (state) {
        DisplayLightBox('savecomparisondescriptionlightbox', '600', '300', 'true');
    } else {
        tb_remove();
    }
}


//FEEDBACK=====================
function doFeedback() {
    var ease = $('input[name=EaseOfUse]:checked').val();
    var desn = $('input[name=DesignStyling]:checked').val();
    var rang = $('input[name=RangeOfCars]:checked').val();
    var info = $('input[name=DealerInfo]:checked').val();

    var reco = $('select[name=likelytorecommend]').val();

    var sender = $('input[name=SenderName]').val();
    var senderEmail = $('input[name=SenderEmail]').val();
    var postcode = $('input[name=PostCode]').val();
    var inform = $('input[name=StayInformed]:checked').val();
    var improv = $('textarea[name=improvement]').val();

    SaveUserFeedback(ease, desn, rang, info, reco, improv, sender, senderEmail, postcode, inform == undefined ? false : true,
        onSaveUserFeedbackSucceeded,
        onSaveUserFeedbackFailed
    );
}

function onSaveUserFeedbackSucceeded(results) {
    //display lightbox
    tb_remove();
    "DisplayLightBox('feedbackrecieved','485','162','true');"
}

function onSaveUserFeedbackFailed() {
    tb_remove();
    setTimeout("displayGenericError();", timoutVal);
}




function doUserLogout() {
    Logout(onDoUserLogoutComplete);
}

function onDoUserLogoutComplete() {
    RemoveCookie('CARMONYAUTH');
    window.location = GetDomainUrl();
}

function pageRegister() {
    $("[assertionTemp]").remove();  // clear previous errors

    var fail = assertionFails($("#ctl00_ctl00_ContentHolder_middleColumn_txtFirstName"), "Please provide name", function() { return $get("ctl00_ctl00_ContentHolder_middleColumn_txtFirstName").value != ""; });
    fail |= assertionFails($("#ctl00_ctl00_ContentHolder_middleColumn_txtSurname"), "Please provide surname", function() { return $get("ctl00_ctl00_ContentHolder_middleColumn_txtSurname").value != ""; });
    fail |= assertionFails($("#ctl00_ctl00_ContentHolder_middleColumn_Email"), "Please provide email address", function() { return new RegExp("\\w+@\\w+\\.\\w+").test($get("ctl00_ctl00_ContentHolder_middleColumn_Email").value); });
    fail |= assertionFails($("#ctl00_ctl00_ContentHolder_middleColumn_Password"), "Please provide password", function() { return $get("ctl00_ctl00_ContentHolder_middleColumn_Password").value != ""; });
    fail |= assertionFails($("#ctl00_ctl00_ContentHolder_middleColumn_ConfirmPassword"), "Please verify password", function() { return $get("ctl00_ctl00_ContentHolder_middleColumn_Password").value == $get("ctl00_ctl00_ContentHolder_middleColumn_ConfirmPassword").value; });

    if (!fail) $get("ctl00_ctl00_ContentHolder_middleColumn_signupButton").click();
}

// Check an assertion function returns true otherwise set an error message
function assertionFails(adjacent, errorMessage, assertion) {
    if (!assertion()) {
        var div = document.createElement("div");
        div.onmouseover = function() { validatedissapear($(this)) };
        div.innerHTML = "<span class='registerlogin'>" + errorMessage + "</span>";
        div.className = "errormessage";
        div.assertionTemp = true;

        adjacent.after(div)
        return true;
    }
    return false;
}

function amendSummaryValue(summaryId, amendBy) {
    var html = $get(summaryId).innerHTML;
    var val = html.substring(html.lastIndexOf('(') + 1, html.lastIndexOf(')'));
    var newVal = parseInt(val) + parseInt(amendBy);
    html = html.replace('(' + val + ')', '(' + newVal + ')');
    $get(summaryId).innerHTML = html;
    return newVal;
}