
(function (fetion) {

    var hismgr = new fetion.History,
        History = fetion.History,
        utils = fetion.utils;

    var doc = $(document),
        pager = $('#fetion_pager'),
        bar = $('#fetion_splitbar'),
        menuContainer = $('#fetion_menu_container'),
        contentContainer = $('#fetion_content_container'),
        splitbar = $('#fetion_splitbar'),
        menu = $('#fetion_menu'),
        content = $('#fetion_content');

    fetion.noConsole();

    // 切换loading
    {
        $('#fetion_loading').hide();
        $('#fetion_wrapper').show();
    }

    // 初始化window事件
    {
        $(window).bind('contextmenu', function () {
            //return false;

        }).bind('resize', function () {
            var wheight = $(window).height(),
                menuHeight = wheight - 85,
                contentHeight = wheight - 85,
                sheight = wheight - 57;

            if (hismgr.nav == History.NAV.CONTACT_CHATLOG ||
                hismgr.nav == History.NAV.DISCUS_CHATLOG ||
                hismgr.nav == History.NAV.GROUP_CHATLOG) {
                contentHeight -= 40;
            }
            menuContainer.css({ 'height': menuHeight + 'px' });
            contentContainer.css({ 'height': contentHeight + 'px' });
            splitbar.css({ 'height': sheight + 'px' });

        }).resize();
    }

    // 初始化分割条
    {
        function barMouseUp() {
            window.releaseEvents(Event.MOUSEMOVE | Event.MOUSEUP);
            bar.unbind('mousemove').unbind('mouseout').unbind('mouseup');

            $(this).css({ 'background-color': '#FFF' });
        }

        function docMouseUp() {
            doc.unbind('mousemove').unbind('mouseup');

            barMouseUp();
        }

        function mouseMove(e) {
            var moveX = e.clientX - 7;
            if (140 < moveX && moveX < 600) {
                menu.css({ 'width': moveX });
                content.css({ 'margin-left': moveX + 7 });
            }
        }

        bar.bind('mousedown', function () {
            // 设置捕获范围
            window.captureEvents(Event.MOUSEMOVE | Event.MOUSEDOWN);

            $(this).css({ 'background-color': '#000' });

            bar.bind('mousemove', mouseMove).bind('mouseout', function () {
                doc.bind('mousemove', mouseMove).bind('mouseup', docMouseUp);

            }).bind('mouseup', barMouseUp);
        });
    }

    $.fn.menuItemSelected = function () {
        if (this.tagName == 'H3') {
            $('#fetion_menu_container .selected').removeClass('selected').next().hide();
        } else {
            $('#fetion_menu_container .selected').removeClass('selected');
        }
        this.addClass('selected');
        return this;
    };

    function getRecentContacts() {
        var current = $(this);

        if (hismgr.myself > 0) {
            current.click();
        } else {
            History.prototype.getRecentContacts.call(hismgr, null, function () {
                current.bind('click', {}, generateContactList).click();
            });
        }
    }

    function generateContactList(e) {
        $(this).unbind('click');

        var gid = e.data.gid;
        var all = [];
        var contacts = _.clone(hismgr.contact.recent);
        var title = '我的最近联系人';
        var tr = '<tr{0}><td>{1}</td><td>{2}</td><td>{3}</td></tr>';

        if (!_.isEmpty(gid)) {
            all = hismgr.contact.group[gid].cs;
            title = hismgr.contact.group[gid].n + '的联系人';

            var filterUids = _.map(all, function (c) {
                return c.uid;
            });

            contacts = _.filter(contacts, function (contact) {
                return $.inArray(contact.uid, filterUids) != -1;
            });
        }

        $('#fetion_content_title').attr('data-uid', hismgr.myself).text(title);
        $('#fetion_content_container').html('<table id="fetion_latest_contact"><tr><td>姓名</td><td>飞信号/手机号</td><td>最好会话时间</td></tr></table>');

        $.each(contacts, function (i, c) {
            var trClass = (i % 2 == 0) ? '' : ' class="tr_spliter"';
            var item = $(String.format(tr, trClass, c.n, c.no, c.dt));

            item.bind('dblclick', { c: c }, generateChatLog)
                .bind('mouseover', function () {
                    $(this).addClass('selected');
                }).bind('mouseover', function () {
                    $(this).removeClass('selected');
                });

            $('#fetion_latest_contact').append(item);
        });

        $(this).menuItemSelected().bind('click', { gid: gid }, generateContactList);
    }

    function generateChatLog(e) {
        var contact = e.data.c;

        History.prototype.getChatLog.call(hismgr, contact, 0, null, function (logObj) {
            var htmlArr = [];

            $.each(logObj, function (date, logs) {
                htmlArr.push('<div class="chatlog clearfix">');
                htmlArr.push('<div class="title"><h3>日期：' + date + '</h3></div>');

                htmlArr.push(_.template('<% _.each(logs, function(log){ %>' +
                '<div class="section clearfix"><p class="info">' +
                '<span class="fl"><%= log.un %></span><span class="fr">' +
                '<a href="javascript:;">回复</a></span><span class="fr">' +
                '<%= log.time %></span></p>' +
                '<p class="msg"><%= log.msg %></p></div>' +
                '<% }); %>', { logs: logs }));
            });

            $('#fetion_content_container').html(htmlArr.join());
        });

        $(this).menuItemSelected();
    }

    function generateGroupList(e) {
        $(this).unbind('click');

        var gid = e.data.gid;

        $(this).menuItemSelected().bind('click', { gid: gid }, generateGroupList);
    }

    // 初始化历史记录分组
    {
        var myselfNode = { name: '我自己' },
            contactNode = { name: '联系人', autoExpand: true, nodes: [] },
            contactGroupNode = { name: '群组', nodes: [] },
            thumbNode = { name: '拇指群', nodes: [] },
            groupNode = { name: '飞信群', nodes: [contactGroupNode, thumbNode] },
            discusNode = { name: '讨论组', nodes: [] },
            smsNode = { name: '短信', nodes: [] },
            otherNode = { name: '其他历史记录', nodes: [] },
            treeData = { nodes: [myselfNode, contactNode, groupNode, discusNode, smsNode, otherNode] };

        contactNode.onclick = getRecentContacts;
        menuContainer.yinker(treeData);

        getRecentContacts();

        // 获取联系人分组
        History.prototype.getContactGroups.call(hismgr, null, function () {

            // 获取所有联系人
            History.prototype.getAllContacts.call(hismgr, null, function () {
                var groups = this.group;

                // 填充各个分组中的联系人
                for (var id in groups) {
                    var group = groups[id],
                        contacts = group.cs,
                        node = {
                            name: group.n,
                            nodes: []
                        };

                    for (var i = 0, len = contacts.length; i < len; i++) {
                        var contact = contacts[i];

                        node.nodes.push({
                            name: contact.n
                        });
                    }

                    contactNode.nodes.push(node);
                }

                contactNode.op = 'update';
                menuContainer.yinker(contactNode);
            });
        });

        // 获取最近联系群
        History.prototype.getRecentGroups.call(hismgr, null, function () {
        });

        // 获取群
        History.prototype.getGroups.call(hismgr, null, function () {
            var usualGroups = this.group.usual,
                discusGroups = this.discus;

            for (var i = 0, len1 = usualGroups.length; i < len1; i++) {
                var group = usualGroups[i];

                contactGroupNode.nodes.push({
                    name: group.n
                });
            }
            contactGroupNode.op = 'update';
            menuContainer.yinker(contactGroupNode);

            for (var j = 0, len2 = discusGroups.length; j < len2; j++) {
                var discus = discusGroups[j];

                discusNode.nodes.push({
                    name: discus.n
                });
            }
            discusNode.op = 'update';
            menuContainer.yinker(discusNode);
        });

        // 获取讨论组
        History.prototype.getDiscus.call(hismgr, null, function () {
        });

        // 获取短信
        History.prototype.getSms.call(hismgr, null, function () {
        });

        // 获取其他记录
        History.prototype.getOthers.call(hismgr, null, function () {
        });

    }

    // 初始化左侧导航树
    {
        menuContainer.find('h3').bind('dblclick', function () {
            $(this).menuItemSelected().next().toggle();
        });

        $('#mi_self').bind('click', function () {
            History.prototype.getChatLog.call(hismgr, hismgr.myself, null, function (contacts) {
                // TODO:view
            });
        });

        // 获取最近联系人列表
        $('#mi_contact').bind('click', function () {
            History.prototype.getRecentContacts.call(hismgr, null, function () {
                var myself = this.myself,
                    contacts = this.contact.recent;
                var trHeader = '<tr><td>姓名</td><td>飞信号/手机号</td><td>最好会话时间</td></tr>',
                    tr = '<tr{0}><td>{1}</td><td>{2}</td><td>{3}</td></tr>';

                $('#fetion_content_title').attr('data-uid', myself).text('我的最近联系人');
                $('#fetion_content_container').html('<table id="fetion_latest_contact"><tr><td>loading...</td></tr></table>');
                $('#fetion_latest_contact').html(trHeader);

                $.each(contacts, function (i, c) {
                    var trClass = (i % 2 == 0) ? '' : ' class="tr_spliter"';
                    var item = $(String.format(tr, trClass, c.n, c.no, c.dt));

                    item.bind('dblclick', { c: c }, generateChatLog)
                        .bind('mouseover', function () {
                            $(this).addClass('selected');
                        }).bind('mouseover', function () {
                            $(this).removeClass('selected');
                        });

                    $('#fetion_latest_contact').append(item);
                });
            });

            $(this).unbind('click').bind('click', {}, generateContactList);

        }).click();

        $('#mi_group').bind('click', function () {


        });

        $('#mi_discus').bind('click', function () {

        });

        $('#mi_sms').bind('click', function () {

        });

        $('#mi_other').bind('click', function () {

        });
    }


})(this.fetion);
