// JavaScript Document
var ImageDisplay = new Class({
 
	Implements: [Options,Events],

	options:  {
		id: 'imageDisplay',
		width: 400,
		height: 400,
		color: '#FFF',
		duration: 500,
		zIndex: 5001
	},

	initialize: function(container,options) {
		this.setOptions(options);
		this.container = container;
		this.location = location;
		
		this.overlay = new Overlay(container, { 
			duration: this.options.duration,
			zIndex: this.options.zIndex - 1,
			onClick: function() {
				this.close();
			}.bind(this)
		});
		
		// Draw White Box
		var box = new Element('div',{
			id: this.options.id,
			opacity: 0,
			html: '<p><div style="text-align:center;"><img src="./images/layout/preload.gif" /></div></p>',
			styles: {
				'z-index': this.options.zIndex
			}
		}).inject(this.container);
		
		this.box = box;
		
		// Setup Fade Tween
		this.tween = new Fx.Tween(box,{ 
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onComplete: function() {
				this.fireEvent(box.get('opacity') == 1 ? 'show' : 'hide');
			}.bind(this)
		});
	},
	open: function(url, title) {
		this.overlay.open();
		this.fireEvent('open');
		this.tween.start(1);
		
		var image = Asset.image(url, {
			id: 'largeImage',
			title: title,
			onLoad: function(){
				this.box.set('html', '');
				var el = new Element('div', {
					id:'closeBtn',
					html: '<img src="./images/layout/x-button.png" alt="close" />',
					styles: {
						cursor:'pointer'
					}
				});
				el.addEvent('click', function(){
					this.close();
				}.bind(this));
				el.inject(this.box);
				image.inject(this.box);
				this.fireEvent('ready');
				
				var screenSize = $(document.body).getSize();
				var size = image.getSize();
				if(size.x > screenSize.x || size.y > screenSize.y){
					var ratio = size.x / size.y;
					var diffX = size.x - screenSize.x;
					var diffY = size.y - screenSize.y;
					if(diffX > diffY){
						size.x = screenSize.x;
						size.y = size.x / ratio;
					} else {
						size.y = screenSize.y;
						size.x = size.y * ratio;
					}
					
					size.x -= 40;
					size.y -= 40;
				}
				
				image.width = size.x;
				image.height = size.y;
				var padding = this.box.getStyle('padding').split(' ')[0];
				padding = padding.substr(0,padding.length-2);
				this.box.setStyles({
					'margin-left': -(size.x / 2) - padding, 
					'margin-top': -(size.y / 2) - padding,
					'width': size.x,
					'height': size.y
				});
			}.bind(this)
		});
		return this;
	},
	close: function(){
		this.tween.start(0);
		this.overlay.close();
		return this;
	},
	setWidth: function(width){
		this.options.width = width;
		$(this.options.id).setStyles({'width':width, 'margin-left':-width/2});
	}
});
