var isCatGet = false;
var loadingArray = Array();
var selectArray = Array("mark", "model", "engine"); // "cat", "subcat", "manu");

$(document).ready(function() {
	for(m in selectArray) {
		$("#" + selectArray[m] + "Select").attr("disabled", "disabled");
		$("#" + selectArray[m] + "Select").change(function() { getAllData(false); });
	}
	
	if($("#qstring").val() == "") 
		$("#qstring").val("Otsingusõna või tootekood");
	
	$("#qstring").blur(function() {
		if($(this).val() == "") {
			$(this).val("Otsingusõna või tootekood");
		}
	});
	
	$("#qstring").focus(function() {
		if($(this).val() == "Otsingusõna või tootekood") {
			$(this).val("");
		}
	});
	
	getAllData(true);
});

function getAllData(getSessionData) {
	var postData = "";
	
	if(getSessionData == false)
		for(m in selectArray) 
			postData += "&" + selectArray[m] + "=" + $("#" + selectArray[m] + "Select").val();
		
	for(i = selectArray.length; i--; i >= 0) {
		var obj = $("#" + selectArray[i] + "Select");
		obj.removeOption(/.+/i);
		obj.attr("disabled", "disabled");
	}
	
	for(m in selectArray) {
		$.post("index.php", "act=getData" + postData + "&list=" + selectArray[m], function(serverData) {
			ShowData(serverData);
		});
	}
}

function clearSearch() {
	$.post("index.php", "act=clearSearch", function(serverData) {
		history.go(0);
	});
}

function ShowData(serverData) {
	fillData($("data", serverData), $("target", serverData).text() + "Select");
}

function fillData(data, target) {
	var obj = $("#" + target);
	
	obj.removeOption(/.+/i);
	obj.attr("disabled", "disabled");
	
	var sel = $("selected", data);
	if(sel.childNodes) 
		sel = sel.firstChild.nodeValue;
	else
		sel = sel.text();
	
	if($("item", data).length > 0) {
		obj.attr("disabled", false);
		$("item", data).each(function(i) {
			name = this.firstChild == null ? " " : this.firstChild.nodeValue;
			
			selected = this.getAttribute("id") == sel;
			obj.addOption(this.getAttribute("id"), name, selected)
		});	
	}
}
