var imagem = new Image();
imagem.src = "app/imagens/botao_salvar.gif";

var imagem = new Image();
imagem.src = "app/imagens/botao_salvar_over.gif";

if(!document.getElementById){
  if(document.all)
  document.getElementById=function(){
    if(typeof document.all[arguments[0]]!="undefined")
    return document.all[arguments[0]]
    else
    return null
  }
  else if(document.layers)
  document.getElementById=function(){
    if(typeof document[arguments[0]]!="undefined")
    return document[arguments[0]]
    else
    return null
  }
}

function excluir(link) {
	if (confirm('Confirma exclusão do item?')) {
		document.location.href=link;
		return true;
	}
	return false;
}

function setaFocus(formulario, campo) {
	document.forms[formulario].elements[campo].focus();
}

function habilitaDiv (div) {
	elemento = document.getElementById(div);
	if (elemento) elemento.style.display = "";
}

function desabilitaDiv (div) {
	elemento = document.getElementById(div);
	if (elemento) elemento.style.display = "none";
}

function selecionar_tudo(formulario, marcar){
	with(document.forms[formulario]) {
		for (i=0;i<elements.length;i++) {
			if(elements[i].type == "checkbox") {
				elements[i].checked = marcar;
			}
		}
	}
	return false;
}

function selecionar_invert(formulario){
	with(document.forms[formulario]) {
		for (i=0;i<elements.length;i++) {
			if(elements[i].type == "checkbox") {
				elements[i].checked = !elements[i].checked;
			}
		}
	}
	return false;
}

function acrescentaTabela(tabela, html) {
	if (tabela.insertAdjacentHTML) {
		tabela.insertAdjacentHTML("afterEnd",html);
	} else {
		var r = document.createRange();
		r.setStartBefore(tabela);

		var parsedNode = r.createContextualFragment(html);
		var parent = tabela.parentNode;
		if (tabela.nextSibling)
			parent.insertBefore(parsedNode, tabela.nextSibling);
		else
			parent.appendChild(parsedNode);
	}
}

function RelogioServer () {
	hora = hora_server
	minuto = minuto_server
	segundo = segundo_server
	
	if (hora < 10){
		hora = "0" +  hora
	}
	if (minuto < 10){
		minuto = "0" + minuto
	}
	if (segundo < 10){
		segundo = "0" + segundo
	}
   
	elemento = document.getElementById("relogio_server");
	if (elemento) elemento.innerHTML = ""+hora+":"+minuto+":"+segundo;
	window.status = "Data e hora do servidor: "+data_server+" "+hora+":"+minuto+":"+segundo;
	segundo_server = segundo_server + 1;
	
	if (segundo_server==60) {
		segundo_server = 0;
		minuto_server = minuto_server + 1;
	}
	if (minuto_server==60) {
		minuto_server = 0;
		hora_server = hora_server + 1;
	}
	if (hora_server==24) hora_server = 0;

	var RelogioServerAtualizar = setTimeout("RelogioServer()",  "1000");
}

function Relogio() {
	elemento = document.getElementById("relogio");
	if (elemento) {
		data = new Date()
	   
		var horas= data.getHours()
		var minutos= data.getMinutes()
		var segundos= data.getSeconds()
	   
		if (horas < 10){
			horas = "0" +  horas
		}
		if (minutos < 10){
			minutos = "0" + minutos
		}
		if (segundos < 10){
			segundos = "0" + segundos
		}
	   
		elemento.innerHTML = ""+horas+":"+minutos+":"+segundos;
	
		var RelogioAtualizar = setTimeout("Relogio()",  "1000");
	}
}

function GetXmlHttpObject()
{
	var objXMLHttp=null
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest()
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
	}
	return objXMLHttp
}

function format_number(pnumber,decimals) 
{  
	if (isNaN(pnumber)) { return 0};  
	if (pnumber=='') { return 0};  
	var IsNegative=(parseInt(pnumber)<0); 
	if(IsNegative)pnumber=-pnumber; 
	var snum = new String(pnumber);  
	var sec = snum.split('.');  
	var whole = parseInt(sec[0]);  
	var result = '';
	if(sec.length > 1){  
		var dec = new String(sec[1]);  
		dec = parseInt(dec*1)/Math.pow(10,parseInt(dec.length-decimals-1)); 
		Math.round(dec); 
		dec = parseInt(dec)/10; 
		if(IsNegative) 	{
			var x = 0-dec; 
			x = Math.round(x); 
			dec = - x; 
		} 
		else {	dec = Math.round(dec); 	} 
		if(dec==Math.pow(10, parseInt(decimals))){ 
			whole+=1; 
			dec="0"; 
		} 
		dec = String(dec);
		while(dec.length < decimals) { dec = '0'+dec; }  
		dec = String(whole) + "." + String(dec);  
		var dot = dec.indexOf('.');  
		if(dot == -1){  
			dec += '.';  
			dot = dec.indexOf('.');  
		} 
		var l=parseInt(dot)+parseInt(decimals); 
		while(dec.length <= l) { dec += '0'; }  
		result = dec;  
	} else{  
		var dot;  
		var dec = new String(whole);  
		dec += '.';  
		dot = dec.indexOf('.');  
		var l=parseInt(dot)+parseInt(decimals); 
		while(dec.length <= l) { dec += '0'; }  
		result = dec;  
	}  
	if(IsNegative)result="-"+result; 
	return result;  
}

function float2moeda(num) {

   x = 0;

   if(num<0) {
      num = Math.abs(num);
      x = 1;
   }

   if(isNaN(num)) num = "0";
      cents = Math.floor((num*100+0.5)%100);

   num = Math.floor((num*100+0.5)/100).toString();

   if(cents < 10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
         num = num.substring(0,num.length-(4*i+3))+'.'
               +num.substring(num.length-(4*i+3));

   ret = num + ',' + cents;

   if (x == 1) ret = ' - ' + ret;return ret;

}

//ajax utilizado para chamar rotina que apaga arquivos temporários
var xmlHttp2
xmlHttp2=GetXmlHttpObject()
if (xmlHttp2!=null) {
	var url="app/functions/limpaPastas.php"
	xmlHttp2.open("GET",url,true)
	xmlHttp2.send(null)
}

function invertDiv (div) {
	elemento = document.getElementById(div);
	if (elemento) {
		if (elemento.style.display=="none") {
			elemento.style.display = "";
		} else {
			elemento.style.display = "none";
		}
	}
}

Mascaras = {
	IsIE: navigator.appName.toLowerCase().indexOf('microsoft')!=-1,
	AZ: /[A-Z]/i,
	Acentos: /[À-ÿ]/i,
	Num: /[0-9]/,
	carregar: function(parte){
		var Tags = ['input','textarea'];
		if (typeof parte == "undefined") parte = document;
		for(var z=0;z<Tags.length;z++){
			Inputs=parte.getElementsByTagName(Tags[z]);
			for(var i=0;i<Inputs.length;i++)
				if(('button,image,hidden,submit,reset').indexOf(Inputs[i].type.toLowerCase())==-1)
			this.aplicar(Inputs[i]);
		}
	},
	aplicar: function(campo){
		tipo = campo.getAttribute('tipo');
		if (!tipo || campo.type == "select-one") return;
		orientacao = campo.getAttribute('orientacao');
		mascara = campo.getAttribute('mascara');
		if (tipo.toLowerCase() == "decimal"){
			orientacao = "esquerda";
			casasdecimais = campo.getAttribute('casasdecimais');
			tamanho = campo.getAttribute('maxLength');
			if (!tamanho || tamanho > 50)
				tamanho = 10;
			if (!casasdecimais)
				casasdecimais = 2;
			campo.setAttribute("mascara", this.geraMascaraDecimal(tamanho, casasdecimais));
			campo.setAttribute("tipo", "numerico");
			campo.setAttribute("orientacao", orientacao);
		}
		if (orientacao && orientacao.toLowerCase() == "esquerda") campo.style.textAlign = "right";
		if (mascara) campo.setAttribute("maxLength", mascara.length);
		if (tipo){
			campo.onkeypress = function(e){ return Mascaras.onkeypress(e?e:event); };
			campo.onkeyup = function(e){ Mascaras.onkeyup(e?e:event, campo) };
		}
		campo.setAttribute("snegativo", ((campo.value).substr(0,1) == "-" ? "s" : "n"));
	},
	onkeypress: function(e){
		KeyCode = this.IsIE ? event.keyCode : e.which;
		campo =  this.IsIE ? event.srcElement : e.target;
		readonly = campo.getAttribute('readonly');
		if (readonly) return;
		maxlength = campo.getAttribute('maxlength');
		pt = campo.getAttribute('pt');
		selecao = this.selecao(campo);
		if (selecao.length > 0 && KeyCode != 0){
			campo.value = ""; return true;
		}
		if (KeyCode == 0) return true;
		Char = String.fromCharCode(KeyCode);
		valor = campo.value;
		mascara = campo.getAttribute('mascara');
		if (KeyCode != 8){
			tipo = campo.getAttribute('tipo').toLowerCase();
			negativo = campo.getAttribute('negativo');
			if(negativo && KeyCode == 45){
				snegativo = campo.getAttribute('snegativo');
				snegativo = (snegativo == "s" ? "n" : "s");
				campo.setAttribute("snegativo", snegativo);
			}else{
				valor += Char
				if (tipo == "numerico" && Char.search(this.Num) == -1) return false;
				if (KeyCode != 32 && tipo == "caracter" && Char.search(this.AZ) == -1 && Char.search(this.Acentos) == -1) return false;
			}
		}
		if (mascara){
			this.aplicarMascara(campo, valor);
			return false;
		}
		return true;
	},
	onkeyup: function(e, campo){
		KeyCode = this.IsIE ? event.keyCode : e.which;
		if (KeyCode != 9 && KeyCode != 16 && KeyCode != 109){
			valor = campo.value;
			if (KeyCode == 8 && !this.IsIE) valor = valor.substr(0,valor.length-1);
			this.aplicarMascara(campo, valor);
		}
	},
	aplicarMascara: function(campo, valor){
		mascara = campo.getAttribute('mascara');
		if (!mascara) return;
		negativo = campo.getAttribute('negativo');
		snegativo = campo.getAttribute('snegativo');
		if (negativo && valor.substr(0,1) == "-")
			valor = valor.substr(1,valor.length-1);
		orientacao = campo.getAttribute('orientacao');
		var i = 0;
		for(i=0;i<mascara.length;i++){
			caracter = mascara.substr(i,1);
			if (caracter != "#") valor = valor.replace(caracter, "");
		}
		retorno = "";
		if (orientacao != "esquerda"){
			contador = 0;
			for(i=0;i<mascara.length;i++){
				caracter = mascara.substr(i,1);
				if (caracter == "#"){
					retorno += valor.substr(contador,1);
					contador++;
				}else
					retorno += caracter;
				if(contador >= valor.length) break;
			}
		}else{
			contador = valor.length-1;
			for(i=mascara.length-1;i>=0;i--){
				if(contador < 0) break;
				caracter = mascara.substr(i,1);
				if (caracter == "#"){
					retorno = valor.substr(contador,1) + retorno;
					contador--;
				}else
					retorno = caracter + retorno;
			}
		}
		if (negativo && snegativo == "s")
			retorno = "-" + retorno;
		campo.value = retorno;
	},
	geraMascaraDecimal: function(tam, decimais){
		var retorno = ""; var contador = 0; var i = 0;
		decimais = parseInt(decimais);
		for (i=0;i<(tam-(decimais+1));i++){
			retorno = "#" + retorno;
			contador++;
			if (contador == 3){
				retorno = "." + retorno;
				contador=0;
			}
		}
		retorno = retorno + ",";
		for (i=0;i<decimais;i++) retorno += "#";
		return retorno;
	},
	selecao: function(campo){
		if (this.IsIE)
			return document.selection.createRange().text;
		else
			return (campo.value).substr(campo.selectionStart, (campo.selectionEnd - campo.selectionStart));
	},
	formataValor: function (valor, decimais){
		valor = valor.split('.');
		if (valor.length == 1) valor[1] = "";
		for(var i=valor[1].length;i<decimais;i++)
			valor[1] += "0";
		valor[1] = valor[1].substr(0,2);
		return (valor[0] + "." + valor[1]);
	}
}

var xmlHttpConteudo

function buscaConteudo(modulo, acao, params) {
	if (modulo=="" || acao=="") {
		return false;
	}
	xmlHttpConteudo=GetXmlHttpObject()
	if (xmlHttpConteudo==null)
	{
		alert ("Este browser não suporta HTTP Request")
		return false;
	}
	
	if (params==undefined) {
		params = "";
	}
	
	var url="ajax.php";
	params = params+"modulo="+modulo+"&acao="+acao;
	xmlHttpConteudo.onreadystatechange = function () {
		if (xmlHttpConteudo.readyState==4 || xmlHttpConteudo.readyState=="complete")
		{
			if (xmlHttpConteudo.responseText=="autenticar") {
				window.location.href = "index.php";
			} else {
				document.getElementById("conteudo").innerHTML = xmlHttpConteudo.responseText
				ultimo = 0;
				Mascaras.carregar();
				desabilitaDiv('carregando');
				desabilitaDiv('carregando2');
			}
		} else {
			window.status = "Carregando...";
			habilitaDiv('carregando');
			habilitaDiv('carregando2');
		}
	}
	xmlHttpConteudo.open("GET",url+"?"+params,true);
    //xmlHttpConteudo.setRequestHeader('Content-Type','text/xml'); 
    //xmlHttpConteudo.setRequestHeader('encoding','ISO-8859-1'); 
	//xmlHttpConteudo.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//xmlHttpConteudo.setRequestHeader("Content-length", params.length);
	xmlHttpConteudo.send('');
	
	return false;
}

function processa_form(formulario){
	var params = "";
	var modulo = "";
	var acao = "";
	with(document.forms[formulario]) {
		for (i=0;i<elements.length;i++) {
			if (elements[i].name=="modulo") {
				modulo = elements[i].value;
				continue;
			}
			if (elements[i].name=="acao") {
				acao = elements[i].value;
				continue;
			}
			if(elements[i].type == "checkbox") {
				if (elements[i].checked)
					params = params + elements[i].name + "=" + elements[i].value + "&";
			} else {
				params = params + elements[i].name + "=" + elements[i].value + "&";
			}
		}
	}
	buscaConteudo(modulo, acao, params);
	return false;
}

var ultimo = 0;
function addTabela(tipo) {
	xmlHttpEnd=GetXmlHttpObject()
	if (xmlHttpEnd==null)
	{
		alert ("Este browser não suporta HTTP Request")
		return false;
	}
	tabela = document.getElementById(tipo+"[0]");
	ultimo = ultimo + 1;
	
	var url="ajax.php";
	params = "modulo="+tipo+"&acao=add"+tipo+"&secure=0&key="+ultimo;
	xmlHttpEnd.onreadystatechange = function () {
		if (xmlHttpEnd.readyState==4 || xmlHttpEnd.readyState=="complete")
		{
			if (xmlHttpEnd.responseText=="autenticar") {
				window.location.href = "index.php";
			} else {
				html = xmlHttpEnd.responseText
				acrescentaTabela(tabela, html);
				Mascaras.carregar();
			}
			desabilitaDiv('carregando');
			desabilitaDiv('carregando2');
		} else {
			window.status = "Carregando...";
			habilitaDiv('carregando');
			habilitaDiv('carregando2');
		}
	}
	xmlHttpEnd.open("GET",url+"?"+params,true);
	xmlHttpEnd.send('');
}

function delTabela (tipo, key) {
	excluir = document.getElementById(tipo+"s["+key+"][excluir]");
	if (excluir) { 
		excluir.value = "S";
		desabilitaDiv(tipo+"["+key+"]");
	}
}

function PulaCampo(e) {
	if (document.all)
		ctrl = e.srcElement;
	else
		ctrl = e.target;
		
  iNumCampo = parseInt(ctrl.name.substr(4, 2));
	
	if ((iNumCampo < 10 && ctrl.value.length != 4) || (iNumCampo == 10 && ctrl.value.length != 1))
		return true;
	
	if (iNumCampo == 10)
		sNomeCampo = "save";
	else
		sNomeCampo = "area" + (iNumCampo +1);
	
	for (ind = 0; ind < document.form_cadastro.elements.length; ind++)
		if (document.form_cadastro.elements[ind].name == sNomeCampo) {
			document.form_cadastro.elements[ind].focus();
			break;
		}
			
	return true;
}

function PulaCampo2(e) {
	if (document.all)
		ctrl = e.srcElement;
	else
		ctrl = e.target;
		
  iNumCampo = parseInt(ctrl.name.substr(4, 2));
	
	if (iNumCampo <= 12 && ctrl.value.length != 4)
		return true;
	
	if (iNumCampo == 12)
		sNomeCampo = "save";
	else
		sNomeCampo = "area" + (iNumCampo +1);
	
	for (ind = 0; ind < document.form_cadastro.elements.length; ind++)
		if (document.form_cadastro.elements[ind].name == sNomeCampo) {
			document.form_cadastro.elements[ind].focus();
			break;
		}
			
	return true;
}

function ValidaTecla(e) {
	// Valida tecla
	if (document.all)
		KeyNum = event.keyCode;
	else
		KeyNum = e.which;
		
	if (KeyNum < 32)
		return true;
		
	Key =	String.fromCharCode(KeyNum);

	if (Key < "0" || Key > "9")
		return false;
		
	return true;
}

function muda_sistema (sistema) {
	buscaConteudo("contra_senha", "cadastro", "tipo_sistema="+sistema+"&");
}

var campo_cidade = "";
function MandaID(estado_id, cidade_id, num_registro) {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp==null) {
		alert ("Este browser não suporta HTTP Request");
		return;
	}
	
	var url="app/functions/buscaCidades.php";
	url=url+"?estado_id="+estado_id+"&cidade_id="+cidade_id+"&texto=Selecione&sid="+Math.random();
	campo_cidade = "enderecos["+num_registro+"][cidade_id]";
	xmlHttp.onreadystatechange = function stateChanged() {
		if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
			document.getElementById(campo_cidade).innerHTML = xmlHttp.responseText;
			desabilitaDiv('carregando');
			desabilitaDiv('carregando2');
		} else {
			habilitaDiv('carregando');
			habilitaDiv('carregando2');
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function popUp(pagina, largura, altura) {
	var top = (window.screen.height - altura) / 2;
	var left = (window.screen.width - largura) / 2;
	window.open(pagina, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,statusbar=no,menubar=no,scrollbars=no,resizable=no,copyhistory=no,width='+largura+',height='+altura+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

function popUp2(pagina, largura, altura) {
	var top = (window.screen.height - altura) / 2;
	var left = (window.screen.width - largura) / 2;
	window.open(pagina, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,statusbar=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width='+largura+',height='+altura+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

function Escolheu_versao(item) {
	window.location = "#" + item.options[item.selectedIndex].value;
}

function abreJanelaChamado (chamado_id) {
	var janela = new Ext.Window({
		title: 'Dados do Chamado '+chamado_id, //Titulo
		modal: true, //Bloquear a página
		resizable: true, //Redimencionar Janela
		draggable: true, //Mover Janela
		width: 550, //Largura
		autoHeight: true,
		autoLoad: {url: 'ajax.php?modulo=suporte&acao=buscaChamado&chamado_id='+chamado_id}
	});
	janela.show();
}
