function drawTerminator(cxt, theta) {
    var delta_phi = Math.PI / 64;
    for (var phi = Math.PI; phi >= 0.0; phi -= delta_phi) {
        var t = r * Math.sin(phi);
        var x = t * Math.cos(theta);
        //var y = t * Math.sin(theta);
        var z = r * Math.cos(phi);
        cxt.lineTo(x + r, z + r);
    }
}

function runglobeclock() {
    // get current time
    var d = new Date();
    var hour = d.getHours();
    var min = d.getMinutes();

    // get the canvas and its attributes
    canvas = document.getElementById("globeclock");
    if (!canvas) {
        return;
    }
    width = canvas.width;
    height = canvas.height;
    cxt = canvas.getContext("2d");

    // draw the image of Earth
    var img = new Image();
    img.onload = function() {
	cxt.drawImage(img, 0, 0);

        r = width / 2;    // assumes canvas is square

        // draw the yellow arc of sunlight
        if (hour == 12 && min == 0) {   // noon
            cxt.fillStyle = "rgba(255, 255, 100, 0.5)";
            cxt.beginPath();
            cxt.arc(width / 2, height / 2, r, 0, Math.PI * 2, false);
        } else if (hour != 0 || min != 0) {
            var theta = Math.PI * (((hour % 12) * 60 + min) / (12 * 60));

            cxt.fillStyle = "rgba(0, 0, 0, 0.7)";
            cxt.moveTo(width / 2, 0);
	    cxt.beginPath();
	    drawTerminator(cxt, theta);
            cxt.arc(width / 2, height / 2, width / 2, Math.PI / 2, Math.PI * 3 / 2, hour >= 12);
	    cxt.fill();

            cxt.fillStyle = "rgba(255, 255, 100, 0.5)";
            cxt.moveTo(width / 2, 0);
	    cxt.beginPath();
	    drawTerminator(cxt, theta);
            cxt.arc(width / 2, height / 2, width / 2, Math.PI / 2, Math.PI * 3 / 2, hour < 12);
            cxt.fill();
        }

        setTimeout("runglobeclock();", 30000);
    }
    img.src = "http://joeganley.com/images/earth.png";
}
