(function($, undefined){
	$.widget("charter.chtrmenu",$.ui.menu,{
		options: {
			alignSide:'left',
			activeButtonClassName:'active',
			top:null,
			left:null,
			posOnClick:false
		},

		_create: function(){
			this._super();

			var $element  = this.element,
				buttonId  = $element.prop('id').replace(/menu$/,'button'),
				$button   = $('#'+buttonId),
				self      = this,
				blurTimerAbandoned = 200,
				blurTimer;

			
			// store alignSide property in button
			$button.data('align-side',this.options.alignSide.toLowerCase() );

			$button.unbind('click');
			$button.unbind('mouseleave');
			$button.unbind('mouseenter');

			$button.click(function(e){
				// close all dropdown menus
				$(".dropdown-menu").hide();
				if( $(this).is(":visible") )
				{
					if($(this).hasClass( self.options.activeButtonClassName )){
						$(this).removeClass( self.options.activeButtonClassName );
						$( ('#' + $element.prop('id')) ).hide();
					} else {
						var pos  = $(this).offset(),
						    left = self.options.left,
						    top  = self.options.top,
						    opts = {};

						if(left===null){
							if( $(this).data('align-side') === 'right' )
							{
								var menuWidth = $(self.element).outerWidth();
								left = (Math.floor(pos.left) + 1 + $(this).outerWidth() - menuWidth) + "px";

							} else {
								left = (Math.floor(pos.left)-1) + "px";
							}
						}
						
						opts['left'] = left;
						if(top!==null){
							opts['top'] = top;
						}

						if(self.options.posOnClick){
							opts = $(this).position();
							opts['top'] += $(this).outerHeight();
						}

						$(this).addClass( self.options.activeButtonClassName );
						$( ('#' + $element.prop('id')) ).css(opts).show();
					}
				}
			}).mouseleave(function(e){
				blurTimer = setTimeout(function(){
					$('.dropdown-menu-button').removeClass( self.options.activeButtonClassName );
					$('.dropdown-menu').hide();
				},blurTimerAbandoned);
			});

			$element.mouseenter(function(e){
				clearTimeout(blurTimer);
			}).mouseleave(function(e){
				blurTimer = setTimeout(function(){
					$('.dropdown-menu-button').removeClass( self.options.activeButtonClassName );
					$('.dropdown-menu').hide();
				},blurTimerAbandoned);
			});
		}
	});
})( jQuery );
