/*
Es necesaria la libreria prototype.js
*/

function loadAjax(metodo, url, elemento, animacion, fxJSON){
	
	if(url.indexOf('?') != -1){
		operador = '&';	
	}
	else{
		operador = '?';	
	}
	
	url = url + operador +'dummy=' + Math.random(); //Para evitar posibles problemas de cache
	
	new Ajax.Request(url, {
		method: metodo,
		//requestHeaders: {Accept: 'application/json'},
		encoding: 'iso-8859-15', //Parece no funcionar
		charset:'iso-8859-15', //Parece no funcionar
		onCreate: function(){ cargaIniciada(elemento, animacion); },
		onLoaded: function(){ cargaCompletando(); },
		//onLoading: function(){ alert('onLoading'); },
		//onComplete: function(){ alert('onComplete'); },
		onException: function(transport){ cargaError(transport.responseText, elemento, fxJSON); },
		onFailure: function(transport){ cargaFallo(transport.responseText, elemento, fxJSON); },
		onSuccess: function(transport){ cargaCompletada(transport.responseText, elemento, fxJSON); }
	});
}

function cargaIniciada(elemento, animacion){
	if(animacion == 1){
		obj = $(elemento);
		obj.innerHTML = "<center><img src='/images/loading.gif'></center>";
	}
	
	if(animacion == 2){
		obj = $(elemento);
		loadingDiv = "<div id='loading' class='divLoadingFondo' style='width:" + obj.getWidth() + "px; height:" + obj.getHeight() + "px'>&nbsp;</div>";
		loadingDiv = loadingDiv + "<div id='loading' class='divLoadingImagen' style='width:" + obj.getWidth() + "px; height:" + obj.getHeight() + "px'>&nbsp;</div>";
		obj.innerHTML = loadingDiv + obj.innerHTML;
	}
}

function cargaCompletando(){
}

function cargaCompletada(responseText, elemento, fxJSON){

	if (fxJSON != ''){
			eval(fxJSON + "('" + responseText.replace('\\', '\\\\\\\\') + "')");
	}
	else{
		responseText.evalScripts(); //Para que ejecute el código js que pueda venir en el html
		
		if (responseText != ''){
			obj = $(elemento);
			
			if (!obj){
				obj = eval(elemento);
			}
			
			if (obj && obj != 'undefined'){
				obj.innerHTML = responseText;
			}			
		}
	}
}

function cargaError(responseText, elemento, fxJSON){
	//obj = $(elemento);
	//obj.innerHTML = "<center><img src='/images/error.gif'></center>";

	if (fxJSON != ''){
		eval(fxJSON + "('" + responseText + "')");
	}
	else{
		obj = $(elemento);
		obj.innerHTML = responseText;
	}
}

function cargaFallo(responseText, elemento, fxJSON){
	//obj = $(elemento);
	//obj.innerHTML = "<center><img src='/images/error.gif'></center>";
	
	if (fxJSON != ''){
		eval(fxJSON + "('" + responseText.replace("\r\n", "") + "')");
	}
	else{
		obj = $(elemento);
		obj.innerHTML = responseText;
	}
}
