/**
 * TikiCMS
 * Copyright (C) 2009, Tiki Web Inteligente Ltda.
 * @requires jQuery 1.3.2 or latter
 *
 * $Id: application.js 295 2010-11-29 18:15:34Z leandro $
 */

// define o namespace da aplicação
Application = {
    Controller: {}
};

/**
 * Retorna uma URL completa dado um caminho relativo.
 *
 * É importante que esta função seja definida antes
 * da definição das biliotecas "thickbox" e "sIFR",
 * pois alterei o código-fonte delas para que caminhos
 * relativos sejam convertidos em caminhos absolutos utilizando
 * esta função.
 *
 * @param  string url Um pedaço de URL (caminho relativo dentro do servidor)
 * @return string     Uma URL completa
 */
Application.build_url = function(url) {

    if (!Application.BASE_URL || !Application.BASE_URL.match(/^http/)) {
        Application.BASE_URL = $('meta[name=base_url]').attr('content');
    }

    return Application.BASE_URL + url; 
}

jQuery(document).ready(function($) {
    // invoca o controlador e o método solicitados
    var controller = $('meta[name=controller]').attr('content');
    var method = $('meta[name=method]').attr('content');
    var camelizedController = $.map(controller.split('_'), function(val) { return val.substr(0,1).toUpperCase() + val.substr(1) } ).join('');

    Application.Controller[camelizedController] &&
    Application.Controller[camelizedController][method] &&
    Application.Controller[camelizedController][method].call();

    // Abre links com o rel external em novas janelas
    $("a[rel~='external']").click(function(){
        window.open($(this).attr('href'));
        return false;
    });

    // posição relativa de cada link dentro do menu
    window.menuPositions = {
        bt_home: { left: '0' },
        bt_estudio: { left: '40px' },
        bt_portfolio: { left: '238px' },
        bt_clientes: { left: '435px' },
        bt_contato: { left: '626px' }
    };

    // página atualmente sendo exibida
    window.currentPage = $('#current_page').text();

    // velocidade da animação de posicionamento do cursor
    var speed = 200;

    // verificando se está vindo de uma página referência
    var nova_url = window.location.href.split('#');
    
    if (nova_url[1]) {
    	
    	var page = nova_url[1].replace("/", "");
    	
    	currentPage = page;
    	
    	$('.menu_current').show().css('opacity','1').stop(true, false).animate({ left : menuPositions['bt_'+page].left }, speed);
    	
        setTimeout(function() {
            $('#content').load(Application.build_url(page+'.html'), function(){
                $('#content').fadeIn(speed);
                $('#bg img.'+page).fadeIn(speed);

                $("a[rel=lightbox]").fancybox({
                    transitionIn: 'fade',
                    transitionOut: 'fade',
                    titlePosition: 'inside',
                    titleFormat: function(title, currentArray, currentIndex, currentOpts) {
                        return '<span id="fancybox-title-outside">' + (title.length ? ' &nbsp; ' + title : '') + '</span>';
                    }
                });
            });
        }, speed);    	
    	
    }    
    
    // controle o movimento do cursor
    $('.menu a').hover(function() {

        var linkId = $(this).attr('id');

        $('.menu_current').show().css('opacity','1').stop(true, false).animate({ left : menuPositions[linkId].left }, speed);
    }, function(e) {

        // reposiciona o indicador se estamos em uma página interna
        if (currentPage != 'home') {
            $('.menu_current').stop(true, false).animate({ left : menuPositions["bt_"+currentPage].left }, speed);
        }
    });

    // esconde o indicador quando algum link do menu perde o foco (e estamos na página home)
    $('.menu').mouseleave(function(e) {

        if (currentPage == 'home') {
            $('.menu_current').stop(true, false).fadeOut(speed);
            setTimeout(function(){
                $('.menu_current').css('left', '0');
            }, speed);
        }
        
    });
    
    // Troca de paginas com ajax e fade
    $('.menu a, .logo_quiz a').click(function(){
        var $link = $(this);
        var page = $(this).attr('class').replace(/^bt_/, '');
        var speed = 500;

        
        
        // evita que o blur() em $('.menu a') coloque o indicador em -9999px
        currentPage = page;

        // após clicar em "Home" o indicador deve sumir
        if (page == 'home') {
            $('.menu_current').stop(true, false).hide().css('left', '0');
        }
        
        $('#content').fadeOut(speed);
        $('#bg img').fadeOut(speed);
        setTimeout(function() {
            $('#content').load(Application.build_url(page+'.html'), function(){
                $('#content').fadeIn(speed);
                $('#bg img.'+page).fadeIn(speed);

                $("a[rel=lightbox]").fancybox({
                    transitionIn: 'fade',
                    transitionOut: 'fade',
                    titlePosition: 'inside',
                    titleFormat: function(title, currentArray, currentIndex, currentOpts) {
                        return '<span id="fancybox-title-outside">' + (title.length ? ' &nbsp; ' + title : '') + '</span>';
                    }
                });
            });
        }, speed);
    });
    
    // Troca automatica do background
    /*
    $('#bg img').load(function(){
        $(this).addClass('loaded');
    });
    function troca_bg() {
        if( $('#bg img:nth-child(1)').is('.loaded') ) {
            var speed = 500;
            $('#bg img:first-child').fadeOut(speed).detach().appendTo('#bg');
            $('#bg img:first-child').fadeIn(speed);
        }
    }
    
    troca_bg_intervalo = setInterval(troca_bg, 8000);
    */
    
    
    // Twitter na home
    $("#twitter").getTwitter({
        userName: "quizcomunicacao",
        numTweets: 2,
        loaderText: "Carregando tweets...",
        slideIn: false,
        showHeading: false,
        headingText: "Últimos Tweets",
        showProfileLink: false
    });
    

    // invoca a lightbox
    $(function(){
            
        $("a[rel=lightbox]").fancybox({
            transitionIn: 'fade',
            transitionOut: 'fade',
            titlePosition: 'inside',
            titleFormat: function(title, currentArray, currentIndex, currentOpts) {
                return '<span id="fancybox-title-outside">' + (title.length ? ' &nbsp; ' + title : '') + '</span>';
            }
        });

    });
    
    
    //scroll
    /*
    $('html, body').animate({
        scrollTop: $("#home").offset().top
    }, 'fast');
    
    $('html, body').animate({
        scrollTop: $("#estudio").offset().top
    }, 'fast');
    
    $('html, body').animate({
        scrollTop: $("#portfolio").offset().top
    }, 'fast');
    
    $('html, body').animate({
        scrollTop: $("#clientes").offset().top
    }, 'fast');
    
    $('html, body').animate({
        scrollTop: $("#contato").offset().top
    }, 'fast');
    */

    /*
    // background 100%
    // You need to specify the size of your background image here (could be done automatically by some PHP code)
    var FullscreenrOptions = {  width: 1024, height: 768, bgID: '#bg img' };
    // This will activate the full screen background!
    jQuery.fn.fullscreenr(FullscreenrOptions);
    */
    
    // hover
    $('.thumbs a').live('mouseenter', function() {
        $(this).children('span').fadeIn(150);
    });
    $('.thumbs a').live('mouseleave', function() {
        $(this).children('span').fadeOut(150);
    });
    
    // carrega o feed de notícias
    $.getFeed({
        url: Application.build_url('blog/feed'),
        success: function(feed) {
            if (feed.items && feed.items[0]) {

                var maxItems = 3;
                var totalItems = feed.items.length;
                var htmlNoticias = '';

                if (maxItems > totalItems) {
                    maxItems = totalItems;
                }

                for (var i = 0; i < maxItems; i++) {

                    var titulo = feed.items[i].title;
                    var url = feed.items[i].link;
                    var data = new Date(feed.items[i].updated);
                    var corpo = feed.items[i].description.substring(0, 220)+' [...]';

                    var dataFormatada = data.getDate() + '/' + (data.getMonth() + 1) + '/' + data.getFullYear();

                    htmlNoticias +=
                    	'<li>' +
	                    	'<a href="javascript:;">'+
	                    		'<span class="data_noticia">'+dataFormatada+'</span>'+
	                    		'<span class="desc_noticia">'+titulo+'</span>'+
	                    		'<span class="'+url+'">Leia mais</span>'+
	                    	'</a>'+
	                    '</li>';
                }

                $('h2.titulo_news').after('<ul class="lista_news">'+htmlNoticias+'</ul>');
                
            }
        }
    });
    
    
});

