var custom_dropdowns = {
	box_class: 'custom_dropdown',
	trigger_class: 'custom_dropdown_trigger',
	list_class: 'custom_dropdown_list',
	
	initialize: function() {
		Event.observe(document, 'click', custom_dropdowns.hidden_dropdown);
	},
	
	hidden_dropdown: function (e){
		var target = e.element();
		var box = null;

		var clickedOnTrigger = target.hasClassName('custom_dropdown_trigger');
		// Finds out if the user clicked on a trigger. Otherwise the dropdown will popup when the user clicks on an unrelated element that shares the same ancestor.
		// Find the box containing this trigger element.
		target.ancestors().each(function(ancestor) {
			if(ancestor.hasClassName('custom_dropdown_trigger') && !clickedOnTrigger){
				clickedOnTrigger = true;
			}

			if (ancestor.hasClassName(custom_dropdowns.box_class)) {
				box = ancestor;
				throw $break;
			}
		});

		// Toggle all elements with class "list_class" inside box.
		if (box) {
			
			var visible = [];
			box.select('.'+custom_dropdowns.list_class).each(function(list) {
				if (list.visible()) {
					visible.push(list);
				}
			});
			
			custom_dropdowns.hide_all();

			box.select('.'+custom_dropdowns.list_class).each(function(list) {
				//e.stop();
				for (i = 0; i < visible.length; i++) {
					if (visible[i] == list) {
						throw $break;
					}
				}
				if(clickedOnTrigger){
					list.toggle();
					e.stop();
				}
				
			});
		} else {
			custom_dropdowns.hide_all();
		}
	},
	
	hide_all: function () {
		$$('.'+custom_dropdowns.list_class).each(function(list) {
			list.hide();
		});
	}
}


document.observe('dom:loaded', function() {
	custom_dropdowns.initialize();
});


