
(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 = {
        templates: {
            //carousel items
            imageTemplate: '<a href=""></a>',
            videoTemplate: '<a href=""></a>',
            playlist: null,
            //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
    };

    $.fn.galleryItems = function(options) {
        return this.each(function() {

            if (options) {
                $.extend(opts, options);
            }
            playlist = opts.albumInfo.playlist;
            if (playlist.length != 0) {
                currentClip = playlist[0];
            }
            //setup modal events
            $(this).children("li").click(function(e) {
                e.preventDefault();
                handleItemClick(this);
                return false;

            });
        });
    };

    /**
    * NyroModal Functions
    * When user clicks a jcarousel item a modal box displays
    * all the associated images for that album.
    **/
    function handleItemClick(listItem) {
        if ($.nyroModalManual) {
            //get IDs of 'li' and 'a'
            var index = $(listItem).find("a:first").attr("id").split("_")[1];
            //console.log($(listItem).find("a:first").attr("href"));
            var modalContent = "<div><div class=\"flowplayer\" style=\"display:none;height:350px;\"></div></div>";
            $.nyroModalManual({
                width: 500,
                height: 400,
                content: modalContent,
                endFillContent: function(elts, settings) {
                    setPlayerData(index, 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);
                }
            });
        }
    }

    function setPlayerData(selectedIndex, container) {
        var clipIdx = 0;
        var newClip = null;

        if (selectedIndex != null && selectedIndex >= 0 && selectedIndex < playlist.length) {
            clipIdx = selectedIndex;
        }

        $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 && playlist.length > 1) {
                    prevBtn.click(function() {
                        return play(currentClip.index - 1, container);
                    });
                }

                if (nextBtn != null && playlist.length > 1) {
                    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);
