var runonceYear = false;
var runonceModel = false;

function parseJSON(text) {
	return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(text.replace(/"(\\.|[^"\\])*"/g, ''))) 
		&& eval('(' + text + ')');
}

function getMake(){
	var my_make = document.getElementById('makeList')[document.getElementById('makeList').selectedIndex].innerHTML;
	return my_make;
}

function fetchYear(){
	var my_year = document.getElementById('yearList')[document.getElementById('yearList').selectedIndex].innerHTML;
	return my_year;
}

$(document).ready(function() {
	$.getJSON("/sites/default/themes/bilsmart/include/make.php", function(j) {
		var options = '<option selected="selected">Välj bilmärke</option>';
		for (var i = 0; i < j.length; i++) {
			options += '<option value="' + j[i]['make_code'] + '">' + j[i]['make_name'] + '</option>';
		}
		$("select#makeList").html(options);
		// set form if hash
		var hash = window.location.hash;
		if (hash != null && hash > "") {
			hash = Base64.decode(hash);
			var obj = parseJSON(hash); 
			if (obj != false) {
				//alert(obj['make'] + " " + obj['year'] + " " + obj['modelIndex']);
				$("select#makeList").val(obj['make']);
				carYear(obj['year'], obj['modelIndex']);
			}
		}
	});
});

function carYear(preYear, preModel) {
	
	var current_make = getMake();
	var current_year;

	$.getJSON("/sites/default/themes/bilsmart/include/year.php", 
			{make: $("#makeList").val()}, function(j){
		var clear = '<option selected="selected"></option>';
		var options = '<option selected="selected">Välj årsmodell</option>';  
		for (var i = j[0]['endyear']; i >= j[0]['startyear']; i--) {
			options += '<option value="' + i + '">' + i + '</option>';
		}
		$("select#yearList").html(options);
		$("select#modelList").html(clear);
		if (preYear != null) {
			$("select#yearList").val(preYear);
			carModel(preModel);
		}
	});
	
	if(!runonceYear){
		runonceYear = true;
		if( current_make != 'Välj bilmärke' ){
			var o = document.getElementById('makeList');
			o.removeChild(o.options[0]);
			
		}
	}
	$("div#fragment-2-result table").css({display: 'none'});
	
	runonceModel = false;
}

function carModel(preModel) {
	var current_year = fetchYear();
	var callback_func = 
		function(j) {
			var models = '';
			var nbrOfPlaces = 7;
			var k = 0;
			var model_id;
			var model;
			var model_desig;
			var thumb;
			var rows = 0;
			var imgNbr = 0;
			var my_make;
			var year = fetchYear();

			if (j.length != 0) {
				var options = '<option selected="selected">Välj modell</option>';	 
			}

			for (var i = 0; i < j.length; i++) {

				model_id = j[i]['model_id'];
				model = j[i]['model'];
				model_desig = j[i]['model_desig'];
				thumb = j[i]['thumbnail'];
				
				options += '<option value="' + model_id + '">' + model + '</option>';

				if (k == 0){
					models += '<table><tr>';
					rows++;
				}
				
				if (k == nbrOfPlaces) {
					k = 0;
					models += '</tr></table><table><tr>';
					rows++;
				}

				imgNbr = i + 1;			
				my_make = getMake();
				models += '<td onclick="setModelList(' + imgNbr + ');searchByModel()">'
					+ '<div class="upper" title="'
					+ my_make +' '+ model +'">' + model_desig +'</div><div class="lower" title="Klicka här för att gå till modellen: &#13;' 
					+ my_make + ' ' + model +'"><img id="img'+ imgNbr +'" class="thumbs" src="/' 
					+ thumb + '" style="opacity:0.5;filter:alpha(opacity=50)"  onmouseover="this.style.opacity=1;this.filters.alpha.opacity=100" onmouseout="this.style.opacity=0.5;this.filters.alpha.opacity=50" /></div></td>';
				k++;
				
				if (k == nbrOfPlaces) {
					k = 0;
					models += '</tr></table>';
				}
			}
			
			if (k < nbrOfPlaces) {				
				while (k < nbrOfPlaces) {				
					models += '<td><div class="upper"></div><div class="lower-empty"></div></td>';
					k++;
				}
				models += '</tr></table>';
			}
							
			$("select#modelList").html(options); 
			$("div#fragment-2-result").html(models);
			$("div#fragment-2-result table").css({display: 'block'});
			if (preModel != null) {
				highlightThumb(preModel);
				setModelList(preModel);
			}
		};
	
	if ($("#yearList").val() == 'Alla') {
		$.getJSON("/sites/default/themes/bilsmart/include/allmodels.php",
			{make: $("#makeList").val()}, callback_func);
	} else {
		$.getJSON("/sites/default/themes/bilsmart/include/model.php", 
			{make: $("#makeList").val(), year: $("#yearList").val() }, callback_func);
	}
	
	if (!runonceModel) {
		runonceModel = true;
		if (current_year != 'Välj årsmodell' ) {
			var o = document.getElementById('yearList');
			o.removeChild(o.options[0]);
		}
	}
}

function highlightThumb(index) {
		var tmp;
		if (index != null) {
			tmp = 'img' + index;
		} else {
			tmp = 'img' + document.getElementById('modelList').selectedIndex;
		}
		$('img.thumbs').css({opacity: 0.5, filter: 'alpha(opacity=50)'});
	    $('img#'+tmp).css({opacity: 1.0, filter: 'alpha(opacity=100)'});
}
function setModelList(index) {
	document.getElementById('modelList').selectedIndex = index;
}
function searchByModel() {
	if ($("#modelList").val() == '' || $("#modelList").val() == null || $("#modelList").val() == 'Välj modell' ) {
		alert("Ingen modell vald");
	} else {
	  $("#orderby").val(0);
    $("#searchtype").val(2);
    $("#year").val($("#yearList").val());
    $("#model").val($("#modelList").val());
    $("div#loading").css({display: 'block'});
    $("div#loading").bind("ajaxSend", function(){ $(this).show(); });
    $("#searchform")[0].submit();	    
	}
}
