function removeFieldRow(node){

    // XXX replace with getParentElement
    row = node.parentNode.parentNode;
    row.parentNode.removeChild(row);

    return;
}


function handleKeyPress (e) {
    /* Dispatcher for handling the last row */

    // XXX: Generalize window.event for windows
    // Grab current node, replicate, remove listener, append
    var currnode = window.event ? window.event.srcElement : e.currentTarget;
    /* 
       XXX Should add/remove event listeners via JS, but IE has
       non-standard methods.  Not hard, but for now, just check 
       if we are the last row.  If not, bail.
    */

    var tbody = getParentElement(currnode, "TBODY");
    //alert(currnode);
    var tr = getParentElement(currnode, "TR");
    var rows = tbody.getElementsByTagName("TR");

    if (rows.length == (tr.rowIndex)) {
	// Add all the last row specific stuff here
	var newtr = tr.cloneNode(true);
	tr.parentNode.appendChild(newtr);

	// Turn on hidden "delete" image for current node
	var img = tr.getElementsByTagName("img")[0];
	img.style.display = "inline";
    } else {
	// Handle all other keypress entries, like cursor keys
    }

    return;
}

function addNewFieldRow (e,node) {
    // Adding a new row in a (start,end) scenario works as follows:
    // 1) clone the table row. 2) Change the id of the select fields.
    // 3) Append the row to existing rows.
    var currnode = window.event ? window.event.srcElement : e.currentTarget;
    var tbody = getParentElement(currnode, "TBODY");
    var tr = getParentElement(currnode, "TR");
    //var rows = tbody.getElementsByTagName("TR");
    var nextcount = tbody.childNodes.length;
    //alert(nextcount);
    var hiddenFields; // List of fields manipulated by the calendar widget.
    var hiddenDiv; // div containing the hidden fields.
    var trChildren;
    var inputFields;
    var selectFields;
    var iid;
    var iidNew;
    var calendarFields;
    var tmpFields;
    var tmp;
    var tattr;
    var inputId='';
    var x1; var x2;
    var tclass;
    
    // Clone tr and adjust the hidden fields.
    var newtr = tr.cloneNode(true);
    var trc;
    var tdiv;
    var tname; var tvalue;
    var tid;
    trChildren = newtr.getElementsByTagName("TD"); // td
    for (i=0; i<2; i++) {
      // We've got 2 columns ('start','end'), this could be parametrized.
      trc = trChildren.item(i).childNodes;
      for (z=0;z<trc.length;z++) {
        // getElementsByTagName won't work here. This should work cross-browser.
        if (trc.item(z).tagName == 'DIV') {
          //alert('DIV');
          hiddenDiv = trc.item(z);
          break;
        }
        //if (trc.item(z).tagName == 'input') {
        //  alert('input found');
        //}
      }
      //alert('bla');
      inputFields = newtr.getElementsByTagName("INPUT");
      for (i=0;i<inputFields.length;i++) {
        // Replace the id by substituting the digits with the new row count.
        //iid = inputFields.item(i).getAttribute('id'); 
        inputFields.item(i).removeAttribute('class');
        iid = inputFields.item(i).getAttributeNode('id').nodeValue; 
        //alert(inputFields+' '+iid+' '+iid.replace(/__[\d]+/,'__'+nextcount)+' *** '+iid.replace(/_[\d]+/,'_'+nextcount));
        iidNew = iid.replace(/__[\d]+/,'__'+nextcount);
        if (iid == iidNew) {
          // We most likely have a hiddenField.
          iidNew = iid.replace(/_[\d]+/,'_'+nextcount);
          // Find the calendar field.
        }
        //alert(inputFields+' old:'+iid+' new:'+iidNew+' match:'+iidNew.search(/[^_]_[\d]+$/)); 
        if (iidNew.search(/[^_]_[\d]+$/) != -1) {
          tdiv = inputFields.item(i).parentNode; // DIV.
          //tmpFields = tdiv.childNodes;
          //for (z=0;z<tmpFields.length;z++) {
          //  if (tmpFields.item(z).tagName == 'a') {
          //      alert('found aaaa');
          //  }
          //  alert(iid+' *'+tmpFields.item(z)+'*');
          //}
          tmpFields = newtr.getElementsByTagName("A"); // calendar icon-links.
          for (z=0;z<tmpFields.length;z++) {
            // Change the onclick of the calendar icon-link.
            tmp = tmpFields.item(z);
            //tname = tmp.getAttribute('name').replace(/_[\d]+_calendar$/,'_'+nextcount+'_calendar');
            tname = tmp.getAttributeNode('name').nodeValue.replace(/_[\d]+_calendar$/,'_'+nextcount+'_calendar');
            //tmp.setAttribute('name',tname);
            tmp.setAttribute('id',tname);
            tmp.setAttribute('name',tname);
            //tattr = tmp.getAttribute('onclick');
            tattr = tmp.getAttributeNode('onclick').nodeValue;
            //alert(tattr+'****'+tattr.replace(RegExp(iid,'g'),iidNew));
            //alert('black '+tattr);
            //alert('yellow '+tattr);
            //alert('yellowx '+tmp.getAttributeNode('onclick').nodeValue);
            //t = tattr.replace('/_[\d]/','4');
            //alert('yellow '+t);
            tmp.setAttribute('onclick',tattr.replace(RegExp(iid,'g'),iidNew));
            //alert(tmp.tagName+' '+tname+' '+tmp.getAttributeNode('name').nodeValue+' ***** '+tmp.getAttributeNode('onclick').nodeValue);
            //alert(iid+' '+tattr.replace(RegExp(iid,'g'),iidNew));
          }
          //alert('blue');
          //alert(iid+' *'+tmpFields.length+'*');
        }
        inputFields.item(i).setAttribute('id',iidNew);
      }
      selectFields = newtr.getElementsByTagName("SELECT");
      for (i=0;i<selectFields.length;i++) {
        // Replace the input_id part in the 'onchange' and 'name' attributes
        // on hidden fields.
        tmp = selectFields.item(i);
        //tid = tmp.getAttribute('id'); 
        tid = tmp.getAttributeNode('id').nodeValue; 
        x1 = tid.search(/[\d]+/);
        x2 = tid.search(/_[\D]+$/);
        iid = tid.substring(0,x2);
        iidNew = tid.substring(0,x1)+nextcount;
        //iid = tmp.getAttribute('id'); 
        //iid = tid.substring(0,x2);
        //iidNew = iid.replace(/__[\d]+/,'__'+nextcount);
        //alert(iidNew+' '+x1+' '+x2);
        //if (iid == iidNew) {
        //  // We most likely have a hiddenField.
        //  iidNew = iid.replace(/_[\d]+/,'_'+nextcount);
        //  // Find the calendar field.
        //}
        //tattr = tmp.getAttribute('onchange');
        tattr = tmp.getAttributeNode('onchange').nodeValue;
        tmp.setAttribute('onchange',tattr.replace(RegExp(iid,'g'),iidNew));
        tmp.setAttribute('id',tid.replace(/[\d]+/,nextcount));
        //alert(tmp.getAttribute('id')+' *** '+tmp.getAttribute('onchange'));
        //tid = tmp.getAttribute('id');
        //tmp.setAttribute('id',iidNew);
        //alert(tmp+' '+tattr+' id:'+tmp.getAttribute('id')+' onchange:'+tmp.getAttribute('onchange'));
        //alert(tmp+' '+tattr+' iid:'+iid+' iidNew:'+iidNew+' onchange='+tmp.getAttribute('onchange'));
      }
      //alert(hiddenDiv);
      //tdiv = trc.getElementsByTagName("DIV");
      //alert(tdiv);
      //hiddenDiv = tdiv; // The calendar fields DIV.
      //alert('bla'+hiddenDiv);
      //hiddenFields = [hiddenDiv.item(3),hiddenDiv.item(7),hiddenDiv.item(11),hiddenDiv.item(15),hiddenDiv.item(19)];
      //hiddenFields = hiddenDiv.getElementsByTagName("SELECT");
      //// All hidden fields are selection fields. Change the id.
      //alert(hiddenFields.item(1));
      //for (x=0; x<hiddenFields.length; x++) {
      //  tname = hiddenFields.item(x).getAttribute('name');
      //  tvalue = hiddenFields.item(x).getAttribute('value');
      //  alert('name'+' '+tname+'; value: '+tvalue);
      //  //Change ids....
      //}
    }
    tr.parentNode.appendChild(newtr);
    //alert(newtr.innerHTML);
}

//function update_grid_field(id,year,month,day,hour,minute,ampm) {
//    // Wrapper method for updating date field.
//    // We reuse the calendar widget update method and add our own to update
//    // the grid field.
//    //alert(id+' '+year+' '+month+' '+day+' '+hour+' '+minute+' '+ampm);
//    //update_date_field(id,year,month,day,hour,minute,ampm);
//    alert('wrapped update_date_field method');
//}

function getParentElement(currnode, tagname) {
    /* Recursive function to move up the tree to a certain parent */

    tagname = tagname.toUpperCase();
    var parent = currnode.parentNode;

    while (parent.tagName.toUpperCase() != tagname) {
	parent = parent.parentNode;
	// Next line is a safety belt
	if (parent.tagName.toUpperCase == "BODY") return null;
    }

    return parent;
}


function moveRowDown(node){
    row = getParentElement(node, "TR")
    nextRow = row.nextSibling
    var tbody = getParentElement(node, "TBODY");
    var rows = tbody.getElementsByTagName("TR");
    if (nextRow && (rows.length != (nextRow.rowIndex))){
        shiftRow(nextRow, row)
    }
}
function moveRowUp(node){
    row = getParentElement(node, "TR")
    previousRow = row.previousSibling
    if (previousRow){
    shiftRow(row, previousRow)
    }
}

function shiftRow(bottom, top){
    bottom.parentNode.insertBefore(bottom, top )   
}

