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

function dropShowMenu(mParent, mId) {
	var menu;
	
	// Clear any open menus
	dropDoHideMenu();
	// Clear any scheduled hidings
	dropStopHiding();
	
	if (dropMenus[mId].length > 0)
		menu = dropCreateMenu(mId);
	else
		return;
		
	dropPositionMenu(mParent, menu);
	
	document.body.appendChild(menu);
}

function dropHideMenu() {
	// If there is nothing opened we must not hide
	var menu = document.getElementById('dropMenu');
	
	if (menu !== null)
		dropTimeout = window.setTimeout(dropDoHideMenu, dropDelay);
}

function dropCreateMenu(mId) {
	var menu = document.createElement('DIV');
	
	menu.id = 'dropMenu';
	menu.className = 'dropMenu';
	menu.setAttribute('dropMenuId', mId);
	
	// Fill in the elements
	var html = '<div class="dropContainer" onMouseOver="dropStopHiding();" onMouseOut="dropHideMenu();">';
	for (var i=0; i<dropMenus[mId].length; ++i) {
		html += '<div class="dropItem" onMouseOver="dropItemOver(this);" onMouseOut="dropItemOut(this);" onClick="dropItemClick(\''+ dropMenus[mId][i][1] +'\');">'+ dropMenus[mId][i][0] +'</div>';
	}
	html += "</div>";
	menu.innerHTML = html;
	
	return menu;
}

function dropPositionMenu(mParent, menu) {
	var left = dropFindLeft(mParent);
	var top = dropFindTop(mParent);
	
	try {
		left += dropOffsetLeft;
		top += dropOffsetTop;
	} catch (e) {
	}
	
	menu.style.left = left +"px";
	menu.style.top = top +"px";
}

function dropFindLeft(mParent) {
	var out = 0;
	
	do {
		out += mParent.offsetLeft;
		mParent = mParent.offsetParent;
	} while(mParent !== null);
	
	return out;
}

function dropFindTop(mParent) {
	var out = 0;
	
	out += mParent.offsetHeight;
	
	do {
		out += mParent.offsetTop;
		mParent = mParent.offsetParent;
	} while(mParent !== null);
	
	return out;
}

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

function dropStopHiding() {
	if (dropTimeout !== null)
		window.clearTimeout(dropTimeout);
}



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

function dropItemOut(item) {
	item.className = "dropItem";
}

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


