/*  AJAX Callback
 *  2006 Tim Igoe (tim@jellymedia.com)
 *
/*--------------------------------------------------------------------------*/

var runner;

function ajax() 
{
  this.req = null;
  this.url = '/rpc.php';
  this.handler = null;
  this.method = 'GET';
  this.async = true;
  this.Req = null;
  this.responseFormat = 'text';
  this.postData = null;
  this.response = null;
  this.field = null;
  
   // Initilise the XMLHTTPRequest Object
  this.init = function()
  {
    if (!this.Req)
	{
      if (window.XMLHttpRequest) 
      { // Mozilla, Safari, ...
        this.req = new XMLHttpRequest();
		return true;
      }
      else if (window.ActiveXObject) 
      { // IE
       this.req = new ActiveXObject("Microsoft.XMLHTTP");
	   return true;
      }  
	  return false;
	}
	return true; // Already initilized
  };
  
  // Send the message
  this.sendReq = function()
  {
    if (!this.init())
	{
	  alert('Javascript Error - please make sure you are using an upto date browser.');
	  return;
	}

    runner++;
	this.run = runner;

	this.req.open(this.method, this.url + '?file=' + this.handler + '&query=' + this.postData, this.async);
	
	var self = this;
	
    // Process the return from the communication
	this.req.onreadystatechange = function ()
	{  
      if (self.req.readyState == 4)
      { 
        if (self.req.status == 200)
        {  
		  if (self.type == 'javascript')
		  {
            self.response = self.req.responseText;
			hideLoading();
            eval(self.response);
		  }
          else if (self.type == 'string')
		  {
            self.response = self.req.responseText.split("||");
            self.process(self.response);
		  }
          else if (self.type == 'array')
		  {
            self.response = self.req.responseText.split("\n");
		    self.processTable(self.response);
		  }
        }
		else if (this.req.status == 404)
		{
		  alert('Error - File Not Found');
		}
      }	 
	  
	  return this.response;
	}	

	this.req.send(null);
  };
  
  this.abort = function()
  {
    if (this.req)
	{
	  this.req.onreadystatechange = function() { };
	  this.req.abort();
	  this.req = null;
	}
  }; 
 
  this.process = function(data)
  {
	this.response = data;
    var response = '';
    for (var i = 0; i < this.response.length; i++)
    {
	  if (this.response[i] != '')
	  {
		this.response[i] = this.response[i].replace("\n", "");
  	    response += '<div class="unroll" onMouseOver="this.className=\'roll\'" onmouseout="this.className=\'unroll\'" onclick="';
		response += 'fillForm(\'' + this.field + '\', \'' + this.response[i] + '\');'
		if (this.onChange)
		  response += 'submitField(document.getElementById(\'' + this.field.substr(5) + '\'), \'calc_search\')';
		response += '">' + this.response[i] + '</div>';
	  }
    }
    if (response != '')
    {
  	  div = document.getElementById(this.field);
	  div.innerHTML = response;
      showDiv(this.field);
      response = null;
    }
    else
    { // No data - error
	  hideDiv(this.field)
    }
  
    hideLoading();
}
  
  this.processTable = function(data)
  {
	this.response = data;
    var response = '<table width="100%">';

    var show = true;
	var widths = false;
	var row = 0;

    if (this.response.length > 0)
	{
      for (var i = 0; i < this.response.length; i++)
      {
	    linedata = this.response[i].split("||");
		if (i == 0)
		{ // First row - contains row information
		  // Field 1 = Title Row status
		  // Field 2 = Column widths sent?
          // Field 3 = Rows
		  // Field 4 = Start
		  // Field 5 = End
		  if (linedata[0].match('hidden'))
		  {
            show = false;
		  }
		  else if (linedata[1] != 0)
		  { // 0 in first element of this row means we don't
		    // process the row
		  }
		  
		  if (linedata[1].match('widths'))
		  {
			widths = true;
		  }
		}
		else if (widths && i == 1)
		{ // Widths row - process and store the widths
		  var widthsData = linedata;
		}
		else if (linedata[0] == 'script')
		{
	      eval(linedata[1]);
		}
		else 
        {
		  var colStyle = 1;
		  
		  if (row == 0)
			response += "<thead>";
          else if (row == 1)
			response += "<tbody>";
			
		  if (show || i > 1)
            response += "<tr>";
		
          for (var j = 0; j < linedata.length; j++)
          {	
            if (row == 0)
		    { // First (real) Row - header
		      if (show)
			  {
				if (widths)
				{
				  if (widthsData[j] < 15)
				    response += '<th width="' + widthsData[j] + '%" style="writing-mode:tb-rl; filter: flipv() fliph();">' + linedata[j] + '</th>';
				  else				  
		            response += '<th width="' + widthsData[j] + '%">' + linedata[j] + '</th>';
				}
				else
		          response += '<th>' + linedata[j] + '</th>';
			  }
		    }
		    else
		    { // Other row - normal
			  if (colStyle == 2)
			    colStyle = 1;
			  else
			    colStyle = 2;
				
			  if (widths)
		        response += '<td width="' + widthsData[j] + '%" class="col' + colStyle + '">' + linedata[j] + '</td>';
			  else
		        response += '<td class="col' + colStyle + '">' + linedata[j] + '</td>';
		    }
		  }
	  
		  if (show || i > 1)
		  {
			if (widths && row == 0)
			  response += "<td width=\"20px\">&nbsp;</td>";
            response += "</tr>";
		  }

		  row++;		  
	    }
		
		if (row == 1)
		{
		  response += "</thead>";
		  if (widths)
		    response += "</table><div id=\"limitData\"><table width=\"100%\">";
		}
      }
      response += "</tbody>";
    }
	else
	{
	  response += "</tr>";
	  response += "<td align=\"center\">No Data, please refine your query.</td>";
	  response += "</tr>";
	}
	
	if (widths)
	  response += "</div>";
    response += "</table>";	
  	div = document.getElementById(this.field);
	div.innerHTML = response;
    showDiv(this.field);
    response = null;
	  
    hideLoading();
  }
}



function showDiv(divName)
{
  if (document.layers)
    document.layers[divName].display = "block";
  else 
    document.getElementById(divName).style.display = "block";
}

function hideDiv(divName)
{
  if (document.layers)
    document.layers[divName].display = "none";
  else
    document.getElementById(divName).style.display = "none";
}

function fillForm(field, value)
{
  // Get the field
  fieldEl = document.getElementById(field.substr(5));
  if (fieldEl)
    fieldEl.value = value;


  // Hide the AJAX Selection
  hideDiv(field);
}

function ProcessAjax(value, field, handler, type, onChange)
{
  if (type == null)
    type = 'string';
	
  showLoading();

  if (value == '')
  {
    hideDiv(field);
	hideLoading();
  }
  else
  {
    theAjax = new ajax();
	
	theAjax.type = type;
    theAjax.postData = value;
    theAjax.handler = handler;
    theAjax.field = field;
	
	if (onChange && type == 'string')
	  theAjax.onChange = true;
	
    theAjax.response = theAjax.sendReq();
 
    theAjax = null;
  }
}

function showLoading()
{
  showDiv('loading_box');
}

function hideLoading()
{
  hideDiv('loading_box');
}
