var carouselElmNumber = 6; // configure here the number of screens in the carousel !!!

(function($) {
    
    // carousel callbacks
    function carousel_initCallback(carousel) {
        
        setTimeout(function() {carousel.startAuto(6);},3000);
        
        jQuery('.jcarousel-control a').bind('click', function() {
            carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
            return false;
        });
        
        jQuery('#lacostecarousel-next').bind('click', function(e) {
            carousel.next();
            e.preventDefault();
            return false;
        });
    
        jQuery('#lacostecarousel-prev').bind('click', function() {
            carousel.prev();
            return false;
        });
        // Pause autoscrolling if the user moves with the cursor over the clip.
        carousel.clip.hover(function() {
            carousel.stopAuto();
        }, function() {
            if ($("#expand").size()) {return}
            carousel.startAuto(6);
        });
    
    };

    function handleCarouselControls(carousel, item) {
        var elementIndex = (item.getAttribute('jcarouselindex') - 1) % carouselElmNumber;
        $('.jcarousel-control a').removeClass('on');
        $('.jcarousel-control a').eq(elementIndex).addClass('on');
    }


    
    // add an "id" attribute on HTML element to help distinguish 
    // in CSS when JS is available (accessibility without JS)
    window.document.documentElement.id = 'js';
    
    var focus, focusPos, section, expand, expandLeft, opener, busy, zoom, loaderRef, timeout, loaded = {}, zoomWidth = 300, mainVisualHeight = 420;
    var expandHTML = [
        '<div id="expand" style="left:{$pos}px;">',
            '<div id="expandInner">',
                '<div id="expandContent">',
                    '{$load}',
                    '<a href="{$href}">',
                        '<span class="infos">',
                            '{$infos}',
                        '</span>',
                    '</a>',
                '</div>',
                '<span class="end"></span>',
            '</div>',
        '</div>'
    ];
    var loader = '<span class="loader"></span>';
    // textual informations (such as "Currently loading" above) should not be hardcoded
    // in this file, but should be in a dictionnary file (for example l10n-en-gb.js or i18n-en-gb.js)
    // that can be dynamised and called depending on the language
    
    // extract datas from classes written in the following format:
    // nfo[param1=value1;param2=value2â€¦]
    // jQuery plugin
    $.fn.getNFO = function(key) {
        var datas = null;
        if(this.length) {
            var cls = this[0].className, tmp;
            if(cls && cls.indexOf('nfo[') > -1) {
                if(typeof key == 'string') {
                    var re = new RegExp(key + '=([^;\\]]+)');
                    tmp = cls.match(re);
                    datas = tmp && tmp[1];
                } else {
                    datas = {};
                    var nfo = cls.replace(/.*nfo\[([^)]+)\].*/, '$1');
                    var nfoParts = nfo.split(';');
                    var i = nfoParts.length, l = i - 1;
                    while(i--) {
                        tmp = nfoParts[i].split('=');
                        datas[tmp[0]] = tmp[1];
                    }
                }
            }
        }
        return datas;
    };
    
    // preload an image
    function preload(src, id, ref) {
        var img = document.createElement('img');
        img.onload = function() {
            loaded[src] = true;
            preloadReady(this.src, this.width, this.height, id, ref);
        };
        img.src = src;
        // close zoom when click on main image
        $('.imgVisual').bind('click', function(e){    
            var elmToClose = $(this).prev().find('a.expanded');
            if(elmToClose.length < 1) return;
            closeExpand(elmToClose);
            e.preventDefault();
            return false;
        });
            
    }
    
    // take an action when an image has finished preloading
    function preloadReady(src, w, h, id, ref) {
        if(id == 'main') {
            $('<img class="imgVisual" alt="" src="' + src + '" style="display:none;" />').appendTo(ref).fadeIn(300, function() {
                section.addClass('ready');
                if(loaderRef){
                    loaderRef.remove();
                    loaderRef = null;
                }
            });
            
            // close zoom when click on main image
            /*
            var thisExpand = ref.find('a').eq(0);            
            var thisImg = section.find('.imgVisual');  
            $(thisImg).live('click', function(e){    
                closeExpand(thisExpand);
                e.preventDefault();
                return false;
            });*/
            
        } else if(id == 'zoom') {
            zoom = {src: src, width: w, height: h};
            if(!busy && expand && expand.length) {
                addZoomImg();
            }
        }
    }
    
    // add zoomed image when it is ready
    function addZoomImg() {
        $('#lacostecarousel').jcarousel('stopAuto');
        expand.find('span.loader').remove();
        var top = - (zoom.height - mainVisualHeight) / 2, left = - (zoom.width - zoomWidth) / 2;
        zoom.img = $('<img alt="" src="' + zoom.src + '" style="display:none; top:' + top + 'px; left:' + left + 'px;" />').appendTo(expand.find('#expandContent')).fadeIn(300, function() {
            addMoveImg();
        });
    }
    
    // add zoom moving capabilities
    var timerZoom;
    function addMoveImg() {
        var mCurrentX, mCurrentY, mStartX = zoom.img.css('left'), mStartY = zoom.img.css('top'), tX = 0, tY = 0, top, left;
        var acc = 10, dec = 12;
        var maskW = 300, maskH = 420;
        var img = zoom.img[0], imgW = img.width, imgH = img.height;
        var expandOffset = expand.offset();
        
        expand.find('#expandContent').bind('mousemove.moveImg', function(e) {
            mCurrentX = e.pageX - expandOffset.left;
            mCurrentY = e.pageY - expandOffset.top;
        });
        
        timerZoom = window.setInterval(function() {
            if(imgW > maskW && typeof mCurrentX == 'number') {
                if(mCurrentX > (maskW - 20)) {
                    mCurrentX = maskW;
                } else if(mCurrentX < 20) {
                    mCurrentX = 0;
                }
                
                tX = tX + (mCurrentX - tX) / dec;
                
                left = tX - (tX * imgW) / maskW;
                img.style.left = left + 'px';
            }
            
            if(imgH > maskH && typeof mCurrentY == 'number') {
                if(mCurrentY > (maskH - 20)) {
                    mCurrentY = maskH;
                } else if(mCurrentY < 20) {
                    mCurrentY = 0;
                }
                
                tY = tY + (mCurrentY - tY) / dec;
                
                top = tY - (tY * imgH) / maskH;
                img.style.top = top + 'px';
            }
        }, 30);
    }
    
    // open expand with zoomed image
    function openExpand(elm) {
        // if an expand is already opened, destroy it
        if(expand && expand.length) {
            expand.remove();
            expand = null;
            opener.addClass('expand').removeClass('expanded');
        }
        
        opener = $(elm);
        
        var src = opener.addClass('expanded').removeClass('expand').getNFO('img');
        
        expandLeft = parseInt(elm.parentNode.style.left, 10) + 20;
        expandTop = parseInt(elm.parentNode.style.top, 10);
        var html = expandHTML.join('').replace('{$pos}', expandLeft).replace('{$href}', elm.href).replace('{$infos}', elm.innerHTML);
        // should also check here where the expand can open
        // by default on the right, but we need to also be able to open it on the left
        
        if(loaded[src]) {
            html = html.replace('{$load}', '');
        } else {
            html = html.replace('{$load}', loader);
            preload(src, 'zoom');
        }

        expand = $(html).appendTo(focus);
        busy = true;
        expand.find('#expandInner').animate({left: 0}, 300, function() {
            busy = false;
            if(loaded[src]) {
                addZoomImg();
            }
            expand.find('.infos').css({
                top: expandTop+'px',
                bottom: 'auto'
            })
        });
    }
    
    function closeExpand(elm) {
        /*if(!expand) {
            return;
        } else {*/
        
        expand.find('#expandContent').unbind('mousemove.moveImg');
        window.clearInterval(timerZoom);
        
        expand.find('#expandInner').animate({left: -400}, 300, function() {
            if(!expand) return;
            expand.remove();
            expand = null;
            //this.remove();
        });
        $(elm).parents('ul').find('a').removeClass('expanded');
        $(elm).addClass('expand');
        //}
        
        $('#lacostecarousel').jcarousel('startAuto', '6');
    } 




    // take some action when document is ready
    $(window.document).ready(function() {
        carouselElmNumber = $('#lacostecarousel li.section').length, i = 0, carouselPages = [];
        for(var i = 0; i < carouselElmNumber; i++) {
            carouselPages[i] = '<a href="#">' + (i + 1) + '</a>';
        }
        $('#lacostecarousel div.jcarousel-control').append(carouselPages.join(''));
        
        focus = $('#focus');
        focusPos = focus.offset();
        
        $('#focus a.expand').click(function(e) {
            // prevent default action (follow href)
            e.preventDefault();
            
            if(this.className.indexOf('expanded') > -1) {
                closeExpand(this);
                jQuery('#lacostecarousel').jcarousel('startAuto','6'); // start again autostart when zoom closes
                
            } else {
                openExpand(this);
                jQuery('#lacostecarousel').jcarousel('stopAuto'); // stop autostart when zoom opens
            }
        });
        
        $('.jcarousel-scroll a').click(function(e){
                    if (!expand) return;    
                    var zoomExpanded = $(this).parent().prev().find('a.expanded');
                    closeExpand(zoomExpanded);
                    e.preventDefault();
                    return false;
                });
        $('.jcarousel-control a').click(function(e){    
                    if (!expand) return;
                    var zoomExpanded = $(this).parent().next().find('a.expanded');
                    closeExpand(zoomExpanded);
                    e.preventDefault();
                    return false;
                });
     

        
        // get the first <div class="section">…
        //section = focus.find('li.section').eq(0);
        section = focus.find('li.section');
        // display a loader…
        loaderRef = $(loader).appendTo(focus);
        // and preload the image linked in the special class name nfo[…]
        //preload(section.getNFO('img'), 'main');
        
        focus.find('li.section').each(function(){
            preload($(this).getNFO('img'), 'main', $(this)); 
        });
            
        $('#lacostecarousel').jcarousel({
            scroll: 1,
            size: carouselElmNumber,
            wrap: 'circular',
            initCallback: carousel_initCallback,
            itemVisibleInCallback: handleCarouselControls,
            auto: 6,
            buttonNextHTML: null,
            buttonPrevHTML: null
        });
        
    });    

})(jQuery);


