// define namespaces
if (!NS)
	var NS = {};
if (!NS.UI)
	NS.UI = {};

NS.UI.PairedDropDownController = function (parentId, childId, attributeName) {
	this.parent = document.getElementById(parentId);
	this.child = document.getElementById(childId);
	this.attributeName = attributeName;
	this.options = null;

}
NS.UI.PairedDropDownController.controllers = { };

// updateChild
/// <summary>Reset the child options</summary>
NS.UI.PairedDropDownController.prototype = {
	"type": NS.UI.PairedDropDownController,
	"updateChild": function () {

		if (this.parent && this.child) {
			this.child.options.length = 0;

			var opts = this.options[this.parent.options[this.parent.selectedIndex].value];

			// add the Select element
			if (this.parent.selectedIndex != 0)
				this.child.options.add(this.options[""][""]);
			
			if (opts) {
				for (var i in opts) 
					this.child.options.add(opts[i]);
				if (this.parent.selectedIndex != 0 && this.child.options.length != 0) {
					this.child.focus();
				}
			}
		}

		return false;
	},

	"changeItem": function (e) {
		if (!e) var e = window.event;
		if (e.target) elm = e.target;
		else elm = e.srcElement;

		var parentId;
		// pass the event on to the tab object
		if (elm != null) {
			parentId = elm.id;
			NS.UI.PairedDropDownController.controllers[elm.id].updateChild();
		}
		if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
		return false;
	},

	// initialize
	/// <summary>Initializes the tabs</summary>
	"initialize": function () {
		
		// set up the general/specific item options
		if (this.parent != null && this.child != null) {
			
			this.options = new Object();

			var parentVal, childOpt;
			for (var i = 0; i < this.parent.options.length; i++) {
				parentVal = this.parent.options[i].value;
				if (this.options[parentVal] == null) 
					this.options[parentVal] = new Object();
			}
			for (var i = 0; i < this.child.options.length; i++) {
				childOpt = this.child.options[i];
				parentVal = childOpt.getAttribute(this.attributeName);
				if (parentVal == null && i == 0)
					parentVal = "";
				if (parentVal != null && this.options[parentVal] != null && this.options[parentVal][childOpt.value] == null)
					this.options[parentVal][childOpt.value] = childOpt;
			}
			this.type.controllers[this.parent.id] = this;

			// attach the change event handler
			ow_f_AddEvent(this.parent, "change", this.changeItem, false);

			// do the initial call for the listbox to set up the Select element
			this.updateChild();
		}
	}
};