/**
 * inlineObjectComment.js
 *
 * $Revision: 1.12 $
 * $Date: 2011/11/10 19:21:01 $
 * Last edited by: $Author: mingles $
 *
 * Methods to add/edit/delete ObjectComments
 */

var deleteComment = function(formIdentifier, nObjectCommentId)
{
  var form = document.getElementById('deleteObjectComment'+formIdentifier);
  form.Command.value = 'DELETE';
  form.ObjectCommentId.value = nObjectCommentId;

  $.post( form.action,
          $(form).serialize(),
          function( oData, sStatus )
          {
            if(( typeof oData === 'object' ) && ( typeof oData.success === 'boolean' ))
            {
              if( oData.success === true )
              {
                var divCommentNode = $('#commentNode'+formIdentifier+'_'+nObjectCommentId)[0];
                divCommentNode.parentNode.removeChild(divCommentNode);
                var sNewLabel = updateObjectCommentCount(oData.nTotalComments, formIdentifier);
                if (form.objectType.value == 'RESOURCE')
                {
                  updateFlightboardDisplay(form.objectId.value, sNewLabel);
                }
              }
              else
              {
                alert('An error occurred in processing the request to delete the comment: ' + oData.message);
              }
            }
            else
            {
              alert('Server returned unknown status on attempt to delete the comment.');
            }
          },
          'json'
  );
}

var insertComment = function(thisForm, response)
{
  /* Insert the new or editied comment into the DOM.*/
  var sInstanceIdentifier = response.sInstanceIdentifier;
  var nObjectCommentId = response.id;
  var sCommand = response.Command;
  var sCommentNode = 'commentNode' + sInstanceIdentifier + '_' + nObjectCommentId;

  try
  {
    var sNewLabel = 'Comments';
    $( '#comments' + sInstanceIdentifier )
      .each( function()
      {
        if( sCommand == 'EDIT' )
        {
         /* If it's an edited comment, remove the whole thing, then put the new one
          * at the top of the list, as it
          */
          $( '#commentNode' + sInstanceIdentifier + '_' + nObjectCommentId ).remove();
        }

        $( '<div />' )
          .attr( 'id', sCommentNode )
          .html( response.sObjectCommentDisplay )
          .appendTo( this );

        sNewLabel = updateObjectCommentCount(response.nTotalComments, sInstanceIdentifier, thisForm.objectId.value);

        //break the each() loop after first run
        return false;
      } );

    if (thisForm.objectType.value == 'RESOURCE')
    {
      updateFlightboardDisplay(thisForm.objectId.value, sNewLabel);
    }
  }
  catch (e)
  {
    alert('e:' + e.toSource() + '\n\n Data received for ObjectComment:\n' + response);
  }
}

var likeThis = function(sIdentifier)
{
  var form = document.getElementById('likeThis'+sIdentifier),
			olikeBtn = $( '[id="btnLikeThis' + sIdentifier + '"]' );

  /* Add a spinny and progress message */
	
	olikeBtn.removeClass('ui-button-text-only').addClass('ui-button-text-icon-primary').html( '<span class="ui-button-icon-primary ui-yakabox-icon ui-yakabox-icon-loading"></span><span class="ui-button-text">Saving...</span>' );

  $.post( form.action,
          $(form).serialize(),
          function( oData, sStatus )
          {
            if(( typeof oData === 'object' ) && ( typeof oData.success === 'boolean' ))
            {
              if( oData.success === true )
              {
                if (oData.Command == 'LIKE')
                {
                  form.Command.value = 'UNLIKE';
									olikeBtn.html( '<span class="ybx-microprofile-dialog-noclose">Unlike This</span>' );

                  sNewUserLikeDisplay = '<li class="ui-state-default ui-corner-all" id="tagUser' + oData.aNewUserLikeInfo.id + '_' + sIdentifier + '">';
                  sNewUserLikeDisplay += '<a href="/common/getObject.html?urn=' + oData.aNewUserLikeInfo.urn + '"';
                  sNewUserLikeDisplay += 'style="background-image: url(' + oData.aNewUserLikeInfo.icon + ');"';
                  sNewUserLikeDisplay += 'class="ui-yakabox-icon-link"';
                  sNewUserLikeDisplay += 'title="Likes &quot;' + oData.sObjectTitle + '&quot;">';
                  sNewUserLikeDisplay += oData.aNewUserLikeInfo.name + '</a></li>';

  							  $( '[id="tagUsersThatLikeThis' + sIdentifier + '"]' ).find('.ybx-likeList').prepend( sNewUserLikeDisplay );

                }
                else
                {
                  form.Command.value = 'LIKE';
									olikeBtn.html( '<span class="ybx-microprofile-dialog-noclose">Like This</span>' );
                  $( '[id="tagUser' + oData.nActiveUserId + '_' + sIdentifier + '"]' ).remove();

                  /* If the like comment is in the display, remove it. */
                  $( '[id="commentNode' + sIdentifier + '_' + oData.id + '"]' ).remove();
                }
  							
                var sCountDisplay = '';
                if ( parseInt( oData.nTotalComments, 10 ) !== 0 )
                {
                  sCountDisplay = '<strong><a href="/" onclick="return false;" target="_blank" title="See Who Likes This" ><strong>';
                  sCountDisplay += oData.nTotalComments;
                  sCountDisplay += ' </strong><span class="ui-yakabox-icon ui-yakabox-icon-like"></span></a>';
                }
							 $( '[id="tagUsersThatLikeThisCount' + sIdentifier + '"]' ).html( sCountDisplay );
              }
              else
              {
                alert('An error occurred in processing the request to like the object: ' + oData.message);
              }
            }
            else
            {
              alert('Server returned unknown status on attempt to like the object.');
            }
          },
          'json'
  );
}

function updateObjectCommentCount(nCount, sInstanceIdentifier)
{
  /* Update the count on the display */
  var sLabel = nCount + " Comment";
  if (nCount != 1)
  {
    sLabel += "s";
  }
  oObj = document.getElementById('totalComments'+sInstanceIdentifier);


if (oObj)
  {
    oObj.innerHTML = sLabel;
  }

  return sLabel;
}

function updateFlightboardDisplay(nObjectId, sLabel)
{
  /* This stuff is for comments living in a resource display on the flightboard.
   * Should we ever change that implmentation to use say microprofiles,
   * then we would be able to get rid of this section.
   */

  var sDiv = 'viewComments' + nObjectId;
  var divCommentTab = $('#' + sDiv)[0];
  if (divCommentTab)
  {
    var childNode = divCommentTab.childNodes[0];
    if (childNode)
    {
      childNode.innerHTML = sLabel;
    }
    if (typeof removeMetaFromCache == 'function')
    {
      removeMetaFromCache(nObjectId);
    }
  }
}

