/**
 * SIES - Soluções para Instituições de Ensino Superior
 * Arquivo: ajaxHandler.js
 * Data da criação: 12/12/2008, 14:26:15
 * Criado por: Eduardo Benzi Frazão - eduardo.frazao@faban.com.br
 * Proposta do arquivo JS: Handler principal de requisições AJAX.
 * Realiza requests assincronos, e devolve seus retornos aos respectivos callbacks
*/

/**
 * Classe Container net. Sera usada para objetos que realizarão algum trabalho em rede
 * e que possam ser aninhados sem problemas de performance ou tamanho.
 *
 */
var net = new Object();

/**
 * Função isolada para descobrir qual o melhor objeto MSXML disponível para uso
 */
net.getMsXmlObject = function() {
    var msXmlVersions = [
    "MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0",
    "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp" ];
    for(var i=0; i < msXmlVersions.length; i++) {
        try {
            var msObj = new ActiveXObject(msXmlVersions[i]);
            return msObj;
        }
        catch (ex) {}
    }
    return false; // Se ate agora ninguem retornou status, o mesmo esta quebrado.
}

/**
 * Metodo Classe ContentLoader, que efetivaente fará os requests
 * assíncronos e os devolvera aos seus callbak
 */
net.contentLoader = function(url, params, onLoad, onError, method, oFrame) {
    this.url = url;
    this.params = params;
    this.onLoad = onLoad;
    this.onError = (onError) ? onError : this.defaultError;

    //checando metodo passado
    if( (method != null) && (method.toUpperCase() != 'GET') || (method.toUpperCase() != 'POST') ) {
        this.method = "GET";
    }
    else {
        this.method = method.toUpperCase();
    }
    
    if (oFrame) {
        this.oFrame = window.frames.oFrame;
    }

    if (this.oFrame) {
        var iframe = this.oFrame;
        this.onLoad = iframe.onLoad;
        this.onError = iframe.onError;
    }

    this.initReq(url, params, method);
    
}
//Trabalhando nos metodos via prototype
net.contentLoader.prototype = {
    initReq:function(url, params, method) {
        if (window.XMLHttpRequest) { //Outros Browsers do que I.E.
            this.req = new XMLHttpRequest();
        }
        else { // Tentanto utilizar o melhor objeto Microsoft caso disponível
            this.req = net.getMsXmlObject();
        }
        if (this.req) {
            try{
                if(window['notifications']) {
                    this.loadInfoId = confirmation.message('Processando, aguarde.', 3000, true, true);
                }
                var loader = this;
                this.req.onreadystatechange = function() {
                    loader.onReadyState.call(loader);
                }
                if (method == "GET") {
                    if (params) {
                        url = url + "?" + params;
                    }
                    this.req.open(method, url, true);
                    this.req.setRequestHeader("Charset", "ISO-8859-1");
                    this.req.send(null);
                }
                else {
                    this.req.open(method, url, true);
                    this.req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    this.req.setRequestHeader("Charset", "UTF-8");
                    this.req.send(params);
                }
            }
            catch (err) {
                this.onError.call(this);
            }
        }
    }, //Fim da Funcao initReq
    onReadyState:function() {
        var req = this.req;
        var ready = req.readyState;
        if (ready == 4) {
            var httpStatus = req.status;
            if (httpStatus == 200 || httpStatus == 0) {
                if(window['notifications']) {
                    notifications.removeNotify(this.loadInfoId);
                }
                this.onLoad.call(this);
            }
            else {
                if(window['notifications']) {
                    notifications.removeNotify(this.loadInfoId);
                }
                this.onError.call(this);
            }
        }
    },
    defaultError:function() {
        alert("Erro ao carregar dados!"
            +"\n\nURL: "+this.url
            +"\nProgresso da Transação: "+this.req.readyState
            +"\nStatus HTTP: "+this.req.status
            +"\nHeaders: "+this.req.getAllResponseHeaders());
    }
}
