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

	options:  {
		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,
			onClick: function() {
				this.close();
			}.bind(this)
		});
		
		// Draw White Box
		var box = new Element('div',{
			id: 'box',
			opacity: 0,
			html: '<p><div style="text-align:center;"><img src="./images/layout/preload.gif" /></div></p>',
			styles: {
				'top':'50%',
				background: this.options.color,
				'z-index': this.options.zIndex,
				'margin-left': -this.options.width / 2,
				'margin-top': -this.options.height / 2
			}
		}).inject(this.container);
		
		// Setup Fade Tween
		this.tween = new Fx.Tween(box,{ 
			duration: this.options.duration,
			link: 'cancel',
			property: 'opacity',
			onStart: function() {
				box.setStyles({
					width: this.options.width
				});
			}.bind(this),
			onComplete: function() {
				this.fireEvent(box.get('opacity') == 1 ? 'show' : 'hide');
				if(box.get('opacity') == 0){box.setStyle('display','none');}
			}.bind(this)
		});
	},
	open: function(url) {
		this.overlay.open();
		this.fireEvent('open');
		this.tween.start(1);
		$('box').setStyle('display', 'block');
		var myRequest = new Request.HTML({
			url: url,
			evalScripts: false,
			onRequest: function() {
				$('box').set('html', '<p><div style="text-align:center;"><img src="./images/layout/preload.gif" /></div></p>');
				
				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($('box'));
			},
			onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
				$('box').set('html', responseHTML);
				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($('box'));
				
				$('box').setStyles({'position':'absolute', 'margin-top':0, 'top':20});
				this.fireEvent('ready');
				setTimeout(eval(responseJavaScript), 500);
			}.bind(this),
			onFailure: function(){
				$('box').set('text', 'Could not load page.');
			}
		});
		
		myRequest.send();
		return this;
	},
	close: function(){
		this.tween.start(0);
		this.overlay.close();
		return this;
	},
	setWidth: function(width){
		this.options.width = width;
		$('box').setStyles({'width':width, 'margin-left':-width/2});
	}
});
