var postId = queryString('postId');
var blogId = queryString('blogId');


function onCommentButtonsReady()
{
  var commentButton = new YAHOO.widget.Button({label:"Add Comment", id:"commentButton", container:"buttons", onclick: { fn: submitComment }});

}

function submitComment()
{
  var authorName = document.getElementById("authorName").value;
  if (authorName === null)
  {
    alert("Please enter your name");
  }
  else
  {

    var ed = tinyMCE.get('commentText');
    ed.setProgressState(1); // Show progress
    document.getElementById("commentButton").disabled = true;


    var commentText = ed.getContent();

    var postId = document.getElementById("postId").value;
    var commentId = document.getElementById("commentId").value;
    if (commentText !== "")
    {
      var callData;
      //if the id is set then update the comment, otherwise add a new one
      if (commentId === "")
      {
        callData = {postId: postId, commentText: commentText, authorName: authorName};
      }
      else
      {
        callData = {postId: postId, commentText: commentText, commentId: commentId, authorName: authorName};
      }

      var callString = YAHOO.lang.JSON.stringify(callData);
      var url = "../servlets/blogapi?method=submitComment";

      YAHOO.util.Connect.asyncRequest('POST', url, submitCommentCallback, callString, this);
    }
  }
}


var submitCommentCallback = {
  success : function(o)
  {
    var result;
    try
    {
      result = YAHOO.lang.JSON.parse(o.responseText);
      var ed = tinyMCE.get('commentText');
      ed.setProgressState(0); // Show progress
      document.getElementById("commentButton").disabled = false;
      ed.isNotDirty = 1; // set the editor to say the contents have been saved

      if (result.Result === "Ok")
      {
        var postId = document.getElementById("postId").value;
        var username = result.authorName;
        if (username === "") username = "Public User";
        var commentText = result.commentText;

        //reload the page to remove the edit comment field and load the comment
        window.location = "../secure/viewpost.jsp?id=" + postId;
      }
      else
      {
        alert("submit comment failed");
      }
    }
    catch (x)
    {
      alert("Call failed");
    }
  }  ,
  failure: function(o)
  {
    var ed = tinyMCE.get('commentText');
    document.getElementById("commentButton").disabled = false;
    ed.setProgressState(0);
    alert("Error posting comment");
  },
  timeout: 7000
};

/** Create the editor */
function initComments()
{

  var inlinefilechooser = new Filechooser("inlineLinkPopupContainer", constructHyperLink, function()
  {
    this.filechooser.panel.hide();
  }, {editorName:'commentText'});

  var imageFileChooser = new Filechooser("inlineImagePopupContainer", constructInlineImage, function()
  {
    this.filechooser.panel.hide();
  }, {editorName:'commentText'});


  tinyMCE.init({

    mode : "textareas",
    theme : "advanced",
    plugins : "paste,syntaxhl",
    gecko_spellcheck : true,
    theme_advanced_toolbar_location : "top",
    theme_advanced_buttons1 : "bold,italic,underline,separator,strikethrough,justifyleft,justifycenter,justifyright,justifyfull,bullist,numlist,undo,redo,inkspotLink,link,unlink," +
                              "outdent,indent,separator,link,unlink,image,inkspotImage,cleanup,code,syntaxhl," +
                              "hr,visualaid,separator,sub,sup,separator,charmap,help",
    theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,styleselect,formatselect,fontselect,fontsizeselect",
    theme_advanced_buttons3 : "",
    remove_linebreaks : false,
    extended_valid_elements : "textarea[cols|rows|disabled|name|readonly|class]",

    setup : function(ed)
    {
      // Add a custom button
      ed.addButton('inkspotLink', {
        title : 'Insert link to File',
        image : '../images/i/inkspot-link.gif',
        onclick : function()
        {
          inlinefilechooser.panel.show();
        }
      });
      // Add a custom button
      ed.addButton('inkspotImage', {
        title : 'Insert an Image from e-Science Central',
        image : '../images/inkspot-file-image.png',
        onclick : function()
        {
          imageFileChooser.panel.show();
        }
      });
    }

  });
}

YAHOO.util.Event.addListener(window, "load", initComments);

function unloadMessage()
{
  var ed = tinyMCE.get('commentText');
  if (ed.isDirty())
  {
    return 'You have entered new data on this page.  If you navigate away from this page without first saving your data, the changes will be lost.';
  }
  else
  {
    return undefined;  //needs to be undefined for IE to work
  }
}

