/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* ©2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState) {
						case 1:
							self.onLoading();
							break;
						case 2:
							self.onLoaded();
							break;
						case 3:
							self.onInteractive();
							break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}



///// ========================================== AJAX GENERICO



function AJAX() {

this.Updater=carregarDados;
function carregarDados(caminhoRetorno,idResposta,metodo,mensagem) {

var conteudo=document.getElementById(idResposta)
conteudo.innerHTML= mensagem;

var xmlhttp = getXmlHttp();

//Abre a url
xmlhttp.open(metodo.toUpperCase(), caminhoRetorno,true);

//Executada quando o navegador obtiver o código
xmlhttp.onreadystatechange=function() {

if (xmlhttp.readyState==4){

//Lê o texto
var texto=xmlhttp.responseText;

//Desfaz o urlencode
texto=texto.replace(/\+/g," ");
texto=unescape(texto);

//Exibe o texto no div conteúdo

var conteudo=document.getElementById(idResposta);
conteudo.innerHTML=texto;

}
}
xmlhttp.send(null);
}
}

function getXmlHttp() {
var xmlhttp;
try{
xmlhttp = new XMLHttpRequest();
}catch(ee){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(E){
xmlhttp = false;
}
}
}
return xmlhttp;
}




// Variaveis globais
var obj;
var id;
var funcao;
var dados;
fila  = [];
ifila = 0;

// Funcoes do xmlhttprequest

function CreateObjXMLHttpRequest() { // Cria o objeto

    obj = null;

    // Procura por um objeto nativo W3C (Mozilla/Safari/Konqueror/Opera)
    if (window.XMLHttpRequest){

        obj = new XMLHttpRequest(); // Cria o objeto nativo
        obj_type = "XMLHttpRequest";

    } else if (window.ActiveXObject) { // Senao procura por uma versao ActiveX (IE)

        // Array com tipos de objeto ActiveX
        var msxmls = new Array('Msxml2.XMLHTTP.5.0',
                               'Msxml2.XMLHTTP.4.0',
                               'Msxml2.XMLHTTP.3.0',
                               'Msxml2.XMLHTTP',
                               'Microsoft.XMLHTTP');

        // Percorre array com versoes do ActiveX e tenta criar o objeto
        for (var i = 0; i < msxmls.length; i++) {
            try {
                obj = new ActiveXObject(msxmls[i]); // Tenta criar o objeto nativo
                obj_type = msxmls[i];
                break;
            } catch(e) {
                obj = false;
            }
        }
    } else { // Nenhum objeto suportado pelo browser
        obj = false;
    }
    return obj;
}

function GetContent()
{
    if(obj) // Verifica se objeto ainda existe
    {
        if(obj.readyState == 4) // Se requisicao terminada (readyState = 4)
        {
            if(obj.status == 200) // Se status retornado "ok" (status = 200)
            {
                eval(funcao+'();'); // Chama funcao respectiva
            }
            else  // Se status diferente de "ok"
            {
                alert('Erro! "'+ obj.statusText +'" (erro '+ obj.status +')'); //Exibe mensagem com o erro
            }
            // Proxima requisicao da fila
            ifila++;
            if (ifila < fila.length) {
                setTimeout("SendRequest()",20);
            }
        }
    }
    else
    {
        return false;
    }
}

function Requisition(var_id,arquivo,var_funcao,dados)
{
    obj = CreateObjXMLHttpRequest(); // Cria uma instancia do objeto

    id = var_id;
    funcao = var_funcao;

    // Encadeia variaveis enviadas pela requisicao
    if (dados) {
        var mensagem = '';
        for (var i = 0; i < dados.length; i++) {
            if(i > 0) {
                mensagem += '&';
            }
            mensagem += 'dado'+i+'='+url_encode(dados[i]);
        }
    } else {
        mensagem = null;
    }

    // Adiciona a fila
    fila[fila.length] = [id, arquivo, funcao, mensagem];

    // Se fila sem conexoes pendentes, executa
    if ((ifila + 1) == fila.length) {
        SendRequest();
    }
}

function SendRequest()
{
    id       = fila[ifila][0];
    arquivo  = fila[ifila][1];
    funcao   = fila[ifila][2];
    mensagem = fila[ifila][3];

    obj = CreateObjXMLHttpRequest(); // Cria uma instancia do objeto
    obj.onreadystatechange = GetContent; // Define a funcao chamada na mudanca de status do objeto
    obj.open('POST',arquivo, true) // Metodo prepara objeto pra requisicao
    obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
    obj.send(mensagem); // Envia requisicao
}

// url_encode version 1.0
function url_encode(str) {
    var hex_chars = "0123456789ABCDEF";
    var noEncode = /^([a-zA-Z0-9\_\-\.])$/;
    var n, strCode, hex1, hex2, strEncode = "";

    for(n = 0; n < str.length; n++) {
        if (noEncode.test(str.charAt(n))) {
            strEncode += str.charAt(n);
        } else {
            strCode = str.charCodeAt(n);
            hex1 = hex_chars.charAt(Math.floor(strCode / 16));
            hex2 = hex_chars.charAt(strCode % 16);
            strEncode += "%" + (hex1 + hex2);
        }
    }
    return strEncode;
}

// url_decode version 1.0
function url_decode(str) {
    var n, strCode, strDecode = "";

    for (n = 0; n < str.length; n++) {
        if (str.charAt(n) == "%") {
            strCode = str.charAt(n + 1) + str.charAt(n + 2);
            strDecode += String.fromCharCode(parseInt(strCode, 16));
            n += 2;
        } else {
            strDecode += str.charAt(n);
        }
    }
    return strDecode;
}

// Funcoes do sistema

function InserirPagina_envia(){
    document.getElementById(id).innerHTML = obj.responseText;
}

function InserirPagina_recebe(){
    document.getElementById(id).innerHTML = url_decode(obj.responseText);
}

// Chamadas as funcoes

function InserirComentario(nome,email,url,comentario,pg)
{
	
	if(nome=="")
		{
			window.alert('Digite o seu nome, por favor.');	
			document.getElementById("nome_comenta").focus();
			return false;
		}
		
	if(email=="")
		{
			window.alert('Pode digitar um e-mail valido! Ele nao vai aparecer pra ninguem!');	
			document.getElementById("email_comenta").focus();
			return false;
		}
		
	if(comentario=="")
		{
			window.alert('Escreva o seu comentario, por favor.');	
			document.getElementById("comenta").focus();
			return false;
		}
		

    // Monta array dos dados enviados pela requisicao
    var dados = new Array(nome,
                          email,
                          url,
                          comentario,
                          pg);

    // Chama requisicao
    Requisition(id='comunicacao',url='inserir_comentario.php',funcao='InserirPagina_envia',dados);
    // Limpa formulario
    //document.getElementById("form_comentario").reset();
	window.alert('Obrigado pelo seu comentario!');	
	document.getElementById("botao_comenta").innerHTML="<p align=\"center\"><input type=\"button\" value=\"fechar\" name=\"B1\" onClick=\"parent.comentwindow.hide()\" /></p>";
    // Atualiza comentarios
	//ListarComentario(pg,'adicionado');
	setTimeout("ListarComentario('" + pg + "','adicionado')", 500);
}

function ListarComentario(pg,acao)
{
    // Monta array dos dados enviados pela requisicao
    var dados = new Array(pg,
                          acao);
    // Chama requisicao
    Requisition(id='comentarios',url='listar_comentario.php',funcao='InserirPagina_recebe',dados);
}


function opencomentario(nome,id,titulo){
	if(nome == "comentario")
	{
	  topo = "Comente o nosso Artigo!";
	} else
		{
		  topo = "Leia na integra!";	
		}
	comentwindow=dhtmlmodal.open(nome, 'iframe', nome+'.php?id='+id+'&titulo='+titulo, topo, 'width=455px,height=340px,center=1,resize=0,scrolling=1')

	comentwindow.onclose=function()
	{ //Define custom code to run when window is closed
		var theform=this.contentDoc.forms[0] //Access first form inside iframe just for your reference
		var theemail=this.contentDoc.getElementById("comenta") 
		var nome=this.contentDoc.getElementById("nome") 
		document.getElementById("yourname").innerHTML=nome.value + " - Muito Obrigado pelo seu Comentario!";
		document.getElementById("yourcoment").innerHTML=theemail.value;
		return true //allow closing of window
		
	}
} //End "opencomentario" function



function openfaleconosco(nome,id,erro){

	var topo = "Fale conosco!";
	
	comentwindow=dhtmlmodal.open(nome, 'iframe', nome+'.php?id='+id+'&titulo='+erro, topo, 'width=455px,height=340px,center=1,resize=0,scrolling=1')

} //End "openfaleconosco" function





/*
function openemail(email,opcao){
	emailwindow=dhtmlmodal.open('EmailBox', 'iframe', 'email.php?email='+email+'&opcao='+opcao, 'Comente o nosso Artigo!', 'width=455px,height=340px,center=1,resize=0,scrolling=1')

	comentwindow.onclose=function()
	{ //Define custom code to run when window is closed
		var theform=this.contentDoc.forms[0] //Access first form inside iframe just for your reference
		var theemail=this.contentDoc.getElementById("comenta") 
		var nome=this.contentDoc.getElementById("nome") 
		document.getElementById("yourname").innerHTML=nome.value + " - Muito Obrigado pelo seu Comentario!";
		document.getElementById("yourcoment").innerHTML=theemail.value;
		return true //allow closing of window
		
	}
} //End "opencomentario" function

*/

function ver_corrente(id,id2) {
var el = document.getElementById(id);
var el2 = document.getElementById(id2);
el.style.display = (el.style.display=="") ? "none" : "";
el2.style.display = (el2.style.display=="") ? "none" : "";

}

