/**
 * @author Nikolai Dimitrov
 * @copyright mochanin.com
 */

function marShowMenu(mParent, mId, top) {
  var menu;
  
  if (marMenus === null)
    return;
  if (!marMenus.length)
    return;
  if (marMenus.length < 1)
    return;
   
  // Clear any open menus
  marDoHideMenu();
  // Clear any scheduled hidings
  marStopHiding();
  
  if (!marMenus[mId])
    return;
    
  if (marMenus[mId].length > 0)
  	menu = marCreateMenu(mId);
  else
  	return;
  	
  marPositionMenu(mParent, menu, top);
  
  document.body.appendChild(menu);
}

function marHideMenu() {
	// If there is nothing opened we must not hide
	var menu = document.getElementById('marMenu');
	
	if (menu !== null)
		marTimeout = window.setTimeout(marDoHideMenu, marDelay);
}

function marCreateMenu(mId) {
	var menu = document.createElement('DIV');
	
	menu.id = 'marMenu';
	menu.className = 'marMenu';
	menu.setAttribute('marMenuId', mId);
	
	// Fill in the elements
	var html = "<div class=\"marContainer\" onMouseOver=\"marStopHiding();\" onMouseOut=\"marHideMenu();\">";
	for (var i=0; i<marMenus[mId].length; ++i) {
		html += "<div class=\"marItem\" onMouseOver=\"marItemOver(this);\" onMouseOut=\"marItemOut(this);\" onClick=\"marItemClick('"+ marMenus[mId][i][1] +"');\">"+ marMenus[mId][i][0] +"</div>";
	}
	html += "</div>";
	menu.innerHTML = html;
	
	return menu;
}

function marPositionMenu(mParent, menu, toppos) {
	var left = marFindLeft(mParent, toppos);
	var top = marFindTop(mParent, toppos);
	
	try {
		left += marOffsetLeft;
		top += marOffsetTop;
	} catch (e) {
	}
	
	menu.style.left = left +"px";
	menu.style.top = top +"px";
}

function marFindLeft(mParent, top) {
  var out = 0;
  
  if (!top)
    out += mParent.offsetWidth;
  else
    out -= 2;
  
  do {
  	out += mParent.offsetLeft;
  	mParent = mParent.offsetParent;
  } while(mParent !== null);
  
  return out;
}

function marFindTop(mParent, top) {
  var out = 0;
  
  if (top)
    out += mParent.offsetHeight - 5;
  
  do {
  	out += mParent.offsetTop;
  	mParent = mParent.offsetParent;
  } while(mParent !== null);
  
  return out;
}

function marDoHideMenu() {
	var menu = document.getElementById('marMenu');
	
	while(menu !== null) {
		document.body.removeChild(menu);
		menu = document.getElementById('marMenu');
	}
}

function marStopHiding() {
	if (marTimeout !== null)
		window.clearTimeout(marTimeout);
}



function marItemOver(item) {
	item.className = "marItemOver";
}

function marItemOut(item) {
	item.className = "marItem";
}

function marItemClick(url) {
	window.location = url;
}

