var XmlHttpObj;

var Utf8 = {
    //Convierte de UTF-8 a ISO
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
				
        return string;
    }
}

function CreateXmlHttpObj(){
	try	{
		XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
	
	}catch(e){
		try	{
			XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(oc){
			XmlHttpObj = null;
		}
	}
	
	if(!XmlHttpObj && typeof XMLHttpRequest != "undefined") {
		XmlHttpObj = new XMLHttpRequest();
	}
}

function pobOnChange(){
	var zonesList = document.getElementById("reszon");
	zonesList.options[0] = new Option("...", 0,  false, false);
  var poblacionList = document.getElementById("respob");
 
  var selectedpoblacion = poblacionList.options[poblacionList.selectedIndex].value;
  var requestUrl;

  requestUrl = "php/getZonesWeb.php?pob=" + encodeURIComponent(selectedpoblacion);
    
	CreateXmlHttpObj();
	
	if(XmlHttpObj){
		XmlHttpObj.onreadystatechange = StateChangeHandler;
		XmlHttpObj.open( "POST", requestUrl, true );
		XmlHttpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		XmlHttpObj.send('');		
	}
}

function StateChangeHandler(){
	if(XmlHttpObj.readyState == 4){
		if(XmlHttpObj.status == 200){			
			PopulateZonesList(XmlHttpObj.responseXML.documentElement);
		}else{
			alert("Error: "  + XmlHttpObj.status);
		}
	}
}

function PopulateZonesList(localidadNode){	
  var zonesList = document.getElementById("reszon");
	for (var count = zonesList.options.length-1; count >-1; count--){
		zonesList.options[count] = null;
	}

	var localidadNodes = localidadNode.getElementsByTagName('zona');
	var textValue; 
	var optionItem;
	
	if(localidadNodes.length>0){
		for (var count = 0; count < localidadNodes.length; count++){ 
			var item = localidadNodes[count];
			var idValue=item.childNodes[0].firstChild.nodeValue;
			var textValue=item.childNodes[1].firstChild.nodeValue;

			optionItem = new Option(textValue, idValue,  false, false);
			zonesList.options[zonesList.length] = optionItem;
		}
	}else{
		zonesList.options[0] = new Option("...", 0,  false, false);
	}
}

function GetInnerText (node){
 return (node.textContent || node.innerText || node.text) ;
}
