(function($)
{
    
    $(document).ready
    (
        function()
        {
            /* Controlador da navegação dos highlights da home */
            var highlightController =
            {
                /* Elementos relacionados com tratamento básico */
                elements:
                {
                    holder       : $('#highlights'),
                    container    : $('#highlights div.highlight div.container'),
                    images       : $('#highlights div.highlight div.container a')
                                    .each
                                    (
                                        function()
                                        {
                                            var text = this.getAttribute('title');
                                            this.setAttribute('title','');
                                            this.setAttribute('navTitle',text);
                                            text = null;
                                        }
                                    ),
                    nav          : $('#highlights div.nav div.container')
                                    .attr('unselectable','on')
                                    .css({'-khtml-user-select':'none', '-moz-user-focus':'ignore','-moz-user-input':'disabled','-moz-user-select':'none'}),
                    controllers  : $('#highlights div.nav div.container a'),
                    paragraph    : $('#highlights p.about'),
                    paragraphLink: $('#highlights p.about a'),
                    phantom      : null
                },
                currentPosition : 0, /* Posição atualmente visualizada */
                timer           : null, /* Timer inicial que mostra sequencialmente os elementos */
                config          :
                {
                    generalSpeed: 'slow',
                    timerSpeed  : 5000
                },
                /* Função principal */
                setPosition: function(index)
                {
                    if(index < 0)return false;
                    else if(index > highlightController.elements.images.length - 1)return false;
                    
                    highlightController.currentPosition = index;
                                        
                    var target  = highlightController.elements.images.eq(index),
                        pos     = target.position(),
                        miniPos = {source: highlightController.elements.nav.find('a.active').removeClass('active').position(),
                                   target: highlightController.elements.controllers.eq(index).position()};

                    /* Phantom animation */
                    if(highlightController.elements.phantom == null)
                    {
                       highlightController.elements.phantom = $(document.createElement('span')).addClass('phantom blk').css({top:miniPos.source.top, left:miniPos.source.left});
                       highlightController.elements.nav.append(highlightController.elements.phantom);
                    }
                    else highlightController.elements.phantom.css({display: 'block'});

                    highlightController.elements.phantom.animate
                    (
                        {top: miniPos.target.top, left: miniPos.target.left},
                        highlightController.config.generalSpeed,
                        'linear',
                        function()
                        {
                            highlightController.elements.phantom.css({display: 'none'});
                            highlightController.elements.controllers.removeClass('active');
                            highlightController.elements.controllers.eq(index).addClass('active');
                        }
                    );
                    
                    /* Container */
                    highlightController.elements.container.animate
                    ({top: -pos.top, left: -pos.left},
                    highlightController.config.generalSpeed);

                    /* Paragraph */
                    highlightController.elements.paragraph.animate
                    (
                        {opacity:0},
                        highlightController.config.generalSpeed,
                        'linear',
                        function()
                        {                                
                            highlightController.elements.paragraphLink
                                .html(target.attr('navTitle'))
                                .attr('href', target.attr('href'));
                                
                            if(target.attr('target') == '_blank')
                                highlightController.elements.paragraphLink.attr('target','_blank');
                            else
                                highlightController.elements.paragraphLink.removeAttr('target');
                                
                            highlightController.elements.paragraph.animate
                            ({opacity:1},
                             highlightController.config.generalSpeed,
                             function()
                             {

                                try
                                {
                                    highlightController.elements.paragraph
                                        .css({opacity:1}).get(0).style.removeAttribute('filter');                                    
                                }
                                catch(err)
                                {
                                }

                             });                            
                        }
                    );
                    
                    return true;
                }
            };
            
            if(highlightController.timer == null)
                highlightController.timer = setInterval
                (
                    function()
                    {
                        var maxPos = highlightController.elements.controllers.length - 1;
                        if(++highlightController.currentPosition > maxPos)highlightController.currentPosition = 0;
                        highlightController.setPosition(highlightController.currentPosition);
                    },
                    highlightController.config.timerSpeed
                );
            
            highlightController.elements.controllers.bind
            (
                'click',
                function(e)
                {                    
                    e.preventDefault();
                    e.stopPropagation();

                    if(highlightController.timer != null)window.clearInterval(highlightController.timer);
                    highlightController.setPosition(highlightController.elements.controllers.index(this));
                }
            );
            
            /* Controlador da navegação de vídeos da home */
            var videoNavController =
            {
                currentPosition: 0,
                config:
                {
                    generalSpeed: 'medium'
                },
                elements:
                {
                    mainHolder      : $('#h-videos'),
                    textContainer   : $('#h-videos div.info div'),
                    title           : $('#h-videos div.info strong.title'),
                    more            : $('#h-videos div.info span.more'),
                    container       : $('#h-videos div.video'),
                    videosContainer : $('#h-videos div.video ul'),
                    videos          : $('#h-videos div.video li'),
                    links           : $('#h-videos div.video a'),
                    previous        : $('#h-videos a.previous'),
                    next            : $('#h-videos a.next')
                },
                /* Função principal */
                setPosition: function(index)
                {
                    if(index < 0)return false;
                    else if(index > videoNavController.elements.videos.length - 1)return false;
                    
                    videoNavController.currentPosition = index;
                                        
                    var target  = videoNavController.elements.videos.eq(index),
					pos         = target.position();
                    
					
                    if(!('info' in target[0]))
                        target[0].info = {title: target.find('span.title').html(), more: target.find('span.more').html()};
                    
                    var info = target[0].info;
                    
                    /* Container */
                    videoNavController.elements.videosContainer.animate
                    ({left: -pos.left},
                    videoNavController.config.generalSpeed);
                    
                    /* Textos */
                    videoNavController.elements.textContainer.animate
                    (
                        {opacity:0},
                        videoNavController.config.generalSpeed,
                        'linear',
                        function()
                        {                                
                            videoNavController.elements.title.html(info['title']);
                            videoNavController.elements.more.html(info['more']);
							
                            
                            videoNavController.elements.textContainer.animate
                            ({opacity:1},
                             videoNavController.config.generalSpeed,
                             function()
                             {
                                try
                                {
					videoNavController.elements.textContainer
                                            .css({opacity:1, zoom:1}).get(0).style.removeAttribute('filter');                                    
                                }
                                catch(err)
                                {
                                }
                             });                            
                        }
                    );
                    
                    return true;
                    
                }
            };
            
            videoNavController.setPosition(0);
            
            
            /* Navegação anterior / próximo */
            
            if(videoNavController.elements.previous.length != 0)
            $([videoNavController.elements.previous[0], videoNavController.elements.next[0]]).bind
            (
                'click',
                function(e)
                {                    
		    e.preventDefault();
                    e.stopPropagation();
                    
                    var
                        target = $(this),
                        index  = target.hasClass('previous') ? videoNavController.currentPosition - 1 : videoNavController.currentPosition + 1;
                    
                    videoNavController.setPosition(index);
                    
                    /* Parar vídeos atualmente tocados antes de dar o play atual */
                    $('object',this.parentNode).each
                    (
			function()
                        {
                            var video = this.getAttribute('name');
                            video     = $.browser.msie ? window[video] : document[video];
                            try{video.pauseVideo();}catch(err){/* Previne erros de execução */}
                        }
                    );
                    
                }
            );
            
            /* Binding dos vídeos */
            videoNavController.elements.links.bind
            (
                'click',
                function(e)
                {
                    e.stopPropagation();
                    e.preventDefault();
                    
		    var link   = $(this),
                        swf    = 'content/img/player.swf?video=../../',
                        player = $
                                ('<object data="' + swf + link.attr('href') + '" width="100%" height="100%" type="application/x-shockwave-flash" name="videoObject' + ((new Date()).getTime()) + '" id="videoObject' + ((new Date()).getTime()) + '">' +
                                    '<param name="movie" value="' + swf + link.attr('href') + '" />' +
                                    '<param name="quality" value="high" />' +
                                '</object>');
                    link.replaceWith(player);
                }
            );
            
            
            /* Controlador do carregamento de feeds */
            var feedReaderController =
            {
                cachedFeeds: {},
                elements:
                {
                    'container' : $('#h-feed div.holder'),
                    'flickr'    : $('#h-feed div.flickr div.container'),
                    'twitter'   : $('#h-feed div.twitter div.container'),
                    'blog'      : $('#h-feed div.blog div.container'),
                    'news'      : $('#h-feed div.news div.container'),
                    'facebook'  : $('#h-feed div.facebook div.container')
                },
                requestFeed: function(feedName)
                {
                    if(feedName in feedReaderController.cachedFeeds)
                        return feedReaderController.applyContent(feedReaderController.cachedFeeds);
                    
                    $.post
                    (
                        'content/services/get_feed.php',
                        {feedName: feedName},
                        function(data)
                        {
                            feedReaderController.applyContent(data, feedName);
                        }
                    );
                    
                    return true;
                },
                getContentDimensions: function(content, type)
                {
                    var dummy = $('<div class="item dummy"><div class="container"></div></div>')
                    feedReaderController.elements.container.append(dummy);
                    dummy     = dummy.find('div.container');
                    
                    //Aplicar conteúdo no objeto dummy para verificar quais serão as novas medidas do elemento
                    dummy.parent().removeClass().addClass('item inb dummy ' + type);
                    dummy.html(content);

                    var returnData  = {height:dummy.innerHeight(), width:dummy.innerWidth()};

                    dummy.parent().remove();
                    dummy = null;
                    
                    return returnData;
                },
                applyContent: function(content, type)
                {
                    var newHeight = feedReaderController.getContentDimensions(content, type),
                        oldHeight = feedReaderController.elements[type].innerHeight();
                    feedReaderController.elements[type].addClass('loading').css({height: oldHeight});
                    
                    
                    var maxHeight = parseInt(feedReaderController.elements[type].css('max-height'));
                    if(newHeight.height > maxHeight)newHeight.height = maxHeight;/* IE6 */
                    
                    feedReaderController.elements[type].animate
                    (
                        {height: newHeight.height},
                        'slow',
                        function()
                        {
                            feedReaderController.elements[type].removeClass('loading').html(content);                            
                            return true;
                        }
                    )
                    
                    return true;
                }
            };
        
            /* Set timeout - damn, Safari! */
            if($('body#home').length == 1)
            window.setTimeout
            (
                function()
                {
                    feedReaderController.requestFeed('flickr');
                    feedReaderController.requestFeed('twitter');
                    feedReaderController.requestFeed('blog');
                    feedReaderController.requestFeed('news');
                    feedReaderController.requestFeed('facebook');                    
                },
                100
            );
            
            /* Caixas personalizadas */
            jQuery('select.custom,input[type="checkbox"].custom,input[type="radio"].custom').customBox({swapID: true, forceDimensions: true});
            
            /* Imprensa - critérios de ordenação */
            jQuery('#imprensa #by-vehicle').bind
            (
                'change',
                function(e)
                {
                    if(this.value != '')
                    {
                        self.location.replace(self.location.pathname + '?veiculo=' + this.value);
                    }
                    else
                        self.location.replace(self.location.pathname);
                }
            );
            jQuery('#imprensa #chronologically').bind
            (
                'change',
                function(e)
                {
                    if(this.value != '')
                    {
                        self.location.replace(self.location.pathname + '?periodo=' + escape(this.value));
                    }
                    else
                        self.location.replace(self.location.pathname);
                }
            );
            
            /* Newsletter - cadastro */
            $('form.newsletter').bind
            (
                'submit',
                function(e)
                {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    try
                    {
                        var source = this;
                        
                        if(!this.elements['email'].hasAttribute('alreadyFocused') || this.elements['email'].value == '')
                            throw {message: 'Por favor, informe o seu endereço de e-mail.', source: this.elements['email'], action: 'focus'};
                        
                        if(this.elements['email'].value.indexOf('@') == -1 || this.elements['email'].value.indexOf('.') == -1)
                            throw {message: 'O endereço de e-mail informado é inválido.', source: this.elements['email'], action: 'clear'};

                        $.post
                        (
                            'content/services/add_newsletter.php',
                            {email: this.elements['email'].value.toLowerCase()},
                            function(data)
                            {
                                var response = eval('(' + data + ')');
                                alert(response.message);
                                
                                if(response.status)source.elements['email'].value = '';
                            }
                        );
                    }
                    catch(err)
                    {
                            e.preventDefault();
                            e.stopPropagation();
                            
                            alert(err.message);
                            
                            switch(err.action || '')
                            {
                                    case 'focus':err.source.focus();break;
                                    case 'clear':err.source.value = '';err.source.focus();break;
                            }
                    }
                }
            ).find('input.medium').bind
            (
                'focus',
                function(e)
                {
                    var target = $(this);
                    if(target.attr('alreadyFocused') == null)
                    {
                        this.value = '';
                        target.attr('alreadyFocused','true');
                    }
                }
            );
            
            /*
            $('#sobre ul.program-items li').bind
            (
                'click',
                function(e)
                {
                    e.stopPropagation();
                    e.preventDefault();
                    
                    var target = $(this), routines =
                    {
                        animationSpeed: 500,
                        hide: function(s, callback)
                        {
                            s.addClass('open');

                            s.find('div.hider')
                                .fadeIn(routines.animationSpeed);

                            s.find('> p, > ul').slideUp
                            (
                                routines.animationSpeed,
                                function()
                                {
                                    s.removeClass('open');
                                    if(callback != null)callback.call(this);
                                    return true;
                                }
                            );
                            
                            return true;
                        },
                        show: function(s)
                        {
                            var procedure = function(s)
                            {
                                s.find('div.hider')
                                    .fadeOut(routines.animationSpeed);

                                s.find('> p, > ul').slideDown
                                (
                                    routines.animationSpeed,
                                    function(){s.addClass('open');return true;}
                                );
                            }, toHide = s.parent().find('li.open');
                            
                            if(toHide.length != 0)
                                routines.hide(toHide, function(){procedure(s);});
                            else
                                procedure(s);
                            
                            return true;
                        }
                    };
                    if(target.parent().find(':animated').length == 0)
                    {
                        if(target.hasClass('open'))
                            routines.hide(target);
                        else
                            routines.show(target);
                    }
                }
            );
            */
            $('#sobre ul.program-items li').bind
            (
                'mouseenter',
                function(e)
                {
                    $('span.hider', this).fadeOut('medium');
                }
            ).bind
            (
                'mouseleave',
                function(e)
                {
                    $('span.hider', this).fadeIn('medium');
                }
            );

            /* Agenda - hovers */
            var agendaController = null, lastFocus = null;
            $('#agenda section.program dd, #agenda section.program dt').bind
            (
                'mouseenter',
                function(e)
                {
                    if((this.tagName.toLowerCase() == 'dt' && this.nextSibling == lastFocus) ||
                        (this.tagName.toLowerCase() == 'dd' && this.previousSibling == lastFocus))
                    {
                        if(agendaController != null)window.clearInterval(agendaController);
                    }
                    
                    var target = $('span.hider',this.tagName.toLowerCase() == 'dd' ? this.previousSibling : this);
                    target.fadeOut('medium');
                    return false;
                }
            ).bind
            (
                'mouseleave',
                function(e)
                {
                    var source = lastFocus = this;
                    agendaController = window.setTimeout
                    (
                        function()
                        {
                            var target = $('span.hider',source.tagName.toLowerCase() == 'dd' ? source.previousSibling : source);
                            target.fadeIn('medium');                            
                        },
                        100
                    );
                    return false;
                }
            );
            
            /* Agenda - meses */
            $('#agenda-mes').bind
            (
                'change',
                function(e)
                {
                    if(this.value != '')
                        self.location.replace(this.value);
                }
            );
            
            /* Agenda - navegação inativa */
            $('#agenda nav a.inactive').bind
            (
                'click',
                function(e)
                {
                    e.preventDefault();
                    e.stopPropagation();
                }
            );
            
            
            
            /* Contato */
            $('#contato form.form').bind
            (
                'submit',
                function(e)
                {
                    try
                    {
                        if(this.elements['nome'].value == '')
                            throw {message: 'Por favor, informe o seu nome.', source: this.elements['nome'], action: 'focus'};
                            
                        if(this.elements['email'].value == '')
                            throw {message: 'Por favor, informe o seu endereço de e-mail.', source: this.elements['email'], action: 'focus'};
                        else if(this.elements['email'].value.indexOf('.') == -1 || this.elements['email'].value.indexOf('@') == -1)
                            throw {message: 'O endereço de e-mail informado é inválido.', source: this.elements['email'], action: 'clear'};

                        if(this.elements['cidade'].value == '')
                            throw {message: 'Por favor, informe a sua cidade.', source: this.elements['cidade'], action: 'focus'};

                        if(this.elements['mensagem'].value == '')
                            throw {message: 'Por favor, digite a sua mensagem.', source: this.elements['mensagem'], action: 'focus'};
                    }
                    catch(err)
                    {
                            e.preventDefault();
                            e.stopPropagation();
                            
                            alert(err.message);
                            
                            switch(err.action || '')
                            {
                                    case 'focus':err.source.focus();break;
                                    case 'clear':err.source.value = '';err.source.focus();break;
                            }
                    }
                }
            ).find(':text:eq(0)').focus();
            
            /* Legenda de figuras */
            $('figure').bind
            (
                'mouseenter',
                function(e)
                {
                    $('figcaption',this).fadeIn('fast');
                }
            ).bind
            (
                'mouseleave',
                function(e)
                {
                    $('figcaption',this).fadeOut('fast');
                }
            );
            
            window.setTimeout(function(){$('figcaption').fadeOut('slow');},1000);
            
            /* Sobre - detalhe */
            /*
            $('#sobre-mes').bind
            (
                'change',
                function(e)
                {
                    if(this.value != '')
                        self.location.replace(this.value);
                }
            );
            */
            
            /* Botão "topo" */
            $('a.top').bind
            (
                'click',
                function(e)
                {
                    e.preventDefault();
                    e.stopPropagation();

                    $(navigator.userAgent.toLowerCase().indexOf('webkit') == -1 ? 'html' : 'body')
                    .stop().animate
                    ({scrollTop: 0},
                            'slow',
                            function()
                            {
                                   self.location.hash = '#';
                            }
                    );
                    
                    
                }
            );
            
            /* Notícias - listagem */
            var animate =
            {
               doIt: function(dom, index)
               {
                    var target  = $(dom),
                        dummy   = target.parent().find('> li.dummy'),
                        text    = target.find('> p'),
                        all     = target.find('> p, > aside.share'),
                        hgroup  = target.find('> hgroup'),
                        headers = hgroup.find('h4');
                    
                    if(dom.className.indexOf('dummy') != -1)return;
                    
                    if(target.hasClass('open'))
                    {
                        var height = target.parent().find('li:not(.open) hgroup').height();
                        
                        all.fadeOut('slow');
                                        
                        $(navigator.userAgent.toLowerCase().indexOf('webkit') == -1 ? 'html' : 'body')
                        .stop().animate
                        ({scrollTop: target.offset().top - target.height() + hgroup.height()},
                                'medium',
                                function()
                                {
                                    if(animate.queue.length)animate.queue.pop().call(this);
                                }
                        );
                        target.animate({height:height},'medium',function()
                        {
                            headers.fadeOut('medium', function()
                            {
                                target.removeClass('open');
                                
                                headers.css({'display': 'inline-block'});
                                if($.browser.msie && $.browser.version < 8)headers.css({'display': 'inline'});
                            })
                        });
                    }
                    else
                    {
                        animate.queue.push
                        (
                            function()
                            {
                                var test = dummy.html('<div>' + target.html() + '</div>').find(' > div');
                                dummy.find('*').removeAttr('style');
                                
                                headers.fadeOut('medium', function()
                                {
                                    target.animate({height: test.height()},'medium',
                                    function()
                                    {
                                        target.addClass('open');
                                        headers.fadeIn('medium',
                                        function()
                                        {
                                            all.slideDown('fast');
                                        });
                                        
                                        target.animate({height: test.height()},'medium');
                                        self.location.hash = index;
                                    });                                    
                                });
                            }
                        );
                        
                    }
               },
               target: null,
               queue : []
            };
            
            $('#noticia ol.items li').bind
            (
                'click',
                function(e)
                {
                    if(this.className.indexOf('open') != -1)return;
                    
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var target = $(this), items = $('> li', this.parentNode);
                    
                    items.each
                    (
                        function(i)
                        {
                            if(this.className.indexOf('open') != -1 || target[0] == this)animate.doIt(this, target.attr('data-noticia-id'));
                        }
                    );
                    
                }
            );
            
            $('body#noticia').each
            (
                function()
                {
                    var hash = self.location.hash;
                    if(hash.indexOf('#') == 0)hash = hash.substring(1);
                    
                    hash = parseInt(hash);
                    if(hash == '' || isNaN(hash))hash = 0;
                    
                    if(hash != 0 && $('ol.items > li').length > 1)$('#noticia ol.items li[data-noticia-id="' + hash + '"]').triggerHandler('click');
                }
            );
            
            /* Galeria de vídeos - behavior */
            
            /* Seleção de região */
            $('body#galeria header.about-info a').bind
            (
                'click',
                function(e)
                {
                    var label = this.getAttribute('data-label'), parent = this.parentNode;
                    $('#title').html(label);
                    
                    $('body#galeria header.about-info li:not(.title)').each
                    (
                        function(counter)
                        {
                            $(this)[this == parent ? 'addClass' : 'removeClass']('active');
                            return true;
                        }
                    );
                    
                    /* TODO: modificação da listagem de vídeos ao selecionar */                    
                    
                    e.preventDefault();
                    e.stopPropagation();
                    
                    return true;
                }
            );
            
            /* Video gallery controller */
            var videoGalleryController =
            {
                items:
                {
                    boxes:
                    {
                        player  : $('body#galeria #player'),
                        sinopse : $('body#galeria #sinopse'),
                        creditos: $('body#galeria #creditos'),
                        info    : $('body#galeria section.main aside.info')
                    },
                    screenSelector:
                    {
                        box     : $('body#galeria section.video aside'),
                        buttons :
                        {
                            sinopse : $('body#galeria section.video a.sinopse'),
                            creditos: $('body#galeria section.video a.creditos')
                        }
                    },
                    titles:
                    {
                        main : $('body#galeria aside.info h5:not(.extra)'),
                        extra: $('body#galeria aside.info h5.extra')
                    },
                    vote:
                    {
                        list    : $('body#galeria ul.vote'),
                        stars   : $('body#galeria ul.vote a.star'),
                        message : $('body#galeria aside.info p.message')
                    },
                    navigation:
                    {
                        previous: $('body#galeria footer.navigation a.previous'),
                        next    : $('body#galeria footer.navigation a.next')
                    },
                    videos:
                    {
                        list            : $('body#galeria #video-list'),
                        items           : $('body#galeria #video-list a'),
                        player          : null,
                        playButton      : null,
                        timeBar         : null,
                        timeBarContainer: null,
                        timeController  : null,
                        flowControlTimer: null
                    }
                },
                speedConfig: 'medium',
                /* Seleciona qual das áreas (sinopse / descrição / vídeo) deverá ser mostrada */
                setViewableArea: function(areaName, doAfter)
                {
                    with(videoGalleryController.items)
                    {
                        
                        var doHide = false, items = [], controller = {main: 'player', info: 'info'}, callBack =
                        function(area)
                        {
                            boxes[controller.main][area != controller.main ? 'addClass' : 'removeClass']('hiding');
                            
                            if(!boxes[area].hasClass('hide'))
                            {
                                if(doAfter != null)doAfter.call(this, boxes[area]);
                                return true;
                            }
                            
                            boxes[area].fadeIn(videoGalleryController.speedConfig, function()
                            {
                                $(this).removeClass('hide');
                                return true;
                            });
                            
                            /* Caixas de controle */
                            if(boxes['info'].hasClass('hide'))
                            boxes['info'].fadeIn(videoGalleryController.speedConfig, function()
                            {
                                boxes['info'].removeClass('hide');
                                return true;
                            });
                            
                            if(screenSelector.box.hasClass('hide'))
                            screenSelector.box.fadeIn(videoGalleryController.speedConfig, function()
                            {
                                screenSelector.box.removeClass('hide');
                                return true;
                            });
                            
                            if(doAfter != null)doAfter.call(this, boxes[area]);
                            return true;
                        };
                        
                        for(var name in boxes)
                        {
                            if(name == controller.info)continue;
                            
                            if(!boxes[name].hasClass('hide') &&
                                name != areaName && name != controller.main)
                            {
                                doHide = true;                            
                                items.push(boxes[name][0]);
                            }
                        }
                        
                        if(doHide)
                        {
                            $(items).fadeOut
                            (videoGalleryController.speedConfig, function()
                            {
                                $(items).addClass('hide');
                                callBack.call(this, areaName);
                                return true;
                            });
                        }
                        else
                            callBack.call(this, areaName);
                    }
                    
                    return true;
                },
                /* Coloca o vídeo informado pra rodar */
                setCurrentVideo: function(el)
                {
                    var video = $(el), container = video.parent(), subtitle = '';
                    
                    subtitle = 'de ' + container.attr('data-author');
                    subtitle+= (subtitle != 'de ' ? ' - ' : '') + container.attr('data-place');
                    subtitle+= (subtitle != 'de ' ? ', ' : '') + container.attr('data-year');
                    
                    videoGalleryController.items.videos.items.removeClass('active');
                    $(el).addClass('active');
                    
                    //Título / subtítulo
                    videoGalleryController.items.titles.main.html(container.attr('data-title'));
                    videoGalleryController.items.titles.extra.html(subtitle);
                    
                    //Navegação entre vídeos
                    var pos = videoGalleryController.items.videos.items.index(el) + 1;
                    videoGalleryController.items.videos.list.attr('data-current-view-item', pos);
                    
                    videoGalleryController.items.navigation.previous[pos > 1 ? 'removeClass' : 'addClass']('inactive');
                    videoGalleryController.items.navigation.next[pos < videoGalleryController.items.videos.items.length ? 'removeClass' : 'addClass']('inactive');
                    
                    videoGalleryController.setViewableArea('player', function()
                    {
                        videoGalleryController.playVideo(el);
                    });
                    
                },
                /* Adiciona um player tocando o vídeo informado */
                playVideo: function(videoNode)
                {
                    /* Checar compatibilidade com player HTML5 */
                    var allowHTML5 = !!document.createElement('video').canPlayType,
                        isIphone   = navigator.userAgent.toLowerCase().indexOf('iphone') != -1 || navigator.userAgent.toLowerCase().indexOf('ipad') != -1,
                        extension  = videoNode.getAttribute('href').match(/\.([a-z0-9]{1,})$/i)[1];
                    
                    if(allowHTML5)
                    {
                        
                        HTMLPlayer.init
                        (
                            {
				playerId : 'galeria-player',
                                container: videoGalleryController.items.boxes.player.removeClass('playing'),
                                width    : 754,
                                height   : 348,
                                formats  :
                                {
                                    mp4 : {path: videoNode.getAttribute('href').replace('/' + extension,'/mp4').replace('.' + extension, isIphone ? '-iphone.mp4' : '.mp4'), codec : 'video/mp4'},
                                    ogv : {path: videoNode.getAttribute('href').replace('/' + extension,'/ogv').replace('.' + extension,'.ogv'), codec : 'video/ogg'},
                                    webm: {path: videoNode.getAttribute('href').replace('/' + extension,'/webm').replace('.' + extension,'.webm'),codec: 'video/webm'}
                                },
                                events  :
                                {
                                    onStart: function(){this.container.addClass('playing')},
                                    onLoadedData: function(){this.objects.player[0].play();}
                                }
                            }
                        );
                        /*
                            
                        videoGalleryController.items.videos.player =
                        $('#video-player-element').bind
                        (
                            'loadstart',
                            function(e)
                            {
                                videoGalleryController.items.boxes.player.addClass('playing');
                                videoGalleryController.items.vote.message.html('Carregando');
                                return true;
                            }
                        ).bind
                        (
                            'error suspend abort',
                            function(e)
                            {
                                videoGalleryController.items.boxes.player.addClass('playing');
                                if(e.target.error != null)
                                    videoGalleryController.items.vote.message.html('Ocorreu um erro ao carregar seu vídeo. Por favor, verifique sua conexão e tente novamente.');
                                else if(this.networkState == this.NETWORK_LOADING)
                                    videoGalleryController.items.vote.message.html('Carregando');
                            }
                        ).bind
                        (
                            'stalled progress',
                            function(e)
                            {
                                if(this.networkState == this.NETWORK_LOADING)
                                    videoGalleryController.items.vote.message.html('Carregando');
                                else
                                    videoGalleryController.items.vote.message.html('&nbsp;');
                            }
                        );
                        
                        videoGalleryController.items.videos.timeBar =
                            videoGalleryController.items.boxes.player.find('div.status');
                        
                        videoGalleryController.items.videos.timeController =
                            videoGalleryController.items.boxes.player.find('span.timer');
                            
                        videoGalleryController.items.boxes.player.playButton= 
                            videoGalleryController.items.boxes.player.find('a.play-pause');
                        
                        videoGalleryController.items.boxes.player.find('#flow-controller').bind
                        (
                            'click',
                            function(e)
                            {
                                var target = $(this),
                                offset = Math.round(((e.clientX - target.offset().left) / target.width()) * 100);
                                
                                try
                                {
                                    videoGalleryController.items.videos.player[0].currentTime =
                                        Math.round(videoGalleryController.items.videos.player[0].duration * (offset / 100));
                                    
                                    if(videoGalleryController.items.videos.player[0].paused)
                                    {
                                        videoGalleryController.items.videos.player[0].play();
                                        videoGalleryController.items.boxes.player.playButton.removeClass('paused');
                                    }
                                    
                                    videoGalleryController.items.videos.timeBar.css({width: offset + '%'},'slow');
                                    return true;                                    
                                }
                                catch(x){}
                                return true;
                            }
                        );
                        
                        videoGalleryController.items.boxes.player
                            .unbind('mouseenter mouseleave').bind
                            (
                                'mouseenter',
                                function(e)
                                {
                                    $('#flow-controller', this)
                                        .fadeIn(videoGalleryController.speedConfig);
                                    
                                    if(videoGalleryController.items.videos.flowControlTimer != null)
                                        window.clearInterval(videoGalleryController.items.videos.flowControlTimer);
                                        
                                    if(videoGalleryController.items.videos.timeBarContainer == null)
                                        videoGalleryController.items.videos.timeBarContainer = videoGalleryController.items.videos.timeBar.parent();
                                    
                                    var width = videoGalleryController.items.videos.timeBarContainer.width();
                                }
                            ).bind
                            (
                                'mouseleave',
                                function(e)
                                {
                                    $('#flow-controller', this)
                                        .fadeOut(videoGalleryController.speedConfig);
                                }
                            );
                        
                        videoGalleryController.items.boxes.player.playButton
                        .unbind('click').bind
                        (
                            'click',
                            function(e)
                            {
                                e.preventDefault();
                                e.stopPropagation();
                                
                                var target = $(this);
                                
                                if(videoGalleryController.items.videos.player[0].ended)
                                {
                                    videoGalleryController.items.videos.player[0].play();
                                    target.removeClass('paused');
                                    return false;
                                }
                                
                                videoGalleryController.items.videos.player[0][target.hasClass('paused') ? 'play' : 'pause']();
                                target.toggleClass('paused');
                                return true;
                            }
                        );
                        
                        if(navigator.userAgent.toLowerCase().indexOf('iphone') != -1 ||
                           navigator.userAgent.toLowerCase().indexOf('ipad') != -1)
                            videoGalleryController.items.videos.player.triggerHandler('play');
                        */
                    }
                    else
                    {
                        /* Flash fallback */
                        var videoPath= 'content/img/player_interna_videos.swf?video=../../' + formats.mp4.path + '&autoPlay=true',
                        flash        =
                        '<object type="application/x-shockwave-flash" data="'+ videoPath + '" id="flash-video" width="100%" height="100%">' +
                            '<param name="movie" value="' + videoPath + '" />' +
                            '<param name="wmode" value="transparent" />' +
                            '<param name="quality" value="high" />' +
                            '<param name="loop"  value="true" />' +
                            '<param name="menu"  value="false"/>' +
                        '</object>';
                        
                        videoGalleryController.items.boxes.player.removeClass('playing').html(flash);
                    }
                }
            };
            
            /* Videos - ativar player no clique */
            videoGalleryController.items.videos.items.bind
            (
                'click',
                function(e)
                {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var body     = $(navigator.userAgent.toLowerCase().indexOf('webkit') == -1 ? 'html' : 'body'),
                        scrollTop= body[0].scrollTop,
                        targetTop= $('#title').offset().top,
                        current  = this,
                        callBack = function()
                        {
                            videoGalleryController.setCurrentVideo(current);
                            return true;
                        };
                    
                    if((scrollTop - targetTop) > -40)
                        body.stop().animate({scrollTop: targetTop},videoGalleryController.speedConfig,callBack);
                    else
                        callBack.call(this);
                    
                    return true;
                }
            );
            
            /* Vídeo - navegação próximo / anterior */
            if(videoGalleryController.items.navigation.previous[0])
            $([videoGalleryController.items.navigation.previous[0],
               videoGalleryController.items.navigation.next[0]]).bind
            (
                'click',
                function(e)
                {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var pos = videoGalleryController.items.videos.list.attr('data-current-view-item'), target = $(this);
                    if(target.hasClass('inactive'))return false;
                    
                    videoGalleryController.setCurrentVideo
                    (videoGalleryController.items.videos.items[target.hasClass('previous') ? pos - 2 : pos]);
                    
                    return true;                    
                }
            );
            
            /* Vídeos - botões "sinopse" e "créditos" */
            if(videoGalleryController.items.screenSelector.buttons.creditos[0])
            $([videoGalleryController.items.screenSelector.buttons.creditos[0],
               videoGalleryController.items.screenSelector.buttons.sinopse[0]]).bind
            (
                'click',
                function(e)
                {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    var area = '';
                    
                    for(var name in videoGalleryController.items.screenSelector.buttons)
                    {
                        videoGalleryController.items.screenSelector.buttons[name]
                        [videoGalleryController.items.screenSelector.buttons[name][0] != this ||
                        (videoGalleryController.items.screenSelector.buttons[name][0] == this &&
                        !videoGalleryController.items.screenSelector.buttons[name].hasClass('inactive')) ? 'addClass' : 'removeClass']('inactive');
                        
                        if(videoGalleryController.items.screenSelector.buttons[name][0] == this)area = name;
                    }
                    
                    videoGalleryController.setViewableArea
                    (videoGalleryController.items.screenSelector.buttons[area].hasClass('inactive') ? 'player' : area,
                     function(e)
                     {
                        if((e == videoGalleryController.items.boxes.sinopse  ||
                            e == videoGalleryController.items.boxes.creditos))
                        {
                            if($('#galeria-player'))
                                $('#galeria-player').trigger('pause');
                            else
                            {
                                try
                                {
                                    var object = $.browser.msie ? window['flash-video'] : document['flash-video'];
                                    object.pauseVideo();
                                }
                                catch(x)
                                {
                                }
                            }
                        }
                        else
                        {
                            if($('#galeria-player'))
                                $('#galeria-player').trigger('play');
                            else
                            {
                                try
                                {
                                    var object = $.browser.msie ? window['flash-video'] : document['flash-video'];
                                    object.playVideo();
                                }
                                catch(x)
                                {
                                }
                            }
                        }
                        
                     });                  
                    return true;
                }
            );
            
            /* Vídeos - estrelinhas de voto */
            videoGalleryController.items.vote.stars.bind
            (
                'mouseenter',
                function(e)
                {
                    var current = this, found = false;

                    videoGalleryController.items.vote.stars.each
                    (
                        function()
                        {
                            $(this)[!found ? 'addClass' : 'removeClass']('fill');
                            if(current == this)found = true;
                            return true;
                        }
                    );
                    
                    return true;
                }
            ).bind
            (
                'mouseleave',
                function(e)
                {
                    var pos = this.parentNode.parentNode.getAttribute('data-default-stars');

                    videoGalleryController.items.vote.stars.each
                    (
                        function(counter)
                        {
                            $(this)[counter < pos ? 'addClass' : 'removeClass']('fill');
                            return true;
                        }
                    );
                    
                    return true;
                }
            ).bind
            (
                'click',
                function(e)
                {
                    e.preventDefault();
                    e.stopPropagation();
                    
                    this.parentNode.parentNode.setAttribute('data-default-stars', videoGalleryController.items.vote.stars.index(this) + 1);
                    /* TODO: verificar se já há voto para o vídeo no cookie e mostrar mensagem de erro se houver */
                    videoGalleryController.items.vote.message.html('Obrigado pelo seu voto');
                    return true;
                }
            );
            /* Método chamado pelo Flash, escurece a tela */
            window.flashPlay = function()
            {
                videoGalleryController.items.boxes.player.addClass('playing');
            }
            
        }
    )
})(jQuery);
