/**
 * Filterable
 * 
 */
var Filterable = Class.create();
Object.extend(Filterable.prototype, {

	/**
	 * Initializes the instance
	 * 
	 */
	initialize: function(options){
		options = options || {};

		// get Elements
		this.defaultTag = options.defaultTag || null;
		this.target = $(options.target) || null;
		this.controls = this.target.getElementsBySelector('.filterable-controls a.filterable-control');
		this.items = this.target.getElementsBySelector('.filterable-filtered .filterable-filtered-item');
		
		// observe click events with filter function
		var _this = this;
		this.controls.each(function(control){
			Event.observe(control, 'click', _this.onControlClick.bindAsEventListener(_this, control));
		});
	
		if( this.defaultTag ){
			this.filter(this.defaultTag);
		}
		
		return false;
	},

	/**
	 * Called on click on a control
	 * 
	 */
	onControlClick: function(evt, control){
		Event.stop(evt);
		
		// get the desired tag and filter
		var tag = control.getAttribute('rel');
		this.filter(tag);
		
		return false;
	},
	
	/**
	 * Filters items by tag
	 * 
	 */
	filter: function(tag){
		// set clicked control as active
		this.controls.each(function(c){
			if( tag == c.getAttribute('rel') || 'all'==tag){
				c.addClassName('filterable-control-on');
			} else {
				c.removeClassName('filterable-control-on');
			}
		});
		
		// simply hide all items at once
		this.items.each(function(item){
			item.hide();
		});

		// clear all effects in queue
		var queue = Effect.Queues.get('filterable');
		queue.each(function(effect) { effect.cancel(); });
		
		// let desired items appear
		this.items.each(function(item){
			if( item.hasClassName(tag) || 'all'==tag ){
				new Effect.Appear(item, {
					'duration'		: .3,
					'queue'			: { scope: 'filterable' }
				});
			}
		});
	}
	
	
});