
var DropMenu = function(button, onShow) { this.initialize(button, onShow); }; 
DropMenu.prototype = {

	initialize: function(button, onShow) {
		this.button = jQuery(button);
		this.menu   = this.button.next('.drop-menu-content');
		this.onShow = onShow;

		// Check button position on screen
		this.bottomMargin = jQuery(document.body).height() - 
							this.button.offset().top - 
							$('#main .footer').height();
		
		// Set menu position
		if (this.bottomMargin > this.menu.height()) {
			this.menu.css('top', this.button.position().top + this.button.height());
		} else {
			this.menu.css('top', this.button.position().top - this.menu.height());
		}
		this.menu.css('left', this.button.position().left);

		// Add hover to button when mouseover
		this.button.hover(
			function(){ jQuery(this).addClass('drop-menu-hover');    }, 
			function(){ jQuery(this).removeClass('drop-menu-hover'); }
		);

		// Open/close the menu when the user clicks the sort button
		var self = this;
		this.button.click(function(e){
			e.preventDefault();
			e.stopPropagation();
			if (self.menu.is(':visible')) self.hide(); else self.show();
		});
	},

	show: function() {
		// If the menu is already open, don't do anything
		if (this.menu.is(':visible')) return;

		// Close any other menus open
		jQuery(document).click();

		// Show the menu
		this.menu.fadeIn();
		this.button.addClass('menu-open');

		// Close the menu if the user clicks somewhere else
		var self = this;
		jQuery(document).bind('click', function(e) {
			self.hide();
			jQuery(document).unbind('click');
		});
		
		if (this.onShow) this.onShow(this);
	},

	hide: function() {
		// Hide the menu
		this.menu.hide();
		this.button.removeClass('menu-open');
	}
};

