$(function () {

    function inUrl(text) {
        var url = window.location.href;
        return (url.indexOf(text) != -1);
    }

    // difference in milliseconds

    function msToTime(s) {
        var time = {};

        time.ms = s % 1000;
        s = (s - time.ms) / 1000;
        time.secs = s % 60;
        s = (s - time.secs) / 60;
        time.mins = s % 60;
        time.hrs = (s - time.mins) / 60;

        return time;//hrs + ':' + mins + ':' + secs;
    }

    function pad(num, size) {
        var s = "000000000" + num;
        return s.substr(s.length - size);
    }

    var time = $("#time_started").data('time');
    var timer = $("div.timer")
    var d2 = new Date(time);  // start date

    var time2 = $("#stage_started").data('time');
    var d22 = new Date(time2);  // start date


    showTime();// its showtime babe
    function showTime() {

        if ($("#time_ended").length) {
            d1 = new Date($("#time_ended").data('time'));
        } else
            d1 = new Date();

        var diff = Math.abs(d1 - d2);
        var diff2 = Math.abs(d1 - d22);

        var time = msToTime(diff);
        var time2 = msToTime(diff2);

        timer.text(time.hrs + ":" + pad(time.mins, 2) + ":" + pad(time.secs, 2));
        $(timer[0]).text(time2.hrs + ":" + pad(time2.mins, 2) + ":" + pad(time2.secs, 2));

        if (inUrl("result")) {
            if (diff > 3600000 && diff < 4500000) // hodina
            {
                $(timer[0]).addClass('orange');
            } else if (diff > 4500000) // hodina a čtvrt
            {
                $(timer[0]).addClass('red');
            }
        } else {
            if (diff2 > 300000 && diff2 < 420000) // 5 minut
            {
                $(timer[0]).addClass('orange');
            } else if (diff2 > 420000) // 7 minut
            {
                $(timer[0]).addClass('red');
            }
        }

        if (diff > 3600000 && diff < 4500000) // hodina
        {
            $(timer[1]).addClass('orange');
        } else if (diff > 4500000) // hodina a čtvrt
        {
            $(timer[1]).addClass('red');
        }

        setTimeout(showTime, 500);
    }

});
