    //<![CDATA[
    
    var comments_loaded = []
    var replies_loaded = []
    var bound_links = []
    
    function is_in(list, item) {
        for (var i=0;i<list.length;i++) {
            if (list[i] == item) return true
        }
        return false
    }    
    
    $(document).ready(function(){

        var comment_level_re = new RegExp("comment_level_(\\d+)", "")
        var comment_pk_re = new RegExp("comment_(\\d+)", "")
        
        var posted_re = new RegExp("this_is_a_comment", "g")

        function repopulate_loaded_comments() {
            
            comments_loaded = []
            
            $('.mptt-comments-tree .comment').each(function(){                 
                
                var classes = $(this).attr('class');
                var id = $(this).attr('id');
                
                console.log("classes="+classes);
                console.log("id=",id);
                
                var pk = parseInt(comment_pk_re.exec(id)[1])
                var level = parseInt(comment_level_re.exec(classes)[1])
                
                comments_loaded.push({id: id, pk: pk, level: level})
                
            })
            
        }

        function bind_submit(form, nxt) {
          
            form.bind("submit", function() {
            
                $.post(form.attr("action"), form.serialize(), function(data, textStatus){
 
                    var object_id = $("input[name=object_id]", form).val();
                    var content_type = $("input[name=content_type]", form).val();
                    var unique = "_" + content_type + "_" + object_id;
                    
                    if (posted_re.test(data)) {
                        if (nxt.hasClass('new_comment_form_wrapper')) {
                            $('#mptt-comments-tree' + unique).append(data)
                            nxt.replaceWith('<p>' + _MMF_GLOBAL.text.add_comment_confirm + '</p>')
                        }
                        else {
                            nxt.replaceWith(data)
                        }
                    }
                    else {
                        nxt.empty()
                        nxt.append(data)
                        nxt.slideDown("slow")
                        
                        var new_form = $("form", nxt)
                        bind_submit(new_form, nxt)
                    }
                }, "html")
                
                return false
            })
        }

        $(".comment_form").live("submit", function(e) {
          
          e.preventDefault();
          
          var form = $(this);
          
          var total_comments = $(".total_comment_count", this).text();
          var object_id = $("input[name=object_id]", this).val();
          var content_type = $("input[name=content_type]", this).val();
          var unique = "_" + content_type + "_" + object_id;
          
          if (total_comments) {
            total_comments = parseInt(total_comments);
          } else { 
            total_comments = 0;
          }
          
          $.post(form.attr("action"), form.serialize(), function(data, textStatus){
             total_comments += 1;
             $("#mptt-comments-tree" + unique).show();
             $("#comment_form" + unique).hide();
             $("#mptt-comments-tree" + unique).prepend(data);
             $("#comments" + unique + " h3").html("Comments (" + total_comments + ")");
             $(".add_comment"+unique+" .comment_details").html("<p>" + _MMF_GLOBAL.text.add_comment_confirm + "</p>")

          }, "html"); // post
 
        }); // live
    
        // Delete Replies
        $('.delete_comment').live('click', function(e){
            
            e.preventDefault();
            
            if (!confirm(_MMF_GLOBAL.text.delete_request_confirmirmation)) {
              return false;
            }

            var delete_url = $(this).attr("href");
            var delete_message = '';
            var delete_id = $(this).attr("id");

            $.get(delete_url, {}, function(data, textStatus){
                if (textStatus == 'success') {
                   delete_message = _MMF_GLOBAL.text.delete_comment_confirm;
                } else {
                   delete_message = _MMF_GLOBAL.text.delete_comment_error;
                }

                $('#comment_text_'+delete_id).text(delete_message);
            })

        });
        
        // Add a Comment or Reply
        $('.comment_reply, .comment_new').live("click", function(e) {
          
          e.preventDefault();
        
          var reply_link = $(this);
          var parent = reply_link.parent('p').parent("div").parent("div");
          
          parent.after('<div class="comment_form_wrapper comment_level_2"></div>')
  
          $.get(reply_link.attr('href') + '?is_ajax=1', function(data, textStatus){
                var nxt = parent.next('.comment_form_wrapper')
                nxt.empty()
                nxt.append(data)
                nxt.slideDown("slow")
                
                var form = $("form", nxt);
                bind_submit(form, nxt);
                
                $(".add_a_comment", nxt).trigger("click");
                
            }, "html");
            
            return false;
         });
         
         
         // View Replies
         $('.comment_replies').live("click", function(e) {
            
            var replies_link = $(this);

            e.preventDefault();
            
            var href = replies_link.attr('href');
            var id = 'comment_' + (new RegExp("(\\d+)/$").exec(href)[1]);

            if (!is_in(replies_loaded, id)) {
            
                $.get($(this).attr('href') + '?is_ajax=1', {}, function(data, textStatus){
                    
                    var comments_tree = data.comments_tree;

                    if (comments_tree) {  // 
                        $('#' + id).append( comments_tree.html );
                    }
                        
                }, "json");
                
                replies_loaded.push(id)
            }
            return false
        });
        
        // Expand Comments
        $('.comment_expand').live("click", function() {
        
            var expand_link = $(this);  
            
            var href = expand_link.attr('href')    
            var id = 'comment_' + (new RegExp("(\\d+)/$").exec(href)[1])
            
            var comment_el = $('#' + id)
            var content_el = $('.comment_content', comment_el)
            
            if (!is_in(bound_links, id)) {
                        
                if (content_el.hasClass('comment_collapsed_below')) {
                    content_el.removeClass('comment_collapsed_below');
                }
                else {
                    if (comment_el.hasClass('comment_collapsed')) {
                        comment_el.removeClass('comment_collapsed');
                    }
                    else {
                        comment_el.addClass('comment_collapsed');
                    } 
                }
            
                bound_links.push(id);
            }
            
            return false;
            
        })
            
        // Add a Comment Link
        $(".add_a_comment").live("click", function(e) {
            e.preventDefault();
            $(this).parent('p').parent('div').find('.add_comment_details').show();
            $(this).hide();
        })

        // Unknown Link
        $('.comments_more').live("click", function(e) {
            
            e.preventDefault();
            
            var comment_more_link = $(this);
            
            repopulate_loaded_comments();
            
            $.get(comment_more_link.attr('href') + '?is_ajax=1', { }, function(data, textStatus){
                
                var comments_for_update = data.comments_for_update;
                
                if (comments_for_update) {
                    for (var c=0;c<comments_for_update.length;c++){
                        var append_to_id = ''
                        var comment = comments_for_update[c]
                        for (var l=0;l<comments_loaded.length;l++) {
                            var loaded_comment = comments_loaded[l]
                            if (comment.level-1 == loaded_comment.level) append_to_id = loaded_comment.id
                        }
                        $('#' + append_to_id).append(comment.html)
                        comments_loaded.push({id: 'comment_' + comment.pk, pk: comment.pk, level: comment.level})
                    }
                }
                
                var comments_tree = data.comments_tree;
                
                if (comments_tree) {
                    comment_more_link.closest('.mptt-comments-tree').append(comments_tree.html);
                }
                
                repopulate_loaded_comments();
                
                var remaining_count = data.remaining_count;
                console.log("remaining_count="+remaining_count);
                if (remaining_count>0) {
                    $('.comments_more_remaining', this).html(remaining_count);
                    
                    var old_href = $(this).attr('href');
                    
                    comment_more_link.attr('href', 
                        old_href.replace(new RegExp("\\d+/$"), comments_loaded[comments_loaded.length-1].pk + '/')
                    )
                }
                else {
                     comment_more_link.hide();
                }
                
            }, "json")
            
            return false
        });
    
    }); // document ready

        
    //]]>

