/**
* @version 20090605
*/

var Ajax = new Object();


Ajax.READY_STATE_UNINITIALIZED = 0;
Ajax.READY_STATE_LOADING = 1;
Ajax.READY_STATE_LOADED = 2;
Ajax.READY_STATE_INTERACTIVE = 3;
Ajax.READY_STATE_COMPLETE = 4;


// Constructor
Ajax.request = function(URL,handlerFunction,errorFunction,method,parameters,contentType) {
	this.URL = URL;
	this.parameters = parameters;
	this.xhr = null;
	this.succeded = handlerFunction;
	this.failed = (errorFunction) 
		? errorFunction
		: this.defaultError;
	this.makeRequest(URL,method,contentType,parameters);
  }


Ajax.request.prototype = {
	makeRequest: function(URL,method,contentType,parameters) {
		if(window.XMLHttpRequest) {
			this.xhr = new XMLHttpRequest();
		  } 
    else if(window.ActiveXObject) {
			this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
		  }
		if(this.xhr) {
			try {
				var loader = this;
				this.xhr.onreadystatechange = function() {
					loader.onReadyState.call(loader);
					//this.onReadyState();
				  }
				this.xhr.open(method, URL, true);
				//if(contentType)
				this.xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
        this.xhr.setRequestHeader('If-Modified-Since', 'Wed, 06 May 2009 00:00:00 GMT');
        //this.xhr.setRequestHeader('Accept-Charset','UTF-8');
        //this.xhr.setRequestHeader("Content-Type", contentType);
				this.xhr.send(parameters);
			  } 
      catch (err) {
				this.failed.call(this);
			  }
      }
    },


	onReadyState: function() {
		var xhr = this.xhr;
		if (xhr.readyState == Ajax.READY_STATE_COMPLETE) {
			if(xhr.status == 200 || xhr.status == 0) {
        if(this.succeded) {
				  this.succeded.call(this);
          }
        } 
      else {
				this.failed.call(this);
        }
      }
    },


	defaultError: function() {
		alert("Se ha producido un error al obtener los datos"
		+ "\n\nURL: " + this.URL
		+ "\nQuery String: " + this.parameters
		+ "\nReady State: " + this.xhr.readyState
		+ "\nStatus: " + this.xhr.status
		+ "\nHeaders: " + this.xhr.getAllResponseHeaders());
    }


  }

