

   
//-----------------------------------------------------
//Funcao: MascaraMoeda
//Sinopse: Mascara de preenchimento de moeda
//Parametro:
//   objTextBox : Objeto (TextBox)
//   SeparadorMilesimo : Caracter separador de milésimos
//   SeparadorDecimal : Caracter separador de decimais
//   e : Evento

function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, 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 == 13) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.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++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}



 function abrir(pagina, fora) {
	 
	
   // Definindo meio da tela
   //var esquerda = (screen.width - largura)/2;
   //var topo = (screen.height - altura)/2;
	
   //$('#frameSistema').height(altura);
   //$('#frameSistema').width(largura);
   
   // Abre a nova janela
   //window.open(pagina,'frameSistema','height=' + altura + ', width=' + largura + ', top=' + topo + ', left=' + esquerda + ', scrollbars=yes');
 	//window.open(pagina,'', 'scrollbars=yes');
 	
	if(fora == true){
		window.open(pagina)
	}else{
		window.location.href = pagina;
	}
 	//window.location.href=pagina;
 }
 
 
 function abrir_janela(pagina, fora, largura, altura) {
	 
	
		   // Definindo meio da tela
		   var esquerda = (screen.width - largura)/2;
		   var topo = (screen.height - altura)/2;
		
		   
		   // Abre a nova janela
		  //window.open(pagina,'frameSistema','height=' + altura + ', width=' + largura + ', top=' + topo + ', left=' + esquerda + ', scrollbars=yes');
			//window.open(pagina,'', 'scrollbars=yes');
			
			if(fora == true){
				window.open(pagina,'','height=' + altura + ', width=' + largura + ', top=' + topo + ', left=' + esquerda + ', scrollbars=yes');
			}else{
				window.location.href = pagina;
			}
			//window.location.href=pagina;
		 }
		 
		 
		  

function MostraListagemPaginas(pagina_pai) {
	// MOSTRA A LISTAGEM DAS PAGINAS FILHAS DA PAGINA PAI INFORMADA
		busca = valor_busca();
		if($('#paginas_filhas').html() == '<div class="carregando"></div>'){
        	//alert("aguarde o final da pesquisa");
            return false;
        }
		
       
	$.ajax({
		type: 'GET',
    	url: 'paginas.php?acao=pesquisar&busca='+busca+'&pagina_pai='+pagina_pai,
		beforeSend: function(){
						$('#carregando').html('<div class="carregando"></div>');
                        $('#paginas_filhas').html($('#paginas_filhas').html());
						
					},

		success: function(txt) {
			$('#carregando').html('');
			$('#paginas_filhas').html(txt);
			
		},
		error: function() 
		{
			//alert("Problema para executar essa função!");	
		}
	});
	

	return false;
}


	function getEndereco(CEP) 
	{
			if($.trim(CEP) != "")
			{
				$.getScript("http://cep.republicavirtual.com.br/web_cep.php?formato=javascript&cep="+CEP, function(){
			  		if(resultadoCEP["resultado"])
					{
						// troca o valor dos elementos
						$("#endereco").val(unescape(resultadoCEP["tipo_logradouro"])+" "+unescape(resultadoCEP["logradouro"]));
						$("#bairro").val(unescape(resultadoCEP["bairro"]));
						$("#cidade").val(unescape(resultadoCEP["cidade"]));
						$("#uf").val(unescape(resultadoCEP["uf"]));
					}
					else
					{
						alert("Endereço não encontrado");
					}
				});				
			}			
	}

// QUANDO CARREGA A PAGINA
$(document).ready(function() {

			
			<!-- BOTAO SMOOTHNESS -->
			
			if($(".botao").length){
				$(function() {
					$("button, input:submit, a", ".botao").button();
					$("a", ".botao").click(function() { return false; });
				});
			}
				/* EXEMPLO BOTAO (PODE USAR EM LINK
				<div class="botao"> 
					<button>A button element</button>
					<input value="A submit button" type="submit">
					<a href="#">An anchor</a>
				</botao>    */
			
			
			<!-- TAB SMOOTHNESS -->
			
			if($("#tabs").length){
				$(function() {
					$( "#tabs" ).tabs();
				});
			}
			
			
			/* CALENDARIO SMOOTHNESS */
			
			if($(".calendario").length){
				$(function(){
				$(".calendario").datepicker({
					changeMonth: true,
					changeYear: true,
					showOtherMonths: true,
					selectOtherMonths: true,
					//showOn: "button",
					//buttonImage: "../../imagens/icon-date.png",
					//buttonImageOnly: true,
					
					dateFormat: 'dd/mm/yy',
					
					dayNamesMin: [
					'D','S','T','Q','Q','S','S'
					],
					
					monthNamesShort: [
					'Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set',
					'Out','Nov','Dez'
					],
					nextText: 'Próximo',
					prevText: 'Anterior'
					
					});
				
				});
			}
						
			
			/* AUTOCOMPLETE SMOOTHNESS */
			
			if($( "#txtDescricaoProduto" ).length){ 
					$(function() {
						
						$.ajax({
							url: "busca_xml.php?tipo_acao=lista_produtos",
							dataType: "xml",
							success: function( xmlResponse ) {
								var data = $( "dados", xmlResponse ).map(function() {
									return {
										value: $( "titulo", this ).text(),
										id: $( "codigo", this ).text(),
										preco: $( "preco", this ).text(),
										promocao: $( "promocao", this ).text()
									};
								}).get();
								$('#txtDescricaoProduto').autocomplete({
									source: data,
									minLength: 0,
									select: function( event, ui ) {
										$('#txtCodProduto').val(ui.item.id);
										
										preco = ui.item.preco;
										promocao = ui.item.promocao;
									
										valor = retornaMenor(preco,promocao);
										
										$('#txtValor').val(valor);
										
									
										$('#txtQuant').focus() ;
									}
								});
							}
						});
					});
			}


});





function mudaTamanhoLista(col){
	
    	
		var bloco; // IEca
		
		
		bloco = $('.bloco').width();
        //$('#info').html(bloco);
		
		coluna = col; // LARGURA MINIMA DE CADA COLUNA
		
		// CALCULA QUANTOS PROD. POR LINHA
		// arredonda pra menor
		quant = Math.floor(bloco / coluna); 
		porc = 100 / quant;
		
		//$('#info').html(bloco +' ' + quant );
		$('.bloco').find('li').css('width',porc + '%').end();
}






function informa(x, class_tipo) {

		
		if(x == "") {
			$('#informacoes').html("").fadeOut(300);
		
		}else {
			$('#informacoes').html("<span class='"+class_tipo+"'></span>"+x+"").fadeIn(300);
			
		}
}

function zebraListagem(){
		$('#listagem tbody tr:odd').addClass('listagemOut');
		$('#listagem tbody tr:even').addClass('listagemOver');
	}
	


<!-- VALOR PADRAO CAMPO BUSCA-->
	$(function(){
			var $this = $("#busca");
			//$this.val($this.attr("title"));
            
            if ($this.val() == ""){
						$this.val($this.attr("title"));
				}
                
			$this.focus(function(){
						if($this.attr("title") == $this.val()){
							$this.val("");	
						}
			});
			$this.blur(function(){
				if ($this.val() == ""){
						$this.val($this.attr("title"));
				}
			});
	});
	
	function valor_busca(){
		busca = ""
        
		if($("#busca").val() != $("#busca").attr("title")){
			busca = $("#busca").val();
		}	
        
        
		return busca;
	}





function mudaTab(tab, num_tab){
	var $tabs = $(tab).tabs(); // first tab selected
	$tabs.tabs('select', num_tab); // switch to third tab		
}




function getObj(idObj)	
{	// RETORNA UM ELEMENTO 
	return document.getElementById(idObj);
}


function retornaDataHoraAtual(){
	hoje = new Date();
	
	var dia = hoje.getDate();
	var mes = hoje.getMonth()+1;
	ano = hoje.getFullYear();
	var hora = hoje.getHours();
	var minutos = hoje.getMinutes();
	
	
	if(dia < 10) dia = "0" + dia;
	
	if(mes < 10) mes = "0" + mes;
    
    if(horas < 10) horas = "0" + horas;
	if(minutos < 10) minutos = "0" + minutos;
    
	
	datahora = dia + "/" + mes + "/" + ano + ' ' + hora + ':' + minuto;
	
	return datahora;
}


function dataAtual(){
	hoje = new Date();
	
	var dia = hoje.getDate();

	if(dia < 10) dia = "0" + dia;
	
	var mes = hoje.getMonth()+1;
	if(mes < 10) mes = "0" + mes;
	
	ano = hoje.getFullYear();
	data = dia + "/" + mes + "/" + ano;
	
	return data;
}

function dataInicioAtual(){
	hoje = new Date();
	
	var mes = hoje.getMonth()+1;
	if(mes < 10) mes = "0" + mes;
	
	ano = hoje.getFullYear();
	data = '01'+ "/" + mes + "/" + ano;
	
	return data;
}


function horaAtual()
{
	hoje = new Date();
    horas = hoje.getHours();
    minutos =  hoje.getMinutes();
    segundos = hoje.getSeconds();
    
    if(horas < 10) horas = "0" + horas;
	if(minutos < 10) minutos = "0" + minutos;
	if(segundos < 10) segundos = "0" + segundos;
	
    
	hora = horas + ":" + minutos + ":" + segundos;	
	return hora;
}

// FUNCAO QUE COMPLETA A DATA AUTOMATICAMENTE
// PODE SER DIGITADO APENAS O DIA... OU DIA E MES... SEM BARRAS
// UTILIZA A FUNCAO


function completaData(z) {
	x = ApenasNumeros(z.value); // FUNCAO EXTRA
	
	 hoje = new Date();
	
	var dia = hoje.getDate();
	var mes = hoje.getMonth()+1;
	var ano = hoje.getFullYear();

		//alert(dia);
		//alert(mes);
		//alert(ano);
	
	if ((x == 0)) {
		z.value = dia + "/" + mes + "/" + ano;
		
	} else if ((x.length == 3) ) {
		z.value = null;
		
	} else if ((x.length == 1) || (x.length == 2)) {
		z.value = x + "/" + mes + "/" + ano;
		
	} else if((x.length == 4) && (x.indexOf("/") == -1)) {
		var dia = x.substring(0, 2);
		var mes = x.substring(2, 4);
		z.value = dia + "/" + mes + "/" + ano;
		
	} else if((x.length >= 6) && (x.indexOf("/") == -1)) {
		var dia = x.substring(0, 2);
		var mes = x.substring(2, 4);
		var ano = x.substring(4, x.length);
	
		z.value = dia + "/" + mes + "/" + ano;
	}
	
	// FUNCAO EXTRA 
	// VALIDA SE A DATA É VALIDA
	if (ValidaData(z.value) == false){
		z.value = dia + "/" + mes + "/" + ano;
	}
}




function retornaMenor(v1, v2){
	v2 = retornaFloat(v2);
	v1 = retornaFloat(v1);

	return v1 <  v2 || v2 == 0 ? v1 : v2;
	
}
//FORMATA O CAMPO EM FLOAT PARA EFETUAR CONTAS ARITIMETICAS
//


function retornaMoeda(moeda)
{
	if (moeda == ''){
		moeda = 0;
	}
	else{
		
		moeda = moeda.replace(".",",");
	}
		return moeda;
	
}

//FORMATA O CAMPO EM FLOAT PARA EFETUAR CONTAS ARITIMETICAS
//
function retornaFloat(moeda)
{
	if (moeda == ''){
		moeda = 0;
	}
	else{
		
		moeda = moeda.replace(".","");	
		moeda = moeda.replace(",",".");
	}
		return parseFloat(moeda);
	
}

function formatacao(text, mask) {
	// FORMATA CAMPO APOS DIGITAR
	// FUNCIONA COM NUMEROS E LETRAS... 

 	string = text;   // 
 	s = string.length; // quant letras string
	if(s == 0){
		return "";
	}	
	m = mask.length;

	resultado = "";

	k = 0;
	
	for(i = 0; i <= m; i++){
		if(mask.charAt(i) == "#"){
			resultado = resultado + string.charAt(k);
			k++;
		}	
		else{
			resultado = resultado + mask.charAt(i);	
		}
		
	}
	return resultado; // RETORNA TEXTO
}


// FORMATA QUALQUER CAMPO.
// PODE SER DATA, CPF, TELEFONE. UTILIZAR # PARA PERMITIR APENAS NUMEROS OU ! PARA QUALQUER CARACTER OU @ PARA APENAS LETRAS
function formatar(evt, campo, mask) {

 if(document.all) { // Internet Explorer
    key = evt.keyCode; }
    else{ // Nestcape
       key = evt.which;
     }


if (key == 8 || key ==0) {
return true;
}

 string = campo.value;  
 i = string.length;

 if (i < mask.length) {
  if (mask.charAt(i) == '#') {
       return (key > 47 && key < 58);
      } else {
               if (mask.charAt(i) == '!') {  
                     return true;   
               }
               else if (mask.charAt(i) == '@'){
                    return ((key > 64 && key < 91 ) || (key > 96 && key < 123 ) );
               }
               
       
   for (c = i; c < mask.length; c++) {
         if (mask.charAt(c) != '#' && mask.charAt(c) != '!')
         campo.value = campo.value + mask.charAt(c);
      else if (mask.charAt(c) == '!'){
                return true;
       } else {
         return (key > 47 && key < 58);
          }
       }
    }
  } else return false;
}




function listagemFundo(obj,tipo) {

	if(tipo =='out'){
		obj.className = "listagemOut";

	}else if(tipo=='over'){
		obj.className = "listagemOver";
	}
}





// TAB ENTER FUNCIONA QUANDO PRESSIONANDO ENTER PULAR PARA O PROXIMO CAMPO
// FUNCIONA COM INTERNET EXPLORER, FIREFOX, OPERA...
// NAO FUNCIONA COM CHROME POIS ELE ENVIA O FORMULARIO AUTOMATICAMENTE PRESSIONANDO ENTER

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;
};
enterAsTab = function(f, a){
    addEvent(f, "keypress", function(e){
        var l, i, f, j, o = e.target;
        if(e.key == 13 && (a || !/textarea|select/i.test(o.type))){
            for(i = l = (f = o.form.elements).length; f[--i] != o;);
            for(j = i; (j = (j + 1) % l) != i && (!f[j].type || f[j].disabled || f[j].readOnly || f[j].type.toLowerCase() == "hidden"););
            e.preventDefault(), j != i && f[j].focus();
        }
    });
};

// VALIDA TELEFONE
function ValidaTelefone(telefone, requerido){
	if(requerido == false && telefone == ""){
		return true;	
	}
	telefone =ApenasNumeros(telefone);
	if (telefone.length != 10){
		return false;	
	}
	else{
		return true;
	}
}

// VALIDA E-MAIL
function ValidaEmail(email, requerido){
	if(requerido == false && email == ""){
		return true;	
	}
	
	if( email == "" || email.indexOf('@')==-1 || email.indexOf('.')==-1 ){
		return false;
	}
	else{
		return true;	
	}
}

// VALIDA DATA
function ValidaData(dateStr, requerido) {
	if(requerido == false && dateStr == ""){
		return true;	
	}
	
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?
	
	if (matchArray == null) {
		//alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
		return false;
	}
	
	day = matchArray[1]; // p@rse date into variables
	month = matchArray[3];
	year = matchArray[5];
	
	if (month < 1 || month > 12) { // check month range
		//alert("Month must be between 1 and 12.");
		return false;
	}
	
	if (day < 1 || day > 31) {
		//alert("Day must be between 1 and 31.");
		return false;
	}
	if(year < 1900 || year > 2015){
		return false;	
	}
	// verifica meses q tem 31 dias
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		return false;
	}
	
	if (month == 2) { // verificia fevereiro
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day > 29 || (day==29 && !isleap)) {
			//alert("February " + year + " doesn`t have " + day + " days!");
			return false;
		}
	}
	return true; // date is valid
}


//RETORNA APENAS NUMEROS
function ApenasNumeros(v){
    return v.replace(/\D/g,"");
}

function ValidaCPF_CNPJ(n, requerido){
	n = ApenasNumeros(n);
	if (n.length == 14){
		return ValidaCNPJ(n, requerido);	
	}else if(n.length == 11){
		return ValidaCPF(n, requerido);	
	}
	else{
		if( requerido == false && n == ""){
			return true;
		}else{
			return false;	
		}
	}
}

// VALIDA CNPJ
function ValidaCNPJ(cnpj, requerido)
{
	if(requerido == false && cnpj == ""){
		return true;	
	}
	  cnpj = ApenasNumeros(cnpj);
      var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
      digitos_iguais = 1;
      if (cnpj.length < 14 && cnpj.length < 15)
            return false;
      for (i = 0; i < cnpj.length - 1; i++)
            if (cnpj.charAt(i) != cnpj.charAt(i + 1))
                  {
                  digitos_iguais = 0;
                  break;
                  }
      if (!digitos_iguais)
            {
            tamanho = cnpj.length - 2
            numeros = cnpj.substring(0,tamanho);
            digitos = cnpj.substring(tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
                  return false;
            tamanho = tamanho + 1;
            numeros = cnpj.substring(0,tamanho);
            soma = 0;
            pos = tamanho - 7;
            for (i = tamanho; i >= 1; i--)
                  {
                  soma += numeros.charAt(tamanho - i) * pos--;
                  if (pos < 2)
                        pos = 9;
                  }
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1))
                  return false;
            return true;
            }
      else
            return false;
      }

// VALIDA CPF
function ValidaCPF (StrCPF, requerido) {

if(requerido == false && StrCPF == ""){
	return true;	
}

var cpf = ApenasNumeros(StrCPF);
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  //window.alert("CPF inválido. Tente novamente.");
	  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))){
	 //window.alert("CPF inválido. Tente novamente.");
	 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))){
     //window.alert("CPF inválido. Tente novamente.");
	 return false;
   }
   return true;
 }
 


