var addImageLoad;

$(function(){
	function imageLoad(elm){
		var src = $(elm).attr('name');
		var width = $(elm).attr('w');
		var height = $(elm).attr('h');
		var no_image = $(elm).attr('ng');

		if (!src || !width || !height || !no_image) {
			return;
		}

		var image = new Image();
		image.onload = function(){
			var w = (this.naturalWidth)? this.naturalWidth : this.width;
			var h = (this.naturalHeight)? this.naturalHeight : this.height;

			$(elm).hide();
			var wrate = w / width;
			var hrate = h / height;
			if (wrate > 1) {
				if (wrate > hrate) {
					elm.width = width;
					elm.height = Math.round(h / wrate);
				} else {
					elm.width = Math.round(w / hrate);
					elm.height = height;
				}
			} else {
				if (hrate > 1) {
					elm.width = Math.round(w / hrate);
					elm.height = height;
				} else {
					elm.width = w;
					elm.height = h;
				}
			}
			$(elm).attr('src', src).show();
		};
		image.onerror = function(){
			elm.onmouseover = null;
			elm.src = no_image;
			elm.onerror = null;
		};
		$(elm).removeClass('loading');
		image.src = src;
	}

	addImageLoad = function(){
		$('img.cxsea_image.loading').each(function(){
			imageLoad(this);
		});
	};

	addImageLoad();
});
