/**
 * OptionPropertiesContainer (VO)
 * @param value
 * @param text
 * @param selected
 */
function OptionPropertiesContainer(value, text, selected)
{
	this.Value = value;
	this.Text = text;
	this.Selected = selected ? true : false;
}

OptionPropertiesContainer.prototype = {
	toHtml: function() {
		return '<option value="' + this.Value + '"' +
			(this.Selected ? ' SELECTED' : '') +
			'>' + 
			this.Text  + 
			'</option>';
	}
}

var Voi = function(defaults) {
	this.defaults = defaults;
}

Voi.prototype = {
	usedAndCertifedEnabled : undefined,
	vehicles : { 'new':{}, 'preowned':{}, 'used':{}, 'certified':{} },
	dontDefault: false,
	//
	buildOptions : function(array, firstOption, selectedOption) {
		this.dontDefault = (selectedOption === "") || this.dontDefault;
		var options = new OptionPropertiesContainer('', firstOption, this.dontDefault).toHtml();
		if (array != undefined) {
			for (i=0; i < array.length; i++) {
				if (typeof array[i] === "string")
					array[i] = new OptionPropertiesContainer(array[i], array[i]);
				array[i].Selected = (!this.dontDefault && (array[i].Value == selectedOption));
				options += array[i].toHtml();
			}
		}
		return options;
	},
	disableSelect : function(name) {
		jQuery(name).attr("disabled", true);
		// back to default selection
		jQuery(name).attr("selectedIndex",0);
	},
	hideSelect : function(name) {
		// only hide element if it's not required
		if (jQuery(name).length > 0) {
			if (!this.isRequired(name)) { jQuery(name).parent().addClass("hidden"); }
		}
	},
	enableSelect : function(name) {
		jQuery(name).attr("disabled", false);
	},
	showSelect : function(name) {
		jQuery(name).parent().removeClass("hidden");
	},
	getVehicleType : function() {
		return jQuery("#select_vehicleType").val();
	},
	getVehicleYear : function() {
		return jQuery("#select_year").val();
	},
	alreadyExist : function(array, key) {
		for (i=0; i < array.length; i++) {
			if (array[i]== key) {
				return true;
			}
		}
		return false;
	},
	// test markup for both forms A and B
	isRequired : function(name) {
		return ((jQuery(name).attr("class").indexOf("validate[required]") != -1) || (jQuery(name).attr("required") == ""));
	},
	setType: function(defaultType) {
		var optionsList = [];
		optionsList.push(new OptionPropertiesContainer('new', 'New', defaultType === 'new'));
		// This is used by GM, Saab, etc.
		if ( this.vehicles && this.vehicles.preowned && this.vehicles.preowned.years && this.vehicles.preowned.years.length > 0) {
			optionsList.push(new OptionPropertiesContainer('preowned', 'PreOwned', defaultType === 'preowned'));
		}
		// This is used by VW
		if ( this.vehicles && this.vehicles.certified && this.vehicles.certified.years && this.vehicles.certified.years.length > 0) {
			optionsList.push(new OptionPropertiesContainer('certified', 'Certified', defaultType === 'certified'));
		}
		// This is used by VW
		if ( this.vehicles && this.vehicles.used && this.vehicles.used.years && this.vehicles.used.years.length > 0) {
			optionsList.push(new OptionPropertiesContainer('used', 'Used', defaultType === 'used'));
		}
		
		// Show on undefined because this was the default behavior, in the new jsp this value will be set based on the 
		// configuration to either true or false.  In this case only display if true
		if(Cobalt === undefined || Cobalt.PageOptions === undefined || Cobalt.PageOptions.choiceUndecidedIsDisplayed === undefined || Cobalt.PageOptions.choiceUndecidedIsDisplayed) {
			optionsList.push(new OptionPropertiesContainer('undecided', 'Undecided', defaultType === 'undecided'));
		}
		
		var options = this.buildOptions(optionsList, "Choose Vehicle Type", defaultType);
		jQuery("#select_vehicleType").html(options).trigger('change');
	}
};

jQuery(document).ready(function() {
	// Do not proceed if A/B test has chosen old form
	if (jQuery("#select_year").length < 1) { return; }
	
	var defaults = {};
	defaults.type = jQuery.query.get('search');
	defaults.type = (defaults.type === 'used' || defaults.type === 'certified') ? 'preowned' : defaults.type;
	defaults.year = jQuery.query.get('vehicle:buy:year');
	defaults.make = jQuery.query.get('vehicle:buy:make');
	defaults.model = jQuery.query.get('vehicle:buy:model');
		
	var voi = new Voi(defaults);
	
	// Hide vehicle drop-downs if not required
	voi.hideSelect("#select_year");
	voi.hideSelect("#select_make");
	voi.hideSelect("#select_model");
	voi.disableSelect("#select_year");
	voi.disableSelect("#select_make");
	voi.disableSelect("#select_model");
	//
	jQuery.ajax({
        type: "GET",
        url: "getVehicleOfInterest.do",
        dataType: "xml",
        success: function(xml) {
			jQuery(xml).find('Vehicle').each(function() {
				var type = jQuery(this).find('type').text();
				var year = jQuery(this).find('year').text();
				var make = jQuery(this).find('make').text();
				var model = jQuery(this).find('model').text();
				
				//building type (new vs preowned)
				if (voi.vehicles[type] == undefined) {
				   voi.vehicles[type]={};
				}
				if (voi.vehicles[type].years == undefined) {
					voi.vehicles[type].years=[];
				}

				if (!voi.alreadyExist(voi.vehicles[type].years,year)) {
				  voi.vehicles[type].years[voi.vehicles[type].years.length]=year;
				}

				//building type/year
				if (voi.vehicles[type][year] == undefined) {
					voi.vehicles[type][year]={};
				}

				if (voi.vehicles[type][year].makes == undefined) {
					voi.vehicles[type][year].makes = [];
				}

				if (!voi.alreadyExist(voi.vehicles[type][year].makes,make)) {
				  voi.vehicles[type][year].makes[voi.vehicles[type][year].makes.length]=make;
				}

				//building type/year/make
				if (voi.vehicles[type][year][make] == undefined) {
					voi.vehicles[type][year][make]={};
				}

				if (voi.vehicles[type][year][make].models == undefined) {
					voi.vehicles[type][year][make].models = [];
				}

				if (!voi.alreadyExist(voi.vehicles[type][year][make].models,model)) {
				  voi.vehicles[type][year][make].models[ voi.vehicles[type][year][make].models.length]=model;
				}
			}); // end each
			voi.setType(voi.defaults.type);
        } // end Success
    });	// end AJAX
	//
	jQuery("#select_vehicleType").bind("change", function(){
		var type = voi.getVehicleType();
		//
		voi.dontDefault = voi.dontDefault || (type != voi.defaults.type);
		if (type == "" || type == "undecided") {
			voi.hideSelect("#select_year");
			voi.hideSelect("#select_make");
			voi.hideSelect("#select_model");
			voi.disableSelect("#select_year");
			voi.disableSelect("#select_make");
			voi.disableSelect("#select_model");
			jQuery("#yearGroup").hide();
			jQuery("#makeGroup").hide();
			jQuery("#modelGroup").hide();
		} else {
			jQuery("#yearGroup").show();
			jQuery("#makeGroup").show();
			jQuery("#modelGroup").show();
			voi.enableSelect("#select_year");
			voi.showSelect("#select_year");
			voi.showSelect("#select_make");
			voi.showSelect("#select_model");
			// USING HARD-CODED VALUE FOR A/B TEST. Should use <fmt:message bundle="${web}" key="SELECT.A.YEAR" />
			var options = voi.buildOptions(voi.vehicles[type].years, "Select a Year", voi.defaults.year);
			jQuery("#select_year").html(options).trigger('change');
		}
    });
	//
	jQuery("#select_year").change(function(){
		// If 'vehicle type' fields are not displayed, then set type to 'new'
		var type = (voi.getVehicleType() == "") ? 'new' : voi.getVehicleType();
		var year = voi.getVehicleYear();
		voi.dontDefault = voi.dontDefault || (year != voi.defaults.year);
		//
		if (year != "") {
			voi.enableSelect("#select_make");
			// USING HARD-CODED VALUE FOR A/B TEST. Should use <fmt:message bundle="${web}" key="SELECT.A.MAKE" />
			var options = voi.buildOptions(voi.vehicles[type][year].makes, "Select a Make", voi.defaults.make);
			jQuery("#select_make").html(options).trigger('change');
		} else {
			voi.disableSelect("#select_make");
			voi.disableSelect("#select_model");
		}
    });
	//
	jQuery("#select_make").change(function(){
		// If 'vehicle type' fields are not displayed, then set type to 'new'
		var type = (voi.getVehicleType() == "") ? 'new' : voi.getVehicleType();
		var year = voi.getVehicleYear();
		var make = jQuery(this).val();
		voi.dontDefault = voi.dontDefault || (make != voi.defaults.make);

		if (make != "") {
			voi.enableSelect("#select_model");
			// USING HARD-CODED VALUE FOR A/B TEST. Should use <fmt:message bundle="${web}" key="SELECT.A.MODEL" />
			var options = voi.buildOptions(voi.vehicles[type][year][make].models, "Select a Model", voi.defaults.model);
			jQuery("#select_model").html(options);
		} else {
			voi.disableSelect("#select_model");
		}
    });
});

