// requires nicolib.js

if (typeof Nico.Community == "undefined") Nico.Community = {};

Nico.Community.BBS = function (container, template, id, count, hashKey) {
	Nico.onReady(function () {
		var method = "NicoCommunityBBS_update_" + (container.id || container).replace(/\W/, "_");
		window[method] = function (data) {
			Nico.Community.BBS.update($(container), template, id, data);
			window[method] = undefined;
		}
		setTimeout(function () {
			new JSONP(Nico.Community.BBS.BASE_URL + id + "/api/res/l" + count
				+ "/" + method + "/?hash_key=" + hashKey);
		}, 300);
	});
};
Nico.Community.BBS.BASE_URL = 'http://dic.nicovideo.jp/b/c/';
Nico.Community.BBS.ERROR_CANT_FETCH = '<p class="TXT12">取得できませんでした</p>';
Nico.Community.BBS.ERROR_NO_RES = '<p class="TXT12">書き込みはありません</p>';
Nico.Community.BBS.update = function (container, template, id, data) {
	if (!(data instanceof Array)) {
		container.update(Nico.Community.BBS.ERROR_CANT_FETCH);
		return;
	}
	if (data.length == 0) {
		container.update(Nico.Community.BBS.ERROR_NO_RES);
		return;
	}

	container.update("");

	template = new Nico.Template($(template));
	data.each(function (res) {
		var data = {
			id:        res.i || id,
			number:    res.n || "",
			date:      res.d.replace(/^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/, "$1/$2/$3 $4:$5:$6"),
			name:      res.f || "ななしのよっしん",
			body:      res.b || "",
			oekaki:    res.o || "",
			comname:   res.c || "",
			comtype:   (res.i || id).substring(0, 2) == "ch" ? "channel" : "community"
		};
		new Insertion.Bottom(container, template.evaluate(data));
	});
};
