jQuery.validator.messages.required = "";
jQuery.validator.messages.email = "";

function fecharPopUp(){
	$j('#popupSorteio').hide();
}
$j(function(){
	$j('#form-news').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?cadastra-news', type:'post', data:$j(form).serialize(),
				success:function(response){
					if(response == "" ){
						$j.alert({type:'success', html:'Seu e-mail foi cadastrado com sucesso'});
						form.reset();
					}else{
						$j.alert({type:'alert', html:response});
					}
				}
			});
		},
		errorClass: "invalido"
	});
	$j('#bannerTextos #slider').nivoSlider({
		pauseTime:5000,
		controlNav:false,
		effect:'slideInRight',
		directionNav:false
	});
	$j("#busca").Watermark('Buscar produtos', '#666');
	//$j("#form-news #nome").Watermark('Nome', '#666');
	//$j("#form-news #email").Watermark('E-mail', '#666');
	//$j('.divisor-produtos .floatFrete').width($j('.divisor-produtos dl').width()-20);
	//$j('a[@rel*=lightbox]').lightBox();
	$j('#popupSorteio').show();
	
	setTimeout("fecharPopUp()", 30000);
	
	$j.ajax({
		url:'/bemvindo.php',
		success:function(response){
			//if($j('#bemvindo') != null){
				$j('#bemvindo').html(response);
			//}
		}
	});
	
	/*$j(".divisor-produtos dl dt").hover(function() {
		$j(this).css({'z-index' : '100'});
		var altura = $j(this).find('img').height();
		var largura = $j(this).find('img').width();
		if($j.browser.msie){
			altura = altura+4;
			largura = largura+4;
		}
		$j(this).find('a').addClass("hover").stop()
		.animate({
			width: largura, 
			height: altura
		}, 200);
	} , function() {
		$j(this).css({'z-index' : '0'});
		$j(this).find('a').removeClass("hover").stop()
		.animate({
			width: '180px', 
			height: '180px'
		}, 400);
	});*/
});
var Variacoes={
	setPagina:function(produto, pagina){
		$j.alert({type:'loading', hide:false});
		$j.ajax({
			url:'acoes.php?setPaginaVariacoes&produto='+produto+'&pagina='+pagina,
			success:function(response){
				$j('#variacoes').html(response);
				$j.alert("hide");
			}
		});
	}
};

var Busca={
		
	value:function(obj){
		if(obj.value=="Faça sua busca"){
			obj.value = "";
		}else if(obj.value == ""){
			obj.value="Faça sua busca";
		}
	}
};
function validarCPF(cpf){
	
	cpf = cpf.replace('.','');
	cpf = cpf.replace('.','');
	cpf = cpf.replace('-','');

	erro = new String;
	if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
	var nonNumbers = /\D/;
	
	if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
	
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
		erro += "Numero de CPF invalido!";
	}
	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; }
	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
		erro +="Digito verificador do CPF com problema!";
	}
	if (erro.length > 0){
		return erro;
	}
	return "valido";
}

function validaCNPJ(CNPJ){
	CNPJ = CNPJ. replace (".","");
    CNPJ = CNPJ. replace (".","");
    CNPJ = CNPJ. replace ("-","");
    CNPJ = CNPJ. replace ("/","");
	   
	erro = new String;
	if (CNPJ.length < 14) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";

	//	substituir os caracteres que não são números

	var nonNumbers = /\D/;
   	if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
	var a = [];
	var b = new Number;
	var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	for (i=0; i<12; i++){
		a[i] = CNPJ.charAt(i);
		b += a[i] * c[i+1];
	}
	if ((x = b % 11) < 2) { a[12] = 0; } else { a[12] = 11-x; }
	b = 0;
	for (y=0; y<13; y++) {
		b += (a[y] * c[y]);
	}
	if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
	if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
		erro +="Dígito verificador do CNPJ com problema!";
	}
	if (erro.length > 0){
		return erro;
	}
	return "valido";
}
var Promocao={
	validar:function(form){
		if($Form.validate(form) != false) {
			if($j("#regras:checked").length){
				$j.ajax({
					url:'acoes.php?promocao', type:'post', data:$j(form).serialize(),
					success:function(response){
						if(response == "" || response.length < 2){
							$j('#formPromocao input').val('');
							$j('#formPromocao #regras').attr('checked', false);
							$j.alert({
								type:'success', 
								html:'Seu cadastro em nossa sistema foi realizado com sucesso.<br />Seu ticket para o sorterio foi enviado para seu e-mail.',
								timeout:7000
							});
							_gaq.push(['_trackPageview', '/promo.html'])
						}else{
							$j.alert({type:'alert', html:response});
						}
					}
				});
			}else{
				$j.alert({
					type:'alert', 'html':'Você deve concordar com <strong>Regulamento do Sorteio</strong> para poder se inscrever na promoção.', width:450, timeout:7000
				});
			}
			
		}else{
			$j.alert({
				type:'error', 'html':'Os campos obrigatórios do formulário não foram preenchidos', timeout:7000
			});
		}
		return false;
	}
};

//abrir janela chat
function atendimento_atacado(){
	window.open('http://suporte.feiradastoalhas.com.br/chat.php','','width=590,height=610,left=0,top=0,resizable=yes,menubar=no,location=no,status=yes,scrollbars=yes');
}
