//menuBoxDirection 1/fekvő 2/álló
//menuBoxOpeningDirectio = 1/felnyíló - 2/jobbranyíló - 3/lenyíló - 4/balranyíló
$(document).ready(function(){

	$menus = $('.menuBox').each(function() {
		$menu = $(this);
		$roots = $menu.find('.menuBoxMain');
		$roots.each(function() {
			$root = $(this);
			$content = $root.find('div.menuBoxSub')
			
			if ($content.length > 0)
			{	
				posX = 'left';
				posY = 'bottom';
				directionH = 'right';
				directionV = 'down';
				offsetX = 0;
				offsetY = 0;
				// open up
				if ($menu.hasClass('menuBoxOpeningDirection1'))
				{
					posX = 'left';
					posY = 'top';
					directionH = 'right';
					directionV = 'up';
					offsetX = 0;
					offsetY = $menu.height();
				} 
				// open right
				else if ($menu.hasClass('menuBoxOpeningDirection2'))
				{
					posX = 'right';
					posY = 'top';
					directionH = 'right';
					directionV = 'down';
					offsetX = 0;
					offsetY = 0;
				}
				// open down
				else if ($menu.hasClass('menuBoxOpeningDirection3'))
				{
					posX = 'left';
					posY = 'bottom';
					directionH = 'right';
					directionV = 'down';
					offsetX = 0;
					offsetY = 0;
				}
				// open left
				else if ($menu.hasClass('menuBoxOpeningDirection4'))
				{
					posX = 'left';
					posY = 'top';
					directionH = 'left';
					directionV = 'down';
					offsetX = $menu.width();
					offsetY = 0;
				}
				$root.menu({
					content: $content.html(),
					positionOpts: {
						posX: posX, 
						posY: posY,
						offsetX: offsetX,
						offsetY: offsetY,
						directionH: directionH,
						directionV: directionV, 
						// do horizontal collision detection  
						detectH: true, 
						// do vertical collision detection
						detectV: true 
					}					
				});
			}
			else
			{
				$root.mouseover(function() { killAllMenus(); });
			}
		});
	});

});

/*-------------------------------------------------------------------- 
Scripts for creating and manipulating custom menus based on standard <ul> markup
Version: 3.0, 03.31.2009

By: Maggie Costello Wachs (maggie@filamentgroup.com) and Scott Jehl (scott@filamentgroup.com)
	http://www.filamentgroup.com
 * reference articles: http://www.filamentgroup.com/lab/jquery_ipod_style_drilldown_menu/
		
Copyright (c) 2009 Filament Group
Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
--------------------------------------------------------------------*/

var allUIMenus = [];

var killAllMenus = function() {
	jQuery.each(allUIMenus, function(i) {
		if (allUIMenus[i].menuOpen) {
			allUIMenus[i].kill();
		}
		;
	});
};

function MenuNavigate(link)
{
	$link = $(link);
	var url = $link.attr('href');
	var target = $link.attr('target');
	if (target == '')
	{
		top.location.href = url;	
	}
	else
	{
		window.open(url, target);		
	}
}
	
jQuery.fn.menu = function(options) {
	var caller = this;
	var options = options;
	var m = new Menu(caller, options);
	allUIMenus.push(m);

	jQuery(this).mouseover(function() {
		if (m.menuOpen == false) {
			m.showMenu();
		} else {
			m.kill();
		};
		return false;
	});
};

function Menu(caller, options) {
	var menu = this;
	var caller = jQuery(caller);
	if (typeof(options.content) == 'object')
	{
		var container = options.content.addClass('fg-menu-container');
	}
	else
	{
		var container = jQuery('<div class="fg-menu-container">' + options.content + '</div>');
	}

	this.menuOpen = false;
	this.menuExists = false;

	var options = jQuery.extend( {
		content : null,
		maxHeight : 180, // max height of menu (if a drilldown: height does
							// not include breadcrumb)
		positionOpts : {
			posX : 'left',
			posY : 'bottom',
			offsetX : 0,
			offsetY : 0,
			directionH : 'right',
			directionV : 'down',
			detectH : true, // do horizontal collision detection
			detectV : true, // do vertical collision detection
			linkToFront : false
		},
		showSpeed : 200, // show/hide speed in milliseconds
		// ----- multi-level menu defaults -----
		crossSpeed : 200 // cross-fade speed for multi-level menus
	}, options);



	this.kill = function() {
		jQuery(window).unbind('resize', this.resize);
		
		caller.removeClass('fg-menu-open');
		container.find('li').find('a');
		if (container.is('.fg-menu-flyout')) {
			menu.resetFlyoutMenu();
		};
		container.parent().hide();
		menu.menuOpen = false;
		jQuery(document).unbind('click', killAllMenus);
		jQuery(document).unbind('keydown');
	};

	this.showMenu = function() {
		killAllMenus();
		menu.create();
		var closure = this;
		this.resize = function() {closure.showMenu();};
		jQuery(window).resize(this.resize);
		caller.addClass('fg-menu-open');
		container.parent().show().click(function() {
			menu.kill();
			$a = caller.find('a:first');
			if ($a.length > 0)
			{
				MenuNavigate($a[0]);
			}
			return false;
		});
		container.hide().slideDown(options.showSpeed).find('.fg-menu:eq(0)');
		menu.menuOpen = true;
		jQuery(document).click(killAllMenus);
	};

	this.create = function() {
		container.css( {
			width : options.width
		}).appendTo('body').find('ul:first').not('.fg-menu-breadcrumb')
				.addClass('fg-menu');
		// when there are multiple levels of hierarchy, create flyout or
		// drilldown menu
		if (container.find('ul').size() > 1) {
			menu.flyout(container, options);
		} else {
			container.find('a').click(function() {
				menu.chooseItem(this);
				return false;
			});
		};

		menu.setPosition(container, caller, options);
		menu.menuExists = true;
	};

	this.chooseItem = function(item) {
		menu.kill();
		// edit this for your own custom function/callback:
		jQuery('#menuSelection').text(jQuery(item).text());
		MenuNavigate(item);
	};
};

Menu.prototype.flyout = function(container, options) {
	var menu = this;

	this.resetFlyoutMenu = function() {
		var allLists = container.find('ul ul');
		allLists.hide();
	};

	container.addClass('fg-menu-flyout').find('li:has(ul)').each(
			function() {
				var linkWidth = container.width();
				var showTimer, hideTimer;
				var allSubLists = jQuery(this).find('ul');

				allSubLists.css( {
					left : linkWidth,
					width : linkWidth
				}).hide();

				jQuery(this).find('a:eq(0)').addClass('fg-menu-indicator')
						.hover(
								function() {
									clearTimeout(hideTimer);
									var subList = jQuery(this).next();
									if (!fitVertical(subList, jQuery(this)
											.offset().top)) {
										subList.css( {
											top : 'auto',
											bottom : 0
										});
									}
									;
									if (!fitHorizontal(subList, jQuery(this)
											.offset().left + 100)) {
										subList.css( {
											left : 'auto',
											right : linkWidth,
											'z-index' : 999
										});
									}
									;
									showTimer = setTimeout(function() {
										subList.show(options.showSpeed);
									}, 300);
								},
								function() {
									clearTimeout(showTimer);
									var subList = jQuery(this).next();
									hideTimer = setTimeout(function() {
										subList
												.hide(options.showSpeed);
									}, 400);
								});

				jQuery(this).find('ul a').hover(
						function() {
							clearTimeout(hideTimer);
							if (jQuery(this).parents('ul').prev().is(
									'a.fg-menu-indicator')) {
								jQuery(this).parents('ul').prev();
							}
						},
						function() {
							hideTimer = setTimeout(function() {
								allSubLists.hide(options.showSpeed);
							}, 500);
						});
			});

	container.find('a').click(function() {
		menu.chooseItem(this);
		return false;
	});
};


/*
 * Menu.prototype.setPosition parameters (defaults noted with *): referrer = the
 * link (or other element) used to show the overlaid object settings = can
 * override the defaults: - posX/Y: where the top left corner of the object
 * should be positioned in relation to its referrer. X: left*, center, right Y:
 * top, center, bottom* - offsetX/Y: the number of pixels to be offset from the
 * x or y position. Can be a positive or negative number. - directionH/V: where
 * the entire menu should appear in relation to its referrer. Horizontal: left*,
 * right Vertical: up, down* - detectH/V: detect the viewport horizontally /
 * vertically - linkToFront: copy the menu link and place it on top of the menu
 * (visual effect to make it look like it overlaps the object)
 */

Menu.prototype.setPosition = function(widget, caller, options) {
	var el = widget;
	var referrer = caller;
	var dims = {
		refX : referrer.offset().left,
		refY : referrer.offset().top,
		refW : referrer.getTotalWidth(),
		refH : referrer.getTotalHeight()
	};
	var options = options;
	var xVal, yVal;

	jQuery('.menuPositionHelper').remove();
	var helper = jQuery('<div class="menuPositionHelper"></div>');
	helper.css( {
		position : 'absolute',
		left : dims.refX,
		top : dims.refY,
		width : dims.refW,
		height : dims.refH
	});

	el.wrap(helper);
	
	// get X pos
	switch (options.positionOpts.posX) {
	case 'left':
		xVal = 0;
		break;
	case 'center':
		xVal = dims.refW / 2;
		break;
	case 'right':
		xVal = dims.refW;
		break;
	}
	;

	// get Y pos
	switch (options.positionOpts.posY) {
	case 'top':
		yVal = 0;
		break;
	case 'center':
		yVal = dims.refH / 2;
		break;
	case 'bottom':
		yVal = dims.refH;
		break;
	}
	;

	// add the offsets (zero by default)
	xVal += options.positionOpts.offsetX;
	yVal += options.positionOpts.offsetY;

	// position the object vertically
	if (options.positionOpts.directionV == 'up') {
		el.css( {
			top : 'auto',
			bottom : yVal
		});
		if (options.positionOpts.detectV && !fitVertical(el)) {
			el.css( {
				bottom : 'auto',
				top : yVal
			});
		}
	} else {
		el.css( {
			bottom : 'auto',
			top : yVal
		});
		if (options.positionOpts.detectV && !fitVertical(el)) {
			el.css( {
				top : 'auto',
				bottom : yVal
			});
		}
	}
	;

	// and horizontally
	if (options.positionOpts.directionH == 'left') {
		el.css( {
			left : 'auto',
			right : xVal
		});
		if (options.positionOpts.detectH && !fitHorizontal(el)) {
			el.css( {
				right : 'auto',
				left : xVal
			});
		}
	} else {
		el.css( {
			right : 'auto',
			left : xVal
		});
		if (options.positionOpts.detectH && !fitHorizontal(el)) {
			el.css( {
				left : 'auto',
				right : xVal
			});
		}
	};
};

/* Utilities to sort and find viewport dimensions */

function sortBigToSmall(a, b) {
	return b - a;
};

jQuery.fn.getTotalWidth = function() {
	var result = jQuery(this).width() + parseInt(jQuery(this).css('paddingRight'))
	+ parseInt(jQuery(this).css('paddingLeft'))
	+ parseInt(jQuery(this).css('borderRightWidth'))
	+ parseInt(jQuery(this).css('borderLeftWidth'));
	if (isNaN(result) )
	{
		result = jQuery(this).width();
	}
	return result;
};

jQuery.fn.getTotalHeight = function() {
	var result = jQuery(this).height() + parseInt(jQuery(this).css('paddingTop'))
	+ parseInt(jQuery(this).css('paddingBottom'))
	+ parseInt(jQuery(this).css('borderTopWidth'))
	+ parseInt(jQuery(this).css('borderBottomWidth'));
	if (isNaN(result) )
	{
		result = jQuery(this).height();
	}
	
	return result;
};

function getScrollTop() {
	return self.pageYOffset || document.documentElement.scrollTop
			|| document.body.scrollTop;
};

function getScrollLeft() {
	return self.pageXOffset || document.documentElement.scrollLeft
			|| document.body.scrollLeft;
};

function getWindowHeight() {
	var de = document.documentElement;
	return self.innerHeight || (de && de.clientHeight)
			|| document.body.clientHeight;
};

function getWindowWidth() {
	var de = document.documentElement;
	return self.innerWidth || (de && de.clientWidth)
			|| document.body.clientWidth;
};

/*
 * Utilities to test whether an element will fit in the viewport Parameters: el =
 * element to position, required leftOffset / topOffset = optional parameter if
 * the offset cannot be calculated (i.e., if the object is in the DOM but is set
 * to display: 'none')
 */

function fitHorizontal(el, leftOffset) {
	var leftVal = parseInt(leftOffset) || jQuery(el).offset().left;
	return (leftVal + jQuery(el).width() <= getWindowWidth() + getScrollLeft() && leftVal
			- getScrollLeft() >= 0);
};

function fitVertical(el, topOffset) {
	var topVal = parseInt(topOffset) || jQuery(el).offset().top;
	return (topVal + jQuery(el).height() <= getWindowHeight() + getScrollTop() && topVal
			- getScrollTop() >= 0);
};

/*-------------------------------------------------------------------- 
 * javascript method: "pxToEm"
 * by:
 Scott Jehl (scott@filamentgroup.com) 
 Maggie Wachs (maggie@filamentgroup.com)
 http://www.filamentgroup.com
 *
 * Copyright (c) 2008 Filament Group
 * Dual licensed under the MIT (filamentgroup.com/examples/mit-license.txt) and GPL (filamentgroup.com/examples/gpl-license.txt) licenses.
 *
 * Description: Extends the native Number and String objects with pxToEm method. pxToEm converts a pixel value to ems depending on inherited font size.  
 * Article: http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/
 * Demo: http://www.filamentgroup.com/examples/pxToEm/	 	
 *							
 * Options:  	 								
 scope: string or jQuery selector for font-size scoping
 reverse: Boolean, true reverses the conversion to em-px
 * Dependencies: jQuery library						  
 * Usage Example: myPixelValue.pxToEm(); or myPixelValue.pxToEm({'scope':'#navigation', reverse: true});
 *
 * Version: 2.0, 08.01.2008 
 * Changelog:
 *		08.02.2007 initial Version 1.0
 *		08.01.2008 - fixed font-size calculation for IE
 --------------------------------------------------------------------*/

Number.prototype.pxToEm = String.prototype.pxToEm = function(settings) {
	// set defaults
	settings = jQuery.extend( {
		scope : 'body',
		reverse : false
	}, settings);

	var pxVal = (this == '') ? 0 : parseFloat(this);
	var scopeVal;
	var getWindowWidth = function() {
		var de = document.documentElement;
		return self.innerWidth || (de && de.clientWidth)
				|| document.body.clientWidth;
	};

	/*
	 * When a percentage-based font-size is set on the body, IE returns that
	 * percent of the window width as the font-size. For example, if the body
	 * font-size is 62.5% and the window width is 1000px, IE will return 625px
	 * as the font-size. When this happens, we calculate the correct body
	 * font-size (%) and multiply it by 16 (the standard browser font size) to
	 * get an accurate em value.
	 */

	if (settings.scope == 'body'
			&& jQuery.browser.msie
			&& (parseFloat(jQuery('body').css('font-size')) / getWindowWidth())
					.toFixed(1) > 0.0) {
		var calcFontSize = function() {
			return (parseFloat(jQuery('body').css('font-size')) / getWindowWidth())
					.toFixed(3) * 16;
		};
		scopeVal = calcFontSize();
	} else {
		scopeVal = parseFloat(jQuery(settings.scope).css("font-size"));
	}
	;

	var result = (settings.reverse == true) ? (pxVal * scopeVal).toFixed(2) + 'px'
			: (pxVal / scopeVal).toFixed(2) + 'em';
	return result;
};
