filter_sets = {};

FilterComponent = Class.create();
FilterComponent.prototype = {
	
	initialize: function(id, trigger) {
		this.id = id;
		this.self = $(this.id);
		this.trigger = $(trigger);
		
		this.items = [];
		this.cur_set = [];
		
		this.last_value = '';
		
		if (this.self && this.trigger) {
			this.injectBehaviours();	
		}
		
	},
	
	injectBehaviours: function() {		
		this.findItems();
		this.trigger.onkeyup = this.filterOptions.bindAsEventListener(this);
	},
	
	findItems: function() {
		var count = this.self.childNodes.length;
		for (var i=0; i<count; i++) {
			var c = this.self.childNodes[i];
			if (c.id) {
				if ($(c.id+'_filter')) {
					var itm = {id:c.id, values:RicoUtil.getContentAsString($(c.id+'_filter'))};
					this.items.push(itm);	
					if (console) console.log('ADDING FILTER: '+itm.id+' : '+itm.values);
				}	
			}
		}
	},

	reset: function() {
		this.cur_set = [];
		this.show();
	},
	
	show: function(id, set) {
		if (id) {
			Element.show(id);	
		} else {
			set = set || this.items;
			for(var i=0; i<set.length; i++) {
				Element.show(set[i].id);	
			}
		}
	},
	
	hide: function(id, set) {
		if (id) {
			Element.hide(id);	
		} else {
			set = set || this.items;
			for(var i=0; i<set.length; i++) {
				Element.hide(set[i].id);	
			}
		}
		
	},
	
	filterOptions: function(e) {
		var target = this.trigger.value;
		
		if (!target) {
			this.reset();	
		} else if(target.indexOf(this.last_value) == -1) { 
			this.cur_set = [];
		} 
		
		this.cur_set = this.makeMatches(target);
		this.last_value = target;
	},
	
	makeMatches: function(compareStr) {
		var set = (this.cur_set.length > 0) ? this.cur_set : this.items;
		var matchArray = [];
		var regExp = new RegExp(compareStr, 'i');
		for(var i=0; i<set.length; ++i) {
			if (console) console.log('MATCHING TO: '+set[i].values);
			var the_match = set[i].values.match(regExp);
			if (the_match) {
				matchArray.push(set[i]);
				this.show(set[i].id);
			} else {
				this.hide(set[i].id);	
			}
		}
		return matchArray;
	},
	
	serialize: function(var_name) {
		var_name = var_name || 'filter_set';
		var ids = [];
		for(var i=0; i<this.items.length; i++) {
			var id = this.items[i].id;
			if (Element.visible(id)) {
				var parts = id.split('_');
				ids.push(parts[parts.length-1]);
			}
		}
		if (ids.length > 0) {
			this.onSerialize(var_name+'[]='+ids.join('&'+var_name+'[]='));	
		}
	},
	
	onSerialize: function() {}

	
};