/**
 * Manages a popup dialog that allows filtering of elements based on desired properties.
 *
 * Copyright 2007 by <GX> creative online development B.V.
 * <GX> open for business
 * http://gx.nl
 *
 * @author	StijnW <Stijn.de.Witt@gx.nl>
 * @date		2007/08/22
 * @desc		KPNP-182
 *
 * DEPENDS ON: prototype.js, general.js, lightbox.js, elementfilter.js
 */

var FilterPopup = Class.create();
Object.extend(FilterPopup.prototype, {
	initialize: function (popup, filterList, applyButton, elementFilter) {
		this.popup = $(popup);
		this.filterList = $(filterList);
		this.applyButton = $(applyButton);
		this.elementFilter = elementFilter;
		this.lightBox = null;

		Event.observe(this.applyButton, 'click', this.apply.bindAsEventListener(this));
	},

	clear: function() {
		while(this.filterList.hasChildNodes())
			this.filterList.removeChild(this.filterList.lastChild);
	},

	populate: function() {
		for (var idx=0; idx < this.elementFilter.filters.length; idx++) {
			var filter = this.elementFilter.filters[idx];
			var li = document.createElement('li');
			this.filterList.appendChild(li);
			var input = document.createElement('input');
			input.type = "checkbox";
			input.name = this.elementFilter.elementClass + "-input";
			input.id = input.name + "-" + idx;
			input.value = filter.value;
			li.appendChild(input);
			input.checked = filter.enabled;
			var label = document.createElement('label');
			li.appendChild(label);
			label.htmlFor = input.id;
			label.appendChild(document.createTextNode(filter.description));
		}
	},

	open: function() {
		if (this.popup && this.filterList && this.elementFilter) {
			this.clear();
			this.populate();
			this.lightBox = new Lightbox.base(this.popup);
			sIRFPopupTitles();
		}
		return false;
	},

	close: function(evt) {
		if (this.lightBox)
			this.lightBox.hideBox(evt);
		this.lightBox = null;
		return false;
	},

	apply: function(evt) {
		if (this.popup && this.applyButton && this.elementFilter) {
			var inputs = this.popup.getElementsByTagName("input");
			for (var idx=0; idx < inputs.length; idx++) {
				if (inputs[idx].name == this.elementFilter.elementClass + "-input")
					this.elementFilter.setFilterState(inputs[idx].value, inputs[idx].checked);
			}
			this.elementFilter.filter();
		}
		this.close(evt);
		Event.stop(evt);
	}
});
