// JavaScript Document

// SELECT HEADER
$(document).ready(function() {
	$('ul.selectAmbev li.item1').click(function() {
		$('ul.selectAmbev li.outrosItens').slideToggle("fast");
	});
	
	$('ul.selectAmbev li.outrosItens').click(function() {
		$('ul.selectAmbev li.outrosItens').slideUp("fast");
	});
	$('ul.selectAmbev li.outrosItens').mouseenter(function() {
		$(this).addClass('active');
	});
	$('ul.selectAmbev li.outrosItens').mouseleave(function() {
		$(this).removeClass('active');
	});
	
});

//  MENU SITE
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);
$(document).ready(function() {
	//$('.divConteinerGeral .divAreaUtil ul.menuSite li a').hover(function() {														 
			//$(this).toggleClass("active");
	//});
	
	$('.menuSite li a')
	  .css( {backgroundPosition: "0 48px"} )
	  
	  .mouseleave(function(){
		 $(this).stop().animate({backgroundPosition:"(0 48px)"}, {duration:200, complete:function(){
		 }}).removeClass('active');
	  })
	  
	  .mouseenter(function(){
						   
		 $(this).stop().animate({backgroundPosition:"(0 0)"}, {duration:200})
		 .addClass('active');
		 
	  })
	  
	  
	  $('.menuSite li a.active').css( {backgroundPosition: "0 48px"} ).mouseenter(function(){
			 $(this).unbind('mouseleave');
	  })
	   

});

// MENU SIDEBAR PUBLICOS
$(document).ready(function() {				   
	$('.divConteinerGeral .divAreaUtil .sidebarPublicos ul.publicoAmbev li a').hover(function() {
		$(this).toggleClass('active');
	});

});

// ESTRELAS VOTAÇÃO
$(document).ready(function() {
	$('.divConteinerGeral .divAreaUtil .divMutimidiaHome .divInfosMultimidia ul.estrelas li').hover(function() {
		$(this).toggleClass("estrelaon");
	});
});


//  MENU FOOTER RECENTES
$(document).ready(function() {
	//$('.divConteinerGeral .divAreaUtil ul.menuSite li a').hover(function() {														 
			//$(this).toggleClass("active");
	//});
	$('.divConteinerGeral .divRecentesHome ul.menuRecentes li a')
	  .css( {backgroundPosition: "0 63px"} )
	  .mouseenter(function(){
		 if ($(this).attr('class') != 'active')
		 {
			 $(this).stop().animate({backgroundPosition:"(0 0)"}, {duration:200})
			 .addClass('active-on');
			 $(this).css('color', 'white');
		 }
	  })
	  .mouseleave(function(){
		 if ($(this).attr('class') != 'active')
		 {
			 $(this).stop().animate({backgroundPosition:"(0 63px)"}, {duration:200, complete:function(){
			 }}).removeClass('active-on');
			 //$(this).css('color', '#929292');
			 $(this).css('color', '#ffffff');
		 }
	  })
	

});

// ACCORDION MENU APOIO
$(document).ready(function() {
	
    $('.divMenuApoio').find('.menuApoio').click(function() {
        $(this).next().slideToggle('fast');
		$(this).toggleClass('active');
		$(this).parent().toggleClass('alturaApoioOn');
    })

});

// ASSUNTOS - TAGS
$(document).ready(function(){
	$(".assuntostags div").hide();
	$(".assuntostags span").click(function(){
	$(this).next("div").slideToggle("fast").siblings("div:visible").slideUp("fast");
	$(this).toggleClass("active");
	$(this).siblings("span").removeClass("active");
	
	});
}); 

// ACCORDION MENU SUPERIOR COM SUBMENU

$(document).ready(function(){
    //$('.divSubItens_a_ambev').hover(function() {$(this).show(); }, function() {$(this).hide('fast'); })
    $('.divSubItens_a_ambev') .mouseenter(function() {$(this).show(); $('.a_ambev a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast');$('.a_ambev a').removeClass("active2");  }) 
    $('.divSubItens_valores_ambientais') .mouseenter(function() {$(this).show(); $('.valores_ambientais a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast'); $('.valores_ambientais a').removeClass("active2"); }) 
    $('.divSubItens_valores_sociais') .mouseenter(function() {$(this).show(); $('.valores_sociais a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast'); $('.valores_sociais a').removeClass("active2"); }) 
    $('.divSubItens_nossas_marcas') .mouseenter(function() {$(this).show(); $('.nossas_marcas a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast'); $('.nossas_marcas a').removeClass("active2"); }) 
    $('.divSubItens_sociedade_da_cerveja') .mouseenter(function() {$(this).show(); $('.sociedade_da_cerveja a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast'); $('.sociedade_da_cerveja a').removeClass("active2"); }) 
    $('.divSubItens_valores_economicos') .mouseenter(function() {$(this).show(); $('.valores_economicos a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast'); $('.valores_economicos a').removeClass("active2"); }) 
    $('.divSubItens_consumo_responsavel') .mouseenter(function() {$(this).show(); $('.consumo_responsavel a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast'); $('.consumo_responsavel a').removeClass("active2"); })
    $('.divSubItens_carnaval2012') .mouseenter(function() {$(this).show(); $('.carnaval2012 a').addClass("active2"); }) .mouseleave(function() {$(this).hide('fast'); $('.carnaval2012 a').removeClass("active2"); })
 
}); 

function openMenu(idItem) {
   $(".divSubItens_" + idItem).show();
}
function closeMenu(idItem) {
    $(".divSubItens_" + idItem).hide();
    $(".linhaItens div").hide();
    $('.menuSite li span').removeClass("active2");
}

/******************************/



// ACCORDION MENU
$(document).ready(function(){
	$(".accordion div").hide();
	$(".accordion span").click(function(){
	$(this).next("div").slideToggle("fast").siblings("div:visible").slideUp("fast");
	$(this).toggleClass("active");
	$(this).siblings("span").removeClass("active");
	//scroll(1,15000);
	
	});
}); 


// ASSUNTOS - TEXTO EXPANSÍVEL
$(document).ready(function(){
	$(".TxtExpansivel div").hide();
	$(".TxtExpansivel span").addClass('active');
	$(".TxtExpansivel span").click(function(){
	$(this).next("div").slideToggle("fast").siblings("div:visible").slideUp("fast");
	$(this).toggleClass("active");
	$(this).siblings("span").removeClass("active");
	
	});
}); 


// NOSSAS MARCAS - TEXTO EXPANSÍVEL
$(document).ready(function(){
	$(".infosProdutos div").hide();
	$(".infosProdutos span").click(function(){
	$(this).next("div").slideToggle("fast").siblings("div:visible").slideUp("fast");
	$(this).toggleClass("active");
	$(this).siblings("span").removeClass("active");
	
	});
});

// IMPRENSA - ACESSORIA IMPRENSA
$(document).ready(function(){
	$(".blocoAcessoria div").hide();
	$(".blocoAcessoria span").click(function(){
	$(this).next("div").slideToggle("fast").siblings("div:visible").slideUp("fast");
	$(this).toggleClass("active");
	$(this).siblings("span").removeClass("active");
	
	});
});



// NOSSAS MARCAS - PRODUTOS - TEXTO EXPANSÍVEL
$(document).ready(function(){
	$(".produtoExpande div").hide();
});


/* 0
funcao que controla a exibicao dos conteudos em lista com controle por setas
------------------------------------------------------------------------------------------------- */

var cont;
function esteira(obj,inicialLength) {
    var esteira = obj;
	
	$(esteira).attr('itLn',inicialLength)
	
    //defino o tamanho da ul de acordo com o numero de lis
    $(obj).find('ul').width($(obj).find('ul').find('li').length * $(obj).find('ul').find('li:first').outerWidth()).attr('itLn',inicialLength + 1)
	

	//desabilito o botao anterior e ativo a 1 listagem
   $(esteira).find('ul:first').addClass('active').end().parent().find('span.anterior').css('visibility', 'hidden');
	 if ($(obj).find('li').length <=inicialLength)
	 	$(obj).next().css('visibility', 'hidden');

    //caso clique no botao proximo
    $('span.proximo').click(function() {
        //habilito o botao esquerdo
        $(this).prev().prev().css('visibility', 'visible');

        if ($(this).prev().find('ul').is(':not(:animated)')) {
            $(this).prev().find('ul').animate({
                marginLeft: '-=' + $(this).prev().find('ul').find('li:first').outerWidth()						  
			})
        }
        
       //caso o tamanho da margin left da ul seja o mesmo que a largura escondo o botao de proximo
        if (($(this).prev().find('ul').css('margin-left') == '-' + (($(this).prev().find('ul').find('li').length - (parseInt($(this).prev().attr('itLn')) + 1)) * $(this).prev().find('ul').find('li:first').outerWidth()) + 'px') || ((($(this).prev().find('ul').find('li').length - (parseInt($(this).prev().attr('itLn')) + 1)) * $(this).prev().find('ul').find('li:first').outerWidth()) + 'px') == '0px')
		    $(this).css('visibility', 'hidden');

    })


    //caso clique no botao anterior
    $('span.anterior').click(function() {
        //habilito o botao esquerdo
        $(this).next().next().css('visibility', 'visible');

        if ($(this).next().find('ul').is(':not(:animated)')) {
            $(this).next().find('ul').animate({
                marginLeft: '+=' + $(this).next().find('ul').find('li:first').outerWidth()						  
			})
		}

		//caso o tamanho da margin left da ul seja o mesmo de 1 objeto li escondo o botao de anterior
        if ($(this).next().find('ul').css('margin-left') == '-' + $(this).next().find('ul').find('li:first').outerWidth() + 'px')
		    $(this).css('visibility', 'hidden');
    })

}



/* 0
funcao que controla a exibicao dos conteudos em lista com controle por setas vertical
------------------------------------------------------------------------------------------------- */

var cont;
function esteiraVertical(obj, inicialLength) {
    var esteiraVertical = obj;

    $(esteiraVertical).attr('itLn', inicialLength)

    //defino o tamanho da ul de acordo com o numero de lis
    $(obj).find('ul').height($(obj).find('ul').find('li').length * $(obj).find('ul').find('li:first').outerHeight()).attr('itLn', inicialLength + 1)


    //desabilito o botao anterior e ativo a 1 listagem
    $(esteiraVertical).find('ul:first').addClass('active').end().parent().find('span.anteriorVertical').css('visibility', 'hidden');
    if ($(obj).find('li').length <= inicialLength)
        $(obj).next().css('visibility', 'hidden');

    //caso clique no botao proximo
    $('span.proximoVertical').click(function() {
        //habilito o botao esquerdo
        $(this).prev().prev().css('visibility', 'visible');

        if ($(this).prev().find('ul').is(':not(:animated)')) {
            $(this).prev().find('ul').animate({
                marginTop: '-=' + $(this).prev().find('ul').find('li:first').outerHeight()
            })
        }

        //caso o tamanho da margin left da ul seja o mesmo que a largura escondo o botao de proximo
        if (($(this).prev().find('ul').css('margin-top') == '-' + (($(this).prev().find('ul').find('li').length - (parseInt($(this).prev().attr('itLn')) + 1)) * $(this).prev().find('ul').find('li:first').outerHeight()) + 'px') || ((($(this).prev().find('ul').find('li').length - (parseInt($(this).prev().attr('itLn')) + 1)) * $(this).prev().find('ul').find('li:first').outerHeight()) + 'px') == '0px')
            $(this).css('visibility', 'hidden');

    })


    //caso clique no botao anterior
    $('span.anteriorVertical').click(function() {
        //habilito o botao esquerdo
        $(this).next().next().css('visibility', 'visible');

        if ($(this).next().find('ul').is(':not(:animated)')) {
            $(this).next().find('ul').animate({
                marginTop: '+=' + $(this).next().find('ul').find('li:first').outerHeight()
            })
        }

        //caso o tamanho da margin left da ul seja o mesmo de 1 objeto li escondo o botao de anterior
        if ($(this).next().find('ul').css('margin-top') == '-' + $(this).next().find('ul').find('li:first').outerHeight() + 'px')
            $(this).css('visibility', 'hidden');
    })

}

//FONT RESIZER
$(document).ready(function(){
$(function(){
		$('span.fontes a').click(function(){
			var ourText = $('p, span');
			var currFontSize = ourText.css('fontSize');
			var finalNum = parseFloat(currFontSize, 10);
			var stringEnding = currFontSize.slice(-2);
			if(this.id == 'aumentar') {
				finalNum *= 1.2;
			}
			else if (this.id == 'diminuir'){
				finalNum /=1.2;
			}
			ourText.css('fontSize', finalNum + stringEnding);
		});
	});

});


// COMPARTILHE MULTIMIDIA
$(document).ready(function() {
	$('.compartilhe').click(function() {
		$(this).toggleClass("active");
		$('ul.lstCompartilhe').slideToggle("fast");
	});
	
	$('ul.lstCompartilhe li').hover(function() {
		$(this).find('span').slideToggle("fast");
	});
	
});

// IMPRENSA ULTIMOS ARQUIVOS
$(document).ready(function() {
    $('ul.menuImprensa li a').click(function() {
        $('ul.menuImprensa li a').removeClass('active');
        $(this).addClass('active');
        
        $('.boxUltimosArquivos div').slideUp();
        $('.boxUltimosArquivos .div_'+$(this).parents().filter('li').attr('class')).slideDown();
    });
});

// MAIS RECENTES HOME E SUBHOMES
$(document).ready(function() {
    $('ul.menuRecentes li a').click(function() {
        $('ul.menuRecentes li a').removeClass('active');
        $(this).addClass('active');
        
        $('.divRecentesHome .carroselFooterHome').hide();
        $('.div_'+$(this).parents().filter('li').attr('class')).show();
    });
});



// TROCA BANNER QUANDO CLICAR
$(document).ready(function() {

    $('.boxEsteiraImagens div').show();
    //$('.boxEsteiraImagens div:first').show();

    // banner superior home
    $('.boxEsteiraImagens div ').fadeOut("slow")
    $('.boxEsteiraImagens div:first').fadeIn("fast")

    $('span.iMotion').addClass('aba_0');
    $('span.iMotion span').hide();
    $('span.iMotion span:first').show();
    // banner superior home


    //DEFINE ID BANNER HOME
    trocaClassBannerHome(0);

    //  TROCA SETA BANNER HOME
    trocaSetaBannerHome();

    $('.boxEsteiraImagens ul li a').click(function() {
        $('.boxEsteiraImagens ul li a').removeClass("active");
        $(this).addClass("active");
        trocaBordaBanner(this,null);
    });
    // });

    $('.boxEsteiraImagens ul li').click(function() {
        var index = $('.boxEsteiraImagens ul li').index(this);

        // Fade do banner maior
        $(".boxEsteiraImagens div").fadeOut("slow")
        $(".boxEsteiraImagens div#oMotion" + index).fadeIn("slow")

        $("#esteiraBoxImagens_" + index + " ul").css('margin-left', 0).parent().next().css('visibility', 'visible');


        // thumbs
        var altura = index * $(this).height();

        $('span.iMotion').animate({ top: altura }, 550);

        $('span.iMotion').removeClass('aba_0').removeClass('aba_1').removeClass('aba_2');

        $('span.iMotion').addClass('aba_' + index);

        $('span.iMotion span').hide();

        $('span.iMotion span.txt_' + index).show();

        esteira("#esteiraBoxImagens_" + index, 3);
    });

    // ESPECIAL PARA A TV DA HOME///
    $('.boxEsteiraImagens ul li a').mouseout(function() { $(this).find('img').fadeTo("slow", 1) });

    // ESPECIAL PARA A TV DA HOME/// 
    $(".boxEsteiraImagens div span ul li").unbind('click');

    esteira("#esteiraBoxImagens_0", 3);

    //CARREGA PRIMEIRA BORDA BANNER
    $('.divConteinerGeral .div_a_ambev span.iMotion').addClass($('.boxEsteiraImagens ul li a').attr('name'));

});


//TROCA BORDA DO BANNER
function trocaBordaBanner(currentValue, p_index) {
    var varMotion = $('.divConteinerGeral .div_a_ambev span.iMotion');

    varMotion.removeClass('a_ambev').removeClass('valores_ambientais')
				    .removeClass('valores_sociais').removeClass('valores_economicos')
				    .removeClass('consumo_responsavel').removeClass('nossas_marcas')
				    .removeClass('sociedade_da_cerveja');

    if (p_index == null) {
       $('.divConteinerGeral .div_a_ambev span.iMotion').addClass($(currentValue).attr('name'));
     }else
     {
        $('.divConteinerGeral .div_a_ambev span.iMotion').addClass($('.divConteinerGeral .div_a_ambev #a_ambev ul.menuHeader').find('li:eq(' + p_index + ')').find('a').attr('name'));
    }
     
 }

//TROCA BANNER DE FORMA ALEATORIA
var index = 0;
var randomValue = 0;
var firstTime = 0;

function giraBanner(index)
{
        // Fade do banner maior
        $(".boxEsteiraImagens div").fadeOut("slow")
        $(".boxEsteiraImagens div#oMotion" + index).fadeIn("slow")

        $("#esteiraBoxImagens_" + index + " ul").css('margin-left', 0).parent().next().css('visibility', 'visible');


        // thumbs
        var altura = index * $('span.iMotion').height();

        $('span.iMotion').animate({ top: altura }, 550);

        $('span.iMotion').removeClass('aba_0').removeClass('aba_1').removeClass('aba_2');

        $('span.iMotion').addClass('aba_' + index);

        $('span.iMotion span').hide();

        $('span.iMotion span.txt_' + index).show();

        esteira("#esteiraBoxImagens_" + index, 3);

        trocaBordaBanner(this,index);
}

//
function randomNumbers(intervaloIni, intervaloFim){
	return (Math.floor(Math.random()*intervaloFim))+intervaloIni
}

// NOSSAS MARCAS INFORMACOES
$(document).ready(function() {
	
	$('.boxEsteiraImagens div').show();
    //$('.boxEsteiraImagens div:first').show();

    // banner superior home
    $('.boxEsteiraImagens div ').fadeOut("slow")
    $('.boxEsteiraImagens div:first').fadeIn("fast")

    $('span.iMotion').addClass('aba_0');
    $('span.iMotion span').hide();
    $('span.iMotion span:first').show();
    // banner superior home


    //DEFINE ID BANNER HOME
    trocaClassBannerHome(0);

    //  TROCA SETA BANNER HOME
    trocaSetaBannerHome();


	setInterval(function() {


		if(firstTime = 0)
		{
			firstTime = 1;
			giraBanner(index);
		}else
		{
			randomValue = randomNumbers(0,3);					
			while(index == randomValue)
			{
				randomValue = randomNumbers(0,3);
			}
			index = randomValue;
			giraBanner(index);
		}

        $('.boxEsteiraImagens ul li a').removeClass("active");
        $(this).addClass("active");
		
	},6600);

    // ESPECIAL PARA A TV DA HOME///
    $('.boxEsteiraImagens ul li a').mouseout(function() { $(this).find('img').fadeTo("slow", 1) });

    // ESPECIAL PARA A TV DA HOME/// 
    $(".boxEsteiraImagens div span ul li").unbind('click');

    esteira("#esteiraBoxImagens_0", 3);

});

//  TROCA SETA BANNER HOME
function trocaSetaBannerHome() {
    var count = 0;

    $('.divConteinerGeral .divAreaUtil #divFlashHome span').click(function() {

        if (!$('.divConteinerGeral .divAreaUtil #divFlashHome ul').is(':animated')) {
            if ($(this).is('.anterior')) {
                count--;
                trocaClassBannerHome(count);
            } else {
                count++;
                trocaClassBannerHome(count);
            }
        }
    });
}

//TROCA CLASS BANNER HOME
function trocaClassBannerHome(count) {
    var lista = $('.divConteinerGeral .divAreaUtil #divFlashHome ul');
    $('.anterior').attr('id', 'prev_' + $(lista).find('li:eq(' + count + ')').find('img:first').attr('class'));
    $('.proximo').attr('id', 'next_' + $(lista).find('li:eq(' + count + ')').find('img:first').attr('class'));
}



// NOSSAS MARCAS SELECIONAR TODOS
$(document).ready(function() {
	$('.selecionar_todosCat a').click(function() {
		if(this.checked == true){
			$("input.cBoxCat[type=checkbox]").each(function() { 
				this.checked = false; 
			});
		} else {
			$("input.cBoxCat[type=checkbox]").each(function() { 
				this.checked = true; 
			});
		}
	});	
	
	
	$('.selecionar_todosPais a').click(function() {
		if(this.checked == true){
			$("input.cBox[type=checkbox]").each(function() { 
				this.checked = false; 
			});
		} else {
			$("input.cBox[type=checkbox]").each(function() { 
				this.checked = true; 
			});
		}
	});	
});

// NOSSAS MARCAS INFORMACOES
$(document).ready(function() {
	$('ul.menuFiltro li a').click(function() {
		$(this).parents().filter('.divFiltro').find('.divPorPais').slideUp();
		$(this).parents().filter('.divFiltro').find('.divAZ').slideUp();
		
		if ($(this).parents().filter('li').attr('class') == 'por_pais')
		{
		    $(this).parents().filter('.divFiltro').find('.divPorPais').slideDown();
		}
		else
		{
		    $(this).parents().filter('.divFiltro').find('.divAZ').slideDown();
        }
        $(this).parents().filter('.menuFiltro').find('.por_pais a').removeClass('active');
	    $(this).parents().filter('.menuFiltro').find('.az a').removeClass('active');
        
        $(this).addClass("active");
	});
});

//Caixa de busca
$(document).ready(function ()
{
    $('#txtBusca').val('Pesquise');
    $('#txtBusca').focus(function(e)
    {
        $('#txtBusca').val('');    
    });
    
    $('#txtBusca').keyup(function(e) {
        if(e.keyCode == 13) {
            Buscar($('#txtBusca').val(), '/pt-br/busca/');
        }
    });
    $('#buscar').click(function(){
        Buscar($('#txtBusca').val(), '/pt-br/busca/');
    });
    
    
    $('#txtBuscaBlog').keyup(function(e) {
        if(e.keyCode == 13) {
            Buscar($('#txtBuscaBlog').val(), '/pt-br/blog-ambev/busca/');
        }
    });
    $('#buscarBlog').click(function(){
        Buscar($('#txtBuscaBlog').val(), '/pt-br/blog-ambev/busca/');
    });
});

function Buscar(valor, url)
{
    if (valor.length == 0)
    {
        alert('Preencha sua busca');
    }
    else
    {
        window.location.href = url + valor;
    }
}

function PerguntaIdade(url) {
    if (getCookie("idade") != null) {
        window.location.href = url;
    } else {
        document.getElementById('idadeDestino').href = url + '&idade=1';
        openModal('.maiorIdade');
    }
}

function abreDhtml(url) {
        openModal('.dhtmlHome');
}


function caixaSucessoErro(sucesso, titulo, texto)
{
    $('.titulo').html(titulo);
    $('.texto').html(texto);
    if (sucesso)
    {
        $('.divErroSucesso img.sucesso').show();
        $('.divErroSucesso img.erro').hide();
    }
    else
    {
        $('.divErroSucesso img.sucesso').hide();
        $('.divErroSucesso img.erro').show();
    }
    openModal('.divErroSucesso');
}

function openModal(id)
{
	
    //Get the screen height and width
	var maskHeight = $(document).height();
	var maskWidth = $(window).width();
	
	//Set heigth and width to mask to fill up the whole screen
	$('#mask').css({'width':maskWidth,'height':maskHeight});
	
	//transition effect		
	$('#mask').fadeIn(1000);	
	$('#mask').fadeTo("slow",0.8);
	
	//Get the window height and width
	var winH = $(window).height();
	var winW = $(window).width();
	
	//Set the popup window to center
	$(id).css('top',  winH/2-$(id).height()/2);
	$(id).css('left', winW/2-$(id).width()/2);
	
	//transition effect
	$(id).fadeIn(2000); 
}

function closeModal()
{
    $('#mask').hide();
    $('.window').hide();
}

// MODAL BOX
$(document).ready(function() {	
	//select all the a tag with name equal to modal
	$('a[name=modal]').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		
		//Get the A tag
		var id = $(this).attr('href');
		openModal(id);
});
	
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		$('.window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			
	
});

$(document).ready(function(){
	if($("#boxes").length != 0) {
		var x_fixo = $("#boxes").offset().top;
		$(window).scroll(function () {
			$("#boxes").animate({
				top: x_fixo+$(document).scrollTop()+"px"
				},{duration:300,queue:false}
			);
		});
	}
});

//Compartilhamento
$(document).ready(function()
{
    $('.compartilheTwitter').click(function(e)
    {
        e.preventDefault();
        window.open("http://twitter.com/share?url=" + $(this).attr('href') + "&text=" +document.title, "twitter", "width=600px, height=350px, status=no, toolbar=no, menubar=no");
    });
    $('.compartilheFacebook').click(function(e)
    {
        e.preventDefault();
        window.open("http://www.facebook.com/share.php?u=" + $(this).attr('href'), "facebook", "width=600px, height=350px, status=no, toolbar=no, menubar=no");
    });
    $('.compartilheGoogle').click(function(e)
    {
        e.preventDefault();
        window.open("https://www.google.com/bookmarks/mark?op=add&bkmk=" + $(this).attr('href') + "&title=" + document.title + "&annotation=", "google");
    });
    $('.compartilheDelicious').click(function(e)
    {
        e.preventDefault();
        window.open("http://www.delicious.com/save?url=" + $(this).attr('href') + "&title=" + document.title, "delicious");
    });
    $('.compartilheOrkut').click(function(e)
    {
        e.preventDefault();
        window.open("http://promote.orkut.com/preview?nt=orkut.com&tt=" + document.title + "&du=http://example.com&cn=" + $(this).attr('href'), "delicious");
    });
});

//  DHTML HOME
//$(document).ready(function() {
	//setTimeout(function () {$('.dhtmlHome').hide("fast");},15000);
	//$('.dhtmlHome .btn_fechar a').click(function () {
			//$('#boxes').hide("fast");
	//});	
//});

function FechaDiv() {
	$('.dhtmlGrande').hide();
}


$(document).ready(function() {
    //  TOOLTIP
    $('li.evento a').hover(function() {
        $(this).next('p.tooltip').show("slow");
        //$(this).next('p.tooltip').slideDown("fast");
    });
    $('li.evento a').mouseleave(function() {
        //$(this).next('p.tooltip').hide;
        $(this).next('p.tooltip').hide("fast");
    });

    //SAC - SELECT FONES
    $('select.selectFones').change(function() {
        $('select.selectFones option').each(function() {
            var option = $(this).attr("selected");
            if (option == true) {
                var optionSelecionado = $(this).attr("value");

                switch (optionSelecionado) {
                    case "antarctica":
                        var imgSrc = "antarctica";
                        var telSac = "0800 725 0003";
                        $('.logoTel').show();
                        $('.logoTel').find('img').attr({ src: "util/img/images/nossas_marcas/logosac/" + imgSrc + ".jpg" });
                        $('.telsac').text(telSac);
                        break;

                    case "brahma":
                        var imgSrc = "brahma";
                        var telSac = "0800 725 0001";
                        $('.logoTel').show();
                        $('.logoTel').find('img').attr({ src: "util/img/images/nossas_marcas/logosac/" + imgSrc + ".jpg" });
                        $('.telsac').text(telSac);
                        break;

                    case "pepsi":
                        var imgSrc = "pepsi";
                        var telSac = "0800 725 0004";
                        $('.logoTel').show();
                        $('.logoTel').find('img').attr({ src: "util/img/images/nossas_marcas/logosac/" + imgSrc + ".jpg" });
                        $('.telsac').text(telSac);
                        break;
                }

            }

        });
    });

    //SAC - Date Calendar
    $.datepicker.regional['pt-BR'] = {
        closeText: 'Fechar',
        prevText: '&#x3c;Anterior',
        nextText: 'Pr&oacute;ximo&#x3e;',
        currentText: 'Hoje',
        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'],
        dayNames: ['Domingo', 'Segunda-feira', 'Ter&ccedil;a-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sabado'],
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
        weekHeader: 'Sm',
        dateFormat: 'dd/mm/yy',
        //dateFormat: dateTimeFormat,
        firstDay: 0,
        isRTL: false,
        showMonthAfterYear: false,
        yearSuffix: ''
    };
    $.datepicker.setDefaults($.datepicker.regional['pt-BR']);

});


//SAC - Funcao Date Calendar
function dataNascCons(cssClass)
{
    //alert('.' + cssClass);
    $(cssClass).datepicker({
        //changeMonth: true,
        changeYear: true,
        minDate: new Date(1930, 1 - 1, 1),
        maxDate: new Date(),
        yearRange: '-80:+0'
    });
}


/*======================================================
//Função comentada por Filipe Henrique. 
//Motivo: houve ajustes na estrutura do SAC do Fale Conosco.

function TrocaLi() {
    $('div.divSac div.sessao ul li').click(function() {
        $('div.divSac div.sessao ul li').removeClass('active');
        $(this).addClass('active');
    });
}

*/
//Função modificada de acordo com a nova estrutura.
/*
$('ul.menuSac li a').click(function() {
    $('ul.menuSac li a').removeClass('active');
    $(this).addClass('active');
});
*/
/*======================================================*/


 //CÓDIGOS PARA MOSTRAR OU ESCONDER OBJETOS
 //=================================================================================================
 function showHidden(idObject, action) {
     if (action == "show") {
         jQuery("#" + idObject).removeClass('hiddenDivBoxFlash');
         jQuery("#" + idObject).addClass('showDivBoxFlash');
     }
     else {
         jQuery("#" + idObject).removeClass('showDivBoxFlash');
         jQuery("#" + idObject).addClass('hiddenDivBoxFlash');
     }
 }
 //=================================================================================================


//CAIXA FLICKR - HOME
//=================================================================================================

 //VARIÁVEIS GLOBAIS
 var fotoGrandeFlickr = '';
 var descriptionFotoGrandeFlickr = '';
 var arrPalavras = new Array();



    function boxFlickr(p_apiKey) {

        //assign your api key equal to a variable
         var apiKey = p_apiKey;
         //var userId = '48504551@N06';
         var userId = '48215814@N04'; //conta ambev

         //the initial json request to flickr
         //to get your latest public photos, use this request: http://api.flickr.com/services/rest/?&;method=flickr.people.getpublicphotos&api_key=' + apikey + '&user_id=29096781@n02&per_page=15&page=2&format=json&jsoncallback=?
         //use another ajax request to get the tags of the image
         $.getJSON('http://api.flickr.com/services/rest/?method=flickr.people.getPublicPhotos&api_key=' + apiKey + '&user_id=' + userId + '&format=json&jsoncallback=?',
            function(data) {
                var html = '';
                var photoURL = '';
                var contentHtml = '';

                $.each(data.photos.photo, function(i, item) {

                    photoURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';

                    $('<li />')
                    .html(
                        $('<a />')
                        .click(function() {
                            carregaFotoFlickr(this);
                        })
                        .attr({
                            id: 'photo_' + item.id,
                            href: 'javascript:void(0);',
                            title: item.title
                        })
                        .html(
                            $('<img />').attr({
                                id: 'img_photo_' + item.id,
                                src: photoURL,
                                //width: '94',
                                //height: '62',
                                alt: item.title
                            })
                        )

                    ).appendTo($('.divConteinerGeral .divAreaUtil .divFlickr .galeriaFlickr .thumbsFlickr #esteiraFlickr ul'));
                });

                carregaFotoFlickr($('.divConteinerGeral .divAreaUtil .divFlickr .galeriaFlickr .thumbsFlickr #esteiraFlickr ul li:first').find('a'));
                esteiraVertical('#esteiraFlickr', 3);
            })
    }
 
 
 // TROCA FOTO PRINCIPAL - FLICKR
 function carregaFotoFlickr(value) {
     var imgGrande = $('.divConteinerGeral .divAreaUtil .divFlickr .galeriaFlickr .imgGrande');

     
     fotoGrandeFlickr = $(value).find('img').attr('src').replace('_m.jpg', '.jpg');
     imgSrc = $(value).find('img').attr('src');
     
    
    getImgSize(imgSrc);
    
    $(imgGrande).find('img').attr({
        src: fotoGrandeFlickr,
        alt: $(value).find('img').attr('alt'),
        width: (curWidth < curHeight) ? ((curHeight / curWidth > 2.5) ? '80' : ((curHeight / curWidth > 1.6) ? '135' : '200')) : '304',
        height: (curWidth < curHeight) ? '240' : '202'
     }).end()
     .find('a').attr({
         href: 'http://www.flickr.com/photos/ambev/' + $(value).attr('id').replace('photo_', ''),
         title: $(value).find('img').attr('alt')
     }).end()
     .find('p').html(
        $('<a />')
        .attr({
            id: $(value).attr('id'),
            href: 'http://www.flickr.com/photos/ambev/' + $(value).attr('id').replace('photo_', ''),
            title: $(value).find('img').attr('alt')
        })).end()
        .find('p').html(
        $('<a />').attr({
            href: 'http://www.flickr.com/photos/ambev/' + $(value).attr('id').replace('photo_', ''),
            onclick: "_gaq.push(['_trackEvent', 'home', 'clique', 'destaque_central_flickr']);"
        }).html($(value).find('img').attr('alt'))
       );

 }

 //=================================================================================================

 var curHeight;
 var curWidth;

//GET IMAGE SIZE OF IMAGE - WIDTH AND HEIGHT
 function getImgSize(imgSrc) {
     var newImg = new Image();
     newImg.src = imgSrc;
     curHeight = newImg.height;
     curWidth = newImg.width;

 }


 //=================================================================================================


//RETORNA COOKIE - PARÂMETRO: NOME DO COOKIE
 function getCookie(name) {
     var nameEQ = name + "=";
     var ca = document.cookie.split(';');
     for (var i = 0; i < ca.length; i++) {
         var c = ca[i];
         while (c.charAt(0) == ' ') c = c.substring(1, c.length);
         if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
     }
     return null;
 }

//SETA COOKIE - PARÂMETROS: 1- NOME DO COOKIE, 2- VALOR, 3- TEMPO DE VIDA (Dias)
 function setCookie(name, value, days) {
     if (days) {
         var date = new Date();
         date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
         var expires = "; expires=" + date.toGMTString();
     }
     else var expires = "";
     document.cookie = name + "=" + value + expires + "; path=/";
 }
 
 
 // BG NATAL
/*$(document).ready(function() {
	var localizacao = window.location.pathname;
	if (localizacao == '/pt-br'){
		$('body').addClass('bgHomeNatal');
	}
});*/
