var xmlHttp = createXmlHttpRequestObject();
var showErrors = true;

function createXmlHttpRequestObject(){
  var xmlHttp;

	try{
    xmlHttp = new XMLHttpRequest();
  }catch(e){
		var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP");

    for(var i=0; i<XmlHttpVersions.length && !xmlHttp; i++){
      try{ 
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      }catch(e){} 
    }
  }
  if(!xmlHttp)
	  alert("Error creating the XMLHttpRequest object.");
  else 
    return xmlHttp;
}

function displayError($message){
  if(showErrors){
    showErrors = false;
    alert("Error encountered: \n" + $message);
  }
}

function getFeed(feed){
  if(xmlHttp){
    try{
      if(xmlHttp.readyState == 6 || xmlHttp.readyState == 0) {
        document.getElementById("loading").style.display = "block";
        params = "feed=" + feed;
        xmlHttp.open("POST", "rss/rss_reader.php", true);
        xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttp.onreadystatechange = handleHttpGetFeeds;
        xmlHttp.send(params);
      }else{
        setTimeout("getFeed('" + feed + "');", 1000);
      }
    }catch(e){
      displayError(e.toString());
    }
  }
}

function handleHttpGetFeeds(){
  if(xmlHttp.readyState == 4){
    if(xmlHttp.status == 200){
      try{
        displayFeed();
      }catch(e){
        displayError(e.toString());
      }
    }else{
      displayError(xmlHttp.statusText);
    }
  }
}

function displayFeed(){
  var response = xmlHttp.responseText;
	var titlesContainer = document.getElementById("feedContainer");

  if(response.indexOf("ERRNO") >= 0 || response.indexOf("error:") >= 0 || response.length == 0)
    throw(response.length == 0 ? "Void server response." : response);
  
  document.getElementById("loading").style.display = "none";
  titlesContainer.innerHTML = response;
  document.getElementById("feedContainer").style.display = "block";
}
