// ****************************************************************************
// FPGroup 2006.
// Filename: menu.js
// ----------
// General menu engine subroutines
// ****************************************************************************

// CONSTANTS
// ============================================================================
// menu[] columns
var PID = 0;										// Parent ID
var TITLE = 1;										// Title
var URL = 2;										// URL
var SUB = 3;										// Submenu available
var PARSED = 4;										// Item parsed

// smenu[] columns
var VIS = 0;										// Menu visible
var LEVEL = 1;										// Menu level
var TIMER = 2;										// Menu hide timer ID
var SIZE = 3;										// Menu size

// GENERAL MENU VARIABLES
// ============================================================================
var menu = new Array();								// Menu items array
var smenu = new Array();							// Submenus array
var timerId;										// Menu hide timeout timer ID
var overitem = -1;
var sm_to_hide = -1;

var stdout;

// TEMPLATES
// ============================================================================
var tpl_evnt = 'onmouseover="mover(this,1)" onmouseout="mout(this,1)" onclick="mclick(this)"';
var tpl_width = ' width="{WIDTH}"';
var tpl_height = ' height="{HEIGHT}"';
//var tpl_bgcolor = ' bgcolor="{BGCOLOR}"';
var tpl_class = ' class="{CLASS}"';

// MAIN MENU
// (defined in h_mmenu.js/v_mmenu.js)

// SUBMENU
// <DIV> container
var tpl_smt_div = '<div id="smt{MENU_ID}" style="position:absolute;visibility:hidden;left:0px;top:0px">{CONTENT}</div>';
// Submenu container table
var tpl_smt = '<table cellpadding="{CP}" cellspacing="{CS}" border="{BORDER}"{PARAMETERS}>{CONTENT}</table>';
// Submenu item passive
var tpl_smi = '<tr id="{MENU_ID}" {EVENTS}><td {CLASS}{HEIGHT}>{CONTENT}</td><td {CLASS} align="right">{POINTER}</td></tr>';

// DESCRIBE MENU STRUCTURE
// ============================================================================

// ----------------------------------------------------------------------------
// Add menu item
// ----------------------------------------------------------------------------
function menu_add(
	pid,											// Parent item ID
	title,											// Item title
	url												// Link URL
)
{
	menu[menu.length] = new Array (pid,title,url,0,0);
}

// BUILDING MENU AND SUBMENU
// ============================================================================

// ----------------------------------------------------------------------------
// Build all and put it to the document
// ----------------------------------------------------------------------------
function build_menu()
{
/*	stdout = document.getElementById('strerr');
	stdout.value = '';
	eprint ('Init - OK');*/

	// Find not terminal nodes
	var pid;
	for (var i=0;i<menu.length;i++)
		if (menu[i][PID] >= 0)
		{
			pid = menu[i][PID];
			menu[pid][SUB] = 1;
		}

 	document.writeln(build_mmenu());
	document.writeln(build_smenus());
}

// ----------------------------------------------------------------------------
// Build submenu tables
// ----------------------------------------------------------------------------
function build_smenus()
{
	var out='';

	// Get main menu top/left coordinates
	get_mmenu_coord();

	var level = 0;
	var pid = 0;
	// Build all submenu tables
	for (var i=0;i<menu.length;i++)
		if ((menu[i][PID] >= 0) && (menu[i][PARSED] < 1))
		{
			pid = menu[i][PID];
			ppid = menu[pid][PID];
			eprint('BUILD_SMENUS: menu['+i+'][PID]: '+pid+' PPID: '+ppid);
			if (smenu[ppid])
				level = smenu[ppid][LEVEL];
			else
				level = 0;

			out += build_smenu(pid,level);
		}

//	alert(out);
	return out;
}

// ----------------------------------------------------------------------------
// Build table of submenu with specified index
// ----------------------------------------------------------------------------
function build_smenu(idx,level)
{
	var out='', cnt=0;
	var par='';

	eprint ('BUILD_SMENU('+idx+', '+level+')');
	for (var i=0;i<menu.length;i++)
	{
		if (menu[i][PID] == idx)
		{
			eprint('BUILD_SMENU: i: '+i+' menu['+i+'][PID]: '+menu[i][PID]);
			out += str_replace(tpl_smi,'{CONTENT}',menu[i][TITLE]);
			if (menu[i][SUB])
				out = str_replace(out,'{POINTER}',tpl_ptr);
			else
				out = str_replace(out,'{POINTER}','&nbsp;');
			out = str_replace(out,'{MENU_ID}',i);
			out = str_replace(out,'{EVENTS}',tpl_evnt);

			// Build row parameters list
			if (s_smip_class)
				par = str_replace(tpl_class,'{CLASS}',s_smip_class);
			else
				par = '';
			out = str_replace(out,'{CLASS}',par);

			if (s_smi_height)
				par = str_replace(tpl_height,'{HEIGHT}',s_smi_height);
			else
				par = '';
			out = str_replace(out,'{HEIGHT}',par);

			cnt++;									// Increase row counter
			menu[i][PARSED] = 1;					// Mark node as parsed
		}
	}
	eprint('BUILD_SMENU: menu idx: '+idx+' size: '+cnt);


	if (out != '')
	{
		// Build menu table parameters
		par = '';
		if (s_smt_width)
			par += str_replace(tpl_width,'{WIDTH}',s_smt_width);
		if (s_smt_class)
			par += str_replace(tpl_class,'{CLASS}',s_smt_class);

		out = str_replace (tpl_smt,'{CONTENT}',out);
		out = str_replace (out,'{PARAMETERS}',par);
		out = str_replace (out,'{CP}',s_smt_cp);
		out = str_replace (out,'{CS}',s_smt_cs);
		out = str_replace (out,'{BORDER}',s_smt_border);
		out = str_replace (tpl_smt_div,'{CONTENT}',out);
		out = str_replace (out,'{MENU_ID}',idx);

		smenu[idx] = new Array(0,level+1,0,cnt);
	}
	return out;
}

// ----------------------------------------------------------------------------
// Get main menu top/left coords and put them to absTop/absLeft variables
// ----------------------------------------------------------------------------
function get_mmenu_coord()
{
	// Get main menu top/left coordinates
	var mm = document.getElementById('mainmenu');
	if (mm)
	{
		var coord = objectXY(mm);
		absLeft = coord[0];
		absTop = coord[1];
	}
	else
	{
		absLeft = 0;
		absTop = 0;
	}
}


//*********

function print_menu()
{
	var s='';
	for (var i=0;i<menu.length;i++)
		s += i+'. '+menu[i]+'\n';
	s += 'Total: '+menu.length;
	alert(s);
}

function print_smenu()
{
	var s='';
	for (var i=0;i<smenu.length;i++)
		s += i+'. '+smenu[i]+'\n';
	s += 'Total: '+smenu.length;
	alert(s);
}

//*********



// MENU ACTIVE SUBROUTINES
// ============================================================================

// ----------------------------------------------------------------------------
// 1. Main menu item mouse over
// ----------------------------------------------------------------------------
function mover(
	obj,											// Item object
	type											// Item type: 0-main,1-submenu
)
{
	eprint('MOVER('+obj.id+')');
	var idx = obj.id;								// Get item index

	if (type)
	{	// submenu
		set_style(idx,s_smia_class);				// Highlight item
		var pid = menu[idx][PID];					// Get item's menu index
		show_parents(pid);							// Don't hide all item's parent menus
	}
	else
	{
		set_style(idx,s_mmia_class);				// Highlight item
		clear_timer(idx);
	}

	if (smenu[idx])									// If submenu available
	{
		eprint('MOVER: smenu['+idx+']: '+smenu[idx]);
		hide_level(smenu[idx][LEVEL],idx);			// hide all submenus with the same level except IDX
		set_visibility(idx,1);						// show submenu
	}
	eprint('MOVER: end');
}

// ----------------------------------------------------------------------------
// 2. Main menu and submenu item mouse out
// ----------------------------------------------------------------------------
function mout(
	obj,											// Item object
	type											// Item type: 0-main,1-submenu
)
{
	var idx = obj.id;								// Get item index

	eprint ('MOUT: obj.id="'+obj.id+'"');
	if (type)
		set_style(idx,s_smip_class);				// Unhighlight item
	else
		set_style(idx,s_mmip_class);

	hide_visibles();
}

// ----------------------------------------------------------------------------
// 3. Click menu action
// ----------------------------------------------------------------------------
function mclick(
	obj												// Item object
)
{
	var idx = obj.id;
	var url = menu[idx][URL];
	if (url != '')
		document.location = url;
}

// ADDITIONAL FUNCTIONS
// ============================================================================

// ----------------------------------------------------------------------------
// 1. Set given style to menu item
// ----------------------------------------------------------------------------
function set_style(
	idx,											// Menu item index
	style											// New item style (CSS style name)
)
{
//	eprint ('SET_STYLE ('+idx+', '+style+')');
	var obj = document.getElementById(idx);
	if (obj.cells)
	{
		for (var i=0;i<obj.cells.length;i++)
			obj.cells[i].className = style;
//		alert ('CELLS: '+obj.cells.length);
	}
	obj.className = style;
}

// ----------------------------------------------------------------------------
// 2. Set given submenu table visibility. Immediately.
// ----------------------------------------------------------------------------
function set_visibility(
	idx,											// Submenu index
	state											// Visibility state. 0-hidden; 1-visible
)
{
	eprint('SET_VISIBILITY('+idx+', '+state+')');
	var obj = document.getElementById('smt'+idx);
	if (obj)
	{
		if (state)
		{
			var pmi = document.getElementById(idx);// get parent item object
			if (pmi)
			{
				var pcoord = objectXY(pmi);			// get parent's coords
				// set submenu coords
				if (menu[idx][PID] < 0)
				{	// show 1st level submenu
					obj.style.left = pcoord[0] - 10 + 'px';
					if ((obj.offsetLeft+obj.offsetWidth) > document.body.clientWidth)
						obj.style.left = pcoord[0] + pmi.offsetWidth - obj.offsetWidth - 10 +'px';

					if (slide_dir == 'up')
						obj.style.top = pcoord[1] - (s_smi_height*smenu[idx][SIZE] + 2) + 'px';
					else
						obj.style.top = pcoord[1] + pmi.offsetHeight + 2 + 'px';
				}
				else
				{	// show 2nd and more level submenu
					obj.style.left = pcoord[0] + pmi.offsetWidth + 'px';
					if ((obj.offsetLeft+obj.offsetWidth) > document.body.clientWidth)
						obj.style.left = pcoord[0] - obj.offsetWidth + 'px';

					if (slide_dir == 'up')
						obj.style.top = pcoord[1] + pmi.offsetHeight - (s_smi_height*smenu[idx][SIZE]) + 'px';
					else
						obj.style.top = pcoord[1] + 'px';
				}
			}

			obj.style.visibility = 'visible';
			smenu[idx][VIS] = 1;
		}
		else
		{
			obj.style.visibility = 'hidden';
			obj.style.top = 0 + 'px';
			obj.style.left = 0 + 'px';
			smenu[idx][VIS] = 0;
		}
	}
	eprint('SET_VISIBILITY: end');
}

// ----------------------------------------------------------------------------
// 3. Set timeout to hide submenu table
// ----------------------------------------------------------------------------
function hide(
	idx												// Submenu index
)
{
	if (smenu[idx] && (smenu[idx][VIS]))
	{
		clearTimeout(smenu[idx][TIMER]);
		smenu[idx][TIMER] = eval("setTimeout('set_visibility("+idx+",0)',timeout)");
	}
}

// ----------------------------------------------------------------------------
// 4. Clear submenus timeout timer
// ----------------------------------------------------------------------------
function clear_timer(
	idx												// Submenu index
)
{
	if (smenu[idx] && smenu[idx][TIMER])
		clearTimeout(smenu[idx][TIMER]);
}

// ----------------------------------------------------------------------------
// 5. Show all parents of given submenu
// ----------------------------------------------------------------------------
function show_parents(
	idx												// Submenu index
)
{
	while (idx >= 0)
	{
		clear_timer(idx);
		idx = menu[idx][PID];						// get submenu PID
	}
}

// ----------------------------------------------------------------------------
// 6. Set hide timeouts for all visible submenus
// ----------------------------------------------------------------------------
function hide_visibles()
{
//	eprint('HIDE_VISIBLES:
	for (var i=0;i<smenu.length;i++)
		if (smenu[i]) hide(i);						// set hide timeout
}

// ----------------------------------------------------------------------------
// 7. Hide visible submenus of given level. Immediately.
// ----------------------------------------------------------------------------
function hide_level(
	level,											// Level of submenus, that should be hidden
	expt											// Menu item to leave visible
)
{
	eprint('HIDE_LEVEL('+level+', '+expt+')');
	for (var i=0;i<smenu.length;i++)
		if (smenu[i] && (smenu[i][LEVEL] == level) && (i != expt))
			set_visibility(i,0);					// hide submenu
	eprint('HIDE_LEVEL: end');
}

// ===
// ----------------------------------------------------------------------------
//	Return object coordinates relative to HTML window object
// ----------------------------------------------------------------------------
function objectXY(obj)
{
	var x = 0, y = 0;
	do
	{
		x += obj.offsetLeft;
		y += obj.offsetTop
	}
	while (typeof(obj = obj.offsetParent) != 'undefined' && obj != null);
	return [x,y];
}

// ----------------------------------------------------------------------------
// Replace s1 entry to s2 in s3 string
// ----------------------------------------------------------------------------
function str_replace(s1,s2,s3)
{
	var i=0;

	if (s2 == "") s2 = " ";
	var s = "";
	while(i = s1.indexOf(s2))
	{
		if (i >= 0)
		{
			s = s1.substr(0,i) + s3;
			s1 = s + s1.substr(i+s2.length);
		}
		else
			break;
	}
	return s1;
}

function eprint(msg)
{
	return;
	if (stdout)
	{
		stdout.value = msg+'\n'+stdout.value;
		stdout.focus();
	}
}