function secondsSinceEpoch(d)
{
    return Math.floor(d.getTime() / 1000);
}

function Timer(div, server_now, server_expire) {
    var now = secondsSinceEpoch( new Date() );
    server_now = secondsSinceEpoch( server_now );
    server_expire = secondsSinceEpoch( server_expire );
   
    this.div = div;
    this.expires = server_expire - server_now + now;
    this.interval = null;
    this.update();
}

Timer.prototype.getSecondsLeft = function()
{
    var now = secondsSinceEpoch( new Date() );
    return this.expires - now;
};

Timer.prototype.update = function()
{
    var seconds = this.getSecondsLeft();
    var minutes = Math.floor(seconds / 60);
    var display = "0:00";
    
    if (seconds > 0)
    {
        seconds = seconds % 60;
        display = minutes + ":" + (seconds < 10 ? "0" + seconds : seconds);
    }
    
    this.div.empty().append(display);
};

Timer.prototype.start = function()
{
    if (this.interval)
    {
        return;
    }
    var self = this;
    this.interval = setInterval(function() { self.update() }, 1000);
};

Timer.prototype.stop = function()
{
    clearInterval(this.interval);
    this.interval = false;
};
