ODIL_Initializer.add_selector_with_action('.drawer', function(element) {
	new Drawer().initialize_on_element(element);
});

var Drawer = Class.create(ODIL_Base, {
	namespace: function($super) {
		return $super() + 'drawer-';
	},
	
	drawer: null,
	handle: null,
	attachment: null,
	travel_distance: null,
	open: null,
	duration: 0.3,
	
	initialize_on_element: function(element) {
		this.drawer = element;
		this.handle = this.drawer.down('.handle');
		this.attachment = this.drawer.readAttribute(this.namespace() + 'attachment');
		this.travel_distance = this.drawer.readAttribute(this.namespace() + 'travel_distance');
		
		var that = this;
		
		this.handle.observe('click', function() {
			if(that.open == true)
				that.move_to('closed');
			else
				that.move_to('open');
		});
		
		if(this.drawer.readAttribute(this.namespace() + 'start_open') == 'true') {
			this.move_to('open', this.drawer.readAttribute(this.namespace() + 'initial_delay'));
		}
	},
	
	move_to: function(state, delay) {
		var delta = 0;
		if(state == 'closed') {
			delta = -1 * this.travel_distance;
			this.open = false;
		}
		else {
			delta = this.travel_distance;
			this.open = true;
		}
		
		if(delay == null)
			delay = 0;
		
		if(this.attachment == 'bottom') {
			var that = this;
			delta = -1 * delta;
			var goal = parseInt(that.drawer.getStyle('bottom')) + parseInt(delta);
			
			new Effect.Morph(this.drawer, {
				style: {
					bottom: goal + 'px'
				},
				delay: delay,
				duration: that.duration,
				mode: 'relative',
				queue: {
					position: 'end',
					scope: 'drawer_queue_for-'+that.drawer.identify(),
					limit: 1
				}
			});
		}
	}
});
