/*
 @Name: layui WebIM 1.0.0
 @Author:贤心
 @Date: 2014-04-25
 @Blog: http://sentsin.com
 */
;!function(win, undefined){
var config = {
    msgurl: 'mailbox.html?msg=',
    chatlogurl: 'mailbox.html?user=',
    aniTime: 200,
    right: -232,
    api: {
        friend: 'js/plugins/layer/layim/data/friend.json', //好友列表接口
        group: 'js/plugins/layer/layim/data/group.json', //群组列表接口
        chatlog: 'js/plugins/layer/layim/data/chatlog.json', //聊天记录接口
        groups: 'js/plugins/layer/layim/data/groups.json', //群组成员接口
        sendurl: '' //发送消息接口
    },
    user: { //当前用户信息
        name: '游客',
        face: 'img/a1.jpg'
    },
    //自动回复内置文案,也可动态读取数据库配置
    autoReplay: [
        '您好,我现在有事不在,一会再和您联系。',
        '你没发错吧?',
        '洗澡中,请勿打扰,偷窥请购票,个体四十,团体八折,订票电话:一般人我不告诉他!',
        '你好,我是主人的美女秘书,有什么事就跟我说吧,等他回来我会转告他的。',
        '我正在拉磨,没法招呼您,因为我们家毛驴去动物保护协会把我告了,说我剥夺它休产假的权利。',
        '<(@ ̄︶ ̄@)>',
        '你要和我说话?你真的要和我说话?你确定自己想说吗?你一定非说不可吗?那你说吧,这是自动回复。',
        '主人正在开机自检,键盘鼠标看好机会出去凉快去了,我是他的电冰箱,我打字比较慢,你慢慢说,别急……',
        '(*^__^*) 嘻嘻,是贤心吗?'
    ],
    chating: {},
    hosts: (function(){
        var dk = location.href.match(/\:\d+/);
        dk = dk ? dk[0] : '';
        return 'http://' + document.domain + dk + '/';
    })(),
    json: function(url, data, callback, error){
        return $.ajax({
            type: 'POST',
            url: url,
            data: data,
            dataType: 'json',
            success: callback,
            error: error
        });
    },
    stopMP: function(e){
        e ? e.stopPropagation() : e.cancelBubble = true;
    }
}, dom = [$(window), $(document), $('html'), $('body')], xxim = {};
//主界面tab
xxim.tabs = function(index){
    var node = xxim.node;
    node.tabs.eq(index).addClass('xxim_tabnow').siblings().removeClass('xxim_tabnow');
    node.list.eq(index).show().siblings('.xxim_list').hide();
    if(node.list.eq(index).find('li').length === 0){
        xxim.getDates(index);
    }
};
//节点
xxim.renode = function(){
    var node = xxim.node = {
        tabs: $('#xxim_tabs>span'),
        list: $('.xxim_list'),
        online: $('.xxim_online'),
        setonline: $('.xxim_setonline'),
        onlinetex: $('#xxim_onlinetex'),
        xximon: $('#xxim_on'),
        layimFooter: $('#xxim_bottom'),
        xximHide: $('#xxim_hide'),
        xximSearch: $('#xxim_searchkey'),
        searchMian: $('#xxim_searchmain'),
        closeSearch: $('#xxim_closesearch'),
        layimMin: $('#layim_min')
    };
};
//主界面缩放
xxim.expend = function(){
    var node = xxim.node;
    if(xxim.layimNode.attr('state') !== '1'){
        xxim.layimNode.stop().animate({right: config.right}, config.aniTime, function(){
            node.xximon.addClass('xxim_off');
            try{
                localStorage.layimState = 1;
            }catch(e){}
            xxim.layimNode.attr({state: 1});
            node.layimFooter.addClass('xxim_expend').stop().animate({marginLeft: config.right}, config.aniTime/2);
            node.xximHide.addClass('xxim_show');
        });
    } else {
        xxim.layimNode.stop().animate({right: 1}, config.aniTime, function(){
            node.xximon.removeClass('xxim_off');
            try{
                localStorage.layimState = 2;
            }catch(e){}
            xxim.layimNode.removeAttr('state');
            node.layimFooter.removeClass('xxim_expend');
            node.xximHide.removeClass('xxim_show');
        });
        node.layimFooter.stop().animate({marginLeft: 0}, config.aniTime);
    }
};
//初始化窗口格局
xxim.layinit = function(){
    var node = xxim.node;
    //主界面
    try{
        /*
        if(!localStorage.layimState){
            config.aniTime = 0;
            localStorage.layimState = 1;
        }
        */
        if(localStorage.layimState === '1'){
            xxim.layimNode.attr({state: 1}).css({right: config.right});
            node.xximon.addClass('xxim_off');
            node.layimFooter.addClass('xxim_expend').css({marginLeft: config.right});
            node.xximHide.addClass('xxim_show');
        }
    }catch(e){
        //layer.msg(e.message, 5, -1);
    }
};
//聊天窗口
xxim.popchat = function(param){
    var node = xxim.node, log = {};
    log.success = function(layero){
        layer.setMove();
        xxim.chatbox = layero.find('#layim_chatbox');
        log.chatlist = xxim.chatbox.find('.layim_chatmore>ul');
        log.chatlist.html('
'+ param.name +'×')
        xxim.tabchat(param, xxim.chatbox);
        //最小化聊天窗
        xxim.chatbox.find('.layer_setmin').on('click', function(){
            var indexs = layero.attr('times');
            layero.hide();
            node.layimMin.text(xxim.nowchat.name).show();
        });
        //关闭窗口
        xxim.chatbox.find('.layim_close').on('click', function(){
            var indexs = layero.attr('times');
            layer.close(indexs);
            xxim.chatbox = null;
            config.chating = {};
            config.chatings = 0;
        });
        //关闭某个聊天
        log.chatlist.on('mouseenter', 'li', function(){
            $(this).find('em').show();
        }).on('mouseleave', 'li', function(){
            $(this).find('em').hide();
        });
        log.chatlist.on('click', 'li em', function(e){
            var parents = $(this).parent(), dataType = parents.attr('type');
            var dataId = parents.attr('data-id'), index = parents.index();
            var chatlist = log.chatlist.find('li'), indexs;
            config.stopMP(e);
            delete config.chating[dataType + dataId];
            config.chatings--;
            parents.remove();
            $('#layim_area'+ dataType + dataId).remove();
            if(dataType === 'group'){
                $('#layim_group'+ dataType + dataId).remove();
            }
            if(parents.hasClass('layim_chatnow')){
                if(index === config.chatings){
                    indexs = index - 1;
                } else {
                    indexs = index + 1;
                }
                xxim.tabchat(config.chating[chatlist.eq(indexs).attr('type') + chatlist.eq(indexs).attr('data-id')]);
            }
            if(log.chatlist.find('li').length === 1){
                log.chatlist.parent().hide();
            }
        });
        //聊天选项卡
        log.chatlist.on('click', 'li', function(){
            var othis = $(this), dataType = othis.attr('type'), dataId = othis.attr('data-id');
            xxim.tabchat(config.chating[dataType + dataId]);
        });
        //发送热键切换
        log.sendType = $('#layim_sendtype'), log.sendTypes = log.sendType.find('span');
        $('#layim_enter').on('click', function(e){
            config.stopMP(e);
            log.sendType.show();
        });
        log.sendTypes.on('click', function(){
            log.sendTypes.find('i').text('')
            $(this).find('i').text('√');
        });
        xxim.transmit();
    };
    log.html = ''
            +'
'
            +''
            +'     '
            +'    '+ param.name +''
            +'    '
            +'        —'
            +'        ×'
            +'    '
            +'
'
            +'    '+ param.name +''
            +'    '
            +'        —'
            +'        ×'
            +'    '
            +'
'
            +'
'
            +'
'
            +'
'
            +'    
'
            +'    
'
            +'    
'
            +'    
'
            +'        
发送
'
            +'        
'
            +'            √按Enter键发送'
            +'            按Ctrl+Enter键发送'
            +'        
'
            +'    
'
            +'
'
            +'
 '+ datas.data[ii].name +'';
                }
            } else {
                str = '没有群员';
            }
        } else {
            str = ''+ datas.msg +'';
        }
        groupss.removeClass('loading');
        groupss.html(str);
    }, function(){
        groupss.removeClass('loading');
        groupss.html('请求异常');
    });
};
//消息传输
xxim.transmit = function(){
    var node = xxim.node, log = {};
    node.sendbtn = $('#layim_sendbtn');
    node.imwrite = $('#layim_write');
    //发送
    log.send = function(){
        var data = {
            content: node.imwrite.val(),
            id: xxim.nowchat.id,
            sign_key: '', //密匙
            _: +new Date
        };
        if(data.content.replace(/\s/g, '') === ''){
            layer.tips('说点啥呗!', '#layim_write', 2);
            node.imwrite.focus();
        } else {
            //此处皆为模拟
            var keys = xxim.nowchat.type + xxim.nowchat.id;
            //聊天模版
            log.html = function(param, type){
                return ''
                    +'
'+ datas.data[ii].name +'';
                }
            } else {
                str = '没有群员';
            }
        } else {
            str = ''+ datas.msg +'';
        }
        groupss.removeClass('loading');
        groupss.html(str);
    }, function(){
        groupss.removeClass('loading');
        groupss.html('请求异常');
    });
};
//消息传输
xxim.transmit = function(){
    var node = xxim.node, log = {};
    node.sendbtn = $('#layim_sendbtn');
    node.imwrite = $('#layim_write');
    //发送
    log.send = function(){
        var data = {
            content: node.imwrite.val(),
            id: xxim.nowchat.id,
            sign_key: '', //密匙
            _: +new Date
        };
        if(data.content.replace(/\s/g, '') === ''){
            layer.tips('说点啥呗!', '#layim_write', 2);
            node.imwrite.focus();
        } else {
            //此处皆为模拟
            var keys = xxim.nowchat.type + xxim.nowchat.id;
            //聊天模版
            log.html = function(param, type){
                return ''
                    +''
                        + function(){
                            if(type === 'me'){
                                return '
'+ param.time +''
                                       +'
'+ param.name +''
                                       +'

';
                            } else {
                                return '

'
                                       +'
'+ param.name +''
                                       +'
'+ param.time +'';
                            }
                        }()
                    +'
'+ param.content +'
'
                +'';
            };
            log.imarea = xxim.chatbox.find('#layim_area'+ keys);
            log.imarea.append(log.html({
                time: '2014-04-26 0:37',
                name: config.user.name,
                face: config.user.face,
                content: data.content
            }, 'me'));
            node.imwrite.val('').focus();
            log.imarea.scrollTop(log.imarea[0].scrollHeight);
            setTimeout(function(){
                log.imarea.append(log.html({
                    time: '2014-04-26 0:38',
                    name: xxim.nowchat.name,
                    face: xxim.nowchat.face,
                    content: config.autoReplay[(Math.random()*config.autoReplay.length) | 0]
                }));
                log.imarea.scrollTop(log.imarea[0].scrollHeight);
            }, 500);
            /*
            that.json(config.api.sendurl, data, function(datas){
            });
            */
        }
    };
    node.sendbtn.on('click', log.send);
    node.imwrite.keyup(function(e){
        if(e.keyCode === 13){
            log.send();
        }
    });
};
//事件
xxim.event = function(){
    var node = xxim.node;
    //主界面tab
    node.tabs.eq(0).addClass('xxim_tabnow');
    node.tabs.on('click', function(){
        var othis = $(this), index = othis.index();
        xxim.tabs(index);
    });
    //列表展收
    node.list.on('click', 'h5', function(){
        var othis = $(this), chat = othis.siblings('.xxim_chatlist'), parentss = othis.find("i");
        if(parentss.hasClass('fa-caret-down')){
            chat.hide();
            parentss.attr('class','fa fa-caret-right');
        } else {
            chat.show();
            parentss.attr('class','fa fa-caret-down');
        }
    });
    //设置在线隐身
    node.online.on('click', function(e){
        config.stopMP(e);
        node.setonline.show();
    });
    node.setonline.find('span').on('click', function(e){
        var index = $(this).index();
        config.stopMP(e);
        if(index === 0){
            node.onlinetex.html('在线');
            node.online.removeClass('xxim_offline');
        } else if(index === 1) {
            node.onlinetex.html('隐身');
            node.online.addClass('xxim_offline');
        }
        node.setonline.hide();
    });
    node.xximon.on('click', xxim.expend);
    node.xximHide.on('click', xxim.expend);
    //搜索
    node.xximSearch.keyup(function(){
        var val = $(this).val().replace(/\s/g, '');
        if(val !== ''){
            node.searchMian.show();
            node.closeSearch.show();
            //此处的搜索ajax参考xxim.getDates
            node.list.eq(3).html('没有符合条件的结果');
        } else {
            node.searchMian.hide();
            node.closeSearch.hide();
        }
    });
    node.closeSearch.on('click', function(){
        $(this).hide();
        node.searchMian.hide();
        node.xximSearch.val('').focus();
    });
    //弹出聊天窗
    config.chatings = 0;
    node.list.on('click', '.xxim_childnode', function(){
        var othis = $(this);
        xxim.popchatbox(othis);
    });
    //点击最小化栏
    node.layimMin.on('click', function(){
        $(this).hide();
        $('#layim_chatbox').parents('.xubox_layer').show();
    });
    //document事件
    dom[1].on('click', function(){
        node.setonline.hide();
        $('#layim_sendtype').hide();
    });
};
//请求列表数据
xxim.getDates = function(index){
    var api = [config.api.friend, config.api.group, config.api.chatlog],
        node = xxim.node, myf = node.list.eq(index);
    myf.addClass('loading');
    config.json(api[index], {}, function(datas){
        if(datas.status === 1){
            var i = 0, myflen = datas.data.length, str = '', item;
            if(myflen > 1){
                if(index !== 2){
                    for(; i < myflen; i++){
                        str += ''
                            +''+ datas.data[i].name +'('+ datas.data[i].nums +')
'
                            +'';
                        item = datas.data[i].item;
                        for(var j = 0; j < item.length; j++){
                            str += ' '+ item[j].name +' '+ item[j].name +'
';
                        }
                        str += '
';
                    }
                } else {
                    str += ''
                        +'';
                    for(; i < myflen; i++){
                        str += ' '+ datas.data[i].name +''+ datas.data[i].time +' '+ datas.data[i].name +''+ datas.data[i].time +'
';
                    }
                    str += '
';
                }
                myf.html(str);
            } else {
                myf.html('没有任何数据');
            }
            myf.removeClass('loading');
        } else {
            myf.html(''+ datas.msg +'');
        }
    }, function(){
        myf.html('请求失败');
        myf.removeClass('loading');
    });
};
//渲染骨架
xxim.view = (function(){
    var xximNode = xxim.layimNode = $(''
            +'
'
            +'  
×
'
            +'  
'
            +'  
'
            +'  
'
            +'  
'
            +'  
'
            +'
'
            +'
'
            +'- '
                +'在线'
                +''
                    +'在线'
                    +'隐身'
                +' '
            +'
'
            +''
            +'
- '
                +''
                +''
                +' '
            +'
'
            +''
            +''
            +''
        +'
'
    +'