/*
 * interxml.js
 *
 * Copyright (c) 2007-2008 by Szymon 'polemon' Bereziak <polemon@polemon.org>
 *  - for JustBase.FM webradio
 *
 * This file provides the xml class definition, for the 'xml' namespace
 * that returns an Ajax request as XML-Object.
 * 
 * Usage:
 *
 * var reqobj = new xml.InterXml(<url>, <callback>, [<post-data>]);
 *
 * First and second parameter is required.
 * If no <post-data> parameter is given, the request is performed as
 * a simple HTTP GET request, an HTTP POST is performed if there is
 * any data supplied.
 *
 * Context is always the XML-Object itself, you can access the content
 * of the responce with 'this.responseText', for instace.
 *
 * This file is distributed under MIT-License
 *
 */

/* --- GetXMLObjekt -------------- */

// Namespace object for XMLHttpRequests
var net = new Object();

// Friendly names for return states
net.UNINITIALIZED = 0;
net.LOADING = 1;
net.LOADED = 2;
net.INTERACTIVE = 3;
net.COMPLETE = 4;

// container for the XMLHttpRequest objekt
net.request = null;

// GetXMLObjekt class - creates the XMLHttpRequest objekt
net.GetXMLObject = function() {
  if(window.XMLHttpRequest)
    this.request = new XMLHttpRequest();
  else if(typeof ActiveXObject != "undefined")
    this.request = new ActiveXObject("Microsoft.XMLHTTP");
};

/* --- XML retrieve -------------- */

// Namesspace objekt for XML retrieve
var xml = new Object();

// xml Properties
xml.url = "";
xml.callback = null;
xml.postdata = null;

// Request container
xml.req = null;

// Construktor - c_target is the targeted callback function
xml.InterXml = function(url, c_target, post_params) {
  this.url = url;
  this.callback = c_target;
  this.postdata = (post_params) ? post_params.toString() : null; // Stringify params

  this.loadXml(url);
};

// InterXml.loadXml() - Method for loading an XML structure
xml.InterXml.prototype = {
  loadXml:function(url) {
    this.req = new net.GetXMLObject();
	
    if(this.req.request) {
      var method = (this.postdata != null) ? 'POST' : 'GET';
		
      // Objekt copy
      var retobj = this;
		
      this.req.request.onreadystatechange = function() {
        // Callback handler gives itself to its own handler
        retobj.returnCall.call(retobj);
      };
		
      this.req.request.open(method, this.url, true);
      this.req.request.send(this.postdata);
    }
  },

  // Callback handler - calls defined function
  returnCall:function() {
    var state = this.req.request.readyState;
	
    // Do on COMPLETE, can be anything else, though
    if(state == net.COMPLETE) {
      var retr = this.req.request;
      var HTTPret = retr.status;

      if(HTTPret == 200 || HTTPret == 0) // Callback in XMLHttpRequest context
        this.callback.call(retr);
      else {
// 	alert("ERROR AT XML REQUEST\nHTTP: " + HTTPret 
// 	  + "\nSTATE: " + state 
// 	  + "\nURL: " + this.url
// 	  + "\nCALLBACK: " + this.callback
// 	  + "\nHeaders: " + this.req.request.getAllResponseHeaders());
      }
    }
  }
};

