var popupElement = null;

function registerBodyClicks () {
	document.body.onclick = function (event) {
	  if (popupElement != null){
	    if(!popupElement.justNew) {
	        document.body.removeChild(popupElement);
	        popupElement = null;
	    }
	    if (popupElement != null)
	    {
	        popupElement.justNew = false;
	    }
	  }
	};
}
  
function popupTime(timeField) {
    if (popupElement != null) {
        return;
    }
    timeField = $(timeField);
    var element = document.createElement("div");
	for (var h = 0; h <= 23; h++) {
	    for (var m = 0; m < 60; m += 30) {
	        var time = this.formatTime(h, m);
	        var cell = document.createElement("span");
	    cell.time = time;
	    cell.timeField = timeField;
	    cell.onmousedown = function(event) {
	            this.timeField.value = this.time;
	        };
	    cell.appendChild(document.createTextNode(time));
	    cell.className = "popupCell";
	        element.appendChild(cell);
	    }
    }
    var position = findPos(timeField);

    element.style.left = position[0]+'px';
    element.style.top = position[1]+'px';
    element.className = "popupElement";
    
    popupElement = element;
    popupElement.justNew = true;
    document.body.appendChild(element);
}
  
function findPos(obj) {
    var curleft = curtop = h = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        h = obj.offsetHeight
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop+h];
}
  
function formatTime(hour, minute) {
    return zeroPad(hour, 2) + ":" + zeroPad(minute, 2);
}

function zeroPad (s, length) {
    s = s.toString();
    while (s.length < length) {
      s = "0" + s;
    }
    return s;
}