// source --> https://uprawnienia-budowlane.pl/wp-content/themes/uprawnienia-budowlane/timer/script.js 
function timeToGo(s) {

    function z(n) {
        return (n < 10 ? '0' : '') + n;
    }
    var diff = s - new Date();

    diff = Math.abs(diff);

    var hours = diff / 3.6e6 | 0;
    var mins = diff % 3.6e6 / 6e4 | 0;
    var secs = Math.round(diff % 6e4 / 1e3);
    if (secs === 60) {
        secs = 0;
        mins++;
    }

    return [z(hours), z(mins), z(secs)];
}

function animateDigit(el, value) {
    if (el.html() != value) {
        el.animate({ top: '2.5em', opacity: 0 }, 'fast', function () {
            el.html(value);
            el.css({
                top: '-2.1em',
                opacity: 0
            });
            el.delay(100).animate({ top: 0, opacity: 1 }, 'fast');
        });
    }
}

function updateTimer(id) {
    var targetDate = new Date();
    targetDate.setDate(targetDate.getDate() + 1);
    targetDate.setHours(0, 0, 0, 0);

    var note = $('#note_' + id);
    var hours1 = $('#hours_1_' + id);
    var hours2 = $('#hours_2_' + id);
    var minutes1 = $('#minutes_1_' + id);
    var minutes2 = $('#minutes_2_' + id);
    var seconds1 = $('#seconds_1_' + id);
    var seconds2 = $('#seconds_2_' + id);

    var timeLeft = timeToGo(targetDate);
    var days = 0;
    var hours = timeLeft[0];
    animateDigit(hours1, hours[0]);
    animateDigit(hours2, hours[1]);
    var minutes = timeLeft[1];
    animateDigit(minutes1, minutes[0]);
    animateDigit(minutes2, minutes[1]);
    var seconds = timeLeft[2];    
    animateDigit(seconds1, seconds[0]);
    animateDigit(seconds2, seconds[1]);

    
    var message = "";

    var hours_text = " godzin ";
    var minutes_text = " minut ";
    var seconds_text = " sekund ";

    if ((hours <= 4 && hours > 0) || (hours > 20 && ((hours % 10 == 2) || (hours % 10 == 3) || (hours % 10 == 4)))) {
        hours_text = " godziny ";
    }
    if (hours == 1) {
        hours_text = " godzina ";
    }

    if ((minutes <= 4 && minutes > 0) || (minutes > 20 && ((minutes % 10 == 2) || (minutes % 10 == 3) || (minutes % 10 == 4)))) {
        minutes_text = " minuty ";
    }
    if (minutes == 1) {
        minutes_text = " minuta ";
    }

    if ((seconds <= 4 && seconds > 0) || (seconds > 20 && ((seconds % 10 == 2) || (seconds % 10 == 3) || (seconds % 10 == 4)))) {
        seconds_text = " sekundy ";
    }
    if (seconds == 1) {
        seconds_text = " sekunda ";
    }

    message += days + (days == 1 ? ' dzień ' : ' dni') + ", ";
    message += parseInt(hours) + hours_text + ", ";
    message += parseInt(minutes) + minutes_text + " i ";
    message += parseInt(seconds) + seconds_text + " <br />";

    message += 'pozostało do <b>zakończenia pakietu</b>!';

    note.html(message);



    setTimeout(function () {
        updateTimer(id);
    }, 1000);
};