﻿var VehicleType = "Car";
var numberOfAds;
var totalNumberOfAdverts = 0;
var minSelectedValue = 0;
var maxSelectedValue = 0;


$(document).ready(function() {

	$("a.enlarge").hover(loadLargeImage);
	$("a.enlarge").click(function() { return false; });
	
    // initailly hidden elements
    hide("#total-advert-number");

    // vars to store the make and model ID, thses are used for the selected values on postback
    MakeID = $('#MakeID').attr('value');
    ModelID = $('#ModelID').attr('value');

    RegionID = $('#advert-region').attr('value');
    CountyID = $('#advert-county').attr('value');
    TownID = $('#advert-town').attr('value');

    RegionIDDealer = $('#dealer-region').attr('value');
    CountyIDDealer = $('#dealer-county').attr('value');
    TownIDDealer = $('#dealer-town').attr('value');

    // populate both the region and dealer dropdowns
    populateRegion('#advert-region');
    populateRegion('#dealer-region');

    /* Ajax dropdowns
    method also calculates the total number of adverts
    */

    $.post("/webservices/cvd-webservice.asmx/GetCarMakes", function(data) {
        var items = $('ListMake', data);
        items.each(function() {

        if (($(this).attr('DisplayInUsedFooter') == "true") && (($(this).attr('NumberOfUsedAdverts') > 0))) {
            // store the name of the car.
            var CarMake = $(this).attr('Name');
            var CarID = $(this).attr('ID');
            var NumberOfAds = $(this).attr('NumberOfUsedAdverts');
            totalNumberOfAdverts += parseInt(NumberOfAds);

            // create an option for the make dropdown.
            var newOption = document.createElement('option');
            var ValueAttr = document.createAttribute('value');
            ValueAttr.value = $(this).attr('ID');
            newOption.setAttributeNode(ValueAttr);

            // check to see if the current model id maches modelID
            if ($(this).attr('ID') == MakeID) {
                // create a selected attribute
                SelAttr = document.createAttribute('selected');
                SelAttr.value = "selected";
                newOption.setAttributeNode(SelAttr);
            }

            // add the name of the car to to dropdown
            newOption.innerHTML = CarMake + " (" + NumberOfAds + ")";

            // add the option to the dropdown
            $('#MakeID').append(newOption);
        }
    });

        if (totalNumberOfAdverts > 0) {
            $('#total-advert-number-container').append("<span id='totalNumber' class='total-advert-number'>" + totalNumberOfAdverts + "</span>");
            $('#totalNumber').fadeIn(("slow"), 2000);
        }
    });

    // this removed the duplicated make name at the specified index
    document.getElementById('MakeID').options[1] = null;

    // remove the duplicated entry in the models dropdown
    if (ModelID > 0) {
        populateModels(MakeID, "Car");
        document.getElementById('ModelID').options[1] = null;
    }




    // when the user changes the make dropdown...
    $('#MakeID').change(function() {
        // store the makeID
        var makeID = $('#MakeID').attr('value');
        if (makeID > 0) {
            $('#ModelID').removeAttr('disabled', 'disabled');
            populateModels(makeID, "Car");
        }
        else {
            $('#ModelID').attr('disabled', 'disabled');
        }
    });

    // when the user clicks the MakeID box, clear the make dropdown box.
    $("#MakeID").click(function() {
        if (document.getElementById("ModelID").options.length > 0) {
            var BoxToClear = "ModelID";
            clearComboBox(BoxToClear);
        }
    });

    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */
    /* Dealer serach dropdowns - START    */
    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */

    // when the user selects a region
    $('#dealer-region').change(function() {
        // store the regionID
        RegionIDDealer = $('#dealer-region option:selected').val()

        // remove the disabled attribute
        $('#dealer-county').removeAttr("disabled");

        // call the get Counties web service
        getCounties(RegionIDDealer, '#dealer-county');

    });

    // when the user selects a county
    $('#dealer-county').change(function() {
        // store the countyID
        var CountyIDDealer = $('#dealer-county').attr('value');
        if (CountyIDDealer > 0) {

            // remove the disabled attribute
            $('#dealer-town').removeAttr("disabled");

            // call the get Counties web service
            getTowns(CountyIDDealer, '#dealer-town');
        }
    });

    // when the user clicks the MakeID box, clear the make dropdown box.
    $("#dealer-region").click(function() {
        if (document.getElementById("dealer-county").options.length > 0) {
            var BoxToClear = "dealer-county";
            clearComboBox(BoxToClear);
        }
        if (document.getElementById("dealer-town").options.length > 0) {
            var BoxToClear = "dealer-town";
            clearComboBox(BoxToClear);
        }
    });

    // check that the dropdowns dont already contain values, if so call the ajax functions
    if ($('#dealer-region option:selected').text() != "Select a Region") {
        $('#dealer-county').removeAttr("disabled");
        // store the regionID
        if (RegionIDDealer == 0) {
            RegionIDDealer = $('#dealer-region option:selected').attr('value');
        }
        if (RegionIDDealer > 0) {

            // remove the disabled attribute
            $('#dealer-county').removeAttr("disabled");
            var BoxToClear = "dealer-county";
            clearComboBox(BoxToClear);

            // call the get Counties web service
            getCounties(RegionIDDealer, '#dealer-county');
            clearDuplicate(BoxToClear);

            $('#dealer-town').removeAttr("disabled");
            // store the regionID
            if (CountyIDDealer == 0) {
                CountyIDDealer = $('#dealer-county option:selected').attr('value');
            }
            if (CountyIDDealer > 0) {

                // remove the disabled attribute
                $('#dealer-town').removeAttr("disabled");
                var BoxToClear = "dealer-town";
                clearComboBox(BoxToClear);

                // call the get Counties web service
                getTowns(CountyIDDealer, '#dealer-town');
                clearDuplicate(BoxToClear);
            }
        }
    }


    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */
    /* Dealer serach dropdowns - END      */
    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */

    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */
    /* Advert serach dropdowns - START    */
    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */

    // when the user selects a region
    $('#advert-region').change(function() {
        // store the regionID
        var regionID = $('#advert-region').attr('value');
        if (regionID > 0) {

            // remove the disabled attribute
            $('#advert-county').removeAttr("disabled");

            // call the get Counties web service
            getCounties(regionID, '#advert-county');
        }
    });

    // when the user selects a county
    $('#advert-county').change(function() {
        // store the countyID
        var countyID = $('#advert-county').attr('value');
        if (countyID > 0) {

            // remove the disabled attribute
            $('#advert-town').removeAttr("disabled");

            // call the get Counties web service
            getTowns(countyID, '#advert-town');
        }
    });


    // when the user clicks the MakeID box, clear the make dropdown box.
    $("#advert-region").click(function() {
        if (document.getElementById("advert-county").options.length > 0) {
            var BoxToClear = "advert-county";
            clearComboBox(BoxToClear);
        }
        if (document.getElementById("advert-town").options.length > 0) {
            var BoxToClear = "advert-town";
            clearComboBox(BoxToClear);
        }
    });

    // when the user click on the Counties dropdown clear the town dorpdown
    $('#advert-county').click(function() {
        if (document.getElementById("advert-town").options.length > 0) {
            var BoxToClear = "advert-town";
            clearComboBox(BoxToClear);
        }
    });


    // check that the dropdowns dont already contain values, if so call the ajax functions
    if ($('#advert-region option:selected').text() != "Select a Region") {
        $('#advert-county').removeAttr("disabled");
        // store the regionID
        if (RegionID == 0) {
            RegionID = $('#advert-region option:selected').attr('value');
        }
        if (RegionID > 0) {

            // remove the disabled attribute
            $('#advert-county').removeAttr("disabled");
            var BoxToClear = "advert-county";
            clearComboBox(BoxToClear);

            // call the get Counties web service
            getCounties(RegionID, '#advert-county');
            clearDuplicate(BoxToClear);

            $('#advert-town').removeAttr("disabled");
            // store the regionID
            if (CountyID == 0) {
                CountyID = $('#advert-county option:selected').attr('value');
            }
            if (CountyID > 0) {

                // remove the disabled attribute
                $('#advert-town').removeAttr("disabled");
                var BoxToClear = "advert-town";
                clearComboBox(BoxToClear);

                // call the get Counties web service
                getTowns(CountyID, '#advert-town');
                clearDuplicate(BoxToClear);
            }
        }
    }


    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */
    /*   Advert serach dropdowns - END    */
    /* }æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ}æ */

    // when the user click the postcode box, lost the text inside
    $('#postcode-input').click(function() {
        $('#postcode-input').removeAttr("value");
    });

    // remove the initial text of enter postcode when the user clicks the text box
    $("#Postcode").click(function() {
        if ($("#Postcode").attr("value") == "Enter Postcode")
            $("#Postcode").attr("value", "");
    });

    $("#Postcode").blur(function() {
        if ($("#Postcode").attr("value") == "")
            $("#Postcode").attr("value", "Enter Postcode");
    });

    // add a blue rollover background to the adverts
    $('div.advert-container-div').hover
    (
        function() { $(this).css({ 'background-color': '#EFF3FF' }); },
        function() { $(this).css({ 'background-color': 'white' }); }
    );

    /* bodystyle image rollovers */
    $("#hatchback").mouseover(function() {
        $("#bodystyle-image").replaceWith("<img id='bodystyle-image' src='/images/icons/hatchback.png' />");
    });

    $("#Convertible").mouseover(function() {
        $("#bodystyle-image").replaceWith("<img id='bodystyle-image' src='/images/icons/convertable.png' />");
    });

    $("#Saloon").mouseover(function() {
        $("#bodystyle-image").replaceWith("<img id='bodystyle-image' src='/images/icons/saloon.png' />");
    });

    $("#MPV").mouseover(function() {
        $("#bodystyle-image").replaceWith("<img id='bodystyle-image' src='/images/icons/mpv.png' />");
    });

    $("#estate").mouseover(function() {
        $("#bodystyle-image").replaceWith("<img id='bodystyle-image' src='/images/icons/estate.png' />");
    });

    $("#4x4").mouseover(function() {
        $("#bodystyle-image").replaceWith("<img id='bodystyle-image' src='/images/icons/4x4.png' />");
    });

    $("#coupe").mouseover(function() {
        $("#bodystyle-image").replaceWith("<img id='bodystyle-image' src='/images/icons/coupe.png' />");
    });


    var i = 0;
    // when the page loads, set up the models
    $("#MakeID").bind("ajaxStop", (function() {
        //call the populateModels function using the selected value of the makes dropdown
        while (i == 0) {
            if ($("#MakeID option:selected").val() > 0) {
                clearComboBox("ModelID")
                populateModels($("#MakeID option:selected").val(), "Car");
                i++;
            }
            else {
                break;
            }
        }
    }));

    // rollovers for the dealer adverts
    $(".dealer-advert-list-container").hover
    (
        function() { $(this).css({ 'background-color': '#CEE7FF' }); },
        function() { $(this).css({ 'background-color': 'white' }); }
    );

    // dropdowns form
    $("#SortOrder").change(function() {
        $("#dropdownsForm").submit();
    });

    $("#NumberPerPage").change(function() {
        $("#dropdownsForm").submit();
    });

    /* 
    if the user clicks any of the
    dropdowns in the search bar        
    */
    $("#Search-bar-form > .dropDown").click(function() {
        // check to see if this element exists
        if ($(".dropDown-search").length > 0) {
            if ($(".dropDown-search").attr("disabled").text == null) {
                $(".dropDown-search").attr("disabled", "disabled");
            }
        }
    });

    // back to search results - submit the serach-bar form
    $("#back-to-search-results").click(function() {
        //alert("tackel");
        $("#Search-bar-form").submit();
    });




});

// show the email form
function showEmailForm(elementID) {
    var el = document.getElementById(elementID);
    el.scrollIntoView(true);
}


function populatePrices(dropDownID, initalStartValue, initalFinalValue) {

    // fill this dropdown with price values
    for (var i = parseInt(initalStartValue); i < parseInt(initalFinalValue); i += 5000) {
        var newOption = document.createElement('option');
        var valueAttr = document.createAttribute('value');
        valueAttr.value = i;
        newOption.setAttributeNode(valueAttr);

        newOption.innerHTML = "£" + i;
        $('#' + dropDownID).append(newOption);

    }
}

function hide(ElementID) {
    $(ElementID).hide();
}

// region dropdowns - populate both the advert and dealer
function populateRegion(dropDownID) {
    $.post("/webservices/cvd-regions.asmx/GetRegions", function(data) {

        var regions = $('BasicRegion', data);
        regions.each(function() {

            // store the name of the region
            var region = $(this).attr("Name");
            var regionID = $(this).attr("ID");

            // create a new option object
            var newOption = document.createElement('option');
            var ValueAttr = document.createAttribute('value');
            ValueAttr.value = regionID;
            newOption.setAttributeNode(ValueAttr);

            // check to see if the current model id maches modelID
            if ($(this).attr('ID') == RegionID) {
                // create a selected attribute
                SelAttr = document.createAttribute('selected');
                SelAttr.value = "selected";
                newOption.setAttributeNode(SelAttr);
            }

            newOption.innerHTML = region;

            $(dropDownID).append(newOption);

        });
    });
}

function getCounties(regionID, countyDropDownID) {
    $.post("/webservices/cvd-regions.asmx/GetCounties", "regionID=" + regionID, function(data) {

        var counties = $('BasicCounty', data);
        counties.each(function() {

            // store the name of the counties
            var countyName = $(this).attr('Name');
            var countyID = $(this).attr('ID');

            // create a new option object
            var newOption = document.createElement('option');
            var ValueAttr = document.createAttribute('value');
            ValueAttr.value = countyID;
            newOption.setAttributeNode(ValueAttr);

            // check to see if the current model id maches modelID
            if ($(this).attr('ID') == CountyID) {
                // create a selected attribute
                SelAttr = document.createAttribute('selected');
                SelAttr.value = "selected";
                newOption.setAttributeNode(SelAttr);
            }

            newOption.innerHTML = countyName;

            $(countyDropDownID).append(newOption);


        });
    });
}

function getTowns(countyID, townDropDownID) {
    $.post("/webservices/cvd-regions.asmx/GetTowns", "countyID=" + countyID, function(data) {
        var towns = $('BasicTown', data);
        towns.each(function() {

            // store the name of the counties
            var townName = $(this).attr('Name');
            var townID = $(this).attr('ID');

            // create a new option object
            var newOption = document.createElement('option');
            var ValueAttr = document.createAttribute('value');
            ValueAttr.value = townID;
            newOption.setAttributeNode(ValueAttr);

            // check to see if the current model id maches modelID
            if ($(this).attr('ID') == TownID) {
                // create a selected attribute
                SelAttr = document.createAttribute('selected');
                SelAttr.value = "selected";
                newOption.setAttributeNode(SelAttr);
            }

            newOption.innerHTML = townName;

            $(townDropDownID).append(newOption);


        });
    });
}

function clearDuplicate(ID) {
    document.getElementById(ID).options[1] = null;
}

// function to bring back the models
function populateModels(makeID, vehicleType) {
    $.post("/webservices/cvd-webservice.asmx/GetCarModels", "carMakeID=" + makeID, function(data) {
        var models = $('ListModel', data);
        models.each(function() {

        if ($(this).attr('NumberOfUsedAdverts') > 0)
            {
                // store the model details
                var modelName = $(this).attr('Name');
                var ID = $(this).attr('ID');
                var NumberOfAds = $(this).attr('NumberOfUsedAdverts');

                // create the option dropdown
                var newOption = document.createElement('option');
                var valueAttr = document.createAttribute('value');
                valueAttr.value = $(this).attr('ID');
                newOption.setAttributeNode(valueAttr);

                // check to see if the current model id maches modelID
                // alert(" value " + $(this).attr('ID') + " makelID " + ModelID);
                if ($(this).attr('ID') == ModelID) {
                    // create a selected attribute
                    SelAttr = document.createAttribute('selected');
                    SelAttr.value = "selected";
                    newOption.setAttributeNode(SelAttr);
                }

                // add the name of the car to to dropdown
                newOption.innerHTML = modelName + " (" + NumberOfAds + ")";

                // add this option to the dropdown                
                $('#ModelID').append(newOption);
            }

        });
    });
}


function clearComboBox(BoxToClear) {
    for (var i = document.getElementById(BoxToClear).options.length; i > 1; i--) {
        document.getElementById(BoxToClear).options[i - 1] = null;
    }
}

function loadLargeImage() {
	document.getElementById('LargeImage').src = this.href;
}