// Current version: 1.4
// This is based on the orignal js script:-
//    tabledeleterow.js version 1.2 2006-02-21 by mredkj.com
//
// Adapted by Peter Barkway baytree-cs.com 14-11-2006
// to incorporate fade and move rows up and down functionality
//
// Modified be Peter Barkway 04-07-2007
// Added extra fields to generate combobox facility
// Modified be Peter Barkway 01-10-2007
// To improve the combobox facility to work across more browsers
// Modified be Peter Barkway 10-11-2007
// To allow landing page radion button
// Modified be Peter Barkway 10-08-2008
// Added extra functionality to allow fo multiple menus.
// Streamlined code for speed
// Modified be Peter Barkway 17-10-2008
// Syncronised cell classnames with php class
// Modified be Peter Barkway 07-02-2010
// Modified getNextId to read and update a hidden field to help cope with multiple sites
// Modified be Peter Barkway 19-02-2010
// Updated to utilize mootools
//
// CONFIG notes. Below are some comments that point to where this script can be customized.
// Note: Make sure to include a <tbody></tbody> in your table's HTML

var MENU_ID_PREFIX = 'menu_id'; // this is being set via script
var MENU_TITLE_PREFIX = 'menu_title'; // this is being set via script
var MENU_IMAGE_PREFIX = 'menu_image'; // this is being set via script
var MENU_BREAK_PREFIX = 'menu_hr'; // this is being set via script
var TARGET_PREFIX = 'page_target'; // this is being set via script
var PAGE_INP_PREFIX = 'page_inp'; // this is being set via script
var PAGE_SEL_PREFIX = 'page_sel'; // this is being set via script
var PARENT_ID_PREFIX = 'parent_id'; // this is being set via script
var TABLE_NAME = 'mmgTable_1'; // this should be named in the HTML
var TABLE_NAME_PREFIX = 'mmgTable_'; // used as a default
var MENU_NAME_PREFIX = 'mmgMenu_'; // used as a default
var ROW_BASE = 1; // first number (for display)
var ITERATION_FIELD = 'iterations'; // field to hold number of rows
var MENU_ITERATION_FIELD = 'menu_iterations'; // field to hold number of rows
var MAXLEVEL = 3;
var NEXTID_FIELD = 'nextId';
var inProgressGlobal = false; // to prevent multiple calls while a fade is happening
var nextId = 1;

// Values below refer the the table cell positioning
var eOrder = 0;
var eMenuTitle = 1;
var ePageLink = 2;
var ePageSel = 2;
var ePageTarget = 3;
var eParent = 4;
var eImage = 5;
var eMenuBreak = 6;
var eMenuId = 7;

function fillInRows(addRow, pagesList, menuList, nxtId, tableName, menuCnt) {
  initComboSel();
  if(tableName != null) { TABLE_NAME = tableName; }
  if(nxtId != null) {
    nextId = nxtId;
  } else {
    nextId = getNextID();
  }
  if(addRow) {addRowToTable(null,null,pagesList,menuList,null,null,null,null,null,null,null,true,tableName,menuCnt);}
}

function insertRowToTableEnd(tableName, menuCnt) {
	if (!inProgressGlobal) {
		if(tableName != null) { TABLE_NAME = tableName; }
		inProgressGlobal = true;

		addRowToTable(null,null,pagesList,menuList,null,null,null,null,null,null,null,true,tableName,menuCnt);
		createComboList();
		repositionComboBox();

		row.style.visibility = 'hidden';
		var countUp = 1;
		setTimeout('rowFade(' + countUp + ')', 100); // initial pause
	}
}

function insertRowToTableHere(obj, menuCnt) {
	var tbl = obj.parentNode.parentNode.parentNode.parentNode;
	var rowToInsertAt = tbl.tBodies[0].rows.length;

	var insRow = obj.parentNode.parentNode;
	var rIndex = insRow.sectionRowIndex;
	if(rIndex >= 0 ) {
		rowToInsertAt = rIndex;
	}
	if (!inProgressGlobal) {
		inProgressGlobal = true;
		addRowToTable(rowToInsertAt,null,pagesList,menuList,null,null,null,null,null,null,null,false,tbl.id,menuCnt);
		reorderRows(tbl, rowToInsertAt, menuCnt);
		createComboList();
		repositionComboBox();

		row.style.visibility = 'hidden';
		var countUp = 1;
		setTimeout('rowFade(' + countUp + ')', 100); // initial pause
	}
}

function addRowToTable(num, m_title, page, menu, p_title, m_image, m_break, parent_id, page_id, menu_id,p_target, atEnd,tableName,menuCnt) {
	if(tableName != null) { TABLE_NAME = tableName; }
	document.getElementById(menuCnt + '_' + ITERATION_FIELD).value++;
	var tbl = document.getElementById(TABLE_NAME);
	var nextRow = tbl.tBodies[0].rows.length;
	var iteration = nextRow + ROW_BASE;
	if (num == null) {
		num = nextRow;
	} else {
		iteration = num + ROW_BASE;
	}
	if(menu_id == null) {
		menu_id = nextId++;
	}

	// add the row
	row = tbl.tBodies[0].insertRow(num);

	// CONFIG: requires classes named classy0 and classy1
	row.className = 'classy' + (iteration % 2);

	// CONFIG: This whole section can be configured

	// cell 0 - text
	var cell0 = row.insertCell(0);
	cell0.className = "mmg_orderCell";
	cell0.setAttribute('title', 'Order of menu item');
	var textNode = document.createTextNode(iteration);
	cell0.appendChild(textNode);

	// cell 1 - input menu title
	var cell1 = row.insertCell(1);
	cell1.className = "mmg_menuTitleCell";
	cell1.setAttribute('title', 'Enter the text that you wish to appear for this menu item');
	var mtEl = document.createElement('input');
	mtEl.setAttribute('type', 'text');
	mtEl.setAttribute('name', menuCnt + '_' + MENU_TITLE_PREFIX + iteration);
	mtEl.setAttribute('id', menuCnt + '_' + MENU_TITLE_PREFIX + iteration);
	if(m_title == null) {
		mtEl.setAttribute('value', '');
	} else {
		mtEl.setAttribute('value', m_title);
	}
	mtEl.className = "mmg_menuTitle";
	mtEl.onchange = function () {updateMenuChoice();};
	cell1.appendChild(mtEl);

	// cell 2 - select page
	var cell2 = row.insertCell(2);
	cell2.className = "mmg_pageLinkCell";
	cell2.setAttribute('title', 'Choose the page that this menu item will link to from the select list or type in a full path to the file or enter a URL address');

	var spanEl = document.createElement('span');
	spanEl.className = _blkName;
	cell2.appendChild(spanEl);

	var pEl = document.createElement('input');
	pEl.setAttribute('type', 'text');
	pEl.setAttribute('name', menuCnt + '_' + PAGE_INP_PREFIX + iteration);
	pEl.setAttribute('id', menuCnt + '_' + PAGE_INP_PREFIX + iteration);
	if(page_id == null) {
		pEl.setAttribute('value', '');
	} else if(page_id == 0 && p_title != '') {
		pEl.setAttribute('value', p_title);
	} else {
		for(i=0;i<page.length;i++){
			if(page[i]['id'] == page_id) {
				pEl.setAttribute('value', page[i]['title']);
			}
		}
	}
	pEl.className = "mmg_comboInput";
	spanEl.appendChild(pEl);

	psEl = document.createElement('select');
	psEl.setAttribute('name', menuCnt + '_' + PAGE_SEL_PREFIX + iteration);
	psEl.setAttribute('id', menuCnt + '_' + PAGE_SEL_PREFIX + iteration);
	psEl.className = "mmg_comboSel";
	psEl.setAttribute('tabIndex', -1);
	psEl.setAttribute('size', 1);
	if(page == null) {
		newop=document.createElement('option');
		newop.setAttribute('value',"");
		newop.appendChild(document.createTextNode(""));
		psEl.appendChild(newop)
	} else {
		for(i=0;i<page.length;i++){
			newop=document.createElement('option');
			newop.setAttribute('value',page[i]['id']);
			newop.appendChild(document.createTextNode(page[i]['title']));
			psEl.appendChild(newop)
		}
	}
	spanEl.appendChild(psEl);

	// cell 3 - select parent
	var cell3 = row.insertCell(3);
	cell3.className = "mmg_targetCell";
	cell3.setAttribute('title', 'Choose the target window for this menu item');
	ptgEl = document.createElement('select');
	ptgEl.setAttribute('name', menuCnt + '_' + TARGET_PREFIX + iteration);
	ptgEl.setAttribute('id', menuCnt + '_' + TARGET_PREFIX + iteration);
	ptgEl.setAttribute('size', '1');
	newop=document.createElement('option');
	newop.appendChild(document.createTextNode('_blank'));
	newop.setAttribute('value','_blank');
	if(p_target == '_blank') { newop.setAttribute('selected','selected'); }
	ptgEl.appendChild(newop)
	newop=document.createElement('option');
	newop.appendChild(document.createTextNode('_parent'));
	newop.setAttribute('value','_parent');
	if(p_target == '_parent') { newop.setAttribute('selected','selected'); }
	ptgEl.appendChild(newop)
	newop=document.createElement('option');
	newop.appendChild(document.createTextNode('_self'));
	newop.setAttribute('value','_self');
	if(p_target == '_self' || p_target == null) { newop.setAttribute('selected','selected'); }
	ptgEl.appendChild(newop)
	newop=document.createElement('option');
	newop.appendChild(document.createTextNode('_top'));
	newop.setAttribute('value','_top');
	if(p_target == '_top') { newop.setAttribute('selected','selected'); }
	ptgEl.appendChild(newop)
	ptgEl.className = "mmg_target";
	cell3.appendChild(ptgEl);

	// cell 4 - select parent
	var cell4 = row.insertCell(4);
	cell4.className = "mmg_parentCell";
	cell4.setAttribute('title', 'Choose parent menu item if this is a submenu item.  Leave blank for top level.');
	ptEl = document.createElement('select');
	ptEl.setAttribute('name', menuCnt + '_' + PARENT_ID_PREFIX + iteration);
	ptEl.setAttribute('id', menuCnt + '_' + PARENT_ID_PREFIX + iteration);
	ptEl.setAttribute('size', '1');
	if(menu == null) {
		newop=document.createElement('option');
		newop.appendChild(document.createTextNode(""));
		newop.setAttribute('value',"");
		ptEl.appendChild(newop)
	} else {
		for(i=0;i<menu.length;i++){
			newop=document.createElement('option');
			newop.appendChild(document.createTextNode(menu[i]['title']));
			newop.setAttribute('value',menu[i]['id']);
			if(menu[i]['id'] == parent_id) {
				newop.setAttribute('selected','selected');
			}
			ptEl.appendChild(newop)
		}
	}
	ptEl.onchange = function () {checkLevel(this, this, 1);};
	ptEl.className = "mmg_parentSelect";
	cell4.appendChild(ptEl);

	// cell 5 - item image
	var cell5 = row.insertCell(5);
	cell5.className = "mmg_imageCell";
	cell5.setAttribute('title', 'Enter the path for an image to appear next to this menu item.  Leave blank if no image required.');
	var mimEl = document.createElement('input');
	mimEl.setAttribute('type', 'text');
	mimEl.setAttribute('name', menuCnt + '_' + MENU_IMAGE_PREFIX + iteration);
	mimEl.setAttribute('id', menuCnt + '_' + MENU_IMAGE_PREFIX + iteration);
	if(m_image == null) {
		mimEl.setAttribute('value', '');
	} else {
		mimEl.setAttribute('value', m_image);
	}
	mimEl.className = "mmg_imageInput";
	cell5.appendChild(mimEl);

	// cell 6 - item menu break
	var cell6 = row.insertCell(6);
	cell6.className = "mmg_breakCell";
	cell6.setAttribute('title', 'Check this box if you wish to have a break after this item.');
	var mbEl = document.createElement('input');
	mbEl.setAttribute('type', 'checkbox');
	mbEl.setAttribute('name', menuCnt + '_' + MENU_BREAK_PREFIX + iteration);
	mbEl.setAttribute('id', menuCnt + '_' + MENU_BREAK_PREFIX + iteration);
	mbEl.setAttribute('align', 'center');
	mbEl.setAttribute('value','yes');
	mbEl.className = "mmg_menuBreak";
	cell6.appendChild(mbEl);
	if(m_break == 'yes') { // must come after append because of IE
		mbEl.setAttribute('checked', 'checked');
	}

	// cell 7 - hidden menu_id & delete button
	var cell7 = row.insertCell(7);
	cell7.innerHTML += '<div class="mmg_deleteButton" alt="Delete this item" title="Delete this item" onclick="deleteCurrentRow(this, ' + menuCnt + '); return false;"></div>';
	var miEl = document.createElement('input');
	miEl.setAttribute('type', 'hidden');
	miEl.setAttribute('name', menuCnt + '_' + MENU_ID_PREFIX + iteration);
	miEl.setAttribute('id', menuCnt + '_' + MENU_ID_PREFIX + iteration);
	miEl.setAttribute('value', menu_id);
	cell7.appendChild(miEl);

	// cell 8 - Insert button
	var cell8 = row.insertCell(8);
	cell8.innerHTML += '<div class="mmg_smallAddButton" alt="Insert new line above this line" title="Insert new line above this line" onclick="insertRowToTableHere(this, ' + menuCnt + '); return false;"></div>';

	// cell 9 - Up button
	cell9 = row.insertCell(9);
	cell9.innerHTML += '<div class="mmg_upButton" alt="Move this item up" title="Move this item up" onclick="moveRowUp(this, ' + menuCnt + '); return false;"></div>';

	// cell 10 - Down button
	var cell10 = row.insertCell(10);
	cell10.innerHTML += '<div class="mmg_downButton" alt="Move this item down" title="Move this item down" onclick="moveRowDown(this, ' + menuCnt + '); return false;"></div>';

	if(atEnd) {
		_comboBoxArray.push([pEl.id,psEl.id]);
	}
	positionComboBox(pEl.id,psEl.id);
}

function rowFade(countUp) {
  row.style.visibility = 'visible';
  for (var i=0; i<row.cells.length; i++) {
    row.cells[i].style.filter = 'alpha(opacity=' + (countUp * 10) + ')'; // IE
  }
  row.style.opacity = countUp / 10; // CSS 3
  countUp += 2;
  if (countUp < 10) {
    setTimeout('rowFade(' + countUp + ')', 75); // remaining pauses
  } else {
    inProgressGlobal = false;
  }
}

// switch with the row above
function moveRowUp(obj, menuCnt) {
  //obj.parentNode.parentNode.parentNode.parentNode -  div.td.tr.tbody.table
	var mvRow = obj.parentNode.parentNode;
	var tbl = mvRow.parentNode.parentNode;
	var rIndex = mvRow.sectionRowIndex;

	if (mvRow.previousSibling) {
		swapRows(tbl, mvRow.sectionRowIndex, obj.parentNode.parentNode.previousSibling.sectionRowIndex,menuCnt);
		var b = obj.parentNode.parentNode;
		b.parentNode.insertBefore(b,b.previousSibling);
	}
}

//switch with the row below
function moveRowDown(obj, menuCnt) {
	var mvRow = obj.parentNode.parentNode;
	var tbl = mvRow.parentNode.parentNode;
	var rIndex = mvRow.sectionRowIndex;

	if (mvRow.nextSibling) {
		swapRows(tbl, mvRow.sectionRowIndex, obj.parentNode.parentNode.nextSibling.sectionRowIndex,menuCnt);
		var b = obj.parentNode.parentNode;
		b.parentNode.insertBefore(b,b.nextSibling.nextSibling);
	}
}

// If there isn't an element with an onclick event in your row, then this function can't be used.
function deleteCurrentRow(obj, menuCnt) {
	var delRow = obj.parentNode.parentNode;
	var tbl = delRow.parentNode.parentNode;
	var rIndex = delRow.sectionRowIndex;

	delRow.parentNode.deleteRow(rIndex);
	createComboList();
	repositionComboBox();

	reorderRows(tbl, rIndex, menuCnt);
	document.getElementById(menuCnt + '_' + ITERATION_FIELD).value--;

	createComboList();
	repositionComboBox();
}

function swapRows(tbl, row1, row2, menuCnt) {
	if (tbl.tBodies[0].rows[row1] && tbl.tBodies[0].rows[row2]) {
		var count1 = row1 + ROW_BASE;
		var count2 = row2 + ROW_BASE;

// Row1 becomes Row2
		j1 = tbl.tBodies[0].rows[row1].cells[eMenuTitle].getElementsByTagName('input')[0];
		j2 = tbl.tBodies[0].rows[row1].cells[ePageLink].getElementsByTagName('input')[0];
		j3 = tbl.tBodies[0].rows[row1].cells[ePageSel].getElementsByTagName('select')[0];
		j4 = tbl.tBodies[0].rows[row1].cells[ePageTarget].getElementsByTagName('select')[0];
		j5 = tbl.tBodies[0].rows[row1].cells[eParent].getElementsByTagName('select')[0];
		j6 = tbl.tBodies[0].rows[row1].cells[eImage].getElementsByTagName('input')[0];
		j7 = tbl.tBodies[0].rows[row1].cells[eMenuBreak].getElementsByTagName('input')[0];
		j8 = tbl.tBodies[0].rows[row1].cells[eMenuId].getElementsByTagName('input')[0];

		tbl.tBodies[0].rows[row1].cells[eOrder].innerHTML = count2;
		j1.id = j1.name = menuCnt + '_' + MENU_TITLE_PREFIX + count2;
		j2.id = j2.name = menuCnt + '_' + PAGE_INP_PREFIX + count2;
		j3.id = j3.name = menuCnt + '_' + PAGE_SEL_PREFIX + count2;
		j4.id = j4.name = menuCnt + '_' + TARGET_PREFIX + count2;
		j5.id = j5.name = menuCnt + '_' + PARENT_ID_PREFIX + count2;
		j6.id = j6.name = menuCnt + '_' + MENU_IMAGE_PREFIX + count2;
		j7.id = j7.name = menuCnt + '_' + MENU_BREAK_PREFIX + count2;
		j8.id = j8.name = menuCnt + '_' + MENU_ID_PREFIX + count2;
		tbl.tBodies[0].rows[row1].className = 'classy' + (row1 % 2);

// Row2 becomes Row1
		j1 = tbl.tBodies[0].rows[row2].cells[eMenuTitle].getElementsByTagName('input')[0];
		j2 = tbl.tBodies[0].rows[row2].cells[ePageLink].getElementsByTagName('input')[0];
		j3 = tbl.tBodies[0].rows[row2].cells[ePageSel].getElementsByTagName('select')[0];
		j4 = tbl.tBodies[0].rows[row2].cells[ePageTarget].getElementsByTagName('select')[0];
		j5 = tbl.tBodies[0].rows[row2].cells[eParent].getElementsByTagName('select')[0];
		j6 = tbl.tBodies[0].rows[row2].cells[eImage].getElementsByTagName('input')[0];
		j7 = tbl.tBodies[0].rows[row2].cells[eMenuBreak].getElementsByTagName('input')[0];
		j8 = tbl.tBodies[0].rows[row2].cells[eMenuId].getElementsByTagName('input')[0];

		tbl.tBodies[0].rows[row2].cells[eOrder].innerHTML = count1;
		j1.id = j1.name = menuCnt + '_' + MENU_TITLE_PREFIX + count1;
		j2.id = j2.name = menuCnt + '_' + PAGE_INP_PREFIX + count1;
		j3.id = j3.name = menuCnt + '_' + PAGE_SEL_PREFIX + count1;
		j4.id = j4.name = menuCnt + '_' + TARGET_PREFIX + count1;
		j5.id = j5.name = menuCnt + '_' + PARENT_ID_PREFIX + count1;
		j6.id = j6.name = menuCnt + '_' + MENU_IMAGE_PREFIX + count1;
		j7.id = j7.name = menuCnt + '_' + MENU_BREAK_PREFIX + count1;
		j8.id = j8.name = menuCnt + '_' + MENU_ID_PREFIX + count1;
		tbl.tBodies[0].rows[row2].className = 'classy' + (row2 % 2);
	}
}

function reorderRows(tbl, startingIndex, menuCnt) {
	if (tbl.tBodies[0].rows[startingIndex]) {
		var count = startingIndex + ROW_BASE;
		for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++) {
			j1 = tbl.tBodies[0].rows[i].cells[eMenuTitle].getElementsByTagName('input')[0];
			j2 = tbl.tBodies[0].rows[i].cells[ePageLink].getElementsByTagName('input')[0];
			j3 = tbl.tBodies[0].rows[i].cells[ePageSel].getElementsByTagName('select')[0];
			j4 = tbl.tBodies[0].rows[i].cells[ePageTarget].getElementsByTagName('select')[0];
			j5 = tbl.tBodies[0].rows[i].cells[eParent].getElementsByTagName('select')[0];
			j6 = tbl.tBodies[0].rows[i].cells[eImage].getElementsByTagName('input')[0];
			j7 = tbl.tBodies[0].rows[i].cells[eMenuBreak].getElementsByTagName('input')[0];
			j8 = tbl.tBodies[0].rows[i].cells[eMenuId].getElementsByTagName('input')[0];

//alert('row'+count+'='+j1.id+', '+j2.id+', '+j3.id+', '+j4.id+', '+j5.id+', '+j6.id+', '+j7.id+', '+j8.id);

			tbl.tBodies[0].rows[i].cells[eOrder].innerHTML = count;
			j1.id = j1.name = menuCnt + '_' + MENU_TITLE_PREFIX + count;
			j2.id = j2.name = menuCnt + '_' + PAGE_INP_PREFIX + count;
			j3.id = j3.name = menuCnt + '_' + PAGE_SEL_PREFIX + count;
			j4.id = j4.name = menuCnt + '_' + TARGET_PREFIX + count;
			j5.id = j5.name = menuCnt + '_' + PARENT_ID_PREFIX + count;
			j6.id = j6.name = menuCnt + '_' + MENU_IMAGE_PREFIX + count;
			j7.id = j7.name = menuCnt + '_' + MENU_BREAK_PREFIX + count;
			j8.id = j8.name = menuCnt + '_' + MENU_ID_PREFIX + count;
			tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
			count++;
		}
	}
}

// Find the next incremented number to use for new row
// This means going through the all the rows that exist and finding the highest number
function getNextID() {
  j = document.getElementById(NEXTID_FIELD).value;
  document.getElementById(NEXTID_FIELD).value++;
  return j;
}

function checkMenuPage(obj, id, pageList) {
	var itRow = obj.parentNode.parentNode;
	var tbl = itRow.parentNode.parentNode;
	var i = itRow.sectionRowIndex;
	var p =  tbl.tBodies[0].rows[i].cells[2].firstChild[tbl.tBodies[0].rows[i].cells[2].firstChild.selectedIndex].value;
	if(p > 0) {
		for (j=0; j < pageList.length; j++) {
			if(pageList[j]['id'] == p) {
				document.getElementById(id).value = pageList[j]['description'];
			}
		}
	} else {
		document.getElementById(id).value = '';
	}
}

function sortByTitle(a, b) {
   if(a['title'].toLowerCase() < b['title'].toLowerCase())
      return -1
   if(a['title'].toLowerCase() > b['title'].toLowerCase())
      return 1
   return 0
}

// Update the menu choices after a change to the menu title has been made
function updateMenuChoice() {
	var array_count = 0;
	menuList = new Array();
	var myHash = {id:'', title:''};
	menuList[array_count++] = myHash;
	var tbl = document.getElementById(TABLE_NAME);
	for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
		if(tbl.tBodies[0].rows[i].cells[eMenuTitle].getElementsByTagName('input')[0].value != '') {
			var myHash = {id:tbl.tBodies[0].rows[i].cells[eMenuId].getElementsByTagName('input')[0].value, title:tbl.tBodies[0].rows[i].cells[eMenuTitle].getElementsByTagName('input')[0].value};
			menuList[array_count++] = myHash;
		}
	}
	menuList.sort(sortByTitle);

	for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
		var e = tbl.tBodies[0].rows[i].cells[eParent].getElementsByTagName('select')[0];
		var selectedVal = e.options[e.selectedIndex].value;
		e.length = menuList.length;
		for(j=0;j<menuList.length;j++){
			e.options[j].value = menuList[j]['id'];
			e.options[j].text = menuList[j]['title'];
			if(menuList[j]['id'] == selectedVal && selectedVal != '') {
				e.options[j].selected = true;
			}
		}
	}
}

// Find out hown many levels we are down to
function checkLevel(obj, currentRow, levelCount) {
  if(levelCount > MAXLEVEL) {
    var itRow = currentRow.parentNode.parentNode;
    var tbl = itRow.parentNode.parentNode;
    var i = itRow.sectionRowIndex;
    alert("You have exceed the maxmimum menu depth of "+MAXLEVEL+"!\nPlease refer to your administrator to allow for an increase\nin the depth or choose an alternative parent for this item.");
    tbl.tBodies[0].rows[i].cells[eParent].getElementsByTagName('select')[0].selectedIndex = 0;
  } else {
    checkForParent(obj, currentRow, levelCount);
  }
}

// Find out hown many levels we are down to
function checkForParent(obj, currentRow, levelCount) {
  var itRow = obj.parentNode.parentNode;
  var tbl = itRow.parentNode.parentNode;
  var i = itRow.sectionRowIndex;
  var cSel = tbl.tBodies[0].rows[i].cells[eParent].getElementsByTagName('select')[0].options[tbl.tBodies[0].rows[i].cells[eParent].getElementsByTagName('select')[0].selectedIndex].text;

  for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
    if(tbl.tBodies[0].rows[i].cells[eMenuTitle].getElementsByTagName('input')[0].value == cSel) {
      checkLevel(tbl.tBodies[0].rows[i].cells[eMenuTitle].getElementsByTagName('input')[0], currentRow, ++levelCount);
    }
  }
}

function deleteMenuNode(e){
  // get the parent.parent of this object to get fieldset
  // get id of parent div object to get menu number
  // Remove div object
  // reorder div names and field names of other menu divs
  // decrement menu count
  var fldEl = e.parentNode.parentNode.parentNode; // Fieldset
  var divEl = e.parentNode.parentNode.id; // Div

  // Strip out number from divEl to give current menu number
  var divIdNum = divEl.match(/\d$/);

  // Remove div object
  var nodeCount = fldEl.childNodes.length;
  for(var c = nodeCount-1; c >= 0; c--) {
    if(fldEl.childNodes[c].id == MENU_NAME_PREFIX+divIdNum) {
      fldEl.removeChild(fldEl.childNodes[c]);
    }
  }

  // get current value of menu count
  var menuCnt = document.getElementById(MENU_ITERATION_FIELD).value;

  // reorder all the menus
  for(var i = parseInt(divIdNum) + 1; i <= menuCnt; i++) {
    var julie = i-1;
    var dObj = document.getElementById(MENU_NAME_PREFIX+i);
    dObj.id = MENU_NAME_PREFIX+julie;

    // find table in this div & then rename all the rows
    divChildrenCount = dObj.childNodes.length;
    for(var j = divChildrenCount-1; j >= 0; j--) {
      if(dObj.childNodes[j].id == i + '_' + ITERATION_FIELD) {
        var mb = document.getElementById('menuTitleBanner' + i);
        var butEl = document.getElementById('addToEnd_' + i);
        dObj.childNodes[j].id = dObj.childNodes[j].name = julie + '_' + ITERATION_FIELD;
        mb.innerHTML = "Menu " + julie;
        mb.id = "menuTitleBanner" + julie;
        butEl.innerHTML = '<div id="addToEnd_'+julie+'" class="mmg_bigAddButton" alt="Add new line at the end of the list" title="Add new line at the end of the list" onclick="insertRowToTableEnd(\'mmgTable_'+julie+'\', '+julie+');"></div>';
        butEl.id = "addToEnd_" + julie;
      } else if(dObj.childNodes[j].id == TABLE_NAME_PREFIX + i) {
        tbl = dObj.childNodes[j];
        tbl.id = TABLE_NAME_PREFIX + julie;
        reorderRows(tbl, 0, julie);
        initComboSel();
        break;
      }
    }
  }

  document.getElementById(MENU_ITERATION_FIELD).value--;
}

// Combo Box stuff
// ===================================================================
// Author: Peter Barkway
// WWW: http://www.baytree-cs.com/
// Version: 1.0d
// Date: 31/10/2007
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however it is
// appreciated by the author if at least my web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
//
// Please DO NOT link directly to my .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================

var _blkName = 'bcs_comboBox';
var _comboBoxArray = new Array(); 
if(Browser.Engine.trident) {
	var _offsetLeftClip = 18;
} else {
	var _offsetLeftClip = 14;
}
//window.onresize = repositionComboBox;

function initComboSel() {
  createComboList();
  repositionComboBox();
}

function createComboList() {
  // get all "bcs_comboBox" block elements in the document
  _comboBoxArray = new Array();
  var elements = $$('#_menuDetailsDivSet span.'+_blkName);
  if (elements) {
  	$each(elements, function(el, i) {
			// Now we have a valid block element get the input and select id
			inpObj = el.getChildren("input");
			selObj = el.getChildren("select");
			_comboBoxArray.push([inpObj[0].id,selObj[0].id]);
			selObj.selectedIndex = -1;
    });
  }
//	alert(print_r(_comboBoxArray));
}

function print_r(x) {
	var r = '';
	
	$each(x, function(el, i) {
	r += i+': '+el+'\n';
	});
	return r;

};
var_dump = print_r;

function checkEvent(evt){
  var ie_var = "srcElement";
  var moz_var = "target";
  // "target" for Mozilla, Netscape, Firefox et al. ; "srcElement" for IE
  if(evt[moz_var]) {
    return [ evt[moz_var]['inputEl'],evt[moz_var]['selectEl'] ];
  } else {
    return [ evt[ie_var]['inputEl'],evt[ie_var]['selectEl'] ];
  }
}

function comboFocus(cId) {
  $(cId).focus();
  return false;
}

function evtSelect(evt) {
  objs = checkEvent(evt);
  idEdit = objs[0];
  idSel = objs[1];
  if(idSel.selectedIndex > -1) {
    $(idEdit).value = idSel.options[idSel.options.selectedIndex].text;
    idSel.selectedIndex = -1;
  }
  comboFocus(idEdit);
}

function evtKey(evt) {
  objs = checkEvent(evt);
  idEdit = objs[0];
  idSel = objs[1];

  if(window.event)
    keyCode = window.event.keyCode;  //IE
  else
    keyCode = evt.keyCode;           //firefox

  if (keyCode == 27) {
    idSel.selectedIndex = -1;
    comboFocus(idEdit);
  }
}

function positionComboBox(inpId, selId) {
  inpObj = $(inpId);
  selObj = $(selId);
  //alert(inpId+', '+ selId);
  
  // Positioning of the combotext boxes
  inpObj.setStyles({"position": "absolute", "z-index":"100"});
	ofs = inpObj.getCoordinates(inpObj.parentNode);
  selObj.setStyles({"position": "relative", "z-index":"99", "height":ofs.height+'px', "left": ofs.left+'px', "width":(inpObj.offsetWidth+_offsetLeftClip)+'px'});

  if(window.addEventListener){ // Mozilla, Netscape, Firefox
    selObj.addEventListener('change', evtSelect, false);
    selObj.addEventListener('keyup', evtKey, false);
    selObj.inputEl = inpObj.id;
    selObj.selectEl = selObj;
  } else { // IE
    selObj.attachEvent('onchange', evtSelect);
    selObj.attachEvent('onkeyup', evtKey);
    selObj.inputEl = inpObj.id;
    selObj.selectEl = selObj;
  }
}

function repositionComboBox() {
 	$each(_comboBoxArray, function(el, i) {
    positionComboBox(el[0],el[1]);
  });
}

