/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete)
        {
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}

/* Replaces the options of the "destination" select using the options found in "URL" page */
function replaceSelectOptions(URL, destination) {
	var fnCarica = function (oGet) {  
		objSelect = document.getElementById(destination) ;
		var sJSON = oGet.responseText;
		var oJSON = eval(sJSON);

		/* deleting the old options */
		while (objSelect.options.length>0){
			objSelect.options[0] = null;
		}
		
		/* adding the new options */
		for( n=0;n<=oJSON.length;n++) { 
			objSelect.options[objSelect.options.length] = new Option( oJSON[n].text , oJSON[n].value );
			
			/* if is set the parameter "selected", sets the select selectedIndex to the current index */
			if (oJSON [n].selected=="selected"){
				objSelect.selectedIndex=objSelect.options.length-1;
			}
			
		}
	};
	new XHConn().connect(URL, 'GET', '' , fnCarica);
}

/* Replaces the options of the "destination" select using the options found in "URL" page */
function replaceText(URL, destination) {
	var fnCarica = function (oGet) {  
		objText = document.getElementById(destination);
		var sJSON = oGet.responseText;
		var oJSON = eval(sJSON);
		
		objText.value =  oJSON [0].value;
		alert(oGet.responseText); 
		
	};
	new XHConn().connect(URL, 'GET', '' , fnCarica);
}
