// JavaScript Document

var counter = 0;
var columns = new Array();

function init() {
	if (document.getElementById('rc')) { columns.push('rc'); }
  if (document.getElementById('body')) { columns.push('body'); }
  if (document.getElementById('lc')) { columns.push('lc'); }
	setHeight(columns);
	if (document.getElementById('moreFields')) {
    document.getElementById('moreFields').onclick = moreFields;
    moreFields();
  }
}

function setHeight(input,size) {
  var ids = input;
  var len = size || -1;
  size = 0;
  var count = input.length;
  for (var i=0;i<count;i++) {
	  ids[i] = document.getElementById(ids[i]);
    if (ids[i].scrollHeight > size) { size = ids[i].scrollHeight; }
  }
  for (var i=0;i<count;i++) {
    if (len < 0) { 
		  ids[i].style.height = size + 'px';
		} else {
		  ids[i].style.height = len + 'px';
		}
  }
}

function moreFields() {
  counter++;
  var newFields = document.getElementById('readroot').cloneNode(true);
  var insertHere = document.getElementById('writeroot');
  matches = r_scan(newFields,'name!=null');
  for (var i=0;i<matches.length;i++) { 
	  matches[i].name += counter;
	}
  newFields.style.display = 'block';
  insertHere.parentNode.insertBefore(newFields,insertHere);
  document.getElementById('body').style.height = 'auto';
}

function r_scan(id,condition) {
  var currentNode = id; var matchNode = new Array();
  var read_all_nodes = false; var lastNode = 'abc';
  while (!read_all_nodes) {
  if (currentNode.parentNode==null&&(currentNode.childNodes==null||currentNode.firstChild==lastNode)&&currentNode.nextSibling==null) {
    read_all_nodes = true;
  } else if (currentNode.childNodes!=null&&currentNode.firstChild!=null&&currentNode.firstChild!=lastNode) {
    currentNode = currentNode.firstChild;
    if (eval('currentNode.'+condition)) { matchNode.push(currentNode); }
  } else if (currentNode.nextSibling!=null) {
    currentNode = currentNode.nextSibling;
    if (eval('currentNode.'+condition)) { matchNode.push(currentNode); }
  } else if (currentNode.parentNode!=null) {
    lastNode = currentNode.parentNode.firstChild;
    currentNode = currentNode.parentNode;
  } else {
    throw 'Unexpected node configuration.';
    break;
  }
  } 
  return matchNode;
}

function openEditWindow(id) {
  var editWindow = window.open("","","height=500, width=400,toolbar=no,scrollbars=no,menubar=no");
  editWindow.document.write("<TITLE>Edit '"+id+"'</TITLE>");
  editWindow.document.write("<BODY>");
  editWindow.document.write("<TEXTAREA style=\"width:100%;height:100%;\" id=\"editField\" ");
  editWindow.document.write("onchange=\"window.opener.document.getElementById('"+id+"').value = ");
  editWindow.document.write("document.getElementById('editField').value;\">");
  editWindow.document.write(document.getElementById(id).value);
  editWindow.document.write("</TEXTAREA>");
  editWindow.document.write("</BODY>");
  editWindow.document.write("</HTML>");
}
