var cor1 = "F9F9F9";
var cor2 = "FFFFFF";
var cor3 = "EDF5FA";
var corDestaque = "BACDFA";

function verificaValor(valor, objeto) {
	if(valor == '1') {
		mostra(objeto);
	} else {
		esconde(objeto);
	}
}

function verificaValorCampos(valor, objeto, objeto2) {
	if(valor == '1') {
		mostra(objeto2);
		esconde(objeto);
	} else {
		esconde(objeto2);
		mostra(objeto);
	}
}

function verificaValorCampos_(valor) {
	valor = parseInt(valor) + 1;

	if(arguments[valor].length)
		mostra(arguments[valor]);
	
	for(i = 1; i < arguments.length; i++){
		if((i == valor))
			continue;
		else if(arguments[i].length)
			esconde(arguments[i]);
	}
}

// Funcao para abrir janela que sera dimensionada
function abrirImagem (param) {
	novaJanela = window.open(param, 'Imagem', 'width=1,height=1,left=0,top=20'); 
	novaJanela.focus();
}

// Funcao para dimencionar a janela de acordo com o tamanho da imagem
function dimensionarJanela(){
	if ((screen.Width <= (document.images.imagem_selecionada.width)) && (screen.availHeight <= (document.images.imagem_selecionada.height))) {
		window.resizeTo(screen.Width, screen.availHeight);
	} else {
		window.resizeTo(document.images.imagem_selecionada.width+30,document.images.imagem_selecionada.height+105);
	}
}

// Encripta em SHA1
function encripta(objeto) {
	objeto.value = hex_sha1(objeto.value);
}

function escondeSenhas() {
	senhas.style.display	= 'none';
	senhas0.style.display	= 'block';
	document.form1.alteraSenha.value = "nao";
}

function mostraSenhas() {
	senhas.style.display	= 'block';
	senhas0.style.display	= 'none';
	document.form1.alteraSenha.value = "sim";
}
	

// Funcao que altera o valor caso de erro
function camposFile(nomeForm) {

	var campos = '';
	var separador = "/";
	var primeiro = 0;

	//Limpa marca de erro de todos os campos
	for(i=0; i<document.form1.length; i++) {
		if(document.form1[i].type == 'file') {
			if(primeiro == 0) {
				separador = "";
				primeiro = 1;
			} else {
				separador = "/";
			}
			campos += separador + document.form1[i].name;
		}
	}
	
	return campos;
}

//Verifica extensao do arquivo antes de enviar para o servidor
function verificaImagem(nomeForm, campo, obrigatorio) {
	var campoNovo = eval('document.' + nomeForm + '.' + campo + '.value');

	if (obrigatorio == '') obrigatorio = 0;
	if (obrigatorio) {
		if (campoNovo.length == 0) {
			campoErro(nomeForm, campo);
			erro("Você deve enviar um arquivo para cadastrar esse registro.")
			return false;
		} else {
			verifica = campoNovo.substring((campoNovo.lastIndexOf(".")+1),campoNovo.length);
			if (verifica == "jpg" || verifica == "jpeg" || verifica == "JPG" || verifica == "JPEG") {
				return true;
			} else {
				campoErro(nomeForm, campo);
				erro("Você deve enviar um arquivo no formato .jpg")
				return false;
			}
		}
	} else {
		if (campoNovo.length != 0) {
			verifica = campoNovo.substring((campoNovo.lastIndexOf(".")+1),campoNovo.length);
			if (verifica == "jpg" || verifica == "jpeg" || verifica == "JPG" || verifica == "JPEG") {
				return true;
			} else {
				campoErro(nomeForm, campo);
				erro("Você deve enviar um arquivo no formato .jpg")
				return false;
			}
		} else {
			return true;
		}
	}
}

//Funcao para marcar a linha
function marcarLinha(linha, total) {
	var linhaAtual = '';
	for(i=1; i<=total; i++) {
		linhaAtual = 'document.getElementById(\'linha' + i + '\')';
		if(i == linha) {
			corFundo(eval(linhaAtual),corDestaque)
		} else {
			if(i % 2) {
				corFundo(eval(linhaAtual),cor1)
			} else {
				corFundo(eval(linhaAtual),cor2)
			}
		}
	}
}

//Funcao para marcar a linha
function marcarLinha2(linha, total) {
	var linhaAtual = '';
	for(i=1; i<=total; i++) {
		linhaAtual = 'document.getElementById(\'linha' + i + '\')';
		if(i == linha) {
			corFundo(eval(linhaAtual),"F1F1F1");
			eval(linhaAtual).style.fontWeight='bold';
		} else {
			if(i % 2) {
				corFundo(eval(linhaAtual),"ffffff");
				eval(linhaAtual).style.fontWeight='normal';
			} else {
				corFundo(eval(linhaAtual),"ffffff");
				eval(linhaAtual).style.fontWeight='normal';
			}
		}
	}
}

//Funcao para marcar campo de erro
function campoErro(formulario, campo) {
	if (campo != undefined && formulario != undefined) {
		var campo = 'document.' + formulario + '.' + campo;
		eval(campo).focus();
		eval(campo).style.border = '1px solid #CC3300';
		eval(campo).style.background = '#FFFFE5';
	}
}

//Trocar a cor de fundo
function corFundo(el,cor) {
	el.style.backgroundColor=cor;
}

// Funcao para abrir e fechar os frames
function painel(busca, listagem, formulario) {
	top.principal.document.body.rows = busca + "," + listagem + "," + formulario;
}

// Funcao para abrir e fechar os frames
function painelLateral(listagem, formulario) {
	top.principal.CONTEUDO_FRAME.document.body.cols = listagem + "," + formulario;
}

// Funcao para mostrar a listagem no frame
function listagem(msgTexto) {
	if(msgTexto.length == 0) {
		top.principal.CONTEUDO_LISTAGEM.document.location.href = 'listagem.cfm';
	} else {
		top.principal.CONTEUDO_LISTAGEM.document.location.href = 'listagem.cfm?msgTexto='+msgTexto;
	}
}

// Funcao para mostrar a listagem no frame
function listagemLateral(arquivo) {
	if(arquivo.length == 0) {
		top.principal.CONTEUDO_FRAME.CONTEUDO_LISTAGEM.document.location.href = 'listagem.cfm';
	} else {
		top.principal.CONTEUDO_FRAME.CONTEUDO_LISTAGEM.document.location.href = arquivo;
	}
}

// Funcao para mostrar o formulario no frame
function formulario(codigo, arquivo) {
	//codigo = '' ---> mostra arquivo em branco para evitar piscadas
	//codigo = '0' ---> mostra formulario de insercao
	//codigo = 'idpk' ---> mostra formulario de alteracao
	if(arquivo == undefined) {
		top.principal.CONTEUDO_FORMULARIO.document.location.href = 'formulario.cfm?codigo='+codigo;
	} else {
		top.principal.CONTEUDO_FORMULARIO.document.location.href = arquivo;
	}
}

// Funcao para mostrar o formulario no frame
function formularioLateral(codigo, arquivo) {
	//codigo = '' ---> mostra arquivo em branco para evitar piscadas
	//codigo = '0' ---> mostra formulario de insercao
	//codigo = 'idpk' ---> mostra formulario de alteracao
	if(arquivo == undefined) {
		top.principal.CONTEUDO_FRAME.CONTEUDO_FORMULARIO.document.location.href = 'formulario.cfm?codigo='+codigo;
	} else {
		top.principal.CONTEUDO_FRAME.CONTEUDO_FORMULARIO.document.location.href = arquivo;
	}
}

function FormataData(Campo, teclapres) {
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	vr = vr.replace("/", "");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8) {
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, tam);
		if (tam >= 5 && tam <=10)
			Campo.value = vr.substr(0,2) + '/' + vr.substr(2,2) + '/' + vr.substr(4,4);
	}
}

function FormataHora(Campo, teclapres)
{
	var tecla = teclapres.keyCode;
	var vr = new String(Campo.value);
	vr = vr.replace(":", "");
	vr = vr.replace(":", "");
	vr = vr.replace(":", "");
	vr = vr.replace(":", "");
	vr = vr.replace(":", "");
	tam = vr.length + 1;
	
	if (tecla != 9 && tecla != 8){
		if (tam > 2 && tam < 5)
			Campo.value = vr.substr(0, 2) + ':' + vr.substr(2, tam);
	}
		
}

// Funcoes para mostrar objetos
function mostra(objeto, tipo) {
	elemento = 'document.getElementById(\'' + objeto + '\')';
	if (tipo == undefined) {
		if(elemento) eval(elemento).style.display = 'inline';
	} else {
		if(elemento) eval(elemento).style.display = tipo;
	}
}

// Funcoes para ocultar objetos
function esconde(objeto) {
	elemento = 'document.getElementById(\'' + objeto + '\')';
	if(elemento) eval(elemento).style.display = 'none';
}

function escondeMostra(objeto, tipo) {
	elemento = 'document.getElementById(\'' + objeto + '\')';
	if(elemento && eval(elemento).style.display == 'none') {
		if (tipo == undefined) {
			mostra(objeto, 'inline')
		} else {
			mostra(objeto, tipo)
		}
	} else {
		esconde(objeto)
	}
}

// Funcao para abrir janela que sera dimensionada
function abrirJanela(param, largura, altura) {
	novaJanela = window.open(param, 'Janela', 'width='+largura+',height='+altura+',left=0,top=0'); 
	novaJanela.focus();
}

function popup(arquivo, titulo, largura, altura, tipo) {
		
	if( typeof(tipo) == "undefined" ){
		novaJanela = window.open(arquivo, titulo, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width='+largura+',height='+altura+',top=0,left=0');
	} else if(tipo == "impressao"){
		novaJanela = window.open(arquivo, titulo, 'toolbar=yes,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+largura+',height='+altura+',top=0,left=0');
	} else if(tipo == "novo" || tipo == "nova") {
		novaJanela = window.open(arquivo, titulo, '');
	} else {
		novaJanela = window.open(arquivo, titulo, tipo);
	}

	// Verifica se abriu a janela
	if (!novaJanela) {

		elemento1 = 'document.getElementById("popupBloqueado")';
		elemento2 = 'document.getElementById("estrutura")';
		elemento3 = 'document.getElementById("bannerLateral")';

		// Verifica se existe o DIV
		if (eval(elemento1)) {
			eval(elemento1).style.display = 'block';
		}

		// Verifica se existe o DIV
		if (eval(elemento2)) {
			eval(elemento2).style.top = '42px';
		}

		// Verifica se existe o DIV
		if (eval(elemento3)) {
			eval(elemento3).style.top = '42px';
		}

	} else {
		novaJanela.focus();
	}
}

// Funcao para alterar posicao do elemento
function posicao(objeto,pos) {
	elemento = 'document.getElementById(\'' + objeto + '\')';
	if(elemento) eval(elemento).style.top = pos;
}

function estaInativo(valor, alvo){
	var linha = document.getElementById(alvo);
	if(typeof(linha) == 'object'){
		if(valor == 0)
			linha.style.color = 'gray';
		else
			linha.style.color = 'black';
	}
}

function limiteCampo(campo, limite, avisa) {
	if (campo.value.length > limite)
		campo.value = campo.value.substring(0, limite);
	if (avisa != undefined) {
		avisa.innerHTML = campo.value.length;
	} else {
		document.getElementById('avisaTamanho').innerHTML = campo.value.length + ' caracteres de ' + limite;
	}
}

function marcaletra(letra) {
	var elemento = "";
	var letras = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,Todos";
	letras = letras.split(",");

	for(i=0; i<letras.length; i++){
		elemento = 'document.getElementById(\'' + letras[i] + '\')';
		eval(elemento).style.color = "000000";
		eval(elemento).style.fontWeight = "normal";
	}

	elemento = 'document.getElementById(\'' + letra + '\')';
	eval(elemento).style.color = "bc1212";
	eval(elemento).style.fontWeight = "bold";

}


function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

MaskInput = function(f, m){
   function mask(e){
       var patterns = {"1": /[A-Z]/i, "2": /[0-9]/, "4": /[\xC0-\xFF]/i, "8": /./ },
           rules = { "a": 3, "A": 7, "9": 2, "C":5, "c": 1, "*": 8};
       function accept(c, rule){
           for(var i = 1, r = rules[rule] || 0; i <= r; i<<=1)
               if(r & i && patterns[i].test(c))
                   break;
               return i <= r || c == rule;
       }
       var k, mC, r, c = String.fromCharCode(k = e.key), l = f.value.length;
       (!k || k == 8 ? 1 : (r = /^(.)\^(.*)$/.exec(m)) && (r[0] = r[2].indexOf(c) + 1) + 1 ?
           r[1] == "O" ? r[0] : r[1] == "E" ? !r[0] : accept(c, r[1]) || r[0]
           : (l = (f.value += m.substr(l, (r = /[A|9|C|\*]/i.exec(m.substr(l))) ?
           r.index : l)).length) < m.length && accept(c, m.charAt(l))) || e.preventDefault();
   }
   for(var i in !/^(.)\^(.*)$/.test(m) && (f.maxLength = m.length), {keypress: 0, keyup: 1})
       addEvent(f, i, mask);
};

addEvent = function(o, e, f, s){
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e){
        try{
            (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
            e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
            e.target || (e.target = e.srcElement || null);
            e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        }catch(f){}
        for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
    for(var i = (e = o["_on" + e] || []).length; i;)
        if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
            return delete e[i];
    return false;
};


function mascarar(w,e,m,r,a) {
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	
	// Variáveis da função
	var txt = (!r) ? w.value.replace(/[^\d]+/gi,'') : w.value.replace(/[^\d]+/gi,'').reverse();
	var mask = (!r) ? m : m.reverse();
	var pre = (a ) ? a.pre : "";
	var pos = (a ) ? a.pos : "";
	var ret = "";
	
	// Cancela se o evento for Backspace
	//if(code == 9 || code == 8 || txt.length == mask.replace(/[^#]+/g,'').length) return false;

	// Loop na máscara para aplicar os caracteres
	for(var x=0,y=0, z=mask.length;x<z && y<txt.length;){
		if(mask.charAt(x)!='#'){
			ret += mask.charAt(x); x++;
		} else{
			ret += txt.charAt(y); y++; x++;
		}
	}

	// Retorno da função
	ret = (!r) ? ret : ret.reverse() 
	w.value = pre+ret+pos;
}

// Novo método para o objeto 'String'
String.prototype.reverse = function(){
	return this.split('').reverse().join('');
}
