var attachedObject = null;
var attachedMouseXDiff = 0;
var attachedMouseYDiff = 0;

var currentZ = 1;

document.onmousemove = mouseMoved;
document.onmouseup   = detachWindow;

var timer = null;

function mouseCoords(ev)
{
  if(ev.pageX || ev.pageY)
  {
    return {x:ev.pageX, y:ev.pageY};
  }

  var xret = ev.clientX + document.body.scrollLeft - document.body.clientLeft;
  var yret = ev.clientY + document.body.scrollTop  - document.body.clientTop;

  return {x:(xret), y:(yret)};
}

function shrinkIncrement(winId)
{
  var win = document.getElementById(winId);

  var w = parseInt(win.style.width) - 5;
  var h = parseInt(win.style.height) - 5;

  if ((w <= 0) || (h <= 0))
  {
    win.style.display = "none";
    win.style.width = 250;
    win.style.height = 120;

    return false;
  }

  win.style.width = w;
  win.style.height = h;

  return true;
}

function shrinkObject(winId)
{
  var win = document.getElementById(winId);

  win.innerHTML = "";

  var str ="";

  str += "if (!shrinkIncrement('"+winId+"')) { stopInterval(); }";

  timer = setInterval(str, 300);
}

function stopInterval()
{
  clearInterval(timer);
  timer = null;
}

function doWindow(winId, txtElementId, txtId, show, ev)
{
  var win = document.getElementById(winId);

  if (!show)
  {
    //if (win.style.display != "none")
    //  shrinkObject(winId);

    win.style.display = "none";
    return;
  }

  ev = ev || window.event;
  p = mouseCoords(ev);


  win.style.left = p.x - (parseInt(win.style.width)/2);
  win.style.top = p.y+3;
  document.getElementById(txtElementId).innerHTML = document.getElementById(txtId).value;
  win.style.display = "block";
}

function attachObjectToMouse(winId, e)
{
  var win = document.getElementById(winId);

  e = e || window.event;

  p = mouseCoords(e);

  attachedObject = winId;

  //attachedMouseXDiff = e.clientX - parseInt(win.style.left);
  //attachedMouseYDiff = e.clientY - parseInt(win.style.top);

  attachedMouseXDiff = p.x - parseInt(win.style.left);
  attachedMouseYDiff = p.y - parseInt(win.style.top);

  win.style.zIndex = currentZ;
  currentZ++;
}



function detachWindow()
{
  attachedObject = null;
}

function mouseMoved(e)
{
  if (attachedObject == null)
    return;

  //var x = e.clientX;
  //var y = e.clientY;

  e = e || window.event;

  var pos = mouseCoords(e);
  //var x = pos.x;
  //var y = pos.y;

  document.getElementById(attachedObject).style.top = pos.y - attachedMouseYDiff;
  document.getElementById(attachedObject).style.left = pos.x - attachedMouseXDiff;

  return false;
}

