/********************************************************
 * @Author mpoisson
 *
 * Clase para enviar un formulario html utilizando Ajax
 ********************************************************/

// Constructor de la clase
function AjaxConnector() {
	this._formItemCount = 0;
	this._handlerScript = '';
	this._containerID = '';
	this._waitContainerID = '';
	this._waitHtml = '';
	this._method = 'POST';
	this._contentTypeHeader = 'application/x-www-form-urlencoded';

	this.keyArray = new Array();
	this.valueArray = new Array();

	this._Strategy = new SimpleWriteStrategy();


	this.setMethod = AjaxConnector_setMethod;
	this.getMethod = AjaxConnector_getMethod;
	this.setHandlerScript = AjaxConnector_setHandlerScript;
	this.getHandlerScript = AjaxConnector_getHandlerScript;
	this.setStrategy = AjaxConnector_setStrategy;
	this.getStrategy = AjaxConnector_getStrategy;
	this.setContainerID = AjaxConnector_setContainerID;
	this.getContainerID = AjaxConnector_getContainerID;
	this.setWaitContainerID = AjaxConnector_setWaitContainerID;
	this.getWaitContainerID = AjaxConnector_getWaitContainerID;
	this.addFormItem = AjaxConnector_addFormItem;
	this.getFormItem = AjaxConnector_getFormItem;
	this.getWaitHtml = AjaxConnector_getWaitHtml;
	this.setWaitHtml = AjaxConnector_setWaitHtml;
	this.getFormItemCount = AjaxConnector_getFormItemCount;
	this.getContentTypeHeader = AjaxConnector_getContentTypeHeader;
	this.getXhttp = AjaxConnector_getXhttp;
	this.send = AjaxConnector_send;
	this.runStrategy = AjaxConnector_runStrategy;

	this._xHttp = this.getXhttp();
	this._Strategy.setXHttpRequest(this._xHttp);
}

/********************************************************
 * Funciones Publicas
 ********************************************************/
// setea metodo de envio para el formulario
function AjaxConnector_setMethod(value) {
	this._method = value;
}

// devuelve metodo de envio para el formulario
function AjaxConnector_getMethod() {
	return this._method;
}

// setea el archivo de manejo del lado del server
function AjaxConnector_setHandlerScript(script) {
	this._handlerScript = script;
}

// devuelve el archivo de manejo seteado del lado del server
function AjaxConnector_getHandlerScript() {
	return this._handlerScript;
}

// setea la estrategia a utilizar al finalizar la ejecucion de ayax
function AjaxConnector_setStrategy(strategy) {
	this._Strategy = strategy;
}

// devuelve la estrategia a utilizar al finalizar la ejecucion de ayax
function AjaxConnector_getStrategy() {
	return this._Strategy;
}

// setea el ID del elemento html a usar como contenedor de respuestas
function AjaxConnector_setContainerID(id) {
	this._containerID = id;
}

// devuelve el ID del elemento html a usar como contenedor del respuestas
function AjaxConnector_getContainerID() {
	return this._containerID;
}

// setea el ID del elemento html a usar como contenedor del item de espera
function AjaxConnector_setWaitContainerID(id) {
	this._waitContainerID = id;
}

// devuelve el ID del elemento html a usar como contenedor de item de espera
function AjaxConnector_getWaitContainerID() {
	return this._waitContainerID;
}

// Agrega un elemento del formulario para enviar
function AjaxConnector_addFormItem(key, value) {
	this.keyArray[this.getFormItemCount()] = key;
	this.valueArray[this.getFormItemCount()] = value;
	this._formItemCount++;

}

// devuelve el valor de un elemento del formulario a partir de la clave
function AjaxConnector_getFormItem(key) {
	var value = "";
	for (i=0; i< this.keyArray.length; i++) {
		if (this.keyArray[i] == key) {
			value = this.valueArray[i];
		}
	}
	return value;
}

// devuelve el header de content-type
function AjaxConnector_getContentTypeHeader() {
	return this._contentTypeHeader;
}

// setea el header de content-type
function AjaxConnector_setContentTypeHeader(value) {
	this._contentTypeHeader = value;
}

// devuelve el html de wait (mientras se procesa)
function AjaxConnector_getWaitHtml() {
	return this._waitHtml;
}

// setea el html de wait (mientras se procesa)
function AjaxConnector_setWaitHtml(value) {
	this._waitHtml = value;
}

// Devuelve la cantidad de parametros en la lista a enviar
function AjaxConnector_getFormItemCount() {
	return this._formItemCount;
}

// Envia el formulario html al servidor
function AjaxConnector_send() {

	XHttp = this._xHttp;
	var waitTime = 200;
	stgy = this.getStrategy();

	if (!XHttp) {
	   alert('Error retrieving xHttpRequest object')
       return false;
	} else {


		XHttp.open(this.getMethod(), this.getHandlerScript());
	    XHttp.setRequestHeader('Content-Type', this.getContentTypeHeader());
	    var parameters = "";
	    for (i=0; i < this.keyArray.length; i++) {
	    	if (i>0) parameters += "&";
			parameters += this.keyArray[i] + "=" + this.valueArray[i];
		}
		if (parameters.length > 0) {
			//var node = document.getElementById(stgy.getContainerID());
			//node.innerHTML = '';

			waitHtml = this.getWaitHtml();
			waitContainerID = this.getWaitContainerID();
			if (waitContainerID.length > 0 && waitHtml.length > 0) {
	    		//Pongo la ruedita de proceso
	    		var ajaxDisplay = document.getElementById(waitContainerID);
				ajaxDisplay.innerHTML = waitHtml;
				waitTime = 1500;
			}


    		XHttp.send(parameters);
			XHttp.onreadystatechange = function()	{
				if (XHttp.readyState == 4) {
					if (XHttp.status == 200) {
						setTimeout("AjaxConnector_runStrategy(XHttp, stgy,'" + waitContainerID + "')" , waitTime);
					}
				}
			}
	    }
	}
}


/********************************************************
 * Funciones Privadas
 ********************************************************/

// Devuelve un objeto XmlHttpRequest segun el navegador
function AjaxConnector_getXhttp () {
	var ajax_request;

	if ( window.ActiveXObject )  {

        var mSoftVersions = ['MSXML2.DOMDocument.5.0','MSXML2.DOMDocument.4.0', 'MSXML2.DOMDocument.3.0',
         					 'MSXML2.DOMDocument.2.0','MSXML2.DOMDocument','Microsoft.XmlDom',
         					 'Msxml2.XMLHTTP','Microsoft.XMLHTTP'];

        for (i=0; i<mSoftVersions.length; i++)  {
            try {
                ajax_request = new ActiveXObject (mSoftVersions[i]);
            }  catch (  e  )  {    }
        }
    }  else if (  !ajax_request && typeof XMLHttpRequest != 'undefined'  )  {
        try {
            ajax_request = new XMLHttpRequest;
        }  catch (  e  )  {    }
    }  else if (  !ajax_request && window.createRequest  )  {
        try {
            ajax_request = window.createRequest;
        }  catch (  e  )  {    }
    }  else  {
        ajax_request = false;
    }

    return ajax_request;
}

// imprime el resultado devuelto por el servidor
function AjaxConnector_runStrategy(xHttp, strategy, waitContainerID) {
	try {
		strategy.setXHttpRequest(xHttp);
		strategy.run();

		// Limpio la ruedita de waiting
		if (waitContainerID.length > 0 && waitContainerID!=strategy.getContainerID()) {
			var ajaxDisplay = document.getElementById(waitContainerID);
			ajaxDisplay.innerHTML = '';
		}


	} catch (e) {
		alert(e);
	}
}
