

var arrowRight = null;
var arrowDown = null;

var getArrowRight = function () {
    if (arrowRight == null) {
        arrowRight = $('<img src="/media/p/images/doc_arrowright.png"/>');
    }
    return arrowRight;
}

var getArrowDown = function () {
    if (arrowDown == null) {
        arrowDown = $('<img src="/media/p/images/doc_arrowdown.png"/>');
    }
    return arrowDown;
}
    
var setArrow = function(ch, arrow) {
    var linkSpan = ch.find('.post_comment_link').parent('span');
    linkSpan.children('img').remove();
    linkSpan.prepend(arrow);        
}    

    
var ElHolder = function()
{
    var holder = null;
    
    $(function(){
        holder = $('body').append('<div/>');
    });

    var self = {
        add: function(el) {
            $(function(){
                holder.append(el);
            });
        }
    };
    return self;
}


var CommentManager = function(document_id) {
    var doc_id = document_id;

    var getCommentHolderSel = function(id) {
            return '#ch-p'+id;
    }

    var self = 
    {
        // retrieves comment counts and injects comment indicator 
        // on response
        init: function() {
            //self.holder = ElHolder();
            self.commentFormManager = CommentFormManager();
            self.commentFormManager.init();
            self.commentFormManager.onCommentPostSuccess = function(id, comment_id) {
                self.incrCommentNum(id);
            };
            self.inject();
        },

        inject: function() {
            
            var enter2 = function(blockwrap, commentholder) {
                blockwrap.children('.block').removeClass('blockoff');
                var b = blockwrap.find('.bubble');
                b.addClass('bubbleselected');
                if (b.text() == '0') {
                    b.removeClass('bubbleNo');
                } 
                
                commentholder.addClass('blockon');
            };

            var leave2 = function(blockwrap, commentholder) { 
                blockwrap.children('.block').addClass('blockoff');
                var b = blockwrap.find('.bubbleselected');
                b.removeClass('bubbleselected');
                if (b.text() == '0') {
                    b.addClass('bubbleNo');
                } 
                commentholder.removeClass('blockon');
            };
            
            $('.blockwrap').mouseenter(function() { 
                    enter2($(this), $(this).next('.comment_holder'));
                });

            $('.blockwrap').mouseleave(function() {
                    leave2($(this), $(this).next('.comment_holder'));
                });
              

            $('.comment_holder').mouseenter(function() {
                    enter2($(this).prev('.blockwrap'), $(this));
                });

            $('.comment_holder').mouseleave(function() {
                    leave2($(this).prev('.blockwrap'), $(this));
                });
            
            $('.bubble').click(self.commentClk);
            $('.blockwrap').click(function() {
                var ch = $(this).next('.comment_holder');
                if (ch.is(':visible')) { 
                    ch.fadeOut('fast');
                } else {
                    ch.fadeIn();
                    setArrow(ch, getArrowRight());
                }
                return false;
            });

            $('.hide').click(function() { 
                $(this).parents('.comment_holder').fadeOut('fast');
            });


            
        },
        
        commentClk: function() {
            var el = $(this).parents('.blockwrap').next('.comment_holder');
            if (el.is(':visible')) { 
                el.fadeOut('fast');
            } else {
                el.fadeIn();
            }
            return false;
            
        },
        
        // increment the comment num for a particular paragraph
        incrCommentNum: function(id) {
            var bubble = $('#cb-'+id);
            bubble.text(parseInt(bubble.text())+1);
            bubble.removeClass('bubbleNo').addClass('bubbleHas');
        }
    };
    
    return self;
};

// wraps up logic to attach event to 
// form. This is necessary to abstract
// away some IE errors
function AttachFormSubmit(el, cb) {
    el.find('form').submit(cb);
    el.find('.submit').click(cb);
    
    // workaround for IE form bubble event problem
    el.find(':submit').click(cb);
    
    // turn on enter form submission in ie
    // from: http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/
    el.find('input').keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
            el.find(':submit').click();  
            return false;  
        } else {  
            return true;  
        } 
    });            
}

/*
 * Controls opening and closing of comment form
 */
var CommentFormToggler = function() {


    
    var self = {
        
        // called when new .comment_form element is created
        // with new .comment_form element as argument.
        onFormCreate: function(commentForm, commentHolder) {
            
        },
       
        toggle: function() {
            var on = $(this).data('comment-form-toggle');
            if (on == null || on == false) {
                on = false;
                self.on($(this));
            } else {
                self.off($(this));
            }

        },
        on: function(el){
            el.data('comment-form-toggle', true);
            var f = $('.comment_form_holder > .comment_form').clone();
            var ch = el.parents('.comment_holder');
            // ! Assumes post_comment_link is a child of .comment_holder
            var pID = ch.attr('id').replace('ch-', '');
            //f.prepend('<div class="form_comment_error" id="form_comment_error_'+pID+'"></div>');

            f.find('#id_elementID').val(pID);
            //f.find('#id_object_pk').val('');
            f.find('#id_timestamp').val(Math.round(new Date().getTime() / 1000));

            f.hide().appendTo(el.parents('.comments')).fadeIn();
           
            self.onFormCreate(f, ch);

            setArrow(ch, getArrowDown());

        },    
        
        // needs to be called by a child of .comment_holder
        off: function(el) {
            el.data('comment-form-toggle', false);
            var ch = el.parents('.comment_holder');
            ch.find('.comment_form')
                   .fadeOut("fast", function() { $(this).remove(); });            

            setArrow(ch, getArrowRight());
        }
    };
    
    return self;        
    
};

/*
 * Controls actions related to the comment form, such as comment
 * posting
 */
var CommentFormManager = function() {
    var commentFormToggler = CommentFormToggler();
    

    
    commentFormToggler.onFormCreate = function(commentForm, commentHolder) {
        AttachFormSubmit(commentForm, form_submit);
    };
        
    var setErrorMsg = function(json, pID) {
        var e = '';
        if (json.errorMsg) {
            e = json.errorMsg;
        } else {
            var d  = {'url': 'Website', 'comment': 'Note', 'name': 'Name'};
            var s = "There were some issues with your note:<br/><br/>";
            for(a in json.errors) {
                s += '<b>'+d[a] + "</b>: ";
                s += json.errors[a];
                s += "<br/>";
            }
            e = s;
        }
        
        $('#ch-'+pID).find('.msg')
                    .html(e).show().css('backgroundColor', '#FFACAC')
                    .animate({ backgroundColor: '#FFFFCC'}, 1500);

    };
      
    var commentPostSuccess = function(commentsList, pID, comment_id) {
        var holder = commentsList.parents('.comment_holder');
        commentFormToggler.off(holder.find('.post_comment_link'));

        self.onCommentPostSuccess(pID, comment_id);

        var msg = 'Thank you, your note has been posted.';
        $('#ch-'+pID).find('.msg')
                    .text(msg).show().css('backgroundColor', '#D9F8E1')
                    .animate({ backgroundColor: '#FFFFCC'}, 1500,
                            function(){
                                var el = $(this);
                                setTimeout(function(){el.fadeOut();}, 2000);
                            });
                          

        setTimeout(function(){
            $.get('/fr/comments/id/'+comment_id+'/', function(data){ 
                commentsList.find('.nocomments').remove();
                var newComment = '';//$(data);
                if (commentsList.children().length == 0) {
                    newComment = $('<div class="commentbody_first" id="c'+comment_id+'">'+data+'</div>');
                } else {
                    newComment = $('<div class="commentbody" id="c'+comment_id+'">'+data+'</div>');
                }
                newComment.appendTo(commentsList)
                              .animate({ backgroundColor: '#AED0F9'}, 400,
                              function() {
                                  $(this).animate({ backgroundColor: commentsList.parents('.comments').css('backgroundColor')}, 1500);
                              });
                }
             );
         }, 1500);
         
    };      
      
    var form_submit = function() {
        var holder = $(this).parents('.comment_holder');
        var pID = holder.attr('id').replace('ch-', '');

        var formEls = {};
        $(this).parents('.comment_form').find(':input').each(function(){ 
            var el = $(this);
            formEls[el.attr('name')] = el.val();
        });
        
        var commentsList = holder.find('.comments-list');
        var cb = function(data){ 
            if (data.error) {
                setErrorMsg(data, pID);
            } else {
                commentPostSuccess(commentsList, pID, data.comment_id);
            }
        
        };
        
        $.post('/fr/comments/post_ajax/'+documentid+'/', formEls, cb, "json");
        return false;
    };          
      
    var self = {
        init: function() {
            $('.post_comment_link').click(commentFormToggler.toggle);
        },
        
        onCommentPostSuccess: function() {}
        
    };

    return self;  
    
};

