﻿// ---------------------------------------------------------------------------- //
//   Base AJAX Padrão
// ---------------------------------------------------------------------------- //


// Define a list of Microsoft XML HTTP ProgIDs.
var XMLHTTPREQUEST_MS_PROGIDS = new Array(
	"Msxml2.XMLHTTP.7.0",
	"Msxml2.XMLHTTP.6.0",
	"Msxml2.XMLHTTP.5.0",
	"Msxml2.XMLHTTP.4.0",
	"MSXML2.XMLHTTP.3.0",
	"MSXML2.XMLHTTP",
	"Microsoft.XMLHTTP"
);

// Define ready state constants.
var XMLHTTPREQUEST_READY_STATE_UNINITIALIZED = 0;
var XMLHTTPREQUEST_READY_STATE_LOADING       = 1;
var XMLHTTPREQUEST_READY_STATE_LOADED        = 2;
var XMLHTTPREQUEST_READY_STATE_INTERACTIVE   = 3;
var XMLHTTPREQUEST_READY_STATE_COMPLETED     = 4;

function getXMLHttpRequest()
{
	var httpRequest = null;

	// Create the appropriate HttpRequest object for the browser.
	if (window.XMLHttpRequest != null)
		httpRequest = new window.XMLHttpRequest();
	else if (window.ActiveXObject != null)
	{
		// Must be IE, find the right ActiveXObject.
		var success = false;
		for (var i = 0; i < XMLHTTPREQUEST_MS_PROGIDS.length && !success; i++)
		{
			try
			{
				httpRequest = new ActiveXObject(XMLHTTPREQUEST_MS_PROGIDS[i]);
				success = true;
			}
			catch (ex)
			{}
		}
	}

	// Display an error if we couldn't create one.
	if (httpRequest == null)
		alert("Erro no Ajax:\n\nNão foi possível criar o objeto XMLHttpRequest.");

	// Return it.
	return httpRequest;
}

// ---------------------------------------------------------------------------- //
//   Base AJAX que retorna string facilmente
// ---------------------------------------------------------------------------- //

/***************************
*    Classe Ajax
*    - Cria o objeto ajax
*    - Faz a busca em uma página 
*    - Retorna o resultado
* 
* Parametros
* url      : url que o ajax ira executar
* metodo   : tipo de envio de dados, por padrão é GET
* params   : parametros com os dados de envio, somente se o metodo for POST , por padrão é null
* processa : resultado 
* modo     : Tipo de arquivo que o ajax ira retornar X para 'xml' e T para 'texto'
  *****************************/

function AJX(url, metodo, params, processa, modo)
{
    this.url                = url;
    this.metodo             = (metodo) ? metodo : 'GET';
    this.params             = (metodo='GET') ? null : params;
    this.processaresultado  = processa;
    this.modo               = (modo) ? modo : 'T';
    
    
    /* T = Text , X = XML */
    if( this.modo != 'T' && this.modo != 'X' ){
        this.modo = 'T';
    }
    
    this.conectar();
}

AJX.prototype = {
    /*
        Cria o método conectar()
        Responsavel pela criação do objeto Ajax ( httprequest )
    */
    conectar: function(){
                /* Verifica se URL é válda */
                if( this.url == undefined || this.url == ''){
                    return;
                }
                
                /* Cria o objeto httpRequest */
                this.httprequest = null;
                
                /* Mozilla, Safari, FireFox ... */
                if( window.XMLHttpRequest ){
                    this.httprequest = new XMLHttpRequest();
                    
                /* IE */
                } else if( window.ActiveXObject){
                    try{
                        this.httprequest = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e){
                        try{
                            this.httprequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e) {}
                    }
                }
                if(this.httprequest != null && this.httprequest != undefined ){
                    var obj = this;
                    this.httprequest.onreadystatechange = function(){
                                                                obj.processaretorno.call(obj);
                                                            }
                    this.httprequest.open(this.metodo,this.url,"false");
                    this.httprequest.send(this.params);

                }
                
            }, // fim conectar

    /*
        Cria o método processaretorno()
        recebe a resposta do responseText ou responseXML
    */            
    processaretorno: function(){
                        if( this.httprequest.readyState == 4 ){
                            if( this.httprequest.status == 200 ){
                                var resp = ( this.modo == 'T' ) ? this.httprequest.responseText : this.httprequest.responseXML;
                                
                                if( this.processaresultado != null ){
                                    //alert(resp);
                                    this.processaresultado(resp);
                                } else {
                                    window.status = "erro=" + resp;
                            }
                            } else {
                                this.processaerro();
                            }
                        }
                    }, // fim processaretorno

    /*
        Cria o método processaerro()
        Retorna um alert de erro, caso houver
    */                    
    processaerro: function(){
                        window.status = this.httprequest.status + '-' + this.httprequest.statusText + ' :-> ' + this.url;
                  }            
}

// ---------------------------------------------------------------------------- //