//Função Principal É responsável por todos os loads e sends da pagina
var xmlhttp;
//Fila de conexões
fila=[];
ifila=0;

//--Abre conexão XMLHttpRequest
try{ 
	xmlhttp = new XMLHttpRequest();
}catch(ee){
	try{
	   xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){
			xmlhttp = false;
		}
	}
}
//------------------------------------------------------------------------------------------------------------------------
//Prepara para executar o historico
function ajax(objOrigem,objDestino,func) {
	if(objOrigem.method == "post") {
		ajax_start(objOrigem,objDestino,func);
	}
	else {
		if((!objOrigem.href) && (!objOrigem.action)) {
			url = objOrigem;
		}
		else
			if(objOrigem.href)
				url = objOrigem.href;
			else
				url = objOrigem.action;	
		
			var command = "ajax_start('"+url+"','"+objDestino+"',"+func+");";
			//alert(command)
	
		ajaxHistory.add(command, url);
		new Function(command)();
	}
}
//------------------------------------------------------------------------------------------------------------------------
//Executa em Fila
function ajax_start(objOrigem,objDestino,func) {
	
	if(objOrigem.method == "post") {
		
		if(prosseguir == 1)
			fila[fila.length]=[objOrigem,objDestino,func]
			if((ifila+1)==fila.length) 
				ajaxRun()
	}
	else {
	    fila[fila.length]=[objOrigem,objDestino,func]
		if((ifila+1)==fila.length) 
			ajaxRun()
	}
}

//------------------------------------------------------------------------------------------------------------------------
function ajaxRun() {
	//fila[ifila][0]//objOrigem
	//fila[ifila][1]//objDestino
	//fila[ifila][2]//func
	var urlSend = new Array();
	var urlPost = new Array();



	if (!fila[ifila][2]) 
		fila[ifila][2] = carregarDados; // Se a função de manipulacao de dados não for informada, ele pega a padrão
	
	urlSend[ifila] = fila[ifila][0];
	
	if((!fila[ifila][0].href) && (!fila[ifila][0].action))
		urlSend[ifila] = fila[ifila][0];
	else
		if(fila[ifila][0].href)
			urlSend[ifila] = fila[ifila][0].href;
		else
			urlSend[ifila] = fila[ifila][0].action;
	
	
	//--Envia a requisição e recebe os dados--------------------------------------------------------------------------	
	try { //--Se POST-------------
		if(fila[ifila][0].method == "post") { // Para enviar dados
			
			mostrarCarregando();
			urlPost[ifila] = montaString(fila[ifila][0]); //Carrega os dados para serem postados
			xmlhttp.open("POST",urlSend[ifila], true);//Abre a conexão
			//xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");//Seta o tipo de post do form	
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=iso-8859-1");
			xmlhttp.setRequestHeader("Cache-Control", "no-store, no-cache, must-revalidate");
			xmlhttp.setRequestHeader("Cache-Control", "post-check=0, pre-check=0");
			xmlhttp.setRequestHeader("Pragma", "no-cache");

			xmlhttp.onreadystatechange = function() {//Seta a função que vai tratar o retorno 
				if (xmlhttp.readyState==4){
					fila[ifila][2](ifila);
					ocultarCarregando();
					ifila++
					if(ifila<fila.length)setTimeout("ajaxRun()",0)						
				}
			}
			if (prosseguir == 1) {
				xmlhttp.send(urlPost[ifila]);//Envia os dados
			}
			else {
				ocultarCarregando();
			}
		}
		else { //--Se GET-------------
			mostrarCarregando();
			xmlhttp.open("GET",urlSend[ifila], true); //Abre a conexão 
			xmlhttp.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");//Seta o tipo de arquivo
			xmlhttp.onreadystatechange = function() {//Seta a função que vai tratar o retorno
				if (xmlhttp.readyState==4){
					fila[ifila][2](ifila);
					ocultarCarregando();
					ifila++
					if(ifila<fila.length)setTimeout("ajaxRun()",0)					
				}
			} 
			xmlhttp.send(null); //Requisita os dados	
		}
	}catch(a){	
	}	
}

//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
/*Funções de Manipulação de Retornos do AJAX*/
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
//Essa função é a padrão do sistema. Ela recebe os dados e carrega no objetoDestino
//Ela não deve ser alterada sem que se saiba o que está fazendo

function carregarDados(ifila) {
	document.getElementById(fila[ifila][1]).innerHTML = xmlhttp.responseText;;
}

//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
/*Funções Complementares do AJAX*/
//------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------
function montaString (objOrigem) {//Monta a string de dados
	var obj = objOrigem; //cria o form de dados a partir do objOrigem
	var urlPost = '';//Cria a var de envio de dados
	var inputs = obj.getElementsByTagName('input');//Carrega todos os objetos <input> do form objOrigem
	var areas = obj.getElementsByTagName('textarea');	//Carrega todos os objetos <textarea> do form objOrigem
	var selects = obj.getElementsByTagName('select');	//Carrega todos os objetos <select> do form objOrigem
	
	for (var i=0;i<inputs.length;i++ ){//Realiza a montagem da string de dados dos <input Text,Radio e Check>
		if((inputs[i].type == 'text') || (inputs[i].type == 'radio') || (inputs[i].type == 'checkbox') || (inputs[i].type == 'hidden') || (inputs[i].type == 'password') || (inputs[i].type == 'select')) {
			if ((inputs[i].type == 'radio') || (inputs[i].type == 'checkbox')) {
				if(inputs[i].checked == true)
					urlPost += converterCaracteres(inputs[i].name)+"="+escape(converterCaracteres(inputs[i].value))+"&";
			}
			else
				urlPost += converterCaracteres(inputs[i].name)+"="+escape(converterCaracteres(inputs[i].value))+"&";
		}
		if((inputs[i].type == 'file')){
			//alert(inputs[i].value);
		}
	}
			
	for (var i=0;i<areas.length;i++ )//Realiza a montagem da string de dados dos <textarea>
		urlPost += converterCaracteres(areas[i].name)+"="+escape(converterCaracteres(areas[i].value))+"&";
			
	for (var i=0;i<selects.length;i++ ) {//Realiza a montagem da string de dados dos <select>
		if(selects[i].type == 'select-one') {
			urlPost += converterCaracteres(selects[i].name)+"="+escape(converterCaracteres(selects[i].options[selects[i].options.selectedIndex].value))+"&";			
		}
		else
			if(selects[i].type == 'select-multiple') {
				for (var x = 0; x < selects[i].options.length; x++) {
				if (selects[i].options[x].selected)
					urlPost += converterCaracteres(selects[i].name)+"[]="+escape(converterCaracteres(selects[i].options[x].value))+"&";			
				}			
			}
	}


return (urlPost);//Retorna a string de dados formatada
}
function converterCaracteres(variavel)//Converte os caracteres +, & e = para as string determinadas
{
	variavel = variavel.replace(/&/g,"**am**");
	variavel = variavel.replace(/=/g,"**eq**");
	variavel = variavel.replace(/\+/g,"**pl**");
	return(variavel);
}

function mostrarCarregando() {
	var loader = document.getElementById('loadBar');
	loader.style.display = 'block';
	//sentTimer = setTimeout("ocultarCarregando()",8000);
}

function ocultarCarregando() {
	var loader = document.getElementById('loadBar');
	loader.style.display = "none";
}

function FieldValidate()
{
	prosseguir = 0;
	args=FieldValidate.arguments;
	//alert(idfila);
	for(var i=0;i<args.length;i++)
	{
		obj = document.getElementById(args[i]);

		if ((obj.type == 'text')||(obj.type == 'radio')||(obj.type == 'checkbox'))
			if((obj.value.length < 1) ||(obj.value.substr(0,6) == "Digite seu e-mail aqui")){
				alert("Todos os campos são de preenchimento obrigatório");
				prosseguir = 0;
				return false;
		}
	}
	prosseguir = 1;
}


/**
* ajaxHistory - histórico de comandos para navegação por Ajax
*/

var ajaxHistory = {
	'items': [],
	'captions': [],
	'currentIndex': 0,
	'go': function(ref) {
		if(this.items[this.currentIndex + ref] || false) 
			this.currentIndex += ref;
		else 
			return;
		if(this.activeHistory) 
			this.setHash();
		if(this.captions[this.currentIndex]) 
			document.title = this.captions[this.currentIndex];
		new Function(this.items[this.currentIndex])();
	},
	'goTo': function(ind) {
		if(this.items[ind] || false) 
			this.currentIndex = ind;
		else 
			return;
		if(this.activeHistory) 
			this.setHash();
		if(this.captions[this.currentIndex]) 
			document.title = this.captions[this.currentIndex];
		new Function(this.items[this.currentIndex])();
	},
	'add': function(str, cap) {
		if(str == this.items[this.currentIndex]) 
			return false;
		this.currentIndex = this.items.length;
		this.items.push(str);
		this.captions.push(cap || false);
		if(this.activeHistory) 
			this.setHash();
		return true;
	},
	'hasBack': function() { return (this.items[this.currentIndex - 1] || false) ? true : false; },
	'hasForward': function() { return (this.items[this.currentIndex + 1] || false) ? true : false; },
	'activeHistory': false,
	'activateBrowserHistory': function() {
		if(document.all) 
			this.makeIframe();
		else 
			setInterval("ajaxHistory.checkHash()", 100);
		this.activeHistory = true;
	},
	'makeIframe': function() {
		this.iframe = document.createElement('iframe');
		this.iframe.style.display = 'none';
		this.iframe.src = 'js/historyframe.html';
		document.getElementsByTagName('body')[0].appendChild(this.iframe);
	},
	'checkHash': function() {
		var curHash = location.hash.replace(/#/,'');
		if(this.currentIndex != curHash) 
			this.goTo(curHash);
	},
	'setHash': function() {
		top.location.hash = this.currentIndex;
		if(document.all)
			this.iframe.contentWindow.location.href = 'js/historyframe.html?'+this.currentIndex;
	}
};

