﻿var _targetDate;
var _displayHoursFormat = "%%H%%h:%%M%%m:%%S%%s";
var _displayDaysFormat = "%%D%%d:%%H%%h:%%M%%m";
var _leadingZero = true;
var _controlId;
var _secs;

function calculate(secs, num1, num2) {
    s = ((Math.floor(secs / num1)) % num2).toString();
    if (_leadingZero && s.length < 2)
        s = "0" + s;
    return s;
}

function start() {
    if (_secs < 0) {
        document.getElementById(_controlId).innerHTML = '00h:00m:00s';
        return;
    }        
    counter = (_secs / 86400 > 1) ? _displayDaysFormat : _displayHoursFormat;
    counter = counter.replace(/%%D%%/g, calculate(_secs, 86400, 86400));
    counter = counter.replace(/%%H%%/g, calculate(_secs, 3600, 24));
    counter = counter.replace(/%%M%%/g, calculate(_secs, 60, 60));
    counter = counter.replace(/%%S%%/g, calculate(_secs, 1, 60));
    document.getElementById(_controlId).innerHTML = counter;
    _secs = _secs + _step;
}

function initialize(controlId, secs, step) {

    _controlId = controlId;
    _secs = secs;  
    _step = step;
    setInterval(start, 1000);
}

function DealRunningTime(id, seconds) {
    this.clientId = id;
    this.seconds = seconds;
}

DealRunningTime.prototype = {
    update: function () {
        var el = document.getElementById(this.clientId);
        if (el) {
            this.seconds = this.seconds - 1;
            if (this.seconds > 0)
                el.innerHTML = this.toString(this.seconds);
        }

    },

    toString: function (span) {
        var secs = 1;
        var mins = secs * 60;
        var hours = mins * 60;
        var days = 24 * hours;

        var d = span;
        var dd = parseInt(d / days + '', 10);

        d = d % days;
        var hh = parseInt(d / hours + '', 10);

        d = d % hours;
        var mm = parseInt(d / mins + '', 10);

        d = d % mins;
        var ss = parseInt(d / secs + '', 10);
        var str = '';
        if (dd > 0)
            str = str + dd + 'd: ';
        if (hh > 0 || (hh == 0 && dd > 0))
            str = str + hh + 'h : ';
        if (mm > 0 || (mm == 0 && hh > 0))
            str = str + mm + 'm : ';
        if (ss > 0 || (ss == 0 && mm > 0))
            str = str + ss + 's';
        return str;

    }
}

