var commentsView = {
  COMMENT_VIEWABLE_COUNT: 6,
  selectedVideoId: 0,
  selectedCliqueId: 0,
  currentSortOrder: 0,
  init: function () {
    commentsView.initFunc();
    commentsView.initEvents();
  }, //init
  initFunc: function () {
    $('.comments-button').button();
    commentsView.showMoreComments();
  }, //initFunc
  initEvents: function () {
    $('#commentSortDropdown').live('click', function () {
      $('#commentSortDropdown .customDropdownOptions').show();
    });

    $('#commentSortDropdown .customDropdownOptions').live('mouseleave', function () { $(this).hide() });

    $('#commentSortDropdown .customDropdownOptions div').live('click', function () {
      commentsView.loadSortedComments(commentsView.selectedVideoId, commentsView.selectedCliqueId, 0);
      //            revCove.updateScroll("#commentWrapper");
    });

    $('#comments_placeholder .comments-reply-select').live('click', function () {
      $.get('/Comment/ReplyView', { id: $(this).attr('data-parentid') }, function (data) {
        var id = $(this)[0].data.split('=')[1].replace("&nocache", "");
        var target = commentsView.getCommentElementById(id, '.comments-reply-input-wrapper');
        $(target).html(data);
        $(target).removeClass('ui-helper-hidden');
        $('.comments-button').button();
        $('textarea.resizable:not(.processed)').resizable({
          handles: "s",
          minHeight: 145
        });
        //                commentsView.createScroll($(target).find("textarea"));
      });
    });

    $('#comments_placeholder .comments-edit-select').live('click', function () {
      var date, nocache;
      if ($.browser.msie) {
        date = new Date();
        nocache = date.getDay() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds();
      }
      $.get('/Comment/EditView', { id: $(this).attr('data-parentid'), nocache: nocache }, function (data) {
        var id = $(this)[0].data.split('=')[1].replace("&nocache", "");
        var target = commentsView.getCommentElementById(id, '.comments-edit-input-wrapper');
        $(commentsView.getCommentElementById(id, '.comment-text')).hide();
        $(target).html(data);
        $(target).removeClass('ui-helper-hidden');
        $('.comments-button').button();
        $('textarea.resizable:not(.processed)').resizable({
          handles: "s",
          minHeight: 145
        });
      });
    });

    $('#comments_placeholder .comments-like-select').live('click', function () {
      $.post('/Comment/Like', { commentid: $(this).attr('data-parentid') }, function (data) {
        if (data.showRegistration != undefined) {
          commentsView.showRegistration();
          return;
        }

        if (undefined != data.result && true == data.result) {
          var id = $(this)[0].data.split('=')[1].replace("&nocache", "");
          var currentLike = parseInt($("#like-comment-" + id).html());
          $("#like-comment-" + id).html((currentLike + 1));
          $("#like-button-" + id).addClass("hidden");
          $("#unlike-button-" + id).removeClass("hidden");
        }
      }); //like
    });

    $('#comments_placeholder .comments-unlike-select').live('click', function () {
      $.post('/Comment/Unlike', { commentid: $(this).attr('data-parentid') }, function (data) {
        if (data.showRegistration != undefined) {
          commentsView.showRegistration();
          return;
        }

        if (undefined != data.result && true == data.result) {
          var id = $(this)[0].data.split('=')[1].replace("&nocache", "");
          var currentLike = parseInt($("#like-comment-" + id).html());
          $("#like-comment-" + id).html((currentLike - 1));
          $("#unlike-button-" + id).addClass("hidden");
          $("#like-button-" + id).removeClass("hidden");
        }
      }); //like
    });

    $('.comments-reply-post-submit').live('click', function () {
      var id = $(this).attr('data-id');
      var target = commentsView.getCommentElementById(id, 'textarea');
      $.post('/Comment/ReplyView', { id: id, comment: escape($(target).val()) }, function (data) {
        if (data.showRegistration != undefined)
          commentsView.showRegistration();
        else
          $(target).val('');

        var currentPage = commentsPaging.currentPage;
        var nbPage = commentsPaging.nbPages;
        commentsView.closeRepliesAndEdits();
        commentsPaging.onInitGoToPage = (currentPage + commentsPaging.nbPages - nbPage);
        commentsView.refreshComments();


      });
    });

    $('.comments-reply-post-cancel').live('click', function () {
      commentsView.closeRepliesAndEdits();
    });

    $('.comments-edit-post-submit').live('click', function () {
      var id = $(this).attr('data-id');
      var target = commentsView.getCommentElementById(id, 'textarea');
      $.post('/Comment/EditView', { id: id, comment: escape($(target).val()) }, function (data) {
        if (data.showRegistration != undefined)
          commentsView.showRegistration();
        else
          $(target).val('');

        var currentPage = commentsPaging.currentPage;
        var nbPage = commentsPaging.nbPages;

        commentsView.closeRepliesAndEdits();
        commentsPaging.onInitGoToPage = (currentPage + commentsPaging.nbPages - nbPage);
        commentsView.refreshComments();
      });
    });

    $('.comments-edit-post-cancel').live('click', function () {
      commentsView.closeRepliesAndEdits();
      //            revCove.updateScroll("#commentWrapper");
    });

    $('#post_submit_new').live('click', function () {
      $.post('/Comment/PostNewComment', { videoId: $(this).attr('data-id'), cliqueId: commentsView.selectedCliqueId, comment: escape($('#new_post').val()) }, function (data) {
        //todo something if they are not a user
        if (data.showRegistration != undefined)
          commentsView.showRegistration();
        else
          $('#new_post').val('');
        commentsPaging.onInitGoToPage = 0;
        commentsView.refreshComments();
      });
    });

    $('#show_more_comments').live('click', function () { commentsView.showMoreComments(); });

    //Show Hide
    $('.show-comment').live('click', function () {
      $.post('/Comment/SetCommentVisibility', { commentId: $(this).attr('data-value'), visible: true }, function (data) {
        commentsView.refreshComments();
      });
    });

    $('.hide-comment').live('click', function () {
      $.post('/Comment/SetCommentVisibility', { commentId: $(this).attr('data-value'), visible: false }, function (data) {
        commentsView.refreshComments();
      });
    });

    $('textarea.resizable').live('keyup', function () {
      var contentHeight = $(this)[0].scrollHeight;
      if (contentHeight > 145 && contentHeight != $(this).height()) {
        $(this).height(contentHeight).parent().height(contentHeight + 2);
      }
    });
  }, //initEvents
  closeRepliesAndEdits: function () {
    $('.comments-reply-input-wrapper').html('&nbsp;');
    $('.comments-edit-input-wrapper').html('');
    $('.comments-reply-input-wrapper').addClass('ui-helper-hidden');
    $('.comment-text').show();
    //        revCove.updateScroll("#commentWrapper");
  }, //closeRepliesAndEdits
  getCommentElementById: function (id, selector) {
    return $('#comment_' + id + ' ' + selector);
  }, //getCommentElementById
  showRegistration: function () {
    modal.openLoginModal("COMMENTS");
    // modal.setHtml('<div id="comment_registration_placeholder"></div>');
    //$('#comment_registration_placeholder').append($('#user_registration_template').jqote());
    modal.open();
  }, //showRegistration
  showMoreComments: function () {
    for (var i = 0; i < commentsView.COMMENT_VIEWABLE_COUNT; i++) {
      $($('#comments_wrap ul.ui-helper-hidden')[0]).removeClass('ui-helper-hidden');

    }
    if ($('#comments_wrap ul.ui-helper-hidden').length == 0)
      $('#show_more_comments_wrap').hide();
    //        revCove.updateScroll("#commentWrapper");
  }, //showMoreComments
  loadComments: function (video, clique, vipVideoId) {

    ////commentsView.loadSortedComments(video, clique, 0, vipVideoId); remove load comments

  }, //loadcomments
  showCommentListLoadingIndicator: function () {
    $('#comments').empty();
    $('#comments').append($('#commentsLoadingTemplate').jqote());
  },
  loadSortedComments: function (video, clique, sort, vipVideoId) {
 
    commentsView.showCommentListLoadingIndicator();
    commentsView.selectedVideoId = video;
    if (clique != null && clique != '')
      commentsView.selectedCliqueId = clique;
    else
      commentsView.selectedCliqueId = 0;
    commentsView.currentSortOrder = sort;
    var date = new Date();
    var nocache = date.getDay() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds();


    $.get('/Comment/CommentListView', { videoId: commentsView.selectedVideoId,
      cliqueId: commentsView.selectedCliqueId,
      sortOrder: commentsView.currentSortOrder,
      nocache: nocache,
      vipVidId: vipVideoId
    }, function (data) {
      $('#comments').html(data);
      commentsView.showMoreComments();
      $('#new_post.resizable:not(.processed)').resizable({
        handles: "s",
        minHeight: 145
      });
      $('span.currentSort').text($('#commentSortDropdown  .customDropdownOptions').find('div[data-value=' + commentsView.currentSortOrder + '] span').text());
      commentsPaging.init();
      //            revCove.updateScroll("#commentWrapper");
    });
  }, //loadSortedcomments
  refreshComments: function () {
 
    commentsView.showCommentListLoadingIndicator();
    var date = new Date();
    var nocache = date.getDay() + '' + date.getHours() + '' + date.getMinutes() + '' + date.getSeconds();
    $.post('/Comment/CommentListView', { videoId: commentsView.selectedVideoId, cliqueId: commentsView.selectedCliqueId, sortOrder: commentsView.currentSortOrder, nocache: nocache }, function (data) {
      $('#comments').empty();
      $('#comments').append($(data));
      commentsView.showMoreComments();
      $('textarea.resizable:not(.processed)').resizable({
        handles: "s",
        minHeight: 145
      });
      commentsPaging.init();
      //            revCove.updateScroll("#commentWrapper");
    });
  }, //refreshComments

  initScroll: function () {
    commentsView.createScroll("#new_post");
  },

  createScroll: function (selectorOrObj) {
    if (typeof selectorOrObj == "string") {
      selectorOrObj = $(selectorOrObj);
    }
    selectorOrObj.jScrollPane({
      showArrows: true,
      verticalGutter: 0,
      animateScroll: true,
      verticalDragMinHeight: 98,
      verticalDragMaxHeight: 98,
      autoReinitialise: true
    });
  }
};

$(document).ready(function () {
    commentsView.init();    
});

var commentsPaging = {
    CommentsPerPage: 10,
    currentPage: 1,
    nbComments: 0,
    nbPages: 0,
    onInitGoToPage: 0,
    init: function () {
        commentsPaging.nbComments = $(".comments-from-user").length;
        commentsPaging.nbPages = Math.ceil(commentsPaging.nbComments / commentsPaging.CommentsPerPage);

        commentsPaging.currentPage = 1;
        if (commentsPaging.onInitGoToPage != 0) {
            commentsPaging.currentPage = commentsPaging.onInitGoToPage;
            commentsPaging.onInitGoToPage = 0;
        }
        commentsPaging.showCommentsForPage(commentsPaging.currentPage);
        commentsPaging.drawPaging();

    },
    initAndLoadLastPost: function (currentPageBeforePost, totalPageBeforePost) {
        var nbComments = $(".comments-from-user").length;
        var nbPages = Math.ceil(nbComments / commentsPaging.CommentsPerPage);
        commentsPaging.init(currentPageBeforePost + totalPageBeforePost - nbPages);
    },
    drawPaging: function () {
        var output = "";
        var nbPageToDisplay = 10;
        var FirstPages = commentsPaging.currentPage <= 5
        var LastPages = commentsPaging.currentPage > (commentsPaging.nbPages - 5);
        var MorePagesThanAllowedToDisplay = commentsPaging.nbPages > nbPageToDisplay;

        if (commentsPaging.nbPages < 1) return;

        if (commentsPaging.currentPage > 1) output += '<a onclick="commentsPaging.showCommentsForPage(' + (commentsPaging.currentPage - 1) + ')"><span>&lt;&lt; Previous</span></a>';

        if (MorePagesThanAllowedToDisplay && !FirstPages) {
            output += '<a onclick="commentsPaging.showCommentsForPage(1)"><span>1</span></a>';
            output += '<a onclick="commentsPaging.showCommentsForPage(2)"><span>2</span></a>...';
        }

        if (FirstPages && LastPages) {
            LastPages = false;
        }

        var startPosition = commentsPaging.currentPage - 2;
        var nbPaging = 5;
        if (FirstPages) {
            startPosition = 1;
            nbPaging += 2;
        }
        if (LastPages) {
            startPosition = commentsPaging.nbPages - 6;
            nbPaging += 3;
        }

        var pageNum = 0;
        for (var i = 0; i < nbPaging && pageNum < commentsPaging.nbPages; i++) {
            pageNum = i + startPosition;
            var selected = pageNum == commentsPaging.currentPage ? 'class="selected" ' : '';
            output += '<a ' + selected + 'onclick="commentsPaging.showCommentsForPage(' + pageNum + ')"><span>' + pageNum + '</span></a>';

        }

        if (MorePagesThanAllowedToDisplay && !LastPages) {
            output += '...<a onclick="commentsPaging.showCommentsForPage(' + (commentsPaging.nbPages - 1) + ')"><span>' + (commentsPaging.nbPages - 1) + '</span></a>';
            output += '<a onclick="commentsPaging.showCommentsForPage(' + commentsPaging.nbPages + ')"><span>' + commentsPaging.nbPages + '</span></a>';
        }
        if (commentsPaging.currentPage < commentsPaging.nbPages) output += '<a onclick="commentsPaging.showCommentsForPage(' + (commentsPaging.currentPage + 1) + ')"><span>Next &gt;&gt;</span></a>';

        $("#comments_paging_container").html(output);
        //        revCove.updateScroll("#commentWrapper");
    },

    showCommentsForPage: function (page, scrollToTop) {
        commentsPaging.currentPage = page;
        var arrayOfComments = $(".comments-from-user");
        $(".comments-from-user").addClass("hide");
        for (var i = 0; i < commentsPaging.CommentsPerPage; i++) {
            if (arrayOfComments[i + (page - 1) * commentsPaging.CommentsPerPage] == undefined) break;
            $("#" + arrayOfComments[i + (page - 1) * commentsPaging.CommentsPerPage].id).removeClass("hide");
        }
        commentsPaging.drawPaging();
        if (scrollToTop){
            commentsPaging.scrollToTop();
    }
    },

    scrollToTop: function(){
        $('html, body').animate({
            scrollTop: $("ul.comments-thread").offset().top - 82
        }, 600);
    }
};


