﻿
$(document).ready
(
    function () {

        $('a[name=private-modal]').click(function (e) {

            //Prevent the links default behaviour
            e.preventDefault();

            imageIndex = $(this).attr('class');

            var id = "#dialog";

            var maskHeight = $(document).height();
            var maskWidth = $(window).width();

            //Set the mask style and animate the fade in process
            $('#mask').css({ 'width': maskWidth, 'height': maskHeight, 'position': 'absolute', 'left': '0px', 'top': '0px' });
            $('#mask').fadeIn(10);
            $('#mask').fadeTo("fast", 0.8);

            //Obtain the window height and width
            var winH = $(window).height();
            var winW = $(window).width();

            $(id).css('top', winH / 2 - $(id).height() / 2);
            $(id).css('left', winW / 2 - $(id).width() / 2);

            $(id).fadeIn(10);

            //Load the image viewer page within the iframe passing through page values
            $(".iframeviewer").attr("src", "/pages/privatesellerimageviewer.aspx?makeid=" + makeID + "&modelid=" + modelID + "&channel=" + channel + "&advertid=" + advertCode + "&imageindex=" + imageIndex);

            $('html, body').animate({ scrollTop: 0 }, 'slow');

        });

        //Handles a click event on the mask - hides the mask so advert is visible
        $('#mask').click(function () {
            $(this).hide();
            $('.window').hide();
        });

    }
        )

    function LoadImageViewer(imageIndex) {

        var productionOnly = true;

        try {

            if (previewMode != undefined) {
                productionOnly = false;
            }
        } catch (err)
        {}



    
        $.post('/webservices/usedvehiclewebservice.asmx/getadvertimagedetails', { advertcode: advertcode, makeid: makeid, modelid: modelid, imageindex: imageIndex, productionAdvertOnly:productionOnly }, function (data) {

            //Define an array to store the parsed data
            var thumbnails = [];

            var detail = [];

            $(data).find('AdvertImageView').each(function () {
                detail.push(
                    {
                        make: $('make', this).text(),
                        model: $('model', this).text(),
                        price: $('price', this).text(),
                        registration: $('registration', this).text(),
                        mileage: $('mileage', this).text(),
                        year: $('year', this).text(),
                        specification: $('specification', this).text(),
                        transmission: $('transmission', this).text(),
                        doors: $('doors', this).text(),
                        enginesize: $('enginesize', this).text(),
                        bodystyle: $('bodystyle', this).text(),
                        fueltype: $('fueltype', this).text(),
                        colour: $('colour', this).text(),
                        currentimageurl: $('currentimageurl', this).text(),
                        nextindex: $('nextindex', this).text(),
                        lastindex: $('lastindex', this).text(),
                        makeid: $('makeid', this).text(),
                        modelid: $('modelid', this).text()

                    }
                   )
            });

            $(data).find('thumbnails string').each(function () {
                thumbnails.push(
                        {
                            url: $(this).text()
                        }
                    )
            });

            //Create the HTML output
            var html = '<table style="width: 970px; min-height: 600px; background-color: White;" cellpadding="0px" cellspacing="0px"><tbody><tr><td style="vertical-align: top; width: 305px; text-align: center;"><img alt="BuyYourCar.co.uk" src="http://res.buyyourcar.co.uk/images/logo.gif" style="margin-top: -10px;"></td><td style="vertical-align: top; text-align: center;"><span id="dlThumbnails">';

            var imageCount = 0;

            for (var i = 0; i < thumbnails.length; i++) {
                if (thumbnails[i].url != "") {
                    html += '<a href="#" onclick="LoadImageViewer(' + i + ')"><img src="http://res.buyyourcar.co.uk' + thumbnails[i].url + '" /></a>';
                    imageCount++;
                }
            }

            html += '</span></td></tr><tr><td style="vertical-align: top; width: 305px;"><table><tbody><tr><td><div class="twocolumn-right vehiclesummary" style="width: 300px; margin-left: 0px;"><div class="v1"><div class="v2"><div class="v3"><div class="v4"><div class="pad"><h3 style="margin:0px" class="mb">' + detail[0].make + ' ' + detail[0].model + '</h3><div class="Details bcb"><div class="detailrow"><div class="clr"></div></div>';

            html += WriteVehicleProperty("Price", "£" + detail[0].price);
            html += WriteVehicleProperty("Registration", detail[0].registration);
            html += WriteVehicleProperty("Mileage", detail[0].mileage);
            html += WriteVehicleProperty("Year", detail[0].year);
            html += WriteVehicleProperty("Specification", detail[0].specification);
            html += WriteVehicleProperty("Transmission", detail[0].transmission);

            if (detail[0].doors > 0) {
                html += WriteVehicleProperty("Doors", detail[0].doors);
            }
            if (detail[0].enginesize != "0") {
                html += WriteVehicleProperty("Engine Size", detail[0].enginesize);
            }
            html += WriteVehicleProperty("Body Style", detail[0].bodystyle);
            html += WriteVehicleProperty("Fuel Type", detail[0].fueltype);
            html += WriteVehicleProperty("Exterior Colour", detail[0].colour);
            html += '</div></div></div></div></div></div></div></td></tr><tr><td style="height: 270px;text-align:center">';
            html += '<iframe src="/pages/adverts/usedcars/mputop.aspx" class="iframemputop" id="I1" name="I1" width="305px" frameborder="0" height="250px" scrolling="NO"></iframe>';
            html += '</td></tr></tbody></table></td><td style="vertical-align: top; padding: 5px; text-align: center;"><table style="width: 100%;"><tbody><tr><td style="height: 475px; vertical-align: middle; background-color: rgb(239, 239, 239); border: 1px solid rgb(51, 51, 51);">';
            html += '<img id="imgMainImage" src="' + detail[0].currentimageurl + '" style="border: 1px solid rgb(153, 153, 153);">';
            html += '</td></tr><tr><td><table style="width: 100%;" cellpadding="0" cellspacing="0"><tbody><tr><td style="text-align: left;">';
            html += '<a href="#" onclick="LoadImageViewer(' + detail[0].lastindex + ')"><img style="border: 0px none;" src="http://res.buyyourcar.co.uk/images/lastarrow.gif" alt="Show Previous Image"></a></td><td><div style="float: right; font-size: large;"><a href="#" onclick="CloseImageViewer();">Close</a></div><span style="font-weight: bold;">' + detail[0].make + ' ' + detail[0].model + ' ' + detail[0].specification + '</span>&nbsp;<span style="font-weight: bold;"> - Image ' + (imageIndex + 1) + '</span><br><span>' + (imageIndex + 1) + ' of ' + imageCount + '</span></td><td style="text-align: right;"><a href="#" onclick="LoadImageViewer(' + detail[0].nextindex + ')"><img style="border: 0px none;" src="http://res.buyyourcar.co.uk/images/nextarrow.gif" alt="Show Next Image"></a></td></tr></tbody></table></td></tr></tbody></table>';
            $("#usedcarimageviewer").html(html);

        });

        var id = "#dialog";
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();

        //Set the mask style and animate the fade in process
        $('#mask').css({ 'width': maskWidth, 'height': maskHeight, 'position': 'absolute', 'left': '0px', 'top': '0px' });
        $('#mask').fadeIn(10);
        $('#mask').fadeTo("fast", 0.8);

        //Obtain the window height and width
        var winH = $(window).height();
        var winW = $(window).width();

        $(id).css('top', winH / 2 - $(id).height() / 2);
        $(id).css('left', winW / 2 - $(id).width() / 2);

        $(id).fadeIn(10);
        $('html, body').animate({ scrollTop: 0 }, 'slow');


        try {
            StopEvent(event);
        }
        catch (err) {

        }
        return false;
    }


    function WriteVehicleProperty(title, value) {
        return '<div class="attr"><div class="fl">' + title + '</div><div class="fr"><span>' + value + '</span></div><div class="clr"></div></div>';
    }

    //Closes the ImageViewer, called from the imageviewer page
    function CloseImageViewer() {
        $('#mask').hide();
        $('.window').hide();

        try {
            StopEvent(event);
        }
        catch (err) {

        }

        return false;
    }

    function StopEvent(pE) {
        if (!pE)
            if (window.event)
                pE = window.event;
            else
                return;
        if (pE.cancelBubble != null)
            pE.cancelBubble = true;
        if (pE.stopPropagation)
            pE.stopPropagation();
        if (pE.preventDefault)
            pE.preventDefault();
        if (window.event)
            pE.returnValue = false;
        if (pE.cancel != null)
            pE.cancel = true;
    }

    function SelectedMakeChanged(makeList) {

        if (makeList.valueOf != "-1") {


            //Reference the model drop down list
            var ddlModel = $('#ddlModel');

            //Remove the model options
            $(ddlModel).find('option').remove();

            //Append the loading option
            ddlModel.append($('<option></option>').val('-1').text('-- Loading --'));

            //Make the data request
            $.post('/webservices/usedvehiclewebservice.asmx/getmodelswithadverts', 'makeid=' + makeList.value, function (data) { onModelSuccess(data); });

        }
    }

    //--------------------------------------------------------------------
    // Handles a successful response from requesting the model data.
    // Adds models to the model drop down list
    //--------------------------------------------------------------------
    function onModelSuccess(data) {

        //Define an array to store the parsed data
        var parsedData = [];

        //Loop through each element in the XML object
        //and create an JS object to store the data
        $(data).find('VehicleListItem').each(function () {

            parsedData.push(
            {
                id: $('Value', this).text(),
                name: $('Text', this).text()
            }
            )
        });

        //Sort the collection by model name
        parsedData.sort(function (a, b) {
            if (a.name > b.name) {
                return 1;
            }
            else if (a.name == b.name) {
                return 0;
            }
            else {
                return -1;
            }

        });

        //Reference the model drop down list
        var ddlModel = $('#ddlModel');

        //Clear all existing option
        $(ddlModel).find('option').remove();

        //Add the please select option
        ddlModel.append($('<option></option>').val('-1').text('Please Select'));

        //Add each returned model to the drop down list
        for (var i = 0; i < parsedData.length; i++) {
            ddlModel.append($('<option></option>').val(parsedData[i].id).text(parsedData[i].name));
        }
    }

    function SortOrderChanged(ddlSortOrder) {
        var searchForm = $('form.SearchOptionsForm');

        if (searchForm.length > 0) {
            $('#hidSortOrderID', searchForm).val($("#ddlSortOrder").val());

            searchForm.submit();
        }
    }
