// JavaScript Document
$(document).ready(function(){
	var curYear = (new Date()).getYear();
	if (curYear < 1900)	//normalize year just in case
		curYear += 1900;
	var temp = $('#year');
	if(temp)
	{
		var firstOption = $('option:first', temp);
		var firstText = firstOption.text();
		var curVal = temp.attr('value');
		var loopVar = 0;

		temp = temp.get(0);
		temp.options.length = 0;
		if(firstText && isNaN(firstText))
		{
			loopVar = 1;
			temp.options[0] = new Option(firstText, '', true, false);
		}
		for(var i = curYear; i >= curYear - 25; i -= 1)
		{
			temp.options[loopVar] = new Option(i, i, false, (i == curVal));
			loopVar++;
		}
	}
	
	temp = $('#make');
	if(temp && vehicleObj)
	{
		firstOption = $('option:first', temp);
		firstText = firstOption.text();
		curVal = temp.attr('value');
		loopVar = 0;

		temp = temp.get(0);
		temp.options.length = 0;
		if(firstText && isNaN(firstText))
		{
			loopVar = 1;
			temp.options[0] = new Option(firstText, '', true, false);
		}
		for(i in vehicleObj['models'])
		{
			temp.options[loopVar] = new Option(i, i, false, (i == curVal));
			loopVar++;
		}
		if(curVal)
		{
			$('#make').attr('value', curVal)
		}
	}
	
	var currentMake = $('#make').attr('value');
	temp = $('#model');
	if(temp && vehicleObj && currentMake && vehicleObj['models'][currentMake])
	{
		firstOption = $('option:first', temp);
		firstText = firstOption.text();
		curVal = temp.attr('value');
		loopVar = 0;

		temp = temp.get(0);
		temp.options.length = 0;
		if(firstText && isNaN(firstText))
		{
			loopVar = 1;
			temp.options[0] = new Option(firstText, '', true, false);
		}
		for(i in vehicleObj['models'][currentMake])
		{
			temp.options[loopVar] = new Option(vehicleObj['models'][currentMake][i], vehicleObj['models'][currentMake][i], false, (vehicleObj['models'][currentMake][i] == curVal));
			loopVar++;
		}
		if(curVal)
		{
			$('#model').attr('value', curVal)
		}
	}
	
	$('#make').change(function(){
		var $me = $(this);
		var currentMake = $me.attr('value');
		var $model = $('#model');
		var curModel = $model.attr('value');
		var firstText = $('option:first', $model).text();
		var dropdown = $model.get(0);
		var loopVar = 0;

		if(firstText && isNaN(firstText))
		{
			loopVar = 1;
			dropdown.options[0] = new Option(firstText, '', true, false);
		}

		if(vehicleObj['models'][currentMake])
		{
			for(i in vehicleObj['models'][currentMake])
			{
				dropdown.options[loopVar] = new Option(vehicleObj['models'][currentMake][i], vehicleObj['models'][currentMake][i], false, (vehicleObj['models'][currentMake][i] == curModel));
				loopVar++;
			}
		}
	});
});