var req;
var isIE = false;
var prov = document.getElementById("prov_select");
var city = document.getElementById("city_select");
var abv='';

function gotoCity() {
	location.href = '/locations/'+city.value+'/'+prov.value;
}

function getXML(abv,cit) {
	req = false;
  // branch for native XMLHttpRequest object
  if(window.XMLHttpRequest) {
    try {
      req = new XMLHttpRequest();
    } catch(e) {
      req = false;
    }
  // branch for IE/Windows ActiveX version
  } else if(window.ActiveXObject) {
    isIE = true;
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch(e) {
        req = false;
      }
    }
  }
  if(req) {
    req.onreadystatechange = processReq;
		if (abv=='') {
			abv = prov.value;
		}
    url = '/incl/ajax_select.php?abv='+abv;
    req.open("GET", url, false);
    req.send("");
    processReq(cit);
  }
}

function processReq(cit) {
  // only if req shows "loaded"
  if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
      // remove all existing options in select list
		  city.options.length = 0;
			var oOpt = document.createElement("option");
			oOpt.appendChild(document.createTextNode('--'));
			oOpt.setAttribute("value",id);
			city.appendChild(oOpt);
			var items = req.responseXML.getElementsByTagName("item");
			var arysize = items.length;
			for (i=0; i<arysize; i++) {
				var id = getElementTextNS("", "city", items[i], 0);
				var nam = getElementTextNS("", "city", items[i], 0);
				var oOpt = document.createElement("option");
				oOpt.appendChild(document.createTextNode(nam));
				oOpt.setAttribute("value",id);
				city.appendChild(oOpt);
			}
			city.value = cit;
    } else {
      alert("There was a problem retrieving the XML data:\n" + req.statusText);
    }
  }
}

// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
    var result = "";
    if (prefix && isIE) {
        // IE/Windows way of handling namespaces
        result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
    } else {
        // the namespace versions of this method 
        // (getElementsByTagNameNS()) operate
        // differently in Safari and Mozilla, but both
        // return value with just local name, provided 
        // there aren't conflicts with non-namespace element
        // names
        result = parentElem.getElementsByTagName(local)[index];
    }
    if (result) {
        // get text, accounting for possible
        // whitespace (carriage return) text nodes 
        if (result.childNodes.length > 1) {
            return result.childNodes[1].nodeValue;
        } else {
            return result.firstChild.nodeValue;    		
        }
    } else {
        return "n/a";
    }
}

