$(function () {
    var days;
    var hours;
    var minutes;
    var seconds;
    var n_days    = 0;
    var n_hours   = 0;
    var n_minutes = 0;
    var n_seconds = 0;

    function setValue(name, val)
    {
        $(".tnt_coupons .bloc-time." + name).data("value", val);
        val = parseInt(val);

        let divider        = val.toString().length;
        let figureCount    = $(".tnt_coupons .countdown .bloc-time." + name + " .figure").length;
        let missingFigures = figureCount - divider;
        val                = val.toString();
        if (missingFigures > 0) {
            for (let i = 1; i <= missingFigures; i++) {
                val = "0" + val;
            }
        }
        for (let e = 1; e <= figureCount; e++) {
            $(".tnt_coupons .countdown .figure." + name + "-" + e).html(val[e - 1]);
        }
    }

    setValue("sec", $(".tnt_coupons .bloc-time.sec").data("value"));
    setValue("min", $(".tnt_coupons .bloc-time.min").data("value"));
    setValue("hours", $(".tnt_coupons .bloc-time.hours").data("value"));
    setValue("days", $(".tnt_coupons .bloc-time.days").data("value"));

    var countdown = setInterval(function () {
        days    = parseInt($(".tnt_coupons .bloc-time.days").data("value"));
        hours   = parseInt($(".tnt_coupons .bloc-time.hours").data("value"));
        minutes = parseInt($(".tnt_coupons .bloc-time.min").data("value"));
        seconds = parseInt($(".tnt_coupons .bloc-time.sec").data("value"));

        n_seconds = seconds - 1;
        setValue("sec", n_seconds);
        if (n_seconds < 0) {
            setValue("sec", 59);
            n_minutes = minutes - 1;
            if (n_minutes < 0) {
                setValue("min", 59);
                n_hours = hours - 1;
                if (n_hours < 0) {
                    setValue("hours", 23);
                    n_days = days - 1;
                    if (n_days < 0) {
                        setValue("days", 0);
                        setValue("hours", 0);
                        setValue("min", 0);
                        setValue("sec", 0);
                        clearInterval(countdown);
                    } else {
                        setValue("days", n_days);
                    }
                } else {
                    setValue("hours", n_hours);
                }
            } else {
                setValue("min", n_minutes);
            }
        }
    }, 1000);
});
