/**
 * [OElove] (C)2010-2099 oelove.com  biz
 * Email: service@phpcoo.com ,phpcoo@qq.com
 * This is NOT a freeware, use is subject to license terms
 * $ Last update 2020/11/10 by BO $
*/
$(function () {
    function OEscroll (options) {
        var default_option = {
            time: 5000
        }
        this.option = $.extend({}, default_option, options);
        this.el = typeof this.option.el == 'Object'? this.option.el: $(this.option.el);
        if(this.el.length == 0) {
            return;
        }
        this.wrapper = this.el.find('.scroll');
        this.width = this.option.width;
        this.item = this.wrapper.children();
        this.index = 1;
        this.indicator_ele = this.el.find('.indicator span');
        this.timer = null;

        this.indicator_ele.eq(0).addClass('current');
        if(this.item.length < 2) {
            return;
        }
        
        this.init();
        if(this.option.autoPlay) {
            this.autoPlay();
        }
        this.stop();
        this.showCurrent();
        this.bindNext();
        this.bindPrev();
    }
    OEscroll.prototype = {
        init: function () {
            var last = this.item[this.item.length - 1].cloneNode(true);
            var first = this.item[0].cloneNode(true);
            var width = (this.item.length + 2) * this.width;
            this.wrapper.css({
                'width': width +'px',
                'left': -this.width + 'px',
                'font-size': '0',
                'position': 'relative'
            }).prepend(last).append(first);
            this.item = this.el.find('.group');
            this.item.css({
                'display': 'inline-block',
                'width': this.width + 'px'
            });
        },
        next: function () {
            var _this =  this;
            this.index ++;
            this.wrapper.animate({'left': -this.index*this.width+ 'px'}, 800, 'swing', function () {
                if(_this.index > _this.item.length - 2) {
                    _this.index = 1;
                    _this.wrapper.css('left', -_this.width + 'px');
                }
            });
            this.indicator();
        },
        autoPlay: function () {
            var _this = this;
            this.timer = setInterval(function () {
              _this.next();
            }, this.option.time);
        },
        indicator: function () {
            var index = this.index - 1;
            if(this.index > this.item.length - 2) {
                index = 0;
            }
            this.indicator_ele.eq(index).addClass('bg_e').removeClass('bg_9').siblings().removeClass('bg_e').addClass('bg_9');
        },
        stop: function () {
            var _this = this;
            this.el.on('mouseenter', function () {
                clearInterval(_this.timer);
                _this.timer = null;
            }).on('mouseleave', function () {
                if(_this.option.autoPlay) {
                    _this.autoPlay();
                } 
            });
        },
        showCurrent: function () {
            var _this = this;
            this.indicator_ele.on('mouseenter', function () {
                // if(_this.wrapper.is(':animated')) {
                //     return;
                // }
                var index = $(this).index();
                _this.index = index;
                _this.next();
            });
        },
        bindNext: function () {
            var _this = this;
            this.el.find('.next').on('click', function () {
                if(_this.wrapper.is(':animated')) {
                    return;
                }
                _this.next();
            });
        },
        prev: function () {
            var _this =  this;
            if(this.index <= 1) {
                this.index = _this.item.length - 1;
                _this.wrapper.css('left', -_this.width * this.index + 'px');
            }
            this.index --;
            this.wrapper.animate({'left': -this.index*this.width+ 'px'}, 800, 'swing');
            this.indicator();
        },
        bindPrev: function () {
            var _this = this;
            _this.el.find('.prev').on('click', function () {
                if(_this.wrapper.is(':animated')) {
                    return;
                }
                _this.prev();
            });
        }
    }
    new OEscroll({
        el: $('#face_box'),
        width: window.innerWidth,
        time: 5000
    });

    function Chat () {
        this.showFacePicker();
        this.selectFace();
        this.send();
        this.switchVoice();
        this.loadChatRecord(1);
        this.unlock();
        this.helpUnlock();
    }
    Chat.prototype = {
        showFacePicker: function () {
            $('[f="but_show_face"]').on('click', function () {
                if (!$("#face_box").is(":hidden")) {
                    $("#face_box").hide();
                } else {
                    $("#face_box").show();
                }
            });
        },
        selectFace: function () {
            $('[f="but_select_face"]').on('click', function () {
                var _id = $(this).attr("data-id");
                var tag_em = "{emf_" + _id + "}";
                var myField = document.getElementById("msgchat_content");
                if (document.selection) {
                    sel = document.selection.createRange();
                    sel.text = tag_em;
                } else if (myField.selectionStart || myField.selectionStart == '0') {
                    var startPos = myField.selectionStart;
                    var endPos = myField.selectionEnd;
                    var cursorPos = endPos;
                    myField.value = myField.value.substring(0, startPos)
                        + tag_em
                        + myField.value.substring(endPos, myField.value.length);
                    cursorPos += tag_em.length;
                    myField.selectionStart = cursorPos;
                    myField.selectionEnd = cursorPos;
                } else {
                    myField.value += tag_em;
                }
                $("#face_box").hide();
            });
        },
        send: function () {
            var _this = this;
            $('[f="but_send_msgchat"]').on('click', function () {
                var sid = $(this).attr("data-sid") || '';
                var touid = $(this).attr("data-touid") || '';
                var content = $("#msgchat_content").val();

                if (content == '') {
                    OEUI.message.msg({text: '请输入内容'});
                    return;
                }
        
                $.ajax({
                    type: "GET",
                    url: _ROOT_PATH + "index.php?m=user&c=msgchat",
                    data: {
                        a: "savewrite", touid: touid, content: content
                    },
                    success: function (json) {
                        var res = JSON.parse(json);
                        if (res.response == '1') {
                            //发送成功
                            //载入最新发送记录
                            _this.getFinishSend(res.result);
                            $("#msgchat_content").val("");
                        } else if (res.response == 2) {
                            //次数超额
                            _this.noChatTimesTips(sid);
                        } else {
                            if (res.result > 0) {
                                OEUI.message.msg({text: res.result});
                            } else {
                                OEUI.message.msg({text: '网络繁忙，请稍后再试'});
                            }
                        }
                    },
                    error: function () {
                        OEUI.message.msg({text: '网络繁忙，请稍后再试'});
                    }
                });
            });
        },
        getFinishSend: function (lastid) {
            var _this = this;
            $.ajax({
                type: "GET",
                url: _ROOT_PATH + "index.php?m=user&c=msgchat",
                cache: false,
                data: {
                    a: "getlast", id: lastid
                },
                dataType: "json",
                success: function (data) {
                    var json = eval(data);
                    var response = json.response;
                    var result = json.result;
                    if (response == 1) {
                        if (result.length > 0) {
                            $("#chat_log_data").append(result);
        
                            _this.scrollToFoot();
        
                            var input_lastid = $("#lastid").val();
                            if (typeof (input_lastid) == "undefined") {
                                input_lastid = 0;
                            } else {
                                input_lastid = parseInt(input_lastid);
                            }
                            if (lastid > input_lastid) {
                                $("#lastid").val(lastid);
                            }
                        }
                    }
                },
                error: function () {
        
                }
            });
        },
        scrollToFoot: function () {
            $('#chat_content').animate({scrollTop: $('#chat_content')[0].scrollHeight + 'px'}, 200);
        },
        //发送次数已满提示
        noChatTimesTips: function (sid) {
            if (typeof (sid) == "undefined") {
                sid = "";
            }

            OEUI.modal.info({
                title: '温馨提示',
                text: "对不起，您今天的发信次数已超额<br />可以通过升级VIP解除限制。",
                confirmText: '去升级',
                cancelText: '取消',
                confirm: function () {
                    //点击确定var
                    var _back_url = _ROOT_PATH + "index.php?m=user&c=msgcontact&nofollow=1";
                    window.top.location.href = _ROOT_PATH + "index.php?m=user&c=vip&forward=" + encodeURIComponent(_back_url);
                }
            });
        },
        switchVoice:function () {
            $('[f="but_change_voice"]').on('click', function () {
                OEUI.modal.info({
                    title: '温馨提示',
                    text: '暂不支持语音功能，语音功能请在微信浏览器下使用'
                });
            });
        },
        loadChatRecord: function (page, callBack) {
            var _this = this;
            callBack || (callBack = function () {
            });
            var sid = $("#msgchat_sid").val(); //SID
            var obj_box = $("#chat_log_data");
            $.ajax({
                type: "GET",
                url: _ROOT_PATH + "index.php?m=user&c=msgchat&a=list&datatype=json",
                cache: false,
                data: {sid: sid, page: page},
                dataType: "json",
                success: function (data) {
                    var json = eval(data);
                    var prepage = json.prepage; //上一页
                    var nextpage = json.nextpage; //下一页
                    var result = json.result;
                    if (result.length > 0) {
                        if (page == "1") {
                            obj_box.html(result);
                        } else {
                            obj_box.prepend(result);
                        }
                        if (nextpage > 0) { //还有下一页
                            $("[f='but_get_msgchatpage']").attr("data-page", nextpage);
                            $("[f='but_get_msgchatpage']").show();
                            $("[f='but_get_msgchatpage']").find("img").hide();
                        } else {
                            $("[f='but_get_msgchatpage']").hide();
                        }
        
                        if (page == "1") {
                            _this.scrollToFoot();
        
                            //获取聊天记录最后一条信件ID 9.10.22
                            var lastid = json.lastid;
                            if (typeof (lastid) == "undefined") {
                                lastid = "0";
                            }
                            $("#lastid").val(lastid);
        
                            //时时获取最后一条消息 9.10.22
                            if (MSGCHAT_KEEP == "1") {
                                setTimeout(function () {
                                    _this.getLastList();
                                }, MSGCHAT_TIMER);
                            }
                        }
                    }
                },
                error: function () {
                    OEUI.message.msg({text: '聊天记录加载失败'});
                }
            });
        },
        getLastList: function () {
            var _this = this;
            var sid = $("#msgchat_sid").val(); //SID
            var lastid = $("#lastid").val(); //last
            var obj_box = $("#chat_log_data");
            $.ajax({
                type: "POST",
                url: _ROOT_PATH + "index.php?m=user&c=msgchat",
                cache: false,
                data: {
                    a: "lastlist", sid: sid, lastid: lastid
                },
                dataType: "json",
                success: function (data) {
                    var json = eval(data);
                    var result = json.result;
                    var total = json.total;
                    if (result.length > 0 && total != "0") {
                        obj_box.append(result);
                        _this.scrollToFoot();
        
                        //获取聊天记录最后一条信件ID 9.10.22
                        lastid = json.lastid;
                        if (typeof (lastid) == "undefined") {
                            lastid = "0";
                        }
                        if (lastid != "" && lastid != "0") {
                            $("#lastid").val(lastid);
                        }
        
                        if (MSGCHAT_KEEP == "1") {
                            setTimeout(function () {
                                _this.getLastList();
                            }, MSGCHAT_TIMER);
                        }
                    } else {
        
                        if (MSGCHAT_KEEP == "1") {
                            setTimeout(function () {
                                _this.getLastList();
                            }, MSGCHAT_TIMER);
                        }
                    }
                },
                error: function () {
        
                }
            });
        },
        //解锁
        unlock: function () {
            var _this = this;
            $(document).on("click", "[f='but_freesid_tips']", function () {
                var sid = $(this).attr("data-sid");
                var fee = $(this).attr("data-fee") ||0;
                var moneyname = $(this).attr("data-moneyname");
                var layer_lock = false;
                OEUI.modal.info({
                    title: '温馨提示',
                    text: "你与对方的聊天通道还没打开<br />可以通过以下方式解锁通信<br />1、支付 <font color=\'red\'>" + fee + "</font> " + moneyname + "解锁<br />2、升级VIP会员",
                    confirmText: '立即解锁',
                    cancelText: '升级会员',
                    confirm: function () {
                        //点击解锁
                        if (!layer_lock) {
                            layer_lock = true;
                            _this.payFreeSid(sid);
                        }
                    },
                    cancel: function () {
                        //点击升级.
                        if (!layer_lock) {
                            layer_lock = true;
                            var _back_url = _ROOT_PATH + "index.php?m=user&c=msgcontact&nofollow=1";
                            window.open(_ROOT_PATH + "index.php?m=user&c=vip&forward=" + encodeURIComponent(_back_url),'_blank');
                        }
                    }
                });
            });
        },
        payFreeSid: function (sid) {
            $.ajax({
                type: "GET",
                url: _ROOT_PATH + "index.php?m=user&c=msgchat",
                cache: false,
                data: {
                    a: "freesid", sid: sid, datatype: "json"
                },
                dataType: "json",
                success: function (data) {
                    var json = eval(data);
                    var response = json.response;
                    var result = json.result;
                    if (response == "1") {
                        //余额支付..重新加载聊天记录
                        OEUI.message.msg({text: '解锁成功'});
                        //9.05.10
                        if ($("#help_freelock_box").length > 0) {
                            if ($("#help_freelock_box").css("display") == "block") {
                                $("#help_freelock_box").hide();
                            }
                        }
                        setTimeout(function () {
                            _getMsgchatPageList(1);
                        }, 500);
                    } else if (response == "2") {
                        //在线支付...
                        // var _back_url = _ROOT_PATH + "index.php?m=user&c=msgcontact&nofollow=1";
                        // window.top.location.href = _ROOT_PATH + "index.php?c=pay&paynum=" + result + "&forward=" + encodeURIComponent(_back_url);
                        // window.open(_ROOT_PATH + "index.php?c=pay&paynum=" + result + "&forward=" + encodeURIComponent(_back_url),'_blank');
                        $("#both_guide").show();
                    } else {
                        if (result.length > 0) {
                            OEUI.message.msg({text: result});
                        } else {
                            OEUI.message.msg({text: '解锁失败'});
                        }
                    }
                },
                error: function () {
                    OEUI.message.msg({text: '系统繁忙，请稍后再试'});
                }
            });
        },
        //帮他解锁
        helpUnlock: function () {
            var _this = this;
            $(document).on("click", '[f="but_post_freelock"]', function () {
                var sid = $(this).attr("data-sid");
                _this.payFreeSid(sid);
            });
        }

    }
    new Chat();
});