﻿function initTwoStageDropdown(parent, child, JSONURL, defaultOptionText, keyName) {
    //This function is used to initialse most Body/Model choosers
    //Update the child if it has been pre-selected by the browser
    if ($(child).val() == null) {
        globalUpdateChild($(parent).val(), child, JSONURL, defaultOptionText);
    }
    //Add a change event to the important dropdown
    $(parent).change(function() { globalUpdateChild(this.value, child, JSONURL, defaultOptionText, keyName); });

    $("#newOrUsedNew").click(function() { globalUpdateChild($(parent).val(), child, JSONURL, defaultOptionText, keyName); });
    $("#newOrUsedUsed").click(function() { globalUpdateChild($(parent).val(), child, JSONURL, defaultOptionText, keyName); });

    $("#priceFinderNew").click(function() { globalUpdateChild($(parent).val(), child, JSONURL, defaultOptionText, keyName); });
    $("#priceFinderCH").click(function() { globalUpdateChild($(parent).val(), child, JSONURL, defaultOptionText, keyName); });
}

//Helpers to populate the 'generic' lists - occasionaly these differ so are implemented locally
function globalUpdateChild(parentValue, childToUpdate, URL, defaultOptionText, keyName) {
    //Trigger the loading message
    $(childToUpdate).loadingDropdown();
    
    if (defaultOptionText == null) {
        defaultOptionText = "Choose a model";
    }

    //Check for newOrUsed
    var newOrUsedVal = $("input[name='newOrUsed']:checked").val();
    //check for newCar or contract hire
    var newCarOrCHVal = $("input[name='priceType']:checked").val();  //$("#priceFinder:checked").val();
    
    //Request the data
    if (keyName == null) {
        $.getJSON(URL, { makeId: parentValue, newOrUsed: newOrUsedVal }, function(json) { globalEndUpdateChild(json, childToUpdate, defaultOptionText); });
    }
    else if (keyName == 'FindAPrice') {
    $.getJSON(URL, { makeId: parentValue, priceType: newCarOrCHVal }, function(json) { globalEndUpdateChild(json, childToUpdate, defaultOptionText); });
}
    else {
        for (var i in keyName) {
            keyName[i] = parentValue;
        }
        keyName.newOrUsed = newOrUsedVal;

        $.getJSON(URL, keyName, function(json) { globalEndUpdateChild(json, childToUpdate, defaultOptionText); });
    }
}

function globalEndUpdateChild(json, childToUpdate, defaultOptionText) {
    var modelList = buildFriendlyModelVersionList(json);

    //Remove the loading message
    $(childToUpdate).removeOptionDropdown(0);
    //Add the any item tag
    $(childToUpdate).addOptionDropdown(defaultOptionText, "null");
    //Fill up the dropdown
    $(childToUpdate).populateDropdown(modelList);
    //Re-enable the dropdown
    $(childToUpdate).removeAttr("disabled");
}

//A helper for building friendly model names from the 'standard' JSON object
function buildFriendlyModelVersionList(json) {
    //Because not all calls return all data, we have to double check what is available and display appropriately. This function may not cover all eventualities so is often duplicated elsewhere.
 
    var modelList = new Array();
    for (var i = 0; i < json.length; i++) {
        var item = new Object();
        item.value = json[i].id;

        var modelName = ((json[i].modelName == null) ? "" : json[i].modelName) + " " + ((json[i].name == null) ? "" : json[i].name) + " " + ((json[i].Name == null) ? "" : json[i].Name);
            
        var firstYear = (json[i].firstYear == null) ? "" : json[i].firstYear;
        var lastYear = (json[i].lastYear == null) ? "" : json[i].lastYear;
        var yearBadge = (firstYear == "" && lastYear == "")? "" : " (" + firstYear.toString().substr(2,2) + "-" + lastYear.toString().substr(2,2) + ")";
        if (lastYear == "" && firstYear !="") {
            yearBadge = " (" + firstYear.toString().substr(2, 2) + "-)";
        }
        
        item.text = modelName + yearBadge;
        modelList.push(item);
    }
    return (modelList);
}
 
//jQuery functions for clearing and populating the dropdown.
//PRA
$.fn.emptyDropdown = function(fromIndex) {
    return this.each(function() {
        if (this.tagName == "SELECT")
            this.options.length = fromIndex;
    });
}

$.fn.populateDropdown = function(data) {
    return this.emptyDropdown(1).each(function() {
        if (this.tagName == "SELECT") {
            var dropdown = this;
            $.each(data, function(index, pairs) {
                $(dropdown).addOptionDropdown(pairs.text, pairs.value);
            });
        }
    });
}

$.fn.loadingDropdown = function() {
    return this.emptyDropdown(0).each(function() {
        if (this.tagName == "SELECT") {
            var dropdown = this;
            $(dropdown).attr("disabled", true);
            $(dropdown).addOptionDropdown("Loading...", "");
        };
    });
}

$.fn.addOptionDropdown = function(itemText, itemValue) {
    return this.each(function() {
        if (this.tagName == "SELECT") {
            var dropdown = this;
            var option = new Option(itemText, itemValue);

            if ($.browser.msie) {
                dropdown.add(option);
            }
            else {
                dropdown.add(option, null);
            }
        }
    });
}

$.fn.removeOptionDropdown = function(index) {
    return this.each(function() {
        if (this.tagName == "SELECT") {
            var dropdown = this;
            dropdown.remove(index);
        }
    });
}