var _GLOBAL_AJAX 	= null;
var _DELEGADO 		= null;
var _DELIMITADOR        = "&";
function AjaxCall(){
    
    //declaracion de variables
    
    this.version 		= "1.4.0";
    this.ajax 			= null;
    this.div_info 		= null;
    this.mensajeExito           = "";
    this.url 			= "";
    this.directorio_imagenes    = "";	
    this.parametros             = "";
    this.metodo 		= "GET";
    this.delegado 		= null;	
    this.formulario             = "";
    this.funcionCallBack        = null;
    this.responseText           = "";
    this.responseTextDescription= "";
    this.delimitador            = "";
    
    //declaracion de funciones	
    this.setDelimitador         = setDelimitador;
    this.getDelimitador         = getDelimitador;    
    this.setVersion 		= setVersion;
    this.getVersion 		= getVersion;
    this.setImageDirectory 	= setImageDirectory;
    this.getImageDirectory 	= getImageDirectory;
    this.setMensajeExito 	= setMensajeExito;
    this.getMensajeExito 	= getMensajeExito;
    this.obtenerDatosPOST	= obtenerDatosPOST; 
    this.printMessage		= printMessage;
    this.setDivOutput		= setDivOutput;
    this.getDivOutput 		= getDivOutput;
    this.setURL                 = setURL;
    this.getURL			= getURL;
    this.setParametros		= setParametros;
    this.getParametros		= getParametros;
    this.setMetodo 		= setMetodo;
    this.getMetodo		= getMetodo;
    this.setDelegado		= setDelegado;
    this.getDelegado		= getDelegado;
    this.runDelegado		= runDelegado;
    this.Llamar			= Llamar;
    this.setFormulario		= setFormulario;
    this.getFormulario		= getFormulario;
    this.validaParametros	= validaParametros;
    this.setFuncionCallBack     = setFuncionCallBack;
    this.getFuncionCallBack     = getFuncionCallBack;	
    this.callFuntionCallBack    = callFuntionCallBack;
    this.DefaultFunctionCallBack= DefaultFunctionCallBack;	
    this.procesoInterno 	= procesoInterno;
    this.setResponseText	= setResponseText;
    this.getResponseText	= getResponseText;		
    this.setAjax		= setAjax;
    this.getAjax		= getAjax;	
    this.useDefaultHandler 	= useDefaultHandler;
    
}
function setDelimitador(delim){
    _DELIMITADOR = delim;
}
function getDelimitador(){
    return _DELIMITADOR;
}
function getResponseTextDescription(){
    return this.responseTextDescription;
}

function setResponseTextDescription(str){
    this.responseTextDescription = str;
}
function useDefaultHandler(){
    this.setFuncionCallBack(this.DefaultFunctionCallBack);	
}
var AJAX_ABS;

function procesoInterno(){
    
    _GLOBAL_AJAX                        = createInternalAjax();
    this.getAjax().onreadystatechange   = this.funcionCallBack;   
    AJAX_ABS = _GLOBAL_AJAX;    
    // alert("INIT: " + AJAX_ABS);
    
    //alert(parametros_GET + " URL: " + url );
    var d = new Date();
    //alert(url + parametros_GET);
    var parametros_GET  = "";
    var parametros_POST = "";
    
    if(this.getMetodo()== "GET" || this.getMetodo()=="get"){
        parametros_GET  = this.getParametros(); 		
    }else{
        parametros_POST = this.getParametros();	
    }	
    //alert(this.getMetodo());
    //alert(this.getURL() + parametros_GET);
    //alert(parametros_POST);	
    //alert( this.funcionCallBack);
    //alert("get ajax: " + this.getAjax());
    var str_url = this.getURL() + "?" + d.getTime() + "&" + parametros_GET;
    //alert(str_url);
    this.getAjax().open(this.getMetodo(),str_url,true);
    this.getAjax().setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-1"); 
    //alert(parametros_POST);
    this.getAjax().send(parametros_POST); 	
}
function setResponseText(s){ this.responseText = s;}
function getResponseText(){	return this.responseText;}

function createInternalAjax(){
    var xmlhttp=false;
    try {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {
            xmlhttp = false;
        }
    }
    
   
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        xmlhttp = new XMLHttpRequest();
    }
    return xmlhttp;
}

function DefaultFunctionCallBack(){
    
    ajax_interno = null;
    
    if(getAjax()==null){
        ajax_interno = AJAX_ABS;
    }else{
        ajax_interno = getAjax();
    }    
    if(ajax_interno.readyState == 0){		
        alert("El explorador no soporta llamadas Ajax");
    }
    if(ajax_interno.readyState == 1){		
    }
    if(ajax_interno.readyState == 4){
        // listo
        isError = false;
        
        //alert(this.getAjax().responseText);
        if( ajax_interno.status == 200 ){
            //mensaje normal
            resultado = ajax_interno.responseText;
            setResponseText("La operacion no contiene mensajes");            
            
            vec = resultado.split(_DELIMITADOR);
            if(resultado.indexOf("error") != -1){
                //cuando hay errores
                setResponseText(vec[1]);
                setResponseTextDescription(vec[2]);
                isError = true;
            }
            if(resultado.indexOf("ok") != -1){
                // cuando es exito
                setResponseText(vec[1]);	
                setResponseTextDescription(vec[2]);
                isError = false;
            }            
        }
        if( ajax_interno.status == 404 ){
            setResponseText("La pagina no fue encontrada: " + getURL());
            isError= true;
        } 
        if(ajax_interno.status == 500 ){
            setResponseText("Ocurrio un Error al procesar la peticion. Contace al administrador. (Error http:500)");
            isError = true;
        }
        runDelegado(getResponseText(),isError, getResponseTextDescription());
    }	    
}

function setFuncionCallBack(f){ this.funcionCallBack = f;}
function getFuncionCallBack(){ 
    if(this.funcionCallBack==undefined || this.funcionCallBack==null || this.funcionCallBack==""){
        setFuncionCallBack(this.DefaultFunctionCallBack);			
    }	
    return this.funcionCallBack;
}
function Llamar(){
    if(this.getURL()==undefined){
        this.showError("No esta establecida la URL");
        return;
    }
    if(this.validaParametros()){
        this.procesoInterno();
    }
}
function validaParametros(){
    method = this.getMetodo();
    param = this.getParametros();
    if(method=="GET" || method=="get"){
        if(param==undefined || param==""){
            showError("No se enviaron parametros GET");
            return false;
        }
    }else if(method=="POST" || method=="post"){
        //alert(this.obtenerDatosPOST(this.getFormulario()));
        this.setParametros(this.obtenerDatosPOST(this.getFormulario()));
        param = this.getParametros();
        //alert(this.getParametros());
        if(param==undefined || param==""){
            showError("No se enviaron parametros POST");
            return false;
        }		
    }else{
        showError("No se establecio el metodo de envio correctamente");
        return false;
    }
    //alert(this.getMetodo());
    //alert(this.getURL() );
    return true;
}
function showError(causa){
    alert("No se puede llamar a procedimiento remoto.("+causa+")");	
}
function setAjax(a){ this.ajax = a;}
function getAjax(){ return _GLOBAL_AJAX ;}
function setFormulario(f){ this.formulario = f;}
function getFormulario(){ return this.formulario;}
function setDelegado(d){ _DELEGADO = d;}
function getDelegado(){ return _DELEGADO;}
function setMetodo(m){ this.metodo = m;}
function getMetodo(){ return this.metodo; }
function setParametros(param){ this.parametros = param;}
function getParametros(){ return this.parametros; }
function setMensajeExito(mensaje){ this.mensajeExito = mensaje;}
function getMensajeExito(mensaje){ return this.mensajeExito;}
function setImageDirectory(dir){ this.directorio_imagenes = dir;}
function getImageDirectory(){ return this.directorio_imagenes;}
function setVersion(v){ 	this.version = v; }
function getVersion(v){ return this.version; }
function obtenerDatosPOST(form_id){
    //var Formulario = document.getElementById(form_id); 
    var Formulario = form_id;
    //alert("antes");
    var longitudFormulario = Formulario.elements.length; 
    //alert("despues");
    var cadenaFormulario = ""; 
    var sepCampos; 
    sepCampos = "" ;
    
    for (var i=0; i <= Formulario.elements.length-1;i++) { 
        //alert(Formulario.elements[i].name + " " + Formulario.elements[i].type);
        if(Formulario.elements[i].type=="checkbox" || Formulario.elements[i].type=="radio"){
            if(Formulario.elements[i].checked){
                cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+Formulario.elements[i].value;
            }else{
                cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+Formulario.elements[i].value;
            }
        }else if(Formulario.elements[i].type=="select-one"){
            sel= Formulario.elements[i];            
            for(cont = 0;cont < sel.length; cont++){
                //alert(sel.options[cont].value + " " + sel.options[cont].text);
                if(cont==Formulario.elements[i].selectedIndex){                
                    cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+encodeURI(sel.options[cont].value); 
                }
            }
        }else{
            valor = encodeURI(Formulario.elements[i].value);
            valor = valor.replace(/[&]/g,'');
            //alert("VALOR: " + valor);
            cadenaFormulario += sepCampos+Formulario.elements[i].name+'='+valor; 
        }
        sepCampos="&"; 
    }
    //alert("cadena form: " + cadenaFormulario);
    return cadenaFormulario;
}
function setDivOutput(div){ this.div_info = div;}
function getDivOutput(){ return this.div_info;}
function printMessage(str){
    getDivOutput().style.display  = "block";
    getDivOutput().innerHTML      = "<b>"+str + "</b>"; 
}
function setURL(new_url){this.url = new_url;}
function getURL(){ return this.url;}
function runDelegado(responseText,isError,shortDesc){	
    this._DELEGADO(responseText,isError,shortDesc);
}
function callFuntionCallBack(){	
    alert("FUNCTION DEPRECATED");
    this.funcionCallBack();
}
function printTo(div,texto){
    div.style.display  = "block";
    div.innerHTML      = "<b>"+ texto + "</b>"; 	
}
function setText(name,text){
    document.getElementById(name).innerHTML = text;
}
function printFormatTo(div,texto,isError,image_dir){
    if(this.getImageDirectory()==undefined){
        this.setImageDirectory(image_dir);
    }   
    div.style.display  = "block";
    if(!isError){
        div.innerHTML      = "<b><img src='"+ this.getImageDirectory() +"ok_small.gif' alt='Ok' width='13' height='13' /> "+ texto + "</b>"; 
    }else{
        div.innerHTML      = "<b><img src='"+ this.getImageDirectory() +"critical_medium.gif' alt='Ok' width='13' height='13' /> "+ texto + "</b>"; 
    }
}