/* comments.js updated 4/26/2010 */

/*Added the condition for 'wpbody' for comments count by Irfan on 07/21/10 */
Comment.comments_count_template = function() {
    if ($("body").attr("id") == "gallery" || $("body").attr("id") == "wpbody" ) 
        template = "(#{count})";
    else if($("body").attr("id") == "cchome" || $("body").attr("id") == "rchome" || $("body").attr("id") == "lschann") 
        template = "Join the conversation (#{count} comments)";
    else
        template = "#{count} comments";
    return template;
};

Comment.top_pagination_template = function() {
    template = '<div id="commentBox"><div class="commentBoxTop"><div class="upper clear"> <span class="replyLink"><a href="#new_comment_form"><img src="http://img2.timeinc.net/health/static/i/btn_reply.png" alt="Reply to this Discussion" width="165" height="25"/></a></span> <span class="commentLinks">#{expand_all_or_collapse_all} | <a href="#new_comment_form">Add comment</a></span> </div><div class="commentPageList clear"> <span class="pages">#{info}</span> <span class="pagination"> Page: #{links}</span> </div></div><div class="sortLinks">#{oldest_first} | #{newest_first}</div></div>';
    return template;
};

Comment.bottom_pagination_template = function() {
    template = '<div class="commentPageList bottomPagination clear"> <span class="pages">#{info}</span> <span class="pagination"> Page: #{links}</span> </div>';  
  return template;
};

Comment.render_updated_comments_pagination= function() {
      $.getJSON(Comment.comments_url(), function(data) {
        var pagination = data.pagination;
        Pagination.init(pagination);
        pagination.info = Pagination.pagination_info();
        pagination.links = Pagination.paginate();
        pagination.expand_all_or_collapse_all = Comment.expand_all_or_collapse_all_link();
        pagination.oldest_first = Comment.oldest_first_link_or_span();
        pagination.newest_first = Comment.newest_first_link_or_span();

        if((typeof pagination.total_entries) !== 'undefined' && parseInt(pagination.total_entries, 10) > 0){
            $("#commentBox").replaceWith(Template.evaluate(Comment.top_pagination_template(), pagination));
            Comment.render_comments_count();
            $(".bottomPagination").replaceWith(Template.evaluate(Comment.bottom_pagination_template(), pagination));
        }
      });
};

Comment.render_comments_count = function(version) {
      if (version == undefined) version = "";
      tmpl = Comment.comments_count_template();
       $.getJSON(Comment.comments_count_url(), function(data) { 
        $("a.comments_count").each(function() {                                      
          board_resource_id = $(this).attr("rel");
          object = {count: data[board_resource_id]};
          if (object.count > 0) {
            if (object.count == 1) tmpl = tmpl.replace(/comments/i, "comment");
            $(this).html(Template.evaluate(tmpl, object));
          }          
        });
      });
    };

Comment.clone_form = function(comment_id) {
    var reply_form = $("#new_comment_form").clone();
    reply_form.removeAttr("id");
    reply_form.append('<input type="hidden" name="comment[parent_id]" value="'+comment_id+'" />');
    reply_form.find(".form_title").text("Reply");
    reply_form.find("div.errors").empty();
    reply_form.find(".charCount").text("500 characters remaining");
    reply_form.find("textarea").maxLength(500);    
    reply_form.find("textarea").bind("click change keydown keyup keypress blur focus", function(){
        var count = $(this).val().length;
        $(this).parent().find(".charCount").text((500 - count) + " characters remaining");
    });
    return reply_form;
};

Comment.comment_template = function() {
    template =
    '<li class="comment" id="comment_#{id}"><span class="author">#{user_name}</span><span class="date">#{created_at:Format.iso_date}</span>#{body:Format.text}<ul class="comment-tools"><li><a href="#" class="get expand_replies_link #{viewable_children_count:Format.quantity_class_name}" id="toggle_replies_#{id}">Read replies (#{viewable_children_count})</a></li><li><a href="#" class="get add_reply_link" id="toggle_add_reply_#{id}">Add reply</a></li></ul><div class="form"></div><ul class="replies"><li/></ul></li>';
    return template;
};

Comment.expand_all_or_collapse_all_link = function() {
    if (Url.get_params().expand_all == 'true') {
        return '<a class="collapse" href="'+Url.new_url({expand_all: 'false'})+'">Collapse all replies</a>';
    } else {
        return '<a class="expand" href="'+Url.new_url({expand_all: 'true'})+'">Expand all replies</a>';
    }
}

Comment.reset_form = function(form, options) {
      options = options || {};
      form = $(form);

      form.find("input#comment_user_name").val("");
      form.find("textarea").val("");
      form.find("div.errors").empty();
      try {
          form.enable_submit();
      } catch (e) {
          if(typeof(console) !== "undefined" || typeof(console.log) !== "undefined") console.log("Error enabling submit: ", e)
      }
      if (form.attr("id") != "new_comment_form" && options.hide) form.parent().hide();
    };

jQuery.fn.maxLength = function(max){
    this.each(function(){
        var type = this.tagName.toLowerCase();
        var inputType = this.type? this.type.toLowerCase() : null;
        if(type == "input" && inputType == "text" || inputType == "password"){
            this.maxLength = max;
        }
        else if(type == "textarea"){
            this.onkeypress = function(e){
                var ob = e || event;
                var keyCode = ob.keyCode;
                var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
                return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
            };
            this.onkeyup = function(){
                if(this.value.length > max){
                    this.value = this.value.substring(0,max);
                }
            };
        }
    });
};

function getContentUrl(url) {return url.replace("comments.html", "index.html");}

$(document).ready(function(){
    $("div.form textarea").maxLength(500);                
    //character counter
    $("div.form textarea").bind("click change keydown keyup keypress blur focus", function(){
        var count = $(this).val().length;
        $(this).parent().find(".charCount").text((500 - count) + " characters remaining");
    });
});
