var ProductZoom = new Class({
	Implements:[Options, Events],
	
	options: {
		loadingImage: null
	},
	
	initialize: function(element, options){
		this.element = $(element);
		this.setOptions(options);
		this.overlay = new Element('div', {'class': 'product-zoom-overlay'});
		var bound = this.bound = {};
		bound.imageLoaded = this.imageLoaded.bindWithEvent(this);
		bound.mouseMove = this.mouseMove.bindWithEvent(this);
		bound.mouseLeave = this.mouseLeave.bindWithEvent(this);
		var show = bound.show = this.show.bindWithEvent(this);
		this.element.addEvent('mouseenter', show);
		var loadingImage = this.options.loadingImage;
		if ($type(loadingImage) == 'string'){
			this.options.loadingImage = ['url(' + loadingImage + ') center center no-repeat scroll'];
		}
	},
	
	toElement: function(){
		return this.element;	
	},
	
	loadImage: function(imagePath){
		this.largeImage = new Asset.image(imagePath, {
			onload: this.bound.imageLoaded
		});
	},
	
	imageLoaded: function(event){
		$clear(this.overlayTimer);
		var overlay = this.overlay;
		var bound = this.bound;
		overlay.setStyle('background-image', 'url(' + this.largeImage.get('src') + ')');
		$(document).addEvent('mousemove', bound.mouseMove);
	},
	
	show: function(event){
		var href = this.element.getElement('a').get('href');
		this.showOverlay();
		this.element.addEvent('mouseleave', this.bound.mouseLeave);
		this.loadImage(href);
	},
	
	hide: function(){
		$(document).removeEvent('mousemove', this.bound.mouseMove);
		this.overlay.removeEvent('mouseleave', this.bound.mouseLeave);
		this.hideOverlay();
	},
	
	showOverlay: function(){
		var element = this.element;
		var overlay = this.overlay;
		var loadingImage = this.options.loadingImage;
		if (loadingImage){
			this.overlayTimer = this.showLoadingImage.delay(250, this);
		}
		else {
			overlay.setStyle('background', 'none');
		}
		overlay.setStyle('height', element.getSize().y);
		element.adopt(overlay);
	},
	
	showLoadingImage: function(){
		this.overlay.setStyle('background', this.options.loadingImage.join(', '));
	},
	
	hideOverlay: function(){
		this.overlay.dispose();
	},
	
	mouseMove: function(event){
		var overlay = this.overlay;
		var page = event.page;
		var dim = overlay.getCoordinates(document);
		var x = page.x - dim.left;
		var y = page.y - dim.top;
		
		var px = Math.floor((x / dim.width) * 100);
		var py = Math.floor((y / dim.height) * 100);
		
		overlay.setStyle('background-position', px + '% ' + py + '%');
	},
	
	mouseLeave: function(event){
		this.hide();
	}
	
})
