var Popup = new Class({
	id: false,
	className:'popup',
	options:{
		width:300,
		title:'Title',
		position:'center',
		resizable:true,
		draggable:true,
		closable:true
		// height, duration, title, content
	},
	initialize: function(id, options) {
		this.id = id + 'Popup';
		this.options.container = document.body;
		this.setOptions(options);
		
		this.DOM = new Element('div', {id:id, 'class':'popup'});
		this.DOM.setStyles({
			width:this.options.width + 'px',
			zIndex:100,
			visibility:'hidden'
		});
		this.DOM.addEvent('click', function() {this.giveFocus();}.bind(this));
		this.titleBar = (!(this.options.draggable || this.options.closable) ) ? false : new Element('h1', {'class':'titlebar'}).setText(this.options.title).injectTop(this.DOM);
		this.window = new Element('div', {'class':'window'}).injectInside(this.DOM);		
		
		this.options.container.appendChild(this.DOM);
		
		if (this.options.content) 				this.options.content.clone().injectInside(this.window).removeClass('hidden');
		if (this.options.draggable) 			this.makeDraggable();
		if (this.options.closable)				this.makeClosable();
		if (this.options.resizable)				this.makeResizable();
	},
	center: function() {
		if (this.DOM) {
			var scrollHeight = window.getScrollTop();
			var windowHeight = window.getHeight();
			var objHeight = this.DOM.getSize().size.y;
			
			var top = scrollHeight + windowHeight/2;
			var top = (objHeight < windowHeight) ? top-objHeight/2 : scrollHeight + 20;

			var left = (window.getWidth()/2) - (this.DOM.getSize().size.x/2);
			if (left < 0) left = 20;
	
			this.DOM.setStyles({
				position:'absolute',
				left: left + 'px',
				top: top + 'px'
			});
		}
	},
	makeDraggable: function() {
		new Drag.Move(this.DOM, {
			handle: this.titleBar,
			onStart: function(){  
				this.giveFocus();
			}.bind(this),
			onComplete: function(){

			}.bind(this)
		});
	},
	makeClosable: function() {
		var btn = new Element('a', {'class':'close'}).setText('Close').injectTop(this.DOM);
			btn.addEvent('click', function() {
				this.hide();
			}.bind(this));
		
	},
	makeResizable: function() {
		var div = new Element('div').injectInside(this.DOM);
		this.DOM.makeResizable({
			handle: new Element('a', {'class':'resize'}).injectInside(div),
			limit: {x: [200, 800], y: [40]}
		});		
	},
	giveFocus: function() {
		var zIndex = 0;
		$$('.popup').each(function(popup) {
			if (popup.getStyle('zIndex') > zIndex) zIndex = popup.getStyle('zIndex');
		});
		this.DOM.setStyle('zIndex', zIndex -0 + 1);
	},
	show: function() {
		if (this.options.position == 'center') 	this.center();
		this.DOM.setStyle('visibility', 'visible');
		this.giveFocus();
	},
	hide: function() {
		this.DOM.setStyle('visibility', 'hidden');
	}
});
Popup.implement(new Options);

var Alert = Popup.extend({
	options:{
		width:250,
		resizable: false,
		draggable: false
	},
	initialize: function() {
	}
});

