﻿/*
**************图片预加载插件******************
///作者：没剑(2008-06-23)
///http://regedit.cnblogs.com
///增加自动居中代码
///修改人:坏坏(2010-07-23)

///说明：在图片加载前显示一个加载标志，当图片下载完毕后显示图片出来
可对图片进行是否自动缩放功能
此插件使用时可让页面先加载，而图片后加载的方式，
解决了平时使用时要在图片显示出来后才能进行缩放时撑大布局的问题
///参数设置：
scaling     是否等比例自动缩放
width       图片最大高
height      图片最大宽
loadpic     加载中的图片路径
autoh       是否自动上下居中
$("#imgurl").LoadImage(true,651,651,"images/loading.gif",false)
*/
jQuery.fn.LoadImage=function(scaling,width,height,loadpic,autoh){
    if(loadpic==null)loadpic="load3.gif";
	return this.each(function(){
		var t=$(this);
		var src=$(this).attr("src")
		var img=new Image();
		var cssh
		var cssw
		//alert("Loading...")
		img.src=src;
		//自动缩放图片
		var autoScaling=function(){
			if(scaling){
			
				if(img.width>0 && img.height>0){ 
			        if(img.width/img.height>=width/height){ 
			            if(img.width>width){ 
			                t.width(width); 
			                t.height((img.height*width)/img.width); 
							if (autoh){
							cssh=(height - ((img.height*width)/img.width))*0.5
							t.css("margin-top",""+cssh+"px")
							}
			            }else{ 
			                t.width(img.width); 
			                t.height(img.height);
							if (autoh){ 
								cssh=(height - img.height)*0.5
								t.css("margin-top",""+cssh+"px")
							}
			            } 
			        } 
			        else{ 
			            if(img.height>height){ 
			                t.height(height); 
			                t.width((img.width*height)/img.height); 
							//cssw=(width - ((img.width*height)/img.height))*0.5
//							t.css("margin-left",""+cssw+"px")
			            }else{ 
			                t.width(img.width); 
			                t.height(img.height); 
							if (autoh){
								cssh=(height - img.height)*0.5
								t.css("margin-top",""+cssh+"px")
							}
							//cssw=(width - img.width)*0.5
//							t.css("margin-left",""+cssw+"px")
			            } 
			        } 
							
							
//					var left = (width - t.w)*0.5;
//					var top = (height - t.h)*0.5;
				//t.css({marginLeft:(width - t.width)*0.5,marginTop:(height - t.height)*0.5});
			    } 
			}	
		}
		//处理ff下会自动读取缓存图片
		if(img.complete){
		    //alert("getToCache!");
			autoScaling();
		    return;
		}
		$(this).attr("src","");
		var loading=$("<img alt=\"加载中...\" title=\"图片加载中...\" src=\""+loadpic+"\" />");
		
		t.hide();
		t.after(loading);
		$(img).load(function(){
			autoScaling();
			loading.remove();
			t.attr("src",this.src);
			t.show();
			//alert("finally!")
		});
		
	});
}
