// JavaScript Document
function ImageCanvas(eldiv, zoom) {
	this.eldiv = eldiv;
	this.zoom = zoom || 1.2;
	this.imagesrc = $(this.eldiv).find('img').attr('src');
	$(this.eldiv).find('img').remove();
	this.img = new Image();
	
	this.imgheight = 0;
	this.imgwidth = 0;
	this.imgposx = 0;
	this.imgposy = 0;
	
	this.divwidth = $(this.eldiv).width();
	this.divheight = $(this.eldiv).height();
	
	this.divtop = $(this.eldiv).position().top;
	this.divleft = $(this.eldiv).position().left;
	
	if(isNaN(this.divtop)) {
		this.divtop = 0;
	}
	if(isNaN(this.divleft)) {
		this.divleft = 0;
	}
	
	var that = this;
	$(this.img)
	.load(function () {
		
		$(that.eldiv).append($(that.img));
		
		
		$(that.img).css('position', 'absolute');
		
		
	
		
		//calculating size
		var oldheight = $(that.img).height();
		var oldwidth = $(that.img).width();
		
		if(oldwidth / oldheight > that.divwidth / that.divheight) {
			that.imgwidth = that.divheight/oldheight*oldwidth;
			that.imgheight = that.divheight;
		} else {
			that.imgheight = that.divwidth/oldwidth*oldheight;
			that.imgwidth = that.divwidth;
		}
		
		$(that.img).width(that.imgwidth);
		$(that.img).height(that.imgheight);
		
		that.imgposx =  -0.5*(that.imgwidth-that.divwidth);
		that.imgposy =  -0.5*(that.imgheight-that.divheight);
		
		$(that.img).css('left',that.imgposx);
		$(that.img).css('top', that.imgposy);
		//grayscale(that.img);
		$(that.img).fadeIn();
		
		
		$(that.eldiv).hover(function() {
					 
					//Set the width and height according to the zoom percentage
					var width =that.imgwidth * that.zoom;
					var height = that.imgheight* that.zoom;
					
					movex = that.imgposx*that.zoom;//that.imgposx-0.5*(width - that.imgwidth);
					movey = that.imgposy*that.zoom;//that.imgposy-0.5*(height - that.imgheight);
					 
					 $(this).css('z-index', '2');
					//Move and zoom the image
					$(this).find('img').stop(false,true).animate({'width':width, 'height':height, 'top':movey, 'left':movex}, {duration:200});
					$(this).stop(false,true).animate({'width':(that.divwidth*that.zoom), 'height':(that.divheight*that.zoom), 'top':that.divtop+(-0.5*(that.divheight*that.zoom-that.divheight)), 'left':that.divleft+(-0.5*(that.divwidth*that.zoom-that.divwidth))}, {duration:200});
					 
					
				},
				function() {
					//Reset the image
					$(this).find('img').stop(false,true).animate({'width':that.imgwidth, 'height':that.imgheight, 'top':that.imgposy, 'left':that.imgposx}, {duration:100});
					$(this).stop(false,true).animate({'width':that.divwidth, 'height':that.divheight, 'top':that.divtop, 'left':that.divleft}, 100,function() {$(that.eldiv).css('z-index', '1');});  
			 
		});
		
	})
	.error(function () {alert("error");})
	.attr('src', this.imagesrc);
	
	
	
}
