﻿// 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(){
	//alert(list_functions[0])
	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 ajaxUBS(url,param,display,obj_form,modo,text_inic,callfunction) 
{ 
	if(!obj_form)obj_form = "";
	if(!modo)modo = "";
	if(!text_inic)text_inic = "";
	if(!callfunction) callfunction = "";

	var e = window.event;
	if(!called){
		
		//historico_ajax = document.getElementById("myBody").innerHTML;
		
		if(e){
			if(e.type == "click"){
				url_refresh = "";
				url_refresh = [url,param,display,'','','<center><img src=imgs/carrega_imagem.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;  background: #FFFFFF; padding: 10px 10px 10px 10px; border:solid 3px; borderColor: #999999'>";
						content_div += "<div style='float:left'><img src=imgs/carrega_imagem.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.open("POST",url,true); 
				req.send(); 
			} 
		}
	}else{
		
		if(e.type != "click"){
			AddListFunctions("ajaxUBS('"+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=0; 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.statusText);
			called = false;
		} 
		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 ObjPaleta(where){
	var display_paleta = "showpaleta_"+Math.round(Math.random()*100);
	document.write("<div id=boxpaleta style='position:absolute; float:none;'><div style='width:20px; height:20px' onclick=DesenhaPaleta('"+where+"','"+display_paleta+"',this)><img src=images/icone_paleta.gif></div><div id='"+display_paleta+"' style='display:none'></div></div>");
}
function FechaPaleta(display_paleta){
	document.getElementById(display_paleta).innerHTML = "";
	document.getElementById(display_paleta).style.display = "none";
}

function getStyle(obj, styleProp)
{
  if (obj.currentStyle)
    return obj.currentStyle[styleProp];
  else if (window.getComputedStyle)
    return document.defaultView.getComputedStyle(obj,null).getPropertyValue(styleProp);
}

function DesenhaPaleta(campo,display_paleta,obj){
	var r = new Array("00","33","66","99","CC","FF"); 
	var g = new Array("00","33","66","99","CC","FF"); 
	var b = new Array("00","33","66","99","CC","FF");
	
	var c = 0;
	
	var str = "<div style='border:solid 1px; width:100px'><table cellspacing=0 cellpadding=0 border=0><tr>";
	
	for (i=0;i<r.length;i++){ 
	
		str += "<td>"; 
		for (j=0;j<g.length;j++) {
		   str += "<table cellspacing=0 cellpadding=0><tr>";
		   for (k=0;k<b.length;k++) { 
			  var novoc = "#" + r[i] + g[j] + b[k]; 
			  var hexa = "0x" + r[i] + g[j] + b[k]; 
			  str += "<td bgcolor=\"" + novoc + "\" width=7 height=7 align=center onmouseover=EscreveCampo('"+campo+"','"+hexa+"')  onclick=FechaPaleta('"+display_paleta+"')>";
			  //document.write(novoc); 
			  str += "</td>";
		   } 
		   str += "</tr></table>"; 
		} 
		str += "</td>"; 
		
		c++;
		if(c == 3){
			c = 0;
			str += "</tr><tr>";
		}
	} 
	str += "</td></tr></table></div>";
	
	document.getElementById(display_paleta).innerHTML = str;
	document.getElementById(display_paleta).style.display = "block";
}


/*window.onload = function (){
    var m = document.all.bloco.children;
    for (i=0; i<m.length; i++)
       //alert(m.item(i).tagName); 
	   alert(m.item(i).className); 
}*/

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;
	}
}


function MousePosition(e) {
	if(identObj){
		obj_evidencia = document.getElementById("obj_"+identObj);
		
		if(obj_evidencia != null){
			
			if(!MouseHitTestObj(e,obj_evidencia)){
				var obj = document.getElementById("input_"+identObj);
				obj.style.display = "none";

				var obj1 = document.getElementById("text_"+identObj);
				obj1.style.display = "block";
				
				identObj = "";				
			}
			/*var px = pegarPosicaoX(obj_evidencia);
			var py = pegarPosicaoY(obj_evidencia)
		
			var oEvt = e || window.event;
			
			var mx = oEvt.clientX;
			var my = oEvt.clientY;
			
			var larg = obj_evidencia.style.width.replace(/px/gi,"");
			var alt = obj_evidencia.scrollHeight;
			
			if(!((mx > px && mx < px+Number(larg)) && (my > py && my < py+Number(alt)))){
				var obj = document.getElementById("input_"+identObj);
				obj.style.display = "none";

				var obj1 = document.getElementById("text_"+identObj);
				obj1.style.display = "block";
				
				identObj = "";
			}*/		
		}
	}

}

/*function AjustarWindowPric(){

	tam_pag = parent.document.body.scrollHeight;
	
	var iframe = parent.document.getElementById("main_diciplinas");
	if(iframe != null){
		tam_iframe = iframe.height;
		py_iframe = pegarPosicaoY(iframe);
		
		if(tam_pag != tam_iframe && tam_pag < 600){
			iframe.height = tam_pag;
		}
	}
}*/

function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ 
			return true;
		} else {
			mail = "";
			alert("Preencha o e-mail corretamente");
			return false;	
		}
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){ 
           return true; 
        } else {
			alert("Preencha o e-mail corretamente");
			mail.value = "";
			return false;	
		}
    }else{
        return false;
    }
}

/*function checkMail(mail){
    var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    if(typeof(mail) == "string"){
        if(er.test(mail)){ 
			return true;
		}
    }else if(typeof(mail) == "object"){
        if(er.test(mail.value)){ 
           return true; 
        }
    }else{
        return false;
    }
}*/

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);
		var parent = divClear.parentElement || divClear.parentNode;
		
		setTimeout(function() {parent.removeChild(divClear)}, tempo);
	}
}


//////////////////////////////////////////
/////////////////PARCEIROS
identObj = null;

function FormAlterarNome(ident){
	var obj = document.getElementById('input_'+ident);
	obj.style.display = 'block';
	
	identObj = ident;
	
	var obj1 = document.getElementById('text_'+ident);
	obj1.style.display = 'none';
}

document.onmousedown = function(e) { MousePosition(e); } 
//////////////

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;
}
///////////////////////////////////
////////////
url_refresh = "";
function Refresh(){
	if(url_refresh){
		ajax(url_refresh[0],url_refresh[1],url_refresh[2],url_refresh[3],url_refresh[4],url_refresh[5]);
	}
}

function LimpaTeclas(){
	teclas_press = "";
	teclas_press = [];
	tecla_ant = "";
}
LimpaTeclas();

/*
function doSomething(e) {
	
	var code;
	
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	
	var character = String.fromCharCode(code);
	
	var ctrl = e.ctrlKey;
	var tecla = e.keyCode;
	
	///CONTROL + R PARA ATUALIZAR AJAX
	if (ctrl && tecla==82) {Refresh(); e.keyCode=0; return false;}
	///F5 PARA ATUALIZAR AJAX
	if (tecla==116) {Refresh(); e.keyCode=0; return false;}
	
	if(tecla_ant != tecla && teclas_press.length < 3){
		teclas_press.push(tecla);
		//document.getElementById("display").innerHTML = teclas_press.join(" - ");
		tecla_ant = tecla;		
	}
	///CHECA COMBINAÇÕES
	if(teclas_press.length >= 2){
		var tc1 = teclas_press[0];
		var tc2 = teclas_press[1];
		var tc3 = teclas_press[2];
		
		///CONTROL + SHIFT + C PARA CANCELAR AJAX
		if (tc1 == 17 && tc2 == 16 && tc3 == 67) {
			
			LimpaTeclas();
			
			CancelAjax(); 
			e.keyCode=0; 
			
			return false;
		}
		
		///CONTROL + SHIFT + N
		if (tc1 == 17 && tc2 == 16 && tc3 == 78) {
			
			LimpaTeclas();
			
			NovoCadastroPessoa()
			e.keyCode=0; 
			
			return false;
		}
			
		
	}

}
*/
function CancelAjax(){
	/*req = false
	called = false
	alert("Ajax cancelado!");*/
}

function NovoCadastroPessoa(){
	ajax('cadastro/pessoas/index.php','dna=001.001','interior_pag','','','',"setTimeout(function (){document.getElementById('add_pessoa').onclick();},20)");
}


document.onkeydown = function (e){return doSomething(e)}

document.onkeyup = function (){LimpaTeclas()}

/*function EnterFrame = function(func){
	
}*/


/////////////////////////////////////////////////////////////////
//////////// 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 = "images/busca_cep.gif";
	var h = img.height;
	div.style.height = h;
	div.style.top = (y-h)-2;
	
	div.id = "but_cep_"+obj.id;
	
	div.innerHTML = "<div class='cursor_hand' onclick=cxAuxilio('"+obj.id+"')><img src='images/busca_cep.gif'></div>";
	
	obj.style.zIndex = '0';
	document.getElementById('main_result').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(images/fundo_busca_cep.gif?"+Math.round(Math.random()*1000000)+")";
	div.style.zIndex = '1';
	//div.style.border = "solid 1px";
	
	var img = new Image();
	img.src = "images/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.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>";
	
	obj.style.zIndex = '0';
	document.getElementById('main_result').appendChild(div);
	
	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);
	document.getElementById(id_obj).onblur();
}


