﻿var Zoom = function(options){
	this.SetOptions(options);
	this.warp = $(this.options.warp).find("a");
	this.thumbnail = $(this.options.thumbnail);
	this.ImgWidth = this.options.ImgWidth;
	this.ImgHeight = this.options.ImgHeight;
	this.loading = this.options.loading;
	this.init();
	this.LoadImage();
};

Zoom.prototype = {
	init: function(){
		this.image = [], this.image_src = [];
		for(var i = 0; i < this.thumbnail.length; i++){
			this.image_src.push($(this.thumbnail[i]).attr("src"));
			this.image.push(new Image());
			$(this.thumbnail[i]).css({ display: "none" });
			$(this.warp[i]).append(this.loading);
		}
	},
	SetOptions: function(options){
		this.options = {
			warp:      ".thumbnail_box",
			thumbnail: ".thumbnail",
			ImgWidth:  200,
			ImgHeight: 200,
			loading: "<img class='loading' src='" + templatesUrl + "Styles/images/2009/search/images/loading.gif' />"
		};
		$.extend(this.options, options || {});
	},
	AutoScaling: function(source, index){
		if (source.width > 0 && source.height > 0) {
			if (source.width / source.height >= this.ImgWidth / this.ImgHeight) {
				if (source.width > this.ImgWidth) {
					$(this.thumbnail[index]).width(this.ImgWidth);
					$(this.thumbnail[index]).height((source.height * this.ImgWidth) / source.width);
				}
				else {
					$(this.thumbnail[index]).width(source.width);
					$(this.thumbnail[index]).height(source.height);
				}
			}
			else {
				if (source.height > this.ImgHeight) {
					$(this.thumbnail[index]).height(this.ImgHeight);
					$(this.thumbnail[index]).width((source.width * this.ImgHeight) / source.height);
				}
				else {
					$(this.thumbnail[index]).width(source.width);
					$(this.thumbnail[index]).height(source.height);
				}
			}
		}
		source = new Image();
	},
	LoadImage: function(){
		var _this = this;
		for(var j = 0; j < this.image_src.length; j++){
			(function(){
				var index = j;
				$(_this.image[index]).load(function(){
					if(_this.image[index].width == 0 || _this.image[index].height == 0) return;
					_this.AutoScaling(_this.image[index], index);
					$(_this.warp[index]).find("img").remove(".loading");
					$(_this.thumbnail[index]).css({ display: "inline" });
					_this.image[index] = new Image();
				});
				_this.image[index].src = _this.image_src[index];
			})();
		}
	}
};

