﻿/**
Function which updates any abbr tags with class timestap
and data-date attributes

@params classname: class to look for
@params pageloadtime: time when the page loads
*/
function updateDates(classname) {
    var inputdate;
    var timestring; // holds time value
    var diff; // holds the difference
    var now = new Date(); // current time
    var newstring = ""; // new datetime caption to replace current caption
    var gmtHours = 0;//-now.getTimezoneOffset() / 60;

    $('abbr.' + classname).each(function() {
        timestring = new Date($(this).attr("data-date"));
        if (happenedYesterday(timestring)) {
            newstring = "gisteren om " + formatTime(timestring);
        }
        else {
            timestring = timestring.getTime();

            diff = Math.ceil(now.getTime() - timestring);
            newstring = diffTimeString(diff);
        }
        if (newstring != null)
            $(this).html(newstring);

    });
}


function happenedYesterday(JSDateTime) {
    var yesterday = new Date((new Date()).getTime() - 86400000);

    return ((JSDateTime.getYear() == yesterday.getYear()) &&
                (JSDateTime.getUTCMonth() == yesterday.getUTCMonth()) &&
                (JSDateTime.getUTCDate() == yesterday.getUTCDate()));
}


/**
Function to determine the string to use
to display time difference

@params time : time difference since pageload
*/
function diffTimeString(time) {
    var result = null;
    time = Math.ceil(time / 1000); // round up to closest second

    if (time > 1) {
        if (time < 50) {
            result = time + ' seconden geleden';
        }
        else if (time >= 50 && time <= 3300) {
            time = Math.ceil(time / 60);
            if (time == 1)
                result = time + ' minuut geleden';
            else
                result = time + ' minuten geleden';
        }
        else if (time > 3300 && time < 86400) {
            time = Math.ceil(time / 3600);
            result = time + ' uur geleden';
        }
        else {
            result = null;
        }
    }

    return result;
}

function formatTime(time) {
    var curr_hour = time.getHours();
    var curr_min = time.getMinutes();
    var curr_sec = time.getSeconds();

    var result = "";
    if (curr_hour < 10)
        result += "0";
    result += curr_hour + ":";

    if (curr_min < 10)
        result += "0";
    result += curr_min + ":";

    if (curr_sec < 10)
        result += "0";
    result += curr_sec;

    return result;
}
