﻿var sendToLightbox;  // Used to indicate that the lightbox is to be opened and optionally pass the vehicle ID
var subject;  // The email subject
var searchUrl;  // The url to rerun the search

// Send the div ID parameter to a new lightbox
function sendToAFriend(subject, vehicleId) {
    this.subject = subject;
    sendToLightbox = (vehicleId ? vehicleId : -1);
    DisplayLightBox('dyn/sendtoafriendlightbox?vid=' + vehicleId, '600', '350', 'true');
}

function getUserDetails() {
    getCurrentUserDetails(
        onGetUserDetailsSucceeded,
        onGetUserDetailsFailed
    );
}

function onGetUserDetailsSucceeded(results) {
    if(results!="")
    {
        var output=results.split("|");
        $("input[@name=name]").val(output[0]);
        $("input[@name=myEmailAddress]").val(output[1]);
    }
}

function onGetUserDetailsFailed() {
    //dont really need to do anything
    //the user will just have to fill
    //in their own details!!
}

// The 'send' button has been pressed
function ProcessFriendMessage() {
    if ($("#formSendToAFriend").valid()) {

        var sendername = $("input[@name=name]").val();
        var sendermessage = $("textarea[@name=details]").val();
        
        if (sendToLightbox < 0)
        {
            AjaxProcessFriendMessage(
                subject,
                $("input[@name=myEmailAddress]").val(),
                $("input[@name=emailAddress]").val(),
                sendername,
                encodeURI(sendermessage) + GetValCheck(),
                onSendEmailSucceeded,
                onSendEmailFailed
            );
        }
        else
        {
            AjaxProcessFriendCarMessage(
                subject,
                $("input[@name=myEmailAddress]").val(),
                $("input[@name=emailAddress]").val(),
                sendername,
                encodeURI(sendermessage) + GetValCheck(),
                sendToLightbox, 
                onSendEmailSucceeded,
                onSendEmailFailed
            );
        }
    }
}

function onSendEmailFailed() {
    displayGenericError();
}

function onSendEmailSucceeded(result) {
    if (!result) {
        displayGenericError();
    } else {

    DisplayLightBox('senttoafriend', '485', '162', 'true');
    }
}

var winParams = 'resizable=1,scrollbars=1,toolbar=0,status=0,width=626,height=436';

function openGMailWindow() {
    window.open(BuildJSUrl() + 'Callbacks/GMailCallback.aspx', 'contacts', winParams);
}

function openYahooWindow() {
    window.open(BuildJSUrl() + 'Callbacks/YahooCallback.aspx', 'contacts', winParams);
}

function openMsnWindow() {
    window.open(BuildJSUrl() + 'Callbacks/MsnCallback.aspx', 'contacts', winParams);
}

function updateContacts(contacts) {
    var select = $('contactsSelect');

    $('contactsDiv').style.display = 'block';
    
    for (var i = 0; i < contacts.length; i++) {
        for (var j = 0; j < contacts[i].addresses.length; j++) {
            var option = document.createElement("option");
            
            option.value = contacts[i].addresses[j];
            option.innerHTML = contacts[i].name + " - " + option.value;
            select.appendChild(option);
        }    
    }
}

function addContact() {
    var select = $('contactsSelect');
    var emailAddress = $('emailAddress');
    
    emailAddress.value += (emailAddress.value.length == 0 ? "" : ", ");
    emailAddress.value += select.options[select.selectedIndex].value;
}

function sendImage() {
    var output = "";
    
    output += '<table width="100%" cellpadding="5" cellspacing="5" border="0" style="border-bottom:1px dotted #555;">';
    output += '<tr>';
    output += '<td width="190" height="73" valign="middle"><img src="' + StaticContentRoot + 'images/header_email.jpg" border="0" alt="An email from carmony.co.uk" />';
    output += '</td>';
    output += '<td valign="middle" style="font-weight:bold;font-size:16px;font-family:  Arial, Helvetica, sans-serif; ">';
    output += '</td>';
    output += '</tr>';
    output += '<tr>';
    output += '<td colspan="2" height="50" valign="middle" style="font-weight:bold;font-size:16px;font-family:  Arial, Helvetica, sans-serif; ">';
    output += '{sendername} <span style="color:#666666;">has just seen this on carmony and says</span> {sendermessage} ...';
    output += '</td>';
    output += '</tr>';
    output += '</table>';
    output += '<br/>';
    output += '<a href="' + BuildJSUrl() +'lifestyle" style="text-decoration: none; color: black">';
    output += '  <img src="' + StaticContentRoot + 'images/usedCarFinder.jpeg" style="border-style: none">';
    output += '</a>';

    $("input[@name=htmlContent]").val(output);
}

function RefreshSecCode() {
    AjaxRefreshSecCode(UpdateSecCode, null);
}

function UpdateSecCode(data) {
    var obj = GetDotNetCtrl('valcheck');
    var captId = GetDotNetCtrl("valchkid");
    var img = $("#secimg");
    if (captId == null) return;
    if (obj == null) return ;
    if (img == null) return;
    captId.val(data.ID);
    obj.val("");
    img.attr("src", data.Image);
 }

function GetValCheck() {
    var obj = GetDotNetCtrl('valcheck');
    var captId = GetDotNetCtrl("valchkid");
    if (captId == null) return "";
    if (obj==null) return "";
    return "(valchk:" + encodeURI(obj.val())  +":captId:" + encodeURI(captId.val()) + ")";
}

function sendDealerEmailEnquiry(dealerId) {
    //alert(dealerId);
    //  tb_remove();

    if ($('#form1').valid()) {
        SendDealerEmail(dealerId,
                            $('#ddEmailOnlyTitle').val(),
                            $('#tbEmailOnlyFirstName').val(),
                            $('#surname').val(),
                            $('#emailFrom').val(),
                            $('#telephone').val(),
                            $('#enquiry').val(),
                            $('#ctasrc').val() + GetValCheck(),
    onEmailSuccess);
    }
}

function DisplayNOValMsg(failed) {
    if (!failed) return !failed;
    alert("Invalid Security Code");
    RefreshSecCode();
    return !failed;
}

function onEmailSuccess(data) {

    if (!DisplayNOValMsg(data == false)) return;
    DisplayLightBox('dealercontacted', '485', '162', 'true');
}


function bookNPTestDrive(vehicleId, dealerEmail) {
    if ($('#form1').valid()) {
        ArrangeTestDrive(vehicleId,
                            $('#title').val(),
                            $('#firstName').val(),
                            $('#surname').val(),
                            $('#emailFrom').val(),
                            $('#telephone').val(), "", "", GetValCheck(),
                            bookNPTestDriveSucceeded, 
                            bookTestDriveFailed);
    }
}


function bookTestDrive(vehicleId, dealerEmail) {
    if ($('#form1').valid()) {
        ArrangeTestDrive(vehicleId,
                            $('#title').val(),
                            $('#firstName').val(),
                            $('#surname').val(),
                            $('#emailFrom').val(),
                            $('#telephone').val(),
                            $('#selectedDate').val(),
                            $('#preferredTime').find('input[@checked]').val(),
                            $('#ctasrc').val() + GetValCheck(),
                            bookTestDriveSucceeded, 
                            bookTestDriveFailed);
    }
}
function bookNPTestDriveSucceeded(data) {
    if (!DisplayNOValMsg(data == -1)) return;
    if (data == 0) { bookTestDriveFailed(); return; }
    DisplayLightBox('dyn/freethankyou?vid=' + data + "&type=testdrive", '600', '350', 'true');
}
function bookTestDriveSucceeded(data) {
    if (!DisplayNOValMsg(data == -1)) return;
    if (data == 0) { bookTestDriveFailed(); return; }
    DisplayLightBox('dealercontacted', '485', '162', 'true');
}
function bookTestDriveFailed() {
    displayGenericError();
}
function sendEnquiry() {
    if ($('#form1').valid()) {
        SendVehicleEnquiry($('#vehicleID').val(),
                                $('#vehicleTitle').val(),
                                $('#title').val(),
                                $('#firstName').val(),
                                $('#surname').val(),
                                $('#emailFrom').val(),
                                $('#telephone').val(),
                                $('#enquiry').val(),
                                $('#ctasrc').val() + GetValCheck(),
                                 sendEnquirySucceeded, sendEnquiryFailed);
        return false;
    }
}
function sendNPEnquiry() {
 
    if ($('#form1').valid()) {
        SendVehicleEnquiry($('#vehicleID').val(),
                                $('#vehicleTitle').val(),
                                $('#title').val(),
                                $('#firstName').val(),
                                $('#surname').val(),
                                $('#emailFrom').val(),
                                $('#telephone').val(),
                                $('#enquiry').val(),
                                GetValCheck(), sendNPEnquirySucceeded, sendEnquiryFailed);
        return false;
    }
}
function sendNPEnquirySucceeded(data) {
    if (!DisplayNOValMsg(data == -1)) return;
    if (data == 0) { sendEnquiryFailed(); return; }
    DisplayLightBox('dyn/freethankyou?vid=' + data + "&type=enq", '600', '350', 'true');
}
function sendEnquirySucceeded(data) {
    if (!DisplayNOValMsg(data == -1)) return;
    if (data == 0) { sendEnquiryFailed(); return; }
    DisplayLightBox('dealercontacted', '485', '162', 'true');
}
function sendEnquiryFailed() {
    displayGenericError();
}


//===========
function callMeBack() {
    var ctasrc = $('#ctasrc');
    var additionalData =  GetValCheck()
    if (ctasrc != null) {
        if (IsDefined(ctasrc.val())){
        additionalData = ctasrc.val() + additionalData;
        }
    }
   

    if ($('#form1').valid()) {
        CallMeBackEnquiry($('#vehicleID').val(),
                                $('#title').val(),
                                $('#firstName').val(),
                                $('#surname').val(),
                               $('#telephone').val(),'',
                               additionalData, CallMeBackEnquirySucceeded, CallMeBackFailed);
        return false;
    }
}
function callNPMeBack() {

    if ($('#form1').valid()) {
        CallMeBackEnquiry($('#vehicleID').val(),
                                $('#title').val(),
                                $('#firstName').val(),
                                $('#surname').val(),
                               $('#telephone').val(),'',
                                GetValCheck(), CallNPMeBackEnquirySucceeded, CallMeBackFailed);
        return false;
    }
}
function CallNPMeBackEnquirySucceeded(data) {

    DisplayLightBox('dyn/freethankyou?vid=' + data + "&type=cmb", '600', '350', 'true');
}
function CallMeBackEnquirySucceeded(data) {
    if (!DisplayNOValMsg(data == -1)) return;
    if (data == 0) { CallMeBackFailed(); return; }
    DisplayLightBox('dealercontacted', '485', '162', 'true');
}
function CallMeBackFailed() {
    displayGenericError();
}