          
(function($) {
    /** album clip view vars **/
    var playlist = [];
    var player = null;
    var prevBtn = null;
    var nextBtn = null;
    var footer = null;
    var clipDetails = null;
    var currentClip = null;

    var opts = {
        carouselPlaylist: null,
        enableJCarousel: true,

        templates: {
            //carousel items
            imageTemplate: '<a href=""></a>',
            videoTemplate: '<a href=""></a>',

            //modal clip
            prevBtn: "<a href='#' class='clipPrev'><span>Previous</span></a>",
            nextBtn: "<a href='#' class='clipNext'><span>Next</span></a>",
            clipDetails: "<div class='clipDetails'>" +
            "   <div><span>${title}</span></div>" +
            "   <div><span>${index} of ${total}</span></div>" +
            "</div>"
        },

        playerKey: null,
        playerURL: null,
        requestURL: null
    };

    $.fn.galleryStrip = function(options) {
        return this.each(function() {

            if (options) {
                $.extend(opts, options);
            }

            //setup modal events
            $(this).children("li").click(function(e) {
                e.preventDefault();
                handleItemClick(this);
                return false;

            });

            //Load JCarousel
            if (opts.enableJCarousel) {
                loadJCarousel($(this));
            }
        });
    };

    /**
    * JCarousel Functions
    **/
    function loadJCarousel(listElement) {
        var wrapType = null;

        if (opts.carouselPlaylist.length > 3) {
            wrapType = 'last';
        }

        listElement.jcarousel({
            wrap: wrapType,
            size: opts.carouselPlaylist.length,
            buttonPrevHTML: '<div><a href="#" onclick="return false;"></a></div>',
            buttonNextHTML: '<div><a href="#" onclick="return false;"></a></div>',
            itemVisibleInCallback: {
                onBeforeAnimation: mycarousel_itemVisibleInCallback
            }
        });
    };

    function mycarousel_itemVisibleInCallback(carousel, item, i, state, evt) {
        if (state == "next") {
            if (i <= opts.carouselPlaylist.length && !carousel.has(i)) {
                carousel.add(i, mycarousel_getItemHTML(opts.carouselPlaylist[i - 1], i - 1));
                item.id = "galAlbum_" + opts.carouselPlaylist[i - 1].albumId + "_" + opts.carouselPlaylist[i - 1].id;

                $(item).click(function(e) {
                    e.preventDefault();
                    handleItemClick(item);
                    return false;
                });
            }
        }
    };

    /**
    * NyroModal Functions
    * When user clicks a jcarousel item a modal box displays
    * all the associated images for that album.
    **/
    function handleItemClick(carouselItem) {
        if (opts.requestURL != null && $.nyroModalManual) {
            //get IDs of 'li' and 'a'
            var albumId = carouselItem.id.split("_")[1];
            var title = $(carouselItem).attr("title");

            $.get(opts.requestURL,
                { "categoryName": title, "categoryId": albumId },
                function(albumInfo) {

                    if (albumInfo && albumInfo.playlist) {
                        var modalContent = "<div><div class=\"flowplayer\" style=\"display:none;height:350px;\"></div></div>";
                        $.nyroModalManual({
                            width: 500,
                            height: 430,
                            content: modalContent,
                            playlist: albumInfo.playlist,
                            selectedIndex: albumInfo.selectedIndex,
                            endFillContent: function(elts, settings) {
                                setPlayerData(settings.playlist, albumInfo.selectedIndex, elts.content);
                            },
                            endShowContent: function(elts, settings) {

                                if (currentClip.type != "video") {
                                    setTimeout(function() { resizeModal(elts.content); }, 500);
                                }
                                player.play(currentClip);
                            },
                            hideContent: function(elts, settings, callback) {
                                try {
                                    if (player && player.isPlaying()) {
                                        player.stop();
                                        player.unload();
                                    }
                                } catch (e) { }
                                setTimeout(callback, 500);
                            }
                        });
                    }
                },
                "json");
        }
    }

    function setPlayerData(newPlaylist, selectedIndex, container) {

        var clipIdx = 0;
        var newClip = null;

        if (selectedIndex != null && selectedIndex >= 0 && selectedIndex < newPlaylist.length) {
            clipIdx = selectedIndex;
        }
        playlist = newPlaylist;


        $f($(".flowplayer", container).get(0), opts.playerURL, {
            key: opts.playerKey,
            plugins: {
                controls: {
                    backgroundColor: '#9d0101',
                    bufferColor: '#000000',
                    buttonOverColor: '#000000',
                    sliderColor: '#000000',
                    progressGradient: 'medium',
                    borderRadius: '0px',
                    durationColor: '#ffffff',
                    progressColor: '#000000',
                    opacity: 1.0
                }
            },

            onFinish: function() { this.stop(); }
        });

        player = $f($(".flowplayer", container).get(0));
        if (player) {
            currentClip = playlist[clipIdx];

            if (currentClip) {
                var playerContainer = $(".flowplayer", container);
                var clipImage = $(".flowplayer", container).next("img");
                if (clipImage.length == 0) {
                    clipImage = $("<img src=\"\" alt\"\"/>");
                    playerContainer.after(clipImage);
                }

                if (currentClip.type == "image") {
                    playerContainer.hide();
                    clipImage.attr("src", currentClip.url);
                    clipImage.fadeIn(opts.fadeSpeed);
                }
                else {
                    clipImage.hide();
                    playerContainer.fadeIn(opts.fadeSpeed);
                }
                clipDetails = $(opts.templates.clipDetails);
                footer = $("<div class='footergallery'></div>").append(clipDetails);
                container.append(footer);
                setDetails(footer);
                setNavCSS(playlist.length, null, clipIdx, footer);

                if (prevBtn != null) {
                    prevBtn.click(function() {
                        return play(currentClip.index - 1, container);
                    });
                }

                if (nextBtn != null) {
                    nextBtn.click(function() {
                        return play(currentClip.index + 1, container);
                    });
                }
            }
        }
    }

    function setDetails(container) {
        if (container && player) {
            var maxLength = playlist.length;
            var elemHtml = opts.templates.clipDetails;
            var currentIndex = currentClip.index + 1;
            //fix index
            elemHtml = elemHtml.replace("$\{index\}", currentIndex).replace("$%7Bindex%7D", currentIndex);
            elemHtml = elemHtml.replace("$\{albumTitle\}", currentClip.albumTitle).replace("$%7albumTitle%7D", currentClip.albumTitle);
            elemHtml = elemHtml.replace("$\{total\}", maxLength).replace("$%7Btotal%7D", maxLength);

            $.each(currentClip, function(key, val) {
                elemHtml = elemHtml.replace("$\{" + key + "\}", val).replace("$%7B" + key + "%7D", val);
            });

            clipDetails.html(elemHtml);

        }
    }

    function setNavCSS(maxLength, prevClipIdx, currClipIdx, container) {
        var btnWrap = $("div.clipNavBtns", container);

        if (btnWrap.length == 0) {
            btnWrap = $("<div class='clipNavBtns'></div>");
            prevBtn = $(opts.templates.prevBtn);
            nextBtn = $(opts.templates.nextBtn);

            btnWrap.append(prevBtn);
            btnWrap.append(nextBtn);
            container.append(btnWrap);
        }

        $(prevBtn).removeClass("selected");
        if (currClipIdx == 0) {
            $(prevBtn).addClass("disabled");
        }
        else {
            $(prevBtn).removeClass("disabled");
            if (prevClipIdx && prevClipIdx > currClipIdx) {
                $(prevBtn).addClass("selected");
            }
        }

        $(nextBtn).removeClass("selected");
        if (currClipIdx >= maxLength) {
            $(nextBtn).addClass("disabled");
        }
        else {
            $(nextBtn).removeClass("disabled");
            if (prevClipIdx && prevClipIdx < currClipIdx) {
                $(nextBtn).addClass("selected");
            }
        }
    }

    function resizeModal(container) {
        var img = new Image();
        var footerHeight = $(".footergallery", container).outerHeight();

        if (currentClip.type == "image") {
            img.src = currentClip.url;
        }
        else {
            img.src = currentClip.splash;
            footerHeight += 10;
        }

        if (img.width == 0) {
            img.onload = function() {
                var w = img.width;
                var h = img.height + footerHeight;
                $(".flowplayer", container).height(img.height);
                $.nyroModalSettings({ width: w, height: h });
            }
        }
        else {
            var w = img.width;
            var h = img.height + footerHeight;
            $(".flowplayer", container).height(img.height);
            $.nyroModalSettings({ width: w, height: h });
        }
    }

    function play(clipIndex, container) {

        var maxLength = playlist.length;
        var oldClip = currentClip;

        if (clipIndex >= 0 && clipIndex < maxLength) {

            currentClip = playlist[clipIndex];

            var playerContainer = $(".flowplayer", container);
            var clipImage = $(".flowplayer", container).next("img");

            setDetails(footer);

            if (currentClip.type == "image") {
                if (oldClip.type == "video") {
                    if (player.isPlaying()) {
                        player.pause();
                    }

                    playerContainer.hide();
                    clipImage.attr("src", currentClip.url);
                    clipImage.fadeIn(opts.fadeSpeed * 2);
                }
                else {
                    clipImage.fadeOut(opts.fadeSpeed,
                    function() {
                        clipImage.attr("src", currentClip.url);
                        clipImage.fadeIn(opts.fadeSpeed);
                    });
                }
            }
            else {

                clipImage.fadeOut(opts.fadeSpeed,
                    function() {
                        playerContainer.fadeIn(opts.fadeSpeed, function() {
                            player.play(currentClip);
                        });
                    });
            }

        }

        setNavCSS(maxLength, oldClip.index, currentClip.index, footer);
        resizeModal(container);

        return false;
    }
    /**
    * Item html creation helper.
    */
    function mycarousel_getItemHTML(item, idx) {
        var itemHtml = opts.templates.imageTemplate;
        if (item.type && item.type == "video") {
            itemHtml = opts.templates.videoTemplate;
        }

        $.each(item, function(key, val) {
            itemHtml = itemHtml.replace("$\{" + key + "\}", val).replace("$%7B" + key + "%7D", val);
        });

        return itemHtml;
    };



})(jQuery);

$(function() {

    $('a.galleryItemModal').nyroModal({
        endFillContent: function(elts, settings) {
            var fpKey = $(document).data("flowplayerKey");
            var playerURL = $(document).data("flowplayer");
            var movieURL = $(".fpSingle", elts.content).text();
            $f($(".fpSingle", elts.content).get(0), playerURL, {
                key: fpKey,
                clip: {
                    scaling: 'orig',
                    autoPlay: true,
                    url: movieURL
                },

                plugins: {
                    controls: {
                        backgroundColor: '#9d0101',
                        bufferColor: '#000000',
                        buttonOverColor: '#000000',
                        sliderColor: '#000000',
                        progressGradient: 'medium',
                        borderRadius: '0px',
                        durationColor: '#ffffff',
                        progressColor: '#000000',
                        opacity: 1.0
                    }
                },

                onFinish: function() { this.stop(); }
            });
        },
        endShowContent: function(elts, settings) {
            $f($(".fpSingle", elts.content).get(0)).play();
            FB.XFBML.parse();///This loads the facebook share button.
        },
        hideContent: function(elts, settings, callback) {
            try {
                var player = $f($(".fpSingle", elts.content).get(0));
                if (player && player.isPlaying()) {
                    player.pause();
                    player.unload();
                }
            } catch (e) { }
            setTimeout(callback, 500);
        }
    });
});
