jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
    random: function(a, i, m, r) {
        if (i == 0) {
            jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
        };
        return i == jQuery.jQueryRandom;
    }
});

$.fn.pause = function(duration) {
    $(this).animate({ dummy: 1 }, duration);
    return this;
};

;(function($){
	$.fn.simplecycle = function(images) {
		this.images = images;
		
		var that = this;
		
		if ($(this.images + ' img').size() < ($(this.selector).length)*2){
			clone = true;
		} else {
			clone = false;
		}
		
		var updater = function(i, v, part){
			
			target = $(this);
			image_store = $(that.images);
			
			if(clone){
				image = target.find('img');
				if (image){
					$(image).clone().appendTo(image_store);
				}
			}
			
			image = $(that.images + " img").get().sort(function(){ 
			  return Math.round(Math.random())-0.5
			})[0];
			
			$(image).show();
			old_image = target.find('img')[0]
			if (old_image) {
				$(old_image).before($(image));
			} else {
				target.append(image);
			}
			
			if (old_image) {
			
				$(old_image).pause(700 * i).fadeOut("slow", function(){
					if (clone) {
						$(this).remove();
					}
					else {
						$(this).appendTo(image_store);
						
					}
				});
			}
						
		}
		
		var loop = function(){
			
			targets = $(that.selector).get().sort(function(){ 
			  return Math.round(Math.random())-0.5
			});
			$.each(targets, updater);
			
			setTimeout(loop, 5000);
			
		}
		
		$(window).load(function(){
			
			targets = $(that.selector).get().sort(function(){ 
			  return Math.round(Math.random())-0.5
			});
			
			$.each(targets, updater);
			
			// waiting for images.
			setTimeout(loop, 500);
		});
		
		
	}
})(jQuery);
