
//Used to keep a container in the vertical center of the browser

var PanelViewer = new Class({
	
	Implements: [Options, Elements, Events, Request],
	
	//options
	options: {
		holder: 'panel-holder',
		panelClassName: null,
		onUpdate: $empty,
		onShow: $empty,
		onHide: $empty,
		onLoad: $empty,
		onComplete: $empty
	},
	
	//initialization
	initialize: function(button, options) {

		this.panel = null;
		this.backgroundimage = null;
		// //set options
		this.setOptions(options);
		//This is the button that the user will select in the interface
		this.button = $(button);
		//The Container that will hold created Panel
		
		this.position = {};
		
		this.wrapper = $(this.options.holder) || null;
		
		if(this.wrapper) {
			this.position.top = this.wrapper.getHeight();
			this.wrapper.setStyle('visibility', 'hidden');
		}		
		this.href = this.button.href;
		//Lets create the Controls for the Panel Viewer
		this.setUpControls();
	},
	setUpControls: function() {
		this.button.addEvents({
			'click': function(e){
					if(e) e.stop();
					this.change();
				}.bind(this)
		});
	},
	change: function(){
		this.fireEvent('onChange');
		this.button.addClass('active');
		if(!this.panel) {
			if(this.wrapper) {
				this.panel = new Element('div', { 
					'class'	: (this.button.id || "") + " " + (this.options.panelClassName || ""),
					'id'	: 'panel-' + (this.button.id || "")
					}
				).setStyles(
					{
						'top': this.position.top,
						'opacity': 0
					}
				).inject(this.wrapper,'inside');
			
				this.anifex = new Fx.Tween(this.panel, { transition: Fx.Transitions.Quart.easeOut, duration: 1000});
			
				this.load();				
			} 
			else 
			{
				throw new Error('There is now wrapper set in the HTML');
			}

		} else {
			if(!this.current) this.show();
		}
	},
	load: function() {
		$(document.body).setStyle('cursor', 'wait');
		this.fireEvent('onLoad');

		var req = new Request.HTML({ 
			url: this.button.href+'?type=ajax', 
			evalScripts: true,
			update: this.panel,
			onSuccess: function(html) {
				$(document.body).setStyle('cursor', 'default');
				this.show();
			}.bind(this)
		}).send();
	},
	show: function() {
		this.fireEvent('onShow');
		this.anifex.start('top', 0);
		this.wrapper.setStyle('visibility','visible');
		this.panel.fade('in');
		this.current = true;
	},
	hide: function() {
		this.fireEvent('onHide');
		this.anifex.start('top', this.position.top);
		this.panel.fade('out');
		this.wrapper.setStyle('visibility','hidden');
		this.current = false;
	},
	current: false,
	getParent: function(){
		return this.button.rel || '0';
	}	
});