// JavaScript Document

/////************************************************
/////************************************************
/////***********************AJAX*********************
/////************************************************
/////************************************************

list_functions = [];
function AddListFunctions(value){
	var tem = false
	for(var i=0; i<list_functions.length; i++){
		if(list_functions[i] == value){
			tem = true;
			break;
		}
	}
	if(!tem)list_functions.push(value);
}

function AjaxList(){
	eval(list_functions[0]);
	list_functions.shift();
}

/////////////////////////////////////////////////////////////////////
/////////////////////////FUNCAO AJAX/////////////////////////////////
/*
	PARAMENTROS:
	
	url 		 ==> pagina a ser consultada
	param 		 ==> get a ser passado
	display 	 ==> o id da div onde o resultado sera retornado
	obj_form 	 ==> o id do objeto de formulario onde sera retornado o resultado
	modo 		 ==> CASO ESPECIFICO FALE COM O PROGRAMADOR
	text_inic	 ==> o texto que irá aparecer onde terá o retorno antes do resultado
	callfunction ==> função javascript a ser chamada após o retorno do ajax
*/
called = false;

historico_ajax = "";
function ajax(url,param,display,obj_form,modo,text_inic,callfunction) 
{ 

	if(obj_form == "undefined"){
		obj_form = "";
	}
		
	var e = window.event;
	
	if(!called){
		
		if(display){
			historico_ajax = document.body.innerHTML;
		}
		
		if(e){
			
			if(e.type == "click" && display){
				url_refresh = "";
				url_refresh = [url,param,display,'','','<center><img src='+_host+'/'+_raiz+'/adm/images/carregando.gif></center>'];
				//if(list_functions.length) modo = "sequencial";
			}
		
		}
		
		called = true;
		
		modoLoad = "";
		if(modo)modoLoad = modo;
		
		if(!text_inic)text_inic = "Aguarde...";
		
		CallFunction = "";
		if(callfunction){
			CallFunction = callfunction.toString();
		}
		
		
		if(display){
			
			type_return_ajax = 1;
			first = false;
			obj_recip_ajax = "";
			obj_recip_ajax = document.getElementById(display);
			
			if(modoLoad == "disabled"){
				
				var y = pegarPosicaoY(obj_recip_ajax);
				var x = pegarPosicaoX(obj_recip_ajax);
				var w = obj_recip_ajax.scrollWidth;
				var h = obj_recip_ajax.scrollHeight;
				
				var div = document.createElement('div');
				div.style.width = w;
				div.style.height = h;
				div.style.position = 'absolute';
				div.style.float = 'left';
				div.style.top = y;
				div.style.left = x;
				div.style.background = "#FFFFFF";
				div.style.zIndex = '1';
				div.style.filter = "alpha(opacity = 50)";
				//div.style.border = 'solid 1px';
				div.id = "fundo_ajax";
				
				var div1 = document.createElement('div');
				div1.style.width = w;
				div1.style.height = h;
				div1.style.position = 'absolute';
				div1.style.float = 'left';
				div1.style.top = y;
				div1.style.left = x;
				div1.style.zIndex = '1';
				div1.id = "preload_ajax";
				
				obj_recip_ajax.style.zIndex = '0';
				
				var content_div = "";
				content_div += "<center>";
					content_div += "<div style='position:absolute; top: 50%; background: #FFFFFF; padding: 10px 10px 10px 10px; border:solid 3px; borderColor: #999999'>";
						content_div += "<div style='float:left'><img src=http://"+_host+"/"+_raiz+"/adm/images/carregando.gif /></div>";
					content_div += "<div style='float:left'>&nbsp;&nbsp;</div>";
						content_div += "<div style='float:left'>"+text_inic+"</div>";
					content_div += "</div>";
				content_div += "</center>";
				
				div1.innerHTML = content_div;
								
				document.body.appendChild(div);
				document.body.appendChild(div1);
				
				CallFunction += ";document.body.removeChild("+div.id+");document.body.removeChild("+div1.id+");";
				
			}else{
				if(obj_recip_ajax.style.display == "none"){
					obj_recip_ajax.style.display = "block";
				}
				
				obj_recip_ajax.innerHTML = text_inic;
								
			}
			
			//return false;
			
		}
		
		if(obj_form){
			
			type_return_ajax = 2;
			obj_recip_ajax = document.getElementById(obj_form);
			
			//type = obj_recip_ajax.type;
			//if(type == "select-one"){
			obj_recip_ajax.length = 1;
			obj_recip_ajax.options[0].text = text_inic;
			//}
			
			/*
			if(type == "text"){
				obj_recip_ajax.value = text_inic;
			}
			*/
		}
		
		url=url+"?"+param+"&@sid="+Math.random()+"@&";
		
		req = null; 
		
		// Procura por um objeto nativo (Mozilla/Safari) 
		if (window.XMLHttpRequest) { 
			req = new XMLHttpRequest();
			req.onreadystatechange = processReqChange; 
			req.open("GET",url,true); 
			req.send(null); 
			
			// Procura por uma versão ActiveX (IE) 
		} else if (window.ActiveXObject) { 
			req = new ActiveXObject("Microsoft.XMLHTTP"); 
			if (req) { 
				req.onreadystatechange = processReqChange; 
				//req.setRequestHeader("Content-Type", "multipart/form-data");
				req.open("GET",url,true); 				
				req.send(null); 
			} 
		}
		
	}else{
		if(e.type != "click"){
			AddListFunctions("ajax('"+url+"','"+param+"','"+display+"','"+obj_form+"','"+modo+"','"+text_inic+"','"+callfunction+"');");
		}
		//setTimeout("AjaxList()",100);
	}
	
} 


janPop = "";
function processReqChange(){ 
	// apenas quando o estado for "completado" 
	if (req.readyState == 4) { 
		// apenas se o servidor retornar "OK" 
		if (req.status == 200) { 
			
			// procura pela div id="pagina" e insere o conteudo 
			// retornado nela, como texto HTML 
			resp = req.responseText;
			
			if(type_return_ajax == 1){			
				
				obj_recip_ajax.innerHTML = resp;
				
				//document.getElementById("display").innerHTML = obj_recip_ajax.id;
				
				
				if(modoLoad == "sequencial"){
					newTag(obj_recip_ajax);
					AjaxList();
				}else{
					/*if(!first){
						first = true;*/
						
						//document.getElementById("display").innerHTML = Math.random();
						/*if(janPop){
							janPop.close();
						}
						
						janPop = window.open("clean.php","janPop");
						janPop.document.write(resp.replace(/</gi,"#"));*/
						
						newTag(obj_recip_ajax);
					/*}*/
				}
			}
			
			if(type_return_ajax == 2){
				if(resp){
					
					//if(type == "select-one"){
						dados = resp.split("<@>");
						size = dados.length;
						obj_recip_ajax.options[0].text = "---";
						
						for(var i=0, n=1; i<size-1;i++, n++){
							var opt = document.createElement("option");
							
							itens = dados[i].split("<!>");
							obj_recip_ajax.options[n] = new Option(itens[1],itens[0].substr(0,30));
			
						}
					//}
					
					/*
					if(type == "text" || type == "hidden"){
						obj_recip_ajax.value = resp;
					}
					*/
				}else{
					if(type == "select"){	
						obj_recip_ajax.options[0].text = "Nenhum registro encontrado.";
					}
				}		
			}
			if(CallFunction){
				//setTimeout(CallFunction);
				eval(CallFunction);
			}
			called = false;
			
		} else { 
			alert("Houve um problema ao obter os dados: "+req.status+" - " + req.statusText);
			obj_recip_ajax.innerHTML = "";
			called = false;			
		} 
		if(list_functions.length){
			//alert(list_functions.length)
			AjaxList();			
		}
	} 
	
} 


function newTag(obj_recip_ajax){
    // Pegando a div que recebrá o JavaScript
    var conteudo = document.body;
    
	if(conteudo != null){
		// Declarando a criação de uma nova tag <script>
		var newElement = document.createElement("script");
		// Pegando os valores das Tags <script> que estão na página carregada pelo AJAX
		var scripts = obj_recip_ajax.getElementsByTagName("script");
		// Aki, vamos inserir o conteúdo da tag <script> que pegamos na linha acima    
		for(i = 0; i < scripts.length; i++)
	   {
			newElement.text += scripts[i].innerHTML;
		
	   }
	   // Agora, inserimos a nova tag <script> dentro da div na página inicial
	   conteudo.appendChild(newElement);
   }
   
   first = false;
   
}


/////////////////////////////