var RequestObject = false;
var ResponseXMLObject;
var ResponseXMLDocument;
var ResponseText;
//var strEventHandler;

var Parameter = new Array();
var xmlPage;
var cstrNullValue = "";

var strParentName;
var strParentID;
var strChildName ;
var strChildID;
var strChildDescr;

    function getAjaxValuesGeo(strModule, strParent, strChild, optionParentID, optSuffix, strServerPage, strSysLID)  
    {   	
//	window.alert ('getAjaxValuesGeo...'+strModule+','+strParent+','+strChild+','+optionParentID.value+','+optSuffix);
	strParentName = "cbo" + strParent + optSuffix;
	strChildName = "cbo" + strChild + optSuffix;

      // set hourglass cursor
      document.body.style.cursor = "wait";
      	
  	  // Clear always the current Ajax parameter list first
  	  clearAjaxParameter();

	xmlPage = strServerPage + "Sysadmin/";

    switch(strChild) {
        case 'Country': 
        	xmlPage = xmlPage + "XMLCountry.asp";
        	strChildID = "CountryID";
        	strChildDescr = "CountryDescr";
        	break;
        case 'State': 
        	xmlPage = xmlPage + "XMLState.asp";
        	strChildID = "StateID";
        	strChildDescr = "StateDescr";
        	break;
        case 'City': 
        	xmlPage = xmlPage + "XMLCity.asp";
        	strChildID = "CityID";
        	strChildDescr = "CityDescr";
        	break;
    }

    switch(strParent) {
        case 'Site': 
        	xmlPage = xmlPage + "?SiteID=" + optionParentID.value;
        	strParentID = "SiteID";
        	break;
        case 'Country': 
        	xmlPage = xmlPage + "?CountryID=" + optionParentID.value;
        	strParentID = "CountryID";
        	break;
        case 'State': 
        	xmlPage = xmlPage + "?StateID=" + optionParentID.value;
        	strParentID = "StateID";
        	break;
    }
    
   	xmlPage = xmlPage + "&SysLID=" + strSysLID;
   	xmlPage = xmlPage + "&cboType=" + optSuffix;
   	xmlPage = xmlPage + "&Module=" + strModule;
   	  	
  	  // set ReadOnly flag for country
	if (strParent == 'Site') {
    	  var ctlSite = document.getElementById('cboCountry'+optSuffix);
    	  
    	  clearAndAddNullListItem(ctlSite);
  	    
  	  // set ReadOnly flag
  	  setMyControlDisabled(ctlSite, true);
	}

  	  // set ReadOnly flag for state, city
	if ((strParent == 'Site') || (strParent == 'Country')) {
    	  
		// attention: recursive loop...
    	  if (strChild != 'City') {
	    	var ctlState = document.getElementById('cboState'+optSuffix);
		clearAndAddNullListItem(ctlState);
	  	setMyControlDisabled(ctlState, true);
	  }

    	  var ctlCity = document.getElementById('cboCity'+optSuffix);
    	  clearAndAddNullListItem(ctlCity); 	    
  	  setMyControlDisabled(ctlCity, true);
	}


  	// Set the Parameter(s)
  	if (optionParentID.value == cstrNullValue)
  	  {
    	  var ctl = document.getElementById(strChildName);
    	  
    	  clearAndAddNullListItem(ctl);
  	    
  	  // set ReadOnly flag
  	  setMyControlDisabled(ctl, true);


          // show normal cursor
          document.body.style.cursor = "auto";
  	    
    	}
    	else
    	{
    	  var ctl = document.getElementById(strChildName);

	 setMyControlDisabled(ctl, false);

    	 addAjaxParameter(strParentID, optionParentID.value);

  	    // Send Ajax request and assign event handler
  	    sendAjaxRequest("handleAjaxResponseListBox");
    	}  


	// Refresh Cities with change of Country or change of State
	// Carefull: this is called recursive
	if ((strParent == 'Country') && (strChild == 'State')) {
		var ctlCity1 = document.getElementById('cboCity'+optSuffix);
		if (ctlCity1) {
			getAjaxValuesGeo(strModule, strParent, 'City', optionParentID, optSuffix, strServerPage, strSysLID)
		}
	}
    } 

function createAjaxRequestObject()
{

  // try to create a new instance of the xmlhttprequest object        
  try {
  
      // Browser = Microsoft Internet Explorer
      if(window.ActiveXObject) {
          for(var i = 5; i; i--) {
              try {
                  // loading of a newer version of msxml dll (msxml3 - msxml5) failed
                  // use fallback solution
                  // old style msxml version independent, deprecated
                  if( i == 2 ) {
                      RequestObject = new ActiveXObject( "Microsoft.XMLHTTP" );    
                  }
                  // try to use the latest msxml dll
                  else {                      
                      RequestObject = new ActiveXObject( "Msxml2.XMLHTTP." + i + ".0" );
                  }
                  break;
              } 
              catch(excNotLoadable) {                        
                  RequestObject = false;
              }
          }
      }
      // All other browsers (Mozilla, Opera ...)
      else if(window.XMLHttpRequest) {
          RequestObject = new XMLHttpRequest();
      }
  }
  // loading of xmlhttp object failed
  catch(excNotLoadable)
  {
      RequestObject = false;
  }

}

function sendAjaxRequest(EventHandler, Mode)
{
//    	window.alert ("sendAjaxRequest");

	// You can decide which mode will be used
	// Asynchron (true, false)	
	if (Mode == null)
		Mode = false;	// true;
		
	var NameValuePairs = "";
	var ContentLength = 0;
	
  // Previous request not finished yet, return
  if(RequestObject && RequestObject.readyState)
  {
		RequestObject.abort( );
		RequestObject = false;
  }

  // create a new instance of XMLHttpRequest object
  // if it fails, return
  if(!RequestObject) {
      createAjaxRequestObject();
      if(!RequestObject)
          return;
  }

	for(var i = 0; i < Parameter.length; i++) {
		NameValuePairs = NameValuePairs + escape(Parameter[i]) + "=" + escape(Parameter[i + 1]);
		
		if(i < Parameter.length - 1)
			NameValuePairs = NameValuePairs + "&";
		i++ // count one more	
	}


	// Send the request (Methode, Asynchron (true, false)
	RequestObject.open("POST", xmlPage, Mode);
	RequestObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	RequestObject.setRequestHeader("Content-Length", NameValuePairs.length);
	RequestObject.setRequestHeader("Connection", "close");

    // Set onload data event-handler
    RequestObject.onreadystatechange = new Function( "", "processAjaxResponse(" + EventHandler + ")" );

	// Send request
	RequestObject.send(NameValuePairs);
}

function processAjaxResponse(EventHandler)
{
//	window.alert ("processAjaxResponse=" + RequestObject.readyState);
	
    // status 0 UNINITIALIZED open() has not been called yet.
    // status 1 LOADING send() has not been called yet.
    // status 2 LOADED send() has been called, headers and status are available.
    // status 3 INTERACTIVE Downloading, responseText holds the partial data.
    // status 4 COMPLETED Finished with all operations.
    
    switch(RequestObject.readyState) {
        // uninitialized
        case 0:
        // loading
        case 1:
        // loaded
        case 2:
        // interactive
        case 3:
            break;
        // complete
        case 4:    
            // Check http status
            if( RequestObject.status == 200 ) {    // success
					ResponseXMLObject = RequestObject.responseXML;
					ResponseXMLDocument = ResponseXMLObject.getElementsByTagName("response").item(0);
					ResponseText = RequestObject.responseText;
//   				handleAjaxResponse();
				   EventHandler();

            }
            // loading not successfull, e.g. page not available
            else {
			    debugger;
                alert( "ERROR\n HTTP status = " + RequestObject.status + "\n" + RequestObject.statusText) ;
            }
            break;
    }
}

function getAjaxElementByTagName(objXMLDoc, tagName)
{
	var retValue = null;
	
	if(objXMLDoc.getElementsByTagName(tagName).item(0))
		if (objXMLDoc.getElementsByTagName(tagName).item(0).firstChild != null)
			// node was found and value can be returned
			retValue = objXMLDoc.getElementsByTagName(tagName).item(0).firstChild.nodeValue;

   if (retValue == null)
	  retValue = ""; // Return NullString instead of Null
	  		 
	return retValue;
}

function getAjaxElementsByTagNameAsArray(objXMLDoc, tagName)
{
	var retValue = new Array();
	
	for(var i = 0; i < objXMLDoc.getElementsByTagName(tagName).length; i++)
		retValue[i] = objXMLDoc.getElementsByTagName(tagName).item(i)

	return retValue;
}

function addAjaxParameter(vstrName, vvarValue)
{
    // Raise error message in case of missing name parameter
	if(vstrName == null || vstrName == "")
	{
		alert("The name of the Ajax Parameter must be given.");
	}

	// Assign given parameter
	Parameter[Parameter.length] = vstrName;
	Parameter[Parameter.length] = vvarValue;
		
}

function clearAjaxParameter()
{
	Parameter = new Array();
}



    function handleAjaxResponseListBox()
    {    	
      var i;
      var firstOption = null;
      var appendix=0;
    
      // This section will be called after the Ajax request is finished.
  	  var ctl = document.getElementById(strChildName);
  	  var arrChildID = getAjaxElementsByTagNameAsArray(ResponseXMLDocument, strChildID);
  	  var arrChildDescr = getAjaxElementsByTagNameAsArray(ResponseXMLDocument, strChildDescr);
  	  
    // remove ReadOnly flag
      setMyControlDisabled(ctl, false);	// PvS??

      if(ctl.options.length > 0)
        if(ctl.options[0].value == cstrNullValue)
          appendix = 1;
          
  	  // save 1st option - if it is a null-element
      clearAndAddNullListItem(ctl);

      // add another options from XML
  	  for(i=0; i<arrChildID.length; i++)
  	  {
  	    ctl.options[i + appendix] = new Option(arrChildDescr[i].childNodes[0].nodeValue, arrChildID[i].childNodes[0].nodeValue);
  	  }
              
      // show normal cursor
      document.body.style.cursor = "auto";
  	  
    }


    function clearAndAddNullListItem(ctl)
    {
	if (ctl) {

      var firstOption;
  	  
  	  // save 1st option - if it is a null-element
      if(ctl.options.length > 0)
        if(ctl.options[0].value == cstrNullValue)
          firstOption = ctl.options[0];
  	    
  	  // clear all options
  	  ctl.options.length = 0;

      // add 1st option - if present
      if(firstOption != null)
        ctl.options.add(firstOption);    

	}	// if (ctl)
    }
    
    function setMyControlDisabled (ctl, flgDisable)
    {
	if (ctl) {
		if (flgDisable == true) {
            ctl.setAttribute("disabled", "disabled");
		}
	else
		{
            ctl.removeAttribute("disabled");
		}
	}	// if ctl
    }
