$j(function(){
	
	$j("#emailTopo, #emailNews").watermark('E-mail', '#666');
	$j("#senhaTopo").watermark('Senha', '#666');
	$j("#nomeNews").watermark('Nome', '#666');
	
	// Validação de formulários
	jQuery.validator.messages.required = "";
	jQuery.validator.messages.email = "";
	
	$j('#f_busca').validate({
		ignoreTitle:true,
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? '1 campo obrigatório não foi preenchido!'
					: errors + ' campos obrigatórios não foram preenchidos!';
					
				$j.alert({ type:'error', html:message, width:350 });
			}
		},
		submitHandler: function(form) {				
			Busca.pesquisar($j('#q').val());
		},
		errorClass: "invalido"
	});
		
	Validar.fvalidate('#loginHome, #Login');
	Validar.fvalidate('#FormRecuperarSenha', function(){Clientes.recuperarSenha();});
	
	$j("#FormVerificaEmail").validate({
		rules: {
			confirmaEmail: {
				required: true,
				email: true,
				equalTo: "#emailNovo"
			},
			emailNovo: {
				required: true,
				email: true
			}
		},
		messages: {
			confirmaEmail: {
				required: "E-mail inválido",
				equalTo: "E-mails não são idênticos",
				email: "E-mail inválido"
			},
			email: "E-mail inválido"
		},
		errorClass: "invalido"
	});
	
	
	
	var hoje = new Date();
	
	if(hoje.getDate() > 28){
		var exibeMes = 2;
	}else{
		var exibeMes = 1;
	}
    
	$j("#datepicker").datepicker({clearText: 'Limpar', clearStatus: '',
		closeText: 'Fechar', closeStatus: '',
		prevText: '&lt;Anterior', prevStatus: '',
		nextText: 'Pr&oacute;ximo&gt;', nextStatus: '',
		currentText: 'Hoje', currentStatus: '',
		monthNames: ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho',
		'Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun',
		'Jul','Ago','Set','Out','Nov','Dez'],
		monthStatus: '', yearStatus: '',
		weekHeader: 'Sm', weekStatus: '',
		dayNames: ['Domingo','Segunda-feira','Ter&ccedil;a-feira','Quarta-feira','Quinta-feira','Sexta-feira','Sabado'],
		dayNamesShort: ['Dom','Seg','Ter','Qua','Qui','Sex','Sab'],
		dayNamesMin: ['D','S','T','Q','Q','S','S'],
		dayStatus: 'DD', dateStatus: 'D, M d',
		dateFormat: 'yy/mm/dd', firstDay: 0, 
		initStatus: '', isRTL: false,
		onSelect: function(dateText, inst) {
			location = '/index.php?Agenda-de-Obrigacoes&cpt=6&data='+dateText;
		},
		beforeShowDay  : desabilitarAlgunsDias,
		numberOfMonths: exibeMes
	});
	
	
	function desabilitarAlgunsDias(date) {
		
		mstr = date.getMonth()+1;
		dstr = date.getDate();
		var m = mstr.toString().length == 1 ? '0'+(date.getMonth()+1) : date.getMonth()+1;
		var d = dstr.toString().length == 1 ? '0'+date.getDate() : date.getDate();  // date.getDate();
		var y = date.getFullYear();

		/*if ( inArray( y+'-'+(m)+'-'+d, datasCalendario)) {
			return [true];
		}*/

		for(var i=0; i<datasCalendario.length; i++){
			if(y+'-'+(m)+'-'+d == datasCalendario[i]){
				return [true];
			}
		}

		return [false];
	}
    
	function inArray (x, matriz){
        var txt = "¬" + matriz.join("¬") + "¬";
        var er = new RegExp ("¬" + x + "¬", "gim");
        return ( (txt.match (er)) ? true : false );
	}

    

	//Verifica se o objeto $Form existe
	if(typeof $Form != "object"){
		include('/cms/estrutura/js/tipos.js');
		include('/cms/estrutura/js/jquery/personal/jquery.fvalidator.js');
		include('/cms/estrutura/js/jquery/plugins/jquery.maskedinput.js');
		include('/cms/estrutura/js/jquery/personal/jquery.formasks.js');
	}
});

var Busca = {
	pesquisar:function(pesquisa){
		location = 'busca.php?Busca&pagina='+pagina+'&q='+pesquisa;
	}
};

//função que verifica se o objeto $Form existe caso não encontre inclui os arquivos necessários
function include(file){
       $j.ajax({
		url:file,
		success:function(response){
			$j('body').append('<script>'+response+'<\/script>');
		}
   });
}
function formata_moeda(num){
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num)) 
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 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));
    return (((sign) ? '' : '-') + num + ',' + cents);
}

var Validar = {
	fvalidate:function(form, fn) {

		$j(form).validate({
			messages:{
				email:"e-mail inválido"
			},
			invalidHandler: function(e, validator) {
				var errors = validator.numberOfInvalids();
				if (errors) {
					var message = errors == 1
						? '1 campo obrigatório não foi preenchido!'
						: errors + ' campos obrigatórios não foram preenchidos!';
						
					$j.alert({ type:'error', html:message, width:350 });
				}
			},
			submitHandler: function(form) {				
				if(typeof(fn) !='undefined' ) {
					fn();	
				} else {
					form.submit();
				}
			},
			errorClass: "invalido"
		});
	}
};
function validaCNPJ(cnpj){
	cnpj = jQuery.trim(cnpj);
	
	// DEIXA APENAS OS NÚMEROS
   cnpj = cnpj.replace('/','');
   cnpj = cnpj.replace('.','');
   cnpj = cnpj.replace('.','');
   cnpj = cnpj.replace('-','');

   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;
   }
}
