/* 
 * Bologna Iperbole
 *
 * @package		Iperbole
 * @author		Oskar Krawczyk (o.krawczyk@keepthinking.it)
 * @version		1.0
 * @dependecies	MooTools 1.2+
 * @copyright	Copyright (c) 2009-2010, Oskar Krawczyk (Keepthinking Ltd.)		
 * @link		http://keepthinking.it
 * 
 ======================================================================= */

var UserPanel = new Class({
	
	Extends: Common,
	
	Implements: [Options],

	initialize: function(options){
		this.setOptions(options);
		this.userPanel();
		this.clearDropdowns();
	},
   
	userPanel: function(){		
		this.actionTabs = $$('#ui-actions a.ocTrigger');
		this.formContainers = $$('#ui-actions div.formCont');
		
		this.actionTabs.each(function(el, index){			
			el.addEvents({
				click: function(e){
					if (e) e.stop();
					
					this.actionTabs.removeClass('active');
					this.actionTabs[index].addClass('active');

					this.formContainers.hide();
					this.formContainers[index].show();
					
					// store the currently selected tab
					Cookie.write('current:tab', index);
				}.bind(this)
			});
		}, this);

		if (this.options.stayOpen){
			
			// show the previously active tab
			if (this.actionTabs.length){
				this.actionTabs[$pick(Cookie.read('current:tab'), 0)].fireEvent('click');
			}
		}
		
		this.remoteTriggers();
		this.keyboardTrigger();
	},
	
	clearDropdowns: function(){
		$(document.body).addEvents({
			click: function(e){
				
				// hide tabs if triggered remotely (via keyboard shortcuts) or clicked outside of the tab
				if (e === 'remote' || !$(e.target).getParent('.formCont')){
					this.actionTabs.removeClass('active');
					this.formContainers.hide();
				}
			}.bind(this)
		});
	},
	
	remoteTriggers: function(){
		var self = this;
		
		// setup remote triggers (links with a specific class name, and anchor)
		$$('.remoteTrigger').addEvents({
			click: function(e){
				e.stop();
				
				// search for the index of the element inside href, and fire the click event on the tabs object
				self.actionTabs[this.get('href').split('-')[1]].fireEvent('click');
			}
		});
	},
	
	keyboardTrigger: function(){
		new Keyboard({
			defaultEventType: 'keyup',
			events: {
				esc: function(){
					// hide the tabs when ESC is pressed
					this.fireEvent('click', 'remote');
				}.bind($(document.body))
			}
		}).activate();
	}
});
