$.fn.extend({
    slide : function () {
        var

        delay = 1000,
        duration = 1000,

        canvas = $(this),

        reel = $('div.sponsors_reel', canvas)
            .append(
                $('div.sponsors_sponsor:first',canvas)
                .clone()
            ),

        container = $('div.sponsors_container',canvas),

        blocks = $('div.sponsors_sponsor', canvas),

        width = 0,
        height = 0,

        cTime = new Date().getTime(),
        startDelay = cTime % delay,
        index = Math.floor((cTime) / delay) % (blocks.length - 1),
        startLeft = 0;

        if (blocks.length < 2) {
            return $(this);
        }

		function init () {

	        $.each(blocks, function (i) {
	            var
	            w = $(this).width(),
	            h = $(this).height();

	            if (i < index) {
	                startLeft += w;
	            }

	            width += w;

	            if (h > height) {
	                height = h;
	            }
	        });

	        reel.css({
	            width: width,
	            left: -startLeft
	        });

	        container.css({
	            height: height < 69 ? 69 : height
	        });

	        function swap(d){
	            var left = parseInt(reel.css('left'));
	            reel
	                .delay(d)
	                .animate({
	                    left : left - $(blocks[index]).width()
	                },duration, function () {

	                    if (index == blocks.length - 1) {
	                        reel.css('left', 0);
	                        index = 0;
	                    }

	                    swap(delay);
	                });

	            index ++;
            
	        }

	        swap(delay - startDelay);
		}
		
		var loaded = 0;
		$.each(blocks, function () {
			$('img',this)
				.one('load', function () {
					
					loaded++;
					
					if (loaded == blocks.length) {
						init();
					}
				})
				
			if ($('img',this).attr('complete')) {
				$('img',this).load();
			}
			
		});

        return $(this);
    }
})

$(function () {
    $('div.tx-sponsors-pi1').slide();
});

