var http_request ;        // global http_request
var browser ;             // browser name
var common_folder ;       // Folder where to find the xmlburst for backend process
var def_ajax_obj_layout ; // default layout for ajax popups

// Initializes the objects used in AJAX things 
function initAjaxEngine(base_folder , ajax_obj_layout)
{
  browser = navigator.appName; //find the browser name  
  if(browser == "Microsoft Internet Explorer")/* Create the object using MSIE's method */
	http_request = new ActiveXObject("Microsoft.XMLHTTP");
  else  /* Create the object using other browser's method */
	http_request = new XMLHttpRequest();
  
  //Set common folder to be used for AJAX calls
  if (base_folder == null)
    common_folder = "/xmlburst" ;
  else  
    common_folder = "/" + base_folder + "/xmlburst" ;
  def_ajax_obj_layout = ajax_obj_layout ;
} // initAjaxEngine

function debug(val , name) 
{
  alert(name + ": " + val) ;
}

function getElementContent(parent_element , element_name)
{
  var final_result = checkElementContent(parent_element,element_name) ;
  
  if (final_result == null)
    alert("Element: " + element_name + " not found under " + parent_element.nodeName);
  
  return trim(final_result) ; 
}

// Tries to find the content of element name under parent_element. Returns null if not found
function checkElementContent(parent_element , element_name)
{
  var final_result = null ;
  
  var child_nodes = parent_element.childNodes ;
	
  // Now find which of the found nodes are directly under parent element
  var no_of_nodes_found = 0 ;
  for (var i = 0 ; i < child_nodes.length ; i++)
  {
    if (child_nodes[i].nodeName == element_name)
	{
	  no_of_nodes_found++ ;
	  final_result = child_nodes[i].childNodes[0].nodeValue ;
    }	
  }  
  if (no_of_nodes_found > 1)
    alert("Element element_name found more than once under " + parent_element.nodeName);
  
  if (final_result != null)
    final_result = trim(final_result) ;
	
  return final_result ; 
} // checkElementContent

// Tries to find the content of element name under parent_element. Returns null if not found
function checkElementRoot(parent_element , element_name)
{
  var final_result = null ;
  
  var child_nodes = parent_element.childNodes ;
	
  // Now find which of the found nodes are directly under parent element
  var no_of_nodes_found = 0 ;
  for (var i = 0 ; i < child_nodes.length ; i++)
  {
    if (child_nodes[i].nodeName == element_name)
	{
	  no_of_nodes_found++ ;
	  final_result = child_nodes[i] ;
    }	
  }  
  if (no_of_nodes_found > 1)
    alert("Element element_name found more than once under " + parent_element.nodeName);
  
  return final_result ; 
} // checkElementRoot

// Causes an ajax object be created and returned by calling the file create_ajax_object.php
function loadAjaxObject(cur_obj , params)
{
  
  // Show the wait object
  //var ajax_wait = document.getElementById("ajax_obj") ; // hidden wait indicator // debug later
  //ajax_wait.style.display = "block" ;// debug later
  
  http_request.open("GET",common_folder + "/create_ajax_object.php?" + params + "&seconds=" + new Date().getTime(),true);
  http_request.send(null); 
  http_request.onreadystatechange = function()
  {
	if (http_request.readyState == 4)
    {
	  //debug later ajax_wait.style.display = "none" ; // hide the wait object

	  var xml_doc ;
	  var error_msg = "" ;
	  
	  //document.write(http_request.responseText) ;
	  if (browser == "Microsoft Internet Explorer")
	  {
	    // Use Microsoft XML object to parse the returned XML and show on screen
        xml_doc = new ActiveXObject("Microsoft.XMLDOM") ;
        xml_doc.async = "false" ;
	    xml_doc.loadXML(http_request.responseText) ;
		//alert(http_request.responseText) ;
		if (xml_doc.parseError.errorCode != 0)
		  error_msg = "Error in XML " + xml_doc.parseError.reason ; 
	  }
	  else // other browsers
      {
        var parser = new DOMParser(); 
        xml_doc = parser.parseFromString(http_request.responseText,"text/xml"); 
        xml_doc.async = "false" ;
        if (xml_doc.documentElement.nodeName == "parsererror") 
		  error_msg = "Error in XML " ; 
      }	  
	  // If no error continue
	  if (error_msg == "") 
	  {	  
	    var xml_root = xml_doc.documentElement ;
		// See what to show at the top of the AJAX object, either defined in the page or use the default for web site
		var page_layout = checkElementContent(xml_root,"page_layout") ;
        if (page_layout == null) // If page layout not specified for this page, then use the default for this web site 
 		  page_layout = def_ajax_obj_layout ;
		  
		// See in which object we should show the content  
		var ajax_obj_id = checkElementContent(xml_root,"show_in_element") ;
        if (ajax_obj_id == null) // If page layout not specified for this page, then use the default for this web site 
 		  ajax_obj_id = "ajax_obj" ;
		var ajax_obj = document.getElementById(ajax_obj_id) ; // hidden div
		if (ajax_obj == null) 
		  alert("The object with id: " + ajax_obj_id + " is missing or undefined. Usually a hidden div in the head_tag") ;
		
		// See if object height and width has been set by the page then do so otherwise do nothing
		var obj_height = checkElementContent(xml_root,"height") ;
		if (obj_height != null)
		  ajax_obj.style.height = obj_height ;
		var obj_width = checkElementContent(xml_root,"width") ;
		if (obj_width != null)
		  ajax_obj.style.width = obj_width ;
		
		// See if we need to auto position the object in the middle of the screen.  
		var positioning = checkElementContent(xml_root,"positioning") ;
		if (positioning == "auto")  
		{
          ajax_obj.style.position = "absolute" ;
		  var new_top = (parseInt(screen.height) - parseInt(ajax_obj.style.height)) / 2 - 80 ; // 80 is for probable top parts and toolbars
		  if (new_top < document.body.scrollTop + 30)
		    new_top = document.body.scrollTop + 30 ;
		  var new_left = (parseInt(screen.width) - parseInt(ajax_obj.style.width)) / 2 ;
		  
		  // check if there is a limit on the left hand side of the object
		  var min_left = checkElementContent(xml_root,"min_left") ;
		  if (min_left != null && new_left < min_left)
		    new_left = min_left ;
		  else if (new_left < 10)
		    new_left = 10 ;
			
		  // Make sure the new left and top have the px at the end
		  new_top = String(new_top) ;
		  new_left = String(new_left) ;
          if (new_top.indexOf('px') == -1)		  
		    new_top += 'px' ;
          if (new_left.indexOf('px') == -1)		  
		    new_left += 'px' ;

		  // finally assign top and left	
		  if(new_top)
		    ajax_obj.style.top = new_top ;
		  else
		    ajax_obj.style.top = "100px" ;		  
		  if(new_left)
		    ajax_obj.style.left = new_left ;
		}
	    else // If not automatic positioning then check if there is any specfic postion required
	    {
		  //debug later
	    } 
		// Finally set the contents
		page_layout = page_layout.replace("#page_content#",getElementContent(xml_root,"html_source")) ;
		//document.write(page_layout) ; // debug
		ajax_obj.innerHTML = page_layout ;
		// Now show it
		//debug should use these functions later on with more care $(ajax_obj_id).appear() ;
	    ajax_obj.style.display = "block" ;
	  }
      else
	  {
        alert(error_msg) ;
		document.write(http_request.responseText) ;
      }		
	}  
  } // onreadystatechange 
  return false ;  
} // loadAjaxObject

function unloadAjaxObject() 
{
  document.getElementById("ajax_obj").style.display = "none" ;
  //debug later Effect.DropOut('ajax_obj') ;
  return false ;
}

// Updates a child select element when the parent element changes. This is called when the parent of a child element gets updated, so child element also updates 
function updateChildElement(element_id , link_field , link_value , element_name , show_on_no_value , show_on_no_rec)
{
  // If no record found and is show_on_no_rec is not defined then show_on_no_value instead
  show_on_no_value = typeof(show_on_no_value) != 'undefined' ? show_on_no_value : "" ;
  show_on_no_rec = typeof(show_on_no_rec) != 'undefined' ? show_on_no_rec : show_on_no_value ;
   
  http_request.open("GET",common_folder + "/create_ajax_object.php?obj=elm&element_id=" + element_id + "&lnk_field=" + link_field + "&lnk_val=" + link_value + "&show_on_no_value=" + show_on_no_value,true);
  http_request.send(null); 
  http_request.onreadystatechange = function()
  {
    if (http_request.readyState == 4)
    {
      // alert(browser) ;
	  var cur_obj = document.forms[0].elements[element_name] ;
	  
	  // If it is Internet Explorer because of IE bug, I can not simply assign the return value to innerHTML. This is a known bug
	  if (browser == "Microsoft Internet Explorer")
	  {
	    var initial_len = cur_obj.options.length ;
        for (var i = 0 ; i < initial_len ; i++)
          cur_obj.remove(0) ;
  
        var xml_doc = new ActiveXObject("Microsoft.XMLDOM") ;
        xml_doc.async = "false" ;
	    xml_doc.loadXML(http_request.responseText) ;
		//alert(http_request.responseText) ;
        if (xml_doc.parseError.errorCode == 0) 
	    {	  
	      var xml_root = xml_doc.documentElement ;
          for (i = 0 ; i < xml_root.childNodes.length ; i++)
	        cur_obj.options[i] = new Option(xml_root.childNodes[i].childNodes[0].nodeValue,xml_root.childNodes[i].attributes.item(0).value) ;
		  // If no record found the put the record not found message
		  if (i ==  0)
	  	  {
	        // cur_obj.options[i] = new Option("--No Record Found--","--No Record Found--") ;
	        cur_obj.options[i] = new Option(show_on_no_rec,show_on_no_rec) ;
		    cur_obj.disabled = true ; 
		  }  
		  else
		    cur_obj.disabled = false ;  
	    }
        else
          alert("Error in XML: " + xml_doc.parseError.reason) ;
	  }	
      else  // Browsers other than Internet Explorer
	  {
	    var return_val = http_request.responseText ;
        if(return_val == "<options></options>")
		{
		  cur_obj.innerHTML = "<option value='--No Record Found--'>--No Record Found--</option>" ; 	
		  cur_obj.disabled = true ; 
		}
		else
		{
		  // can not simply use cur_obj.innerHTML = return_val because of the use of CDATA we need to parse the XML and create the innerHTML
          parser = new DOMParser();
          xml_doc = parser.parseFromString(return_val,"text/xml");
	      
		  var xml_root = xml_doc.documentElement ;
		  var new_inner_html = "" ;
          for (i = 0 ; i < xml_root.childNodes.length ; i++)
		  {
		    cur_node = xml_root.childNodes[i] ;
	        new_inner_html += "<option value='" + cur_node.getAttribute("VALUE") + "'>" ;
	        new_inner_html += cur_node.textContent + "</option>" ;
		  }
		  cur_obj.innerHTML = new_inner_html ; 
          cur_obj.disabled = false ; 		  
		}
	  }	
	}  
  } 
} // updateChildElement

// Runs the program code in the back end.
function runBackEndProg(program_code , args)
{
  var call_url = common_folder + "/run_backend_script.php?prog=" + program_code + "&" + args + "&seconds=" + new Date().getTime() ;
  
  http_request.open("GET",call_url,true); // call the url to run the program
  http_request.send(null); 
  
  //return true ;
  http_request.onreadystatechange = function()
  {
    if (http_request.readyState == 4)
    {
	  var xml_doc ;
	  var error_msg = "" ;
	  
	  // alert("http_request.responseText: " + http_request.responseText) ; //debug
	  if (browser == "Microsoft Internet Explorer")
	  {
	    // Use Microsoft XML object to parse the returned XML and show on screen
        xml_doc = new ActiveXObject("Microsoft.XMLDOM") ;
        xml_doc.async = "false" ;
	    xml_doc.loadXML(http_request.responseText) ;
		if (xml_doc.parseError.errorCode != 0)
		  error_msg = "Error in XML Response: " + xml_doc.parseError.reason ; 
	  }
	  else // other browsers
      {
        var parser = new DOMParser(); 
        xml_doc = parser.parseFromString(http_request.responseText,"text/xml"); 
        xml_doc.async = "false" ;
        if (xml_doc.documentElement.nodeName == "parsererror") 
		  error_msg = "Error in XML Response: " + http_request.responseText ; 
      }	  
	  // If no error continue
	  if (error_msg == "") 
	  {	  
	    var xml_root = xml_doc.documentElement ;
		var prog_result = getElementContent(xml_root,"prog_result") ;
		// alert("prog_result: " + prog_result) ; //debug
		eval(prog_result) ;
	  }
      else
	  {
        alert(error_msg) ;
		return false ;
      }		
	}  
  } 
} // runBackEndProg

// In a heirarchy of 3 elements when the top parent changes, its child will also update, this function resets its second level child
// or its grand child
function resetGrandChild(element_name , reset_message)
{
  var cur_obj = document.forms[0].elements[element_name] ;
  var initial_len = cur_obj.options.length ;
      for (var i = 0 ; i < initial_len ; i++)
        cur_obj.remove(0) ;
  cur_obj.options[0] = new Option(reset_message,reset_message) ;
  cur_obj.disabled = true ;
}

