var priceranges = [
	[2500, 5000],
	[5000, 10000],
	[10000, 15000],
	[15000, 1000000]
];

function UsedMakerSelect() {
	var maker = $('maker').value;
	var modelsel = $('model');
	
	if (!maker.length)
		return;
	
	modelsel.options.length = 0;
	modelsel.options[0] = new Option('All models', '', true, true);
	
	models = available_models[maker];
	for (var i = 0, l = models.length; i < l; i++) {
		modelsel.options[i+1] = new Option(models[i], models[i]);
	}
	
	SetPriceRanges(used_prices[maker]);
	SetDealerships();	

}
 
function UsedModelSelect() {
	var maker = $('maker').value;
	var model = $('model').value;
	
	SetPriceRanges(model != '' ? used_prices[maker][model] : used_prices[maker]);
	SetDealerships();	
}

function SetPriceRanges(obj) {
	var pricelist = $('value');
	pricelist.options.length = 0;
	pricelist.options[0] = new Option('Any', '0', true, true);
	
	for (i = 0, l = priceranges.length; i < l; i++) {
		if (obj.maxprice >= priceranges[i][0] && obj.minprice <= priceranges[i][1])
			pricelist.options[pricelist.options.length] = new Option('£' + priceranges[i][0] + (i + 1 == l ? '+' : ' - £' + (priceranges[i][1] - 1)), priceranges[i][0]);
	}
}

function SetDealerships() {
	var maker = $('maker').value;
	var model = $('model').value;
	var price = 0;
	
	for (i = 0, l = priceranges.length; i < l; i++) {
		if (priceranges[i][0] == Number($('value').value))
			price = priceranges[i];
	}
	
	var loclist = [
		[1, 'Verve Glasgow'],
		[2, 'Verve Wishaw'],
		[4, 'Glasgow Van Centre'],
		[5, 'Bickets'],
		[16, 'Verve Bathgate'],
		[18, 'Verve Coatbridge']
	];
	var cloclist = [];
	
	if (model != '') {
		var vloclist = used_prices[maker][model].locations;
		for (i = 0, l = vloclist.length; i < l; i++) {
			if (price != 0 && (price[0] > vloclist[i][0] || price[1] < vloclist[i][0]))
				continue;
			cloclist[vloclist[i][1]] = 1;
		}
	}
	else {
		for (j = 0, k = available_models[maker].length; j < k; j++) {
			var vloclist = used_prices[maker][available_models[maker][j]].locations;
			for (i = 0, l = vloclist.length; i < l; i++) {
				if (price != 0 && (price[0] > vloclist[i][0] || price[1] < vloclist[i][0]))
					continue;
				cloclist[vloclist[i][1]] = 1;
			}
		}
	}
	
	var dealerlist = $('location');
	dealerlist.options.length = 0;
	dealerlist.options[0] = new Option('All', '0', true, true);
	for (i = 0, l = loclist.length; i < l; i++) {
		if (cloclist[loclist[i][0]])
			dealerlist.options[dealerlist.options.length] = new Option(loclist[i][1], loclist[i][0]);
	}
}