// -*- 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'),
	RE_LCASE: new RegExp ('[^a-z]', 'g'),
	RE_UCASE: new RegExp ('[^A-Z]', 'g'),
	MAX_UCASE_RATIO: 0.25,

	toLower: function (button, cuerpo_id) {
		var div = document.getElementById ("cuerpo" + cuerpo_id);

		if (div.style.textTransform) {
			div.style.textTransform = '';
			button.firstChild.innerHTML = 'Cambiar a minúsculas';
			return
		}

		div.style.height = div.clientHeight + 'px';
		div.style.textTransform = "lowercase";
		button.firstChild.innerHTML = 'Restaurar mayúsculas';
	},

        checkDate: function (link) {
                var day = new Date();
                var month = day.getMonth() + 1;
                if (month < 10)
                        var smonth = '0' + month;
                else
                        var smonth = month;
		if (day.getDate() < 10)
			var date = '0' + day.getDate();
		else
			var date = day.getDate();
		var chkday = day.getFullYear() + '\/' + smonth + '\/' + date;
                if (link.match(chkday) && day.getHours() < 18)
			return true;
		else
			return false;
        },

	renderTree: function (sibs) {
		if (sibs.length == 0)
			return "";

		if (sibs[0])
			var dateIsCurrent = comments.checkDate (sibs[0].href);
		var html = ['<ul class="comentarios">'];
		for (var i = 0, info; info = sibs[i]; i++) {
			if (!info.title)
				info.title = 'Comentario';
			if (!info.author)
				info.author = 'Anónimo';
			if (!info.subject)
				info.subject = '';
			if (!info.date)
				info.date = '';

			html.push ('<li class="comentario"><div class="titulo">' + info.title + "</div>" +
				   '<div class="credito">' + info.author + "</div>" +
				   '<div id="cuerpo' + info.id_comentario + '" class="cuerpocomentario">' + info.subject + "</div>");

			var hasbuttons = false;

			var lcase = info.subject.replace (comments.RE_LCASE, "");
			var ucase = info.subject.replace (comments.RE_UCASE, "");
			if (ucase.length / (lcase.length + ucase.length) > comments.MAX_UCASE_RATIO) {
				hasbuttons = true;
				html.push ('<div class="buttonbar">' +
					   '<div class="botoncomentario right" onclick="comments.toLower (this, \'' + info.id_comentario + 
					   '\')"><span class="button lcase">Cambiar a minúsculas</span></div>');
			}

			if (dateIsCurrent || window.COMMENTS_ADD_ALLOW) {
				if (!hasbuttons) {
					hasbuttons = true;
					html.push ('<div class="buttonbar">');
				}

				html.push ('<div class="botoncomentario" onclick="srvices.srvClickReplyComment (this.firstChild, ' +
        				   info.id_comentario + ", 'rb'" + '); return false">' + 
					   '<span id="rb' + info.id_comentario + '" class="button reply">Responder a este comentario</span></div>' +
					   '<div class="comment-box" id="' + info.id_comentario + '" style="margin-top:45px; position:absolute; z-index:100000000;"></div>');
			}

			if (hasbuttons)
				html.push ('</div>');

			html.push (comments.renderTree (info.children) + "</li>");
		}
		html.push ("</ul>");
		return html.join ('');
	},

	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++) {                                
                                if (child.firstChild)
					switch (child.nodeName) {
					case "title":
						info.title = child.firstChild.nodeValue;
						break;
					case "author":
						info.author = child.firstChild.nodeValue;
						break;
					case "description":
						info.subject = child.firstChild.nodeValue;
						break;
					case "pubDate":
						info.date = new Date (child.firstChild.nodeValue);
						break;
					case "link":
						info.href = child.firstChild.nodeValue;
						break;
					}

			}
                        info.id_comentario = ids[0];
                        info.id_comentario = info.id_comentario.replace('i','');
		}
		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); });
	},

	getArt: function () {
		var url = window.location.pathname;
		var filearticle = url.substring(url.lastIndexOf('/')+1);
		return filearticle;
        },

	getSect: function () {
		var url = window.location.pathname;
		var filesection = url.substring(12);
	        filesection = filesection.substring(0, filesection.length-9);
		return filesection;
        },

        getSectArt: function () {
		var args = {};
                args.section = comments.getSect();
		args.article = comments.getArt();
		return args;
        },

	onLoad: function () {
		var args = dodo.argsParse (document.location);                
		if (args == undefined)
                    args = comments.getSectArt();
		var renderTest = document.getElementById ("renderComments");
		var getArticle;
		getArticle = args.article; 

		if (window.COMMENTS_PRESENT)
			if (window.MEDIA_ID){
	 			comments.commentsLoad (document.getElementById ("renderComments"), "/videos/comentarios/" + window.MEDIA_ID + ".rss");
			}else if (window.MEDIA_ID_C){
	 			comments.commentsLoad (document.getElementById ("renderComments"), "comentarios/" + window.MEDIA_ID_C + ".rss");
			}else if (args.section == 'edito'){
 		 		comments.commentsLoad (document.getElementById ("renderComments"), "comentarios/edito.rss");
			}else if (args.section == 'correo'){
 		 		comments.commentsLoad (document.getElementById ("renderComments"), "comentarios/correo.rss");
			}else if (getArticle.match(/cor/)){
 		 		comments.commentsLoad (document.getElementById ("renderComments"), "comentarios/correo.rss");
			}else if (getArticle.match(/edi/)){
 		 		comments.commentsLoad (document.getElementById ("renderComments"), "comentarios/edito.rss");
                        }else{  				
	 			comments.commentsLoad (document.getElementById ("renderComments"), "comentarios/" + getArticle + ".rss");
			}
		if (window.COMMENTS_ADD_ALLOW || comments.checkDate (document.location.toString ())) {
			var cbmaincomment = document.getElementById ("cbmaincomment");
			if (cbmaincomment) {
				cbmaincomment.style.display = "inline";
				cbmaincomment.onclick = function () { 
					srvices.srvClickReplyComment (this, 'maincomment', 'cb');
					return false;
				};
			}
			var srv = document.getElementById ("srv-comment");
			if (srv)
				srv.style.display = "inline";
		}
	}
}
dodo.onLoadPush (function () { comments.onLoad ();});

