// JavaScript Document
$(document).ready(function()
{
	var link_site = 'http://www.brasita.com.br/';
	
	//autocomplete - início
	$('#inputString').keyup(function() { 
		autocompletar($(this).val());
	});
	
	$('#inputString').click(function() { 
		autocompletar($(this).val());
	});
	
	$('#inputStringBlog').keyup(function() { 
		autocompletarBlog($(this).val());
	});
	
	$('#inputStringBlog').click(function() { 
		autocompletarBlog($(this).val());
	});
	
	$('*').click(function(){ 
		$('#suggestions').hide();
	});	
	
	function autocompletar(valor){
		var inputString =  valor;
		
		 if(inputString.length == 0){
	        // Hide the suggestion box.
	        $('#suggestions').hide();
	    }else {
	        $.post(link_site + "ajax/Completar/completar_busca.php", {queryString: ""+inputString+""}, function(data){
	        	$('#suggestions').hide();
	            if(data.length > 0){	            		            	
	                $('#suggestions').show();	               
	                $('#autoSuggestionsList').html(data);
	            }
	        });
	    }
	}
	
	function autocompletarBlog(valor){
		var inputStringBlog =  valor;
		
		 if(inputStringBlog.length == 0){
	        // Hide the suggestion box.
	        $('#suggestions').hide();
	    }else {
	        $.post(link_site + "ajax/Completar/completar_busca_blog.php", {queryString: ""+inputStringBlog+""}, function(data){
	        	$('#suggestions').hide();
	            if(data.length > 0){	            		            	
	                $('#suggestions').show();	               
	                $('#autoSuggestionsList').html(data);
	            }
	        });
	    }
	}
	//autocompletar - fim
	
	/** 
	 * Função para checar a resolução do usuário
	 */
	checkWindowSize(); //checa qndo abre a pag
	$(window).resize(checkWindowSize); //checa qndo o usuario redimensiona 
	
	function checkWindowSize() {
        if ($(window).width() >= 1024 ) {
            $('#left-efect').show();
            $('#right-efect').show();
        }
        else{
            $('#left-efect').hide();
            $('#right-efect').hide();
        }
        if($(window).height() <= 768){
        	$('.pg-home').css('padding-top','2%');
        }
        if($(window).height() > 768){
        	$('.pg-home').css('padding-top','4%');
        }
        if($(window).height() >= 1024){
        	$('.pg-home').css('padding-top','5%');
        }
	}

	//amplia imagens na página de fotos
	$(".mini-galeria a").click(function(){	
		$(".galeria-grande").html();
		var imagem = $(this).attr('href');

		$(".galeria-grande").html('<img src="' + imagem + '" title="" alt="" />');
		
		return false;
	}); 
	
	//ampliar imagem
	$("ul.thumb li div").hover(function() {
			$(this).css({'z-index' : '10'});
			$(this).find('img').addClass("hover").stop()
				.animate({
					marginTop: '-10px', 
					marginLeft: '-25px', 
					top: '50%', 
					left: '50%', 
					width: '150px', 
					height: '105px',
					padding: '0' 
				}, 200);
			
			} , function() {
			$(this).css({'z-index' : '0'});
			$(this).find('img').removeClass("hover").stop()
				.animate({
					marginTop: '0', 
					marginLeft: '0',
					/*top: '5px', 
					left: '5px', */
					width: '114px', 
					height: '85px'
					/*padding: '5px'*/
				}, 400);
		});
   
  //Tipo o valor default dos campos input
	$('.inputdefault').focus(function() {	
		if (this.value == this.defaultValue){ 
	    	this.value = '';
		}
		if(this.value != this.defaultValue){
			this.select();
		}
	});
	$('.inputdefault').blur(function() {
		if ($.trim(this.value) == ''){
	    	this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});

	
	/*var zIndexNumber = 1000;
	$('div').each(function() {
		$(this).css('zIndex', zIndexNumber);
		zIndexNumber -= 10;
	});*/
	
	//linka a div no menu principal
	$(".borda-men div").click(function(){	
		var link = $(this).next('a').attr('href');
		window.location = link;
	});
	
	//abre o box de listagem de estabelecimentos comercias (onde encontrar)
	$(".ul-cidades li div a").click(function(){	
		$('.box-lojas').addClass('carregando');
		
		//abre o box de escolha do tipo de estabelecimento
		$('.ul-opt-onde').show();
		$('.opt-sel').removeClass('opt-sel');
		$('#tipo_loja').addClass('opt-sel');
		
		var cidade = $(this).attr('href');
		
		$('.cid-sel').removeClass('cid-sel');
		$(this).parents('li').addClass('cid-sel');
		
		$('.carrega-lojas').load(link_site + 'ajax/lojas.php?cidade=' + cidade, function() {
			$('.box-lojas').removeClass('carregando');
		});
		
		return false;
	});
	
	//alterna entre loja e representante (onde encontrar)
	$(".ul-opt-onde ul li a").click(function(){	
		$('.box-lojas').addClass('carregando');
		
		var estab = $(this).attr('href');
		var cidade = $('.cid-sel div a').attr('href');
		
		$('.opt-sel').removeClass('opt-sel');
		$(this).parent('li').addClass('opt-sel');
		
		$('.carrega-lojas').load(link_site + 'ajax/lojas.php?cidade=' + cidade + '&estab=' + estab, function() {
			$('.box-lojas').removeClass('carregando');
		});
		
		return false;
	});
	
	//amplia imagens na página de produtos
	$(".tam-thumb a").click(function(){	
		$(".img-view").html();
		var imagem = $(this).attr('href');
		$(".img-view").html('<img src="' + imagem + '" title="" alt="" width="950" height="440" />');
		/*$(".img-view img").attr("src",load_image);
		
		$(".img-view img").attr("src",imagem);*/
		$('.thumbs-prod div').removeClass("thumb-sel");
		$(this).parents('.img-thumb').addClass("thumb-sel");
		return false;
	});
	
	/** Troca de input contato **/
	//campos de formulário de contato
	$('.field-contato').focus(function() {
		$(this).addClass('field-contato-hover');
	});
	$('.field-contato').blur(function() {
		$(this).removeClass('field-contato-hover');
	});
	
	/** Realiza validação de Campos **/
	//coloca a mascara nos campos numericos
	
	//funcao para verificar se o campo é digito
	function validaDigito(e){
						if((e.which!= '8' && e.which!='0') && (e.which<'48' || e.which>'57'))
						return false;
							}
	
	$("#celular").mask("(99)9999-9999");
	$("#telefone").mask("(99)9999-9999");
	$("#cnpj").mask("99.999.999/9999-99");
	$("#cep").mask("99999-999");
	$("#valor").maskMoney({symbol:"R$",decimal:".",thousands:""});
	$("#data").mask("99/99/9999");
	$("#hora").mask("99:99:99");
	$("#cpf").mask("999.999.999-99");
	
	///função para validar e-mail
	function checkMail(mail)
	{
    	var er = new RegExp(/^[A-Za-z0-9_\-\.]+@[A-Za-z0-9_\-\.]{2,}\.[A-Za-z0-9]{2,}(\.[A-Za-z0-9])?/);
    	if(typeof(mail) == "string")
    	{
        	if(er.test(mail)) 
        		return true;
    	}
    	else if(typeof(mail) == "object")
    	{
        	if(er.test(mail.value))
        	{
                return true;
            }
    	}
    	else
       	 	return false;      
	};
	
	//Aceita apenas número
	$("#numero_festa").keypress(function(e) 
		{  
		return validaDigito(e);
		});

	// CADASTRO EM NEWSLETTER
	$("#voltar-promo").click(function()
	{
		$('.conf-promocoes').hide();
		$('.promocoes').show();
		$("#msg-promo").hide();
		$("#msg-ant").show();
		$("#frase2-cad").hide();
	});
	
	//FORMULÁRIO CADASTRO NEWSLETTER
	$("#frmPromocao").submit(function()
	{		
			
		if(!$("#nome-news").val() || $("#nome-news").val() == 'Nome')
		{
			alert("Por favor informe seu nome");
			$("#nome-news").focus();
			return false;
		}
					
		if(!$("#email-news").val() || $("#email-news").val() == 'E-mail')
		{
			alert("Por favor informe seu e-mail");
			$("#email-news").focus();
			return false;
		}
		
		if(!checkMail($("#email-news").val()))
		{
			alert("E-mail inválido");
			$("#email-news").focus();
			return false;
		}
		
		var nome = $("#nome-news",this).val();
		var email = $("#email-news",this).val();

		$("#msg-nome").text(nome);
		
		$.post(link_site + "AjaxRequest/CadPromocoes/cad_promocao.php",
		{
			nome: nome,
			email: email
		},
		function()
			{ 
				$("#nome-news").val('Nome');
				$("#email-news").val('E-mail');

				$('#news').hide();
				$('.conf-promocoes').show(); 			
			})
					
		return false;

	});
	$("#voltar-promo").click(function()
	{
		$('#news').show();
		$('.conf-promocoes').hide();
	});
	//FIM CADASTRO NEWSLETTER
	
	/**
	* Script para validação de formulário
	* A classe do formulário deve ser validateForm
	* 
	* - Para msg de erro em div deve ser colocado um atributo rel no formulário com o nome da id da div
	* - Para msg de erro em alert de ser colocado um atributo rel em branco no formulário
	* - Os campos que são obrigatórios devem ter a classe required e o title com a mensagem de erro
	*
	**/
	$('.validateForm').submit(function(){
		
		var campo = $(this).attr('class').replace("validateForm ","");
		
	    if(!makeValidate(campo)){
	    	return false;
	    }
	    else{
	    	return true;
	    }
	});
	
	//amplia imagens na página de fotos
	$(".imagem-mini a").click(function(){	
		$(".imagem-grande").html();
		var imagem = $(this).attr('href');

		$(".imagem-grande").html('<img src="' + imagem + '" title="" alt="" />');
		
		return false;
	});
	
	function makeValidate(campo){
		var erro = 0;
		var title = '';
		
		if(campo != "validateForm"){
			$('.required').each(function(){	 
				if($(this).attr('id') == 'email'){
					if(!checkMail($(this).val())){
						$(this).focus();
			            title = $(this).attr('title');
			            $("#" + campo).show('fast');
						$("#" + campo).text(title);
			            erro = 1;
			            return false;
			        }	
				}
				else{
					if(!$(this).val()){
						$(this).focus();
			            title = $(this).attr('title');
			            $("#" + campo).show('fast');
						$("#" + campo).text(title);
			            erro = 1;
			            return false;
			        }	
				}
		    });
		}
		else{
			$('.required').each(function(){	 
				if($(this).attr('id') == 'email'){
					if(!checkMail($(this).val())){
			            $(this).focus();
						title = $(this).attr('title');
			            alert(title);
			            erro = 1;
			            return false;
			        }	
				}
				else{
					if(!$(this).val()){
			            $(this).focus();
						title = $(this).attr('title');
			            alert(title);
			            erro = 1;
			            return false;
			        }	
				}
		    });
		}
		
	    if(erro == 0)
	    	return true;
	}
	
	//Chama Colorbox
	$("a[rel='gallery']").colorbox();
	
	$(".video").colorbox({iframe:true, innerWidth:640, innerHeight:390});
	
	//newsletter
	$(".newsletter-box").colorbox({iframe:true,innerWidth:510, innerHeight:305});
	
	//newsletter
	$(".img-news").colorbox({iframe:true,innerWidth:530, innerHeight:430});
});

function Limpa(ObjId)
{
	ObjId.value = '';
}
