(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: 1000,
                    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
            (
                '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 */
            /* 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
                    },
                    share:
                    {
                        twitter         : $('body#galeria ul.share li.twitter a'),
                        facebook        : $('body#galeria ul.share li.facebook a'),
                        permalink       : $('body#galeria ul.share li.permalink a')
                    }
                },
                speedConfig: 'medium',
                /* Seleciona qual das Áreas (sinopse / descrição / ví­deo) deverão 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');
                    if(container.attr('data-place') != '')subtitle+= (subtitle != 'de ' ? ' - ' : '') + container.attr('data-place');
                    
                    subtitle+= (subtitle != 'de ' ? ', ' : '') + container.attr('data-year');
                    
                    videoGalleryController.items.videos.items.removeClass('active');
                    $(el).addClass('active');
                    
                    //Sinopse / créditos
                    videoGalleryController.items.boxes.sinopse.html(video.find('span.sinopse').html()).removeClass('hide');
                    videoGalleryController.items.boxes.creditos.find('div.middler').html(video.find('span.creditos').html()).removeClass('hide');
                    
                    //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');
                    
                    //Botões de share
                    videoGalleryController.items.share.twitter.attr
                    ('href', 'http://twitter.com/share?url=' + video.attr('data-permalink').replace('&','%26') + '&text=' + video.parent().attr('data-title') + '&via=artemov');
                    videoGalleryController.items.share.facebook.attr
                    ('href', 'http://www.facebook.com/share.php?u=' + video.attr('data-permalink').replace('&','%26') + '&t=' + video.parent().attr('data-title'));
                    videoGalleryController.items.share.permalink.attr('href',video.attr('data-permalink'));
                    
                    //Campo hidden do formulário de votos
                    $('body#galeria #vote-status input[type=hidden][name=video]').attr('value', video.attr('data-video'));
                    
                    //Retira classe ativa dos botões de sinopse / créditos
                    videoGalleryController.items.screenSelector.buttons.creditos.addClass('inactive');
                    videoGalleryController.items.screenSelector.buttons.sinopse.addClass('inactive');
                    
                    videoGalleryController.setViewableArea('player', function()
                    {
                        videoGalleryController.playVideo(el);
                        if('VoteController' in window)VoteController.init();
                    });
                    
                },
                /* Adiciona um player tocando o ví­deo informado */
                playVideo: function(videoNode)
                {

                    if(!('videoFormatSettings' in videoNode))
                        videoNode.videoFormatSettings = eval('(' + videoNode.getAttribute('data-formats') + ')');

                    HTMLPlayer.init
                    (
                        {
                            playerId : 'galeria-player',
                            container: videoGalleryController.items.boxes.player.removeClass('playing'),
                            width    : 754,
                            height   : 348,
                            formats  : videoNode.videoFormatSettings,
                            events  :
                            {
                                onStart: function()
                                {
                                    this.container.addClass('playing')
                                },
                                onLoadedData: function(){this.objects.player[0].play();}
                            }
                        }
                    );
                }
            };
            
            /* 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.boxes)
                        if(videoGalleryController.items.boxes[name].is(':animated'))return true;
                    
                    
                    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;
                        
                     });                  
                    return true;
                }
            );

            /* Método chamado pelo Flash, escurece a tela */
            window.flashPlay = function()
            {
                $('#flow-controller').addClass('hide');
                videoGalleryController.items.boxes.player.addClass('playing');
            }
            
            /* Inicializa o ví­deo selecionado, caso exista um */
            $('body#galeria ul#video-list li.selected a').triggerHandler('click');
            
            /* Legenda dos ví­deos */
            $('body#galeria ul#video-list li').bind
            (
                'mouseenter',
                function(e)
                {
                    var messageBox = $('div#legenda'), target = $(this), inner = target.find('> a');
                    
                    if(messageBox.length == 0)
                    {
                        messageBox = $(document.createElement('div'))
                                        .attr('id','legenda')
                                        .css({zIndex: 9999}).html('');
                    }
                    
                    var content = [target.attr('data-title') + '<br />De ' + target.attr('data-author') + ' ('];
                    if(target.attr('data-place') != '')content.push(target.attr('data-place') + ', ');
                    content.push(target.attr('data-year') + ')');
                    
                    //Before pick up measures
                    messageBox.css({display:'block', visibility: 'hidden'}).html(content.join(""));
                    
                    if(messageBox.parent()[0] != inner[0])inner.append(messageBox[0]);
                    
                    var position = {left: Math.round(messageBox.outerWidth() / 2),
                                    top:  Math.round(messageBox.outerHeight() / 2)};
                    
                    target.addClass('over');
                    
                    //After pickup measures
                    messageBox
                    .css
                    ({
                        display     : 'none',
                        visibility  : 'visible',
                        top         : position.top,
                        left        : position.left
                    })
                    .stop(true, true)
                    .fadeIn('fast');
                    
                    
                }
            ).bind
            (
                'mouseleave',
                function(e)
                {
                    $(this).removeClass('over');
                    $('div#legenda').stop(true, true).fadeOut('fast');
                }
            );
            
            /* Revista - seleção da edição */
            $('#revista-edicao').bind
            (
                'change',
                function(e)
                {
                    if(this.value != '')
                        self.location.replace(this.value);
                }
            );
            
        }
    )
})(jQuery);
