// -*- mode: javascript -*-

var comments = {
	xml: {},
	RSS_DATE_PARSER: new RegExp ('([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})Z'),
	renderTree: function (sibs) {
		if (sibs.length == 0)
			return "";

		var html = "<ul class=\"comentarios\">";
		for (var i = 0; info = sibs[i]; i++) {
			html += '<li class="comentario">';
			if (info.date)
			html += '<div class="titulo">' + info.title + "</div>\n";
			html += '<div class="credito">' + info.autor + "</div>";
			html += "<div>" + info.comm + "</div>\n";
			html += '<a href="' + info.href + '" class="discusion">responder</a>' + "\n";
			html += comments.renderTree (info.children) + "</li>";



		}
		html += "</ul>";
		return html;
	},

	render: function (xml, node) {
		var tree = {};
		var root = [];
		var items = xml.getElementsByTagName ("item");
		for (var i = 0, item; item = items[i]; i++) {
			var ids = item.getAttribute ("id").split (":");
			if (!tree[ids[0]])
				tree[ids[0]] = {date: "", children: []};
			var info = tree[ids[0]];

			if (ids[1]) {
				var id = "i" + ids[1];
				if (!tree[id])
					tree[id] = {date: "", children: []};
				tree[id].children.push (info);
			} else
				root.push (info);

			for (var j = 0, child; child = item.childNodes[j]; j++) {
				switch (child.localName) {
				case "title":
					info.title = child.firstChild.nodeValue;
					break;
				case "link":
					info.href = child.firstChild.nodeValue;
					break;
				case "author":
					info.autor = child.firstChild.nodeValue;
					break;
				case "description":
					info.comm = child.firstChild.nodeValue;
					break;
				case "pubDate":
					info.date = new Date (child.firstChild.nodeValue);
					break;
				}
			}
		}

		node.innerHTML = comments.renderTree (root);
	},

	commentsOnLoad: function (req, node) {
		if (req.readyState == 4 && (req.status == 200 || req.status == 0))
			comments.render (req.responseXML, node);
	},

	commentsLoad: function (node, src, id) {
		var req = dodo.httpReqGet ();
		dodo.httpReqLoad (req, src, function () { comments.commentsOnLoad (req, node); });
	},

	onLoad: function () {
		var args = dodo.argsParse (document.location);
 		comments.commentsLoad (document.getElementById ("renderComments"), "comentarios/" + args.article + ".rss");

	}
}

dodo.onLoadPush (function () { comments.onLoad ();});

