﻿function searchVehicleLookupPanel(options) {
    this.makeDropDown = $(options.makeDropDownSelector);
    this.modelDropDown = $(options.modelDropDownSelector);
    this.seriesDropDown = $(options.seriesDropDownSelector);
    this.bodyTypeDropDown = $(options.bodyTypeDropDownSelector);
    this.locationDropDown = $(options.locationDropDownSelector);
    this.makeLookupUrl = options.makeLookupUrl;
    this.modelLookupUrl = options.modelLookupUrl;
    this.seriesLookupUrl = options.seriesLookupUrl;
    this.bodyTypeLookupUrl = options.bodyTypeLookupUrl;
    this.locationLookupUrl = options.locationLookupUrl;
    this.fieldLookupUrl = options.fieldLookupUrl;
    this.makeModelLookupOnly = options.makeModelLookupOnly;
    this.modelFirstOptionText = (options.modelFirstOptionText != null && options.modelFirstOptionText != '') ? options.modelFirstOptionText : 'Cars by Model';
    this.showLocation = options.showLocation;
    this.searchPattern = options.searchPattern;
    this.makeFirstOptionText = 'Cars by Make';
    this.bodyTypeFirstOptionText = 'Cars by Body Type';
    this.locationFirstOptionText = 'Cars by Location';

    this.init = function() {
        var panel = this;
        var selectedMake = $('option:selected', panel.makeDropDown).val();
        var selectedModel = $('option:selected', panel.modelDropDown).val();
        if (selectedMake == null || selectedMake == '') {
            this.modelDropDown.attr("disabled", "disabled");
        }

        this.seriesDropDown.attr("disabled", "disabled");
        this.makeDropDown.change(function() {
            resetModelDropDown(panel);
            fieldChanged(panel, panel.makeDropDown,true);
        });
        this.modelDropDown.change(function() { fieldChanged(panel, panel.modelDropDown,false) });
        this.bodyTypeDropDown.change(function() { fieldChanged(panel, panel.bodyTypeDropDown,false) });
        if (this.showLocation) {
            this.locationDropDown.change(function() { fieldChanged(panel, panel.locationDropDown,false) });
        }

        //if (selectedModel == null || selectedModel == '') {
        //    this.modelDropDown.attr("disabled", "disabled");
        //}
        //this.makeDropDown.change(function() { makeChanged(panel) });
        //if (!this.makeModelLookupOnly) {
        //    this.modelDropDown.change(function() {modelChanged(panel)});
        //}
    };
    return true;
}

function fieldChanged(panel, control,isMake) {
    var selection = false;
    var fieldValue = $('option:selected', control).val();
    
    var searchTerm = getSearchTerm(panel, isMake);
    var url = panel.fieldLookupUrl.replace('replaceSearchTerm', searchTerm);
    //TODO: Proper error handling if request fails
    $.getJSON(url, function(data) {            
        setSearchFieldsRequestCallback(data, panel)
    });
}

function setSearchFieldsRequestCallback(data, panel) {
    setTimeout(function() {
        $.each(data, function(i, item) {
            var controlToUpdate = null;
            var firstOptionText = '';
            var selectionValue = null;
            var isModel = false;
            var isMake = false;
            switch (item.FieldName) {
                case 'make':
                    controlToUpdate = panel.makeDropDown;
                    firstOptionText = panel.makeFirstOptionText;
                    selectionValue = $('option:selected', panel.makeDropDown).val();
                    isMake = true;
                    break;
                case 'model':
                    controlToUpdate = panel.modelDropDown;
                    firstOptionText = panel.modelFirstOptionText;
                    selectionValue = $('option:selected', panel.modelDropDown).val();
                    isModel = true;
                    break;
                case 'bodytype':
                    controlToUpdate = panel.bodyTypeDropDown;
                    firstOptionText = panel.bodyTypeFirstOptionText;
                    selectionValue = $('option:selected', panel.bodyTypeDropDown).val();
                    break;
                case 'location':
                    controlToUpdate = panel.locationDropDown;
                    firstOptionText = panel.locationFirstOptionText;
                    selectionValue = $('option:selected', panel.locationDropDown).val();
                    break;
            }
            if (controlToUpdate != null && firstOptionText != '') {
                controlToUpdate.empty().append('<option value="">' + firstOptionText + '</option>');
                $.each(item.FieldValues, function(j, listitem) {
                    $('<option />').attr('value', listitem.Value.replace(/\+/g, ' ')).text(listitem.Display).appendTo(controlToUpdate);
                });

                if (selectionValue != null && selectionValue != '') {
                    controlToUpdate.val(selectionValue);
                }
                //controlToUpdate.change(function() { fieldChanged(panel, controlToUpdate) });
                if (isMake) {
                    panel.modelDropDown.attr('disabled', '');
                }
            }

            //if (isModel) {
            //panel.modelDropDown.attr('disabled', '');
            //if (!panel.makeModelLookupOnly) {
            //    resetVehicleDropDown(panel);
            //    panel.seriesDropDown.attr('disabled', 'disabled');
            //}
            //panel.modelDropDown.change(function() { fieldChanged(panel, panel.modelDropDown) });
            //}
        });
        var makeSelection = $('option:selected', panel.makeDropDown).val();
        if (makeSelection == null || makeSelection == '') {
            panel.modelDropDown.attr('disabled', 'disabled');
        }
    }, 300);
}

function makeChanged(panel) {
    setModelDropDownLoading(panel);
    var selectedMake = $('option:selected', panel.makeDropDown).val();
    if (selectedMake != null && selectedMake != '') {
        var selectedMake = selectedMake.replace(/ /g, '+');
        var url = panel.modelLookupUrl.replace('replacewithmake', selectedMake);
        //TODO: Proper error handling if request fails
        $.getJSON(url, function(data, textStatus) {
            modelsForMakeRequestCallback(data, textStatus, panel)
        });
    }
}

function setModelDropDownLoading(panel) {
    panel.modelDropDown.empty().append('<option value="">Loading...</option>');
    panel.modelDropDown.attr('disabled', 'disabled');

    if (!panel.makeModelLookupOnly) {
        setVehicleDropDownLoading(panel);
    }
}

function setVehicleDropDownLoading(panel) {
    panel.seriesDropDown.empty().append('<option value="">Loading...</option>');
    panel.seriesDropDown.attr('disabled', 'disabled');
}

function resetModelDropDown(panel) {
    if (!panel.makeModelLookupOnly) {
        resetVehicleDropDown(panel);
    }
    panel.modelDropDown.empty().append('<option value="">' + panel.modelFirstOptionText +'</option>');
}

function resetVehicleDropDown(panel) {
    panel.seriesDropDown.empty().append('<option value="">Cars by Series</option>');
}

function modelsForMakeRequestCallback(data, textStatus, panel) {
    setTimeout(function() {
        panel.modelDropDown.empty().append('<option value="">' + panel.modelFirstOptionText + '</option>');
        $.each(data, function(i, item) {
            $('<option />').attr('value', item.ModelValue.replace(/\+/g,' ')).text(item.ModelDisplay).appendTo(panel.modelDropDown);
        });
        panel.modelDropDown.attr('disabled', '');
        if (!panel.makeModelLookupOnly) {
            resetVehicleDropDown(panel);
            panel.seriesDropDown.attr('disabled', 'disabled');
        }
    }, 300);
}

function refreshMakes(panel) {
    $.getJSON(panel.makeLookupUrl, function(data, textStatus) {
        makeRequestCallback(data, textStatus, panel); 
    });
}

function makeRequestCallback(data, textStatus, panel) {
    $.each(data, function(i, item) {
        $('<option />').attr('value', item.MakeValue).text(item.MakeDisplay).appendTo(panel.makeDropDown);
    });
}

function modelChanged(panel) {
    if (!panel.makeModelLookupOnly) {
        setVehicleDropDownLoading(panel);
    }
    var selectedMake = $('option:selected', panel.makeDropDown).val();
    var selectedModel = $('option:selected', panel.modelDropDown).val();
    if (selectedMake != null && selectedModel != null && selectedMake != '' && selectedModel != '') {
        var selectedMake = selectedMake.replace(/ /g, '+');
        var selectedModel = selectedModel.replace(/ /g, '+');
        var url = panel.seriesLookupUrl.replace('replacewithmake', selectedMake).replace('replacewithmodelconfiguration', selectedModel);
        //TODO: Proper error handling if request fails
        $.getJSON(url, function(data, textStatus) {
            vehiclesForModelRequestCallback(data, textStatus, panel);
        });
    }
}

function vehiclesForModelRequestCallback(data, textStatus, panel) {
    setTimeout(function() {
        resetVehicleDropDown(panel);
        $.each(data, function(i, item) {
            if (item.VehicleDisplay == null) { item.VehicleDisplay = "NULL" }
            $('<option />').attr('value', item.VehicleValue).text(item.VehicleDisplay).appendTo(panel.seriesDropDown);
        });
        panel.seriesDropDown.attr('disabled', '');
    }, 500);
}

function resetMakeDropDown(panel) {
    resetModelDropDown(panel);
    panel.makeDropDown.empty().append('<option value="">Cars by Make</option>');
}

function formatString(stringvalue) {
    var formattedvalue = '';
    if (stringvalue != null) {
        formattedvalue = stringvalue.replace(/ /g, '+');
    }
    return formattedvalue;
}

function getSearchTerm(panel, isForMake) {
    var selectedMake = $('option:selected', panel.makeDropDown).val();
    var selectedModel = $('option:selected', panel.modelDropDown).val();
    var selectedBodyType = $('option:selected', panel.bodyTypeDropDown).val();

    selectedMake = formatString(selectedMake);
    if (isForMake) {
        selectedModel = '';
    } else {
        selectedModel = formatString(selectedModel);
    }
    selectedBodyType = formatString(selectedBodyType);


    var searchTerm = panel.searchPattern.replace("make", selectedMake).replace("model", selectedModel).replace("bodyType", selectedBodyType);
    if (panel.showLocation) {
        var selectedLocation = $('option:selected', panel.locationDropDown).val();
        selectedLocation = formatString(selectedLocation);
        searchTerm = searchTerm.replace("location", selectedLocation);
    }

    return searchTerm;
}