// http://bby.met004.local/installernet/client/get-guide-data

if (typeof PRPL == 'undefined') {
    PRPL = {};
}

if (typeof PRPL.MET004 == 'undefined') {
    PRPL.MET004 = {};
}


function sortSelect(selElem) {
                var tmpAry = new Array();
                for (var i=0;i<selElem.options.length;i++) {
                        tmpAry[i] = new Array();
                        tmpAry[i][0] = selElem.options[i].text;
                        tmpAry[i][1] = selElem.options[i].value;
                }
                tmpAry.sort();
                while (selElem.options.length > 0) {
                    selElem.options[0] = null;
                }
                for (var i=0;i<tmpAry.length;i++) {
                        var op = new Option(tmpAry[i][0], tmpAry[i][1]);
                        selElem.options[i] = op;
                }
                return;
        }
//
// Populate the select boxes based on the type and data array.
// type is one of:
// + make
// + model
// + year
// + body
// + trim
//
// And the data array comes in the form array( id => label )
//
PRPL.MET004.guidePopulate = function ( type, data ) {
    // Get the requested select
    var element = $('#VFG > form > fieldset > select#'+type);

    // Empty its contents and load the new content
    element.empty();

    var defaultLabel = 'Select ';

    switch(type){
        case "make":
            defaultLabel = defaultLabel + 'Vehicle Make';

        break;
            case "model":
            defaultLabel = defaultLabel + 'Model';
        break;

        case "year":
            defaultLabel = defaultLabel + 'Year';
        break;

        case "body":
            defaultLabel = defaultLabel + 'Vehicle Body';
        break;

        case "trim":
            defaultLabel = defaultLabel + 'Vehicle Trim';
        break;
    }

    element.append(
            '<option value="">'+ defaultLabel +'</option>'
        );
var item = "";
var temp = new Array();
    $.each(data, function( index, label ) {
	
		if (type == 'make')
		{
			item = label + "_" + index;
			temp.push(item);
		}
	
        // Append options from data array
        if (type == 'trim' && label == '') {
            label = 'N/A';
            element.empty();
            // If there are no trim options, just allow to submit...otherwise have to choose first...then submit
            $('button#submit').removeAttr('disabled');
        }

		// If we're doing the make we want to use our forced sort for chrome and IE
		if (type != 'make')
		{
	        element.append(
	            '<option value="'+ index +'">'+ label +'</option>'
	        );
		}

    }); // END each


	// Hack to get json to sort correct for chrome and IE
	temp.sort();

	if (type == 'make')
	{
		for (i=0; i<temp.length; i++)
		{
			item = temp[i];
			item = item.split("_");
			element.append(
	            '<option value="'+ item[1] +'">'+ item[0] +'</option>'
			);
		}
	}


			$('select#make, select#body, select#trim, select#category').selectmenu({
				style:'dropdown',
				width:239,
                                maxHeight:180
			});
			$('select#model').selectmenu({
				style:'dropdown',
				width:130
			});
			$('select#year').selectmenu({
				style:'dropdown',
				width:100
			});
}

PRPL.MET004.handleUnavailable = function(data)
{
    if (data == 'unavailableError') {
        $("#VFG").html('<div class="message notice"><p>The Vehicle Fit Guide service is currently unavailable.</p></div>');
        return false;
    }
    return true;
}

// Add event hooks
$(document).ready(function () {

    var guideEndpoint = '/api-guide-data';

    // Initial Fill of all categories
    $.getJSON(
        guideEndpoint,
        function (data) {
            PRPL.MET004.guidePopulate('make', data.make);
            PRPL.MET004.guidePopulate('model', data.model);
            PRPL.MET004.guidePopulate('year',  data.year);
            PRPL.MET004.guidePopulate('body',  data.body);
            PRPL.MET004.guidePopulate('trim',  data.trim);
            $('select#make, select#body, select#trim, select#category').selectmenu({
                    style:'dropdown',
                    width:239
            });
            $('select#model').selectmenu({
                    style:'dropdown',
                    width:130
            });
            $('select#year').selectmenu({
                    style:'dropdown',
                    width:100
            });
        } // END callback
    ); // END getJSON

    // Starting State
    $('select#model').attr('disabled', true);
    $('select#year').attr('disabled', true);
    $('select#body').attr('disabled', true);
    $('select#trim').attr('disabled', true);
    $('button#submit').attr('disabled', true);

    // If Changed
    $('select#make').change(function () {
        $('#ajax_loading').show();
        $('select#model').attr('disabled', true);
        $('select#year').attr('disabled', true);
        $('select#body').attr('disabled', true);
        $('select#trim').attr('disabled', true);
        $('button#submit').attr('disabled', true);
        //alert($(this).val());
        $.getJSON(
            guideEndpoint + '/make/' + $(this).val(),
            function (data) {
                PRPL.MET004.guidePopulate('model', data.model);
                PRPL.MET004.guidePopulate('year',  data.year);
                PRPL.MET004.guidePopulate('body',  data.body);
                PRPL.MET004.guidePopulate('trim',  data.trim);

                // Must enable, drop classes, destroy selectmenu, and recreate for jQueryUI selectmenu to work
                $('select#model').attr('disabled', false);
                $('select#model').attr('class', '');
                $('select#model').selectmenu('destroy');
                $('select#model').selectmenu({
                    style:'dropdown',
                    width:130,
                    maxHeight:145
                });
                $('#ajax_loading').hide();

            } // END callback

        ); // END getJSON

    }); // END #guide-select-make.change()

    $('select#model').change(function () {
        $('ajax_loading').show();
        $('select#year').attr('disabled', true);
        $('select#body').attr('disabled', true);
        $('select#trim').attr('disabled', true);
        $('button#submit').attr('disabled', true);

        $.getJSON(
            guideEndpoint + '/make/'  + $('select#make').val()
                          + '/model/' + $(this).val(),

            function (data) {
                PRPL.MET004.guidePopulate('year',  data.year);
                PRPL.MET004.guidePopulate('body',  data.body);
                PRPL.MET004.guidePopulate('trim',  data.trim);

                $('select#year').attr('disabled', false);
                $('select#year').attr('class', '');
                $('select#year').selectmenu('destroy');
                $('select#year').selectmenu({
                    style:'dropdown',
                    width:100,
                    maxHeight:145
                });
                $('#ajax_loading').hide();

            } // END callback

        ); // END getJSON

    }); // END #guide-select-model.change()

    $('select#year').change(function () {
        $('#ajax_loading').show();
        $('select#body').attr('disabled', true);
        $('select#trim').attr('disabled', true);
        $('button#submit').attr('disabled', true);

        $.getJSON(
            guideEndpoint + '/make/'  + $('select#make').val()
                          + '/model/' + $('select#model').val()
                          + '/year/'  + $(this).val(),
            function (data) {
                PRPL.MET004.guidePopulate('body',  data.body);
                PRPL.MET004.guidePopulate('trim',  data.trim);

                $('select#body').attr('disabled', false);
                $('select#body').attr('class', '');
                $('select#body').selectmenu('destroy');
                $('select#body').selectmenu({
                    style:'dropdown',
                    width:239,
                    maxHeight:145
                });
                $('#ajax_loading').hide();
            } // END callback

        ); // END getJSON

    }); // END #guide-select-year.change()

    $('select#body').change(function () {
        $('#ajax_loading').show();
        $('select#trim').attr('disabled', true);
        $('button#submit').attr('disabled', true);

        $.getJSON(
            guideEndpoint + '/make/'  + $('select#make').val()
                          + '/model/' + $('select#model').val()
                          + '/year/'  + $('select#year').val()
                          + '/body/'  + $(this).val(),
            function (data) {
                PRPL.MET004.guidePopulate('trim',  data.trim);

                $('select#trim').attr('disabled', false);
                $('select#trim').attr('class', '');
                $('select#trim').selectmenu('destroy');
                $('select#trim').selectmenu({
                    style:'dropdown',
                    width:239,
                    maxHeight:145
                });

                $('#ajax_loading').hide();

            } // END callback

        ); // END getJSON

    }); // END #guide-select-year.change()

    $('select#trim').change(function () {
        $('button#submit').removeAttr('disabled');
    }); // END #guide-select-year.change()


});

