/**
 * @author Joe McGuire <joe@numiko.com>
 */
$( document ).ready(function() {
  commentCountContainers = getCommentCountContainers();
  addCommentCountLoading( commentCountContainers );
  nidString = getNidString( commentCountContainers );
  
  // Request JSON response and then update DOM with returned comment counts
  if( nidString.length > 0 ){
    $.getJSON( Drupal.settings.commentCountAjax.json + '?nid=' + nidString,
    function( data ){
      $.each( data, function( nid, commentCount ){
        if( commentCountContainers[ nid ] ){
          $( commentCountContainers[ nid ] ).html( commentCount );
        }
      });
    });
  }
});

/**
 * Returns an nid or false if none is found
 */
function getNidFromContainer( container ){
  if( nodeContainer.id ){
    return nodeContainer.id.substring( 5, nodeContainer.id.length );
  }
  return false;
}

/**
 * Takes an DOM object id just as 'node-1234' and returns the nid 1234
 */
function getNidString( commentCountContainers ){
  nidString = '';
  for( var nid in commentCountContainers ){
    nidString += nid + ',';
  }
  return nidString.substring( 0 , nidString.length - 1);
}

/**
 * Returns an object with each nid as a property and each value a reference to the comment-count DOM object
 */
function getCommentCountContainers(){
  commentCountContainers = {};
  $( 'div.node' ).each( function(){
    nodeContainer = this;
    commentCountContainer = $( nodeContainer ).find( 'span.comment-count' );
    nid = getNidFromContainer( nodeContainer );
    if( nid != false && commentCountContainer.length === 1 ){
      commentCountContainers[nid] = commentCountContainer;
    }
  });
  return commentCountContainers;
}

/**
 * Replaces the current comment count with a loading graphic
 */
function addCommentCountLoading( commentCountContainers ){
  for( var nid in commentCountContainers ){
    img = new Image();
    img.src = Drupal.settings.commentCountAjax.basePath + 'misc/progress.gif';
    img.alt = 'loading comment count';
    img.height = 10;
    img.width = 10;
    $( commentCountContainers[ nid ] ).html( img );
  }
}