var validFoocus = false;

function stateSel(event, objSelect) {
	var objStateSearch = document.getElementById("state");
	var objHidState = document.getElementById("hidStateSearch");
	
	if (event.keyCode == 13) {
		objStateSearch.value = objSelect.options[objSelect.selectedIndex].text;
		objHidState.value = objSelect.value;
		actualState = objHidState.value;
		
		var objDivSearch = document.getElementById("divSearchState");
		objDivSearch.style.display = "none";
		objStateSearch.focus();
	}
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function searchState(objEvent, objText) {

	if ((objEvent.keyCode > 96 && objEvent.keyCode < 123) ||
		(objEvent.keyCode > 64 && objEvent.keyCode < 89)) {

		var objDivSearch = document.getElementById("divSearchState");
		var pos = findPos(objText);
		objDivSearch.style.top = (parseInt(pos[1]) + parseInt(objText.clientHeight)) + "px";
		objDivSearch.style.left = pos[0] + "px";
		objDivSearch.style.width = objText.clientWidth + "px";
		objDivSearch.style.display = "block";

		var params = "name=" + objText.value + "&country=" + actualCountry;

		serverRequest("data/statesByName.php?" + params, "searchStateDataArrival");
		
	} else if (objEvent.keyCode == 40) {
		validFoocus = true;
		document.getElementById("selState").focus();
	}
}

function getFocus(obj){
	validFoocus = true;
	obj.focus();
	obj.selectedIndex = 0;
}

function onStateClick(objEvent, objSelect) {
	var objStateSearch = document.getElementById("state");
	var objHidState = document.getElementById("hidStateSearch");
	
	objStateSearch.value = objSelect.options[objSelect.selectedIndex].text;
	objHidState.value = objSelect.value;
	actualState = objHidState.value;
	
	var objDivSearch = document.getElementById("divSearchState");
	objDivSearch.style.display = "none";
	objStateSearch.focus();
}

function searchStateDataArrival(responce) {
	var objState = document.getElementById("selState");
	removeAllOptions(objState);
	
    var arrFilas = responce.split("<#>");
	var cantFilas = arrFilas.length;
	
	for (var i = 0; i < cantFilas; i++) {
		var strRow = arrFilas[i];
		
		var arrCols = strRow.split("<@>");

		var option = document.createElement("OPTION");
		option.value = arrCols[0];
		option.text = arrCols[1];
		option.setAttribute("state", arrCols[2]);
		
		objState.options.add(option);
	}
}

function leaveFocus(e) {
	if (!validFoocus) {
		document.getElementById('divSearchState').style.display = 'none';
	} else {
		validFoocus = false;
	}
}
