// Define the API app
var g_szAppName = 'CalTrend';
$ = jQuery;

// Handle always loading vehicle selections by class
$(document).ready(function() {
	var objVehicleDropdownArea = $('.vehicle-dropdowns');
	if (objVehicleDropdownArea.length > 0) {
		objVehicleDropdownArea.each(function () {
			var
				objYear = $('.vehicle-year select:first', this),
				objMake = $('.vehicle-make select:first', this),
				objModel = $('.vehicle-model select:first', this),
				objSubModel = $('.vehicle-submodel select:first', this);
			
			// Validity check
			if (objYear.length == 0 || objMake.length == 0 || objModel.length == 0 || objSubModel.length == 0) { return; }
			
			// Handle API functionality
			API_Vehicles(objYear, objMake, objModel, objSubModel);
			
			// Handle form submission
			$('form[name="frmVehicleSelection"]').submit(handleVehicleFormSubmit);
		});
	}
});

// Vehicle API Functions
function API_Vehicles(yearDropdown, makeDropdown, modelDropdown, subModelDropdown, callbackFunction) {
	/// <summary>Prepares the vehicle dropdowns to dynamically load the data.</summary>
	/// <param name="yearDropdown">A jQuery selector for the year dropdown.</param>
	/// <param name="makeDropdown">A jQuery selector for the make dropdown.</param>
	/// <param name="modelDropdown">A jQuery selector for the model dropdown.</param>
	/// <param name="subModelDropdown">A jQuery selector for the model dropdown.</param>
	/// <param name="callbackFunction">[Optional] A callback function to execute after this method completes.</param>
	
	// Validity check
	if (!yearDropdown || !makeDropdown || !modelDropdown || !subModelDropdown) { return; }
	
	// Get the objects
	var
		ddlYears = $(yearDropdown).addClass('year-dropdown'), ddlMakes = $(makeDropdown).addClass('make-dropdown'),
		ddlModels = $(modelDropdown).addClass('model-dropdown'), ddlSubModels = $(subModelDropdown).addClass('submodel-dropdown');
	
	// Add validation elements
	ddlYears.each(function () {
		var objThis = $(this);
		$('<div>').attr('id', objThis.attr('id') + '-rfv').attr('class', 'errormsg').css({ 'display': 'none' }).text('Vehicle Year is required').insertBefore(objThis);

		// Reset the dropdown
		disableDropdown(this, 'Loading Years...');
	});
	ddlMakes.each(function () {
		var objThis = $(this);
		$('<div>').attr('id', objThis.attr('id') + '-rfv').attr('class', 'errormsg').css({ 'display': 'none' }).text('Vehicle Make is required').insertBefore(objThis);

		// Reset the dropdown
		disableDropdown(this, 'Select Make');
	});
	ddlModels.each(function () {
		var objThis = $(this);
		$('<div>').attr('id', objThis.attr('id') + '-rfv').attr('class', 'errormsg').css({ 'display': 'none' }).text('Vehicle Model is required').insertBefore(objThis);

		// Reset the dropdown
		disableDropdown(this, 'Select Model');
	});
	ddlSubModels.each(function () {
		var objThis = $(this);

		// Reset the dropdown
		disableDropdown(this, 'Select SubModel');
	});
	
	// Create the callback to load submodels (callbacks must be created in reverse since they will reference each other)
    var fLoadSubModels = function (response) {
        // Load the data into the dropdown
		// Load the data into the dropdown
		ddlSubModels.each(function () {
			var objThis = $(this);
			enableDropdown(this, 'Select SubModel');
        
			if (!response || !response.length || (response.length == 1 && !response[0])) {
				$('<option>').val('').text('All SubModels').appendTo(objThis.empty());
			} else {
				$(response).each(function (i, data) {
					$('<option>').val(data).text(data).appendTo(objThis);
				});
			}
		});
    };
	
	// Create the callback to load models
	var fLoadModels = function (response) {
		if (!response) { return; }

		// Load the data into the dropdown
		ddlModels.each(function () {
			var objThis = $(this);
			
			enableDropdown(this, 'Select Model');
			$(response).each(function (i, data) {
				$('<option>').val(data).text(data).appendTo(objThis);
			});
		});
	};

	// Create the callback to load makes
	var fLoadMakes = function (response) {
		if (!response) { return; }

		// Load the data into the dropdown
		ddlMakes.each(function () {
			var objThis = $(this);
			
			enableDropdown(this, 'Select Make');
			$(response).each(function (i, data) {
				$('<option>').val(data).text(data).appendTo(objThis);
			});
		});
	};

	// Create the callback to load years
	var fLoadYears = function (response) {
		if (!response) { return; }

		// Load the years into the dropdown
		ddlYears.each(function () {
			var objThis = $(this);

			enableDropdown(this, 'Select Year');
			$(response).each(function (i, data) {
				$('<option>').val(data).text(data).appendTo(objThis);
			});
		});
	};

	// Add the event handlers
	ddlYears.change(function () {
		// Get objects
		var objThis = $(this);

		// Validity check
		if (!Validate(objThis, false)) { return; }

		// Get the vehicle year
		var nYear = objThis.val();

		// Prepare the makes dropdown
		ddlMakes.each(function () { disableDropdown(this, 'Loading Makes...'); });
		// Prepare the models dropdown
		ddlModels.each(function () { disableDropdown(this, 'Select Model'); });
		// Prepare the submodels dropdown
		ddlSubModels.each(function () { disableDropdown(this, 'Select SubModel'); });

		// Update the other Year dropdowns
		ddlYears.attr('selectedIndex', objThis.attr('selectedIndex'));

		// Load the makes
		API('Vehicles_GetMakes', fLoadMakes, { _year: nYear });
	});
	ddlMakes.change(function () {
		// Get objects
		var objThis = $(this);
		var objYears = $('.year-dropdown', objThis.closest('dl'));

		// Validity check
		if (!Validate(objYears, false) || !Validate(objThis, false)) { return; }

		// Get the vehicle year and make
		var nYear = objYears.val(), szMake = objThis.val();

		// Prepare the models dropdown
		ddlModels.each(function () { disableDropdown(this, 'Loading Models...'); });
		// Prepare the submodels dropdown
		ddlSubModels.each(function () { disableDropdown(this, 'Select SubModel'); });

		// Update the other Make dropdowns
		ddlMakes.attr('selectedIndex', objThis.attr('selectedIndex'));

		// Load the models
		API('Vehicles_GetModels', fLoadModels, { _year: nYear, _make: szMake });
	});
	ddlModels.change(function () {
		// Get objects
		var objThis = $(this);
		var objYears = $('.year-dropdown', objThis.closest('dl'));
		var objMakes = $('.make-dropdown', objThis.closest('dl'));
		
		// Validity check
		if (!Validate(objYears, false) || !Validate(objMakes, false) || !Validate(objThis, false)) { return; }
		
		// Get the vehicle year and make
		var nYear = objYears.val(), szMake = objMakes.val(), szModel = objThis.val();
		
		// Prepare the submodels dropdown
		ddlSubModels.each(function () { disableDropdown(this, 'Loading SubModels...'); });

		// Update the other Model dropdowns
		ddlModels.attr('selectedIndex', objThis.attr('selectedIndex'));
		
		// Load the submodels
		API('Vehicles_GetSubModels', fLoadSubModels, { _year: nYear, _make: szMake, _model: szModel });
	});

	// Load the vehicle years
	API('Vehicles_GetYears', fLoadYears);
}

function disableDropdown(disableDropdown, displayText, callbackFunction) {
	/// <summary>Resets a dropdown and disables it with the supplied displayText.</summary>
	/// <param name="disableDropdown">The jQuery selector for a dropdown to reset.</param>
	/// <param name="displayText">The text to display while the dropdown is in a disabled state.</param>
	/// <param name="callbackFunction">[Optional] A callback function to execute after this method completes.</param>
	
	// Get the callback function
	var fCallback;
	if (arguments.length > 2 && $.isFunction(callbackFunction)) { fCallback = callbackFunction; }
	else { fCallback = g_fDummyFunction; }
	
	// Validity check
	if (!disableDropdown || !displayText) { fCallback(false); return; }
	var objDropdown = $(disableDropdown);
	if (objDropdown.length == 0) { fCallback(false); return; }
	
	// Reset the dropdown
	objDropdown.empty().attr('disabled', 'disabled');
	$('<option>').val('-1').text(displayText).appendTo(objDropdown);
	
	fCallback(true);
}
function enableDropdown(enableDropdown, displayText, callbackFunction) {
	/// <summary>Resets a dropdown and enables it with the supplied displayText.</summary>
	/// <param name="enableDropdown">The jQuery selector for a dropdown to reset.</param>
	/// <param name="displayText">The text to display as the initial value of the dropdown.</param>
	/// <param name="callbackFunction">[Optional] A callback function to execute after this method completes.</param>
	
	// Get the callback function
	var fCallback;
	if (arguments.length > 2 && $.isFunction(callbackFunction)) { fCallback = callbackFunction; }
	else { fCallback = g_fDummyFunction; }
	
	// Validity check
	if (!enableDropdown || !displayText) { fCallback(false); return; }
	var objDropdown = $(enableDropdown);
	if (objDropdown.length == 0) { fCallback(false); return; }
	
	// Reset the dropdown
	objDropdown.empty().removeAttr('disabled');
	$('<option>').val('-1').text(displayText).appendTo(objDropdown);
	
	fCallback(true);
}
function handleVehicleFormSubmit(e) {
	/// <summary>Handles the submit event for the vehicle selection form.</summary>
	/// <param name="e">The event that triggered this method.</param>

	// Get the form
	var objForm = $(this);
	if (!objForm.is('form')) { return; }
	
	// Resize the parts list
	var objPartsList = $('#part-results');
	if (objPartsList.length == 0) { return; }
	var bResizedPartsList = true;
	
	// Prevent the event
	e.preventDefault();
	
	// Create the callback function
	var fLoadParts = function (response) {
		// Load the parts list
		objPartsList.empty();
		
		var objResponse = { SeatGroups: response };
    	var objTemplate = $('#tmplPart').tmpl(objResponse);
		objTemplate.css({position:'absolute', left: -20000}).insertAfter(objPartsList);
		var nHeight = objTemplate.outerHeight() + 20;
		objTemplate.removeAttr('style').css({height: 0});
		
		objPartsList.replaceWith(objTemplate);
		objPartsList = objTemplate;
		objPartsList.animate({height: nHeight}, { duration: 600 });
	};
	
	var fApiCallback = function (response) {
		if (bResizedPartsList) {
			fLoadParts(response);
		} else {
			setTimeout(function() { fApiCallback(response); }, 100);
		}
	};
	
	// Get the API results
	var objYear = $('.year-dropdown', objForm), objMake = $('.make-dropdown', objForm), objModel = $('.model-dropdown', objForm), objSubModel = $('.submodel-dropdown', objForm);
	var szSubModel = objSubModel.val();
	if (szSubModel == '-1') { szSubmodel = ''; }
	API('Vehicles_GetProducts', fApiCallback, { _year: parseInt(objYear.val(), 10), _make: objMake.val(), _model: objModel.val(), _submodel: szSubModel });
}
