// mozXPath [http://km0ti0n.blunted.co.uk/mozxpath/] km0ti0n@gmail.com
// Code licensed under Creative Commons Attribution-ShareAlike License 
// http://creativecommons.org/licenses/by-sa/2.5/
if( document.implementation.hasFeature("XPath", "3.0") ) {
	XMLDocument.prototype.selectNodes = function(cXPathString, xNode)	{
		if( !xNode ) { xNode = this; } 
		var oNSResolver = this.createNSResolver(this.documentElement)
		var aItems = this.evaluate(cXPathString, xNode, oNSResolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
		var aResult = [];
		for( var i = 0; i < aItems.snapshotLength; i++) {
			aResult[i] =  aItems.snapshotItem(i);
		}
		return aResult;
	}
	XMLDocument.prototype.selectSingleNode = function(cXPathString, xNode)	{
		if( !xNode ) { xNode = this; } 
		var xItems = this.selectNodes(cXPathString, xNode);
		if( xItems.length > 0 ) {
			return xItems[0];
		} else {
			return null;
		}
	}

	Element.prototype.selectNodes = function(cXPathString)	{
		if(this.ownerDocument.selectNodes) {
			return this.ownerDocument.selectNodes(cXPathString, this);
		}else{
			throw "For XML Elements Only";
		}
	}

	Element.prototype.selectSingleNode = function(cXPathString)	{	
		if(this.ownerDocument.selectSingleNode){
			return this.ownerDocument.selectSingleNode(cXPathString, this);
		}else{
			throw "For XML Elements Only";
		}
	}
}
var cache = new Array();
serverAddress = 'http://www.casasdealmeria.com/Scripts/proxy.php';
// holds an instance of XMLHttpRequest
var xmlHttp = createXmlHttpRequestObject();
// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() {
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  } catch(e) {
    // assume IE6 or older
    var XmlHttpVersions = new Array('MSXML2.XMLHTTP.6.0',
                                    'MSXML2.XMLHTTP.5.0',
                                    'MSXML2.XMLHTTP.4.0',
                                    'MSXML2.XMLHTTP.3.0',
                                    'MSXML2.XMLHTTP',
                                    'Microsoft.XMLHTTP');
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
      try { 
        // try to create XMLHttpRequest object
		xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {}
    }
  }
  // return the created object or display an error message
  if (!xmlHttp) {
    alert("Error creating the XMLHttpRequest object.");
  } else {
    return xmlHttp;
  }
}

// read a file from the server
function process(ciudad, idioma, div) {
	if (ciudad) { cache.push(ciudad+"*"+idioma+"*"+div); }
  // only continue if xmlHttp isn't void
  if (xmlHttp) {
    // try to connect to the server
    try {
      // continue only if the XMLHttpRequest object isn't busy
      // and the cache is not empty
      if ((xmlHttp.readyState == 4 || xmlHttp.readyState == 0) && cache.length > 0) {
		  	var cacheEntry = cache.shift();
			var cacheArray = cacheEntry.split("*");
			codigo = cacheArray[0];
			lang = cacheArray[1];
			divDestino = cacheArray[2];
			//var serverAddress = 'proxy.php';
			var getParams = 'ciudad='+codigo;

		  // initiate reading a file from the server
		  xmlHttp.open('GET', serverAddress + '?' + getParams, true);
		  xmlHttp.onreadystatechange = handleRequestStateChange;
		  xmlHttp.send(null);
	  }
    }
    // display the error in case of failure
    catch (e) {
      alert("Can't connect to server:\n" + e.toString());
    }
  }
}

// function called when the state of the HTTP request changes
function handleRequestStateChange() {
  // when readyState is 4, we are ready to read the server response
  if (xmlHttp.readyState == 4) {
    // continue only if HTTP status is "OK"
    if (xmlHttp.status == 200) {
      try {
        // do something with the response from the server
        handleServerResponse();
      }
      catch(e) {
        // display error message
        alert("Error reading the response: " + e.toString());
      }
    } else {
      // display status message
      alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
    }
  }
}
function getNode(xml, xpath){
	var node = xml.selectSingleNode(xpath);
	if(node){
		return node.value;
	}
	return '';
}
// handles the response received from the server
function handleServerResponse() {
  // read the message from the server
  var xmlResponse = xmlHttp.responseXML;
  // obtain the XML's document element
  xmlRoot = xmlResponse.documentElement;
  <!--[if IE 7]>
if (typeof document.body.style.maxHeight != "undefined") { // PARA IE7, MOZILLA
    var temperature = getNode(xmlRoot, 'channel/item/yweather:condition/@temp')
	var icon = getNode(xmlRoot, 'channel/item/yweather:forecast/@code');
	var text = getNode(xmlRoot, 'channel/item/yweather:forecast/@text');
	var maxima = getNode(xmlRoot, 'channel/item/yweather:forecast/@high');
	var minima = getNode(xmlRoot, 'channel/item/yweather:forecast/@low');
  } else { // PARA IE6 y anteriores
	var temperature = xmlRoot.getElementsByTagName("yweather:condition").item(0).attributes.getNamedItem("temp").value;
	var icon = xmlRoot.getElementsByTagName("yweather:forecast").item(0).attributes.getNamedItem("code").value;
	var text = xmlRoot.getElementsByTagName("yweather:forecast").item(0).attributes.getNamedItem("text").value;
	var maxima = xmlRoot.getElementsByTagName("yweather:forecast").item(0).attributes.getNamedItem("high").value;
	var minima = xmlRoot.getElementsByTagName("yweather:forecast").item(0).attributes.getNamedItem("low").value;
  }
  // generate HTML output
  var html = '';
  // iterate through the arrays and create an HTML structure
  if (lang=="es") {
	  var langMax='Máxima';
	  var langMin='Mínima';
  } else {
	  var langMax='High';
	  var langMin='Low';
  }
  html = '<div style="float:left; width:45px;"><p><img src="../images/weather/'+icon+'.gif" align="left" alt="'+text+'"/></p></div><div style="float:left; WIDTH: 160px;"><p>Temp.: '+temperature+' ºC<br /><strong>'+langMax+'</strong>: '+maxima+' ºC  <strong>'+langMin+'</strong>: '+minima+' ºC</p>';
  // obtain a reference to the <div> element on the page

  myDiv = document.getElementById(divDestino);
  // display the HTML output
  myDiv.innerHTML = html;
  setTimeout("process();", 500);
}