(function( $ ){
	$.fn.fancyMenu = function(options) {
		var settings = {
				vertical : false
		};

		if ( options ) { 
			$.extend( settings, options );
		}

		if(this.length == 0) {
			return;
		}	
		
		var over = function(el) {
		
			var list = el.children("ul");
			var winHeight = $(window).height();
			var winWidth = $(window).width();
			
			if(list.size() > 0) {	
					if(settings.vertical) {
						var leftPos = el.width(); 
					} else {
						var menuList = list.attr("class").split("-");
						var menuIndex = (menuList.length > 1)?parseInt(menuList[menuList.length - 1]):1;
						if(menuIndex > 2) {
							var leftPos = el.width(); 
						} else {
							var leftPos = 0;
						}
					}

					// horizontal position
					if((el.offset().left + el.width() + list.width()) > winWidth) {
						if(!el.parent().hasClass('main-menu-contents')) {
							list.css({left:-(el.width() + list.width())});
						}
					}														
					// vertical position..
					var selectedElTop = el.position().top;
					var selectedOffsetTop = el.offset().top;
					list.css({position:'absolute',marginLeft:leftPos,top:selectedElTop}).show();
					var listOffsetTop = list.offset().top;
					var listHeight = list.height();
					if((listOffsetTop + listHeight) > winHeight) {
						elTop =  winHeight - (list.height() + list.offset().top);
						list.css({top:(elTop + selectedElTop - 5)});
						if(list.offset().top < selectedElTop) {
							list.css({top:(selectedElTop - list.height() + el.height())});
						}
						
						if(list.offset().top < 0) {
							list.css({top:0}).css({top:-(list.offset().top)});
						}
					}
			}
		};

		var out = function (el) {
			el.children("ul").hide();
		}	
			
		var children = this.find(".has-children")		
		children.each(function(i){
			$(this).hover(
				function () {
				   over($(this))
				},
				function () {
				   out($(this))
				}
			);
		});	
	}
})( jQuery );
