function filter(text){
   var chars = Array("&", "<", ">", '"', "'", '\n');
   var replacements = Array("&amp;", "&lt;", "&gt;", "&quot;", "&#039;", '<br />');
   for (var i=0; i<chars.length; i++){
       var re = new RegExp(chars[i], "gi");
       if(re.test(text)){
           text = text.replace(re, replacements[i]);
       }
   }
   return text;
}

function hideOil(){
	$('#noResults').hide();
	$('#resultsTable').hide();
	$('#resultsTable tr:first-child').nextAll().remove();
}

function showOil(data, textStatus, XMLHttpRequest){
	$('#resultsTable tr:first-child').nextAll().remove();
	
	var oilList = data.oilList;
	var html = '';

	for (var i in oilList){
		var oilTypeRow = oilList[i];
		html += '<tr><td rowspan="'+ oilTypeRow.oil.length +'">'+ filter(oilTypeRow.type) +'</td>';
		
		for (var a = 0; a < oilTypeRow.oil.length; a++){
			var oilRow = oilTypeRow.oil[a];
			
			if(a > 0) html += '<tr>';
			html += '<td>'+ filter(oilRow.name) +'&nbsp;</td><td>'+ filter(oilRow.vol) +'&nbsp;</td><td>'+ filter(oilRow.notice) +'&nbsp;</td></tr>';
		}
	}
		
	if(html != ''){
		$(html).appendTo('#resultsTable');
		$('#noResults').hide();
		$('#resultsTable').show();
	}else{
		$('#resultsTable').hide();
		$('#noResults').show();
	}
}

function hideModList(){
	hideOil();
	
	$('#mod option:first-child').nextAll().remove();
	$('#mod').attr('disabled', 'disabled');
}

function showModList(data, textStatus, XMLHttpRequest){
	hideOil();
	$('#mod option:first-child').nextAll().remove();
	
	var modList = data.modList;
	for (var i = 0; i < modList.length; i++){
		var mod = modList[i];
		$('<option value="'+ parseInt(mod.id) +'">'+ filter(mod.name)  +' ('+ filter(mod.year_start) + ' - '+ filter(mod.year_finish) +')</option>').appendTo('#mod');
	}
	
	$('#mod').removeAttr('disabled');
}

function hideModelList(){
	hideModList();
	
	$('#model option:first-child').nextAll().remove();
	$('#model').attr('disabled', 'disabled');
}

function showModelList(data, textStatus, XMLHttpRequest){
	hideModList();
	$('#model option:first-child').nextAll().remove();
	
	var modelList = data.modelList;
	for (var i = 0; i < modelList.length; i++){
		var model = modelList[i];
		$('<option value="'+ parseInt(model.id) +'">'+ filter(model.name) +'</option>').appendTo('#model');
	}
	
	$('#model').removeAttr('disabled');
}

function hideBrandList(){
	hideModelList();
	
	$('#brand option:first-child').nextAll().remove();
	$('#brand').attr('disabled', 'disabled');
}

function showBrandList(data, textStatus, XMLHttpRequest){
	hideModelList();
	$('#brand option:first-child').nextAll().remove();
	
	var brandList = data.brandList;
	for (var i = 0; i < brandList.length; i++){
		var brand = brandList[i];
		$('<option value="'+ parseInt(brand.id) +'">'+ filter(brand.name) +'</option>').appendTo('#brand');
	}
	
	$('#brand').removeAttr('disabled');
}

function setForm(){
	$('#veh_type option:first-child').attr('selected', 'selected');
	hideBrandList();
}	


