var _defaultPlayerMessage = 'Você precisa do <a href="http://get.adobe.com/br/flashplayer/">Flash Player</a> para ouvir as músicas.';


$(function(){
    
	// inits globais
	$('.more-details, h1.title,	h2.subtitle, h3.header-blurb').hide();
    $('#menu-perfil a').html('conheça <span>perfil</span>');
    $('#menu-repertorio a').html('ouça <span>repertório</span>');
    $('#menu-homenagem a').html('surpreenda <span>homenagem</span>');
    $('#menu-evento a').html('realize <span>eventos</span>');
    $('#menu-contato a').html('como <span>contratar</span>');
    //-----------------------------------------------------------------------------------------------
    
    
	// string html da popup de boas-vindas
	var wPopup = '<div id="welcome-popup">';
	wPopup += '<div class="content-holder">';
	wPopup += '<h3 onclick="javascript:hideWelcomePopup();">Olá! Seja bem-vindo(a).</h3>';
	wPopup += '<p>Gostaria de obter informações <span style="text-decoration: underline;">detalhadas</span> sobre os nossos serviços?</p>';
	wPopup += '<a rel="nofollow" href="/servicos" class="yes-now">Sim, mostre-me agora!</a>';
	wPopup += '</div>';
	wPopup += '</div>';
	
	$('body').append(wPopup);
	//-----------------------------------------------------------------------------------------------
	

	// controla a tabela com o repertorio (usado somente na tela de repertorio)
	$('.repertoire-table td').hover(
        function(){
            $(this).addClass('active');
        },
        function(){
            if(!$(this).hasClass('on')) $(this).removeClass('active');
        }
    );
	//-----------------------------------------------------------------------------------------------
	
	// controla o hover nos menus principais
	$('#main-menu-pt ul.menu li, #main-menu-pt ul.menu li').hover(function(){
		if(!$(this).hasClass('active')) 
		{
			$(this).addClass('active hover');
		}
	}, function(){
		if($(this).hasClass('hover')) 
		{
			$(this).removeClass('active hover');
		}
	});
	
	
	//-----------------------------------------------------------------------------------------------
	
	// hover nos botoes de flores e cestas, na pagina de homenagem ao vivo
	$('#flowers-btn, #baskets-btn').hover(function(){
		$(this).stop().fadeTo('fast', 0.7);
	}, function(){
		$(this).stop().fadeTo('slow', 1);
	});
	
	
	// controla os cliques nos h3 q listam os tipos de eventos disponiveis
	var eventTypes = $('#event-types');
	
	if(eventTypes.length)
	{
		var blurbs = eventTypes.find('p.info');
		
		blurbs
		.hide()
		.css({
			paddingLeft: 12
		});
		
		var topics = eventTypes.find('h3.topic');
		
		topics.each(function(){			
			$(this)
			.click(function(){
				blurbs.fadeOut();
				
				$(this).nextAll().each(function(){
					if($(this).filter('h3.topic').length)
					{
						return false;
					}
					$(this).fadeIn();
				});
				
				$(this).addClass('active');
			})
			.hover(function(){	
				
				$(this).stop().fadeTo('fast', 0.7);
				
				
			}, function(){
				
				$(this).stop().fadeTo('fast', 1);			
				
			});
		})
		.css({cursor: 'pointer', color: '#fff', fontWeight: 'bold', margin: '0 0 10px 0', clear: 'both'});
	}
	//-----------------------------------------------------------------------------------------------
	
	
    // funcao usada nas paginas de cestas e flores, para (re)posicionar os numeros sobrepostos em cada imagem (thumb)
	$(window)
	.resize(function(){
		positionThumbNumbers();
	});
	// aguarda 1 segundo antes de posicionar a primeira vez
	setTimeout(positionThumbNumbers, 1000);
	//-----------------------------------------------------------------------------------------------
	
	
	// controla o efeito de mouse over nas miniaturas
	var thumbs = $('.thumb, .about-thumb');
	
	thumbs.hover(function(){
		$(this).find('img').stop().fadeTo('slow', 0.5);
	}, function(){
		$(this).find('img').stop().fadeTo('slow', 1);
	});
	//-----------------------------------------------------------------------------------------------
	
	
	// inicia os ads
    controlAds();
    //-----------------------------------------------------------------------------------------------
    
    
    // setup nos controladores dos ads (links com numeros)
    setupAdsBars();
    setupAdsLinks();
    //-----------------------------------------------------------------------------------------------
       
    
    // mostra a popup de boas-vindas (perguntando se o usuario deseja conhecer os servicos oferecidos)
    setTimeout(showWelcomePopup, 1000);
    //-----------------------------------------------------------------------------------------------
    
    
    // setup dos drawers (usados em diversas paginas)
    setupDrawers();
    setupSpecialDrawers();
    //-----------------------------------------------------------------------------------------------
    
    
    // inicializa o player (usado somente na pagina do repertorio)
    var playerBox = $('.player-box');
    playerBox.find('.loading.pt').append('Aguarde um momento...');
    playerBox.find('.loading.en').append('Loading song...');
    
    playerBox.find('a.stop.pt').append('Parar');
    playerBox.find('a.reload.pt').append('Ouvir novamente');
    
    playerBox.find('a.stop.en').append('Stop');
    playerBox.find('a.reload.en').append('Play again');
    
    
    //ie6: mostra a tela de sugestao de atualizacao de navegador
    if($.browser.msie && parseInt($.browser.version) < 7)
    {
    	$(window).load(function(){
    		showUpdateYourBrowserBox();
    	});
    }
    //-----------------------------------------------------------------------------------------------
    
    
    // inicializacao do shadowbox (componente jquery para galerias de imagens, videos e outros conteudos)
    try
    {
		Shadowbox.init({
		animSequence: "sync",
		skipSetup: false
		});
    }
    catch(e){}
    //-----------------------------------------------------------------------------------------------
});


function positionThumbNumbers()
{
	var t = $('#thumb-1, #thumb-2, #thumb-3, #thumb-4, #thumb-5, #thumb-6, #thumb-7');
	
	t.each(function(){
		
		var i = $(this).attr('id').substr(6);
		
		var container = $('#thumb-number-' + i);
		var target = $('#thumb-' + i);
		
		if(!container.length)
		{
			$('body').append('<div style="position: absolute;top: 0; left: 0;font-size: 19px; text-align: center;color: #fff; width: 20px; height: 20px;" id="thumb-number-' + i + '">0' + i + '</div>');
			container = $('#thumb-number-' + i);

		}		

		container.css({left: (target.position().left + (target.width() / 2)), top: (target.position().top + 97) });
		
	});
}


function closePlayer()
{
    var player = $('#player-container');
    player.empty().html(_defaultPlayerMessage);
    
    var target = $('.song-' + _currentSongId);
    target
        .removeClass('on')
        .find('.player-box').slideUp();
};

/*
function setBreadcrumb(data)
{
	$(function(){
		
		var html = '';
		
		for(var i = 0; i < data.length; i++)
		{
			html += '<img src="/images/breadcrumb-indicator.png" class="png-fix"> ';
			
			if(data[i][1])
			{
				html += '<a href="' + data[i][1] + '" rel="nofollow">';
				html += data[i][0];
				html += '</a>';
			}
			else{
				html += data[i][0];
			}
			
			html += '<img src="/images/blank.gif" height="1" width="15">';
		}
		
		$('#breadcrumbs div').html(html);
	});
}*/


_currentSongId = null;
function initPlayer(file, id)
{
    _currentSongId = id;
    
    var html;
    var s1 = new SWFObject("/flash/player.swf","ply","175","25","9","#000");
    s1.addParam("flashvars","file=/songs/" + file + '.mp3&autostart=true');
    s1.write("player-container");
    
    var target = $('.song-' + id);
    
    
    allPlayerBoxes = $('.player-box');
    allPlayerBoxes.slideUp();
    allPlayerBoxes.find('.loading').hide();
    
    $('td.on')
        .removeClass('on')
        .removeClass('active');
        
    target.addClass('on');
    
    // player box
    var playerBox = $('.player-box', target);
    
    if(playerBox.data('init') !== true)
    {
	    playerBox.find('a.stop').unbind('click').click(function(){        
	        closePlayer();            
	        return false;
	    });
	    
	    playerBox.find('a.reload')
	    .unbind('click')
	    .click(function(){
	        initPlayer(file, id);           
	        return false;
	    });
	    
	    playerBox.data('init', true);
	}

    try{pageTracker._trackPageview('/' + file);}catch(e){}

    playerBox.slideDown();
    playerBox.find('.loading').slideDown();
    
    setTimeout("$('.song-' + _currentSongId + ' .player-box .loading').slideUp()", 4000);
    
    return false;
};

function range( min, max ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Leslie Hoare
    // +   bugfixed by: Onno Marsman
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
};

function hideWelcomePopup()
{
    $('#welcome-popup').fadeOut();
};

function showWelcomePopup(force)
{
    if(force === true || $.cookie('FIRSTTIMER') != '1')
    {
        $.cookie('FIRSTTIMER', '1', { expires: 365 });
        var popup = $('#welcome-popup');
        popup.css({
            top: popup.height() * -1,
            left: ($(window).width() - popup.width() - 50)
        })
        .show();
        
        popup.animate({top: 0}, 1500);
        
        setTimeout(hideWelcomePopup, 35000);
    }
};

function showUpdateYourBrowserBox()
{
	var html = '<div id="update-your-browser">';
	html += '<ul>';
	
	html += '<li title="Atualize seu navegador" style="margin: 3px 0pt 0pt; float: left; font-family: Arial,Helvetica,sans-serif; font-style: normal; font-variant: normal; font-weight: bold; font-size: 16px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; color: rgb(102, 102, 102);">Atualize seu navegador</li>';
	html += '<li title="Segurança para você, liberdade aos desenvolvedores" style="margin: 3px 100px 0pt 8px; float: left; font-family: Arial,Helvetica,sans-serif; font-style: normal; font-variant: normal; font-weight: normal; font-size: 9px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none;">Você está usando um navegador antigo e<br/>com falhas de segurança</li>';
	
	html += '<li style="margin: 0pt 0pt 0pt 10px; float: right;">';
	html += '<a title="Fechar" style="margin: 7px 0pt 0pt; background: transparent url(/images/sprite-update-browser.png) no-repeat scroll 0px -41px; display: block; width: 14px; height: 14px; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; text-indent: -9999px;" href="#" onclick="$(\'#update-your-browser\').fadeOut();return false;">Fechar</a>';
	html += '</li>';
	
	html += '<li style="float: right; margin-left: 10px;"><a title="Saiba mais sobre esta campanha" style="margin: 4px 0pt 0pt; padding: 4px; display: block; font-variant: normal; font-weight: bold; font-size: 9px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none; text-decoration: none; color: rgb(102, 102, 102);" href="http://imasters.uol.com.br/crossbrowser/pt-br/" target="_blank">Por que atualizar?</a></li>';
	
	html += '<li style="padding: 2px 0pt 0pt; float: left; font-weight: bold; color: rgb(102, 153, 0);"><small style="font-variant: normal; font-weight: normal; font-size: 10px; line-height: normal; font-size-adjust: none; font-stretch: normal; -x-system-font: none;">Baixe agora!</small></li>';
	html += '<li class="logo" style="margin: 0"><a style="margin: 0pt 0pt 0pt 12px; background: transparent url(http://imasters.uol.com.br/crossbrowser/img/sprBarratopo.png) no-repeat scroll -62px -5px; display: block; width: 26px; height: 26px; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; text-indent: -9999px;" title="Mozilla Firefox" href="http://www.mozilla.com/" target="_blank">Mozilla Firefox</a></li>';
	html += '<li class="logo"><a style="width: 19px; height: 19px;background-position: -125px -8px;" title="Google Chrome" href="http://www.google.com/chrome" target="_blank">Google Chrome</a></li>';
	html += '<li class="logo"><a style="background-position: -96px -9px; width: 19px; height: 19px;" title="Apple Safari" href="http://www.apple.com/safari/download/" target="_blank">Safari</a></li>';
	html += '<li class="logo"><a style="background-position: -151px -8px; width: 22px; height: 18px;" title="Opera" href="http://www.opera.com/download/" target="_blank">Opera</a></li>';
	html += '<li class="logo"><a style="background-position: -180px -7px; width: 21px; height: 20px;" title="Internet Explorer 8" href="http://www.microsoft.com/windows/internet-explorer/" target="_blank">Internet Explorer</a></li>';
	
	html += '</ul></div>';

	$('body').append(html);
	
	$('#update-your-browser').animate({top: 0}, 1500);
}



var _currentAd;
var _adsInterval;
function controlAds()
{
    var ads = $('.ads');
    ads.hide();
    
    var totalAds = ads.length;
    
    if(!ads.data('firstTimer'))
    {
        ads.data('firstTimer',true);
        _adsInterval = setInterval(controlAds, 8000);
        _currentAd = range(1, totalAds);
    }
    else
    {
        _currentAd = _currentAd < totalAds ? (_currentAd + 1) : 1;
    }

    $('.ad-' + _currentAd).fadeIn();
    activeAdLink(_currentAd);
    
    $('.ads-bar').fadeIn();
};

function manualShowAd(who)
{
    if(_adsInterval) clearInterval(_adsInterval);
    
    var ads = $('.ads');
    ads.hide();
    
    ads.data('firstTimer', false);
    
    $('.ad-' + who).fadeIn();
    activeAdLink(who);
};

function activeAdLink(who)
{
    $('.ads-bar li').removeClass('active');
    $('.ads-bar li.ad-link-' + who).addClass('active');
};

function setupAdsBars()
{
    $('.ads-bar li').click(function(){
        manualShowAd( parseInt($(this).text()) );
    });
    
    $('.ads').hover(function(){
    	$('h3, h5, h6', $(this)).css({color: '#fff'});
    }, function(){
    	$('h3, h5, h6', $(this)).css({color: '#939393'});
    });
};

function setupAdsLinks()
{
    $('.ad-1').click(function(){
        showFullAd(1, $(this).hasClass('en'));
    });
    
    $('.ad-2').click(function(){
        showFullAd(2, $(this).hasClass('en'));
    });
    
    $('.ad-3').click(function(){
        showFullAd(3, $(this).hasClass('en'));
    });
    
    $('.ad-4').click(function(){
        showFullAd(4, $(this).hasClass('en'));
    });
    
    $('.ad-1, .ad-2, .ad-3, .ad-4, .ad-5').css({cursor: 'pointer'});
};


function showFullAd(who, english)
{
	switch(who)
	{
		/*case 5:
		location.href = english ? 'hire-saxophonist-in-brazil' : '/contratar-saxofonista';
		break;*/		
		case 4:
		location.href = english ? 'hire-saxophonist-in-brazil' : '/contratar-saxofonista';
		break;
		
		case 3:
		location.href = '/cestas';
		break;

		case 2:
		location.href = '/homenagem-ao-vivo-com-sax';
		break;
		
		case 1:
		location.href = '/sax-para-evento';
		break;
	}		
};


/**
  * accordeon controller 
  */
function _setupDrawers()
{
    _clearDrawerInterval();
            
    // hide all the drawer contents and set him as closed
    var drawer = $('.accordeon p:visible');
    drawer
        .fadeTo(300, 0.1)
        .slideUp()
        //.prev().removeClass('open')
        //.parent().removeClass('open');
    
    // general actions
    _activeDrawerObj
        //.addClass('open')
        .find('p')
        .fadeTo(300, 1)
        .slideDown()
        //.parent().addClass('open');
};

function _clearDrawerInterval()
{
    if(_drawerInterval) clearInterval(_drawerInterval);
};

var _activeDrawerObj, _activeDrawerId, _drawerInterval;
function setupDrawers()
{
    $('.accordeon')
        .mouseover(function () {
            // cancel handling if event box is already open
            if($(this).find('p').is(':visible') || $(this).attr('id') == _activeDrawerId) return;
            
            _activeDrawerObj = $(this);
            _clearDrawerInterval();        
            _drawerInterval = setInterval(_setupDrawers,300);        
        })
        .mouseout(function(){
            _clearDrawerInterval();
        })
        .find('a').hover(function(){
        	$(this).parent().find('span').show();
        }, function(){
        	$(this).parent().find('span').hide();
        });
};

/**
  * special drawers
  */
function _setupSpecialDrawers()
{
    _clearSpecialDrawerInterval();
            
    // hide all the drawer contents and set him as closed
    var drawer = $('.special-drawer .drawer-content:visible');
    drawer
        .slideUp()
        .prev().removeClass('open');
    
    // general actions
    _activeSpecialDrawerObj
        .find('.drawer-content').slideDown()
        .prev().addClass('open');
};

function _clearSpecialDrawerInterval()
{
    if(_specialDrawerInterval) clearInterval(_specialDrawerInterval);
};

var _activeSpecialDrawerObj, _activeSpecialDrawerId, _specialDrawerInterval;
function setupSpecialDrawers()
{
    $('.special-drawer li')
        .click(function () {
            // cancel handling if event box is already open
            if($(this).find('.drawer-content').is(':visible') || $(this).attr('id') == _activeDrawerId) _clearSpecialDrawerInterval();
            
            _activeSpecialDrawerObj = $(this);
            _clearSpecialDrawerInterval();        
            _specialDrawerInterval = setInterval(_setupSpecialDrawers,300);
            
            return false;        
        })
};
