months =["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

YAHOO.namespace('bravo.comments');
YAHOO.bravo.comments = function () {
  return { 
    //Function to be called from outside the object
    //starts the chain of events
    displayComments: function (url) {
		       this.setUpEverything(url); 
		     },
    //Takes in the given datetime and reformats it to our
    //desired output
    formatDate: function (date) {
		  var datetime = date.split(" ");
		  var date = datetime[0].split("-");
		  var time = datetime[1].split(":");
		  var formattedTime = time[0]%12+":"+time[1];
		  if (time[0] > 11) 
		    formattedTime += " PM";
		  else
		    formattedTime += " AM";

		  var formattedDate = months[date[1]-1]+" "+parseInt(date[2])
		    + ", "+date[0]+" at " +formattedTime;
		  return(formattedDate);
		},
    //Checks on a page for the existence of the given anchor
    checkAnchors: function (searchTerm) {
		    for (i=0;i<document.anchors.length;i++) {
		      key = document.anchors[i];
		      if (key.name == searchTerm)
			return (true);
		    }
		    return (false);
		  },
    //Formatter for the user image cells in the table
    userImage_formatter: function(elCell, oRecord, oColumn, oData) {
      		           //Search for alternative user field
			   if (!oData)
			     oData = oRecord.getData("author");
			   elCell.setAttribute('class','user_cell');
			   elCell.innerHTML="<a title='"+oData.screenname+"' href='"+oData.awards_link+"'>"
			     +"<img alt='"+oData.screename+"' src='"+oData.avatar_url+"'></a>";
			 },
    //Gets the current comment page from the ajax control
    getCurrentCommentPage: function()
			   {
			     var text = $D.getElementsByClassName('yui-dt-selected','span');
			     if (text.length > 1) 
			       return(text[0].innerHTML);
			     else
			       return(1);
			   },
    //Formatter for the comment cells in the table
    commentCell_formatter: function(elCell, oRecord, oColumn, oData) {
			     //Search for alternative user/comment field
			     if (!oData){
			       oData = oRecord.getData("author");
			       var comment = oRecord.getData("comment_text");
			     }
			     else
			     	var comment = oRecord.getData("comment");
			     
			     elCell.setAttribute('class','comment_cell');
			     //$('currentPage').value = YAHOO.bravo.comments.getCurrentCommentPage();
			     var name = "comment_"+oRecord._oData.id;
			     var outHTML = "<A name='"+name+"'></A>";
			     outHTML  += "<div class='text'>"+comment+"</div>"; 
			     outHTML += '<div class="byline">Posted by <a href="'+oData.awards_link
			       +'">'+oData.screenname+'</a>';
			     outHTML += ' on ' +YAHOO.bravo.comments.formatDate(oRecord._oData.created_at);
			     outHTML += YAHOO.bravo.comments.makeLinks(oData, oRecord);
			     elCell.innerHTML = outHTML;

			   },

    //Makes the links for the comment cells
    makeLinks: function (oData, oRecord) {
      outHTML = '<div class=comment_links>';
      if ($('logged_in_user_id'))
	if(oData.public_id ==  $('logged_in_user_id').value){
	  outHTML += '<a href="'+oRecord._oData.delete_comment_link+'">Delete   </a>&middot;';
	  outHTML += '<a href="' +oRecord._oData.edit_comment_link+'">   Edit   </a>&middot;';
	}
      outHTML += '<a href="' + oRecord._oData.report_abuse_link+'">   Report   </a>&middot;';
      outHTML += "<a href='#comment"+oRecord._oData.id+"'>  Permalink</a></div>" + '</div>';
      return(outHTML);
    },

    //Checks for a comment permalink anchor in the url and then reacts to it
    dealWithAnchors: function(myDataTable, myDataSource) {
		       var loc = document.location.href;
		       var end=loc.split('/');
		       var last = end.pop();
		       if (last.match(/comment/)){
			 var parts = last.split('t');
			 var num = parts[1];

			 //Calculate what page the anchor will be on
			 recordNum=this.findInDataSource(num,myDataSource);
			 rowsPerPage = myDataTable._configs.paginator.value.rowsPerPage;
			 correctPage = Math.floor(recordNum/rowsPerPage)+1;
			 this.myDataTable.showPage(correctPage);

			 var check = last.substr(1); 
			 if(this.checkAnchors(check))
			   window.location.hash = last;
		       }
		       else if (last.match(/page/)){
			 var parts = last.split('e');
			 var num = parts[1];
			 this.myDataTable.showPage(parseInt(num));
		       }
		     },
    //Sets up the data source for the tables
    setUpDataSource: function(oJSON)
		     {
		       //Takes in a javascript array parsed from JSON
		       //or anywhere else 
		       var myDataSource = new YAHOO.util.DataSource(oJSON);
		       myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
		       if (myDataSource.liveData.length <1)
			 return(0);

		       //The expected response schema
		       myDataSource.responseSchema = {
		       fields: ["award", "award_id","comment","created_at",
			       "deleted","id","link","report_abuse_link","delete_comment_link",
			       "update_at", "user","user_id","author" ,"comment_text","edit_comment_link"]
		       };
		       return(myDataSource);
		     },
    //Find the index of a record in the dataSource by ID
    //Yucky sequential search on unordered dataSource
    findInDataSource: function (id, myDataSource) {
      liveData = myDataSource.liveData;
      for (var i=0;i<liveData.length;i++) {
	if (liveData[i].id == id)
	  return(i);
      }
      return(0);
    },
    //Sets up the data table
    setUpDatatable: function (divName, myDataSource) {
		      //column definitions
		      var myColumnDefs = [
		      {key:"user", formatter: this.userImage_formatter},
		      {key:"user", formatter: this.commentCell_formatter}
		      ];
		      // Configure pagination features
		      var myConfigs = {
    				paginated:true, // Enables built-in client-side pagination
	      			paginator:{ // Configurable options
    				rowsPerPage: 5, // Show up to 500 rows per page
				pageLinks:4
	      		}
		      };

		      //if there are less than 11 items then do not paginate 
		      if (myDataSource.liveData.length <11)
			myConfigs = {};

		      myDataTable = new YAHOO.widget.DataTable(divName, myColumnDefs, myDataSource, myConfigs); 
		      return(myDataTable);
		    },
    setUpEverything: function(sUri) {
		       method = 'GET';
		       crumb = $('std_ucrumb').value;
		       if (sUri.indexOf("_ucrumb") === -1) {
			 sUri = sUri + "&_ucrumb=" + crumb;
			 sUri = sUri + "&per_page=0";
		       }
		       var callBack = {
			//disable caching because ie6 is too aggressive
			cache: false,
			scope: YAHOO.bravo.comments,
		        success: function (o) {
			  //Eval the JSON reply manually because the API format
			  //is not perfectly matched with YUI's format
			  var oJSON = eval("(" + o.responseText + ")");
			  var myDataSource = this.setUpDataSource(oJSON);
			  if (myDataSource == 0)
			    return(0);
			  this.myDataTable = this.setUpDatatable("commentsTable", myDataSource); 
			  this.dealWithAnchors(this.myDataTable, myDataSource);
		         }
			}
		       //make the async request
		       YAHOO.util.Connect.asyncRequest(method, sUri, callBack);
		     }
  }
}();



