﻿// convenience function to create a new instance of the VehicleSelectBoxes class
function fillSelectBoxes(makeBoxId, modelBoxId) {
    var v = new VehicleSelectBoxes(makeBoxId, modelBoxId);
}

///
/// This class uses the two select boxes with the given
/// ids for vehicle selection.
///
function VehicleSelectBoxes(makeBox, modelBox) {
    this.makeBox = makeBox;
    this.modelBox = modelBox;
    
    // post-constructor
    this.init = function() {  
        this.clearBoxes();
        this.populateMake();
    }

    // adds items to select to the select box
    this.addOption = function(selectBox, name, value, isSelectedByDefault) {
        var sld = false;
        if (typeof isSelectedByDefault != 'undefined') {
            sld = isSelectedByDefault;
        }
        var option = new Option(name, value, sld, false);
        selectBox.options[selectBox.length] = option;
    }

    // sets the boxes to an "empty" state
    this.clearBoxes = function() {
        this.makeBox.options.length = 0;
        this.modelBox.options.length = 0;
        this.addOption(this.makeBox, 'Select a Make', '');
        this.addOption(this.modelBox, 'Select a Model', '');
    }

    // fill the make box
    this.populateMake = function() {
        var self = this; // handle scoping issues #1
        function handleResults(self) {
            return function(results) { // handle the scoping issues #2
                for (var i = 0; i < results.length; i++) {
                    self.addOption(self.makeBox, results[i].Value, results[i].Key);
                }
            };
        }
        new WebRequest().callWebMethod('GetActiveMakeList', '', handleResults(self));
    }

    this.populateModel = function(selectedId) {
        var self = this;
        function handleResults(self) {
            return function(results) {
            self.modelBox.options.length = 0;
                for (var i = 0; i < results.length; i++) {
                    self.addOption(self.modelBox, results[i], results[i]);
                }
            };
        }
        new WebRequest().callWebMethod('GetActiveModelListForDivisionId', 'divisionId=' + selectedId, handleResults(self));
    }

    this.handleMakeOnChange = function(self) {
        self.populateModel(self.makeBox.value);
    }

    // get the form that this element belongs to
    this.getForm = function(element) {
        var currentNode = element;
        while (currentNode.parentNode) {
            if (currentNode.NodeName.toLowerCase() == 'form') {
                return currentNode;
            }
        }
        return false;
    }

    this.init();
}

function getTrueCarPrice(styleId, callback) {
	$.get(
        "/services/DataService.svc/GetTrueCarPrice",
        { styleId: styleId },
        callback,
        "json"
    );
}

