/**
 *  Via https://github.com/jherdman/javascript-relative-time-helpers/blob/master/date.extensions.js
 *  and updated to support localized strings
 */
Date.relativeTimeDictionary = { // Overwrite with your localizations before using
	second_ago: "1 second ago",
	seconds_ago: "#{number} seconds ago",
	minute_ago: "1 minute ago",
	minutes_ago: "#{number} minutes ago",
	hour_ago: "1 hour ago",
	hours_ago: "#{number} hours ago",
	day_ago: "1 day ago",
	days_ago: "#{number} days ago",
	month_ago: "1 month ago",
	months_ago: "#{number} months ago"
};

// d = Date
Date.prototype.toRelativeTime = function() {
    var delta = new Date() - this;

    if (delta <= 1000) {
        return Date.relativeTimeDictionary.second_ago;
    }

    var units = null;
    var conversions = {
        second: 1000,
        minute: 60,
        hour: 60,
        day: 24,
        month: 30
    };

    for (var key in conversions) {
        if (delta < conversions[key]) {
            break;
        } else {
            units = key;
            delta = delta / conversions[key];
        }
    }

    delta = Math.floor(delta);
    
    if (delta !== 1) {
        units += "s";
    }
    
    return Date.relativeTimeDictionary[units + '_ago'].replace(/#\{number\}/ig, delta);
};

/**
 *  Wraps up a common pattern used with this plugin whereby you take a String
 *  representation of a Date, and want back a date object.
 */
Date.fromString = function(str) {
    return new Date(Date.parse(str));
};

