/* Before and After in IE6/7 */
(function(a){function d(b,d,e){if(b!="after")b="before";if(e=c(d.currentStyle[b])){a(d)[b=="before"?"prepend":"append"](a(document.createElement("span")).addClass(b).html(e))}}function c(a){if(a&&a.length){var c=a.match(b.text)[1],d=c.match(b.url);return d?'<img src="'+d[1]+'" />':c}}var b={text:/^['"]?(.+?)["']?$/,url:/^url\(["']?(.+?)['"]?\)$/};a.pseudo=function(a){d("before",a);d("after",a);a.runtimeStyle.behavior=null};if(document.createStyleSheet){var e=document.createStyleSheet(null,0);e.addRule(".dummy","display: static;");e.cssText="html, head, head *, body, *.before, *.after, *.before *, *.after * { behavior: none; } * { behavior: expression($.pseudo(this)); }"}})(jQuery)

$(function() {
    $('body').addClass('hasJs');
    $('a[rel=external]').bind({
        'click' : function(e) {
            e.preventDefault();
            window.open( $(this).attr('href') );
        }
    });

    /* Primary-nav */
    if ($('body#home, body#login').length) {
        $('.primary-nav li a').bind({
            'mouseenter': function(){ 
                var liClass = $(this).parent().attr('class').replace("tree-","");
                $('.secondary-nav').css('display', 'none');
                if($('ul.tree-'+liClass).is(":hidden")) {
                    $('.secondary-nav.tree-'+liClass).css({ display: "block", width: 940});
                }
            }
        });
        $('#header').bind({
            'mouseleave': function(){ 
                $('.secondary-nav').css('display','none');
            }
        });
    }
    
    /* Team */
    if($('body#team').length) {
         $('.box-badges .active').tipsy({fade: true, gravity: 's', opacity: 1});
         $('.box-social a').tipsy({fade: true, gravity: 'w', opacity: 1});
         
         $('#copyurl').bind('click', function () {
             $('#field-copy-url').css('display','block').focus();
             return false;
         });
         $('#field-copy-url').bind('blur', function () {
              $('#field-copy-url').css('display','none');
          });
    }


    /* Team-blog */
    $('.teams .team').bind({
        'mouseenter': function(){ 
            $(this).addClass("hover").find('.team-hover').animate({
                top: ($.browser.msie && $.browser.version.substr(0,1)<7) ? -50 : -30,
                opacity: 0.85
            }, {duration:150, queue:false});
        },
        'mouseleave': function(){
            $(this).removeClass("hover").find('.team-hover').animate({
                top: ($.browser.msie && $.browser.version.substr(0,1)<7) ? 30 : 0,
                opacity: 0
            }, {duration:150, queue:false});
        },
        'click': function(){
            var linkUrl = $('a',this).attr('href');
            window.location = linkUrl;
        }
    });


    /*
     * generate number ol list
     */
    var generateListNumb = function () {
       $('body#awards div.text ol li').each(function(i){
            $('<span />', {
                'class' : 'number',
                text :    $(this).index()+1
            }).prependTo($(this));
       });
    }();
    
    /*pager page*/
   $('li.inactive a').click(function(){
      return false; 
   });


    /* register fieldset */
    cpt=2;
    $(".form-group-user").each(function(){
        if($(this).hasClass("form-show")) {
            // nothing
        } else {
            var trigger = $("<fieldset/>", {
                "class": "trigger-form-item-user",
                "html": "<legend class=\"heading-6\">"+formTranslations.participant+" n°"+cpt+"</legend>"
                      + "<a href=\"#\">"+formTranslations.ajouter+" <span class=\"icon icon-plus\"></span></a>"
            }).bind("click", function() {
                $(this).find("a").unbind();
                $(this).hide().prev().slideDown();
                return false;
            });
            trigger.find("a").bind({
                mouseenter: function() {
                    $(this).parent().fadeTo("fast", 1);
                },
                mouseleave: function() {
                    $(this).parent().fadeTo("fast", 0.5);
                }
            });
            $(this).css({display: 'none'}).after(trigger);
        }
        cpt++;
    });


    /* Plugin carousel */   
    $.fn.carousel = function(options) {   
        var defaults = {
            active: 1,
            group: 1,
            speed: 400,
            transition: 'slide',
            loop: true,
            nextprev: true,
            pager: true,
            thumb: false,
            fullWidth: false,
            fadeColor: false
        };   

        var opts = $.extend(defaults, options);
        
        return this.each(function() {
            
            /* init */
            var $$ = $(this);
            var elCount = Math.ceil($$.find('.view li').length);
            var slideCount = Math.ceil(elCount / opts.group);
            var slideCurrent = opts.active;
            var easing = (opts.easing) ? opts.easing : '';
            if(opts.transition=='fade') {
                $$.find('.view li:gt(0)').css('z-index',1).hide();
                if(opts.fadeColor) {
                    $$.find('.view').css('background-color',opts.fadeColor);
                }
            } else {
                if(opts.fullWidth) {
                    $(window).resize( function() { resizeCarousel(); });
                    function resizeCarousel() {
                        $$.find('.view li').css('width', window.innerWidth);
                    }
                    resizeCarousel();
                }
                var elWidth = $$.find('.view li').outerWidth(true);
                var slideWidth = elWidth * opts.group;
                var leftPosition = 0;
                var leftPositionMax = (elCount > 1) ? (slideCount-1) * (-slideWidth) : 0;
                var leftPositionCloned = (elCount > 1) ? (slideCount) * (-slideWidth) : 0;
                if(opts.group>1) {
                    var modulo = elCount%opts.group;
                    if(modulo) {
                        var elOldMargin = parseInt($$.find('.view ul li:first').css('margin-right'));
                        var elNewMargin = (opts.group - modulo) * elWidth + elOldMargin;
                        $$.find('.view ul li:last').css('margin-right', elNewMargin);
                    }
                }
                /* generate html code */
                $$.find('.view').css('overflow', 'hidden');
                $$.find('.view ul').css('width', (slideCount+1) * slideWidth);
                $$.find('.view ul li:lt('+opts.group+')').clone().appendTo($$.find('.view ul'));
            }

            var listDiv = $('<div/>',{'class':'list'}).insertAfter($$.find('>.view'));
            
            checkNextPrev = function() {
                if(opts.nextprev && (opts.loop == false)) {
                    nextprevList.find('.prev').show();
                    nextprevList.find('.next').show();
                    if(slideCurrent==1) {
                        nextprevList.find('.prev').hide();
                    }
                    if(slideCurrent==slideCount) {
                        nextprevList.find('.next').hide();
                    }
                }
            }
            
            
            if(opts.nextprev && slideCount>1) {
                var flagMoving = 0;
                var nextprevList = $('<ul/>', { 'class':'prev-next'});
                
                var nextprevPrev = $('<li/>', {
                        'class': 'prev',
                        html: '<a href="#" class="icon">Previous</a>'
                    }).bind('click', function() {
                        if (flagMoving == 0) {
                            flagMoving = 1;
                            if (opts.transition == 'fade') {
                                if(slideCurrent > 1) {
                                    slideNew = slideCurrent-1;
                                } else {
                                    slideNew = slideCount;
                                }
                                $$.find('.view li:eq('+parseInt(slideNew-1)+')').css('z-index',3)
                                    .fadeIn('normal', function(){
                                        $$.find('.view li').css('z-index',1).hide();
                                        $$.find('.view li:eq('+parseInt(slideNew-1)+')').css('z-index',2).show();
                                        slideCurrent = slideNew;
                                        flagMoving = 0;
                                    });
                            } else {
                                if (leftPosition != 0) {
                                    leftPosition = leftPosition + slideWidth;
                                    $$.find('.view ul').animate({
                                        left: leftPosition
                                    }, opts.speed, function(){
                                        flagMoving = 0;
                                    });
                                    slideCurrent -= 1;
                                }
                                else {
                                    $$.find('.view ul').css('left', leftPositionCloned);
                                    leftPosition = leftPositionMax;
                                    $$.find('.view ul').animate({
                                        left: leftPosition
                                    }, opts.speed, function(){
                                        flagMoving = 0;
                                    });
                                    slideCurrent = slideCount;
                                }
                                $("#slider").slider("value", slideCurrent, afterSlide(slideCurrent));
                            }
                        }
                        $$.find('ul.items li').removeClass('active');
                        $$.find('ul.items li.item-'+slideCurrent).addClass('active');
                        checkNextPrev();
                        return false;
                    }).appendTo(nextprevList);
                    
                var nextprevNext = $('<li/>', {
                        'class': 'next',
                        html: '<a href="#" class="icon">Next</a>'
                    }).bind('click', function() {
                        if (flagMoving == 0) {
                            flagMoving = 1;
                            if (opts.transition == 'fade') { 
                                if(slideCurrent < slideCount) {
                                    slideNew = slideCurrent+1;
                                } else {
                                    slideNew = 1;
                                }

                                if(opts.fadeColor) {
                                    $$.find('.view li:eq('+parseInt(slideCurrent-1)+')')
                                        .fadeTo(parseInt(opts.speed/2), 0.3, function(){
                                            //$$.find('.view li:eq('+parseInt(slideCurrent-1)+')').fadeTo('fast',0);
                                            $$.find('.view li:eq('+parseInt(slideNew-1)+')').css('z-index',3)
                                                .fadeIn(opts.speed, function() {
                                                    $$.find('.view li').css('z-index',1).css('opacity',1).hide();
                                                    $$.find('.view li:eq('+parseInt(slideNew-1)+')').css('z-index',2).show();
                                                    slideCurrent = slideNew;
                                                    flagMoving = 0;
                                                });
                                        });
                                } else {
                                    $$.find('.view li:eq('+parseInt(slideNew-1)+')').css('z-index',3)
                                        .fadeIn(opts.speed, function(){
                                            $$.find('.view li').css('z-index',1).hide();
                                            $$.find('.view li:eq('+parseInt(slideNew-1)+')').css('z-index',2).show();
                                            slideCurrent = slideNew;
                                            flagMoving = 0;
                                        });
                                }
                            } else {
                                if (leftPosition > leftPositionMax) {
                                    leftPosition = leftPosition - slideWidth;
                                    $$.find('.view ul').animate({
                                        left: leftPosition
                                    }, opts.speed, function(){
                                        flagMoving = 0;
                                    });
                                    slideCurrent += 1;
                                }
                                else {
                                    leftPosition = leftPositionCloned;
                                    $$.find('.view ul').animate({
                                        left: leftPosition
                                    }, opts.speed, function(){
                                        $$.find('.view ul').css('left', 0);
                                        flagMoving = 0;
                                    });
                                    leftPosition = 0;
                                    slideCurrent = 1;
                                }
                                $("#slider").slider("value", slideCurrent, afterSlide(slideCurrent));
                            }
                        }
                        $$.find('ul.items li').removeClass('active');
                        $$.find('ul.items li.item-'+slideCurrent).addClass('active');
                        checkNextPrev();
                        return false;
                    }).appendTo(nextprevList);
                nextprevList.appendTo(listDiv);
                checkNextPrev();
            }
            
            if(opts.pager && slideCount>1) {
                var itemsList = $('<ul/>', { 'class':'items'});
                for(var i=1; i<=slideCount; i++) {
                    var active = (i==1) ? 'active' : '';
                    var first  = (i==1) ? 'first' : '';
                    var last  = (i==slideCount) ? 'last' : '';
                    var itemsListEl = $('<li/>', {
                        'class': 'item-'+i+' '+active+' '+first+' '+last,
                        html: '<a href="#" class="icon">'+i+'</a>'
                    }).bind('click', function() {
                        slideCurrent = parseInt($(this).text()); 
                        leftPosition = (slideCurrent-1) * (-slideWidth);
                        $$.find('.view ul')
                            .animate(
                                {
                                    left: leftPosition
                                }, opts.speed, easing);
                        $$.find('ul.items li').removeClass('active');
                        $$.find('ul.items li.item-'+slideCurrent).addClass('active');
                        checkNextPrev();
                        return false;
                    }).appendTo(itemsList);
                }
                
                itemsList.appendTo($$.find('.list'));
            }
        });
    }
    
    /* deployment */
    $('.carousel-etapes').carousel({ 'loop': false});
    function afterSlide(slide){
        $('.etapes-nav li').removeClass('active').removeClass('actived');
        $('.etapes-nav li').eq(slide-1).addClass('active');
        $('.etapes-nav li:lt('+slide+')').addClass('actived');
        $('.carousel-etapes .list .item-'+slide).click();
    }
    $('#slider').CUI("slider", {
        range: "min",
        value:1,
        min: 1,
        max: 4,
        step: 1,
        slide: function(event, ui) {
            afterSlide(ui.value);
        }
    });
    $('.etapes-nav li a').click(function(){
        value = parseInt($(this).attr('rel'));
        $("#slider").slider("value", value, afterSlide(value));
        return false;
    });

    // results
    if ( document.getElementById('results') ) {
        $("#results").tablesorter({widgets: ['zebra']})
            .find("tr").bind({
                mouseenter: function(){
                    $(this).addClass("hover");
                },
                mouseleave: function(){
                    $(this).removeClass("hover");
                }
        });
        $("#results th").bind({
            mouseenter: function(){
                $("body").css("cursor", "pointer");
            },
            mouseleave: function(){
                $("body").css("cursor", "auto");
            }
        });
    }
    
    // buzzmeter
    if (document.getElementById('buzzmeter')) {
        var items = $('ul.buzz-meter-info span.bar-outer'),
            bubbles = items.next('div.bubble'),
            speed   = 150;
            
            bubbles.each(function(){
                var widthElem = $(this).innerWidth(),
                    marginElem = (widthElem / 2) + 5;
                    
                    $(this).css({
                       'width': widthElem + 'px', 'marginLeft' : - marginElem + 'px' 
                    });
                    $(this).hide()
            });
            
            items.bind({
                'mouseenter' : function(){
                    var bubble = $(this).next('div.bubble');
                    bubble.show()
                },
                'mouseleave' : function(){
                    var bubble = $(this).next('div.bubble');
                    bubble.hide()
                }
            });
            
            function toggleBubble(elem, opa, position, speed){
                elem.animate({
                    'bottom' : position + 'px',
                    'opacity' : opa
                },{duration : speed, queue : false});
            }
    }
    
    if ( document.getElementById('page-videos') ) {
        var videosArr = [];

        $('div.box-video').find('iframe').each(function(){
            videosArr.push($(this).attr('src'));
            $(this).remove();
        });
        
        $('.box-video').dialog(
            { autoOpen: false,
              modal : true, 
              resizable: false, 
              width : 640, 
              draggable : false,
              open : function(){
                  var indexVideoArr = $(this).attr('id').split('-'),
                      indexVideo = indexVideoArr[indexVideoArr.length-1],
                      iframeAttr = {
                          'class' : 'youtube-player',
                          'type' : 'text/html',
                          'width' : 640,
                          'height' : 360,
                          'frameborder' : 0,
                          'allowFullScreen' : true,
                          'src' : videosArr[ indexVideo - 1 ]
                      };
                  $('<iframe />').attr(iframeAttr).prependTo( $(this) );
              },
              close : function(){
                  $('iframe', $(this)).remove();
              }
            }
         );
        
        $('.link-dialog').bind({
            'click' : function() {
                var target = $(this).attr('href');
                $(target).dialog('open');
                
                return false;
            }
        })
    }
    
    $('ol.list-buzz-meter > li, ul.list-rules > li').bind({
        mouseenter: function(){
            $(this).addClass("hover");
        },
        mouseleave: function(){
            $(this).removeClass("hover");
        }
    });
    
    $('ul.list-rules h2.heading-9').bind({
        click: function() {
            var $li = $(this).parent();
            if($li.hasClass("expanded")) {
                $li.removeClass("expanded");
                $li.find('.content-list').slideUp("fast");
            } else {
                $li.parent().find('li.expanded').removeClass('expanded')
                                                    .find(".content-list").slideUp("fast");
                $li.addClass("expanded");
                $li.find('.content-list').slideDown("fast");
            }
            /*
            if($(this).hasClass("expanded")) {
                $(this).removeClass("expanded");
                $(this).find('.content-list').slideUp("fast");
            } else {
                $(this).parent().find('li.expanded').removeClass('expanded')
                                                    .find(".content-list").slideUp("fast");
                $(this).addClass("expanded");
                $(this).find('.content-list').slideDown("fast");
            }
            */
        }
    })
    
    if ( document.getElementById('copy-url') ){
        var copyBtn = $('button#copy-url'),
            inputUrl = $('input#field-copy-url');
            inputUrl.addClass('hide');
            copyBtn.bind({
                'click' : function(){
                    inputUrl.toggleClass('hide');
                    if ( !inputUrl.hasClass('hide') ){
                        inputUrl.select();
                    }
                }
            });
    }
});
