//effect for carousel
jQuery.easing['BounceEaseOut'] = function(p, t, b, c, d) {
    if ((t/=d) < (1/2.75)) {
        return c*(7.5625*t*t) + b;
    } else if (t < (2/2.75)) {
        return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    } else if (t < (2.5/2.75)) {
        return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
    } else {
        return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
    }
};
//deal with facybox title
function formatTitle( title, currentArray, currentIndex, currentOpts)
{
    return '<div id="fancy-title">' + (title && title.length ? '<strong>' + title + '</strong>' : '' )+'</div>';
}
$(document).ready(function() {
    //initialize picture fancybox
    if( $("a.grouped_elements").length )
    {
        $("a.grouped_elements").fancybox({
            'transitionIn'  :   'elastic',
            'transitionOut' :   'elastic',
            'autoDimensions' : true,
            'autoScale':    true,
            'speedIn'       :   600, 
            'speedOut'      :   200, 
            'overlayShow'   :   false,
            'centerOnScroll':   true,
            'showCloseButton'   : true,
            'titlePosition'         : 'inside',
            'titleFormat'       : formatTitle
        });
    }
    
    //initialize video fancybox
    if( $("a.grouped_elements_vid").length )
    {
        $("a.grouped_elements_vid").fancybox({
            'transitionIn'  :   'elastic',
            'transitionOut' :   'elastic',
            'autoDimensions' : true,
            'autoScale':    true,
            'speedIn'       :   600, 
            'speedOut'      :   200, 
            'overlayShow'   :   false,
            'centerOnScroll':   true,
            'type': 'swf',
            'swf'           : { 'wmode': 'transparent', 'allowfullscreen': 'false'},
            'showCloseButton'   : true,
            'titlePosition'         : 'inside',
            'titleFormat'       : formatTitle
        });
    }
    
    //initialize the carousel
    var j = 1 ;
    $('#content').children('.block').each( function(indexBlock){
        if( $( this ).attr( 'class' ) == 'block newsletter' )j++;
        var currentUl = $( this ).find( 'ul' ).get( 0 );
        if( $( currentUl ).length )
        {
            var ulClass = getUlClass( $( currentUl ) );
            setCarousel( ulClass ) ;
            //initialize the bottom controller button
            for( var i = 0 ; i<$( currentUl ).children( 'li' ).length; i++)
            {
                var tmpClass = '.link'+j+'-'+i;
                $( tmpClass ).bind('click', function() {
                    var indexTab = $( this ).attr( 'class' ).split('-');
                    var indexController = parseInt(indexTab[1])+1;
                    $( currentUl ).data('jcarousel').scroll( indexController );
                    $( currentUl ).data('jcarousel').stopAuto();
                });
            }
            j++;
        }
    });
    //initialize format field for contact's email field
    if( $("#warning-email").length)
    {
        $("#warning-email").format({type:"email"},function(){
            if($(this).val()=="") alert("L'email est obligatoire, veuillez remplir ce champ pour nous contacter.");
            else 
            {
                alert("Adresse email incorrecte, veuillez saisir une adresse valide");
                $(this).focus();
            }
        });
    }
 });
//return the unic class identifier of the carousel's ul
 function getUlClass( element )
 {
     var completeClass = $( element ).attr('class') ;
     var completeClassArray = completeClass.split(" ") ;
     var ulClass = '.';
     ulClass += ( completeClassArray.length>0)?completeClassArray[0]:element;
     return ulClass;
 };
 //set the carousel
 function setCarousel( elementIdentifier )//elementIdentifier must be an element a class element or an id element
 {
     $( elementIdentifier ).jcarousel(  {
        vertical : false,
        rtl: false,//Specifies wether the carousel appears in RTL (Right-To-Left) mode (true means left to right).
        scroll : 1,//The number of items to scroll by.
        easing: 'BounceEaseOut',//The name of the easing effect that you want to use.
        animation: 'slow',//The speed of the scroll animation as string in jQuery terms ("slow"  or "fast") or milliseconds as integer. If set to 0, animation is turned off.
        auto : 3,//Specifies how many seconds to periodically autoscroll the content. If set to 0 (default) then autoscrolling is turned off. 
        wrap: 'last',//Specifies whether to wrap at the first/last item (or both) and jump back to the start/end. Options are "first", "last", "both" or "circular" as string. If set to null, wrapping is turned off (default).
        visible : 1,//If passed, the width/height of the items will be calculated and set depending on the width/height of the clipping, so that exactly that number of items will be visible.
        initCallback: mycarousel_initCallback,//JavaScript function that is called right after initialisation of the carousel. Two parameters are passed: The instance of the requesting carousel and the state of the carousel initialisation (init, reset or reload)
        itemFirstInCallback: mycarousel_firstInCallBack,//avaScript function that is called (after the scroll animation) when an item becomes the first one in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li> object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init).
        itemLoadCallback: mycarousel_loadCallback,//JavaScript function that is called when the carousel requests a set of items to be loaded. Two parameters are passed: The instance of the requesting carousel and the state of the carousel action (prev, next or init).
        itemVisibleInCallback: mycarousel_visibleinCallBack,//JavaScript function that is called (after the scroll animation) when an item is in the visible range of the carousel. Four parameters are passed: The instance of the requesting carousel and the <li>  object itself, the index which indicates the position of the item in the list and the state of the carousel action (prev, next or init).
        buttonNextHTML: true,//The HTML markup for the auto-generated next button. If set to null, no next-button is created.
        buttonPrevHTML: true//The HTML markup for the auto-generated prev button. If set to null, no prev-button is created.
    } ) ;
};
//return the carousel's instance in a multi instance carousel including incremented controllers
function getCarousel( carousel )
{
    var result = null;
    $('#content').children('.block').each( function(){
        var currentUl = $( this ).find( 'ul' ).get( 0 );
        if( $( currentUl ).length )
        {
            var UlClass = getUlClass( $( currentUl ) );
            if( carousel == $( UlClass ).data('jcarousel') )
            {
                result = carousel;
                return false;//used to behave like a break operator, it s not a real return which breaks the function, it just breaks the loop
            }
        }
    });
    return result;
};
//return the ul class of a current carousel
function getUlClassFromCarousel( carousel )
{
    var result = '';
    $('#content').children('.block').each( function(i){
        var currentUl = $( this ).find( 'ul' ).get( 0 );
        if( $( currentUl ).length )
        {
            var ulClass = getUlClass( $( currentUl ) );
            if( carousel == $( ulClass ).data('jcarousel') )
            {
                result =  ulClass;
                return false;//used to behave like a break operator, it s not a real return which breaks the function, it just breaks the loop
            }
        }
    });
    return result;
};
//return the carousel index from the #content element, each block classed element has one and only one carouel inside
function getCarouselIndex( carousel )
{
    var result = 0;
    $('#content').children('.block').each( function(i){
        var currentUl = $( this ).find( 'ul' ).get( 0 );
        if( $( currentUl ).length )
        {
            var ulClass = getUlClass( $( currentUl ) );
            if( carousel == $( ulClass ).data('jcarousel') )
            {
                return false;//used to behave like a break operator, it s not a real return which breaks the function, it just breaks the loop
            }
        }
        result++ ;
    });
    return result;
}
//event function to animate the carousel
function mycarousel_initCallback( carousel ) 
{
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
    return false;
};
//function mycarousel_loadCallback
function mycarousel_loadCallback( carousel, state )
{
    styleController( carousel );
    return false;
};
//function mycarousel_firstInCallBack
function mycarousel_firstInCallBack( carousel, liItem, index, state )
 {
    
 };
//callback function used in the carousel function, this one enables to stop and start carousel when mouse is over and out
function mycarousel_visibleinCallBack( carousel, liItem, index, state )
{
    //bind mouse events on classed suite elements to stop or start the carousel.
    var indexCarousel = getCarouselIndex( carousel );
    var currentBlock = $('#content').find('.block').get( indexCarousel );
    var targetSuite = $( currentBlock ).find('.suite').get(0);
    $( targetSuite ).bind('mouseover mouseout', function(event) {
        switch(event.type)
        {
            case 'mouseover':
                carousel.stopAuto();
            break;
            case 'mouseout':
                carousel.startAuto();
            break;
        }
        return false;
    });
    dynamicUrl( carousel, index );
};
 //this function enables to change color of the carousel's bottom controller dynamically
 function styleController( carousel )
 { 
    var indexCarousel = getCarouselIndex( carousel );
    var currentBlock = $('#content').find('.block').get( indexCarousel );
    var aLinkArray = $( currentBlock ).find('#idController');
    $( aLinkArray ).each(function(index,element){
        this.style.backgroundColor = "#4088B8";
        this.style.color = "#ffffff";
        if($(this).text()==carousel.first)
        {
            this.style.backgroundColor = "#ffffff";
            this.style.color = "#4088B8";
        }
    });
 };
 //this function enabled to change the url of the  classed 'suite' element
function dynamicUrl( carousel, index )
{
    //write dynamic url in specific target from the current content of the carousel.
    var indexCarousel = getCarouselIndex( carousel );
    var currentBlock = $('#content').find('.block').get( indexCarousel );
    if( typeof $( currentBlock ) !== "undefined" && $( currentBlock ) )
    {
        var h2Tag =$(  currentBlock ).find( 'h2' ).get( index-1 )
        if( typeof $( h2Tag ) !== "undefined" && $( h2Tag ) )
        {
            var aLink = $( h2Tag ).find('a').get( 0 );//query dom function to get the first child 'a' in the current h2
            if( $(aLink).attr('class') != "solo" )//solo manage the unic article block
            {
                var targetSuite = $( currentBlock ).find('.suite').get(0);
                $( targetSuite ).attr("href",$(aLink).attr('href'));
            }
            return false;
        }
    }   
};



