BLIP.Class.create("BLIP.Unit.DropDown", BLIP.Unit,
	function(config) {
		this.captionSelector = config.captionSelector || ".CurrentlySelected";
		BLIP.Unit.call(this, config);
	},
	{
		selector : ".DropDown",

		selectedItem : null,

		init : function() {
			this.onItemSelected = new BLIP.Utils.LocalEvent("ItemSelected");
			this.initEvents();
		},

		initEvents : function() {
			this.domRoot.find(this.captionSelector).bind("click", this.delegate(this.on_captionClicked));
			this.domRoot.find(".DropDownItem").bind("click", this.delegate(this.on_itemClicked));
			$(document.body).bind("click", this.delegate(this.on_documentClicked));
		},


		on_itemClicked : function(event) {
			this.setSelected(event.target);
			this.item = true;

			return false;
		},

		on_captionClicked : function(event) {
			if (this.isOpen()) {
			    this.closeDropDown();
			}
			else {
				this.openDropDown();
			}

			event.stopPropagation();
		},

		on_documentClicked : function(event) {
			if (this.isOpen()) {
				this.closeDropDown();
//				event.preventDefault();
			}
		},

		isOpen : function() {
			return this.domRoot.hasClass("Open");
		},

		openDropDown : function() {
			this.domRoot.addClass("Open");
		},

		closeDropDown : function() {
			this.domRoot.removeClass("Open");
		},

		setSelected : function(item) {
			this.setCaption(item.innerHTML);
			this.selectedItem = item;
			this.onItemSelected.fire(item);
		},

		setCaption : function(caption) {
			this.domRoot.find(".CurrentlySelected .Caption").html(caption);
		}
	}
);

