/**
 * Created by Ivan Aksentijevic
 * Date: 1/26/11
 * Time: 5:16 PM
 */

(function($) {
	$.fn.imgRoll = function(options) {
		var opts = $.extend({}, $.fn.imgRoll.defaults, options || {});
        var rate = 50;
        
        var sliders = [];
        function loop() {
            for (var i = 0; i < sliders.length; i++) { sliders[i](); }
            setTimeout(loop, rate);
        }
        loop();

		return this.each(function() {
            var o = $.metadata ? $.extend({}, opts, $(this).metadata()) : opts;
            var $this = $(this);

            function get_slider() {
                var $list = $this.find('ul');
                var step = o.animate / (rate * 10);

                var imgCount = $this.find('li').size();
                var $li = $this.find('li:first');
                var blockSize, property, canvasSize;
                if (opts.direction == 'horizontal') {
                    canvasSize = $this.width();
                    blockSize = $li.outerWidth(true) * imgCount;
                    property = 'margin-left';
                } else {
                    canvasSize = $this.height();
                    blockSize = $li.outerHeight(true) * imgCount; 
                    property = 'margin-top';
                }

                //number of blocks that fit into wrapping element (each block having a list of images)
                var totalCount = Math.round(canvasSize / blockSize) + 1;
                var viewportWidth = totalCount * blockSize;

                if (opts.direction == 'horizontal') {
                    $list.width((viewportWidth * 2) + 'px');
                } else {
                    $list.height((viewportWidth * 2) + 'px');
                }
                for (var a = 0; a < totalCount * imgCount * 2; a++) {
                    var $a = $this.find('li:eq(' + a + ')').clone().appendTo($list);
                }

                return function() {
                    var position = parseInt($list.css(property)) - step;
                    $list.css(property, position + 'px');
                    if (position <= -viewportWidth) {
                        var inter = position + viewportWidth;
                        $list.css(property, inter + 'px');
                    }
                };
            }

			// Got to wait for image to load, so we can grab the size, problem is that load wont fire in IE if image is cached
            var $img = $this.find('img:first');
            if ($img.complete || $img.width() != 0) {
                sliders.push(get_slider());
            } else {
                $img.load(function() {
                    sliders.push(get_slider());
                });
            }
		});
	};

	$.fn.imgRoll.defaults = {
		'animate': 2500,
        'direction': 'horizontal'
	};

})(jQuery);

