// 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) 
{ 
	
	var e = window.event;
	
	if(!called){
		
		historico_ajax = document.body.innerHTML;
		
		if(e){
			if(e.type == "click"){
				url_refresh = "";
				url_refresh = [url,param,display,'','','<center><img src=imgs/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://www.we3m.com.br/ProjetoMelancia/imgs/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("POST",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(); 
			} 
		}
	}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;
				
				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:n" + req.statusText);
		} 
		if(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;
   
}


/////////////////////////////

var sobre = "";


function EscreveCampo(campo,valor){
	document.getElementById("boxpaleta").style.zIndex = '1'; 
	document.getElementById(campo).value = valor;
}

document.onclick = function (){
	//FechaPaleta(display_paleta);
}

function IsNumber(valor){
	var carCode = event.keyCode;
	if ((carCode < 48) || (carCode > 57)){
		return false;
	}else{
		return true;
	}
}

function IsNotSpace(valor){
	var carCode = event.keyCode;
	if ((carCode == 32)){
		return false;
	}else{
		return true;
	}
}

function hidden(){
	document.body.style.overflow='hidden';
}
function ListarAtrib(obj){
	var objeto = obj;
	var atributos = "";
	for(var i = 0; i < objeto.attributes.length; i++){
		//if(objeto.attributes[i].specified)
		atributos += objeto.attributes[i].nodeName + " - "+ objeto.attributes[i].nodeValue + "<br>";
	}
	
	return atributos;
}

function LimpaEspacos(input){
	
	/*var valor = input.value;
	var pos = valor.indexOf(' ');
	while( pos == 0 ){
		valor = valor.replace(' ','');
		pos = valor.indexOf(' ');			
	}
	
	pos = valor.lastIndexOf(' ');
	if(pos != -1){
		while( pos == (valor.length-1)){
			valor = valor.substr(0,valor.length-1);
			pos = valor.lastIndexOf(' ');
		}
	}
	//return valor;
	input.value = valor;*/
	
	var valor = input.value;
	valor_temp = valor.split(" ");
	for(var i = 0; i<valor.length; i++){
		if(valor_temp[i] == ""){
			t1 = valor_temp.slice(0,i);
			t2 = valor_temp.slice(i+1);
			valor_temp = t1.concat(t2);
			i--;
			
		}
	}
	valor_temp = valor_temp.join(" ");
	input.value = valor_temp;
	
}

function pegarPosicaoX(element)
{
	var current_left = 0;
	
	if (element.offsetParent) {
		while (element.offsetParent) {
			current_left += element.offsetLeft
			element = element.offsetParent;
		}
	} else if (element.x)
		current_left += element.x;
	
	return current_left;	

}

function pegarPosicaoY(element)
{
	var current_top = 0;
	
	if (element.offsetParent) {
		while (element.offsetParent) {
			current_top += element.offsetTop
			element = element.offsetParent;
		}
	} else if (element.y)
		current_top += element.y;
	
	return current_top;

} 


function MouseHitTestObj(e, obj){
	var obj_evidencia = obj;
	var px = pegarPosicaoX(obj_evidencia);
	var py = pegarPosicaoY(obj_evidencia);
	
	var scrolltop = document.documentElement.scrollTop;
	
	//MousePosition(Mouse);
	
	var oEvt = e || window.event;
	
	var mx = oEvt.pageX ||oEvt.clientX;
	var my = oEvt.pageY || oEvt.clientY+scrolltop;
	
	var larg = obj_evidencia.offsetWidth || obj_evidencia.scrollWidth;
	var alt = obj_evidencia.offsetHeight || obj_evidencia.scrollHeight;
	
	if(!((mx > px && mx < Number(px)+Number(larg)) && (my > py && my < Number(py)+Number(alt)))){
		return false;
	}else{
		return true;
	}
}


var disabs;
///////////////////////////
function disabledForm(id_form){
	var form = document.getElementById(id_form);
	disabs = "";
	disabs = [];
	for(var i=0; i<form.length; i++){
		if(form[i].disabled){
			disabs.push(form[i]);
		}
		form[i].disabled = true;
	}	
}

function enabledForm(id_form){
	var form = document.getElementById(id_form); 
	for(var i=0; i<form.length; i++){
		form[i].disabled = false;
	}
	if(disabs.length){
		for(var i=0; i<disabs.length; i++){
			disableItensForm(disabs[i],true);
		}
	}	
}

function disableItensForm(Item,value){
	Item.disabled = value;
}

function limpaForm(id_form){
	var form = document.getElementById(id_form); 
	for(var i=0; i<form.length; i++){
		if(form[i].type != "submit"){
			if(form[i].type == "text"){
				form[i].value = "";
			}			
		}
	}	
}

//////////////////////////////
function clearDiv(id,tempo){
	divClear = document.getElementById(id);
	if(divClear != null){
		//setTimeout("divClear.innerHTML = '';divClear.style.display='none';",tempo);
		if(divClear.parentElement){
			var parent = divClear.parentElement;
		}else{
			var parent = divClear.offsetParent;	
		}
		
		setTimeout(function() {parent.removeChild(divClear)}, tempo);
	}
}


function ChildNodes(element){
	elm = element.childNodes;
	
	var retorno = "";
	var retorno = [];
	
	for(var i=0; i<elm.length; i++){
		if(elm[i].type)retorno.push(elm[i]);
	}
	
	return retorno;
}

function pegaElementos(local){
	local = document.getElementById(local);
	local = local.childNodes;
	
	var retorno = "";
	var retorno = [];
	
	var more;
	
	for(var i=0; i<local.length; i++){
	
		if(local[i].childNodes.length){
			more = ChildNodes(local[i]);
			if(more.length){
				for(var a=0; a<more.length; a++){
					retorno.push(more[a]);
				}
			}
		}else{
			if(local[i].type)retorno.push(local[i]);			
		}
	}

	return retorno;
}

/////////////////////////////////////////////////////////////////
//////////// AUXILIADOR CEP /////////////////////////////////////
/////////////////////////////////////////////////////////////////
evento_ant = document.onmousedown;
function ButAuxilio(obj){
	
	ApagaButAuxilio(obj);
	
	var y = pegarPosicaoY(obj);
	var x = pegarPosicaoX(obj);
	var w = obj.scrollWidth;
	var h = obj.scrollHeight;
	
	var div = document.createElement('div');
	//div.style.width = w;
	div.style.position = 'absolute';
	div.style.float = 'left';
	div.style.left = x-2;
	//div.style.background = "#FFFFFF";
	div.style.zIndex = '1';
	//div.style.border = "solid 1px";
	
	var img = new Image();
	img.src = "imgs/busca_cep.gif";
	var h = img.height;
	div.style.height = h;
	//div.style.top = (y-h)-2;
	div.style.top = y + 20;
	
	div.id = "but_cep_"+obj.id;
	
	div.innerHTML = "<div class='cursor_hand' onclick=ApagaButAuxilio(this);cxAuxilio('"+obj.id+"')><img src='imgs/busca_cep.gif'></div>";
	
	obj.style.zIndex = '0';
	document.body.appendChild(div);
	
	evento_ant = document.onmousedown;		
	document.onmousedown = function (e){ApagaButAuxilio(e,div,obj.id)};
	
}

function cxAuxilio(id_obj){

	var obj = document.getElementById(id_obj);
	
	var y = pegarPosicaoY(obj);
	var x = pegarPosicaoX(obj);
	var h = obj.scrollHeight;
	
	var div = document.createElement('div');
	div.style.position = 'absolute';
	div.style.float = 'left';
	div.style.left = x-2;
	div.style.background = "url(imgs/fundo_busca_cep.gif?"+Math.round(Math.random()*1000000)+")";
	div.style.zIndex = '1';
	//div.style.border = "solid 1px";
	
	var img = new Image();
	img.src = "imgs/fundo_busca_cep.gif";
	var h = img.height;
	var w = img.width;
	div.style.height = h;
	div.style.width = w;
	//div.style.top = (y-h)-2;
	div.style.top = y + 20;
	
	div.id = "cx_busca_cep_"+id_obj;
	
	div.innerHTML = "<center><div style='height:30px; width:100%'>&nbsp;</div>";
		div.innerHTML += "<center><iframe frameborder=0 scrolling=no src='busca_cep/busca_cep.php?id_obj="+id_obj+"&id_div="+div.id+"' width=100% height=100% style='border:solid 1px;width:"+(w-10)+";height:"+(h-45)+";background:#FFFFFF;'></iframe></center>";
	div.innerHTML += "</center>";
	
	document.body.appendChild(div);
	obj.style.zIndex = '0';
	
	evento_ant = document.onmousedown;	
	document.onmousedown = function (e){ApagaCxAuxilio(e,div,obj.id)};
	
	//setTimeout(function (){ajax("cadastro/busca_cep.php","",'content_busca_cep_'+id_obj)},10);
	
	
}
function ApagaButAuxilio(e,div,id_cx){
	if(div){
		document.onmousedown = evento_ant;
		var over = (MouseHitTestObj(e,div));
		if(over){
			cxAuxilio(id_cx);
		}
		clearDiv(div.id,1);
	}
}

function ApagaCxAuxilio(e,div,id_cx){	
	if(div){
		var over = (MouseHitTestObj(e,div));
		if(!over){
			clearDiv(div.id,1);
			document.onmousedown = evento_ant;
		}
	}
}


////////////
function EscolheCEP(cep,id_obj,id_cx){
	document.getElementById(id_obj).value = cep;
	clearDiv(id_cx,1);
	//alert(document.getElementById(id_obj).id);
	document.getElementById(id_obj).focus();
	
}