/**
 * This static object handles callbacks from the Pluck handler. In most cases the callback receives
 * an object from Pluck. The Pluck data is then displayed using markup. The idea is that each site
 * can customize this file for their own Pluck display.
 */
function PluckMarkupGenerator () {
  PluckMarkupGenerator.ratings = "";
  PluckMarkupGenerator.currentView = ""; // Saves the current state. Can be comment, private comment.
  PluckMarkupGenerator.abuseThreshold = 3; // Amount of reports before being removed.
  PluckMarkupGenerator.numberOfComments = 0; // Number of comments.
  PluckMarkupGenerator.userId = ""; // User id
  PluckMarkupGenerator.parentHandler = "";

  // Sets the current view type. Used if toggling between comments and private comments. Each has
  // specific display logic so need to be able to note which view we are in.
  PluckMarkupGenerator.setViewType = function(type) {
    PluckMarkupGenerator.currentView = type;
  }

  // Create ratings objects for the article id.
  PluckMarkupGenerator.initRatings = function(aIds, loggedIn) {
    //PluckMarkupGenerator.isLoggedIn = loggedIn;
    PluckMarkupGenerator.articleRating = 0;

    // Check if a string was passed in.
    if (typeof aIds != "object") {
      var temp = aIds;
      aIds = new Array();
      aIds.push(temp);
    }

    PluckMarkupGenerator.aRatings = PluckMarkupGenerator.aRatings || [];
    for (var j=0; j<aIds.length; j++) {
      PluckMarkupGenerator.aRatings[aIds[j]] = new Rating("ratingGroup_"+aIds[j], aIds[j]);
      PluckMarkupGenerator.aRatings[aIds[j]].initRating();
    }

  }

  // Used if pluck is down.
  PluckMarkupGenerator.suppressPluck = function(aIds) {
    // Check if a string was passed in.
    if (typeof aIds != "object") {
      var temp = aIds;
      aIds = new Array();
      aIds.push(temp);
    }
    try {
    for(j=0;j<aIds.length; j++)
     { document.getElementById("totalComments_" + aIds[j]).style.display = "none";
      //document.getElementById("commentIcon_" + aIds[i]).style.display = "none";

    }
    }
    catch (e) { }

    try {
      for (var j=0; j<aIds.length; j++) {
        document.getElementById("rating_" + aIds[j]).style.display = "none";
      }
    }
    catch (e) { }
  }

  // Draws the rating portion of an article.
  PluckMarkupGenerator.drawArticle = function(Article) {
    var artKey = Article.ArticleKey.Key;
     if (PluckMarkupGenerator.parentHandler.crLogicHelper[artKey].indexOf('R') != "-1")
    {
    // Set the avg rating short and long text.
    var rating = Math.round(Article.Ratings.AverageRating*10)/10;
    if (rating >= 0) {
      //Short rating text
      if (document.getElementById("ratingAverageTxtshort_" + artKey)) {
        document.getElementById("ratingAverageTxtshort_" + artKey).innerHTML = "<span>(Avg "+ rating +")</span>";
      }
      //Long rating text
      if (document.getElementById("ratingAverageTxt_" + artKey)) {
        document.getElementById("ratingAverageTxt_" + artKey).innerHTML = "Average rating ";

      if (rating == 1) {
        rating = rating + " <span class=\"startxt\">star</span>";
      } else {
        rating = rating + " <span class=\"startxt\">stars</span>";
      }
      document.getElementById("ratingAverage_" + artKey).innerHTML = rating;
    }
    }


    // If the current user has rated, then display the number of stars
    PluckMarkupGenerator.articleRating = rating;
    if (Article.Ratings.CurrentUserRating != null) {
      PluckMarkupGenerator.articleRating = Article.Ratings.CurrentUserRating;
      PluckMarkupGenerator.aRatings[artKey].setRating(Article.Ratings.CurrentUserRating);
    }
    else
    {PluckMarkupGenerator.aRatings[artKey].setRating(rating);

    }
    }
  }

  // Draws the comments (which are stored as comments in Pluck).
  PluckMarkupGenerator.drawComments = function(commentPage) {
    // Create a data object to store data.
    PluckMarkupGenerator.aData = new Array();
    PluckMarkupGenerator.aLookup = new Array();
    PluckMarkupGenerator.numberOfComments = 0;
       //alert(PluckMarkupGenerator.parentHandler.crLogicHelper[commentPage.ArticleKey.Key]);

     if (PluckMarkupGenerator.parentHandler.crLogicHelper[commentPage.ArticleKey.Key].indexOf('C') != "-1")
     {
        //alert(PluckMarkupGenerator.parentHandler.crLogicHelper[commentPage.ArticleKey.Key].indexOf('S'));

     //Display number of comments
    if (commentPage.NumberOfComments != null && document.getElementById("commentAnchor_" + commentPage.ArticleKey.Key)) {
      var insertPoint = document.getElementById("commentAnchor_" + commentPage.ArticleKey.Key);
      insertPoint.innerHTML = ""; // Clear out any old comments.

      for (var i=0; i<commentPage.Comments.length; i++) {
          var comment = commentPage.Comments[i];
        if (PluckMarkupGenerator.isUnderAbuseCount(comment)) {
            PluckMarkupGenerator.aLookup[comment.CommentKey.Key] = i;
            PluckMarkupGenerator.aData[i] = comment;
            insertPoint.appendChild(PluckMarkupGenerator.getCommentDiv(comment, i, commentPage.ArticleKey.Key));
            PluckMarkupGenerator.numberOfComments++;
        }
      }


      insertPoint.appendChild(PluckMarkupGenerator.getAbuseDiv(commentPage.ArticleKey.Key));

      // If greater than page one, then show previous link.
      if (commentPage.OnPage > 1) {
        var imgLink = PluckMarkupGenerator.createButton("prev_ten_ "+commentPage.ArticleKey.Key, "/css/i/pluck/prev_ten.gif", commentPage.ArticleKey.Key);
        imgLink.onclick = function () {
            pluckHandler.getPrevPage(commentPage.ArticleKey.Key);
            return false;
        }
        insertPoint.appendChild(imgLink);
      }

      // If exceed the number per page, show next link.
      if (commentPage.NumberOfComments > (commentPage.NumberPerPage * commentPage.OnPage)) {
        var imgLink = PluckMarkupGenerator.createButton("next_ten_"+commentPage.ArticleKey.Key, "/css/i/pluck/next_ten.gif", commentPage.ArticleKey.Key);
        imgLink.onclick = function () {
            pluckHandler.getNextPage(commentPage.ArticleKey.Key);
            return false;
        }
        if (commentPage.OnPage > 1) {imgLink.className="moreLink";}
        insertPoint.appendChild(imgLink);
      }
    }

      /* Commenting this out since we want to always show the # of comments, even if zero
          if (!PluckMarkupGenerator.isLoggedIn && PluckMarkupGenerator.numberOfComments == 0) {
        var loginUrl = pluckHandler.loginUrl;
        var strComments = "<a href=\"" + loginUrl + "\">Register</a> to post your comment";
      //} else if (commentPage.NumberOfComments == 1) {
        //var strComments = commentPage.NumberOfComments + " comment";
      } else { */

      if (PluckMarkupGenerator.parentHandler.crLogicHelper[commentPage.ArticleKey.Key].indexOf('S') != "-1")
      {
       var strComments = "<a href=\"#\" onclick=\"return PluckMarkupGenerator.toggleComments('comments_"+commentPage.ArticleKey.Key+"')\">Comments <span>(" + commentPage.NumberOfComments + ")</span></a>";
       } else {
       var strComments = "Comments <span>(" + commentPage.NumberOfComments + ")</span>";}

     if (document.getElementById("totalCommentsshort_" + commentPage.ArticleKey.Key)){
      document.getElementById("totalCommentsshort_" + commentPage.ArticleKey.Key).innerHTML = strComments;
      document.getElementById("totalCommentsshort_" + commentPage.ArticleKey.Key).style.display = "";
      }

      if (document.getElementById("totalComments_" + commentPage.ArticleKey.Key)){
      var strComments = "<span>" + commentPage.NumberOfComments + " comments</span>";
      document.getElementById("totalComments_" + commentPage.ArticleKey.Key).innerHTML = strComments;
      document.getElementById("totalComments_" + commentPage.ArticleKey.Key).style.display = "";

      }
      if (typeof(SI.ClearChildren) != 'undefined') {   SI.ClearChildren.clear(); }
    }
  }

  PluckMarkupGenerator.toggleComments = function(cmtId,caller) {
       jQuery("div#"+cmtId).slideToggle("fast")
       return false;
   }

  // Checks abuse threshold and supresses if above that.rating
  PluckMarkupGenerator.isUnderAbuseCount = function(comment) {
    if (comment.Author.IsBlocked == "False" && (parseInt(comment.AbuseReportCount) < PluckMarkupGenerator.abuseThreshold)) {
      return true;
    } else if (comment.Author.IsBlocked == "True" && (comment.Author.UserKey.Key == PluckMarkupGenerator.userId) && (parseInt(comment.AbuseReportCount) < PluckMarkupGenerator.abuseThreshold)) {
      return true;
    } else {
      return false;
    }

  }
  // Builds a div to hold a comment.
  PluckMarkupGenerator.getCommentDiv = function(comment, index, artId) {
    // if the user has a tip rating display it.
    var commentRating = "";
    if (comment.CommentRating > 0) {
      commentRating = "<div class=\"commented\">";
      for (var i=0; i<comment.CommentRating; i++) {
        commentRating += "<img class=\"commentRating\" src=\"/css/i/pluck/star_b.gif\" alt=\"\" />";
      }
      commentRating += "</div>";
    }

    var commentDiv = document.createElement('div');
    commentDiv.id = "commentContainer_"+artId+"_"+index;

    commentDiv.className = "entry";
    if (PluckMarkupGenerator.currentView == "privatecomments") {
      commentDiv.className += " private";
    }

    var authorName = "";
    if (typeof(comment.Author) != 'undefined') {
      authorName = " " + comment.Author.DisplayName;
    }

    commentDiv.innerHTML = "<dl><dd>" + comment.CommentBody + "</dd><dd class=\"dated\">Posted at " + comment.PostedAtTime.toLowerCase() + " <span class=\"author\">by " + authorName + "</span>"/*+ commentRating */ + "</dd><dd class=\"report\">" + PluckMarkupGenerator.getAbuseHTML(comment, index, artId) + "</dd></dl>";

//    if (PluckMarkupGenerator.currentView != "privatecomments") {
//      commentDiv.innerHTML += PluckMarkupGenerator.getAbuseHTML(comment, index);
//      commentDiv.innerHTML += PluckMarkupGenerator.getRecommendationHTML(comment, index);
//    }

    return commentDiv;
  }

  // Returns the div that holds the report abuse form.
  PluckMarkupGenerator.getAbuseDiv = function (artId) {
    var abuseDiv = document.createElement('div');
    abuseDiv.id = "abuseForm_"+artId;
    abuseDiv.className = "aform";
    abuseDiv.style.display = "none";
    abuseDiv.innerHTML = "<form id=\"reportAbuseForm_"+artId+"\"><input type=\"hidden\" id=\"ReportAbuseKey_"+artId+"\" value=\"\" /><input type=\"hidden\" id=\"ReportAbuseReason_"+artId+"\" value=\"Report Abuse on Wmag\"/><div class=\"row\"><a href=\"#\" class=\"closebtn\" onclick=\"return PluckMarkupGenerator.hideAbuseForm('"+artId+"')\">X</a></div><div class=\"row\"><label>Comment</label><span class=\"formw\"><textarea id=\"ReportAbuseCommentText_"+artId+"\" cols=16 rows=4></textarea></span></div><input type=\"image\" src=\"/css/i/pluck/report_btn.gif\" value=\"Report\" onclick=\"return PluckMarkupGenerator.errCheckAbuseForm(document.getElementById('ReportAbuseKey_"+artId+"').value,document.getElementById('ReportAbuseReason_"+artId+"').value,document.getElementById('ReportAbuseCommentText_"+artId+"').value,'"+artId+"')\" value=\"Report\" /></form>";
    return abuseDiv;
  }

  // Returns the abuse html.
  PluckMarkupGenerator.getAbuseHTML = function (comment, id, artId) {
    var rKey=comment.CommentKey.Key;
    var fCall;
   if(PluckMarkupGenerator.parentHandler.LoggedIn()){
    fCall="PluckMarkupGenerator.showAbuseForm('"+id+"','"+rKey+"','"+artId+"'); return false    ";
    }else {
    fCall="PluckMarkupGenerator.parentHandler.gatewayHandler.loginHandler('abuse', document.getElementById('report_"+artId+"_"+id+"'));return false;";
    }
     var html = "<span id=\"report_"+artId+"_"+id+"\"><a class=\"reportlink\" href=\"#\" onclick=\""+fCall+"\">Report abuse</a></span>";
    return html;
  }



  PluckMarkupGenerator.getRecommendationHTML = function(comment, id) {
    if (comment.CurrentUserHasRecommended == "False") {
      var html = "<span id=\"commentRecommendation_" + id + "\" class=\"commend\">(" + comment.NumberOfRecommendations + ") ";
      html += "<a href=\"#\" onclick=\"return pluckHandler.submitRecommendation('" + comment.CommentKey.Key + "', this)\">recommend this comment</a></span>";
   } else {
     var html = "<span id=\"commentRecommendation_" + id + "\" class=\"commended\">(" + comment.NumberOfRecommendations + ") ";
     html += "recommended</span>";
   }
      return html;

  }


  PluckMarkupGenerator.setLastRecommendation = function(commentKey) {
    PluckMarkupGenerator.lastItem = commentKey;
  }

  PluckMarkupGenerator.updateRecommendation = function(responseBatch) {
    // helpful firebug debug of entire response batch returned from the API server
    //console.dir(responseBatch);
    if (responseBatch.Messages[0].Message == 'ok') {
      // update the user interface.
      // get the id of the div.
      var index = PluckMarkupGenerator.aLookup[PluckMarkupGenerator.lastItem];
      divId = "commentRecommendation_" + index;
      var comment = PluckMarkupGenerator.aData[index];
      var updatedCount = parseInt(comment.NumberOfRecommendations) + 1;
      var html = "(" + updatedCount + ") recommended</span>";

      document.getElementById(divId).innerHTML = html;
      document.getElementById(divId).className = "commended";


     }

  }

  PluckMarkupGenerator.setComment = function(comment) {
    // Stores the comment in an object to update the user inteface.
    PluckMarkupGenerator.lastComment = comment;

  }

  // show abuse form
  PluckMarkupGenerator.showAbuseForm = function (id, key, artId) {
   var cmd=eval("document.getElementById('reportAbuseForm_"+artId+"').ReportAbuseKey_"+artId);
   cmd.value = key;
   //document.getElementById("abuseForm"+id).style.display = "block";
   var newTop = document.getElementById("commentContainer_"+artId+"_"+id).offsetTop + document.getElementById("commentContainer_"+artId+"_"+id).offsetHeight + document.getElementById("abuseForm_"+artId).offsetHeight;
   document.getElementById("abuseForm_"+artId).style.top = newTop + "px";
   jQuery("div#abuseForm_"+artId).show("fast");
   return false;
  }

  /// hide abuse form
  PluckMarkupGenerator.hideAbuseForm = function (artId){
   jQuery("div#abuseForm_"+artId).hide("fast");
   // Null out the data.
   jQuery("div#abuseForm_"+artId+" :input").val("");
   document.getElementById("ReportAbuseReason_"+artId).selectedIndex = 0;
   return false;
  }

  /// error checking abuse form
  PluckMarkupGenerator.errCheckAbuseForm = function (key,reason,desc, artId){
    // No error checking.

    pluckHandler.submitReportAbuse(key, reason, desc);
    PluckMarkupGenerator.hideAbuseForm(artId);

    return false;
  }


  // Private notes.
  PluckMarkupGenerator.drawNotes = function() {
   var numPerPage = 10;
   var notes = PluckMarkupGenerator.aNotes;
   if (PluckMarkupGenerator.currentNotesPage <= 0) { PluckMarkupGenerator.currentNotesPage = 1; }

   document.getElementById("totalComments").style.display = "none";
   insertPoint = document.getElementById("commentAnchor");
   insertPoint.innerHTML = ""; // Clear out any old comments.
   var startPoint = numPerPage * (PluckMarkupGenerator.currentNotesPage - 1);
   var stopPoint = (numPerPage * PluckMarkupGenerator.currentNotesPage) - 1;
   if (stopPoint >= notes.length) { stopPoint = notes.length-1; }

   for (var i=startPoint; i <= stopPoint; i++) {
      //PluckMarkupGenerator.aLookup[comment.CommentKey.Key] = index;
      var comment = new Object();
      comment.CommentBody = notes[i].note;
      var displayDate = new Date();
      displayDate.setTime(Date.parse(notes[i].creationDate));
      var time = PluckMarkupGenerator.formatTime(displayDate);
      comment.PostedAtTime = displayDate.getMonth()+1 + "/" + displayDate.getDate() + "/" + displayDate.getFullYear() + " " + time;

      insertPoint.appendChild(PluckMarkupGenerator.getCommentDiv(comment, i));
      PluckMarkupGenerator.aData[i] = comment;
   }


      // If greater than page one, then show previous link.
      if (PluckMarkupGenerator.currentNotesPage > 1) {
        var imgLink = PluckMarkupGenerator.createButton("prev_ten", "/css/tipsy/i/prev_ten.gif");
        imgLink.onclick = function () { PluckMarkupGenerator.currentNotesPage--; PluckMarkupGenerator.drawNotes(); return false; }
        insertPoint.appendChild(imgLink);
      }

      // If exceed the number per page, show next link.
      if (PluckMarkupGenerator.aNotes.length > (numPerPage * PluckMarkupGenerator.currentNotesPage)) {
        var imgLink = PluckMarkupGenerator.createButton("next_ten", "/css/tipsy/i/next_ten.gif");
        imgLink.onclick = function () { PluckMarkupGenerator.currentNotesPage++; PluckMarkupGenerator.drawNotes(); return false; }
        insertPoint.appendChild(imgLink);
      }

  }

  /* Utility function to create a pagination button. */
  PluckMarkupGenerator.createButton = function(imgId, imgPath, aId) {
     var imgLink = document.createElement('a');
     imgLink.href = "#commentAnchor_" + aId;
     var img = document.createElement('img');
     img.id = imgId;
     img.className="pageButton";
     img.src = imgPath;
     imgLink.appendChild(img);
     return imgLink;
  }

  /* Utility function to format time */
  PluckMarkupGenerator.formatTime = function(timeObj) {
    var hours = timeObj.getHours();
    var minutes = timeObj.getMinutes();
    var seconds = timeObj.getSeconds()
    var timeValue = "" + ((hours >12) ? hours -12 :hours)
    if (timeValue == "0") timeValue = 12;
    timeValue += ((minutes < 10) ? ":0" : ":") + minutes
    timeValue += ((seconds < 10) ? ":0" : ":") + seconds
    timeValue += (hours >= 12) ? " PM" : " AM"
    return timeValue;
  }

  /* CALLBACKS */
  PluckMarkupGenerator.updateAbuse = function(responseBatch) {
  //console.dir(responseBatch);
    // pass in an id. Update the link so the user cannot report abuse again for this comment.
   if (responseBatch.Messages[0].Message == 'ok') {
      /*
      CODE FOR UPDATED ABUSE GOES HERE
      */
     }
  }

  // main call back function from batch request
  // If a comment is returned then draw the comments.
  // Article returned means draw the rating stars.
PluckMarkupGenerator.renderReviewPage = function(responseBatch) {
// helpful firebug debug of entire response batch returned from the API server
//console.dir(responseBatch);
     for (var i = 0; i < responseBatch.Responses.length; i++) {
        var response = responseBatch.Responses[i];
        if (response.Article != null && PluckMarkupGenerator.parentHandler.crLogicHelper[response.Article.ArticleKey.Key].indexOf('R') != "-1") {
          PluckMarkupGenerator.drawArticle(response.Article);
        } else if (response.CommentPage != null && PluckMarkupGenerator.parentHandler.crLogicHelper[response.CommentPage.ArticleKey.Key].indexOf('C') != "-1") {
          PluckMarkupGenerator.drawComments(response.CommentPage);
    } else if (response.User != null) {
          PluckMarkupGenerator.userId = response.User.UserKey.Key;
        }
     }
  }

 }

 // Callback for the private notes.
 PluckMarkupGenerator.renderNotes = function(notes) {
    // Create a data object to store data.
   PluckMarkupGenerator.aNotes = notes;
   PluckMarkupGenerator.currentNotesPage = 1;

   if (notes.length == 1) {
      var strComments = notes.length + " comment";
   } else {
      var strComments = notes.length + " comments";
   }
   document.getElementById("totalComments").innerHTML = strComments;
   PluckMarkupGenerator.drawNotes();
 }
