var now;
var then = new Date("12:00 pm 4/30/2011");
var counterclock = true;
function strm(str, f){
    return (new Array(f + 1)).join(str);
}
function pad(n, nop){
    return strm("0", nop - String(n).length) + n;
}
var secondsInDay = 86400;
var hoursInDay = 12;
var minutesInHour = 60;
var secondsInMinute = 60;
var secondsInHour = minutesInHour * secondsInMinute;
var rAngleOffset = 91;
var lAngleOffset = -89;
var leftX = 39;
var rightX = 49;
function setXTo(obj, n){
    obj.setAttribute("x", n);
}
function tick(){
    now = new Date();
    var srd, mrd, hrd, trd, ttx;
    var hour = document.getElementById("hour");
    var minute = document.getElementById("minute");
    var second = document.getElementById("second");
    var ttw = document.getElementById("ttw");
    var diff = Math.floor((then.getTime() - now.getTime()) / 1000);
    var cx = 50
    if(diff > secondsInDay / 2){
	var days = diff / secondsInDay;
	srd = days * (360/29);
	ttx = Math.floor(days) + " days";
	trd = srd;
    }else{
	var hours = diff / secondsInHour;
	var minutes = (diff % secondsInHour) / secondsInMinute;
	var seconds = diff % secondsInMinute;
	hrd = hours * (360/12);
	mrd = minutes * (360/60);
	srd = seconds * (360/60);
	ttx = Math.floor(hours) + ":" + pad(Math.floor(minutes), 2) + ":" + pad(Math.floor(seconds), 2);
	trd = mrd;
    }
    if(diff <= 0){
	ttx = "It's here";
	document.getElementById("ubuntu").setAttribute("xlink:href", "http://www.ubuntu.com/desktop/get-ubuntu/download");
    }
    if(!counterclock){    
    hrd = (hrd === undefined) ? undefined : 360 - hrd;
    mrd = (mrd === undefined) ? undefined : 360 - mrd;
    srd = (srd === undefined) ? undefined : 360 - srd;
    trd = 360 - trd;
    }
    if((trd < 0 || trd > 180) && trd < 360){
	trd += rAngleOffset;
	cx = leftX;
    }else{
	trd += lAngleOffset;
	cx = rightX;
    }
    setXTo(ttw, cx);
    ttw.textContent = ttx;
    second.style.display = (srd === undefined) ? "none" : "block";
    minute.style.display = (mrd === undefined) ? "none" : "block";
    hour.style.display = (hrd === undefined) ? "none" : "block";
    second.setAttribute("transform", "rotate(" + srd + " 50 50)");
    minute.setAttribute("transform", "rotate(" + mrd + " 50 50)");
    hour.setAttribute("transform", "rotate(" + hrd + " 50 50)");
    ttw.setAttribute("transform", "rotate(" + trd + " 50 50)");
    setTimeout(tick, (diff > secondsInDay) ? 60000 : 1000);
}
function load(){
    var l = location.href;
    var c = l.substr(l.lastIndexOf("?") + 1);
    var i = c.indexOf("cc=");
    if(i != -1){
	var tf = c.substr(i + 3);
	counterclock = (tf == "true") ? true : false;
    }
    tick();
}
window.onload = load;
//load();
