var mediaActive = 0;
var alreadyVoted;
if(alreadyVoted == undefined)
    alreadyVoted = false;
var cache = new Array();

function manageLogin(){
    var linkLogin = $('a#lnk-login');
    
    linkLogin.addClass('closed');
    
    $('a#lnk-login').live(
        'click', function(e){
            var panelLogin = $('div#panel-login div.outer');
            
            if (panelLogin != undefined) {
                if ( $(this).hasClass('closed') ){
                    $(this).removeClass('closed');
                    panelLogin.slideDown();
                } else {
                    $(this).addClass('closed');
                    panelLogin.slideUp();
                }
            }
            
            e.preventDefault()
        }
    )
}

$(function() { 
    $('body').addClass('hasJs');
    // TABS
    $("#tabs, #tabs-home").tabs();
    var cpt = 0;
    $("#tabs ul.ui-tabs-nav a").each(function() {
        $(this).attr("rel",cpt);
        cpt+=1;
    });
    $("#tabs ul.ui-tabs-nav a").click(function() {
        
    });
    $("#tabs div a.more").click(function() {
        var tabExist = $("#tabs ul.ui-tabs-nav a[href="+$(this).attr("href")+"]").length;
        if(tabExist) {
            var tabId = parseInt($("#tabs ul.ui-tabs-nav a[href="+$(this).attr("href")+"]").attr('rel'));
            $("#tabs").tabs("select" , tabId);
            
            return false;
        }
    });

    DD_roundies.addRule('.rounded-r5', '5px');
    DD_roundies.addRule('.rounded-r5-top', '5px 5px 0 0');
    DD_roundies.addRule('.rounded-r5-bottom', '0 0 5px 5px');
    DD_roundies.addRule('.rounded-r5-top-left', '5px 0 0 0');
    DD_roundies.addRule('.rounded-r5-top-right', '0 5px 0 0');
    DD_roundies.addRule('.rounded-r5-bottom-right', '0 0 5px 0');
    DD_roundies.addRule('.rounded-r5-bottom-left', '0 0 0 5px');
    DD_roundies.addRule('.rounded-r3', '3px');
    DD_roundies.addRule('.rounded-r8', '8px');
    DD_roundies.addRule('.rounded-r10', '10px');
    //DD_roundies.addRule('.ui-corner-all', '3px');
    DD_roundies.addRule('.rounded-r3-left', '3px 0 0 3px');
    DD_roundies.addRule('.rounded-r3-left-top', '3px 0 0 0');
    DD_roundies.addRule('.rounded-r3-right', '0 3px 3px 0');
    DD_roundies.addRule('.rounded-r5-top', '5px 5px 0 0');
    DD_roundies.addRule('.rounded-r3-top', '3px 3px 0 0');    
    DD_roundies.addRule('.rounded-r5-bottom', '0 0 3px 3px');

    

    $('a[rel*=external]').click( function() {
       window.open(this.href);
       
       return false;
    });

    // SEARCHING
    var saveSearchLabel = $('.search .search-input').attr('value');
    $('.search .search-input')
        .focus(function(){
            if(this.value==saveSearchLabel){
                this.value='';
            }
        })
        .blur(function() {
            if(this.value==''){
                this.value=saveSearchLabel;
            }
        });

    $('#search_global').submit(function(){
        $(location).attr('href',$(this).attr('action') + '/query/' + escape($('#query', this).val()));
        return false;
    });


    // NAVIGATION
    $('.primary-menu > li a, .sorter .active, .country .active')
        .mouseenter(function(){
            $(this).parent().parent().find('.picker').css('display', 'none');
            $(this).next('.picker').css('display', 'block');
        })
        .mouseleave(function(){
            $(this).parent().parent().find('.picker').css('display', 'none');
        });
        $('.picker')
            .mouseenter(function(){
            $(this).css('display', 'block');
        })
        .mouseleave(function(){
            $(this).css('display', 'none');
        });

    // FILTERS
    $('ul.filter > li > a[class!=rounded-r3 expand]').next().hide();
    $('ul.filter > li > a').bind('click', function(){
        if($(this).parent().find('ul:visible').length) {
            $(this).removeClass('expand');
            $(this).parent().find('ul').slideUp();
        } else {
            $(this).addClass('expand');
            $(this).parent().find('ul').slideDown();
        }
        return false;
    });
    $('#contest-list ul.filter > li > a').unbind();


    // HOT NEWS
    $('.hot-news ul').each(function(){
        pause = 0;
        function hotNews() { 
            var newsOld = $('.hot-news ul li:visible');
            var newsNew = (newsOld.next().length == 1) ? newsOld.next() : $('.hot-news ul li:first');
            newsOld.hide();
            newsNew.show();
            if(pause==0) { 
                newsAnim = setTimeout(hotNews, 3000);
            }
        }        
        
        $(this).mouseenter(function() { 
            window.clearTimeout(newsAnim); 
        }).mouseleave(function() {
            newsAnim = setTimeout(hotNews, 3000);
        });
        
        $(this).find('li:gt(0)').hide();
        newsAnim = setTimeout(hotNews, 3000); 
    });
    
    // CAROUSEL characters
    /*
    var carouselView = $('<ul/>');
    $('.carousel .carousel-list li a').each(function(i,el) {
        $(this).attr('rel', i);
        $('<li class="carousel-item-'+i+'"><img src="'+$(this).attr('href')+'" width="125" height="175" alt="'+
        $(this).text()+'" class="picture" /></li>').appendTo(carouselView);
    });
    $('<div class="carousel-view"><ul>'+$(carouselView).html()+'</ul></div>').prependTo('.carousel');
    $('.carousel .carousel-list li a:eq(1)').addClass('active');
    $('.carousel .carousel-list li a').bind('click', function() {
        $('.carousel-view ul')
            .animate(
                {
                    left: parseInt($(this).attr('rel') * (-140) + 140)
                }, 400);
        $(this).parent().parent().find('a').removeClass('active');
        $(this).addClass('active');
        return false;
    });*/

    // CAROUSEL home products
    $('.carousel-home').each(function() {
        var carouselHome = this;
        var leftPosition = 0;
        var nbEl = $(carouselHome).find('li').length;
        var leftPositionMax = (nbEl > 4) ? (nbEl-4) * (-140) : 0; 
        if(leftPositionMax==0) $(carouselHome).find('.prev, .next').fadeTo("fast",0.5);
        
        $(carouselHome).find('.prev').bind('click', function() {
            if(leftPosition != 0) {
                leftPosition = leftPosition + 140;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);
            }
            else {
                leftPosition = leftPositionMax;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);
            }
            return false;
        });
        $(carouselHome).find('.next').bind('click', function() {
            if(leftPosition > leftPositionMax) {
                leftPosition = leftPosition - 140;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);
            }
            else {
                leftPosition = 0;
                $(this).parent().find('.carousel-view ul')
                    .animate(
                        {
                            left: leftPosition
                        }, 300);                
            }
            return false;
        });

    });
    var carouselMedia;
    // CAROUSEL MEDIAS
    $('.carousel-medias').each(function() {
        carouselMedia = this;
        var setCpt = 0;
        var mediaCpt = 0;
        $(carouselMedia).addClass('carousel-medias-on').find('.set').each(function() {
            $(this).attr('position', setCpt);
            $(this).find('a.video, a.screenshot').each(function() {
                 $(this).attr('set', setCpt);
                 $(this).attr('position', mediaCpt);
                 mediaCpt += 1;
            });
            setCpt += 1;
        });
        var setTotal = setCpt;
        var setLast = setCpt-1;
        var mediaTotal = mediaCpt;
        var mediaLast = mediaCpt-1;
        var mediaIsLoading = 1;
        
        $(carouselMedia).find('.carousel-view').css('width', setTotal*300);
        if($(carouselMedia).find('a.active').length == 1) {
            var setActive = parseInt($(carouselMedia).find('a.active').attr('set'));
            mediaActive = parseInt($(carouselMedia).find('a.active').attr('position'));
        } else {
            var setActive = 0;
            mediaActive = 0;
        }

        var mediaStart = 1;
        var mediaStop = 6;
        $('<div class="pager"><span class="pager-info">'+mediaStart+' - '+mediaStop+' ' + wordsTranslation.of + ' '+mediaTotal+'</span></div>')
            .appendTo(carouselMedia);

        var pagerPrev = $('<a class="prev" href="#" title="' + wordsTranslation.previous + '"><img height="16" width="16" class="icon" '
                        + ' alt="Prev" src="/layout/nbge/images/px.png" /> ' + wordsTranslation.previous + '</a>');
        var pagerNext = $('<a class="next" href="#" title="' + wordsTranslation.next + '">' + wordsTranslation.next + ' <img height="16" width="16" class="icon" '
                        + ' alt="Next" src="/layout/nbge/images/px.png" /></a>');

        $(pagerPrev).bind('click', function() {
            if(setActive > 0) {
                setActive -= 1;
                updateSet();
            }
            return false;
        }).prependTo($(carouselMedia).find('.pager'));

        $(pagerNext).bind('click', function() {
            if(setActive < setLast) {
                setActive += 1;
                updateSet();
            }
            return false;
        }).appendTo($(carouselMedia).find('.pager'));

        updateSet();

        function updateSet() {
            var leftPosition = setActive * (-295);
            $(carouselMedia).find('.carousel-view')
                .animate(
                    {
                        left: leftPosition
                    }, 300);
            mediaStart = parseInt($(carouselMedia).find('.set[position='+setActive+'] a:first').attr('position')) + 1;
            mediaStop = parseInt($(carouselMedia).find('.set[position='+setActive+'] a:last').attr('position')) + 1;
            
            $(carouselMedia).find('.pager-info').text(mediaStart+' - '+mediaStop+' ' + wordsTranslation.of + ' '+mediaTotal);
            if(mediaStart == 1) {
                $(carouselMedia).find('.prev').hide();
            } else {
                $(carouselMedia).find('.prev').show();
            }
            if (mediaStop == mediaTotal) {
                $(carouselMedia).find('.next').hide();
            } else {
                $(carouselMedia).find('.next').show();
            }
        }

        $(carouselMedia).find('.carousel-view a').bind('click', function() {
            $.historyLoad($(this).attr("id").substr(6));
            return false;
        });

        $(carouselMedia).find('.carousel-view a').bind('mouseover', function() {
            preload($(this).attr("id").substr(6));
            //$(this).unbind('mouseover');

            return false;
        });
        
        function bindData(data) {
            if (mediaClicked.attr('id') != 'media-'+data['id']) {
                return;
            }
            
            mediaIsLoading = 1;
            
            $('h2').html(data.title);
            document.title = data.title.replace(/<[^>]*>/g, "");
            if(mediaType == 'video') {
                var flashvars = {};
                flashvars.config = data.url;
                flashvars.translation = '/media/translation';
                var params = {};
                var attributes = {};
                var params = {wmode:"transparent"};
                attributes.id = "player";
                swfobject.embedSWF('/scripts/player.swf', 'myAlternativeContent', '100%', '100%', '9', 'swf/expressInstall.swf' , flashvars, params, attributes);
            } else {
                $('.container-screenshot .picture').attr("src", data.url).attr("alt", data.title);
            }
            $('.rating').html(data.rating);
            //$('#share').html(data.share);


            mediaClicked.parent().parent().parent().find('a').removeClass('active');
            mediaClicked.addClass('active');
            updateSet();
        }

        
        function pageload(hash) {
            
            if(hash=='') {
                var regId = /\/([0-9_]+)\//g;
                var temp = regId.exec(window.location.href);
                hash = temp[1];
            }
            
            $('.container-screenshot .loading').fadeTo('fast', 1);
                   
            mediaClicked = $('#media-'+hash);
            mediaUrl = mediaClicked.attr('href');
            mediaActive = parseInt(mediaClicked.attr('position'));
            setActive = parseInt(mediaClicked.attr('set'));
            mediaType = mediaClicked.hasClass('video') ? 'video' : 'screenshot';
            if(mediaType == 'video') {
                $('#video-player').html('<div id="myAlternativeContent">'
                    + '<a href="http://www.adobe.com/go/getflashplayer">'
                    + '<img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" '
                    + 'alt="Get Adobe Flash player" /></a></div>');
            } else {
                //$('.container-screenshot .picture').fadeTo('fast', 0);
            }


            if(cache[hash] == undefined)
            {
                $.get(mediaUrl, { is_ajax: true },
                    function(data){
                        cache[hash] = data;
                        bindData(cache[hash]);
                    }
                );
            }else{
                bindData(cache[hash]);
            }

            if(0 <= mediaActive <= mediaLast)
            {
                if(mediaActive > 0) {
                    preload($(carouselMedia).find('.carousel-view .cell:eq('+(parseInt(mediaActive)-1)+')').attr("id").substr(6));
                }
                if(mediaActive!=mediaLast) {
                    preload($(carouselMedia).find('.carousel-view .cell:eq('+(parseInt(mediaActive)+1)+')').attr("id").substr(6));
                }
            }
            return false;
        }

        function preload(hash)
        {
            var preMediaClicked = $('#media-'+hash);
            var mediaUrl = preMediaClicked.attr('href');
            mediaType = preMediaClicked.hasClass('video') ? 'video' : 'screenshot';
            
            if(cache[hash] == undefined)
            {
                $.get(mediaUrl, { is_ajax: true },
                    function(data){
                        cache[hash] = data;
                        if(mediaType != 'video')
                        {
                            heavyImage = new Image();
                            heavyImage.src = data.url;
                        }
                    }
                );
            }
        }

        $('.container-screenshot .prev').bind('click', function() {
            screenId = (mediaActive > 0) 
                        ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive-1)+')').attr("id").substr(6)
                        : $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaLast)+')').attr("id").substr(6);
            $.historyLoad(screenId);
            return false;
        });

        $('.container-screenshot .next').bind('click', function() {
            screenId = (mediaActive < mediaLast) 
                        ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive+1)+')').attr("id").substr(6)
                        : $(carouselMedia).find('.carousel-view .cell:eq(0)').attr("id").substr(6);
            $.historyLoad(screenId);
            return false;
        });

        $(document).keydown(function(e){
            if(e.keyCode=="37") {
                screenId = (mediaActive > 0) 
                            ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive-1)+')').attr("id").substr(6)
                            : $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaLast)+')').attr("id").substr(6);
                $.historyLoad(screenId);
                return false;
            } else if(e.keyCode=="39") {
                screenId = (mediaActive < mediaLast) 
                            ? $(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive+1)+')').attr("id").substr(6)
                            : $(carouselMedia).find('.carousel-view .cell:eq(0)').attr("id").substr(6);
                $.historyLoad(screenId);
                return false;
            }
        });

        var anchor = window.location.hash;
        anchor = anchor.substring(1,anchor.length);

        if(anchor != '') {
            if($(carouselMedia).find('a#media-'+anchor).length) {
                $(carouselMedia).find('a.active').removeClass('active');
                setActive = parseInt($(carouselMedia).find('a#media-'+anchor).attr('set'));
                $.historyInit(pageload, anchor);
            }
        } else {
            $.historyInit(pageload, anchor);
        }

        $('.container-screenshot .picture').load(function(){
            if (mediaIsLoading == 1) {
                mediaIsLoading = 0;
                $('.container-screenshot .loading').fadeTo('fast', 0);
            }
        });
    });

    $('.stars .star:lt('+parseInt($('.stars').attr('rel'))+')').addClass('star-active');

    // RANKING
    $('.stars .star').live('mouseenter', function() {
        $('.stars .star:lt('+parseInt($(this).attr('rel'))+')').addClass('star-hover');
        $('.stars .star:gt('+parseInt($(this).attr('rel')-1)+')').removeClass('star-active').removeClass('star-hover');
    }).live('mouseleave', function() {
        $('.stars .star:lt('+parseInt($(this).parent().attr('rel'))+')').addClass('star-active');
        $('.stars .star').removeClass('star-hover');
    }).live('click', function() {
        var iRanking = $(this).attr('rel');
        var sUrl = $(this).attr('href');
        $.get(sUrl,
            function(data){
                $('.stars .star:lt('+parseInt(iRanking)+')').addClass('star-active');
                $('.stars .star').removeClass('star-hover');
                $('.stars').attr('rel', parseInt(data.rate));
                $('.cpt-rating').text(data.rating_count);
                cache[$(carouselMedia).find('.carousel-view .cell:eq('+parseInt(mediaActive)+')').attr("id").substr(6)] = undefined;
            }
        );
        return false;
    });

    //kcode
    kCode = "38,38,40,40,37,39,37,39,66,65";
    ooCode = "56,56,56,56,56,56,56,56";
    ooPavCode = "104,104,104,104,104,104,104,104";
    redirect = "http://www.octaveoctave.com/project/namco-bandai-games-site-produits-corporate-communautaire"
    kkeys = [];
    $(window).keydown(function(e){
        kkeys.push( e.keyCode );
        if ( kkeys.toString().indexOf( kCode ) >= 0 ||
             kkeys.toString().indexOf( ooCode ) >= 0 ||
             kkeys.toString().indexOf( ooPavCode ) >= 0 ){
            $(this).unbind('keydown', arguments.callee);
            window.location.replace(redirect);
        }
    }, true);


    $("#query").autocomplete({
        source: "/product/search",
        select: function(event, rws) {
            $(location).attr('href',rws.item.url);
        },
        open: function(event, rws) {
            var offset = $('.ui-autocomplete').offset();
            var left = ($.browser.msie) ? parseInt(offset.left - 17) : parseInt(offset.left - 16);
            var top = parseInt(offset.top + 5);
            $('.ui-autocomplete').css('left',left).css('top',top).css('position', 'absolute');
        }
    });
    
    //LostPassword
    var lostPasswordForm = $('#passwordLost');
    lostPasswordForm.addClass('hide');
    $('div.wrapper-login a.lost-password').click(function(){
        lostPasswordForm.toggleClass('hide');
        
        return false;
    });
    
    // medias
    $('div.medias-home .tiny-medias a.video, div.medias-home .tiny-medias a.screenshot, .carousel-medias a.video, .carousel-medias a.screenshot').hover(
        function(){
            $(this).find('span.icon').hide();
            $(this).find('span.infos').animate({
                bottom: 0
            },{duration:150, queue:false});
        },
        function(){
            $(this).find('span.infos').animate(
            {
                bottom: '-90px'
            },200, function(){
                $(this).parent().find('span.icon').show();
            }
           );
        }
    );    
    
    $('.post-answers li')
        .mouseenter(function(){
            $(this).find('.actions a').show();
        })
        .mouseleave(function(){
            $(this).find('.actions a').hide();
        });
    
    $('.icon-cancel').click(function(){
        $('#release_website_id').val('');
        $('.choose-platform').slideUp();
        $('#game').val('');
        $('.platform-list > li').hide();
        $('#choose-game').slideDown();
        $('.game-chosen').hide();
    });
    
    $('.game-list > li').click(function(){      
        var url = $(this).children('a').attr('href');
        loadGameInfo(url);
        return false;
    });
    
    $("#game").autocomplete({
        source: "/product/search",
        select: function(event, rws) {
            loadGameInfo(rws.item.url_game);
        },
        open: function(event, rws) {
            var widget = $(this).autocomplete('widget')
            widget.width( widget.width()-10 );
            widget.css({
                'left': $(this).offset().left,
                'top' : $(this).offset().top + $(this).outerHeight() + 3
            })
        }
    });
    
    $('.platform-list > li > a').click(function(){
        var platformName = $(this).attr('class').replace('platform-', '');
        var rwsId = null;
        
        for(key in platforms) {
            if (platforms[key].class_css == platformName) {
                rwsId = platforms[key].rwsid;
                platform = platforms[key].title;
                break;
            }
        }
        $('#release_website_id').val(rwsId);
        $('.choose-platform').slideUp();

        if ($(this).attr('href') != '#' && $(this).attr('href') != '') {
            $('#search-games').val('');
            $.ajax({
                url: $(this).attr('href'),
                data: {"rwsid" : rwsId},
                dataType: "html",
                success: function(html){
                    $('.favorite-games-items').prepend(html);
                }
            });
        } else {
            $('.game-chosen > h2').text($('.game-chosen > h2').text() + ' - ' + platform);
            $('.game-chosen').show();
        }
        
        return false;
    });
    
    $('.game-chosen').hide();

    $("#search-games").autocomplete({
        source: "/product/search",
        delay: 500,
        select: function(event, rws) {
            loadGameInfo(rws.item.url_game);
        },
        open: function(event, rws) {
            var widget = $(this).autocomplete('widget')
            widget.width( widget.width()-10 );
            widget.css({
                'left': $(this).offset().left,
                'top' : $(this).offset().top + $(this).outerHeight() + 3
            })
        }
    });
    $(".remove-item").live('click', function(){
        var self = this;
        if ($(this).attr('href') != '#'  && $(this).attr('href') != '') {
            $.ajax({
                url: $(this).attr('href'),
                dataType: "text",
                success: function(text){
                    if (text == 'true') {
                        $(self).parent().fadeOut();
                    } else {
                        
                    }
                }
            });
        }
        
        return false;
    });
    
    
    (function(){
        $('div.first-post div.rte a, ul.post-answers div.rte a').attr('target', '_blank');
        
        var loginBox = $('div.box-login'),
            loginForm = $('.box-login form#login-form, #panel-login form#login-form'),
            popinReport;
        
        function renderPopin(elem, classBox, widthPopin){
            elem.dialog({
                autoOpen : false,
                modal : true,
                resizable: false,
                draggable : false,
                dialogClass: classBox,
                width : widthPopin,
                open : function(){
                    $('div#content object').hide();
                },
                close : function(){
                    $('div#content object').show();
                }
            });
        }

        renderPopin(loginBox, 'dialog-login-popin', 406);
        
        $('a.login-required').live('click', function(){
            loginBox.dialog('open');

            return false;
        });
        
        loginBox.find('div.external-accounts a').bind({
            'click' : function(e){
                loginBox.dialog('close');
            }
        })
        
        var inputsLoginForm =  loginForm.find('input[type=text], input[type=password]');
        
        inputsLoginForm.each(function(){
            $(this).data('data-value', $(this).val());
            $(this).bind({
                focus : function(){
                    if ( $(this).val() == $(this).data('data-value') ){
                        $(this).val('');
                    }
                },
                blur : function(){
                    if ( $(this).val() == ''){
                        $(this).val($(this).data('data-value'));
                    }
                }
            });
        });
        
        $('div.ui-widget-overlay').live('click', function(){
            $('div.box-popin').dialog('close');
        })
    
    function loadPopinAbuse(url){
        $.getJSON(url, function(data){
            popinReport = $('<div />',{
                            'class' : 'box-popin box-report-abuse'
                        });
            
            var titleForm = $('<h2 />').text(data.title),
                descriptionFrom = $('<p />').html(data.message);
            
            var form = data.form;
            
            
            var squelettor = $('<div />',{
                                 'class' : 'popin-outer'
                             }),
                squelettorContent = $('<div />',{
                                        'class' : 'popin-content'
                                    }).append($('<div />',{'class':'popin-inner'}).append(titleForm, descriptionFrom)),
                squelettorFooter = $('<div />',{
                                    'class' : 'popin-footer'
                                }).append($('<div />',{'class':'popin-inner'}).html(form));
                                
           squelettor.append(squelettorContent, squelettorFooter);
           popinReport.append(squelettor);
           
           popinReport.appendTo($('body'));
           renderPopin(popinReport, 'dialog-report-abuse', 360);
           popinReport.dialog({
               'close' : function(){
                   $(this).remove();
               }
           })
           popinReport.dialog('open')
        });
    }
    
    if ($('body#discussions-view a.abuse').length > 0) {
        var lnk = $('a.abuse'),
            lastLinkAbuse;
        lnk.bind({
            'click': function(e){
                lastLinkAbuse = $(this);
                var url = this.href;
                loadPopinAbuse(url);
                
                e.preventDefault();
            }
        });
        
        $('form.form-report-abuse').live('submit', function(){
            $el = $(this);
            var url = $(this).attr('action'),
                datasSend = $(this).serialize();

            $.post(url, datasSend, function(result){
                if ( result.code ) {
                    lastLinkAbuse.replaceWith(
                        $('<span />',{
                            'class' : 'abuse'
                        }).text(result.message)
                    )
                    popinReport.dialog('close');
                } else {
                    $el.replaceWith(result.form);
                }
            })
            
            return false;
        });
    }
    
    if ($('input.additional-infos').length){
        var popinAdditionalInfos = $('div.box-additional-infos');
        
        if ( popinAdditionalInfos.length){
            renderPopin(popinAdditionalInfos, 'dialog-additional-infos', 486);
        }
        
        $('input.additional-infos').bind('click', function(e){
            e.preventDefault();
            popinAdditionalInfos.dialog('open');
        })
    }
    
        //popin congrat
        var popinCongrat = $('div.box-congratulation');
        
        if ( popinCongrat.length > 0) {
            renderPopin(popinCongrat, 'dialog-congrat-popin', 360);
            popinCongrat.dialog('open');
            
            popinCongrat.find('a.submit').bind({
                'click' : function(e){
                    popinCongrat.dialog('close');
                    popinCongrat.remove();
                    
                    e.preventDefault();
                }
            })
        }
        
        
        //popin send msg
        var popinSendMsg = $('div.box-send-msg'),
            lnkSendMsg = $('a.send-msg');
        renderPopin(popinSendMsg,'dialog-send-msg', 406);
        
        lnkSendMsg.bind({
            'click': function(e){
                popinSendMsg.dialog('open');
                
                e.preventDefault();
            }
        });
        
        popinSendMsg.dialog({
            'close' : function(){
              $(this).find('form.form-send-msg input[type=text]').val('');
              $(this).find('form.form-send-msg textarea').val('');
            }
        });
        
        //popin how it works
         var popinHIW = $('div.box-hiw'),
             lnkHIW = $('a#hiw');
             
         renderPopin(popinHIW, 'dialog-hiw', 500);
         lnkHIW.bind({
             'click' : function(e){
                 popinHIW.dialog('open');
                 
                 e.preventDefault();
             }
         })
        
        var moreAccounts = $('span#more-accounts');
    
        function renderActive(elem){
            elem.addClass('hover');
            elem.next().addClass('active');
        }
        function renderInactive(elem){
            elem.removeClass('hover');
            elem.next().removeClass('active');
        }
        
        moreAccounts.bind({
            'mouseenter' : function(){
                renderActive($(this));
            },
            'mouseleave' : function(){
                renderInactive($(this));
            }
        });
        
        moreAccounts.next().bind({
            'mouseenter' : function(){
                renderActive($(this).prev());
            },
            'mouseleave' : function(){
                renderInactive($(this).prev());
            }
        })
        
        var favoriteGamesItems = $('div.favorite-games-item');
        
        favoriteGamesItems.live('mouseenter', function(){
            $(this).addClass('hover');
        })
        
        favoriteGamesItems.live('mouseleave', function(){
            $(this).removeClass('hover');
        })

        
        
        //manage files attachments post
        
        function manageFilesAttachments(){
            
            var filesAttachment = $('div.files-attachment a.file'),
                clsPhoto = 'screenshot',
                clsVideo = 'video',
                container = 'mediasorfiles-content';
    
                
                function changeSrc(elem, newSrc){
                    elem.attr('src', newSrc);
                }
                
                function generatePhoto(elem){
                    var newSrc = elem.attr('href');
                    
                    if( $('div#'+ container).find('img.picture').length > 0 ){
                        changeSrc($('div#'+ container).find('img.picture'), newSrc);
                    } else {
                        $('div#'+ container).empty();
                        
                        var img = $('<img />',{
                            'class' : 'picture'
                        });
                        changeSrc(img, newSrc);
                        $('div#'+ container).append(img);
                    }
                }
                
                function generateVideo(elem){
                    var srcVideo = elem.attr('href'),
                        objectVideo = '<object width="500" height="280" data="'+ srcVideo +'" type="application/x-shockwave-flash"><param name="src" value="'+ srcVideo +'" /></object>';
                        $('div#' + container).html(objectVideo)
                }
                
                filesAttachment.bind({
                    'click' : function(){
                        
                        if ( $(this).hasClass(clsPhoto)){
                            generatePhoto($(this));
                        } else {
                            if ($(this).hasClass(clsVideo)) {
                                $('div#' + container).empty()
                                generateVideo($(this));
                            }
                        }
                         return false;
                    }
                })
        }
    
        if ( $('div.files-attachment').length > 0 ){
            manageFilesAttachments();
        }
    
        function manageForm(){
            var form = $('form.form-accordion'),
                fieldsets = form.find('dd.subform'),
                clsIcon = 'trigger-accordion',
                clsIconClosed = 'trigger-accordion-closed',
                clsSubform = 'subform-open',
                clsHover = 'trigger-accordion-hover';
                
                
                function collapse(elem){
                    elem.find('fieldset dl:eq(0)').hide();
                    elem.find('div.favorite-games-items').hide();
                    elem.removeClass(clsSubform);
                }
                
                function extend(elem){
                   $('.'+ clsSubform).find('fieldset dl:eq(0)').hide();
                   $('.'+ clsSubform).find('div.favorite-games-items').hide();
                   $('.'+ clsSubform).removeClass(clsSubform);
                   elem.find('fieldset dl:eq(0)').show();
                   elem.find('div.favorite-games-items').show();
                   elem.addClass(clsSubform);
                }
                
                function collapseExpand(elem, event){
                   var target = event.target;
                    
                   if ( elem.hasClass(clsSubform) ) {
                       if ( (target == elem.find('legend')[0])  || (target == elem.find('span.' + clsIcon)[0]) ){
                           collapse(elem);
                       }
                   } else {
                       extend(elem);
                   }
                }
                
    
                fieldsets.each(function(){
                   var $fieldset = $(this);
                   var trigger = $('<span />',{
                                    'class' : 'icon ' + clsIcon
                                 });
                   $(this).prepend(trigger);
    
                  $(this).bind({
                      'click' : function(e){
                          collapseExpand($(this), e)
                      },
                      'mouseenter' : function(e){
                          if ( !$(this).hasClass(clsSubform) ){
                              trigger.addClass(clsHover);
                          }
                      },
                      'mouseleave' : function(e){
                              trigger.removeClass(clsHover);
                      },
                      'mousemove' : function(e){
                          if ( $(this).hasClass(clsSubform) ){
                              var target = e.target;
                              if ( (target == $(this).find('legend')[0])  || (target == $(this).find('span.' + clsIcon)[0]) ){
                                   trigger.addClass(clsHover);
                               } else {
                                   if ( trigger.hasClass(clsHover)) {
                                       trigger.removeClass(clsHover);
                                   }
                               }
                          }
                      }
                  })
                   if ( !$(this).hasClass(clsSubform) ){
                       collapse($(this));
                   }
                });
    
        }
        
        if ( $('form.form-accordion').length > 0 ) {
            manageForm();
        }
        
        //search-topic
        var searchIn = $('div#search-in'),
            searchType = searchIn.find('label'),
            bar = $('<div />',{
                id : 'bg-bar',
                'class' : 'icon icon-bar'
            }),
            buttonSelect = $('<div />', {
                id : 'button-radio',
                'class' : 'icon icon-button-radio'
            }).appendTo(bar);
            
            bar.prependTo(searchIn);
            
            searchType.bind({
                'click':function(){
                    searchIn.removeClass().addClass('active-' + $(this).attr('for'));
                }
            })
    })();
    
    var saveCommentLabel = $('textarea#comment').attr('value');
    $('textarea#comment')
        .focus(function(){
            if(this.value==saveCommentLabel){
                this.value='';
            }
        })
        .blur(function() {
            if(this.value==''){
                this.value=saveCommentLabel;
            }
        });
        
    //module accordion
    $('.accordion').prepend('<span class="icon trigger-accordion"></span>');
    
    $('.accordion').bind({
        mouseenter: function() {
            $(this).addClass("hover");
            $(this).find('span.trigger-accordion').addClass('trigger-accordion-hover');
        },
        mouseleave: function() {
            $(this).removeClass("hover");
            $(this).find('span.trigger-accordion').removeClass('trigger-accordion-hover');
        },
        click: function() {
            if($(this).hasClass("expanded")) {
                $(this).removeClass("expanded");
//                $(this).find('.accordion-inner').slideUp("fast");
                $(this).find('.accordion-inner').hide();
            } else {
                $('ol.methodo li.expanded').removeClass('expanded')
                                           .find(".accordion-inner").hide();
                $(this).addClass("expanded");
                $(this).find('.accordion-inner').show();
            }
        }
    });
    $('#contest-answers.accordion').click();
});

var platforms; 
function loadGameInfo(url) {
    $.getJSON(url, function(rws) {
        $('#choose-game').slideUp();
        $('.choose-platform').show();
        $('.game-chosen').slideDown();
        
        $('.game-chosen > h2').text(rws.label);
        if (null !== rws.cover) {
            $('.game-chosen > img').show();
            $('.game-chosen > img').attr('src', rws.cover);     
        } else {
            $('.game-chosen > img').hide();
        }
        $('.platform-list > li').hide();
        
        $.each( rws.platform, function(k, v) {
            $('.platform-' + v.class_css).parent().show();
        });
        platforms = rws.platform;
        $('.choose-platform').slideDown();
    });
}

// minimize and maximize video
function changeVideoSize() {
    if($('#video-player').width() == '640') {
        $('#video-view').css('padding-right','0');
        $('.video-list').css('margin-top','2px');
        $('#video-player').css('width', '950px').css('height', '534px');
    } else {
        $('#video-view').css('padding-right','310px');
        $('#video-player').css('width', '640px').css('height', '360px');
        $('.video-list').css('margin-top', '-'+$('#video-view').outerHeight(true)+'px');
    }
}

