﻿var VehicleType = "Car";
var numberOfAds;
var totalNumberOfAdverts = 0;
var minSelectedValue = 0;
var maxSelectedValue = 0;
var MakeID = 143;
var colourArray = [];


$(document).ready(function () {

    // when the user changes the make dropdown... load the models
    $('#CarVehicleMake').change(function () {

        // clear the cars model and trim dropdowns
        CarMakeModelClear();

        // store the makeID
        var makeID = $('#CarVehicleMake').attr('value');

        if (makeID > 0) {
            populateCarModels(makeID, "CarVehicleModel");
        }
        else {
            $('#CarVehicleModel').attr('disabled', 'disabled');
        }

        // ************************************
        // href="#tabs-1" class="UsedCarsTab"
        // Tab Clearers
        // ************************************
        // when the user clicks the MakeID box, clear the model and trim dropdown box.
        $(".UsedCarsTab").click(function () {
            clearComboBox("CarVehicleMake");
            clearComboBox("CarVehicleModel");
            clearComboBox("CarVehicleTrim");

            $("#CarBodyStylesContainerDiv").show();
            $("#VanBodyStylesContainerDiv").hide();

            populateMakes(false, "CarVehicleMake");
            ResetCarSliders();
        });

        $(".UsedVansTab").click(function () {
            clearComboBox("VanVehicleMake");
            clearComboBox("VanVehicleModel");
            clearComboBox("VanVehicleTrim");

            $("#CarBodyStylesContainerDiv").hide();
            $("#VanBodyStylesContainerDiv").show();

            populateMakes(true, "VanVehicleMake");
            ResetVanSliders();

        });

    });

    // when the user changes the model dropdown... load the trims
    $('#CarVehicleModel').change(function () {

        // clear the trim
        CarTrimClear();

        // store the modelID
        var modelID = $('#CarVehicleModel').attr('value');

        if (modelID > 0) {
            populateCarTrims(modelID, "CarVehicleTrim");
        }
        else {
            $('#CarVehicleTrim').attr('disabled', 'disabled');
        }
    });

    //--------------------------------------------------
    //------------- Van Scripts ------------------------
    //--------------------------------------------------
    //-- might want to convert this to class based rather than ID based
    //--------------------------------------------------

    // when the user changes the make dropdown... load the models
    $('#VanVehicleMake').change(function () {

        // clear the cars model and trim dropdowns
        VanMakeModelClear();

        // store the makeID
        var makeID = $('#VanVehicleMake').attr('value');
        if (makeID > 0) {
            populateVanModels(makeID, "VanVehicleModel");
        }
        else {
            $('#VanVehicleModel').attr('disabled', 'disabled');
        }
    });

    // when the user changes the model dropdown... load the trims
    $('#VanVehicleModel').change(function () {

        // clear the trim
        VanTrimClear();

        // store the makeID
        var modelID = $('#VanVehicleModel').attr('value');
        if (modelID > 0) {
            populateVanTrims(modelID, "VanVehicleTrim");
        }
        else {
            $('#VanVehicleTrim').attr('disabled', 'disabled');
        }
    });

    // *************************
    // ** Bodystyle Rollovers **
    // *************************
    // body style rollovers
    $(".BodyStyleRollover").mouseover(function () {

        // save the Image URL
        var ImgURL = $(this).find("div").attr("imgURL");

        // now we have the ImgURL we want to show the image
        $("#BodyStyleImage").attr("src", "/Images/BodyStyleIcons/newStyle/" + ImgURL);
    });

    // body style rollovers
    $(".VanBodyStyleRollover").mouseover(function () {

        // save the Image URL
        var ImgURL = $(this).find("div").attr("imgURL");

        // now we have the ImgURL we want to show the image
        $("#VanBodyStyleImage").attr("src", "/Images/BodyStyleIcons/OriginalBodyStyles/" + ImgURL);
    });

    // ******************************
    // ** Vehicle Colour Rollovers **
    // ******************************
    // Any Colour checkbox
    $("#AnyVehicleColour").click(function () {

        SelectAllColours();

    });

    // if the hidden vehicle colours box is empty, ensure that the any check box is ticked
    if ($("#VehicleColoursFilter").val() == "") {
        $('#AnyVehicleColour').attr('checked', true);
    }

    // Vehicle Colour Selection
    $(".VehicleColourSelector").click(function () {

        // ensure the any colour tick box is unticked
        $('#AnyVehicleColour').attr('checked', false);

        // get the colour name
        var ColourName = $(this).attr("colour");
        var HiddenInputArray = $("#VehicleColoursFilter").val().split(',');

        //console.log("Colour " + ColourName);
        //console.log("Initialize " + HiddenInputArray.toString());
        //console.log("InArray " + InArray(ColourName, HiddenInputArray).toString());
        //console.log("TestInArray " + InArray("Red", HiddenInputArray).toString());

        // **************
        // test area
        //console.log("TestInArray-true " + InArray('Blue', HiddenInputArray).toString());
        //console.log("TestInArray-false " + InArray("Red", HiddenInputArray).toString());

        /*
        if the colour is allready in the Array, we need to clear it out
        if not, then we want to add it in.
        */
        // Add it in if the colour isnt in the array hidden field add it
        if (InArray(ColourName, HiddenInputArray) == false) {

            // add the white border around the element to show this colour is selected
            $(this).removeClass("blackBorder");
            $(this).addClass("whiteBorder");

            $(this).find("img").removeClass("hidden");
            $(this).find("img").addClass("visible");

            // add the colour name into the string array stored in the hidden box -> #VehicleColoursFilter
            colourArray = $("#VehicleColoursFilter").val().split();
            colourArray.push(ColourName);

            $("#VehicleColoursFilter").val(colourArray.toString());

            // store the text box string as a new array
            colourArray = $("#VehicleColoursFilter").val().toString().split(',');

            // save the non duplicates to the hidden box
            $("#VehicleColoursFilter").val(eliminateDuplicates(colourArray).toString());
        }
        // else it equal -1 so we need to remove it from the hidden field array
        else {

            // add the black border around the element to show this colour is NOT selected
            $(this).removeClass("whiteBorder");
            $(this).addClass("blackBorder");

            $(this).find("img").removeClass("visible");
            $(this).find("img").addClass("hidden");

            // get the array from the hidden field
            colourArray = $("#VehicleColoursFilter").val().split(',');

            // get the index of the colour in the array
            var index = _.indexOf(colourArray, ColourName);
            removeByIndex(colourArray, index);

            // save the non duplicates to the hidden box
            $("#VehicleColoursFilter").val(eliminateDuplicates(colourArray).toString());
        }

        // if the hidden field is empty, no colours have been selected so tick the any button
        if ($("#VehicleColoursFilter").val() == "") $('#AnyVehicleColour').attr('checked', true);
        console.log("#VehicleColoursFilter " + $("#VehicleColoursFilter").val());

    });

    // ******************************
    // ** Number of Doors **
    // ******************************
    // if the hidden vehicle colours box is empty, ensure that the any check box is ticked
    $("#AnyNumberOfDoors").click(function () {
        if ($("#AnyNumberOfDoors").is(':checked')) {
            $('.inputDoorCheckBox').attr('checked', false);
        }
    });
    $(".inputDoorCheckBox").click(function () {
        $("#AnyNumberOfDoors").attr('checked', false);
        doorsTicks();
    });

    doorsTicks();
});

function SelectAllColours() {

    if ($('#AnyVehicleColour').is(':checked')) {

        // clear the array hidden field
        $("#VehicleColoursFilter").val("");

        // remove the border from the colour selectors
        $(".VehicleColourSelector").removeClass("whiteBorder");
        $(".VehicleColourSelector").addClass("blackBorder");

    }

    // ensure that when the user clicks any colour, all ticks that are showing are hidden
    $("body").find("*[tick]").each(function (index) {
        $(this).removeClass();
        $(this).addClass("hidden");
    });

}

function doorsTicks()
{
    // when the page loads, if none of the door checkboxes are checked then tick the any door box
    var AnyTick = true;
    $(".inputDoorCheckBox").each(function () {
        if ($(this).is(':checked')) {
            AnyTick = false;
        }
    });

    if (AnyTick == true) {
        $("#AnyNumberOfDoors").attr('checked', true);
    }
}

// Returns the array without duplicates
function eliminateDuplicates(arr) {
    var i,
      len = arr.length,
      out = [],
      obj = {};

    for (i = 0; i < len; i++) {
        obj[arr[i]] = 0;
    }
    for (i in obj) {
        out.push(i);
    }
    return out;
}

function InArray(obj, arr) {
    return (arr.indexOf(obj) != -1);
}

function removeByIndex(arrayName, arrayIndex) {
    arrayName.splice(arrayIndex, 1);
}

// function to Populate the makes
function populateMakes(commercial, ControlID) {

    $.ajax({
        url: "/SearchBar/GetMakes/" + commercial,
        dataType: 'json',
        success: function (data) {
            RemoveDisabled(ControlID);
            $.each(data, function (key, value) {
                $("#" + ControlID).append($("<option />").val(value["MakeID"]).text(value["MakeName"] + " (" + value["NoOfCarsByMake"] + ")"));
            });
        }
    });
}

// function to bring back the Car Models
function populateCarModels(makeID, ControlID) {

    $.ajax({
        url: "/SearchBar/GetModelsByMake/" + makeID + "/false",
        dataType: 'json',
        success: function (data) {
            RemoveDisabled(ControlID);
            $.each(data, function (key, value) {
                //console.log(value["ModelID"] + ': ' + value["ModelName"]);
                $("#" + ControlID).append($("<option />").val(value["ModelID"]).text(value["ModelName"] + " (" + value["NoOfCarsByModel"] + ")"));
            });
        }
    });
}

// function to bring back the Car Trims
function populateCarTrims(ModelID, ControlID) {

    $.ajax({
        url: "/SearchBar/GetTrimsByModel/" + ModelID + "/false",
        dataType: 'json',
        success: function (data) {
            RemoveDisabled(ControlID);
            $.each(data, function (key, value) {
                //console.log(value["TrimName"] + ': ' + value["TrimName"]);
                $("#" + ControlID).append($("<option />").val(value["TrimName"]).text(value["TrimName"] + " (" + value["NoOfCarsByTrim"] + ")"));
            });
        }
    });
}

// *********************
// ** clear functions **
// ********************* 
// when the user clicks the MakeID box, clear the model and trim dropdown box.
// $("#CarVehicleMake").click(function () {
function CarMakeModelClear() {

    // we need to check that the model dropdown is not already populated with
    // the current makes models.

    // 1. add the make ID as a class to the models dropdown
    // 2. use this class to determin if the models dropdown is populated

    // clear model
    if (document.getElementById("CarVehicleModel").options.length > 0) {
        var BoxToClear = "CarVehicleModel";
        clearComboBox(BoxToClear);
        SetDisabled("CarVehicleModel");
    }

    // clear trim
    if (document.getElementById("CarVehicleTrim").options.length > 0) {
        var BoxToClear = "CarVehicleTrim";
        clearComboBox(BoxToClear);
        SetDisabled("CarVehicleTrim");

    }
}

// when the user clicks the MakeID box, clear the model and trim dropdown box.
//$("#CarVehicleModel").click(function () {
function CarTrimClear() {

    // clear trim
    if (document.getElementById("CarVehicleTrim").options.length > 0) {
        var BoxToClear = "CarVehicleTrim";
        clearComboBox(BoxToClear);
    }
}

// *********
// VANS //
// *********
// function to bring back the VAN models
function populateVanModels(makeID, ControlID) {

    $.ajax({
        url: "/SearchBar/GetModelsByMake/" + makeID + "/true",
        dataType: 'json',
        success: function (data) {
            RemoveDisabled(ControlID);
            $.each(data, function (key, value) {
                //console.log(value["ModelID"] + ': ' + value["ModelName"]);
                $("#" + ControlID).append($("<option />").val(value["ModelID"]).text(value["ModelName"] + " (" + value["NoOfCarsByModel"] + ")"));
            });
        }
    });
}

// function to bring back the VAN Trims
function populateVanTrims(ModelID, ControlID) {

    $.ajax({
        url: "/SearchBar/GetTrimsByModel/" + ModelID + "/true",
        dataType: 'json',
        success: function (data) {
            RemoveDisabled(ControlID);
            $.each(data, function (key, value) {
                //console.log(value["TrimName"] + ': ' + value["TrimName"]);
                $("#" + ControlID).append($("<option />").val(value["TrimName"]).text(value["TrimName"] + " (" + value["NoOfCarsByTrim"] + ")"));
            });
        }
    });
}

// when the user clicks the MakeID box, clear the model and trim dropdown box.
//$("#VanVehicleMake").click(function () {
function VanMakeModelClear() {

    // clear model
    if (document.getElementById("VanVehicleModel").options.length > 0) {
        var BoxToClear = "VanVehicleModel";
        clearComboBox(BoxToClear);
        SetDisabled("VanVehicleModel");
    }

    // clear trim
    if (document.getElementById("VanVehicleTrim").options.length > 0) {
        var BoxToClear = "VanVehicleTrim";
        clearComboBox(BoxToClear);
        SetDisabled("VanVehicleTrim");

    }
}

// when the user clicks the MakeID box, clear the model and trim dropdown box.
//$("#VanVehicleModel").click(function () {
function VanTrimClear() {

    // clear trim
    if (document.getElementById("VanVehicleTrim").options.length > 0) {
        var BoxToClear = "VanVehicleTrim";
        clearComboBox(BoxToClear);
    }
}

// *********************
// General Functions //
// *********************
// Clear a combo box
function clearComboBox(BoxToClear) {
    for (var i = document.getElementById(BoxToClear).options.length; i > 1; i--) {
        document.getElementById(BoxToClear).options[i - 1] = null;
    }
}

// set element as disabled
function SetDisabled(ElementID) {
    $('#' + ElementID).attr('disabled', 'disabled');
}

// set element as disabled
function RemoveDisabled(ElementID) {
    $('#' + ElementID).removeAttr('disabled');
}


function ResetSearchOptions() {
    // reset the makes and model dropdowns
    clearComboBox("CarVehicleTrim");
    clearComboBox("CarVehicleModel");

    $("#CarVehicleMake").val(0);
    $("#MinPrice").val(0);
    $("#MaxPrice").val(0);

    // advanced search
    $("#Transmission").val(0);
    $("#FuelType").val(0);
    $("#VehicleColoursFilter").val(0);
    $('#AnyVehicleColour').attr('checked', true);
    
    $('#AnyNumberOfDoors').attr('checked', true);
    $(".inputDoorCheckBox").each(function () {
        $(this).attr('checked', false);
    });

    ResetCarSliders();
    ResetVanSliders();
}

function ResetCarSliders() {
    // reset the Car sliders

    // Car MPG
    var MPGMin = $("#slider-range").slider("option", "min");
    var MPGMax = $("#slider-range").slider("option", "max");

    $("#slider-range").slider({ values: [MPGMin, MPGMax] });
    $("#MinMpg").val(MPGMin);
    $("#MaxMpg").val(MPGMax);

    // Car C02 Slider
    var C02Min = $("#C02-slider-range").slider("option", "min");
    var C02Max = $("#C02-slider-range").slider("option", "max");

    $("#C02-slider-range").slider({ values: [C02Min, C02Max] });
    $("#MinC02").val(C02Min);
    $("#MaxC02").val(C02Max);

    // Car Tax
    var CarTaxMin = $("#slider").slider("option", "min");
    $("#slider").slider("option", "value", CarTaxMin);
    $("#MaxCarTax").val(CarTaxMin);

    // Max Car Age
    $("#MaxCarAge").val(0);
    $("#Age-Slider").slider("option", "value", 0);

    SelectAllColours();
}

function ResetVanSliders() {
    // reset the VAN sliders

    // Van MPG
    var VanMPGMin = $("#Van-MPG-slider-range").slider("option", "min");
    var VanMPGMax = $("#Van-MPG-slider-range").slider("option", "max");

    $("#Van-MPG-slider-range").slider({ values: [VanMPGMin, VanMPGMax] });
    $("#VanMinMpg").val(VanMPGMin);
    $("#VanMaxMpg").val(VanMPGMax);

    // Van C02 Slider
    var VanC02Min = $("#Van-C02-slider-range").slider("option", "min");
    var VanC02Max = $("#Van-C02-slider-range").slider("option", "max");

    $("#Van-C02-slider-range").slider({ values: [VanC02Min, VanC02Max] });
    $("#VanMinC02").val(VanC02Min);
    $("#VanMaxC02").val(VanC02Max);

    // Van Tax slider
    var CarTaxMin = $("#Van-slider").slider("option", "min");
    $("#Van-slider").slider("option", "value", CarTaxMin);
    $("#VanMaxCarTax").val(CarTaxMin);
}

