
var CategoryListHandler = function(departmentList, categoryList) {
	this.departmentList = departmentList;
	this.categoryList = categoryList;
	
	this.url = "/cmarketplace/action/listCategories";
	
	var handler = this;
	this.departmentList.onchange = function(e) { e = e || window.event; handler.departmentChange(e); }
};

CategoryListHandler.prototype = {

	departmentChange: function() {
		this.removeAllChildrenFromNode(this.categoryList);
		this.categoryList.appendChild(this.buildOption("", "Retrieving Categories..."));

		var params = "dept=" + this.departmentList.options[this.departmentList.selectedIndex].value;
		new Ajax.Request(this.url, {method:'post', parameters: params, onSuccess:this.handleUpdate.bind(this), onFailure:this.handleError.bind(this) });
	},

	handleUpdate: function(request) {
		this.changeCategories(request.responseXML);
	},
	
	handleError: function(request) {
		// do nothing
	},
	
	changeCategories: function(doc) {
		var categories = doc.getElementsByTagName("category");
		
		this.removeAllChildrenFromNode(this.categoryList);
		this.categoryList.appendChild(this.buildOption("", "All Categories"));
		
		for (var i = 0; i < categories.length; ++i) {
			var value = this.getXMLValue(categories[i], "id");
			var text = this.getXMLValue(categories[i], "name");
			
			this.categoryList.appendChild(this.buildOption(value, text));
		}
	},
	
	removeAllChildrenFromNode: function(node) {
		while (node.hasChildNodes()) {
			node.removeChild(node.childNodes[0]);
		}
	},
	
	buildOption: function(value, text) {
		var option = document.createElement("OPTION");
		
		option.value = value;
		option.text = text;
		option.innerHTML = text;
		
		return option;
	},
	
	getXMLValue: function(node, tagname) {
		var nodes = node.getElementsByTagName(tagname);
		
		if ((!nodes) || (nodes.length <= 0)) {
			return null;
		}
		
		if (nodes[0].textContent) {
			return nodes[0].textContent;
		}
		
		if (nodes[0].text) {
			return nodes[0].text;
		}
		
		if (nodes[0].firstChild.nodeValue) {
			return nodes[0].firstChild.nodeValue;
		}
		
		return null;
	}
};
