/*
 * Copyright 2006 SitePoint Pty. Ltd, www.sitepoint.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS;
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
*/


//### modified by e-Business Systems #########
// ebsl version 2 - 21/03/08



function Ebsl_ajax_req_done(str)
{
	var req_id = 0;	//need to extract from str to get the request id (when implement multi-threading)
	ajax.response_trackers[req_id].Clear_timer();
	ajax.response_trackers[req_id].response_has_been_received = true;
	ajax.response_trackers[req_id].response_function(str);
}


function Ebsl_ajax_req_timed_out(req_id)
{
	ajax.response_trackers[req_id].timer_is_being_used = false;
	ajax.response_trackers[req_id].error_function(ajax.response_trackers[req_id].error_return_value);
}









//------------------------------------------------------
function Ebsl_ajax_response_tracker(id,error_function,response_function,error_return_value)
{
	this.id = id;
	this.error_function = error_function;
	this.error_function = error_return_value;
	this.response_function = response_function;
	this.response_has_been_received = false;
	this.timeout_id;
	this.timer_is_being_used = false;

}




Ebsl_ajax_response_tracker.prototype.Clear_timer = function (clip_no)
{
	if (this.timer_is_being_used)
	{
		clearTimeout(this.timeout_id);	
	}

}




Ebsl_ajax_response_tracker.prototype.Start_timer = function (time_allowed)
{
	this.timer_is_being_used = true;
	this.timeout_id = setTimeout("Ebsl_ajax_req_timed_out(" + this.id + ")",(1000 * time_allowed));

}




Ebsl_ajax_response_tracker.prototype.Reset = function ()
{
	
	this.Clear_timer();
	this.response_has_been_received = false;
	this.timer_is_being_used = false;

}



//------------------------------------------------------


function Ajax() 
{
  this.req = null;
  this.url = null;
  this.status = null;
  this.statusText = '';
  this.method = 'GET';
  this.async = true;
  this.dataPayload = null;
  this.readyState = null;
  this.responseText = null;
  this.responseXML = null;
  this.handleResp = null;
  this.responseFormat = 'text', // 'text', 'xml', 'object'
  this.mimeType = null;
  this.headers = [];
  
  
  this.response_wait_time = 5; //seconds
  this.response_trackers = new Array();	//need to multithread in due course, but just first array item used for time being
  

  
  
  this.Make_request = function(function_type, timeout_error_function, timeout_error_return_value, url, dataPayload, hand, format)
  {
  	var tracker_id;
  	if (this.response_trackers.length == 0)
  	{
  		this.response_trackers[0] = new Ebsl_ajax_response_tracker(0,null,null,"");
  		tracker_id = 0;
  	}
  	else
  	{
  		this.response_trackers[0].Reset();
  		tracker_id = 0;
  	}
  	
  	
  	this.response_trackers[tracker_id].error_function = timeout_error_function;
  	this.response_trackers[tracker_id].error_return_value = timeout_error_return_value;
  	this.response_trackers[tracker_id].response_function = hand;
  	this.response_trackers[tracker_id].Start_timer(this.response_wait_time);
  	//in due course, for multithreading, the tracker id needs to be added to the query string
  	
  	switch (function_type)
  	{
  		case 'doGet':
  		{
  			this.doGet(url, Ebsl_ajax_req_done, format);
  			break;
  		};
  		
  		case 'doPost':
  		{
  			this.doPost(url, dataPayload, Ebsl_ajax_req_done, format);
  			break;
  		};
  		
  		
		default:
  		{
  			window.alert("There has been an error: Ajax100");
  			break;
  		};
  		
  		

  	}
  };
  
  
  
 
  

  
  this.init = function() 
  {
    var i = 0;
    var reqTry = [ 
      function() { return new XMLHttpRequest(); },
      function() { return new ActiveXObject('Msxml2.XMLHTTP') },
      function() { return new ActiveXObject('Microsoft.XMLHTTP' )} ];
      
    while (!this.req && (i < reqTry.length)) {
      try { 
        this.req = reqTry[i++]();
      } 
      catch(e) {}
    }
    return true;
  };
  
  
  
  
  
  this.doGet = function(url, hand, format) 
  {
    this.url = url;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.doReq();
  };
  
  
  
  
  
  
  this.doPost = function(url, dataPayload, hand, format) 
  {
    this.url = url;
    this.dataPayload = dataPayload;
    this.handleResp = hand;
    this.responseFormat = format || 'text';
    this.method = 'POST';
    this.doReq();
  };
  
  
  
  
  
  
  this.doReq = function() 
  {
    var self = null;
    var req = null;
    var headArr = [];
    
    if (!this.init()) {
      alert('Could not create XMLHttpRequest object.');
      return;
    }
    req = this.req;
    req.open(this.method, this.url, this.async);
    if (this.method == "POST") {
      this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    if (this.method == 'POST') {
      req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    }
    self = this;
    req.onreadystatechange = function() {
      var resp = null;
      self.readyState = req.readyState;
      if (req.readyState == 4) {
        
        self.status = req.status;
        self.statusText = req.statusText;
        self.responseText = req.responseText;
        self.responseXML = req.responseXML;
        
        switch(self.responseFormat) {
          case 'text':
            resp = self.responseText;
            break;
          case 'xml':
            resp = self.responseXML;
            break;
          case 'object':
            resp = req;
            break;
        }
        
        if (self.status > 199 && self.status < 300) {
          if (!self.handleResp) {
            alert('No response handler defined ' +
              'for this XMLHttpRequest object.');
            return;
          }
          else {
            self.handleResp(resp);
          }
        }
        
        else {
          self.handleErr(resp);
        }
      }
    }
    req.send(this.dataPayload);
  };
  
  
  
  
  
  
  this.abort = function() 
  {
    if (this.req) {
      this.req.onreadystatechange = function() { };
      this.req.abort();
      this.req = null;
    }
  };
  
  
  
  
  
  
  this.handleErr = function() 
  {
    var errorWin;
    // Create new window and display error
    try {
    	//alert(this.responseText); // ####### temp #######-----------------------------------------------------------
    	alert("There has been an error: Ajax101"); 
    	
      //errorWin = window.open('', 'errorWin');
      //errorWin.document.body.innerHTML = this.responseText;
    }
    // If pop-up gets blocked, inform user
    catch(e) {
      alert('An error occurred, but the error message cannot be' +
      ' displayed because of your browser\'s pop-up blocker.\n' +
      'Please allow pop-ups from this Web site.');
    }
  };
  
  
  
  
  this.setMimeType = function(mimeType) 
  {
    this.mimeType = mimeType;
  };
  
  
  
  
  
  this.setHandlerResp = function(funcRef) 
  {
    this.handleResp = funcRef;
  };
  
  
  
  
  
  this.setHandlerErr = function(funcRef) 
  {
    this.handleErr = funcRef; 
  };
  
  
  
  
  
  this.setHandlerBoth = function(funcRef) 
  {
    this.handleResp = funcRef;
    this.handleErr = funcRef;
  };
  
  
  
  
  this.setRequestHeader = function(headerName, headerValue) 
  {
    this.headers.push(headerName + ': ' + headerValue);
  };
  
  
  
}











