(function ($) {
	var allowMessage = true;	
	
	var FastQuote = DDC.FastQuote = {	// setup local and global aliases for FastQuote
		data: {},
		call: new ApiCall(),
		models: null,
		loadingDiv: '#' + 'q_loading',
		currentData: null,
        franchises: new Array(),
        selectLabel: {
            model: '',
            trim: ''
        },

        init: function (data) {
			this.data = data;
			this.call.reseller = 'ddc';
			this.call.accountId = this.data.accountId;
			this.call.service = 'builder';
			this.franchises = this.data.franchises;
            this.selectLabel.model =  $('#fastQuoteForm label.model option:eq(0)').text();
            this.selectLabel.trim =  $('#fastQuoteForm label.trim option:eq(0)').text();
            $('#fastQuoteForm select').each(function(){
				if(this.name == "make" || this.name == "model" || this.name == "trim") {
					$('option:gt(0)',this).remove();
				}
			});
            $('#fastQuoteForm .make select, #fastQuoteForm .model select, #fastQuoteForm .trim select').change(function () { DDC.FastQuote.selectOnChange(this); });
			$('#fastQuote .widgetWrap').prepend(this.data.message);			
			$('#fastQuoteForm select[name=model]').attr('disabled', 'true');	//disables all select boxes after the first
			$('#fastQuoteForm select[name=trim]').attr('disabled', 'true');	//disables all select boxes after the first
			this.doLoadMakes();
		},

		get: function(formElementName, returnJQueryObject) { //gets form element by name
			if (returnJQueryObject) {	//return jquery result if true
				return $('#fastQuoteForm select[name=' + formElementName + ']');
			} else {//return html object requested
				return $('#fastQuoteForm select[name='+formElementName+']').get(0);
			}
		},

		doLoadMakes: function() {
			var select = this.get('make');
			for(var i=0;i<this.franchises.length;i++) {
				select.options[select.length] = new Option(this.franchises[i], this.franchises[i]);
			};
			this.autoSelect(select);	//if only one option, autoselect and load for the next selectbox
		},

		doLoadModels: function( make ) {
			this.call.operation = 'models';
			this.call.callback = 'DDC.FastQuote.buildModels';
			this.call.param( 'make', make );
			this.call.execute();
		},

		buildModels: function(data) {
            this.currentData = data;
			var select = this.get('model');
            var d = new Date();
            var minYear = (this.data.minYear) ? this.data.minYear : 0;
            var maxYear = (this.data.maxYear) ? this.data.maxYear : d.getFullYear() + 1;
			select.options[0] = new Option(this.selectLabel.model,'');
			for(var mdl in data.models) {
                //check for ie
                if(data.models[mdl].modelYear){
                    if(data.models[mdl].modelYear > minYear && data.models[mdl].modelYear < maxYear){
                        select.options[select.length] = new Option(this.modelToString(data.models[mdl]),mdl);
                    }
                }
			}
			$('#model').show();
			this.get('trim').options[0] = new Option(this.selectLabel.trim,'');
			this.get('model').disabled = false;	//reenables 'model' selectbox after ajax write
			this.autoSelect(select);	//if only one option, autoselect and load for the next selectbox
		},

		doLoadTrims: function(modelIndex) {
			this.call.operation = 'trims';
			this.call.callback = 'DDC.FastQuote.buildTrims';
			this.call.param('year', this.currentData.models[modelIndex].year);
			this.call.param('make', this.currentData.models[modelIndex].make);
			this.call.param('model', this.currentData.models[modelIndex].model);
			this.call.param('bodystyle', this.currentData.models[modelIndex].bodyStyle);
			this.call.execute();
		},

		buildTrims: function(data) {
			var select = this.get('trim');
			select.options[0] = new Option(this.selectLabel.trim, '');
			for(var trm in data.trims) {
                if(data.trims[trm].trim) //check for ie
					select.options[select.length] = new Option(this.trimToString(data.trims[trm]), data.trims[trm].vehicleId);
			}
			this.get('trim').disabled = false;		//reenables 'trim' selectbox after ajax write
		},

		autoSelect: function(toSelect){//if only one option, autoselect and load for the next selectbox
			if(toSelect.options.length == 2  ) {
				this.selectOnChange(this.get(toSelect.name,true).find('option:eq(1)').attr('selected', true).end().get(0));
			}
		},

		selectVehicle: function(trimIndex) {
			$('#fastquoteForm').get(0).elements['vehicleId'].value = this.trims[trimIndex].vehicleId;
		},

		modelToString: function(modelObj) {
			return modelObj.year + ' ' + modelObj.make + ' ' + modelObj.model + ' ' + modelObj.bodyStyle.replace('Sport Utility Vehicle', 'SUV');
		},

		trimToString: function(obj) {
            if (this.data.showPrice){
                return obj.trim + ' ' + obj.msrp.toString().replace(/(\d+)(\d{3})/, '$$$1' + ',' + '$2');
            }else{
                return obj.trim;                
            }
		},

		clearSelect: function(select) {
			var numopt = select.options.length;
			for (var i = (numopt - 1); i >= 1; i--) {
				select.options[i] = null;
			}
			select.options[0] = new Option('Loading...','Loading...');
		},

		selectOnChange: function(select) {	//select onChange helper
			if(select.getAttribute('name') == 'make' && select.selectedIndex != 0) {
				this.clearSelect(this.get('model'));
				this.clearSelect(this.get('trim'));
				$('#fastQuoteForm select[name=model]').removeAttr('disabled').end().eq(1).attr('disabled', 'true');		//enables the 'model' selectbox, disables subsequent select boxes
				$('#fastQuoteForm option[value=make]').css('color', '#888888');
				$('#fastQuoteForm option[value=Model]').css('color', '#888888');
				this.doLoadModels(select.options[select.selectedIndex].value);
			} else if(select.getAttribute('name') == 'model' && select.selectedIndex != 0) {
				this.clearSelect(this.get('trim'));
				$('#fastQuoteForm select[name=trim]').removeAttr('disabled').end().eq(2).attr('disabled', 'true');		//enables the 'trims' selectbox, disables subsequent select boxes
				$('#fastQuoteForm option[value=Model]').css('color', '#888888');
				this.doLoadTrims(select.options[select.selectedIndex].value);
			} else if(select.getAttribute('name') == 'trim' && select.selectedIndex != 0) {
				document.forms['fastQuoteForm'].elements.vehicleId.value = select.options[select.selectedIndex].value;
			}
		}
	};
	
})(jQuery);