// tag.js -- tagging support.

// onLoad, get our events registered.

window.onload = registerTagHandler;

function registerTagHandler() {
  var icons = getElementsByClassName('tagicon');
  for(var i=0 ; i < icons.length ; i++) {
    icons[i].onclick = createInputFrame;
    if(icons[i].captureEvents) icons[i].captureEvents(Event.click);
  }
}

// onClick handler for tag icon.  (non-edit mode)

function createInputFrame() {
  // get text
  dummy = this.parentNode.getElementsByTagName('p')[0];

  frame = document.createElement('iframe');
  frame.id = 'tag_editor';
  frame.src = 'edit.html';
  frame.style.border = '1px solid #999';
  frame.height = getClientHeight(dummy) * 2;
  frame.width = Math.max(getClientWidth(dummy) + 18, 318);

  frame.style.position = 'relative';
  frame.style.top = '-2px';
  frame.style.left = '-3px';
  frame.style.margin = '2px';
  frame.style.padding = '2px';
  frame.style.display = 'none';
  frame.class = 'tags';

  // note our use of two different registration models here.
  frame.onLoad = load;
  frame.setAttribute('onLoad', 'load');
  this.parentNode.appendChild(frame);


  this.onclick = destroyInputFrame;
  this.style.marginRight = '4px';


  dummy.style.display = 'none';
  frame.style.display = 'inline';
}

// onClick handler for tag icon.  (field mode)
function destroyInputFrame() {
  frame = document.getElementById('tag_editor');
  // insert code to parse tags.  filter, split on ','
  frame.parentNode.removeChild(frame);
  dummy = this.parentNode.getElementsByTagName('p')[0];
  dummy.style.display = 'inline';

  this.onclick = createInputFrame;
}

function getClientHeight(obj) {
  return obj.offsetHeight;
}

function getClientWidth(obj) {
  return obj.offsetWidth;
}

// *sigh*
function load() {
  window.alert("set design mode on");
  getIFrameDocument("tag_editor").designMode = "on";       
}

function getIFrameDocument(aID){
  window.alert("getting "+ aID +" frame");
  if (document.getElementById(aID).contentWindow.document) {
    window.alert("aID gotten");
    return document.getElementById(aID).contentWindow.document;
  } else if (document.getElementById(aID).contentDocument){  
    return document.getElementById(aID).contentDocument;
  } else if(document.frames[aID].document) {
    return document.frames[aID].document;
  } else {
    window.alert("ERRROR");
  }
}

