/**
 * JSAjax
 * Possui os scripts para o AJAX
 *
 * @category   Langtech
 * @package    Langtech
 * @copyright  Copyright (c) 2008 LangTech Language & Technologies Brazil Inc. (http://www.langtech.com.br)
 * @license    http://framework.langetch.com.br/license    New Closed License
 * @version    2.8.9.16
 */
var ajax;
var dadosUsuario;
var idTimeout;
var usaShowForms = true; //ALT20110106 Para a máscara de fundo. Incluído também no TMessage

//var ajax_debug_mode = false;
//function AjaxDebug(text)
//{
//	alert("RSD: " + text);
//}

// ------- cria o objeto e faz a requisição -------
function requisicaoHTTP(tipo,url,assinc)
{
	showForms(false);
	exibeMsg('divMsg',"<img src='images/loading.gif' width='105px'>");

	if(window.XMLHttpRequest)
	{	  // Mozilla, Safari,...
		ajax = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{	// IE
		ajax = new ActiveXObject("Msxml2.XMLHTTP");
		if (!ajax) {
			ajax = new ActiveXObject("Microsoft.XMLHTTP");
		}
  	}

	if(ajax)
	{	// iniciou com sucesso
		iniciaRequisicao(tipo,url,assinc);
	}
	else {
		exibeMsg('divMsg','');
		alert('Seu navegador não possui suporte a essa aplicação!');
	}

	showForms(true);
}

// ------- Inicializa o objeto criado e envia os dados (se existirem) -------
function iniciaRequisicao(tipo,url,bool)
{
		ajax.onreadystatechange=trataResposta;
		ajax.open(tipo,url,bool);
		//idTimeout = setTimeout(tempoEsgotado, 10000);
		ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
		ajax.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate"); //new
		ajax.setRequestHeader("Cache-Control", "post-check=0, pre-check=0"); //new
		ajax.setRequestHeader("Pragma", "no-cache"); //new
		ajax.setRequestHeader("encoding", "ISO-8859-1");
		//ajax.overrideMimeType("text/XML");   /* usado somente no Mozilla */
		ajax.send(dadosUsuario);
}


// ------- Inicia requisição com envio de dados -------
function enviaDados(url)
{
	criaQueryString();
	requisicaoHTTP("POST",url,true);
}


// ------- Cria a string a ser enviada, formato campo1=valor1&campo2=valor2... -------
function criaQueryString()
{
	dadosUsuario="";
	var frm = document.forms[0];
	var numElementos =  frm.elements.length;
	for(var i = 0; i < numElementos; i++)
	{
		if(i < numElementos-1)
		{
			dadosUsuario += frm.elements[i].name+"="+encodeURIComponent(frm.elements[i].value)+"&";
		}
		else
		{
			dadosUsuario += frm.elements[i].name+"="+encodeURIComponent(frm.elements[i].value);
		}
	}
}

// ------- Trata a resposta do servidor -------
function trataResposta()
{
	if(ajax.readyState == 4)
	{
		//clearTimeout(idTimeout);
		if(ajax.status == 200)
		{
			exibeMsg('divMsg','');
			trataDados();  // criar essa função no programa
			showForms(true);
		}
		else
		{
			exibeMsg('divMsg','');
			alert('Problema na comunicação com o objeto XMLHttpRequest.');
			showForms(true);
		}
	}
}

// ------- Atingiu o tempo limite -------
function tempoEsgotado()
{
	ajax.abort();
	exibeMsg('divMsg','');
	alert('Problema na comunicação com o servidor. Tente acessar mais tarde.');
	showForms(true);
}

//1-habilitado, 2-desabilitado
function checaEstado(_campo)
{
	if(typeof(_campo)!='undefined'){
	var lvetCampo = _campo.split("=");
		if(lvetCampo[1]=="2"){
			return true;
		}
	}
	return false;
}

/**
* Função para habiltar/desabilitar todos os elementos da pagina
* Usa o jQuery
*/
function showForms(habilita)
{
	$(document).ready(function(){
		$('#mascara').css('height', $(document).height()).hide();
		if(habilita==true)
		{
			$('#mascara').removeClass('mascara');
			$('#mascara').hide();
		}
		else
			$('#mascara').addClass('mascara');

			//$('#mascara').toggle();
	});
}

/**
	* Função para mostrar  iframe com a mensagem ou temporizador
	*/
function exibeMsg(div,msg)
{
	if(document.getElementById(div)!=null)
	{
		if(msg!="")
		{
			if(document.getElementById(div).innerHTML=="")
			{
				document.getElementById(div).innerHTML = "<iframe name='Loading' frameborder='no' scrolling='no' width='105px' height='16px'></iframe>";
				var cabecalho = "";
					cabecalho += "<HTML><HEAD>";
					cabecalho += "<TITLE>Loading.....</TITLE>";
					cabecalho += "</HEAD>";
					cabecalho += "<BODY bgcolor='#ffffff' leftmargin='0' topmargin='0' marginwidth='0' marginheight='0'><font color=blue size=+1><b>";
				var rodape = "";
					rodape += "</b></font></BODY></HTML>";
				var frmLoading = frames['Loading'];
				frmLoading.document.open();
				frmLoading.document.write(cabecalho + msg + rodape);
				frmLoading.document.close();
			}
			document.getElementById(div).style.margin  = "-" + document.getElementById(div).offsetHeight + " 0 0 -" + (document.getElementById(div).offsetWidth/2);
			document.getElementById(div).style.visibility="visible";
		}
		else
		{
			document.getElementById(div).style.visibility="hidden";
		}
	}
}

/**
 * Monta o retorno do trataDados
 * @access public
 * @return void
 **/
function montaPagina()
{
	var texto 	= ajax.responseText; // obtem a reposta como string
	var camada 	= document.getElementById('divRetorno');

	limpaCamada(camada);
	camada.innerHTML = texto;
}
/**
 * Monta o retorno do trataDados para mensagens
 * @access public
 * @return void
 **/
function montaMensagemRetorno()
{
	var texto 	= ajax.responseText; // obtem a reposta como string
	var camada 	= document.getElementById('divMsg');

	limpaCamada(camada);
	alert(texto);
}
/**
 * Auxiliares
 * @access public
 * @return void
 **/
function onButtonClick(Query){if(usaShowForms) showForms(false); document.location = 'application.php' + Query;}
function onException(Query){document.location = 'application.php?class=' + Query + '&method=onReload';}
function limpaCamada(elemento){elemento.innerHTML='';}
function limpaMensagens()
{
	var menssagens = document.getElementsByTagName("div");
	if(menssagens!=null)
	{
		for(var i=0;i<menssagens.length; i++)
		{
			if(menssagens[i].id=='tmessage')
			{
				menssagens[i].style.display='none';
			}
		}
	}
}
