(function($) {
	$.fn.extend({ imgFlow:function(){
		return this.each(function(){
			var element=this;
			var speed=0;
			$(element).css("overflow","hidden");
			$(document).mousemove(mouseMove);
			$(element).css("position","relative");
			$("a",this).css({display:'none',float:'left'});
			$("<div style=\"width:10000px;position:absolute;top:0;left:0;\"></div>").appendTo($(this));
			var wrapper=$($("div",this).get(0));
			$("a",this).appendTo(wrapper);
			var limitLeft=1;
			loading();
			var elementWidth=$(element).width();
			function imgLoaded() {
				var complete=1;
				$("img",element).each(function(){
					if (!this.complete)complete=0;
					if (typeof this.naturalWidth != "undefined" && this.naturalWidth == 0)complete=0;
				});
				if (!complete)return 0;
				return 1;
			}

			function loading(){
				var height=imgLoaded();
				if (height){
					setTimeout(function(){
						$("a",element).css("display","block");
						$(element).css("height",height+"px");
						var sum=0;
						var elements=$("a",element);
						var cross=0;
						var pre=0;
						for(var i=0;cross<$(element).width();i++){
							cross+=pre+$($(elements).get(i)).width()+parseInt($($(elements).get(i)).css("margin-left"));
							pre=parseInt($($(elements).get(i)).css("margin-right"));
							$(wrapper).append($(elements.get(i)).clone());
						}
						elements.each(function(){sum+=$(this).width()+parseInt($(this).css("margin-right"))+parseInt($(this).css("margin-left"));});
						sum-=parseInt($("a:last",element).css("margin-right"));
						limitLeft=(elementWidth)-sum-cross;
						var maxHeight=0;
						$("img",element).each(function(){
								if (maxHeight<$(this).height())maxHeight=$(this).height();
						});
						$(element).css("height",maxHeight+"px");
						$("a[rel^='prettyPhoto']").prettyPhoto();
						$(element).parent().addClass("loaded");
						run();
					},500);
				}else 
				setTimeout(function(){loading();},100);
			}
			function run(){
				if (speed){
					var _speed=(Math.abs(speed)*speed)*-1;
					var left=parseInt(wrapper.css("left"));
					if (left+_speed >0)wrapper.css("left",(limitLeft)+"px");
					else if (left+_speed<limitLeft)
						wrapper.css("left",(0)+"px");
					else
						wrapper.css("left",(left+_speed)+"px");
				}
				setTimeout(function(){run()},20);
			}
			
			function mouseMove(event){
				
				if (event.pageX>$(element).offset().left && event.pageX< ($(element).offset().left+elementWidth)){
					if (event.pageY>$(element).offset().top && event.pageY<$(element).offset().top+$(element).height()){
						var mx=event.pageX-$(element).offset().left;
						var _speed= (mx+elementWidth/2)- (elementWidth);
						speed=parseInt(_speed*0.04);
					}else speed=0;
				}else speed=0;
			}
		});
	}});

})(jQuery);


