/** Return an object */
function getObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
        // W3C DOM
        return document.getElementById(objectId);
    } else if (document.all && document.all[objectId]) {
        // MSIE 4 DOM
        return document.all[objectId];
    } else if (document.layers && document.layers[objectId]) {
        // NN 4 DOM.. note: this won't find nested layers
        return document.layers[objectId];
    } else {
        return false;
    }
}

function setObjectHtml(objectId, value) {
    var obj = getObject(objectId);
    if(obj) {
        obj.innerHTML = value;
        return 1;
    }
    return 0;
}

var countDownTimer = {
    fieldId: "countDown",
    delay: 1000,
    duration: 0,
    serverTime: 0,
    elapsed: 0,

    // Start the timer
    start: function()
    {
        countDownTimer.tick();
    },
    // Stop the timer
    stop: function()
    {
        if (this.timer) {
            clearTimeout(this.timer);
            this.timer = 0;
        }
    },
    setEndDate: function(endDate)
    {
        this.endDate = new Date(endDate);
    },
    setDuration: function(seconds)
    {
        now = new Date();
        end = new Date(now.getTime() + seconds * 1000);
        countDownTimer.setEndDate(end);
        this.duration = seconds;
    },
    setServerDate: function(serverDate)
    {
        this.serverTime = new Date(serverDate);
    },
	// Tick..
    tick: function()
    {
        if (this.timer) {
            this.elapsed += this.delay;
            clearTimeout(this.timer);
            this.timer = 0;
        }

        now = new Date();
        diff = this.endDate.getTime() - now.getTime();
        if(this.serverTime != 0 && this.duration == 0) {
            serverTimeDiff = this.serverTime.getTime() - now.getTime() + this.elapsed;
            diff -= serverTimeDiff;
        }

        if(diff < 0) {
            days = hours = mins = secs = 0;
        } else {
            days = Math.floor(diff / (1000 * 60 * 60 * 24) );
            diff -= days * (1000 * 60 * 60 * 24);
            hours = Math.floor( diff / (1000 * 60 * 60));
            diff -= hours * (1000 * 60 * 60);
            mins = Math.floor(diff / (1000 * 60)) ;
            diff -= mins * (1000 * 60);
            secs = Math.floor(diff / (1000)) ;
            milsecs = diff - secs * 1000;
        }

        for(var i = 0; i<20; i++) {
            retVal = setObjectHtml(this.fieldId+"Days"+i, days) +
                setObjectHtml(this.fieldId+"Hours"+i, hours) +
                setObjectHtml(this.fieldId+"Minutes"+i, mins) +
                setObjectHtml(this.fieldId+"Seconds"+i, secs);
            if(retVal < 1) break;
        }
        this.timer = setTimeout("countDownTimer.tick()", this.delay);
    },
    setDelay: function( ms )
    {
        this.delay = ms;
    }
}
