/**
*  jQuery Rotator Plugin
*  @requires jQuery v1.2.6 or greater
*  http://hernan.amiune.com/labs
*
*  Copyright (c)  Hernan Amiune (hernan.amiune.com)
*  Licensed under MIT license:
*  http://www.opensource.org/licenses/mit-license.php
*
*  Version: 1.0
*/

(function ($) {
    $.fn.rotator = function (options) {

        var defaults = {
            msb4start: 1000,
            msAnim: 500,
            msPause: 500,
            n: 1,
            autoHeight: false
        };
                
        var options = $.extend(defaults, options);

        if (options.msPause < 60) { options.msPause = 60; }

        return this.each(function (index) {

            var $this = $(this);

            var initialHeight = 0;
            $this.children().filter(":lt(" + options.n + ")").each(function (index, item) {
                initialHeight += $(item).height();
            });

            $this.height(initialHeight);

            function rotate() {
                var childHeight = $this.children().filter(":first-child").height();
                var animParams = { scrollTop: (childHeight) + "px" };
                var autoHeight = 0;
                $this.children().filter(":lt(" + (options.n + 1) + ")").each(function (index, item) {
                    if (index > 0) {
                        autoHeight += $(item).height();
                    }
                });
                if (options.autoHeight) {
                    animParams = $.extend({ height: (autoHeight) + "px" }, animParams);
                }

                if (!$this.data("animating")) {
                    //Start animating
                    $this.data("animating", true);
                    $this.animate(animParams, options.msAnim, function () {
                        $this.append($this.children().filter(":first-child"));
                        $this.scrollTop(0);
                        $this.css("overflow", "hidden"); //Chrome hack
                        // Stop animating
                        $this.data("animating", false);
                    });
                }
            };

            function beginRotation() {
                if (!$this.data("started")) {
                    $this.data("started", true);
                    rotate();
                    if ($this.data("started")) {
                        $this.data("timer", setInterval(rotate, options.msPause + options.msAnim));
                    }
                }
            }

            $this.mouseenter(function () {
                $this.data("started", false);
                clearTimeout($this.data("timer"));
            });

            $this.mouseleave(function () {
                beginRotation();
            });

            // Start rotating
            $this.css("overflow", "hidden"); //Chrome hack
            $this.data("timer", setTimeout(beginRotation, options.msb4start));
        });


    }
})(jQuery);
