$(document).ready(function(){
    
    // Poster de Cinema
	//$('<span class="topo"></span><span class="esq"></span><span class="dir"></span><span class="fundo"></span><span class="pipoca"></span>').insertAfter('.poster');
	//$('<span class="sombra"></span> <span class="brilho"></span>').appendTo('.poster a.filme');
		
	$('.poster a.filme').hover(function(){
		$('.poster span.brilho')
		.stop()
		.animate({
			top: '-40px'
		}, 200);
	}, function() {
		$('.poster span.brilho')
		.stop()
		.animate({
			top: '-50px'
		}, 200);
	});
	
	// Carrossel Cinema Home //
	$('.anterior').addClass('disabled');
	$(function() {
		var step = 1;
		var current = 0;
		var maximum = $('.poster ul li').size();
		var visible = 1;
		var speed = 400;
		var liSize = 227;
		var carousel_height = $('.poster ul').children().height();
 
		var ulSize = liSize * maximum;
		var divSize = liSize * visible;
 
		$('.poster ul').css("width", ulSize+"px").css("left", -(current * liSize)).css("position", "absolute");
		$('.poster').css("width", divSize+"px").css("height", carousel_height+45+"px").css("visibility", "visible").css("overflow", "hidden").css("position", "absolute");
        $('.carrossel').css("height", carousel_height+45+"px");
		
		// Avança para próximo
		$('.proximo').click(function() {
            $('.enviaAmigo').fadeOut(200);
			$('.anterior').removeClass('disabled');
			if(current + step == maximum - step) { $(this).addClass('disabled'); }
			if(current + step < 0 || current + step > maximum - visible) { return; }
			else {
				current = current + step;
				$('.poster ul').animate({left: -(liSize * current)}, speed, null);
				$('.poster ul li h3, .poster ul li span.horario, .poster ul li a.ingressos, .poster ul li dl')
				.stop()
				.animate ({
					opacity:0
				}, 0)
				.delay(400)
				.animate ({
					opacity:1
				}, 200);
			}
			return false;
		});
		
		// Recua para o anterior
		$('.anterior').click(function() {
            $('.enviaAmigo').fadeOut(200);
			$('.proximo').removeClass('disabled');
			if(current - step == 0) { $(this).addClass('disabled'); }
			if(current - step < 0 || current - step > maximum - visible) { return; }
			else {
				current = current - step;
				$('.poster ul').animate({left: -(liSize * current)}, speed, null);
				$('.poster ul li h3, .poster ul li span.horario, .poster ul li a.ingressos, .poster ul li dl')
				.stop()
				.animate ({
					opacity:0
				}, 0)
				.delay(400)
				.animate ({
					opacity:1
				}, 200);
			}
			return false;
		});
	});
    
    // Exibe carrossel após carregar a página
    $(window).load(function(){
        $('.loader').hide();
        $('.secoes .colDir .carrossel').css({visibility: 'visible'});
    });

    // Alinhamento Vertical //
	(function ($) {
		$.fn.vAlign = function() {
			return this.each(function(i){
				var ah = $(this).height();
				var ph = $(this).parent().height();
				var mh = Math.ceil((ph-ah) / 2);
				$(this).css('margin-top', mh);
			});
		};
	})(jQuery);
    $(window).load(function(){
	    $('.valign').vAlign();
    });
	
    // Inputs de texto //
	$('input[type=text], textarea').each(function() {
		var valor = this.value;
		$(this).focus(function() {
			if(this.value == valor) {
				this.value = '';
			}
		});
		$(this).blur(function() {
			if(this.value == '') {
				this.value = valor;
			}
		});
	});
	
	// Box de Acesso Rápido da Busca //

	//$('.busca input').each(function(){
    	//$(this).focus(function(){
    	//	$(this).parents().next('.acessoRapido').fadeIn(200);
    	//});
    	//$('.busca input').blur(function(){
    	//	$(this).parents().next('.acessoRapido').fadeOut(200);
    	//});
    //});
	
	// Links de Atalhos Rodapé //
	$('<span></span>').appendTo('.atalhos ul li a, .boxLinks ul li a');
	$('.atalhos ul li a span, .boxLinks ul li a span').animate({opacity:0}, 0);
	$('.atalhos ul li a').hover(
	function(){
		$('.atalhos ul li a span').stop().animate({opacity: 0.6}, 100);
		$(this).children('span').stop().animate({opacity: 0}, 100);
	}, function(){
		$('.atalhos ul li a span').stop().animate({opacity: 0}, 100);
	});
    $('.boxLinks ul li a').hover(
	function(){
        $('.boxLinks ul li a span').stop().animate({opacity: 0.6}, 100);
		$(this).children('span').stop().animate({opacity: 0}, 100);
	}, function(){
        $('.boxLinks ul li a span').stop().animate({opacity: 0}, 100);
	});
	
	// Compartilhar com amigos //
	$('.enviaAmigo span.erro').hide();

	// exibe modal
     var id;
	$('a.mail').click (function(){
	     id = $(this).attr('id');
          if(id == 0){
               $('.enviaAmigo').fadeIn(200);
          }else{
               $('amigo_'+id).fadeIn(200);
          }
		return false;
	});

	// fecha modal
    $('html').click(function() {
        $('.enviaAmigo').fadeOut(200);
    });
    
    $('.enviaAmigo').click(function(event){
        event.stopPropagation();
    });
     
	$('.enviaAmigo a.fechar').click(function(){
	    $('.enviaAmigo').fadeOut(200);
		return false;
	});

	// exibe mensagem de sucesso no envio
	//$('.enviaAmigo input[type=submit]').click(function() {
     //     $('.enviaAmigo form').hide();
     //     $('.enviaAmigo .enviado').show();
     //     setTimeout (function(){
     //          $('.enviaAmigo').fadeOut();
     //     }, 3000);
	//	return false;
	//});

    // Legenda de localização no mapa
    var link ='';
    
    $('.mapa .locais span.marcMenor').hide();
    
    $('.mapa .outros ul li a')
        .click(false)
        .hover(
        function(){
            link = $(this).attr('href');
            var t = setTimeout(function(){
                $('.mapa .locais span.'+link).fadeIn('fast');
            }, 200);
            $(this).data('timeout', t);
        }, function() {
            clearTimeout($(this).data('timeout'));
            $('.mapa .locais span.'+link).fadeOut('fast');
        }
    );
    
    // Legenda mapa CCT
    $('.cultura #estabelecimentos ul li div').hide();
    
    $('.cultura #estabelecimentos ul li').hover(
        function(){
            $(this).find('div').stop(true).delay(500).fadeTo('fast', 1);
        }, function() {
            $(this).find('div').stop(true).fadeOut('fast');
        }
    );
    
    // Hover Galeria Fotos CCT
    $('<span></span>').appendTo('#galeria ul li a').hide();
    
    $('#galeria ul li a').hover(
        function(){
            $(this).children('span').fadeIn('fast');
        }, function(){
            $(this).children('span').fadeOut('fast');
        }
    );
    
    // Listagem de Filmes em Cartaz
    $('<div class="hr"><hr /></div>').insertAfter('#colEsq .cinema .moldura:nth-child(4n)');
    $('#colEsq .cinema .moldura:nth-child(5n+1)').css({'paddingLeft':'0'});
    
    // Horário de Filmes   
    $('.horarios dl').height(function(){
         var alturaPai = $(this).parents('.horarios').height();
         $(this).css({
             height: alturaPai - 10
         });
    });
    
    // Accordion de Preços do Cinema
    $('.precos ul li a.hoje').next('div').css({'display':'block'});
    
    $('.precos ul li a').click(function() {
        if($(this).is('.ativo, .hoje')) {
            $(this).removeClass().next('div').slideUp('fast');
        } else {
            $('.precos ul li a').removeClass();
            $('.precos ul li div').slideUp('fast');
            $(this).addClass('ativo').next('div').fadeIn('fast');
        }
        return false;
    });
    
    // Paginação
    var largura = 0;
    $('.navPaginacao li').each(function() {
        largura += $(this).outerWidth( true );
    });
    $('.navPaginacao').css('width', largura);
    
    // Lista de Mais Novidades
    $('.maisNovidades ul li:last-child').css({'background':'none'});
    
    // Box de Links
    $('.boxLinks ul li:last-child').css({'padding':'0'});
    
    // Abas Sobre o Shopping
    $('.sobreShopping .abas li:last-child').css({'padding':'0'});
    
    // Lista de Locação
    $('#locacao .esq ul li:last-child').css({'background':'none'});
    
    // Mensagem de erro formulários
    $('form span.erro').hide();

    /** FUNÇÕES BUSCA REFINADA **/
    //Redireciona para página interna
    $('#selLojas').change(function(){
          if($(this).val() != '0'){
               if($('#segmento').val() != 'todas'){
                    $(window.location).attr('href', $('#path').val()+$('#segmento').val()+'/'+$(this).val());
               }else{
                    $(window.location).attr('href', $('#path').val()+$(this).val());
               }
          }
    });

    //Redireciona para página de busca
    $('#selAreas').change(function(){
          if($(this).val() != '0'){
               var i = 0;
               //var busca = $('#txtBusca').val();
               var busca = 'Encontrar-uma-loja';
               while(i < busca.length){
                    busca = busca.replace(' ','-');
                    i++;
               }
               $(window.location).attr('href', $('#path').val()+'busca/'+$('#segmento').val()+'/'+$(this).val()+'/'+busca);
          }
    });

    $('.acessoRapido').hide();
    //Busca palavra-chave
    $('#txtBusca').bind('keyup', function() {
          if($(this).val().length == 0) {
               $('#listaAcessoRapido').fadeOut(); //Hide the suggestions box
          }else{
               var str = limpaCaracteres($(this).val());
               $.ajax({
          	     type: "get",
          		url: $('#path').val()+"selDados/buscaLojas/"+$('#id_segmento').val()+"/"+str+"/"+$('#interna').val(),
          		success: function(retorno) {
          		     $('#listaAcessoRapido').fadeIn(); //Show the suggestions box
                         $('#listaAcessoRapido').html(retorno); //Fill the suggestions box
          		}, error: function() { /* alert('erro'); */ }
          	});
          }
    });

    //Busca palavra-chave Cabeçalho
    $('#txtBuscaCab').bind('keyup', function() {
          if($(this).val().length == 0) {
               $('#acessoRapido').fadeOut(); //Hide the suggestions box
          }else{
               var str = limpaCaracteres($(this).val());
               $.ajax({
          	     type: "get",
          		url: $('#path').val()+"selDados/buscaLojasCab/0/"+str+"/"+$('#interna').val(),
          		success: function(retorno) {
          		     $('#acessoRapido').fadeIn(); //Show the suggestions box
                         $('#acessoRapido').html(retorno); //Fill the suggestions box
          		}, error: function() { /*alert('erro'); */ }
          	});
          }
    });
});

function ValidaFormBusca(Form){
     if($('#txtBusca').val() == ''){
          return false;
     }
}

function ValidaFormBuscaCab(Form){
     if($('#txtBuscaCab').val() == ''){
          return false;
     }
}

function ValidaForm(Form){
     $('span.erro').hide();
     $('#erroEmail').hide();
     if($('#txtNome').val() == ''){
          $('#erroNome').show();
          return false;
     }

     if($('#txtSobrenome').val() == ''){
          $('#erroSobrenome').show();
          return false;
     }

     if($('#txtEmail').val() == ''){
          $('#erroEmail2').show();
          return false;
     }

     if($('#txtCidade').val() == ''){
          $('#erroCidade').show();
          return false;
     }

     if($('#txtEstado').val() == '0'){
          $('#erroEstado').show();
          return false;
     }

     if($('#txtAno').val() == ''){
          $('#erroNascimento').show();
          return false;
     }

     if(emailvalidation($('#txtEmail').val())){
          $('#msgCadastro').hide();
          $('#formCadastro').hide();
          $('div.msgmSucesso').show();
     }else{
          return false;
     }

}

function emailvalidation(field) {
     var goodEmail = field.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\.info)|(\.sex)|(\.biz)|(\.aero)|(\.coop)|(\.museum)|(\.name)|(\.pro)|(\..{2,2}))$)\b/gi);
     apos=field.indexOf("@");
     dotpos=field.lastIndexOf(".");
     lastpos=field.length-1;
     var badEmail = (apos<1 || dotpos-apos<2 || lastpos-dotpos<2)
     if (goodEmail && !badEmail) {
          return true;
     }else{
          $('#erroEmail').show();
          return false;
   }
}

function limpaCaracteres(str){
     str = str.replace(" ", "-");
     str = str.replace('"', "");
     str = str.replace("'", "");
     var acento = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ';
     var semacento = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC';
     var nova='';

     for (i = 0; i < str.length; i++) {
          if (acento.search(str.substr(i, 1)) >= 0) {
               nova += semacento.substr(acento.search(str.substr(i, 1)), 1);
          }else {
               nova += str.substr(i, 1);
          }
     }
     return nova;
}
