CarSelector = function(prefix, show_year) {
	this.make = $(prefix + '_make');
	this.model = $(prefix + '_model');
	this.trim = $(prefix + '_intellichoice_vehicle_id');
	this.carImage = $('car_jpg');
	this.carLabel = $('car_lbl');
	this.carMSRP = $('car_msrp');
	this.carInvoice = $('car_invoice');
	this.value = null;
	this.linkedSelectors = [];
    this.show_year = show_year;
    
	this.loadMakes();
	if (typeof(RequestedCarDisplay) != 'undefined' && RequestedCarDisplay.make) {
		for(var i = 0; i < Makes.length; i++) {
			if(Makes[i][1] == RequestedCarDisplay.make) this.make.value = Makes[i][0];
		}
	} else if (typeof(RequestedCarValue) != 'undefined' && RequestedCarValue.make) {
	    for(var i = 0; i < Makes.length; i++) {
			if(Makes[i][0] == RequestedCarValue.make) this.make.value = Makes[i][0];
		}
	}
	
	this.loadModels();
	if(typeof(RequestedCarDisplay) != 'undefined' && RequestedCarDisplay.year && RequestedCarDisplay.make && RequestedCarDisplay.model && Models[this.make.value]) {
	    for(var i = 0; i < Models[this.make.value].length; i++) {
			if( (Models[this.make.value][i][0] == RequestedCarDisplay.year) && (Models[this.make.value][i][2] == RequestedCarDisplay.model)) {
			    this.model.value = Models[this.make.value][i][0] + '/' + Models[this.make.value][i][1];
			    if (this.show_year) break;
			}
		}
	} else if(typeof(RequestedCarDisplay) != 'undefined' && RequestedCarDisplay.make && RequestedCarDisplay.model && Models[this.make.value]) {
		for(var i = 0; i < Models[this.make.value].length; i++) {
			if(Models[this.make.value][i][2] == RequestedCarDisplay.model) {
			    this.model.value = Models[this.make.value][i][0] + '/' + Models[this.make.value][i][1];
			    if (this.show_year) break;
			}
		}
	} else if(typeof(RequestedCarValue) != 'undefined' && RequestedCarValue.model && Models[this.make.value]) {
        for(var i = 0; i < Models[this.make.value].length; i++) {
			if((Models[this.make.value][i][0] + '/' + Models[this.make.value][i][1]) == RequestedCarValue.model) {
			    this.model.value = Models[this.make.value][i][0] + '/' + Models[this.make.value][i][1];
			}
		}
    }
    
	this.loadTrims();
        
	this.selectEvent = this.handleSelectEvent.bindAsEventListener(this);
	Event.observe(this.make, 'change', this.selectEvent);
	Event.observe(this.model, 'change', this.selectEvent);
	Event.observe(this.trim, 'change', this.selectEvent);
	
	if (this.trim.disabled || this.model.value == 0) {
	    if(this.carImage) {
            this.carImage.src = '/images/cars/audi.jpg';
            this.carImage.style.border = '1px solid #000';
        }
    }
}

CarSelector.prototype.finishLoadTrims = function(options) {
	this.trim.disabled = false;
	this.display = {};

	if (options.length < 2) { //One Trim Option

		for(var i = 0; i < options.length; i++) {
			this.trim.options[i+0] = new Option(options[i][1], options[i][0]);	
			this.display[this.trim.options[i+0].value] = {
				image: options[i][2],
				text: options[i][3],
				msrp: options[i][4],
				invoice: options[i][5]
			}			
		}

	}else{ //Multiple Trim Options

		for(var i = 0; i < options.length; i++) {
			this.trim.options[i+2] = new Option(options[i][1], options[i][0]);	
			this.display[this.trim.options[i+2].value] = {
				image: options[i][2],
				text: options[i][3],
				msrp: options[i][4],
				invoice: options[i][5]
			}			
		}
		
	}

	
	if (options.length >= 2){ // Show "Not Sure" unless there is only one option
		this.trim.options[1] = new Option("Not Sure", options[1][0]);
	}
	

			
	if(options.length > 0) {
	    if (typeof(RequestedCarValue) != 'undefined' && RequestedCarValue.trim) {
    	    for(var i = 0; i < this.trim.options.length; i++) {
    			if(this.trim.options[i].value == RequestedCarValue.trim) {
    			    //this.trim.selectedIndex = i;
    			    this.trim.value = this.trim.options[i].value;
            		this.value = this.trim.value;
    			}
    		}
    	}
    	if (this.trim.selectedIndex == 0) {
			this.trim.value = this.trim.options[3].value;
			this.value = this.trim.value;
    	}
	} else {
		this.value = null;
	}	
	this.updateDisplay();
}

CarSelector.prototype.focus = function(options) {
	if(this.make.value == '0') {
		this.make.focus();
	} else if(this.model.value == '0') {
		this.model.focus();
	} else if(this.trim.value == '0') {
		this.trim.focus();
	} else {
		return false;
	}
	return true;
}

CarSelector.prototype.handleSelectEvent = function(evt) {
	var el = Event.element(evt);
	if(el == this.make) {
		this.model.options.length = 0;
		this.trim.options.length = 0;
		this.loadModels();
		this.loadTrims();
		for(var i = 0; i < this.linkedSelectors.length; i++) {
			this.linkedSelectors[i].loadMakes();
		}
	} else if(el == this.model) {
		this.trim.options.length = 0;
		this.loadTrims();
	} else if(el == this.trim) {
		this.value = this.trim.value;
		this.updateDisplay();
	}
}

CarSelector.prototype.loadMakes = function() {
	var val = this.make.value;
	this.make.options.length = 0;
	this.make.options[0] = new Option("Select make", 0);
	for(var i = 0, j = 0; i < Makes.length; i++) {
		var skip = SkipMakes.indexOf(Makes[i][1]) != -1;
		if(!skip) {
			for(var l = 0; l < this.linkedSelectors.length; l++) {
				if(this.linkedSelectors[l].make.value == Makes[i][0]) {
					skip = true;
					break;
				}
			}
			if(!skip) {
				this.make.options[++j] = new Option(Makes[i][1], Makes[i][0]);
			}
		}
	}
	if(val) this.make.value = val;
}

CarSelector.prototype.loadModels = function() {
	this.model.options[0] = new Option("Select model", 0);
	if(this.make.value == 0) {
		this.model.disabled = true;
	} else {
		this.model.disabled = false;
		if (this.show_year) {	    
    		for(var i = 0; i < Models[this.make.value].length; i++) {
    			this.model.options[i+1] = new Option(Models[this.make.value][i][0] + ' ' + Models[this.make.value][i][2], Models[this.make.value][i][0] + '/' + Models[this.make.value][i][1]);
    		}
    	} else {
			// collect each year in different arrays
			default_year = [];
			no_match = [];
    	    for (var i = 0; i < Models[this.make.value].length; i++) {
				var modelYr = Models[this.make.value][i][0];
			    if (modelYr == '2009') {
			      default_year.push( Models[this.make.value][i] );
			    }
				if (modelYr == '2010') {
				  no_match.push( Models[this.make.value][i] );
				}
    		}
           
		   // loop through 2010 models to remove any overlap with 2009 versions
           for (i = no_match.length - 1; i >= 0; i--) {
                for (var n = 0; n < default_year.length; n++) {
						if (no_match[i][2].match(default_year[n][2]) ) {
							var index = no_match.indexOf(no_match[i]);
							no_match.splice(index,1);
                            if (no_match[i] == undefined) {
								break;
							}
						
						}
				}
						
		   }
		   
		   // combine arrays
		   var model_list = default_year.concat(no_match);
		   // sort combined array alphabetically
		   model_list.sort(compare);
            
		   // add as select options
    	   j = 1; // we have 'select model' so start at 1
    	   for(var i = 0; i < model_list.length; i++) {
			   this.model.options[j] = new Option(model_list[i][2], model_list[i][0] + '/' + model_list[i][1]);
			   j++;
    	   }
			
			
    	}
	}
}

// used to sort results alphabetically
compare = function(a,b) {
  if(a[2] == b[2]) { return 0; }
  return (a[2] < b[2]) ? -1 : 1;
}	



CarSelector.prototype.loadTrims = function() {
	this.trim.options[0] = new Option("Select trim", 0);
	if(this.model.value == 0) {
		this.trim.disabled = true;
	} else {
		var finish = this.finishLoadTrims.bind(this);
		var url = '/new_cars/' + this.make.value + '/' + this.model.value + '/trim.js';
		new Ajax.Request( url, {
											method: 'get',
											onSuccess: function(transport) {
												finish(eval('('+transport.responseText+')'));
											}
										 });
	}
}

CarSelector.prototype.setLinks = function(linkedSelectors) {
	this.linkedSelectors = linkedSelectors;
}

CarSelector.prototype.updateDisplay = function() {
	var display = this.value ? this.display[this.value] : this.display[this.trim.options[1].value];
	if(this.carImage) {
	    if (this.trim.disabled || this.model.value == 0) {
	        this.carImage.src = '/images/cars/audi.jpg';
	        this.carImage.style.border = '1px solid #000';
	    } else {
    		if(null != display && display.image) {
    			this.carImage.src = '/images/cars/' + display.image;
    			this.carImage.style.border = '#333 solid 1px';
    		} else {
    			this.carImage.src = '/images/cars/default_car.jpg';
    			this.carImage.style.border = '';
    		}
    	}
	}
	if(this.carLabel) this.carLabel.innerHTML = (display != null && display.text) ? display.text : '';
	if(this.carMSRP) this.carMSRP.innerHTML = (display.msrp) ? display.msrp : 'not available';
	if(this.carInvoice) this.carInvoice.innerHTML = (display.invoice) ? display.invoice : 'not available';
}






