/********************************/
/*     loading da pagina        */
/********************************/
/*document.write('<div id="divLoadCont"><img src="../img/carregando.gif" border="0" class="carregando" /></div>');
addEvent(window, 'load', preLoad);

// JavaScript Document
function addEvent(obj, evType, fn)
{
    if (obj.addEventListener)
    {
       obj.addEventListener(evType, fn, false);
       return true;
    }
    else if (obj.attachEvent)
    {
       var r = obj.attachEvent("on"+evType, fn);
       return r;
    } 
    else
    {
       return false;
    }
}*/

function Mov(obj){
	obj.style.backgroundColor = '#000000';
}
function Mou(obj){
	obj.style.backgroundColor = '#FFFFFF';
}
function Move(obj){
	obj.style.backgroundColor = '#dfe7ed';
}
function Mout(obj, cor){
	obj.style.backgroundColor = cor;
}
function exibeDetalhes(id){
  var s = document.getElementById(id).style;
  s.display = s.display == "none" ? "block" : "none";
}

function cadastrar(url){
	window.location = "./"+url;
}

function enviar(url){
	window.location = "./"+url;
}

//abre uma janela de pesquisa do grupo
function abrePesquisa(url){
  var esquerda = (window.screen.width-620)/2;
  var topo = (window.screen.height-400)/2;
	window.open(url, "_blank","left=" + esquerda + ",top=" + topo + ",width=640,height=350,resizable=no,status=no,scrollbars=no");
}

function pagina(x,y){
	alert();
   document.y.action = '?acao=consulta&pagina='+x;	
   document.y.submit();	
}


function getKey(e){
	var tecla;
	if(!e)
		e = window.event;
	if(e.keyCode)
		tecla = e.keyCode;
	else if(e.which)
		tecla = e.which;
	return tecla;
}

//colocar no evento onKeyPress = somenteNumero(event) do input
function somenteNumero(e){
	var tecla = getKey(e);
	if ((tecla >= 48 && tecla <= 57) || (tecla == 8) || (tecla==37) || (tecla==39) || (tecla == 9)){
		return true;
	}else 
		return false;
}

function somenteLetra(e){
	var tecla = getKey(e);
	if ((tecla >= 65 && tecla <= 90) || (tecla >= 97 && tecla <= 122) || (tecla == 8) || (tecla==37) || (tecla==39)){
		return true;
	}else 
		return false;
}

function somenteNumeroLetra(e){
	var tecla = getKey(e);
	if ((tecla >= 65 && tecla <= 90) || (tecla >= 97 && tecla <= 122) || (tecla == 8) || (tecla==37) || (tecla==39) || (tecla >= 65 && tecla <= 90)){
		return true;
	}else 
		return false;
}

//colocar no evento onKeyUp="javascript:somentenumero(this);" do input
function maskEdit(mask, objText, e){
	var _mascara = mask.substring(0,1);

    switch(_mascara){
    	case ',':
    	case '.':
			var sep = 0;
		    var key = '';
		    var separadorMilesimo = '.';
		    var separadorDecimal = ',';
		    var i = 0;
		    var j = 0;
		    var len = 0
		    var len2 = 0;
		    var strCheck = '0123456789';
		    var aux = '';
		    var aux2 = '';
		    var tecla = getKey(e);
		    
		    if (_mascara == ','){
		    	separadorMilesimo = ',';
		    	separadorDecimal = '.';
		    }
		    	
		    if (tecla == 13) return true;
		    if (tecla == 8) return true;
		    if (tecla == 37) return true;
		    if (tecla == 39) return true;
		
		    key = String.fromCharCode(tecla); // Valor para o código da Chave
		    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
		    len = objText.value.length;
		    for(i = 0; i < len; i++)
		        if ((objText.value.charAt(i) != '0') && (objText.value.charAt(i) != separadorDecimal)) break;
		    aux = '';
		    for(; i < len; i++)
		        if (strCheck.indexOf(objText.value.charAt(i))!=-1) aux += objText.value.charAt(i);
		    aux += key;
		    len = aux.length;
		    if (len == 0) objText.value = '';
		    if (len == 1) objText.value = '0'+ separadorDecimal + '0' + aux;
		    if (len == 2) objText.value = '0'+ separadorDecimal + aux;
		    if (len > 2) {
		        aux2 = '';
		        for (j = 0, i = len - 3; i >= 0; i--) {
		            if (j == 3) {
		                aux2 += separadorMilesimo;
		                j = 0;
		            }
		            aux2 += aux.charAt(i);
		            j++;
		        }
		        objText.value = '';
		        len2 = aux2.length;
		        for (i = len2 - 1; i >= 0; i--)
		        objText.value += aux2.charAt(i);
		        objText.value += separadorDecimal + aux.substr(len - 2, len);
		    }
		break;	

	case '#':
		var tecla = getKey(e);
    	if(tecla > 47 && tecla < 58) {
 			var i = objText.value.length; 
 			var saida = mask.substring(0,1); 
 			var texto = mask.substring(i)
 			if (texto.substring(0,1) != saida) { 
 				objText.value += texto.substring(0,1); 
 			}
    		return true; 
    	} else { 
    		if (tecla != 8) { 
    			return false; 
    		}
 			else { 
 				return true; 
 			}
    	}			      	
    }
    return false;
}

//FUNÇÃO PARA CARREGAR CONTEÚDO DO SISTEMA


function preLoad() {
	if (document.getElementById) {  // DOM3 = IE5, NS6
		$("#divLoadCont").css("visibility","hidden");
	}
	else {
		if (document.layers) {  // Netscape 4
			document.hidepage.visibility = 'hidden';
		}
		else {  // IE 4
			document.all.hidepage.style.visibility = 'hidden';
	    }
	}
}


/*---------------------------------------------------------------------------------------------------------*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;		
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
			/* currency é false: retornamos os valores COM os zeros à esquerda, 
			* sem considerar os últimos 2 algarismos como casas decimais 
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
	return val3;
	}
}

function reais(obj,event){

var whichCode = (window.Event) ? event.which : event.keyCode;
/*
Executa a formatação após o backspace nos navegadores !document.all
*/
if (whichCode == 8 && !documentall) {	
/*
Previne a ação padrão nos navegadores
*/
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	obj.value= demaskvalue(x,true).formatCurrency();
	return false;
}
/*
Executa o Formata Reais e faz o format currency novamente após o backspace
*/
FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event){
/*
Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
*/

var whichCode = (window.Event) ? event.which : event.keyCode;
if (whichCode == 8 && documentall) {	
	var valor = obj.value;
	var x = valor.substring(0,valor.length-1);
	var y = demaskvalue(x,true).formatCurrency();

	obj.value =""; //necessário para o opera
	obj.value += y;
	
	if (event.preventDefault){ //standart browsers
			event.preventDefault();
		}else{ // internet explorer
			event.returnValue = false;
	}
	return false;

	}// end if		
}// end backspace

function FormataReais(fld, milSep, decSep, e) {
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;

//if (whichCode == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}


function limpar(campoID){
	var campo = document.getElementsByTagName("input");
	for (i=0; i<campo.length; i++){
		if (campo[i].type == "text" || campo[i].type == "password"){
			if(campo[i].id != '_id')
				campo[i].value = '';
		}
	}
	if(campoID != undefined){
		setaFoco(campoID);
	}
		
}

String.prototype.replaceAll = function(de, para){
    var str = this;
    var pos = str.indexOf(de);
    while (pos > -1){
		str = str.replace(de, para);
		pos = str.indexOf(de);
	}
    return (str);
}

function inverteData(data){
	var dia = data.substr(0,2);
	var mes = data.substr(3,2);
	var ano = data.substr(6,8);

	return (ano+''+dia+''+mes);
}

function getDateCurrentInvert(){
	var data = new Date();
	var dia = data.getDate();
	var mes = data.getMonth()+1;
	var ano = data.getFullYear();
	return (ano+''+dia+''+mes);
}

function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	//var whichCode = (window.Event) ? e.which : e.keyCode;
	var whichCode = getKey(e);
	//alert(whichCode);
	if (whichCode == 13) return true;  // Enter
    if (whichCode == 8) return true;  // Enter
	if (whichCode == 46) return true;  // Enter
	if (whichCode == 39) return true;  // Enter
	if (whichCode == 37) return true;  // Enter
	if (whichCode == 9) return true;
	key = String.fromCharCode(whichCode);  // Get key value from key code
	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
		aux = '';
	for(; i < len; i++)
		if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
			aux += key;
			len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) {
		aux2 = '';
	for (j = 0, i = len - 3; i >= 0; i--) {
		if (j == 3) {
			aux2 += milSep;
			j = 0;
		}
		aux2 += aux.charAt(i);
		j++;
	}
	fld.value = '';
	len2 = aux2.length;
	for (i = len2 - 1; i >= 0; i--)
	fld.value += aux2.charAt(i);
	fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}
//colocar no evento onKeyPress="return(currencyFormat(this,',','.',event))"

function setaFoco(campoId){
	document.getElementById(campoId).focus();
}

function enter(e){
	if(document.all){
		var key = event.keyCode;
         }
	else{
		var key = e.which;
	}
	if(key==13){
		consultar();
	}
}

function novo_registro(url){
	window.location = url;
}

function $B(v){
	return document.getElementById(v);
}


  function Mascara(o,f){
        v_obj=o
        v_fun=f
        setTimeout("execmascara()",1)
    }
    
    /*Função que Executa os objetos*/
    function execmascara(){
        v_obj.value=v_fun(v_obj.value)
    }
    
    /*Função que Determina as expressões regulares dos objetos*/
    function leech(v){
        v=v.replace(/o/gi,"0")
        v=v.replace(/i/gi,"1")
        v=v.replace(/z/gi,"2")
        v=v.replace(/e/gi,"3")
        v=v.replace(/a/gi,"4")
        v=v.replace(/s/gi,"5")
        v=v.replace(/t/gi,"7")
        return v
    }
    
	function Telefone(v){
                v=v.replace(/\D/g,"")                            
                v=v.replace(/^(\d\d)(\d)/g,"($1) $2") 
                v=v.replace(/(\d{4})(\d)/,"$1-$2")      
                return v
        }
	
	function Cep(v){
                v=v.replace(/D/g,"")                            
                v=v.replace(/^(\d{5})(\d)/,"$1-$2") 
                return v
        }
		
	 /*Função que padroniza DATA*/
    function Data(v){
        v=v.replace(/\D/g,"") 
        v=v.replace(/(\d{2})(\d)/,"$1/$2") 
        v=v.replace(/(\d{2})(\d)/,"$1/$2") 
        return v
    }
