/* Copyright (c) 2008 Kean Loong Tan http://www.gimiti.com/kltan
 * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * jFlow
 * Version: 1.0 (May 13, 2008)
 * Requires: jQuery 1.2+
 * MAJOR CHANGES BY: Christopher Gooley, 2010-2011, (http://iterat.ive.ly) for FolioHD (http://foliohd.com)
 */
 
(function ($) {

    $.fn.jFlow = function (options) {
        var opts = $.extend({}, $.fn.jFlow.defaults, options);
        var cur = 0;
        var maxi = $(".jFlowControl").length;

        var lastLoggedShortcode = null;

        var timer;
        var goSlideshow = function () {
            goNext(true);
        };

        var stopSlideshow = function () {
            clearTimeout(timer);
            clearTimeout(waitingForImage);
        };

        var displayedSlide = function (cur) {
            var idxid = $(".jFlowControl").eq(cur).attr("href");
            var shortcode = idxid.substr(idxid.lastIndexOf("#") + 1);
            //console.log("logging view of: " + shortcode + " / " + cur);

            if (lastLoggedShortcode != shortcode) {
                // log it
                jQuery.get("/t/m/" + shortcode);
                // don't log it again immediately
                lastLoggedShortcode = shortcode;
            }

            if (opts.onChange) { opts.onChange(); }
        };


        if (opts.imagecontainer) {
            $(opts.imagecontainer).css({ height: "auto" });
        }

        $(this).find(".jFlowControl").each(function (i) {
            $(this).unbind("click");
            $(this).click(function () {
                stopSlideshow(); // if we click on it, we need to stop moving around
                $(".jFlowControl").removeClass("jFlowSelected");
                $(this).addClass("jFlowSelected");
                var dur = Math.abs(cur - i + 1);

                if (dur >= 3) dur = 3; // handle big jumps in images
                if (dur <= 0) dur = 1; // error correction

                $(opts.slides).animate({
                    marginLeft: "-" + (i * $(opts.slides).find(":first-child").width() + "px")
                }, opts.duration * (dur));

                if (opts.autoheight) {
                    var img = $(opts.slides).children().eq(i).find("img").get(0);

                    var newh = img.height;
                    if ($(opts.slides).children().eq(i).find(".video-embed").is(":visible")) {
                        newh = $(opts.slides).children().eq(i).find(".video-embed").height();
                        //console.log("video embed: " + newh);
                    }

                    //console.log("newh: " + newh);
                    if (img.complete || newh > 0) {
                        $("#jFlowSlide").animate({
                            height: newh + "px"
                        }, opts.duration);
                    } else {
                        $("#jFlowSlide").css({ height: opts.height });
                        // reload again in a little bit
                        var self = this;
                        waitingForImage = setTimeout(function () { $(self).click(); }, 300);
                    }
                }

                displayedSlide(i);

                cur = i;
            });
        });

        $(opts.slides).before('<div id="jFlowSlide"></div>').appendTo("#jFlowSlide");

        $(opts.slides).find("div").each(function () {
            $(this).before('<div class="jFlowSlideContainer"></div>').appendTo($(this).prev());
        });

        //initialize the controller
        $(".jFlowControl").eq(cur).addClass("jFlowSelected");

        var waitingForImage = null;

        var resize = function (x) {
            //console.log("resizing!");
            $("#jFlowSlide").css({
                position: "relative",
                width: opts.width,
                height: opts.height,
                overflow: "hidden"
            });

            // for auto-height
            if (opts.autoheight) {
                var img = $(opts.slides).find("div:first img").get(0);

                var newh = img.height;
                if ($(opts.slides).find("div:first .video-embed").is(":visible")) {
                    newh = $(opts.slides).find("div:first .video-embed").height();
                    //console.log("video embed: " + newh);
                }

                if (img.complete || newh > 0) {
                    $("#jFlowSlide").css({
                        height: newh + "px"
                    });
                } else {
                    waitingForImage = setTimeout(resize, 300);
                    //console.log("delaying resize");
                }
            }

            $(opts.slides).css({
                position: "relative",
                width: $("#jFlowSlide").width() * $(".jFlowControl").length + "px",
                //height: $("#jFlowSlide").height() + "px",
                overflow: "hidden"
            });

            $(opts.slides).children().css({
                position: "relative",
                width: $("#jFlowSlide").width() + "px",
                //height: $("#jFlowSlide").height() + "px",
                "float": "left"
            });

            $(opts.slides).css({
                marginLeft: "-" + (cur * $(opts.slides).find(":first-child").width() + "px")
            });
        }

        resize();

        if (!opts.autoheight) {
            $(window).resize(function () {
                resize();
            });
        }

        var goPrev = function () {
            if (cur > 0)
                cur--;
            else
                cur = maxi - 1;

            $(".jFlowControl").removeClass("jFlowSelected");
            $(opts.slides).animate({
                marginLeft: "-" + (cur * $(opts.slides).find(":first-child").width() + "px")
            }, opts.duration);

            //            if (opts.autoheight) {
            //                var newh = $(opts.slides).children().eq(cur).find("img").get(0).height;
            //                if ($(opts.slides).children().eq(cur).find(".video-embed").is(":visible")) {
            //                    newh = $(opts.slides).children().eq(cur).find(".video-embed").height();
            //                    console.log("go prev embed h: " + newh);
            //                }

            //                $("#jFlowSlide").animate({
            //                    height: newh + "px"
            //                }, opts.duration);
            //            }

            //            movedSlide($(".jFlowControl").eq(cur));
            $(".jFlowControl").eq(cur).addClass("jFlowSelected");
        };

        var goNext = function (andContinue) {
            if (cur < maxi - 1)
                cur++;
            else
                cur = 0;

            $(".jFlowControl").removeClass("jFlowSelected");
            $(opts.slides).animate({
                marginLeft: "-" + (cur * $(opts.slides).find(":first-child").width() + "px")
            }, opts.duration, function () {
                // when complete, if we want to continue set the timer up
                if (andContinue) {
                    clearTimeout(timer);
                    timer = setTimeout(goSlideshow, opts.autoscrolldelay);
                }
            });

            //            if (opts.autoheight) {
            //                var newh = $(opts.slides).children().eq(cur).find("img").get(0).height;
            //                if ($(opts.slides).children().eq(cur).find(".video-embed").is(":visible")) {
            //                    newh = $(opts.slides).children().eq(cur).find(".video-embed").height();
            //                    console.log("go next embed h: " + newh);
            //                }

            //                $("#jFlowSlide").animate({
            //                    height: newh + "px"
            //                }, opts.duration);
            //            }

            //            movedSlide($(".jFlowControl").eq(cur));
            $(".jFlowControl").eq(cur).addClass("jFlowSelected");
        };

        $(".jFlowPrev").click(function () {
            stopSlideshow(); // if we interact, we need to stop moving around
            goPrev();
            location.hash = $(".jFlowSelected").attr("href");
        });

        $(".jFlowNext").click(function () {
            stopSlideshow(); // if we interact, we need to stop moving around
            goNext();
            location.hash = $(".jFlowSelected").attr("href");
        });

        // initialize the bookmark in the url hash
        if (location.href.lastIndexOf("#") > 0) {
            var jumpid = location.href.substr(location.href.lastIndexOf("#") + 1);
            $(this).find("#idx-" + jumpid).click();
            opts.autoscroll = false; // disable autoscroll if we are jumping around automatically
        } else {
            displayedSlide(0);
        }

        // Alerts every time the hash changes!
        $(window).bind('hashchange', function () {
            var jumpid = location.hash.substr(1);
            if (jumpid) {
                // go to specified image
                $("#idx-" + jumpid).click();
            }
            else {
                // reset to first image (no hash tag = index 1)                
                $(".jFlowControl:first").click();
            }
        })

        if (opts.autoscroll) {
            timer = setTimeout(goSlideshow, opts.autoscrolldelay);
            //console.log("autoscroll delay");
        }

    };

    $.fn.jFlow.defaults = {
        easing: "swing",
        duration: 400,
        width: "100%",
        autoscroll: false,
        autoscrolldelay: 5000,
        clickadvance: true,
        autoheight: false,
        onChange: null
    };

})(jQuery);

