Comments = {
  page: 1,
  count: 0,
  init: function()
  {
    Comments.count = $('div.comments .count:first').text();
    if ( Comments.count > 0 )
    {
      $('div.comments .header, div.comments .footer').show();
    }
    Comments.buildPaginator();
    Comments.buildActionIcons( $('ul.comments li.comment') );
      
    $('div.comments .login').click(Comments.showLoginForm);
    
    $('div.comments .refresh').click(function(){
      Comments.changeToPage( Comments.page, false );
    });
    
    $('div.comments .delete').click(Comments.deleteCommentClick);
    
    $('.postComment input[@type="image"]').click(function(){
      Comments.changeToPage( 1, true );
      $(this).attr('src', IMAGE_URL + 'images/Comments/post_loading.gif').blur().get(0).disabled = true;
      $.ajax({
        url: '/comments/post',
        type: 'post',
        dataType: 'json',
        data: { 
          content: $(this).siblings('textarea').val(),
          entity: $(this).parents('.container').find('.entity').text(),
          referenceID: $(this).parents('.container').find('.reference').text()
        },
        success: function(data) {
          if ( data.type == 'success' )
          {
            $('.comments .error').remove();
            var newComment = $( data.display ).prependTo('ul.comments');
            Comments.count = data.count;
            Comments.buildActionIcons( newComment );
            Comments.buildPaginator();
            
            var commentsDiv = $('div.comments');
            
            $('.postComment input[@type="image"]', commentsDiv).attr('src', IMAGE_URL + 'images/Comments/post_comment.gif').get(0).disabled = false;
            $('.commentCount .count', commentsDiv).text( ( parseInt( $('div.comments .commentCount .count:eq(0)').text() ) + 1 ) );
            $('.postComment textarea', commentsDiv).val('');
          }
          else 
          {
            Comments.showPostError( data.display );
          }
        },
        error: function(data) {
          Comments.showPostError( 'An error occurred while posting your comment. Please try again later.' );
        }
      });
    });
  },

  deleteCommentClick: function()
  {
    var commentNode = $(this).parent().parent().parent();
    $.ajax({
      url: '/comments/manage',
      type: 'post',
      dataType: 'json',
      data: { 
        action: 'delete',
        id: commentNode.children('.id').text(),
        entity: $(this).parents('.container').find('.entity').text(),
        referenceID: $(this).parents('.container').find('.reference').text()
      },
      success: function(data) {
        if ( data.result )
        {
          commentNode.slideUp('fast',function(){
            $(this).remove();
            Comments.count -= 1;
            $('div.comments .count').text( Comments.count );
            if ( Comments.count == 0 )
            {
              $('div.comments .header, div.comments .footer').hide();
              $('div.comments ul.comments').html('<li class="error">No comments have been posted. Be the first to post!</li>');
            }
          });
          
        }
        else
        {
          alert( data.message );
        }
      },
      error: function(data) {
        alert( 'An error occurred while deleting your comment. Please try again later.' );
      }
    });
  },
  
  showPostError: function( errorContent )
  {
    $('.postComment .error').remove();
    $('<div class="error">' + errorContent + '</div>').insertBefore('.postComment input[@type="image"]');
    $('.postComment input[@type="image"]').attr('src', IMAGE_URL + 'images/Comments/post_comment.gif').get(0).disabled = false;
  },

  buildPaginator: function( )
  {
    var pageCount = Math.ceil( Comments.count / 10 );
    if ( pageCount > 1 )
    {
      
      var html = '';
      // If we're not on page 1
      if ( Comments.page > 1 )
      {
        // Previous pages
        for ( var i = (Comments.page - 1);( ( i >= 1 ) && ( Comments.page - i <= 2 ) ); i-- )
        {
          var pclass = 'pseudolink';
          if ( i == Comments.page )
          {
            pclass += ' selected';
          }
          html = '<span class="' + pclass + '">' + i + '</span>' + html;
        }
        
        if ( i - 1 == 1 || i == 1 )
        {
          html = '<span class="pseudolink">' + i + '</span>' + html;
          if ( i - 1 == 1 )
          {
            html = '<span class="pseudolink">1</span>' + html;
          }
        } 
        
      }
      
      // Next pages
      for ( var i = Comments.page; ( i <= Comments.page + 2 && i <= pageCount ); i++ )
      {
        var pclass = 'pseudolink';
        if ( i == Comments.page )
        {
          pclass += ' selected';
        }
        html += '<span class="' + pclass + '">' + i + '</span>';
      }
      
      if ( i + 1 == pageCount || i == pageCount )
      {
        html += '<span class="pseudolink">' + i + '</span>';
        if ( i + 1 == pageCount )
        {
          html += '<span class="pseudolink">' + ( i + 1 ) + '</span>';
        }
      } 
      
      // If we're not already on the first page... show the first page link
      if ( Comments.page > 1 )
      {
        html = '<span class="pseudolink prev">&laquo;</span>' + html;
      }
      
      // If we're not already on the last page... show the last page link.
      var lastPage = Math.ceil( Comments.count / 10 );
      if ( Comments.page != lastPage )
      {
        html += '<span class="pseudolink next">&raquo;</span>';
      }
      
      $('div.comments .paginator .pages').html( html );
      $('div.comments .paginator .pages span').click(Comments.changePage);
    }
    return pageCount;
  },
  
  changePage: function()
  { 
    var nextVal = $(this).text();
    if ( $(this).hasClass('prev') )
    {
      nextVal = 1;
    } else if ( $(this).hasClass('next') ) {
      var lastPage = Math.ceil( Comments.count / 10 );
      nextVal = lastPage;
    }
    Comments.changeToPage( nextVal, false );
  },
  
  changeToPage: function( pageNumber, wait )
  {
    var async = true;
    if ( wait === true )
    {
      async = false;
    }
    $('div.comments .paginator .pageLoading').show();
    Comments.page = parseInt( pageNumber );
    $.ajax({
      url: '/comments/page',
      data: { 
        entity: $('div.comments').find('.entity').text(),
        referenceID: $('div.comments').find('.reference').text(),
        page: Comments.page 
      },
      async: async,
      dataType: 'json',
      type: 'post',
      success: function(data){
        if ( data.type == false )
        {
          $('div.comments .container').html( '<div class="error">We are performing routine maintenance on comments. Please try again later.</div>' );
        } else {
          if ( data.content )
          {
            $('div.comments .content').html( data.content );
            Comments.count = data.count;
            Comments.buildPaginator();
            Comments.buildActionIcons( $('div.comments ul.comments li.comment') );
            $('div.comments .paginator .pageLoading').hide();
            $('div.comments .delete').click(Comments.deleteCommentClick);
          }
        }
      }
    });
  },
  
  showLoginForm: function()
  {
    $('div.comments p.error').slideUp('slow');
    $('div.comments .loginForm').slideDown('slow');
  },
  
  buildActionIcons: function( commentObj )
  {
    commentObj.each(function(){
      var userid = $(this).children('span.userid').text();
      if( userid != '' )
      {
        // Perform some ActionIcons magic
        $(this).find('.actionIcons').mybActionIcons({
         userid: $(this).children('span.userid').text(),
         firstName: $(this).find('li.name a').text(),
         vipLevel: $(this).find('li.vipLevel').text()
        }, { token: stok, doMsg: true, doFriend: true, doStar: true, doFlirt: true, doGift: true, doAdmire: true, doIconPopUp: true, order: [ 'doMsg', 'doFriend', 'doFlirt', 'doStar', 'doGift', 'doAdmire', 'doIconPopUp' ] });
      }
    });
  }
};
