/* FemtoType client-side script for inserting comment counts */

var xml_http;
var comment_links;
var comment_i;

function comment_callback() {
	if( xml_http.readyState != 4 ) {
		return;
	}

	if( xml_http.status == 200 ) {
		comment_links[comment_i].innerHTML = xml_http.responseText;
	}

	comment_i ++;
	comment_call();
}

function comment_call() {
	if( comment_i < comment_links.length ) {
		var call_url = comment_links[comment_i].href.replace(/#comments$/, 'count/');

		xml_http.open("GET", call_url, true);
		xml_http.onreadystatechange = comment_callback;
		xml_http.send(null);
	}
}

function comment_counts() {
	try { 
		// Firefox, Opera 8.0+, Safari, IE7
		xml_http = new XMLHttpRequest();
  	} catch(e1) {
		// Old IE
	 	try {
			xml_http = new ActiveXObject("Microsoft.XMLHTTP");
    		} catch(e2) {
    			return;  
    		}
  	}

	var links = document.getElementsByTagName("a");

	var archives_url_re = new RegExp("archives/[0-9]{4}/[0-9]{2}/[a-z0-9_]+/#comments");
	var comments_re = new RegExp("Comments");

	comment_links = [];

	var n;
	for(n in links) {
		if( archives_url_re.test(links[n].href) && comments_re.test(links[n].innerHTML) ) {
			comment_links.push(links[n]);
		}
	}

	comment_i = 0;

	comment_call();
}
