/****
Gajax: Interfaz del objeto XMLHTTPREQUEST para el uso de AJAX.

Autor: Fabián E. Gallina

Changelog:
V 2.0: 
* Reestructuración en la programación
* Habilidad de multiproceso
* Función exclusiva para el proceso de archivos gajaxFiles
* Función exclusiva para el proceso de formularios gajaxForms

V 1.5:
* Se agregó la posibilidad de no tener que especificar divs de salida para que solamente se ejecuten procesos sin notificaciones.

V 1.4:
* Mejoras en el código.

V 1.3:
* Extracción automática de los campos de formulario a procesar.

V 1.2:
* Corregido soporte GET para formularios.

V 1.1:
* Soporte correcto de método POST.
Bug: Método GET no soportado para formularios.

V 1.0: 
Version Inicial.
****/

/* Configuración */
_pre_image_ = "images/ajax-loader.gif"; //Imágen que aparece mientras se carga el contenido.
_pre_image_width_ = "20"; //Ancho de la imágen
_pre_image_height_ = "20"; //Alto de la imágen
_pre_text_ = "Cargando..."; //Texto que aparece mientras se carga el contenido.
/***************************************************************************************
* Nota: Se puede customizar totalmente el formato del texto de precarga mediante el uso
* de hojas de estilos, definiendo la clase CSS .gajax_pre_text
***************************************************************************************/
/* Fin Configuración */



// NO TOCAR NADA DEBAJO DE ESTA LÍNEA A NO SER QUE SEPA LO QUE ESTÁ HACIENDO.
// DON'T TOUCH NOTHING BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING.
/*GLOBALES :D*/
i = 0;
var ajax = new Array();

// Llama al objeto XMLHTTP
function http_request() {
	
	// Internet Explorer
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
			xmlhttp = false;
		}
	}
	
	// Navegadores Decentes
	if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	
	return xmlhttp
}

function checkReturnElement($t)
{
	if (!document.getElementById($t) && $t != '')
	{
		alert('Div de salida incorrecto.');
		return;
	}
}

function getFormFields($f)
{
	if (!document.getElementById( $f ))
	{	
		alert('Id de formulario incorrecta.');
		return;
	}
	
	Formulario = document.getElementById($f);
	_amp = "";
	$vars_to_send = "";
	
	for (var i=0; i <= Formulario.elements.length-1;i++) 
	{
		$vars_to_send += _amp+Formulario.elements[i].name+'='+Formulario.elements[i].value;
		_amp="&";
	}	
	
	return $vars_to_send;
}

function defineMethod($m, $a, $u, $v)
{
	switch ($m)
	{
		case "GET":	
		case "get":			
		$a.open( "GET" , $u+'?'+$v ,true);
		break;

		case "POST":	
		case "post":			
		$a.open( "POST" , $u ,true);	
		$a.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		break;
		
		default:
		alert('No ha definido un metodo valido!');
		return;
	}	
}

function ajaxSend($a, $v, $t)
{
		// Listener que se activa al cambiar el estado del objeto XMLHTTPREQUEST. Inserta el contenido o devuelve el error.
	$a.onreadystatechange=function() 
	{
		if ($a.readyState==1)
		{
			_content_ = '<img src='+_pre_image_+' width='+_pre_image_width_+' height='+_pre_image_height_+' /> <span class=gajax_pre_text>'+_pre_text_+'</span>';
		} else if ($a.readyState==4) 
				{
					if($a.status==200)
					{						
							_content_ = $a.responseText;
					} else 
						{
							_content_ = "";
							alert('ERROR '+$a.status+': '+$a.statusText);
						}
					$a = null;
				}
        
        if($t != '')
        {
            document.getElementById($t).innerHTML = _content_;
        }
		
		return;
	}
	
	$a.send ( $v );
}

/***********************************************************************************
* $target : Div donde se mostrará el resultado del proceso.
* $url : Url que procesa el pedido.
* $formid : Si se está procesando un formulario debe colocarse su id.
* $method : Define si debe mandarse las variables mediante POST o GET.
* $vars_to_send : Permite enviar variables con valores predefinidos directamente,
* deshabilitado si $formid no es null.
***********************************************************************************/
function gajaxFiles($target, $url, $method, $vars_to_send, $thread)
{
	if(document.$thread)
	{
		i = $thread; 
	}
	else
	{
		i++;
	}
	
	ajax[i] = http_request();
	
	checkReturnElement($target);
	
	defineMethod($method, ajax[i], $url, $vars_to_send);
	
	ajaxSend(ajax[i], $vars_to_send, $target);	
}

function gajaxForms($target, $url, $method, $formid)
{
	if(document.$thread)
	{
		i = $thread; 
	}
	else
	{
		i++;
	}
	
	ajax[i] = http_request();
	
	checkReturnElement($target);
	
	defineMethod($method, ajax[i], $url, getFormFields($formid));
	
	ajaxSend(ajax[i], $vars_to_send, $target);
}
