/*==============================================================================================



--| Objeto AJAX para comunicação Assincrona com um servidor de aplicações WEB



--| Criado por Antonio Romualdo - www.JuniorMago.com



==============================================================================================*/



function AJAX(url, metodo, params, processa, modo) {

	this.url = url;

	this.metodo = (metodo) ? metodo : 'GET';

	this.params  = (metodo='GET') ? "" : params;

	this.retorno = processa;

	this.modo = (modo) ? modo : 'T';

	if (this.modo != 'T' && this.modo != 'X') { this.modo = 'T'; }

	this.conectar();

}



AJAX.prototype = {

	

	// Instancia o objeto e faz a chamada a assincrona

	conectar: function() {

		if (this.url == undefined || this.url == '') {

			return; 

		}

		this.httprequest = null;

	   	if (window.XMLHttpRequest) { // Mozilla, Safari,...

	     	this.httprequest = new XMLHttpRequest();

		} else if (window.ActiveXObject) { // IE

	     	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);

			}

			if (this.metodo == undefined || this.metodo == '') { this.metodo = 'GET';}

	    	this.httprequest.open(this.metodo, this.url, true);

			

			// Cabeçalho pra evitar CACHE

			this.httprequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");

			this.httprequest.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");

			this.httprequest.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");

			this.httprequest.setRequestHeader("Pragma", "no-cache");

			

	        this.httprequest.send(this.params);

		}

	},

	

	// Processa o retorno

	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.retorno != null) {					

					// Trata os caracteres acentuados no ASP

					if (this.modo == 'T') {

						resp = resp.replace(/\+/g," ");

						resp = unescape(resp); 

					}					

					this.retorno(resp);

				} else {

					document.write(resp);

				}

			} else { 

				this.processaErro();

			}

		}

	},



	// Exibe um alert() com a descrição do ERRO

	processaErro: function() {

		alert(this.httprequest.status + '-' + this.httprequest.statusText + ' :-> ' + this.url);

	}

}



/*==============================================================================================

--| Executa qualquer <script></script> que existir na página

==============================================================================================*/

function executaScript(texto){

    // inicializa o inicio ><

    var ini = 0;

    // loop enquanto achar um script

    while (ini!=-1){

        // procura uma tag de script

        ini = texto.indexOf('<script', ini);

        // se encontrar

        if (ini >=0){

            // define o inicio para depois do fechamento dessa tag

            ini = texto.indexOf('>', ini) + 1;

            // procura o final do script

            var fim = texto.indexOf('</script>', ini);

            // extrai apenas o script

            codigo = texto.substring(ini,fim);

            // executa o script

            eval(codigo);

        }

    }

}



/*==============================================================================================

--| Inclui uma nova página em uma DIV específica

--| Params.: Página e DIV

==============================================================================================*/

function ajaxIncludeDiv(url, containerid) {



	var ajax = new AJAX();

	ajax.url = url;	

	ajax.metodo = "POST";

	ajax.retorno = function(texto) {

		document.getElementById(containerid).innerHTML = texto;

		executaScript(texto);

		// Limpa da tela a mensagem de aguarde

		document.getElementById("div_carregando").style.display = "none";

	}

	ajax.conectar();

}



/*==============================================================================================

--| Inclui uma nova página em uma DIV específica e no obj hidden para envio de email

--| Params.: Página e DIV

==============================================================================================*/

function ajaxIncludeObj(url, id_obj) {

	

	var ajax = new AJAX();

	ajax.url = url;	

	ajax.metodo = "POST";

	ajax.retorno = function(texto) {

		document.getElementById(id_obj).value = texto;		

	}

	ajax.conectar();

}

	



/*==============================================================================================

--| Inclui um novo objeto(.js ou .css) na página atual

==============================================================================================*/

var loadedobjects = "";

function ajaxIncludeJsCss(){

	if (!document.getElementById)

		return

	for (i=0; i<arguments.length; i++) {

		var file=arguments[i]

		var fileref=""

		if (loadedobjects.indexOf(file)==-1) { //Check to see if this object has not already been added to page before proceeding

			if (file.indexOf(".js")!=-1) { //If object is a js file

				fileref=document.createElement('script')

				fileref.setAttribute("type","text/javascript");

				fileref.setAttribute("src", file);

			}

			else if (file.indexOf(".css")!=-1) { //If object is a css file

				fileref=document.createElement("link")

				fileref.setAttribute("rel", "stylesheet");

				fileref.setAttribute("type", "text/css");

				fileref.setAttribute("href", file);

			}

		}

		if (fileref!="") {

			document.getElementsByTagName("head").item(0).appendChild(fileref)

			loadedobjects+=file+" " //Remember this object as being already added to page

		}

	}

}




