/*
 * @name 4chan timezone fix
 * @description Changes times on 4chan to the local timezone
 */

var manifest = {
    settings: [
        {
            name: "format",
            type: "text",
            label: "Format",
            default: "%a %b %d, %Y %H:%M:%S"
        }
    ]
};

jetpack.future.import("storage.settings"); 

jetpack.future.import("pageMods");

function callback(doc) {
    var namenodes = doc.querySelectorAll(".postername, .commentpostername");
    var handlednodes = [];
    for(var i in namenodes) {
        var timenode = namenodes[i];
        while(timenode != null && !(timenode.nodeType == 3 && !timenode.isElementContentWhitespace)) timenode = timenode.nextSibling;
        if(timenode != null) {
            if(handlednodes.indexOf(timenode) != -1) continue;
            handlednodes.push(timenode);
            var r = /(\d{2})\/(\d{2})\/(\d{2})\((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\)(\d{2}:\d{2}:\d{2})/.exec(timenode.textContent);
            if(r != null){
                var date = new Date(r[1] + "/" + r[2] + "/20" + r[3] + " " + r[4] + " -0400");
                timenode.replaceWholeText(" " + date.toLocaleFormat(jetpack.storage.settings.format) + " ");
            } else { // for boards without seconds, (most boards other than /b/)
                var r = /(\d{2})\/(\d{2})\/(\d{2})\((?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\)(\d{2}:\d{2})/.exec(timenode.textContent);
                if(r != null){
                    var date = new Date(r[1] + "/" + r[2] + "/20" + r[3] + " " + r[4] + " -0400");
                    timenode.replaceWholeText(" " + date.toLocaleFormat((jetpack.storage.settings.format).replace(/:?%S/i, "")) + " ");
                }
            }
        }
    }
}

jetpack.pageMods.add(callback, {matches: ["http://boards.4chan.org/*"]});

