
// INICIA O OBJETO AJAX ###########################################################################

if (typeof(ajax) == "undefined") ajax = {};

ajax.enableCache = false; 			// ativa o uso do cache
ajax.autoCache = false; 			// insere automaticamente no cache as execuções

ajax.atividades = 0; 				// numero de execuções que estao ocorrendo para saber quando acabam
ajax.cache = new Array; 			// array com o cache do ajax

ajax.timeout = 30;					// tempo até desistir, em segundos
ajax.timeoutObject = null;

if (typeof(ajax.showCarregando) == "undefined") ajax.showCarregando = true;

ajax.LoadedControllers = new Array; // array com os controlelrs carregados

// USA O FRED.ONLOAD PARA CRIAR A CAIXA 'CARREGANDO' AO INICIAR ================================
fred.onload(function()
{
	// CRIA A CAIXA 'CARREGANDO' SE NAO EXISTIR
	if (!ajax.carregando)
	{			
		ajax.carregando = tag("DIV",{id: 'ajax_carregando'},"<div>Carregando</div>",true);
		ajax.carregando.style.display = 'none';
		ajax.carregando.style.zIndex = '500';
	}
});



// RETORNA O IFRAME 'ACTIONSFRAME' - CRIA SE NAO EXISTIR ================================
fred.onload(function()
{
	// CRIA O IFRAME 'ACTIONSFRAME' SE NAO EXISTIR
	if (!ajax.actionsFrame)
	{	
		ajax.actionsFrame = tag("iframe",{id: 'ajax_actions', name: 'ajax_actions' },'',true);
		ajax.actionsFrame.style.display = 'none';
		ajax.actionsFrame.style.position ='absolute'; 
		ajax.actionsFrame.style.top = '10px';
		ajax.actionsFrame.style.right = '10px';
		ajax.actionsFrame.style.height = '100px';
		ajax.actionsFrame.style.width = '380px';
		ajax.actionsFrame.style.zIndex = '100';
		ajax.actionsFrame.style.backgroundColor = '#fff';
	}
	
});


// AJAXRUN ########################################################################################

AjaxRun = function ()
{
	this.req = {};	
}

// MAKEREQUEST - RODA A URL E EXECUTA A FUNCAO ONSUCCESS OU ONERROR ==============================
// o parametro da funcao onSuccess é o texto de retorno

AjaxRun.prototype.makeRequest = function (url, onSuccess, onError)
{
	
	// DEBUG: DESCOMENTE A LINHA ABAIXO
	//alert(url);
	
	this.url = url;
	
	// FORMA AS FUNÇÕES DE RETORNO ------------------------------------------
	
	if (onSuccess)
		this.onSuccess = onSuccess;
	
	if (onError) 
		this.onError = onError;
	else 
		this.onError = function(status, url)
		{		
			// COLOCA O TEXTO NO OBJETO
			erro("A requisição Ajax retornou o erro '" + status + "'.\nURL:" + url, "Não foi possível efetuar a requisição ao servidor. Verifique se sua conexão está operante e tente novamente.\n\nCód. do erro: " + status + "\n" + "URL: " + url);
		}
		
	

	
	// CACHE ---------------------------------------------------------------
	// se estiver no cache, carrega e termina a requisição
	if (ajax.cache[url] && ajax.cache[url] != "" && ajax.enableCache) 
	{
		var pointer = this;
		
		var carregarCache = function ()
		{
			pointer.onSuccess(ajax.cache[url])
		}

		window.setTimeout(carregarCache,0); // para ficar mais suave a troca

		return;
		
	}
	else
	{
		// MARCA A VARIAVEL DE ATIVIDADE COM + 1 E ABRE O "CARREGANDO" ----------
		ajax.atividades++;	
		if (ajax.showCarregando && ajax.carregando)
		{
			var carregando = ajax.carregando;
			carregando.style.display = "block";
			jsdom_centralizar_div(carregando,90);
		}
		
		
		// TIMEOUT DO AJAX
		if (ajax.timeoutObject) 
		{
			clearTimeout(ajax.timeoutObject);
			ajax.timeoutObject = null;			
		}		
		ajax.timeoutObject = setTimeout(function()
		{
			if (ajax.showCarregando && ajax.carregando)
				ajax.carregando.style.display = "none";
			
			var msg = "A execução chegou a seu tempo limite e não recebeu uma resposta do servidor. Verifique se sua conexão está operante e tente novamente. Caso o problema persista, contate o administrador do sistema."; 
			erro(msg,msg);
			
		},ajax.timeout * 1000);
	}
	
	
	
	// COLOCA O RANDID NA URL -----------------------------------------------
	if (url.indexOf("?") == -1)
		url += "?" + randid(); 
	else
		url += "&" + randid();
	
	
			
	var pointer = this;
	
	// branch for native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		this.req = new XMLHttpRequest();
		this.req.onreadystatechange = function () { pointer.processReqChange() };
		this.req.open("GET", url, true); //
		this.req.send(null);
	// branch for IE/Windows ActiveX version
	}
	else if (window.ActiveXObject)
	{
		this.req = new ActiveXObject("Microsoft.XMLHTTP");
		if (this.req)
		{
			this.req.onreadystatechange = function () { pointer.processReqChange() };
			this.req.open("GET", url, true);
			this.req.send();
		}
	}
}

// FUNCAO CHAMADA QUANDO RECEBE UMA RESPOSTA DO AJAX ========================================================
AjaxRun.prototype.processReqChange = function()
{
	
	// only if req shows "loaded"
	if (this.req.readyState == 4) {
		// only if "OK"
		if (this.req.status == 200)
		{
			resposta = unescape(this.req.responseText.replace(/\+/g," "));
			
			// GRAVA NO CACHE SE ENABLEAUTOCACHE ESTIVER LIGADO
			if (typeof(ajax) != "undefined" && typeof(ajax.cache) != "undefined" && ajax.autoCache)
				ajax.cache[this.url] = resposta; // grava no cache
			
			this.onSuccess(resposta);
			
		}
		else
		{
			this.onError( this.req.status,this.url );
		}
		
		// DIMINUI O CONTADOR DE ATIVIDADES E REMOVE O AVISO DE CARREGAMENTO ---------------
		ajax.atividades = ajax.atividades - 1;
		if (ajax.atividades <= 0) 
		{
			if (ajax.showCarregando && ajax.carregando)
				ajax.carregando.style.display = "none";
				
			clearTimeout(ajax.timeoutObject);
			ajax.timeoutObject = null;
		}

	}
}

// FUNCAO GENERICA PARA RECUPERAR O TEXTO DE "URL" E COLOCA-LO NO OBJETO "ID" ###############################
// o parametro comando é uma instrucao a ser executada no final
ajax.load = function (id,url,comando)
{
	
	if(isString(id))
		id_nome = id;
	
	// SE ID FOR OBJETO, TRATA COMO OBJETO, SE FOR TEXTO, TRATA COMO ID
	if (!isObject(id))
		id = document.getElementById(id);

	// SE NAO ENCONTRAR O OBJETO ID, RETORNA ERRO
	if (!id || !isObject(id))
		alert("Erro: O parametro 'id' de valor '" + id_nome + "' indicado na função ajax.load da Library Ajax não é um objeto nem um ID de objeto válido.");
		    
   var pointer = "";
   pointer = this;
   
   // FUNCAO ONSUCESS ===========================================================
   var onSuccess = function (resposta)
   { 
	   
	   // COLOCA O TEXTO NO OBJETO
		id.innerHTML=resposta;
		
		// DÁ EVAL NO COMANDO SE HOUVER
		if (isFunction(comando))
			comando();
		else if (isString(comando))
			eval(comando);
			
	};
   
	// INICIA O OBJETO AJAXRUN =================================================
	var iniciarAjax = function ()
	{
		var myAjax = new AjaxRun();
		myAjax.makeRequest(url,onSuccess)
	}
	iniciarAjax();
   
}

// ESTA FUNCAO RETORNA UM COMANDO JAVASCRIPT GERADO POR PHP ################################################
//o parametro comandoOuFuncao é executado apos a chamada da url. Pode ser uma string para eval ou uma funcao.

ajax.eval = function (url,comando, onError)
{

   var pointer = "";
   pointer = this;
     
   var onSuccess = function (resposta) {
	   
	   // RODA O COMANDO
		eval(resposta);
		
		if (typeof(comando) == "function")
			comando();
		else
			eval(comando);
		
	};
  
	// INICIA O OBJETO AJAXRUN
	var myAjax = new AjaxRun();
	myAjax.makeRequest( url, onSuccess, onError);
   
}

// AJAX CONTROL ############################################################################
ajax.controller = function (container,rota,comando)
{
	url = URL + rota;
	
	// VERIFICA SE JÁ FOI CHAMADA ANTES (DESLIGUEI POR QUESTAO DE ECONOMIA DE RECURSOS)
	/*if (!ajax.LoadedControllers[rota])
	{
		ajax.LoadedControllers[rota] = 1;
		ajax.findControllerFiles(rota);
	}*/
	
	if (container)	ajax.load(container,url,comando);
	else 			ajax.eval(url,comando);
}

// ENCONTRA ARQUIVOS CSS E JS RELACIONADOS ################################################
/*
ajax.findControllerFiles = function(rota)
{
	ajax.eval(URL + "ajaxcontrol/encontrarcssejs/" + rota);
}*/

// AJAX PRELOADER ############################################################################
ajax.preload = function(url)
{
	var onSuccess = function (resposta)	{ ajax.cache[url] = resposta; };
  
	// INICIA O OBJETO AJAXRUN
	var myAjax = new AjaxRun();
	myAjax.makeRequest( url, onSuccess);
	
}

// AJAX SETUP ############################################################################
// reeval - reexecuta o eval na string de setup
ajax.setup = function(setup,callback,reeval)
{
	if (!setup) erro("Na função ajax.setup() o parametro setup não foi preenchido.");
	
	// SUBFUNÇÃO QUE CARREGA O SETUP
	var load = function()
	{
		evalString  = 'if (typeof(fred.setup) == "undefined") fred.setup = {}; ';
		evalString += 'fred.setup["' + setup + '"] = ' + fred.setupjson[setup] + ';';		
		eval(evalString);
		executar(callback);
	};
	
	// SE REEVAL FOR TRUE O SETUPJSON JA EXISTIR REEXECUTA E CHAMA O CALLBACK
	if (is(fred) && fred.setupjson && fred.setupjson[setup] && reeval)
	{
		ajax.controller(null,'ajaxcontrol/setupjson/' + setup,function(){load();});
	}
	
	// SE O SETUP JA EXISTIR SO EXECUTA O CALLBACK
	else if (is(fred) && fred.setup && fred.setup[setup])
	{
		executar(callback);
	}
	
	// SE NAO EXISTIR, CARREGA
	else
	{
		ajax.controller(null,'ajaxcontrol/setupjson/' + setup,function(){load();});
	}
}

