//
// Simple ajax functionallity. 
//


//
// Create Ajax class
//
function Ajax() {
  this.iframes = [];
  this.ie = (document.all) ? true : false;
  }
  
  
//
// Add a frame using DOM interface (does not work for IE5)
//
Ajax.prototype.AddFrame = function() {
    var frame, id;
    if (!document.createElement) 
      return(false);
    no = this.iframes.length;
    id = 'ajaxsimple' + this.iframes.length;          
    if (this.ie) {
      frame = document.createElement('<iframe id="' + id + '" STYLE="display:none" onload="ajax.AjaxResponse(' + no + ', this.contentWindow.document.body.innerHTML)">');
      } else {
      var _this = this;
      frame = document.createElement('iframe');
      frame.setAttribute('id', id);
      frame.style.display = 'none';      
      frame.onload = function() { _this.AjaxResponse(no, this.contentDocument.body.innerHTML); };                      
      }             
    frame = document.body.appendChild(frame);      
    this.iframes[no] = { 'frame': frame, 'id': id, 'no': no, 'busy': false, 'callback': ''};      
    return(no);
    }      

//
// Find frame that is not in use, or create a new frame. Returns a frame-object.
//
Ajax.prototype.GetFrame = function() {
    for (var no in this.iframes) 
      if (!this.iframes[no].busy) return(no);          
    return(this.AddFrame());                      // create new frame
    }

  
//
// Make request. callback is called with one parameter that contains the
// innerHTML of the iframe used to make the request. Use e.g.
// eval() to transform this content into javascript data!
//
Ajax.prototype.AjaxRequest = function(url, callback) {
  var no = this.GetFrame();
  var _this = this;
  this.iframes[no].busy = true;                             // mark frame busy  
  this.iframes[no].callback = callback;                     // store callback  
  pars = 'no=' + no;     
  url += (url.indexOf('?') == -1) ? ('?' + pars) : ('&' + pars);     
  this.iframes[no].frame.src = url;        
  return(true);
  }
    


//
// Handle response to a request
//  
Ajax.prototype.AjaxResponse = function(no, data) {
  if (!this.iframes[no]) return(false);  
  callback = this.iframes[no].callback;
  this.iframes[no].busy = false;          
  return(callback(data));
  }


//
// Instantiate our Ajax object
//
var ajax = new Ajax; 
