/* 

 * Livefyre.com 

 * 

 * This script displays the number of comments for a list of articles

 * 

 */





var glob;  // debug reasons only



var livefyreIndex = {};



function livefyreCommentCallback(data) {



    var REPLACER = /(\d)+/;



    glob = data;



    var article_id;

    for (article_id in data) {

	if(livefyreIndex[article_id]) { 

	    var node = livefyreIndex[article_id];

	    node.innerHTML = node.innerHTML.replace(REPLACER, data[article_id]);

	    if (data[article_id] == 1) {

		// If there is only 1 comment, get rid of the plural from any instances of the word comments

		var s = node.innerHTML;

		//console.log('got 2');

		var cindex = s.toLowerCase().indexOf('omments');		

		//console.log('cindex is', cindex);

		s = s.substring(0, cindex+6) + s.substring(cindex+7, s.length);

		node.innerHTML = s;

	    }

	} else {

	    //console.error('This article does not exist', article_id);

	}

    }



    /* Don't have to do this if the REPLACER = "0" already

      

     

    // If any nodes still exist, write them as 0 comments

    for (article_id in livefyreIndex) {

	livefyreIndex[article_id].innerHTML = livefyreIndex[article_id].innerHTML.replace(REPLACER, 0);

    }

     */

}





(function () {

    

    var getElementsByClassName = function(clsName){

	

	var retVal = new Array();

	var elements = document.getElementsByTagName("*");

	for(var i = 0;i < elements.length;i++){

	    

            if(elements[i].className.indexOf(" ") >= 0){

		

		var classes = elements[i].className.split(" ");

		for(var j = 0;j < classes.length;j++){

		    

                    if(classes[j] == clsName)

			retVal.push(elements[i]);

		}

            }

            else if(elements[i].className == clsName)

            retVal.push(elements[i]);

	}

	return retVal;

    }



function addLoadEvent(func) {

    

  var oldonload = window.onload;

  if (typeof window.onload != 'function') {

      

    window.onload = func;

  } else {

      

    window.onload = function() {

	

      if (oldonload) {

	  

        oldonload();

      }

      func();

    }

  }

}







     var page_loaded = false;

     var comment_links = [];

     var ncomment_links = 0;

     var cl, article_id, i;

     var blogname;





     var scripts = document.getElementsByTagName('script');

     

     for (i = 0; i < scripts.length; i++) {

	 var script = scripts[i];

	 //console.log('checking script', script.src, script);

	 if (script.src && script.src.match("http://livefyre.com/.*ncomments.js")) {

	     // Found the include of this script

	     blogname = script.src.match("#bn=([^\&]*)")[1];

	     //console.log('got blogname', blogname);

	     break;

	 }

     }



     function getArticleID(node) {

	 var article_id = node.getAttribute('article_id');

	 if (typeof(article_id) == 'undefined' || !article_id || article_id == 'OPTIONAL') {

	     // by default the article id is the href.  

	     //console.log('use the href', node.href);

	     article_id = node.href.match('[^\#]*')[0];  // split off the # and anything after

	 }

	 return article_id;

     }



     function jsonp(url, args) {

	 

	 if (url.indexOf('?') < 1) {

	      url = url + "?";

	 }

	 for (var arg in args) {

	     url = url + "&" + escape(arg) + "=" + escape(args[arg]);   

	 }



	 var headID = document.getElementsByTagName("head")[0];         

	 var newScript = document.createElement('script');

	 newScript.type = 'text/javascript';

	 newScript.src = url;

	 headID.appendChild(newScript);

     }



     

     function processPage() {

	 //console.log('processing page');

	 comment_links = getElementsByClassName('livefyre-ncomments');



	 if (ncomment_links == comment_links.length) {

	     // No new comments found.  

	     return 0;

	 }



	 var request_list = '';

	 for (i = ncomment_links; i < comment_links.length; i++) {

	     cl = comment_links[i];

	     article_id = getArticleID(cl);



	     livefyreIndex[article_id] = cl;

	     //console.log(i, 'got comment', cl, cl.href, article_id); 

	     request_list = request_list + article_id + ",";

	 }



	 var args = {

	     'article_ids': request_list,

	     'blogname': blogname

	 }

	 ncomment_links = comment_links.length; 

	 jsonp('http://livefyre.com/bloggers/ncomments/', args);

	 // found new ones, so lets double check for more in a few ms

	 window.setTimeout(processPage, 100);

	 

     }

     

     processPage();

     

     /// Double ensure that all comments are processed when the page loads

     addLoadEvent(function() {

		      page_loaded = true;	 

		      processPage();

		  });

     

})();





