/******indexOf fo Ie**************/
if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
        for(var i=0; i<this.length; i++){
            if(this[i]==obj){
                return i;
            }
        }
        return -1;
    }
}

//Diaporama Jquery
function customCarrousel () { }

// définition des valeurs par défaut
customCarrousel.prototype.target = '#carrousel';
customCarrousel.prototype.urlParam = 'tab';
customCarrousel.prototype.autoSlide = true;
customCarrousel.prototype.crossTransition = true;
customCarrousel.prototype.autoHeight = false;
customCarrousel.prototype.autoWidth = false;
customCarrousel.prototype.timeToSlide = 3000;
customCarrousel.prototype.slideSpeed = 500;
customCarrousel.prototype.stopAfterFirstClick = false;
customCarrousel.prototype.htmlTemplate = '<tbody><tr><td class="leftColumn"><zone/></td><td class="rightColumn"><list/></td></tr></tbody>';
customCarrousel.prototype.order = ['tab', 'zone'];
customCarrousel.prototype.tabContainer = 'ul';
customCarrousel.prototype.tabLister = 'li';
customCarrousel.prototype.zIndex = 10;
customCarrousel.prototype.trigger = 'click'; //autre valeur : 'hover'
customCarrousel.prototype.menuMode = false;
customCarrousel.prototype.carrousel = function () {

    if (!$(this.target).length) return;
    var tags =[],
    zone=[],
    x=0,
    y=0,
    i=1,
    me=this;

    $(this.target).css({
        'position':'relative'
    });

    // récupération des élemetns du webBlock
    $(this.target+ ' > tbody > tr').each(function () {
        var thisElement = $(' > td', this);

        var thisTag = thisElement.eq(me.order.indexOf("tab")).html(),
        thisZone = thisElement.eq(me.order.indexOf("zone"));

        if (me.autoWidth) x = Math.max (thisZone.width(), x);
        if (me.autoHeight) y = Math.max (thisZone.height(), y);

        tags.push('<'+me.tabLister+' class="tagListElements" ><a class="tagLinks tagLink'+i+'">'+thisTag + '</a></'+me.tabLister+'>');
        var tempZone = thisZone.wrapInner('<div class="tagsZone tagZone'+i+'" />'),
        tempZoneChild = tempZone.children().detach();
        zone.push(tempZoneChild);
        i++;
    });

    // Position initiale diaporama
    var numberOfItems = tags.length,
    timeOut,
    uriCourant = document.location.href,
    reg= new RegExp ("[&\\?]"+this.urlParam+"=(\\d+)", "g"),
    infosInUrl = reg.exec(uriCourant);

    var current = null,
    next = (infosInUrl && infosInUrl.length>0 && parseInt(infosInUrl[1])>0 && parseInt(infosInUrl[1])<=numberOfItems )? parseInt(infosInUrl[1]) : 1;

    //création HTML
    $(this.target).html(this.htmlTemplate);

    $(this.target+' zone:first').replaceWith('<div class="tagsListZone" style="position:relative;"></div>');
    $(this.target+' list:first').replaceWith('<'+this.tabContainer+' class="tagsList">'+tags.join('')+'</'+this.tabContainer+'>');
    for (var j=0; j<numberOfItems; j++) {
        $(me.target+' .tagsListZone:first').append(zone[j]);
    }

    $(this.target+' .tagsListZone:first .tagsZone')
    .css({
        'opacity': 0,
        'left':0,
        'top':0,
        'position':'absolute'
    })
    .hide();

    if (this.autoHeight) $(this.target+' .tagsListZone:first .tagsZone').height(y);
    if (this.autoWidth) $(this.target+' .tagsListZone:first .tagsZone').width(x);


    if (!this.menuMode) shadeIt (1);
    // fonction de transition fondu/enchainé :
    function shadeIt (speed, justHide) {
        
        if (!justHide && current==next) return;
        if(current) {
            var currentZone = $(me.target+' .tagsListZone:first > .tagZone'+current);

            if (me.crossTransition) {
                currentZone.css({
                    'position':'absolute'
                });
            }

            currentZone.animate({
                'opacity': 0,
                'z-index':0
            }, {
                queue: !me.crossTransition,
                duration : speed,
                complete : function () {
                    $(this)
                    .css({
                        'position':'absolute'
                    })
                    .hide();
                    if (!me.crossTransition) showNext ();
                }
            });

            $(me.target+' .tagsList:first > .tagListElements > .tagLink'+current).removeClass('taghighlighted');            
        }

        if (me.crossTransition || !current) showNext ();

        function showNext () {          
            
            if (justHide) {
                current=null;
                return;
            }
            
            $(me.target+' .tagsList:first > .tagListElements > .tagLink'+next).addClass('taghighlighted');
            $(me.target+' .tagsListZone:first').addClass('tagsListZoneActive');
             
            $(me.target+' .tagsListZone:first > .tagZone'+next)
            .show()
            .css({
                'z-index':1,
                'position':'relative'
            })
            .animate({
                'opacity': 1,
                'z-index':me.zIndex
            }, {
                duration : speed,
                complete : function () {
                    if (this.style.removeAttribute) this.style.removeAttribute('filter');
                }
            });
        }

        current=next;
    }

    // affichage zone correspondante lors du clic sur un élement du carousel

    switch (this.trigger) {
        case 'hover':
            $(this.target+' .tagsList:first .tagLinks').mouseenter( function(){
                var meAgain = $(this).attr('class'),
                reg = new RegExp ('tagLink(\\d+)', 'g');
                next = parseInt(reg.exec(meAgain)[1], 10);

                if (me.autoSlide) {
                    stopScroll();
                }
                shadeIt (me.slideSpeed);
                        
            }).mouseleave( function(){
        
                if (me.autoSlide && !me.stopAfterFirstClick && !me.menuMode && !focusFlag)  {
                    autoscroll(); 
                }
            });
            break;
        default:
            $(this.target+' .tagsList:first .tagLinks').bind('click', function(){
                var meAgain = $(this).attr('class'),
                reg = new RegExp ('tagLink(\\d+)', 'g');
                next = parseInt(reg.exec(meAgain)[1], 10);

                if (me.autoSlide) {
                    stopScroll();
                }
                if (me.autoSlide && !me.stopAfterFirstClick && !me.menuMode )  {
                    autoscroll();
                }
                shadeIt (me.slideSpeed);
            });
            break;
    } 

    //zone masquer en mode "menu"
    if (this.menuMode) $(this.target).mouseenter(function() {
        
        }).mouseleave(function() {     
        shadeIt (me.slideSpeed, true);
        $(me.target+' .tagsListZone:first').removeClass('tagsListZoneActive');
    });


    //auto défilement
    var focusFlag = false;
    
    function autoscroll () {
        focusFlag=true;
        timeOut = setTimeout (function () {
            next = (next<numberOfItems) ? next+1 : 1;
            shadeIt (me.slideSpeed);
            autoscroll();
        }, me.timeToSlide);
    }
    
    function stopScroll () {
        focusFlag = false;
        clearTimeout (timeOut);
    }
            
    if (this.autoSlide && !this.menuMode) {

        //gestion perte de focus navigateur
        $(window).bind('blur', stopScroll);
        $(window).bind('focus', function () {
            if (!focusFlag) autoscroll();
        });
        if (!focusFlag) autoscroll();

    }
}
