$j(function(){
	
	$j('#popupF').show().fancybox().trigger('click');
	
/*VAlIDAÇÃO FORMULARIO INDICAÇÃO*/

	$j.validator.messages.required ="";
	$j.validator.messages.email ="";

	$j('#form-indique').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) {
			$j.ajax({
			url:'acoes.php?act=indicacao', type:'post',
			data:$j('#form-indique').serialize(),	
			success:function(response) {
				 if (response == '') {	
					$j.alert({type:'success', html:'E-mail enviado com sucesso!'});
					form.reset();				
				}else { 
					$j.alert({type:'error', html:response});			
				}
			}
		});			
		},
		errorClass: "invalido"
	});
	
	// limpa todas as mensagens de erro dos forms
	jQuery.validator.messages.required = "";
	jQuery.validator.messages.email = "";
	
	$j('#tabs').tabs();
	$j('#menu-twitter a').attr('target', '_blank');
	$j('#gallery li a').lightBox();
	if($j('#popup').html() != null){
		$j('#popup').show();
		var t = setTimeout(removePopUp,30000);
	}
	$j("#cpfcnpjTopo").watermark('CPF/CNPJ', '#666');
	$j("#senhaTopo").watermark('Senha', '#666');
	
	$j('#inscricao-evento').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) {				
			Evento.cadastrar(form);
		},
		errorClass: "invalido"
	});
	
	$j('#f-login-topo').validate({
		ignoreTitle:true,
		messages:{
			cpfcnpj:""
		},
		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) {				
			Clientes.login(form);
		},
		errorClass: "invalido"
	});

	
	/* RECADASTRO NEWS */
	$j('#form_recadastro_news').validate({
		ignoreTitle:true,
		rules:{
			receber:"required",
			'area[]':{
				required:"input[name='receber']:checked",
				minlength: 1
			}
		},
		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) {				
			recadastro();
		},
		errorClass: "invalido"
	});
	
});

/*CADASTRO NEWSLLETER*/
function cadastro_news(){
	$j.ajax({
		url:'acoes.php?act=cadastro_news', type:'post',
		data:$j('#cadastro_news form').serialize(),	
		success:function(response) {
			 if (response == '') {	
				$j.alert({type:'success', html:'registro incluido com sucesso!'});				
			}else { 
				$j.alert({type:'error', html:response});			
			}
		}
	});
}
function recadastro(){
	$j.ajax({
		url:'acoes.php?act=recadastro', type:'post',
		data:$j('#form_recadastro_news').serialize(),	
		success:function(response) {
			 if (response == '') {	
				$j.alert({type:'success', html:'Seu cadastro foi atualizado com sucesso!!!', out:function(){location = "/";}});
			}else { 
				$j.alert({type:'error', html:response});			
			}
		}
	});
}

function removePopUp(){
	if($j('#popup').html() != null){
		$j('#popup').remove();
	}
}

$j(document).ready(function() {
	 
    //Speed of the slideshow
    var speed = 5000;
     
    //You have to specify width and height in #slider CSS properties
    //After that, the following script will set the width and height accordingly
    $j('#mask-gallery, #gallery li').width($j('#slider').width());   
    $j('#gallery').width($j('#slider').width() * $j('#gallery li').length);
    $j('#mask-gallery, #gallery li').height($j('#slider').height());
     
    //Assign a timer, so it will run periodically
    var run = setInterval('newsslider(0)', speed); 
     
    $j('#gallery li:first').addClass('selected');
 
    //Pause the slidershow with clearInterval
    $j('#btn-pause').click(function () {
        clearInterval(run);
        return false;
    });
 
    //Continue the slideshow with setInterval
    $j('#btn-play').click(function () {
        run = setInterval('newsslider(0)', speed); 
        return false;
    });
     
    //Next Slide by calling the function
    $j('#btn-next').click(function () {
        newsslider(0); 
        return false;
    });
 
    //Previous slide by passing prev=1
    $j('#btn-prev').click(function () {
        newsslider(1); 
        return false;
    });
     
    //Mouse over, pause it, on mouse out, resume the slider show
    $j('#slider').hover(
     
        function() {
            clearInterval(run);
        },
        function() {
            run = setInterval('newsslider(0)', speed); 
        }
    ); 
     
});
 
 
function newsslider(prev) {
 
    //Get the current selected item (with selected class), if none was found, get the first item
    var current_image = $j('#gallery li.selected').length ? $j('#gallery li.selected') : $j('#gallery li:first');
     
    //if prev is set to 1 (previous item)
    if (prev) {
         
        //Get previous sibling
        var next_image = (current_image.prev().length) ? current_image.prev() : $j('#gallery li:last');
             
    //if prev is set to 0 (next item)
    } else {
         
        //Get next sibling
        var next_image = (current_image.next().length) ? current_image.next() : $j('#gallery li:first');
    }
 
    //clear the selected class
    $j('#gallery li').removeClass('selected');
     
    //reassign the selected class to current items
    next_image.addClass('selected');
 
    //Scroll the items
    $j('#mask-gallery').scrollTo(next_image, 800);         
     
}
function missao(){
	$j('<div id="dialogMisao" />').load('/lerConteudo.php?conteudo=14').dialog({
		title:'Missão', modal:true, width: '600', height: '200',
		open:function(event, ui){
			$j('.ui-dialog').css("top", "200px");
			var t = setTimeout("$j('.botoes_inferiores').remove()",200);
		},
		beforeClose:function(event, ui){
			$j('#dialogMisao').remove();
		}
	});
}

function Mask_cpfcnpj(obj,evt){
	var tecla = evt.keyCode;
	
	ev = evt || window.event;  
	kCode = ev.keyCode || ev.which;   // gets the keycode in ie or ns
	
    if((ev.ctrlKey && kCode == 65) || (ev.ctrlKey && kCode == 67)|| (ev.ctrlKey && kCode == 86) || (ev.ctrlKey && kCode == 88)|| (ev.ctrlKey && kCode == 90) ||
    		(ev.shiftKey && kCode == 35) || (ev.shiftKey && kCode == 36) || (ev.shiftKey && kCode == 37) || (ev.shiftKey && kCode == 39)
    ){
    	return;
    }
	
	if((tecla > 19 || tecla < 15) && tecla != 9) {
	
		obj.value = obj.value.replace(/[^0-9\.]/g,'') 
	
	    var vr = obj.value;
	    vr = vr.replace( /\//g, "" );
	    vr = vr.replace( /-/g, "" );
	    vr = vr.replace( /\./g, "" );
	    var tam = vr.length;
	
	    if ( tam <= 3 ) {
	            obj.value = vr;
	    }
		
	    if ( (tam > 3) && (tam <= 6) ) {
	            obj.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, tam -3 );
	    }
	    if ( (tam >= 7) && (tam <= 9) ) {
	            obj.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3, 3 ) + '.' + vr.substr( 6, tam - 3 );
	    }
	    if ( (tam >= 10) && (tam <= 12) ) {
	            obj.value = vr.substr( 0, 3 ) + '.' + vr.substr( 3 , 3 ) + '.' + vr.substr( 6, 3 ) + '-' + vr.substr( 9, tam - 2 );
	    }
	    if ( (tam == 12) ) {
	            obj.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5, 3 ) + '/' + vr.substr( 8, tam - 4 );
	    }
	    if ( (tam > 12) && (tam <= 14) ) {
	            obj.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5, 3 ) + '/' + vr.substr( 8, 4 ) + '-' + vr.substr( 12, tam - 2 );
	    }
		if ( tam > 14) {
	            obj.value = vr.substr( 0, 2 ) + '.' + vr.substr( 2, 3 ) + '.' + vr.substr( 5, 3 ) + '/' + vr.substr( 8, 4 ) + '-' + vr.substr( 12, 2 );
	    }
	}
}

function validarCPF(value){
value = jQuery.trim(value);
	
	value = value.replace('.','');
	value = value.replace('.','');
	cpf = value.replace('-','');
	while(cpf.length < 11) cpf = "0"+ cpf;
	var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;
	var a = [];
	var b = new Number;
	var c = 11;
	for (i=0; i<11; i++){
		a[i] = cpf.charAt(i);
		if (i < 9) b += (a[i] * --c);
	}
	if ((x = b % 11) < 2) { a[9] = 0; } else { a[9] = 11-x; }
	b = 0;
	c = 11;
	for (y=0; y<10; y++) b += (a[y] * c--);
	if ((x = b % 11) < 2) { a[10] = 0; } else { a[10] = 11-x; }
	
	var retorno = true;
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]) || cpf.match(expReg)) retorno = false;
	
	return retorno;
}

function validarCNPJ(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;
   }
}

var Evento={
	cadastrar:function(form){
		$j.ajax({
			url:'acoes.php?act=cadastrar_evento', type:'post',
			data:$j('#inscricao-evento').serialize(),	
			success:function(response) {
				 if (response == '') {	
					$j.alert({type:'success', html:'registro incluido com sucesso!'});				
				}else if(response == 1){ 
					$j.alert({type:'error', html:'Você já realizou todas as inscrições disponíves.'});			
				}else if(response == 2){ 
					$j.alert({type:'alert', html:'O Primeiro funcionário já foi inscrito, apenas o segundo funcionário foi inscrito.'});			
				}else if(response == 3){ 
					$j.alert({type:'alert', html:'Você já tinha um funcionário inscrito, apenas o primeiro funcionário foi inscrito.'});			
				}
			}
		});
	}
}
