/*=============================    
jquery.barousel_flash.js 
v.0.1
Julien Decaudin - 08/2010
www.juliendecaudin.com
=============================*/

(function ($) {
    $.fn.barousel = function (callerSettings) {
        var settings = $.extend({
            imageWrapper: '.barousel_image',
            contentWrapper: '.barousel_content',
            contentLinksWrapper: null,
            navWrapper: '.barousel_nav',
            slideDuration: 5000,
            navType: 1, //1: boxes navigation; 2: prev/next navigation; 3: custom navigation
            fadeIn: 1,
            fadeInSpeed: 600,
            manualCarousel: 0,
            enableAjaxLoader: 0,
            contentResize: 1,
            contentResizeSpeed: 300,
            ajaxLoaderPath: '/images/ajax-loader.gif',
            random: 0,
            debug: 0
        }, callerSettings || {});

        settings.imageWrapper = $(this).find(settings.imageWrapper);
        settings.contentWrapper = $(this).find(settings.contentWrapper);
        settings.contentLinksWrapper = $(this).find(settings.contentLinksWrapper);
        settings.navWrapper = $(this).find(settings.navWrapper);
        settings.imageList = settings.imageWrapper.find('> div').not('[class*=intro]'); //list of the items' background image (intro image is ignored)
        settings.contentList = settings.contentWrapper.find('> div').not('[class*=intro]'); //list of the items' content (intro content is ignored)
        settings.contentLinksList = settings.contentLinksWrapper.find('a'); //list of the items' content links (optional)
        settings.imageIntro = settings.imageWrapper.find('div[class*=intro]');
        settings.contentIntro = settings.contentWrapper.find('div[class*=intro]');
        settings.currentIndex = 0; //index of the current displayed item
        settings.totalItem = settings.imageList.length; //total number of items
        settings.stopCarousel = 0; //flag to stop the carousel
        settings.timerCarousel; //timer for the carousel
        settings.ajaxLoaderId = "ajax_loader_" + $(this).attr("id");
        settings.navFreeze = 0; //flag to avoid clicking too fast on the nav
        settings.introActive = 0; //flag to know if there is an intro state and if it's active

        if (settings.imageWrapper.find('div[class*=intro]').length > 0) {
            settings.introActive = 1;
        }

        if (settings.totalItem == 1) {
            //$(settings.navWrapper).hide();            
        } else {
            //append the AJAX loader to the content wrapper  
            if (settings.enableAjaxLoader == 1) {
                settings.contentWrapper.prepend('<img id="' + settings.ajaxLoaderId + '" src="' + settings.ajaxLoaderPath + '" class="ajax_loader" alt=""/>');
            }

            //set the index of each image  
            settings.imageList.each(function (n) { this.index = n; });

            //set the index of each content  
            settings.contentList.each(function (n) { this.index = n; });

            //set the index of each content link (optional) 
            settings.contentLinksList.each(function (n) { this.index = n; });

            //return error if different number of images and contents
            if (settings.imageList.length != settings.contentList.length) {
                /* DEBUG */
                if (settings.debug == 1) console.log('[Barousel error] image and content items must be the same number');
                return this;
            }

            //set current index
            //if random set the first item randomly
            if (settings.random == 1) {
                settings.currentIndex = Math.floor(Math.random() * (parseInt(settings.totalItem)));

                $(settings.imageList).removeClass('default');
                $(settings.imageList[settings.currentIndex]).addClass('default');

                $(settings.contentList).removeClass('default');
                $(settings.contentList[settings.currentIndex]).addClass('default');

                /* DEBUG */
                if (settings.debug == 1) {
                    console.log('[Barousel init] settings.totalItem:' + settings.totalItem);
                    console.log('[Barousel init] settings.currentIndex random:' + settings.currentIndex);
                }
            } else {
                //manual                                
                settings.imageList.each(function (n) {
                    if ($(this).hasClass('default')) {
                        settings.currentIndex = n;
                    }
                });
            }

            //hide the default content if empty
            if ($.trim($(settings.contentList[settings.currentIndex]).text()) == "") {
                $(settings.contentWrapper).hide();
            } else {
                //init the default content height
                if (settings.contentResize == 1 && settings.introActive == 0) {
                    $(settings.contentWrapper).height($(settings.contentList[settings.currentIndex]).height() + 10);
                }
            }

            //init the content link default state (optional)
            if (settings.contentLinksWrapper != null) {
                $(settings.contentLinksList[settings.currentIndex]).addClass('current');
            }

            //build the navigation
            if (settings.navType == 1) {
                //items navigation type
                var strNavList = "<ul>";
                settings.imageList.each(function (n) {
                    var currentClass = "";
					var navNumber = n + 1;
                    if (n == settings.currentIndex) currentClass = "current";
                    strNavList += "<li><a href='#' title='" + $(settings.contentList[n]).find('p.header').text() + "' class='" + currentClass + "'> " + navNumber + " </a></li>";
                });
                strNavList += "</ul>";
                settings.navWrapper.append(strNavList);
                settings.navList = settings.navWrapper.find('a'); //list of the items' nav link

                //set the index of each nav link
                settings.navList.each(function (n) { this.index = n; });

            } else if (settings.navType == 2) {
                //prev/next navigation type
                var strNavList = "<ul>";
                strNavList += "<li class='prev'><a href='#' title='previous'>&nbsp;</a></li>";
                strNavList += "<li class='next'><a href='#' title='next'>&nbsp;</a></li>";
                strNavList += "</ul>";
                settings.navWrapper.append(strNavList);
                settings.navList = settings.navWrapper.find('a'); //list of the items' nav link
            } else if (settings.navType == 3) {
                //custom navigation [static build]
                settings.navList = settings.navWrapper.find('a'); //list of the items' nav link
                //set the index of each nav link
                settings.navList.each(function (n) { this.index = n; });
            }

            //init the navigation click event
            if (settings.navType == 1 || settings.navType == 3) {
                //items navigation type
                settings.navList.each(function (n) {
                    $(this).click(function () {
                        if (settings.navFreeze == 0) {
                            window.clearTimeout(settings.timerCarousel);
                            settings.stopCarousel = 1;
                            if (settings.currentIndex != n || settings.introActive == 1) {
                                loadItem(settings, n, function () {
                                    settings.currentIndex = n;
                                });
                            }
                        }
                        settings.introActive = 0;
                        return false;
                    });
                });

            } else if (settings.navType == 2) {
                //prev/next navigation type
                settings.navList.each(function () {
                    $(this).click(function () {
                        if (settings.navFreeze == 0) {
                            window.clearTimeout(settings.timerCarousel);
                            settings.stopCarousel = 1;

                            if ($(this).parent().hasClass('prev')) {
                                var previousIndex;

                                if (parseInt(settings.currentIndex) == 0) {
                                    previousIndex = parseInt(settings.totalItem) - 1;
                                } else {
                                    previousIndex = parseInt(settings.currentIndex) - 1;
                                }
                                loadItem(settings, previousIndex, function () {
                                    settings.currentIndex = previousIndex;
                                });

                            } else if ($(this).parent().hasClass('next')) {
                                var nextIndex;

                                if (parseInt(settings.currentIndex) == (parseInt(settings.totalItem) - 1)) {
                                    nextIndex = 0;
                                } else {
                                    nextIndex = parseInt(settings.currentIndex) + 1;
                                }
                                loadItem(settings, nextIndex, function () {
                                    settings.currentIndex = nextIndex;
                                });
                            }
                        }
                        settings.introActive = 0;
                        return false;
                    });
                });
            }

            //Load Flash if required
            unloadFlashMovie(settings, settings.currentIndex);
            loadFlashMovie(settings, settings.currentIndex);

            //start the carousel
            if (settings.manualCarousel == 0) {
                var nextIndex;

                if (settings.currentIndex == settings.totalItem - 1) {
                    nextIndex = 0;
                } else {
                    nextIndex = parseInt(settings.currentIndex) + 1;
                }

                var loadItemCall = function () { loadItem(settings, nextIndex, null); };
                settings.timerCarousel = window.setTimeout(loadItemCall, settings.slideDuration);
            }
        }

        return this;
    };

    var loadItem = function (settings, index, callback) {
        var previousIndex = settings.currentIndex;

        //reset the nav link current state
        if (settings.navType != 2) {
            settings.navList.each(function (n) { $(this).removeClass('current'); });
            $(settings.navList[index]).addClass('current');
        }

        //Change the background image then display the new content
        var currentImage;
        if (settings.introActive == 1) {
            currentImage = $(settings.imageIntro);
        } else {
            currentImage = $(settings.imageList[settings.currentIndex]);
        }
        var nextImage = $(settings.imageList[index]);

        /* DEBUG */
        if (settings.debug == 1) {
            console.log('[Barousel loadItem] currentImage:' + currentImage.find('img').attr('src'));
            console.log('[Barousel loadItem] nextImage:' + nextImage.find('img').attr('src'));
            console.log('[Barousel loadItem] currentIndex:' + settings.currentIndex);
            console.log('[Barousel loadItem] index:' + index);
        }

        if (!currentImage.hasClass('default')) { currentImage.attr('class', 'previous'); }
        nextImage.attr('class', 'current');

        //fade-in effect
        if (settings.fadeIn == 0) {
            nextImage.show();
            currentImage.hide();
            loadModuleContent(settings, index);
        } else {
            settings.navFreeze = 1;
            $(settings.contentList).hide();
            if (settings.enableAjaxLoader == 1) $('img#' + settings.ajaxLoaderId).show();

            nextImage.fadeIn(settings.fadeInSpeed, function () {
                currentImage.hide();
                currentImage.removeClass('previous');
                if (settings.enableAjaxLoader == 1) {
                    $('img#' + settings.ajaxLoaderId).hide();
                    loadModuleContent(settings, index);
                }

                //Flash movie unload/load
                unloadFlashMovie(settings, previousIndex);
                loadFlashMovie(settings, index);

                settings.navFreeze = 0;
            });
            if (settings.enableAjaxLoader == 0) loadModuleContent(settings, index);
        }

        //carousel functionnality (deactivated when the user click on an item)
        if (settings.stopCarousel == 0) {
            settings.currentIndex = index;
            var nextIndex;

            if (settings.currentIndex == settings.totalItem - 1) {
                nextIndex = 0;
            } else {
                nextIndex = parseInt(settings.currentIndex) + 1;
            }
            var loadItemCall = function () { loadItem(settings, nextIndex, null); };
            settings.timerCarousel = window.setTimeout(loadItemCall, settings.slideDuration);
        }

        //Callback function
        if (typeof callback == "function") callback();
    };

    var loadModuleContent = function (settings, index) {
        if (settings.introActive == 1) {
            $(settings.contentIntro).hide();
            $(settings.contentWrapper).attr('class', '');
        }

        //if content is empty: fade out
        if ($.trim($(settings.contentList[index]).text()) == "") {
            $(settings.contentWrapper).fadeOut('normal');
        } else if ($(settings.contentWrapper).is(':hidden')) {
            //if the content isn't empty but the container hidden: fade in

            //then fade in
            $(settings.contentWrapper).fadeIn('normal', function () {
                //resize first
                if (settings.contentResize == 1) {
                    $(settings.contentWrapper).animate({
                        height: $(settings.contentList[index]).height() + 10
                    }, settings.contentResizeSpeed, function () {
                        loadModuleContentAction(settings, index);
                    });
                } else {
                    loadModuleContentAction(settings, index);
                }
            });
        } else {
            //Resize content        
            if (settings.contentResize == 1 && parseInt($(settings.contentWrapper).height()) != parseInt($(settings.contentList[index]).height() + 10)) {
                $(settings.contentWrapper).animate({
                    height: $(settings.contentList[index]).height() + 10
                }, settings.contentResizeSpeed, function () {
                    loadModuleContentAction(settings, index);
                });
            } else {
                loadModuleContentAction(settings, index);
            }
        }


    };

    var loadModuleContentAction = function (settings, index) {
        //display the loaded content                
        $(settings.contentList).hide();
        $(settings.contentList[index]).show();

        if (settings.contentLinksWrapper != null) {
            $(settings.contentLinksList).removeClass('current');
            $(settings.contentLinksList[index]).addClass('current');
        }
    };

    var loadFlashMovie = function (settings, index) {
        //Load the Flash movie if required
        if ($(settings.imageList[index]).find('div.flash_container').length > 0) {
            if (settings.debug == 1) console.log('+ Flash load: ' + index);

            var path = $(settings.imageList[index]).find('ul.flash_setup li.path').text();
            var containerId = $(settings.imageList[index]).find('ul.flash_setup li.container_id').text();
            var width = $(settings.imageList[index]).find('ul.flash_setup li.width').text();
            var height = $(settings.imageList[index]).find('ul.flash_setup li.height').text();
            var flashVersion = $(settings.imageList[index]).find('ul.flash_setup li.flash_version').text();

            //SWF Object call
            var flashVars = {};
            var flashParams = {
                wmode: "transparent"
            };

            swfobject.embedSWF(path, containerId, width, height, flashVersion, "", flashVars, flashParams, null, function (e) {
                $(settings.imageList[index]).find('img').fadeOut(settings.fadeInSpeed);                
            });

            //$(settings.imageList[index]).find('img').hide();
            //swfobject.embedSWF(path, containerId, width, height, flashVersion, "", flashVars, flashParams);
        }
    }

    var unloadFlashMovie = function (settings, index) {
        //Unload the Flash movie if required
        if ($(settings.imageList[index]).find('div.flash_container').length > 0) {
            if (settings.debug == 1) console.log('- Flash unload: ' + index);

            var containerId = $(settings.imageList[index]).find('ul.flash_setup li.container_id').text();

            $(settings.imageList[index]).find('img').show();
            $(settings.imageList[index]).find('object').remove();
            $(settings.imageList[index]).find('div.flash_container').prepend("<div id='" + containerId + "'></div>");
        }
    }
})(jQuery);
