/****************************************************
* nxGen AJAX javascript library
*
*
* by nxGen Tech.
****************************************************/

/*enum: tipos de destino*/
var nxTYPE = {
				DIV : 0,
				INPUT: 1,
				SELECT: 2,
				JS: 3
			 };
/*enum: modos de insertar la información en el destino*/
var nxMODE = {
				BEFORE : 0,
				AFTER: 1,
				NEW: 2
			 };

function nxAjax(IDloader, IDdestinity, type, mode) {
	this.objAjax = null;
	
	this.destId = null;
	this.loadId = null;
	this.isWorking = false;
	this.isCanceled = false;
	this.type = nxTYPE.DIV;
	this.mode = nxMODE.NEW;
	
	this.errMsg = 'Esta Web utiliza la tecnología Ajax. Su navegador no parece ser compatible. Instale una versión más actual del mismo.';
	
	this.Cancel = cancel;
	this.Get = get;
	this.Post = post;
	this.GetAndCatch = getAndCatch;
	this.PostAndCatch = postAndCatch;
	this.Submit = submit;
	
	
	putValues(IDdestinity, IDloader, type, mode);
	
	function StartAjax()
	{
		if (window.XMLHttpRequest)
			this.objAjax = new XMLHttpRequest();
		else if (window.ActiveXObject)
		{
			try {
			this.objAjax = new ActiveXObject('Msxml2.XMLHTTP') ;
			} catch(e){
			this.objAjax = new ActiveXObject('Microsoft.XMLHTTP');}
		}
		
		if (this.objAjax == null )
			alert(this.errMsg);
		else if (this.destId && window.location.hash != '' && window.location.hash != '#')
			this.Get(window.location.href,this.destId);
	}
	
	function submit(formId, IDdestinity, IDloader, type, mode)
	{
		putValues(IDdestinity, IDloader, type, mode);
		var form = $(formId);
		var packet = new nxPackage(form.method, form.action);
		for (i = 0; i < form.length; i ++ )
		{
			var tipo = form[i].type;
			var nombre = form[i].name;
			if (tipo == 'select-multiple')
			{
				var n = 0;
				for (j = 0; j < form[i].options.length; j ++ )
					if (form[i].options[j].selected)
						packet.addParam(nombre,form[i].options[j].value);

					
			}
			else if (tipo == 'radio' || tipo == 'checkbox')
			{
				if (form[i].checked)
					packet.addParam(nombre,form[i].value);

				
			}
			else 
				packet.addParam(nombre,obj[i].value);
		}
		packet.onDone = refresh;
		request(packet);
	}
	function getAndCatch(url, IDloader, eventHandler)
	{
		putValues(null, IDloader, null, null);
		var packet = new nxPackage('GET', url);
		packet.onDone = eventHandler;
		request(packet);
	}
	function get(url, IDdestinity, IDloader, type, mode)
	{
		putValues(IDdestinity, IDloader, type, mode);
		getAndCatch(url, null, refresh);
	}
	function postAndCatch(url, IDloader, eventHandler)
	{
		putValues(null, IDloader, null, null);
		var packet = new nxPackage('POST', url);
		packet.onDone = eventHandler;
		request(packet);
	}
	function post(url, IDdestinity, IDloader, type, mode)
	{
		putValues(IDdestinity, IDloader, type, mode);
		postAndCatch(url, null, refresh);
	}
	function putValues(IDdestinity, IDloader, type, mode)
	{
		if(IDloader)
			this.loadId = IDloader;
		if(IDdestinity)
			this.destId = IDdestinity;
		if(type)
			this.type = type;
		else if (IDdestinity)
		{
			if ($(IDdestinity).innerHTML)
				this.type = nxTYPE.DIV;
			else if ($(IDdestinity).options)
				this.type = nxTYPE.SELECT;
			else if ($(IDdestinity).value)
				this.type = nxTYPE.INPUT;
			else
				this.type = nxTYPE.JS;
				
		}
		if(mode)
			this.mode = mode;
		else if (this.mode==undefined)
			this.mode = nxMODE.NEW;
	}
	function request(packet)
	{
		if(!this.objAjax)
			StartAjax();
			
		this.objAjax.open(packet.method, packet.getUrl(), packet.async);
		if (packet.hasHeaders())
			for(var i=0; i<packet.headers.length; i+=2)
				this.objAjax.setRequestHeader(packet.headers[i], packet.headers[i+1]);
				
		if (packet.async)
		{
			var parent = this;
			this.isWorking = true;
			loader(true);
			this.objAjax.onreadystatechange = function ()
			{
				if (parent.objAjax.readyState == 4)
				{
					if(parent.isCanceled)
						parent.isCanceled = false;
					else
					{
						if (packet.onComplete)
							packet.onComplete(parent.type, parent.mode);
						if ((parent.objAjax.status == 200 || parent.objAjax.status == 304) && packet.onDone)
							packet.onDone(parent.destId, parent.type, parent.mode, parent.objAjax);
						else if (packet.onFail)
							packet.onFail(parent.objAjax);
					}
					
					
					loader(false);
					parent.isWorking = false;
				}
			};
		}
		this.objAjax.send(packet.getParams());
	}
	function refresh(id, type, mode, objAjax) {
		switch(type)
		{
			case nxTYPE.DIV:
				$(id).innerHTML = strmode( mode, $(id).innerHTML, objAjax.responseText);
				break;
			case nxTYPE.INPUT: 
				$(id).value = strmode( mode, $(id).value, objAjax.responseText);
				break;
			case nxTYPE.SELECT:
				
				break;
			case nxTYPE.JS: /* javascript */
				eval(this.objAjax.responseText);
				break;
		}
	}
	function cancel() {
		if (this.isWorking) {
			loader(false);
			this.isWorking = false;
			this.isCanceled = true;
		}
	}
	function loader(isOn) {
		if(this.loadId)
			$(this.loadId).style.visibility = (isOn) ? 'visible' : 'hidden';
	}
	function strmode(mode, srcText, newText) {
		switch(mode)
		{
			case nxMODE.BEFORE:
				return newText + srcText;
			case nxMODE.AFTER: 
				return srcText + newText;				
			default:
				return newText;
		}
	}
	function getUrl(url) { /* Recoge lo de detras de la almuadilla '#'*/
		var result = '', obj = str.split('#');
		if (obj.length > 1)
			for (var i = 1; i < obj.length;  ++ i)
			{
				resultado += obj[i];
				if ((i + 1) < obj.length)
					resultado += '#';
			}
		else resultado = obj[0];

		return resultado;
	}
	function nxPackage(method, url, async)
	{
		/*Atributos*/
		this.method = (method == null) ? 'GET' : method;
		this.url = (url == null) ? this.homepage : url;
		this.async = (async == null) ? true : async;
		this.params = new Array();
		this.headers = new Array();
		/*eventos*/
		this.onDone = null;
		this.onFail = null;
		/*Inicializador*/
		if (this.method.toUpperCase() == 'POST')
			this.headers = ['Content-Type','application/x-www-form-urlencoded; charset=ISO-8859-1'];
		/*Métodos*/
		this.addParam = function (name, value)
		{
			this.params[this.params.length] = name + '=' + value;
		};
		this.addHeader = function (value) 
		{
			this.headers[this.headers.lenght] = value;
		};
		this.getUrl = function()
		{
			var result = '';
			if (this.method.toUpperCase() == 'GET' && this.params.lenght>0)
			{
				result = this.url;
				for(var i=0; i<this.params.lenght; i++)
				{
					if(i=0)
						result+='?';
					else
						result+='&';
						
					result += this.params[i];
				}
			}
			else
				return this.url;
		};
		this.getParams = function()
		{
			var result = '';
			if(this.params)
				for(var i=0; i<this.params.lenght; i++)
				{
					if(i>0)
						result+='&';
					
					result += this.params[i];
				}
			
			return result;
		};
		this.hasHeaders = function()
		{
			return this.headers.lenght>0;
		};
	}
}

function $(id)
{
	return (document.getElementById(id));
}