/**
 * @fileoverview 该文件是 xweibo 用户评论管理。
 */
 
 (function($){

var 
    UNDEFINED,
    
    NULL = null,
    
    TRUE = true,
    
    FALSE = false,
    
    slice = Array.prototype.slice,
    
    toString = Object.prototype.toString,
    
    toInt = parseInt,
    
    xwb = window.XWB,
    
    eventMgr = xwb.eventMgr,
    
    buildModulePath = xwb.url,
    
    htmlEscape = xwb.escape,
    
    alertMsg = xwb.alert,
    
    confirmBox = xwb.confirm,
    
    apiCall = xwb.apiCall,
    
    isArray = $.isArray,
    
    isFn = $.isFunction;
    
var myComment = (function() {
    var 
        mc,
        $ui = {};
    
    var 
        show_del_btn = 1, //显示删除按钮
        hide_del_btn = 2, //隐藏删除按钮
        del_comment = 3, //删除评论
        reply_comment = 4, //回复评论
        send_comment = 5, //发送评论
        end = '';
    
    function eventBind(commentCallback) {
        $ui.ul
            .mouseover(function(e) {
                var $li = getLi(e.target);
                
                var $del = $li.find('a.del-icon');
                mc.handle(show_del_btn, {'$del': $del});
            })
            .mouseout(function(e) {
                var $li = getLi(e.target);
                
                if($.contains($li[0], e.relatedTarget)) {return;}
                
                var $del = $li.find('a.del-icon');
                mc.handle(hide_del_btn, {'$del': $del});
            })
            .click(function(e) {
                var 
                    $li,cid,
                    $tar = $(e.target);
                
                if($tar.hasClass('del-icon')) {
                    $li = getLi(e.target);
                    cid = $li.attr('id').substring(2);
                    
                    mc.handle(del_comment, {'$li': $li, 'cid': cid});
                    
                }
                else if($tar.hasClass('reply-icon')) {
                    $li = getLi(e.target);
                    cid = $li.attr('id').substring(2);
                    
                    mc.handle(reply_comment, {
                        'cid': cid,
                        '$ctn': $li.find('div.comment-c')
                    });
                    
                    var 
                        $textarea = $li.find('textarea.comment-textarea'),
                        re = /^回复@.*?:/;
                    
                    $textarea.val('回复@' + $tar.attr('rel') + ':' + $textarea.val().replace(re, ''));
                    $textarea.attr('rel', cid);
                    
                    $li.find('.keyin-tips span').text($textarea.checkText());
                }
                else if($tar.attr('rel')==8) {
                    $li = getLi(e.target);
                    mc.handle(send_comment, {
                        'wbid': $li.attr('rel'),
                        '$li': $li,
                        'type': 2, //头像类型 50
                        'callback': commentCallback
                    });
                }
            });
        
        $ui.selectAll.length > 0 &&
        $ui.selectAll.click(function() {
            var isChecked = this.checked;            
            $('#container li>label>input').attr('checked', isChecked);
        });
        
        $ui.delAll.length > 0 &&
        $ui.delAll.click(function() {
            var cid=[];
            var $li = $('#container div.comment-list li').filter(function(i,item) {
                return $('label>input', item).attr('checked');
            });
            
            $.each($li, function(i, item) {
                cid.push(item.id.substring(2));
            });
            
            cid = cid.join(',');
            
            mc.handle(del_comment, {'$li': $li, 'cid': cid});
            
        });
            
            
    }
    
    function getLi(el) {
        
        while(el && el.tagName != 'LI') {
            el = el.parentNode;            
            if(el == document.body) { return NULL}
        }
        
        return $(el);
    }
    
    return {
        init: function(commentCallback) {
            mc = myComment;            
            //缓存DOM
            $ui.ul = $('#container div.comment-list ul').first();
            $ui.selectAll = $('#container div.filter input[type="checkbox"]');
            $ui.delAll = $('#container div.filter>a');
            
            eventBind(commentCallback);
           
        },
        
        handle: function(cmd, params) {
            switch(cmd) {
                case show_del_btn:
                    params.$del.show();
                    break;
                    
                case hide_del_btn:
                    params.$del.hide();
                    break;
                    
                case del_comment:

                    if(params.$li.length <= 0) {
						alertMsg({
							msg: '请选择要删除的内容。',
							timeout: 2
						});
						return;
					}
                
                    confirmBox({
                        title: '提示',
                        msg: '确定要删除评论吗'
                    }, function(){
                        apiCall('comment_destroy', {
                            data: 'id=' + params.cid,
                            success: function(msg){
                                if (msg.errno == 0) {
                                    params.$li.slideToggle('fast', function() {
                                        params.$li.remove();
                                    });
                                    var $commentBtn = $('#commentBtn');
                                    if($commentBtn[0]) {
                                        var num = $commentBtn.text().match(/\d+/);
                                        if (num == 1) {
                                            $commentBtn.text('评论');
                                        }
                                        else {
                                            $commentBtn.text('评论(' + (--num) + ')');
                                        }
                                    }
                                }
                            }
                        });
                    });  
                    break;
                    
                case reply_comment:
                    var $el = params.$ctn.find('div.feed-comment');
                    if(!$el[0]) {
                        $el = XWB.comment.createTextArea();
                        params.$ctn.append($el);
                        $el.show();
                    }else {
                        $el.toggle();
                    }
                    
                    if($el[0].offsetWidth) {
                        var $area = $el.find('textarea.comment-textarea');
                        $area.focusEnd();
                    }
                    
                    

                    break;
                    
                case send_comment:
                    XWB.comment.sendComment(params);
                    break;
            }

        }
    };
})();

var commentList = (function() {
    var 
        cl,
        $ui = {};
        
    function eventBind() {
        var $area =$ui.postArea;
        
        $area.find('a.choose-emotion').bind('click', function(e) {
            XWB.subjoin.showEmotion(this, $ui.textarea, -20, 30);
            return false;
        });
        
        $ui.textarea.bind('keyup', function() {
            var $area = $(this);
            while ($area.checkText() < 0) {
                var val = $area.val();
                $area.val(val.substring(0, val.length - 1));
            }
            
            $ui.restText.text($area.checkText());
        });
        
        $area.find('a.general-btn').bind('click', function() {
            XWB.comment.sendComment({
                $li: $area,
                $cb: $area.find('input[type="checkbox"]'),
                wbid: XWEIBO_MLOG_ID,
                type: 2,
                callback: cl.commentCallback
            });
        });
        
        $ui.preBtn.click(function() {
            cl.loadData(--cl.curPage);
        });
        
        $ui.nextBtn.click(function() {
            cl.loadData(++cl.curPage);
        });
        
        $ui.commentBtn.click(function() {
            $ui.textarea.focusEnd();
        });
    }
    
    return {
        curPage: 1,
        init: function() {
            cl = commentList;
            //缓存DOM
            $ui.postArea = $('#container div.post-comment-main');
            $ui.textarea = $ui.postArea.find('textarea.comment-textarea');
            $ui.list = $('#container div.comment-list');
            $ui.preBtn = $('#prePageBtn').hide();
            $ui.nextBtn = $('#nextPageBtn').hide();
            $ui.commentBtn = $('#commentBtn');
            $ui.restText = $('.keyin-tips span', $ui.postArea);
            
            eventBind();
            
            this.loadData(this.curPage);
        },
        
        commentCallback: function(data) {
            var $li = cl.addComment(data);
            $li.prependTo($ui.ul);
            $ui.list.find('.feed-comment').hide();
            $ui.textarea.val('');
            $ui.restText.text(140);
            
            var $commentBtn = $('#commentBtn');
            if($commentBtn[0]) {
                var num = $commentBtn.text().match(/\d+/);
                if (num) {
                    $commentBtn.text('评论(' + (++num) + ')');
                }
                else {
                    $commentBtn.text('评论(1)');
                }
            }
        },
        
        addComment: function(data) {
            var 
                delStr = '',
                sinaV = data.sina_v ? 'class="v-icon icon-bg"' : '',
                $ul = $ui.ul,
                url = XWB.url('ta', '', 'id='+data.uid);
                
            if (XWEIBO.wbuid == XWEIBO.uid || data.uid == XWEIBO.uid) {
                delStr = '<a class="del-icon icon-bg" href="javascript:;" style="display:none;">删除</a>';
            }
            
            if(!$ul) {
                $ul = $('<ul></ul>').prependTo($ui.list);
                
                myComment.init(this.commentCallback);
            }
            
            var picSize = 50;
            
            var $li = $('<li></li>')
                .attr({'id': 'c_' + data['id'], 'rel':XWEIBO_MLOG_ID})
                .html([
                    '<div class="user-pic">',
                        '<a href="' + url + '"><img src="' + data['profileImg'] + '" title="' + data['nick'] + '" alt="' + data['nick'] + '的头像" width="'+picSize+'" height="'+picSize+'" /></a>',
                    '</div>',
                    '<div class="comment-c">',
                        '<p class="c-info"><a href="' + url + '" '+sinaV+'>' + data['nick'] + '</a>: '+ data['text'] + '('+ data['create_at'] +') </p>',
                        '<div class="c-for">',
                            '<a class="reply-icon icon-bg" href="javascript:;" rel="'+data['nick']+'">回复</a>',
                            delStr,
                        '</div>',
                    '</div>'
                ].join(''));
            
            $ui.ul = $ul;
            
            return $li;
        },
        
        loadData: function(page) {
            if((page!== UNDEFINED && isNaN(page)) || page < 1) {
                page = 1;
            }else {            
                cl.curPage = page;
            }
            
            apiCall('getComments', {
                data: 'id=' + XWEIBO_MLOG_ID +'&type=2&page='+(page || cl.curPage),
                success: function(msg){
                    if($ui.ul) {
                        $ui.ul.empty();
                    }

                    if (msg.errno == 0) {
                        var frag = document.createDocumentFragment();
                        
                        $.each(msg.rst, function(i, item) {
                            if (isNaN(i)) {return;}
                            var $li = cl.addComment(item);
                            
                            frag.appendChild($li[0]);
                        });
                        
                        $ui.ul && $ui.ul[0].appendChild(frag);
                        
                        //console.log(cl.curPage);
                        var limit = msg.rst.limit || 10;
                        if(msg.rst.total<limit) {
                            $ui.preBtn.hide();
                            $ui.nextBtn.hide();
                        }else {
                            if(cl.curPage <= 1) {
                                $ui.preBtn.hide();
                                $ui.nextBtn.show();
                                cl.curPage = 1;
                            }else  if(cl.curPage >= Math.ceil(msg.rst.total/limit)) {
                                $ui.nextBtn.hide();
                                $ui.preBtn.show();
                                cl.curPage = Math.ceil(msg.rst.total/limit);
                            }else {
                                $ui.preBtn.show();
                                $ui.nextBtn.show();
                            }
                        }                        
                    }
                }
            });
        }
    };
})();

XWB && (XWB.myComment = myComment);
XWB && (XWB.commentList = commentList);

})(jQuery);