function hideOnMouseOut(e)
{
  if (!e) var e = window.event;
  if (checkMouseLeave(document.getElementById('cpop'), e)) {
    // Mouseout took place when mouse actually left layer
    //  --  Instead: add a timer that will do a hidePopup() when it
    //  triggers, and if the mouse moves back into the div w/in the
    //  timeframe, kill the timer.
    hidePopup();
  }
}

function checkMouseLeave (element, evt) {
  if (element.contains && evt.toElement) {
    return !element.contains(evt.toElement);
  }
  else if (evt.relatedTarget) {
    return !containsDOM(element, evt.relatedTarget);
  }
}

function hidePopup()
{
    document.getElementById('cpop').style.visibility='hidden';
}

function containsDOM (container, containee) {
  var isParent = false;
  do {
    if ((isParent = container == containee))
      break;
    containee = containee.parentNode;
  }
  while (containee != null);
  return isParent;
}

var x;
var y;

function trackWhere(e, line_id) {
  if(!e) e = window.event;
  if(!e) e = event;
  if(e) {
    if(e.layerY) {
      x = e.layerX;
      y = e.layerY;
    } else if(e.pageX) {
      x = e.pageX;
      y = e.pageY;
    } else if(e.clientX) {
      x = e.clientX;
      y = e.clientY;
    } else {
      x = e.x;
      y = e.y;
    }
  }
}

function whichElement(e) {
  var targ
  if (!e) var e = window.event
  if (e.target) {
    targ = e.target
  } else if (e.srcElement) {
    targ = e.srcElement
  }

  if (targ.nodeType == 3) // defeat Safari bug
    targ = targ.parentNode

  var tname
  tname=targ.tagName
  if(tname == "DIV" && targ.id == "deadspace") {
    new Ajax.Request('/outlines/add_root_entry', {asynchronous:true, evalScripts:true}); return false;
  }
}

function showPopup() {
  showElement(document.getElementById('cpop'));
}

function showElement(cpop) {
  cpop.style.top = (y-6) + "px";
  cpop.style.left = (x-6) + "px";
  cpop.onmouseout=hideOnMouseOut;
  cpop.style.position='absolute';
  cpop.style.visibility='visible';

  return false;
}

function handleTab(e, id) {
  key = e.keyCode ? e.keyCode : (e.charCode ? e.charCode : (e.which ? e.which : 0));
  var esc = 27;
  if (e) {
    if(e.VK_DOM_ESCAPE) esc = e.VK_DOM_ESCAPE;
  }

  if(key == esc) {
    /**
     *  Workaround for an odd Firefox issue, which cancels the network
     *  activity as soon as its begun, because the ESC key is pressed.
     *  Instead we wait 100 milliseconds before firing the redraw request.
     */
    setTimeout(function(){ new Ajax.Request('/outlines/redraw/'+id, {asynchronous:true, evalScripts:true}); }, 100);
    return false;
  } else if(key == 9) {
    if(e.shiftKey == 1) {
      new Ajax.Request('/outlines/outdent/' + id, {asynchronous:true, evalScripts:true});
    } else {
     new Ajax.Request('/outlines/indent/' + id, {asynchronous:true, evalScripts:true});
    }
    return false;
  }
  return true;
}

function getPos (obj) {
  var pos = {x: obj.offsetLeft||0, y: obj.offsetTop||0};
  while(obj = obj.offsetParent) {
    pos.x += obj.offsetLeft||0;
    pos.y += obj.offsetTop||0;
  }
  return pos;
}

function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    alert('(' + curleft + ', ' + curtop + ')');
    while (obj = obj.offsetParent) {
      curleft += obj.offsetLeft
      curtop += obj.offsetTop
    }
  }
  return [curleft,curtop];
}

function getBounds(element) {
  var iebody = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;
  var dsocleft = document.all ? iebody.scrollLeft : pageXOffset;
  var dsoctop = document.all ? iebody.scrollTop : pageYOffset;

  var posReal = Position.realOffset(element);
  var pos = Position.cumulativeOffset(element);
      
  var top =  pos[1] - posReal[1] + dsoctop;
  var left = pos[0] + posReal[0] - dsocleft;
      
  var offsetWidth = element.offsetWidth;
  var offsetHeight = element.offsetHeight;
      
  return {left: left, top: top, width: offsetWidth, height: offsetHeight};
}

function adjustTarget(targetId) {
  var source = document.getElementById(targetId);
  var where = getBounds(source);
  var target = document.getElementById('target');
  var form_input = document.getElementById('content');

  form_input.style.position = 'absolute';
  form_input.style.top = where.top + "px";
  form_input.style.left = where.left + "px";
  form_input.style.width = source.offsetWidth + "px";
  form_input.style.fontWeight = 'bold';
  form_input.style.display = 'inline';
  form_input.style.visibility = 'visible';
  Element.show("target");
  form_input.focus();
}

function submitForm(line) {
  foo = document.getElementById('outlineForm');
  new Ajax.Request('/outlines/update_item/' + line, {asynchronous:true, evalScripts:true, parameters:Form.serialize(foo)});
  return false;
}

function pointForm(line, update, text) {
  var newForm = '<form id="outlineForm" action="/outlines/update_item/' + line + '" class="getupdate" method="post"';
  newForm += ' onkeypress="return handleTab(event, \'' + line + '\');"';
  newForm += ' onkeydown="return handleTab(event, \'' + line + '\');"';
  newForm += ' onsubmit="new Ajax.Request(\'/outlines/update_item/' + line + '\', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">';

  if(update == 'target') {
    newForm += '<input id="content" name="content" style="font-size: x-large; display: none" type="text" value="' + text + '" onblur="return submitForm(\'' + line + '\');" />';
  } else {
    newForm += '<input id="content" name="content" style="width: 90%" type="text" value="' + text + '" onblur="return submitForm(\'' + line + '\');" />';
  }
  newForm += '</form>';
  Element.update(update, newForm);
  setTimeout(function() {
    if(update == 'target') adjustTarget('root' + line);
    cur = document.getElementById('content');
    cur.focus();
  }, 150);
}

//Event.observe(document, 'keypress', function(event) {
//  if(event.keyCode == Event.KEY_TAB) alert('Tab Pressed');
//  stop(event);
//});

var last_line = null;
var new_effect = null;
var effects = new Array;

function decorate_element(element) {
  element.onmouseover = function(e) {
    showToolbar(e, element.id);
  }

  element.onmouseout = function(e) {
    hideToolbar(e, element.id);
  }
}

function decorate(element_id) {
  decorate_element($(element_id));
}

function showToolbar(e, element_id) {
  if(!e) var e = window.event;
  $$('.toolbar').first().show();
  new Effect.Move('toolbar0', { x: 0, y: $(element_id).viewportOffset().top + $(element_id).getHeight() - 4, mode: 'absolute' });
  //  TODO mrs -- Now add the appropriate AJAX calls to the three buttons, using the element_id as the item to operate on.
}

function hideToolbar(e, element_id) {
  $$('.toolbar').first().hide();
}

function fullStop(e) {
  if(!e) var e = window.event;
  e.cancelBubble = true;
  if(e.stopPropagation) e.stopPropagation();

  return true;
}
