/**
 * 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 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
	*/
function showForms(habilita)
{
	var f;
	var c;
	var lstrEstado = "";

//	for(f=0;f<document.forms.length;f++){
//		for(c=0;c<document.forms[f].elements.length;c++){
//			if(!habilita){
//				if(!document.forms[f].elements[c].disabled){
//					lstrEstado += document.forms[f].elements[c].name + "=1";
//				}
//				else{
//					lstrEstado += document.forms[f].elements[c].name + "=2";
//				}
//				document.forms[f].elements[c].disabled=true;
//			}
//			else{
//				if(checaEstado(document.forms[f].elements[c].name)){
//					document.forms[f].elements[c].disabled=false;
//				}
//			}
//		}
//	}
}

/**
	* 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";
		}	
	}
}
