String.prototype.trim = function(){
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var mes_nome = new Array ("Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro")
var carregandoAberto = false;
var noSubmit = false; // caso essa varivel seja verdadeira a funcao validar nao executa o submit

/* reescrevendo as funcoes*/
	window.onresize = postitPosition;
	window.onload = postiCreate;
/**/
var navegador = /msie/i.test(navigator.userAgent);

function apenasNumeros(e){
	/* how to use
		onKeyPress="return apenasNumeros(event);"
	*/
	
	
	if (navegador){
		var tecla = event.keyCode;
	}else{
		var tecla = e.which;
	}

	if(tecla > 47 && tecla < 58 || tecla ==0) {// numeros de 0 a 9
		return true;
	}else{
		if (tecla != 8){ // backspace
			return false;
		}else{
			return true;
		}
	}
}

/* inicio Valida Cpf */
function validaCPF(cpf) {
	if (cpf.replace(/^\s*|\s*$/g,"").length == 11) {
		var cpf1 = limpaCPF(cpf);
		if(checaCPF(cpf1)){ return true; }else if(cpf1!=""){ return false; }
	} else {
		return false;
	}
}

function limpaCPF(cpf) {
	l = cpf.length;
	st2 = "";
	for (i = 0; i < l; i++) {
		caracter = cpf.substring(i,i+1);
		if ((parseInt(caracter) >= 0) && (parseInt(caracter) <= 9))
			st2 = st2 + caracter;
	}
	return st2;
}
		
function checaCPF(CPF) {
	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" || CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||	CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" || CPF == "88888888888" || CPF == "99999999999" || CPF == "01234567890")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(10)))
		return false;
	return true;
}
/* fim valida cpf */

/* inicio valida email */
function validaEMail(texto) {
	var msgauxem=false;
	if (texto.length >= 0) {
		if(validate1(texto) == false) {
			msgauxem=true;
			erro=true;
		}
		c=0;
		for(i=0; i<=texto.length;i++) {
			if(texto.substring(i,i+1) == "@") {
				c++;
			}
		}
		if(c!=1) {
			msgauxem=true;
			erro=true;
		}
		if(texto.substring(texto.length-1,texto.length) == "-" || texto.substring(texto.length-1, texto.length) == "_") {
			msgauxem=true;
			erro=true;
		}
		for(i=0;i<=texto.length;i++) {
			if(texto.substring(i,i+2) == "-." || texto.substring(i,i+2) == "_." || texto.substring(i,i+2)== "..") {
				msgauxem=true;
				erro=true;
			}
		}
		for(i=0;i<=texto.length;i++) {
			if(texto.substring(i,i+2) == ".-" || texto.substring(i,i+2) == "._") {
				msgauxem=true;
				erro=true;
			}
		}
		p=texto.indexOf('@');
		if (p<1 || p>(texto.length-6)) {
			msgauxem=true;
			erro=true;
		}
		texto1=texto.substring((p+1),texto.length);
		t=texto1.indexOf('.');
		texto4=texto1.substring(0,t);
		if (t<1 || t>(texto1.length-3)) { //
			msgauxem=true;
			erro=true;
		}
		if(texto1.substring(0,1) == "_" || texto1.substring(0,1) == "-") {
			msgauxem=true;
			erro=true;
		}
		if(texto.substring(0,1)=="_" || texto.substring(0,1) == "-" ) {
			msgauxem=true;
			erro=true;
		}
		texto2=texto.substring(p-1,p);
		if(texto2 == "." || texto2 == "-" || texto2 == "_") {
			msgauxem=true;
			erro=true;
		}
		r=texto.indexOf('.');
		if (r<1) {
			msgauxem=true;
			erro=true;
		}
		texto3=texto.substring(r+1,texto.length);
		u=texto3.indexOf('.');
		if(u>(texto3.length-3)) {
			msgauxem=true;
			erro=true;
		}
	}
	
	if (msgauxem == true) { return false; } else { return true; }
	
}

function validate1(texto) {
	var valid = "abcdefghijklmnopqrstuvxyzwABCDEFGHIJKLMNOPQRSTUVXYZW1234567890-_.@"
				var ok = "yes";
	var temp;
	for (var i=0; i<=texto.length; i++) {
		temp = "" + texto.substring(i, i+1);
		if (valid.indexOf(temp) == "-1")
			ok = "no";
	}
	
	if (ok == "no") {
		return false;
	}
	
	return true;
}

/* fim valida email */


function validarData(str){
	var reDate= /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	
		if (reDate.test(str)) {
			return true;
		} else if (str != null && str != "") {
			return false;
		}else{
			return false;
		}

} // doDate


/* inicio valida form */

function validar(form){
	
	
	for (var i = 0; i < form.elements.length; i++) {
		
		var valide = false;
		if(form.elements[i].alt!="" || form.elements[i].title !=""){
			try{
				var continua = true;
				var campo  = form.elements[i];
				while(continua==true){
					campo =  campo.parentNode;
								
					if(campo.nodeName=="BODY"){
						continua = false;
						valide = true;
					}else{
						if(campo.style.display=="none"){
							valide = false;
							continua = false;
						}else{
							valide = true;
						}
					}
				}
					
			}catch(e){
				//alert(e);
				valide = true;
			}
				
				
				
			if(valide==true){
				if (form.elements[i].type == "text" ) {
					if (form.elements[i].value.trim()=="" ){			
							alert("Preencha o Campo " + form.elements[i].alt + form.elements[i].title);
							form.elements[i].focus();
							return false;
					}else if(form.elements[i].alt.indexOf("CPF")>=0 || form.elements[i].title.indexOf("CPF")>=0){
							
						if(!validaCPF(form.elements[i].value)){
							alert("CPF inválido");
							form.elements[i].focus();
							return false;
						}
		
					}else if(form.elements[i].alt.indexOf("E-mail")>=0 || form.elements[i].title.indexOf("E-mail")>=0){
						if(!validaEMail(form.elements[i].value)){
							alert("E-mail inválido");
							form.elements[i].focus();
							return false;
						}
					}else if(form.elements[i].alt.indexOf("Data")>=0 || form.elements[i].title.indexOf("Data")>=0){
						if(!validarData(form.elements[i].value)){
							alert("O campo "+ form.elements[i].title +" é  inválido");
							form.elements[i].focus();
							return false;
						}
					}
				}else if(form.elements[i].type == "textarea"){
					if (form.elements[i].value=="" ){
						if (form.elements[i].title !=""){
							alert("Preencha o Campo " + form.elements[i].title);
							form.elements[i].focus();
							return false;
						}
					}
				}else if(form.elements[i].type == "select-one"){
					if (form.elements[i].title !=""){
						if(form.elements[i].value ==""){
							alert("Escolha um(a) " + form.elements[i].title);
							form.elements[i].focus();
							return false;
						}
					}
				}else if (form.elements[i].type == "hidden" ) {
					if (form.elements[i].value.trim()=="" ){
							if (form.elements[i].title !=""){
								alert("Preencha o Campo " + form.elements[i].title);
								//form.elements[i].focus();
								return false;
							}
					}
				}
			}
		}
	}
	

	
	if(noSubmit==false){
		form.submit();
	}else{
		return true;	
	}
	
}


/* fim valida form */

function formatar(src, mask, e) {
	if(apenasNumeros(e)==true){
	/*  var i = src.value.length;
	  if(i >0){
		  var saida = mask.substring(0,1);
		  var texto = mask.substring(i)
		   
		   if (texto.substring(0,1) != saida)   {
				src.value += texto.substring(0,1);
		   }
	  }*/
	  aplicaMascara(mask,src)
   }else{
	   return false;
   }
}



function aplicaMascara(Mascara, elemento){
    var elemento = (elemento) ? elemento : document.getElementById(elemento);

    if(!elemento) return false;
    function in_array( oque, onde ){

            for(var i = 0 ; i <onde.length; i++){
            if(oque == onde[i]){
                return true;
            }
        }
        return false;
    }

    // Informa o array com todos os caracteres que podem ser considerados caracteres de mascara
    var SpecialChars = [':', '-', '.', '(',')', '/', ',', '_'];
    var oValue = elemento.value;
    var novo_valor = '';

    for( i = 0 ; i <oValue.length; i++){

        //Recebe o caractere de mascara atual
        var nowMask = Mascara.charAt(i);
        //Recebe o caractere do campo atual
        var nowLetter = oValue.charAt(i);
        //Aplica a masca
        if(in_array(nowMask, SpecialChars) == true && nowLetter != nowMask){
            novo_valor +=  nowMask + '' + nowLetter;
        } else {
            novo_valor += nowLetter;
        }

        // Remove regras duplicadas

        var DuplicatedMasks = nowMask+''+nowMask;

        while (novo_valor.indexOf(DuplicatedMasks)>= 0) {

         novo_valor = novo_valor.replace(DuplicatedMasks, nowMask);

        }

    }

    elemento.value = novo_valor;

}



function formata_moeda(campo_valor,tipo) {
 var ValorEdit='',val04='',val03='',val02='',val01='';
 var valor;

 if(tipo!="direto"){
  	valor = campo_valor.value;
 }else{
	valor = campo_valor;
	alert(valor);
 }
 
 for (var i=0; i <= valor.length; i++) {
	 if (valor.substring(i,i+1) >= "0" && valor.substring(i,i+1) <= "9") {
		 ValorEdit=ValorEdit + valor.substring(i,i+1);
	 }
  }
  
	 if (ValorEdit.length == 9){
		 val01=ValorEdit.substring((ValorEdit.length)-2,ValorEdit.length);
		 val02=ValorEdit.substring((ValorEdit.length)-5,(ValorEdit.length)-2)+',';
		 val03=ValorEdit.substring((ValorEdit.length)-8,(ValorEdit.length)-5)+'.';
		 //val04=ValorEdit.substring((ValorEdit.length)-9,(ValorEdit.length)-8)+'.'; 
		 val04=ValorEdit.substring((ValorEdit.length)-9,(ValorEdit.length)-8); 
	 }
	 if (ValorEdit.length <= 8 && ValorEdit.length >= 6){ 
		 val01=ValorEdit.substring((ValorEdit.length)-2,ValorEdit.length);
		 val02=ValorEdit.substring((ValorEdit.length)-5,(ValorEdit.length)-2)+',';
		 val03=ValorEdit.substring((ValorEdit.length)-8,(ValorEdit.length)-5)+'.'; 
	 }
	 if (ValorEdit.length <= 5 && ValorEdit.length >= 3){
		 val01=ValorEdit.substring((ValorEdit.length)-2,ValorEdit.length);
		 val02=ValorEdit.substring((ValorEdit.length)-5,(ValorEdit.length)-2)+',';
	 }
	 if (ValorEdit.length <= 2){
		 val01=ValorEdit.substring((ValorEdit.length)-2,ValorEdit.length);
	 }
	 
	 if(tipo!="direto"){
		 campo_valor.value=val04+val03+val02+val01;
	 }else{
		 	
		 return (val04+val03+val02+val01);

		
	 }
	 
 }
 
 function fmtMoney(n, c, d, t){
    var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".",
        /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;
    return (x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,
        "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : "");
}
 
 
 function ajaxJs(){
    try {
		 aj = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(e) {
		 try {
			aj = new ActiveXObject("Msxml2.XMLHTTP");
		 } catch(ex) {
			try {
			   aj = new XMLHttpRequest();
			}catch(exc) {
			   alert("Esse browser não tem recursos para uso do Ajax");
			   aj = null;
			}
		 }
		}
		
		return aj;
 }
 

 
 function validar_campo(valor, campo, tabela, campo_retorno, campo_ignorar, valor_ignorar){
	 /* valor = valor a ser comparado 
	 	campo = campo da tabela 
		campo_retorno = campo no corpo html para retorno da msg q ja existe o valor na tabela
		campo_ignorar = ID da tabela para quando for atualizar um registro 
		valor_ignorar
	*/ 
	
	document.getElementById(campo_retorno).innerHTML = "";
	
	if(valor!=""){
		 js = ajaxJs();
		
		 
		 js.open("POST", "inc/validar_campo.php", true);
		 js.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		 
		  js.onreadystatechange = function() {
		  
		  document.getElementById(campo_retorno).innerHTML = "";
		  
			if(js.readyState == 4 ) {
			   if(js.responseXML) {
				  var obj = js.responseXML.getElementsByTagName("valida");
				 
				  if(obj.length > 0){
					  
					  document.getElementById(campo_retorno).innerHTML = "<br>O " + valor +" já está cadastrado em outro registro por favor verifique!!!"   
					 // document.getElementById('Button').disabled =true;
				  }else{
					 // document.getElementById('Button').disabled = false;
					  
				  }
				}else{
				//document.getElementById('Button').disabled = false;
			   }
			   // partes do codigo comentada por causa do IE 
			}
		  }
		
				
		 js.send("valor=" + valor + "&campo=" + campo + "&tabela=" + tabela + "&campo_ignorar=" + campo_ignorar + "&valor_ignorar=" + valor_ignorar);
			
	}
 }
 
 
function carregandoAbrir(){
	if(carregandoAberto==false){
		carregandoAberto = true;
	
		var arrayPageSize = tamanhoDaPagina();
		var arrayPageScroll = posicaoDaPagina();
		//alert(arrayPageSize[0] +" - "+ arrayPageSize[1] +" - "+ arrayPageSize[2] + " - " + arrayPageSize[3]);
		
		var d = document.createElement('div');
		d.setAttribute('id', 'carregando_fundo');
		d.innerHTML = "<iframe frameborder='0' style='filter:alpha(opacity=0);z-index:8;height:"+ arrayPageSize[3] +";width:"+ arrayPageSize[2] +";top:0;left:0;visibility:hidde'></iframe>";
		
		var d2 = document.createElement('div')
		d2.setAttribute('id','carrega_interno');
		d2.innerHTML = "<table width='"+ arrayPageSize[2] +"' height='"+ arrayPageSize[3] +"' border='0' cellpadding='0' cellspacing='0'><tr><td align='center' valign='middle' id='td_carregando'><img src='imagens/loading.gif' /><font face='Verdana' size='2' color='#FFFFFF'><br><br>Aguarde Carregando...</font></td></tr></table>";
	
		
		document.body.appendChild(d);
		document.body.appendChild(d2);
		document.getElementById('carregando_fundo').style.background = "#000000";
		document.getElementById('carregando_fundo').style.width  = arrayPageSize[0] + "px";
		document.getElementById('carregando_fundo').style.height = arrayPageSize[1] + "px";
		document.getElementById('carrega_interno').style.top = (arrayPageScroll[1] + (arrayPageSize[3]/80)) + "px";
	}
	
}

function carregandoRemove(){
	carregandoAberto = false;
	document.getElementsByTagName("body").item(0).removeChild(document.getElementById('carrega_interno'));
	document.getElementsByTagName("body").item(0).removeChild(document.getElementById('carregando_fundo'));
}


function tamanhoDaPagina(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function posicaoDaPagina(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}


/* barra de dados pessoais e eventos */
	
	function postitPosition(){
		/*var tamanho = tamanhoDaPagina();
		var posicao  = posicaoDaPagina();
	
		//document.getElementById('postit').style.background = "#000000";
		//document.getElementById('postit').style.width  = "100%";
		document.getElementById('postit').style.top = ((posicao[1] + tamanho[3])-10)+"px";
		//document.getElementById('eventos').style.height = "50px";
		//
		*/
   
	}
	function postiCreate(){
	/*	
		var div = document.createElement('div');
		div.setAttribute('id', 'postit');
		div.setAttribute('style', 'z-index:9999;');
		
		document.body.appendChild(div);
		document.getElementById('postit').innerHTML = "<img src=http://home.img.uol.com.br/0708/d/amarelinha02.jpg />";

		postitPosition();
	*/
		
	}
	
		
	
	/**/
	
	
function sellAll(campo){
	campo.focus();
	campo.select();
}


function selectALL(id, init, end, value){
	for(i=init;i<end;i++){
		document.getElementById(id+i).checked = value;
	}
}



var tabelas = new Array() 
	function tier1Menu(objMenu,img) {
		
		if (document.getElementById(objMenu).style.display == "none") {

			document.getElementById(objMenu).style.display = "";
			if(img!=""){
				try{
					document.getElementById(img).src = "imagens/menos.jpg";
				}catch(e){
					
				}
			}
		}else {
		
			document.getElementById(objMenu).style.display = "none";
			
			if(img!=""){
				try{
					document.getElementById(img).src = "imagens/mais.jpg";
				}catch(e){
					
				}
			}
			
		}
	}
	
	

function centro(id){
		var div  = document.getElementById(id);
		var pageSize = tamanhoDaPagina();
		
		var div_left = (pageSize[0] - div.style.width.replace("px",""))/2;
		div_left = (div_left *100) / pageSize[0];
		div.style.left = div_left + "%";
			 	
}

