var http_request ;        // global http_request
var browser ;             // browser name
var common_folder ;       // Folder where to find the xmlburst for backend process

// Initializes the objects used in AJAX things 
function initAjaxEngine(http_request_prefix , xmlburst_folder , ajax_wait_msg)
{
  if(! ajax_wait_msg)
    ajax_wait_msg = "Please wait!" ;
  
  browser = navigator.appName; //find the browser name  
  common_folder = http_request_prefix + "/" + xmlburst_folder ;	

  var $dialog = $('<div>' + ajax_wait_msg + '</div>');
  
  $(document).ajaxStart(function()
  {  
	$dialog.dialog(
	{
	  dialogClass: 'wait_box',
	  width: 300,
	  height: 100,
	  resizable: false,
	  modal: true
	});
	
	// Hide the title bar
	$(".wait_box .ui-dialog-titlebar").hide();
  }) ;	
  $(document).ajaxStop(function()
  {
	$dialog.dialog("destroy") ;
  }); 
} // initAjaxEngine

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(params)
{
  var call_url = common_folder + "/create_ajax_object.php" ;
  
  // alert("call_url: " + call_url) ; // debug
  
  $.ajax(
  {
    url: call_url, 
	data: params, 
    success: function(returned_data, textStatus, XMLHttpRequest)
    {
	  var xml_doc ;
	  var error_msg = "" ;
	  
	  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(returned_data) ;
		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(returned_data,"text/xml"); 
        xml_doc.async = "false" ;
        if (xml_doc.documentElement.nodeName == "parsererror") 
		  error_msg = "Error in XML " ; 
      }	  
	  
	  // If no error continue
	  if (error_msg == "") 
	  {	
	    // alert("returned_data: " + returned_data) ; // debug
        
        // If there is no error then show the returned object in a dialog box
		// **************************************************************
		var xml_root = xml_doc.documentElement ; // first create the xml doc
		var returned_html = getElementContent(xml_root,"html_source") ;
		
		// 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" ;
		$("#" + ajax_obj_id).html(returned_html) ;
		$("#" + ajax_obj_id).dialog({modal: true, autoOpen: false, close: function() {$(this).dialog("destroy") ;}}) ; // do not open before setting all attributes
		
		// Set the width of the dialog
		var obj_width = checkElementContent(xml_root,"width") ;
		if (obj_width != null)
		  $("#" + ajax_obj_id).dialog('option','width',parseInt(obj_width)) ;
		  
		// Set the postion of the dialog
		var obj_position = checkElementContent(xml_root,"position") ;
		if (obj_position != null)
		  $("#" + ajax_obj_id).dialog('option','position',obj_position) ;
		else	
		  $("#" + ajax_obj_id).dialog('option','position',"center") ;
		
		// Set the title of the dialog
		var obj_title = checkElementContent(xml_root,"title") ;
		if (obj_title != null)
		  $("#" + ajax_obj_id).dialog('option','title',obj_title) ;
		  
		// Set the css class of the dialog
		var obj_class = checkElementContent(xml_root,"css_class") ;
		if (obj_class == null)
		  obj_class = "ajax_obj" ;
		$("#" + ajax_obj_id).dialog('option','dialogClass',obj_class) ;
		  
		// Set the dialog resizable or not
		var resizable = checkElementContent(xml_root,"resizable") ;
		if (resizable == "No")
		  $("#" + ajax_obj_id).dialog('option','resizable',false) ;
		  
		// Finally open the dialog  
		$("#" + ajax_obj_id).dialog("open") ;
	  }
      else
	  {
        alert(error_msg) ;
		alert("returned_data: " + returned_data) ; //debug
		document.write(returned_data) ;
      }		
    }, // on success function  plus parameter list to the ajax function call
	error: function(XMLHttpRequest, textStatus, errorThrown) 
	{
	  alert("Status: " + XMLHttpRequest.status) ; // debug
	  document.write(XMLHttpRequest.responseText) ;
	}
  }) ; 
  
  return false ;  
} // loadAjaxObject

// 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 ;
   
  request_str = 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 ;
  // alert("request_str: " + request_str) ; //debug
  http_request.open("GET",request_str,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();
		  //alert("return_val: " + return_val) ; //debug
          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 params = "prog=" + program_code + "&" + args ;
  
  $.ajax({url: common_folder + "/run_backend_script.php", data: params, 
  success: function(returned_data, textStatus, XMLHttpRequest)
  {
	var xml_doc ;
	var error_msg = "" ;
	
	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(returned_data) ;
	  if (xml_doc.parseError.errorCode != 0)
		error_msg = xml_doc.parseError.reason ; 
	}
	else // other browsers
    {
      var parser = new DOMParser(); 
      xml_doc = parser.parseFromString(returned_data,"text/xml"); 
      xml_doc.async = "false" ;
      if (xml_doc.documentElement.nodeName == "parsererror") 
	    error_msg = returned_data ; 
    }	  
	
	// If no error continue
	if (error_msg == "") 
	{	  
	  var xml_root = xml_doc.documentElement ;
	  var prog_result = checkElementContent(xml_root,"prog_result") ;
	  //alert("prog_result: " + prog_result) ; //debug
	  if (prog_result != null)
		eval(prog_result) ;
	}
    else
	{
      alert("Error in XML Response: " + error_msg) ;
	  return false ;
    }		
  }}) ;
} // runBackEndProg

// Reruns a form and refreshes it usign AJAX methods
function refreshForm(form_name , page_id , params)
{
  // prepare the arguments to send to the AJAX handler: run_backend_script
  var cmd_line = "prog=refreshForm&form_name=" + form_name + "&page_id=" + page_id ;
  if (params)
    cmd_line += "&" + params ;

  // Also add any command line argument
  var all_args = location.search ;
  if (all_args != "")
    cmd_line += "&" + all_args.substring(1) ; // remove the ?

  // alert("cmd_line: " + cmd_line) ; // debug
  
  $.ajax(
  {
    url: common_folder + "/run_backend_script.php", data: cmd_line, 
	type: "GET", 
    success: function(returned_data, textStatus, XMLHttpRequest)
    {
      $("span#" + form_name).html(returned_data) ;
    }
  }) ;
} // refreshForm

// Saves the contents of a form using AJAX
function saveForm(form_name , page_id , params)
{
  // prepare the arguments to send to the AJAX handler: run_backend_script
  var cmd_line = "prog=saveForm&form_name=" + form_name + "&page_id=" + page_id ;
  if (params)
  {
    if (params.substring(0,1) != "&") // add the & if needed
      cmd_line += "&" ;
    cmd_line += params ;
  }	

  // Also add any command line argument
  var all_args = location.search ;
  if (all_args != "")
    cmd_line += "&" + all_args.substring(1) ; // remove the ?
	
    // alert("cmd_line: " + cmd_line) ; // debug
  
  $.ajax(
  {
    url: common_folder + "/run_backend_script.php"
	, data: cmd_line
	, type: "GET" 
    , success: function(returned_data, textStatus, XMLHttpRequest)
    {
	  // alert("returned_data: " + returned_data) ; // debug
      if (returned_data != "")
	    eval(returned_data) ;
    }
  }) ;
} // saveForm

// Deletes one or more record of the given form using AJAX
function deleteRecords(form_name , page_id , page_params , uids_input_name)
{
  // prepare the arguments to send to the AJAX handler: run_backend_script
  var cmd_line = "prog=deleteRecords&form_name=" + form_name + "&page_id=" + page_id ;
  if (page_params != "")
  {
    if (page_params.substring(0,1) != "&") // add the & if needed
      cmd_line += "&" ;
    cmd_line += page_params ;
  }	
  cmd_line += "&uids=" + document.getElementById(uids_input_name).value ;  

  // Also add any command line argument
  var all_args = location.search ;
  if (all_args != "")
    cmd_line += "&" + all_args.substring(1) ; // remove the ?
	
  alert("cmd_line: " + cmd_line) ; // debug
  
  $.ajax(
  {
    url: common_folder + "/run_backend_script.php"
	, data: cmd_line
	, type: "GET" 
    , success: function(returned_data, textStatus, XMLHttpRequest)
    {
	  alert("returned_data: " + returned_data) ; // debug
      if (returned_data != "")
	    eval(returned_data) ;
    }
  }) ;
} // deleteRecords

// 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 ;
}

// Converts the xml_text to the DOM XML object and returns it. Returns false if it fails
function xmlRoot(xml_text)
{
  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(xml_text) ;
	if (xml_doc.parseError.errorCode != 0)
	{
	  alert("Error in XML Response: " + xml_doc.parseError.reason) ; 
	  return false ;
	}  
  }
  else // other browsers
  {
    var parser = new DOMParser(); 
    xml_doc = parser.parseFromString(xml_text,"text/xml"); 
    xml_doc.async = "false" ;
    if (xml_doc.documentElement.nodeName == "parsererror") 
	{
      alert("Error in XML Response: " + xml_text) ; 
	  return false ;
	}  
  }	
  var xml_root = xml_doc.documentElement ;
  return xml_root ;
} // xmlRoot

function updateJEdittable(elm_id , new_value , uid)
{
  runBackEndProg('updateJEdittable("' + elm_id + '","' + new_value + '",' + uid + ') ;') ;
} // updateJEdittable

// add a string to hash
function addHash(in_str)
{
  var hash_str = $.address.hash() ; // get the current hash
			
  if (hash_str != "")
	hash_str += "&" ;
  hash_str += in_str ;  
  $.address.hash(hash_str) ; // update browser hash uing jquery address plugin
} // addHash

// remove an argument or all arguments with the same name from browser hash
function removeHash(in_str)
{
  var hash_str = $.address.hash() ; // get the current hash
			
  // First find if this item has a = sign or not
  // If yes we simply replace it with "" in the hash, otherwise
  // we have to first find it in the hash and then remove it
  var eq_pos = in_str.indexOf("=") ; // position of = sign

  if (eq_pos == -1) 
  {
	// Find it in the hash with = sign
	var var_pos = hash_str.indexOf(in_str + "=") ; 

	while (var_pos != -1) // var exists in the hash
	{
	  var var_end_pos = hash_str.indexOf("&",var_pos) ; // end position for this var, before the next &
	  var cur_var ; // current value for this variable in the hash
	
	  if (var_end_pos != -1)
	    cur_var = hash_str.substring(var_pos,var_end_pos) ;
	  else
	    cur_var = hash_str.substring(var_pos) ; // extract until end of string
	  hash_str = hash_str.replace("&" + cur_var,"") ; // remove it with the & before it
	  hash_str = hash_str.replace(cur_var,"") ; // if not, just remove it
	  
	  var_pos = hash_str.indexOf(in_str + "=") ; 
	} // while var exists in the hash
  } // not been given full var
  else // the whole var has been given
  {
	// Simply remove it 
	// Try to remove it both with & and if not, then without &
	hash_str = hash_str.replace("&" + in_str,"") ;
	hash_str = hash_str.replace(in_str,"") ;
  }
			
  if (hash_str == "") // For some reason if we do not this, the page jumps to the top
    hash_str = " " ;
  $.address.hash(hash_str) ; // update browser hash uing jquery address plugin
} // removeHash
		
// update a string in the browser hash. Add or Update
function updateHash(in_str)
{
  var hash_str = $.address.hash() ; // get the current hash
			
  // First find if this item is alreay in the hash
  var eq_pos = in_str.indexOf("=") ; // position of = sign
  var var_part = in_str.substring(0,eq_pos + 1) ; // ge the part that shows the variable part like "cat_id="
			
  // now see if the var part is already in the hash, replace it
  var var_part_pos = hash_str.indexOf(var_part) ;
  if (var_part_pos != -1)
  {
	var var_part_end_pos = hash_str.indexOf("&",var_part_pos) ; // end position for this var, before the next &
	var cur_var ; // current value for this variable in the hash
	
	if (var_part_end_pos != -1)
	  cur_var = hash_str.substring(var_part_pos,var_part_end_pos) ;
	else
	  cur_var = hash_str.substring(var_part_pos) ; // extract until end of string
	hash_str = hash_str.replace(cur_var,in_str) ;
  }
  else
  {
	if (hash_str != "")
	  hash_str += "&" ;
	hash_str += in_str ;
  }
  
  if (hash_str == "") // For some reason if we do not this, the page jumps to the top
    hash_str = " " ;
  $.address.hash(hash_str) ; // update browser hash uing jquery address plugin
} // updateHash

