var Funbox = Class.create();
Funbox.prototype = {
	initialize: function(url) {
		this.url = url;
		this.bg = new Element('div', { 'class': 'funbox_bg' });
		this.bg.setStyle({'opacity': 0});
		this.img = new Element('img', { 'class': 'funbox_img', 'src': null, 'alt': 'Image' });
		this.wrapper = new Element('span', { 'class': 'funbox_wrapper' });
		//this.closer = new Element('span', { 'class': 'funbox_closer' }).update("&#9746; Close");
		this.imgW = null;
		this.imgH = null;

		this.bg.observe('click', function() {
			this.closeBox();
		}.bind(this));
		
		this.margin = 80;
		Event.observe(window, 'resize', this.updateImage.bind(this)); 
	},
	show: function() {
		document.body.appendChild(this.bg);
		this.bg.fade({ duration: 0.5, from: 0, to: 1 });
        this.preloaded = new Image();
        this.preloaded.onload = (function(){
			this.imgW = this.preloaded.width;
			this.imgH = this.preloaded.height;
			this.bg.appendChild(this.img);
			this.img.setAttribute('src', this.url);
			this.img.wrap(this.wrapper);
			//this.wrapper.appendChild(this.closer);
			this.updateImage();
        }).bind(this);
        this.preloaded.src = this.url;
	},
	updateImage: function() {
		this.viewport = document.viewport.getDimensions();
		this.width = this.viewport.width;
		this.height = this.viewport.height;
		this.winRatio = this.width/this.height;
		this.imgRatio = this.imgW/this.imgH;

		// small image
		if(this.imgW<this.width-this.margin && this.imgH < this.height-this.margin) {
			this.img.setStyle({
				'height': null,
				'width': null,
				'marginTop': (this.height-this.imgH)/2+'px',
				'marginLeft': (this.width-this.imgW)/2+'px',
			});
		}
		// image bigger than screen
		else {
			if(this.winRatio>=this.imgRatio)
				this.img.setStyle({
					'height': this.height-this.margin+'px',
					'width': null,
					'marginTop': this.margin/2+'px',
					'marginLeft': (this.width-((this.height-this.margin)*this.imgRatio))/2+'px',
				});
			else
				this.img.setStyle({
					'height': null,
					'width': this.width-this.margin+'px',
					'marginTop': (this.height-((this.width-this.margin)/this.imgRatio))/2+'px',
					'marginLeft': this.margin/2+'px'
				});
		}
	},
	closeBox: function() {
		this.bg.fade({ duration: 0.5, from: 1, to: 0, afterFinish: function() { this.bg.remove(); }.bind(this) });
	}
};

