// Current version: 1.1c
// 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
//
// 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 HOMEPAGE_PREFIX = 'homepageSel' // 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 = 'tblMenus'; // this should be named in the HTML
var ROW_BASE = 1; // first number (for display)
var ITERATION_FIELD = 'iterations'; // field to hold number of rows
var MAXLEVEL = 3;
var hasLoaded = false;
var inProgressGlobal = false; // to prevent multiple calls while a fade is happening
var nextId = 1;

function fillInRows(addRow, pagesList, menuList, nxtId) {
  hasLoaded = true;
  if(nxtId != null) {
    nextId = nxtId;
  }
  if(addRow) {addRowToTable(null,null,pagesList,menuList,null,null,null,-1,null,null,null,true);}
}

// CONFIG:
// myRowObject is an object for storing information about the table rows
function myRowObject(one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen) {
  this.one      = one;      // input text object
  this.two      = two;      // menu title
  this.three    = three;    // page input
  this.four     = four;     // page select
  this.five     = five;     // parent item
  this.six      = six;      // menu image
  this.seven    = seven;    // menu break
  this.eight    = eight;    // homepage
  this.nine     = nine;     // menu id
  this.ten      = ten;      // button object
  this.eleven   = eleven;   // button object
  this.twelve   = twelve;   // button object
  this.thirteen = thirteen; // button object
}

/*
 * insertRowToTable
 * Insert and reorder
 */
function insertRowToTableEnd() {
  if (hasLoaded) {
    if (!inProgressGlobal) {
      inProgressGlobal = true;

      addRowToTable(null,null,pagesList,menuList,null,null,null,-1,null,null,null,true);

      row.style.visibility = 'hidden';
      var countUp = 1;
      setTimeout('rowFade(' + countUp + ')', 200); // initial pause
    }
  }
}

function insertRowToTableHere(obj) {
  if (hasLoaded) {
    var tbl = document.getElementById(TABLE_NAME);
    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,-1,null,null,null,false);
      reorderRows(tbl, rowToInsertAt);
      _comboBoxArray = createComboList();
      repositionComboBox();

      row.style.visibility = 'hidden';
      var countUp = 1;
      setTimeout('rowFade(' + countUp + ')', 200); // initial pause
    }
  }
}

/*
 * addRowToTable
 * Inserts at row 'num', or appends to the end if no arguments are passed in. Dont pass in empty strings.
 */
function addRowToTable(num, m_title, page, menu, p_title, m_image, m_break, homepage, parent_id, page_id, menu_id, atEnd) {
  if (hasLoaded) {
    document.getElementById(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;
    }

    // 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', 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.setAttribute('id', 'bcs_comboBox');
    cell2.appendChild(spanEl);

    var pEl = document.createElement('input');
    pEl.setAttribute('type', 'text');
    pEl.setAttribute('name', PAGE_INP_PREFIX + iteration);
    pEl.setAttribute('id', 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', PAGE_SEL_PREFIX + iteration);
    psEl.setAttribute('id', 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_parentCell";
    cell3.setAttribute('title', 'Choose parent menu item if this is a submenu item.  Leave blank for top level.');
    ptEl = document.createElement('select');
    ptEl.setAttribute('name', 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";
    cell3.appendChild(ptEl);

    // cell 4 - item image
    var cell4 = row.insertCell(4);
    cell4.className = "mmg_imageCell";
    cell4.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', MENU_IMAGE_PREFIX + iteration);
    if(m_image == null) {
      mimEl.setAttribute('value', '');
    } else {
      mimEl.setAttribute('value', m_image);
    }
    mimEl.className = "mmg_imageInput";
    cell4.appendChild(mimEl);

    // cell 5 - item menu break
    var cell5 = row.insertCell(5);
    cell5.className = "mmg_breakCell";
    cell5.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', MENU_BREAK_PREFIX + iteration);
    mbEl.setAttribute('align', 'center');
    mbEl.setAttribute('value','yes');
    mbEl.className = "mbInput";
    cell5.appendChild(mbEl);
    if(m_break == 'yes') { // must come after append because of IE
      mbEl.setAttribute('checked', 'checked');
    }

    // cell 6 - item menu break
    var cell6 = row.insertCell(6);
    cell6.className = "mmg_homepageCell";
    cell6.setAttribute('title', 'Select this if you want this menu item to be your homepage');
    var hpEl;
    try {
      hpEl = document.createElement("<input type='radio' name='" + HOMEPAGE_PREFIX + "' id='" + HOMEPAGE_PREFIX + iteration + "' value='" + menu_id + "' class='hpInput' />");
    } catch(ex) {
      hpEl = document.createElement('input');
      hpEl.setAttribute('type', 'radio');
      hpEl.setAttribute('id', HOMEPAGE_PREFIX + iteration);
      hpEl.setAttribute('name', HOMEPAGE_PREFIX);
      hpEl.setAttribute('value',menu_id);
      hpEl.className = "hpInput";
    }
    cell6.appendChild(hpEl);
    if(homepage == menu_id) { // must come after append because of IE
      hpEl.setAttribute('checked', 'checked');
    }

    // cell 7 - hidden menu_id & delete button
    var cell7 = row.insertCell(7);
    var miEl = document.createElement('input');
    miEl.setAttribute('type', 'hidden');
    miEl.setAttribute('name', MENU_ID_PREFIX + iteration);
    if(menu_id == null) {
      miEl.setAttribute('value', nextId++);
    } else {
      miEl.setAttribute('value', menu_id);
    }
    cell7.appendChild(miEl);

    var btn1El = document.createElement('div');
    btn1El.setAttribute('alt', 'Delete this item');
    btn1El.setAttribute('title', 'Delete this item');
    btn1El.onclick = function () {deleteCurrentRow(this); return false;};
    btn1El.className = "mmg_deleteButton";
    cell7.appendChild(btn1El);

    // cell 8 - Insert button
    var cell8 = row.insertCell(8);
    var btn2El = document.createElement('div');
    btn2El.setAttribute('alt', 'Insert new line above this line');
    btn2El.setAttribute('title', 'Insert new line above this line');
    btn2El.onclick = function () {insertRowToTableHere(this); return false;};
    btn2El.className = "mmg_smallAddButton";
    cell8.appendChild(btn2El);

    // cell 9 - Up button
    var cell9 = row.insertCell(9);
    var btn3El = document.createElement('div');
    btn3El.setAttribute('alt', 'Move this item up');
    btn3El.setAttribute('title', 'Move this item up');
    btn3El.onclick = function () {moveRowUp(this); return false;};
    btn3El.className = "mmg_upButton";
    cell9.appendChild(btn3El);

    // cell 10 - Down button
    var cell10 = row.insertCell(10);
    var btn4El = document.createElement('div');
    btn4El.setAttribute('alt', 'Move this item down');
    btn4El.setAttribute('title', 'Move this item down');
    btn4El.onclick = function () {moveRowDown(this); return false;};
    btn4El.className = "mmg_downButton";
    cell10.appendChild(btn4El);

    // Pass in the elements you want to reference later
    // Store the myRow object in each row
    row.myRow = new myRowObject(textNode, mtEl, pEl, psEl, ptEl, mimEl, mbEl, hpEl, miEl, btn1El, btn2El, btn3El, btn4El);
    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) {
  //obj.parentNode.parentNode.parentNode.parentNode -  div.td.tr.tbody.table
  if (hasLoaded) {
    var mvRow = obj.parentNode.parentNode;
    var tbl = mvRow.parentNode.parentNode;
    var rIndex = mvRow.sectionRowIndex;

    if (obj.parentNode.parentNode.previousSibling) {
      rowChecked = swapRows(tbl, mvRow.sectionRowIndex, obj.parentNode.parentNode.previousSibling.sectionRowIndex);
      var b = obj.parentNode.parentNode;
      b.parentNode.insertBefore(b,b.previousSibling);
      if(rowChecked > -1) {
        tbl.tBodies[0].rows[rowChecked].myRow.eight.checked=true;
      }
    }
  }
}

//switch with the row below
function moveRowDown(obj) {
  if (hasLoaded) {
    var mvRow = obj.parentNode.parentNode;
    var tbl = mvRow.parentNode.parentNode;
    var rIndex = mvRow.sectionRowIndex;

    if (obj.parentNode.parentNode.nextSibling) {
      rowChecked = swapRows(tbl, mvRow.sectionRowIndex, obj.parentNode.parentNode.nextSibling.sectionRowIndex);
      var b = obj.parentNode.parentNode;
      b.parentNode.insertBefore(b,b.nextSibling.nextSibling);
      if(rowChecked > -1) {
        tbl.tBodies[0].rows[rowChecked].myRow.eight.checked=true;
      }
    }
  }
}

// If there isn't an element with an onclick event in your row, then this function can't be used.
function deleteCurrentRow(obj) {
  if (hasLoaded) {
    var delRow = obj.parentNode.parentNode;
    var tbl = delRow.parentNode.parentNode;
    var rIndex = delRow.sectionRowIndex;

    delRow.parentNode.deleteRow(rIndex);
    _comboBoxArray = createComboList();
    repositionComboBox();

    reorderRows(tbl, rIndex);
    document.getElementById(ITERATION_FIELD).value--;

    _comboBoxArray = createComboList();
    repositionComboBox();
  }
}

function swapRows(tbl, row1, row2) {
  if (hasLoaded) {
    if (tbl.tBodies[0].rows[row1] && tbl.tBodies[0].rows[row2]) {
      var count1 = row1 + ROW_BASE;
      var count2 = row2 + ROW_BASE;
      var rowChecked = -1;
      if(tbl.tBodies[0].rows[row1].myRow.eight.checked) {
        rowChecked = row2;
      } else if(tbl.tBodies[0].rows[row2].myRow.eight.checked) {
        rowChecked = row1;
      }

// Row1 becomes Row2
      tbl.tBodies[0].rows[row1].myRow.one.data = count2; // text
      tbl.tBodies[0].rows[row1].myRow.two.id = tbl.tBodies[0].rows[row1].myRow.two.name = MENU_TITLE_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].myRow.three.id = tbl.tBodies[0].rows[row1].myRow.three.name = PAGE_INP_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].myRow.four.id = tbl.tBodies[0].rows[row1].myRow.four.name = PAGE_SEL_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].myRow.five.id = tbl.tBodies[0].rows[row1].myRow.five.name = PARENT_ID_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].myRow.six.id = tbl.tBodies[0].rows[row1].myRow.six.name = MENU_IMAGE_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].myRow.seven.id = tbl.tBodies[0].rows[row1].myRow.seven.name = MENU_BREAK_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].myRow.eight.id = HOMEPAGE_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].myRow.nine.id = tbl.tBodies[0].rows[row1].myRow.nine.name = MENU_ID_PREFIX + count2; // input text
      tbl.tBodies[0].rows[row1].className = 'classy' + (row1 % 2);

// Row2 becomes Row1
      tbl.tBodies[0].rows[row2].myRow.one.data = count1; // text
      tbl.tBodies[0].rows[row2].myRow.two.id = tbl.tBodies[0].rows[row2].myRow.two.name = MENU_TITLE_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].myRow.three.id = tbl.tBodies[0].rows[row2].myRow.three.name = PAGE_INP_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].myRow.four.id = tbl.tBodies[0].rows[row2].myRow.four.name = PAGE_SEL_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].myRow.five.id = tbl.tBodies[0].rows[row2].myRow.five.name = PARENT_ID_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].myRow.six.id = tbl.tBodies[0].rows[row2].myRow.six.name = MENU_IMAGE_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].myRow.seven.id = tbl.tBodies[0].rows[row2].myRow.seven.name = MENU_BREAK_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].myRow.eight.id = HOMEPAGE_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].myRow.nine.id = tbl.tBodies[0].rows[row2].myRow.nine.name = MENU_ID_PREFIX + count1; // input text
      tbl.tBodies[0].rows[row2].className = 'classy' + (row2 % 2);

    }
  }
  return rowChecked;
}

function reorderRows(tbl, startingIndex) {
  if (hasLoaded) {
    if (tbl.tBodies[0].rows[startingIndex]) {
      var count = startingIndex + ROW_BASE;
      for (var i=startingIndex; i<tbl.tBodies[0].rows.length; i++) {
        tbl.tBodies[0].rows[i].myRow.one.data = count; // text
        tbl.tBodies[0].rows[i].myRow.two.id = tbl.tBodies[0].rows[i].myRow.two.name = MENU_TITLE_PREFIX + count; // menu title
        tbl.tBodies[0].rows[i].myRow.three.id = tbl.tBodies[0].rows[i].myRow.three.name = PAGE_INP_PREFIX + count; // page input
        tbl.tBodies[0].rows[i].myRow.four.id = tbl.tBodies[0].rows[i].myRow.four.name = PAGE_SEL_PREFIX + count; // page select
        tbl.tBodies[0].rows[i].myRow.five.id = tbl.tBodies[0].rows[i].myRow.five.name = PARENT_ID_PREFIX + count; // parent item
        tbl.tBodies[0].rows[i].myRow.six.id = tbl.tBodies[0].rows[i].myRow.six.name = MENU_IMAGE_PREFIX + count; // menu image
        tbl.tBodies[0].rows[i].myRow.seven.id = tbl.tBodies[0].rows[i].myRow.seven.name = MENU_BREAK_PREFIX + count; // menu break
        tbl.tBodies[0].rows[i].myRow.eight.id = HOMEPAGE_PREFIX + count; // homepage radio button
        tbl.tBodies[0].rows[i].myRow.nine.id = tbl.tBodies[0].rows[i].myRow.nine.name = MENU_ID_PREFIX + count; // menu id
        tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
        count++;
      }
    }
  }
}

function nextID(num) { // Find the next incremented number to use for new row
  var j = 0;
  if (hasLoaded) {
    var tbl = document.getElementById(TABLE_NAME);
    for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
      if(num != i) {
        if(parseInt(tbl.tBodies[0].rows[i].myRow.nine.value) > j) {
          j = parseInt(tbl.tBodies[0].rows[i].myRow.nine.value);
        }
      }
    }
    j++;
  }
  return j;
}

function checkMenuPage(obj, id, pageList) {
  if (hasLoaded) {
    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() {
  if (hasLoaded) {
    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].myRow.two.value != '') {
        var myHash = {id:tbl.tBodies[0].rows[i].myRow.nine.value, title:tbl.tBodies[0].rows[i].myRow.two.value};
        menuList[array_count++] = myHash;
      }
    }
    menuList.sort(sortByTitle);

    for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
      var selectedVal = tbl.tBodies[0].rows[i].myRow.five.options[tbl.tBodies[0].rows[i].myRow.five.selectedIndex].value;
      tbl.tBodies[0].rows[i].myRow.five.length = menuList.length;
      for(j=0;j<menuList.length;j++){
        tbl.tBodies[0].rows[i].myRow.five.options[j].value = menuList[j]['id'];
        tbl.tBodies[0].rows[i].myRow.five.options[j].text = menuList[j]['title'];
        if(menuList[j]['id'] == selectedVal && selectedVal != '') {
          tbl.tBodies[0].rows[i].myRow.five.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].myRow.five.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].myRow.five.options[tbl.tBodies[0].rows[i].myRow.five.selectedIndex].text;

  for (var i=0; i<tbl.tBodies[0].rows.length; i++) {
    if(tbl.tBodies[0].rows[i].myRow.two.value == cSel) {
      checkLevel(tbl.tBodies[0].rows[i].myRow.two, currentRow, ++levelCount);
    }
  }
}

// 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 _offsetTop;
var _offsetLeft;
var _offsetLeftClip;
var _comboBoxArray;
var _blkName = 'bcs_comboBox';

function initComboSel() {
  var browser = checkBrowser();
  if(browser[0] == "Explorer") {
    _offsetTop = 0;
    _offsetLeft = 0;
    _offsetLeftClip = 18;
  } else {
    _offsetTop = 0;
    _offsetLeft = 0;
    _offsetLeftClip = 20;
  }

  _comboBoxArray = createComboList();
  repositionComboBox();

  window.onresize = repositionComboBox;
}

function createComboList() {
  // get all "bcs_comboBox" block elements in the document
  var elements = null;
  var found = new Array();
  var re = new RegExp('\\b'+_blkName+'\\b');
  if (document.getElementsByTagName) {elements = document.getElementsByTagName('*');}
  else if (document.all) {elements = document.all.tags('*');}
  if (elements) {
    for (var i = 0; i < elements.length; ++i) {
      if (elements[i].id.search(re) != -1) {
        // Now we have a valid block element get the input and select id
        inpObj = elements[i].getElementsByTagName("input")[0];
        selObj = elements[i].getElementsByTagName("select")[0]
        found[found.length] = [inpObj.id,selObj.id];
        selObj.selectedIndex = -1;
      }
    }
  }
  return found;
}

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) {
  document.getElementById(cId).focus();
  return false;
}

function evtSelect(evt) {
  objs = checkEvent(evt);
  idEdit = objs[0];
  idSel = objs[1];
  if(idSel.selectedIndex > -1) {
    document.getElementById(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 findPos(obj) {
  // Credit for this function: http://www.quirksmode.org/js/findpos.html
  // Visit the URL for a complete tutorial on this function
  var curleft = curtop = parent_offSetLeft = parent_offSetTop = 0;
  if (obj.offsetParent) {
     curleft = obj.offsetLeft
     curtop = obj.offsetTop
     curwidth = obj.offsetWidth;
     while (obj = obj.offsetParent) {
        curleft += obj.offsetLeft
        curtop += obj.offsetTop
        if(obj.id) {
          parent_offSetLeft = obj.offsetLeft;
          parent_offSetTop = obj.offsetTop;
        }
     }
  }
  return [curleft,curtop,curwidth,parent_offSetLeft,parent_offSetTop];
}

function positionComboBox(inpId, selId) {
  inpObj = document.getElementById(inpId);
  selObj = document.getElementById(selId);
  // Positioning of the combotext boxes
  inpObj.style.marginRight = _offsetLeftClip+'px';
  inpObj.style.position = "relative";
  selObj.style.position = "absolute";
  ofs=findPos(inpObj);
  // Find the left/top & width of span
  selObj.style.top=(ofs[1]+_offsetTop+(ofs[4]*-1))+'px';      // Set select box top location
  selObj.style.left=(ofs[0]+_offsetLeft+(ofs[3]*-1))+'px';    // Set select box left location = curleft+_offsetLeft+parent_offSetLeft
  selObj.style.width=(inpObj.offsetWidth+_offsetLeftClip)+'px';
  // The next line crops the select box and shows only the button
  selObj.style.clip = 'rect(0px, '+selObj.offsetWidth+'px, auto, '+
                        (selObj.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;
  }

  selObj.style.visibility = 'visible';
}

function checkBrowser() {
  // Credit for this function: http://www.quirksmode.org/js/detect.html
  // Visit the URL for a complete tutorial on this function
  var BrowserDetect = {
    init: function () {
      this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
      this.version = this.searchVersion(navigator.userAgent)
        || this.searchVersion(navigator.appVersion)
        || "an unknown version";
      this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
      for (var i=0;i<data.length;i++) {
        var dataString = data[i].string;
        var dataProp = data[i].prop;
        this.versionSearchString = data[i].versionSearch || data[i].identity;
        if (dataString) {
          if (dataString.indexOf(data[i].subString) != -1)
            return data[i].identity;
        }
        else if (dataProp)
          return data[i].identity;
      }
    },
    searchVersion: function (dataString) {
      var index = dataString.indexOf(this.versionSearchString);
      if (index == -1) return;
      return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
      { string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
      },
      {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari"
      },
      {
        prop: window.opera,
        identity: "Opera"
      },
      {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
      },
      {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
      },
      {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
      },
      {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
      },
      {   // for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
      },
      {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
      },
      {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
      },
      {     // for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
      }
    ],
    dataOS : [
      {
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
      },
      {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
      },
      {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
      }
    ]

  };
  BrowserDetect.init();

//  document.write('Browser name:'+BrowserDetect.browser);
//  document.write("<br />");
//  document.write('Browser version: '+BrowserDetect.version);
//  document.write("<br />");
//  document.write('OS name: '+BrowserDetect.OS);
//  document.write("<br />");

  return [BrowserDetect.browser,BrowserDetect.version,BrowserDetect.OS];
}

function repositionComboBox() {
  for(j=0; j<_comboBoxArray.length;j++) {
    positionComboBox(_comboBoxArray[j][0],_comboBoxArray[j][1])
  }
}

