var fichedata=new Array();

function builddropdown(id,make,year,model,type){
	
	var pageload=0;
	if(make||year||model||type){pageload=1}
	
	//populate the make dropdown everytime
	if(!make){make=document.getElementById('selectmake').value}
	populatedropdown('make');
	setdropdown('make',make);
	make=document.getElementById('selectmake').value;
	
	if(make){
		//populate the year dropdown
		if(!year){year=document.getElementById('selectyear').value}
		populatedropdown('year',make);
		setdropdown('year',year);
		year=document.getElementById('selectyear').value;
		
		if(year){
			//populate the model dropdown
			if(!model){model=document.getElementById('selectmodel').value}
			populatedropdown('model',make,year);
			setdropdown('model',model);
			model=document.getElementById('selectmodel').value;

			if(model){
				//populate the type dropdown
				if(!type){type=document.getElementById('selecttype').value}
				populatedropdown('type',make,year,model);
				setdropdown('type',type);
				type=document.getElementById('selecttype').value;

				if(type&&!pageload){
					window.location='/?i='+id+'&make='+make+'&year='+year+'&model='+model+'&type='+type;
				}
			}
		}
	}
	
	if(!make){purgedropdown('year')}
	if(!year){purgedropdown('model')}
	if(!model){purgedropdown('type')}
	
}

function purgedropdown(dropdownref){
	var dropdown=document.getElementById('select'+dropdownref);
	
	dropdown.options.length=0;
	dropdown.options.add(new Option('-',''))
}

function setdropdown(dropdownref,value){
	if(value){
		var dropdown=document.getElementById('select'+dropdownref);

		for(var n=0;n<dropdown.length;n++){
			//alert(dropdown.options[n].value+'=='+value);
			if(dropdown.options[n].value==value){
				dropdown.selectedIndex=n;
			}
		}
	}
}

function populatedropdown(dropdownref,make,year,model){
	var matchstring='';
	var dropdowndata=new Array();
	
	var dropdown=document.getElementById('select'+dropdownref);
	
	if(make){matchstring+=make+';'}
	if(year){matchstring+=year+';'}
	if(model){matchstring+=model+';'}
	
	for(var n=0;n<fichedata.length;n++){
		if(fichedata[n].substr(0,matchstring.length)==matchstring){
			var newvalue=fichedata[n].replace(matchstring,'').replace(/\;.*/,'')
			
			if(!exists(dropdowndata,newvalue)){
				dropdowndata[dropdowndata.length]=newvalue;
			}
		}
	}
	
	dropdowndata.sort(numbersort);
	
	dropdown.options.length=0;
	dropdown.options.add(new Option('- select -',''))
	for(var n=0;n<dropdowndata.length;n++){
		dropdown.options.add(new Option(dropdowndata[n],dropdowndata[n]))
	}
	
	//alert(count);
}

//var count=0;

function numbersort(a,b){
	a=a.replace(/[^0-9].*/ig,'');
	b=b.replace(/[^0-9].*/ig,'');
	
	//count++;
	
	return a-b;
}

function exists(dropdowndata,value){
	
	for(var n=0;n<dropdowndata.length;n++){
		if(dropdowndata[n].toLowerCase()==value.toLowerCase()){
			return true;
		}
	}
	
	return false;
	
}
