var weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
              'Oct', 'Nov', 'Dec'];

function get_xml_http_request() {
    var ex;

    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (ex) { }
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (ex) { }
    try {
        return new XMLHttpRequest();
    }
    catch (ex) { }

    return null;
}

function commify(s) {
    var t;

    while (true) {
        t = s.replace(/^(\d+)(\d{3})([\.,][\d\.,]+|)$/, '$1,$2$3');
        if (t == s) return t;
        s = t;
    }

    return s;
}

// convert new line and more than 2 consecutive spaces
function text_to_html_new_line_spaces(s) {
    return s.replace(/( {2,})/g, function(spaces) {
        var n, i, s;

        for (n = spaces.length - 1, i = 0, s = ''; i < n; i++) s += '&nbsp;';
        s += ' ';

        return s;
    }).replace(/ $/, '&nbsp;').replace(/\r\n/g, '<br>').replace(/\n\r/g, '<br>').replace(/\n/g, '<br>').replace(/\r/g, '<br>');
}

function time_to_str(time) {
    var date, year, day, hour, min;
    var s;

    date = new Date(time * 1000);
    s = weekdays[date.getDay()] + ', ' + months[date.getMonth()] + '-';
    day = date.getDate();
    if (day < 10) s += ('0' + day + '-');
    else s += (day + '-');
    year = date.getFullYear() % 100;
    if (year < 10) s += ('0' + year + ' ');
    else s += (year + ' ');
    hour = date.getHours();
    if (hour == 10 || hour == 22) s += '10:';
    else if (hour == 11 || hour == 23) s += '11:';
    else if (hour == 0 || hour == 12) s += '12:';
    else s += ('0' + (hour % 12) + ':');
    min = date.getMinutes();
    if (min < 10) s += ('0' + min);
    else s += min;
    if (hour < 12) s += 'am';
    else s += 'pm';

    return s;
}

function interval_to_str(dtime) {
    if (dtime == 1) return '1 second';
    else if (dtime < 60) return (dtime + ' seconds');
    else if (dtime < 60 * 1.5) return '1 minute';
    else if (dtime < 3600) return (Math.round(dtime / 60) + ' minutes');
    else if (dtime < 3600 * 1.5) return '1 hour';
    else if (dtime < 86400) return (Math.round(dtime / 3600) + ' hours');
    else if (dtime < 86400 * 1.5) return '1 day';
    else if (dtime < 86400 * 7) return (Math.round(dtime / 86400) + ' days');
    else if (dtime < 86400 * 7 * 1.5) return '1 week';
    else if (dtime < 86400 * 30) return (Math.round(dtime / (86400 * 7)) + ' weeks');
    else if (dtime < 86400 * 30 * 1.5) return '1 month';
    else if (dtime < 86400 * 365) return (Math.round(dtime / (86400 * 30)) + ' months');
    else if (dtime < 86400 * 365 * 1.5) return '1 year';
    else return (Math.round(dtime / (86400 * 365)) + ' years');
}

