;(function (exports) {
    var doc = exports.document,
        a = {},
        expose = +new Date(),
        rExtractUri = /((?:http|https|file):\/\/.*?\/[^:]+)(?::\d+)?:\d+/,
        isLtIE8 = ('' + doc.querySelector).indexOf('[native code]') === -1;
    exports.getCurrAbsPath = function () {
        // FF,Chrome
        if (doc.currentScript) {
            return doc.currentScript.src;
        }
        var stack;
        try {
            a.b();
        } catch (e) {
            stack = e.fileName || e.sourceURL || e.stack || e.stacktrace;
        }
        // IE10
        if (stack) {
            var absPath = rExtractUri.exec(stack)[1];
            if (absPath) {
                return absPath;
            }
        }
        // IE5-9
        for (var scripts = doc.scripts,
                 i = scripts.length - 1,
                 script; script = scripts[i--];) {
            if (script.className !== expose && script.readyState === 'interactive') {
                script.className = expose;
                // if less than ie 8, must get abs path by getAttribute(src, 4)
                return isLtIE8 ? script.getAttribute('src', 4) : script.src;
            }
        }
    };
}(window));

;!function (win) {
    "use strict";
    var miniChat = function () {
            ajaxSend("code=" + getCodes());
        },
        currentHost,
        urldata
        , ajaxSend = function (params) {
            var url = currentHost + "/api.php/Cation/getcation.html";
            var xmlhttp;
            if (window.XMLHttpRequest) {
                xmlhttp = new XMLHttpRequest();
            } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    var data = eval("(" + xmlhttp.responseText + ")");
                    if (data.code == 200) {
                        showPage(data.data);
                    }
                }
            }
            xmlhttp.open("POST", url, true);
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
            xmlhttp.send(params);
        }, getCodes = function () {
            var curpath = getCurrAbsPath();
            currentHost = /^http(s)?:\/\/(.*?)\//.exec(curpath)[0];
            return /js\?(.*)/.exec(curpath)[1];
        }, showPage = function (data) {
            console.log(data);
            var headTag = document.getElementsByTagName('head')[0];
            var css = document.createElement('link');
            css.type = 'text/css';
            css.rel = 'stylesheet';
            css.href = currentHost + '/chat/css/chat.css';
            headTag.appendChild(css);
            urldata = data;
            /*var box = document.getElementById('IM_chat-box');
            if(!box) {
                var div = document.createElement('div');
                var chat_lists = '<div class="IM_chat-lists">';
                for (var i = 0; i < urldata.urls.length; i++) {
                    chat_lists += '<p class="IM_chat-item" onclick="say(this,'+urldata.style+');" minitour="'+urldata.urls[i].minitour+'" tour="'+urldata.urls[i].tour+'">'+urldata.urls[i].name+'</p>';
                }
                chat_lists += '</div>';
                div.id = "IM_chat-lists";
                div.className += 'IM_chat-form';
                document.body.appendChild(div);
                document.getElementById('IM_chat-lists').innerHTML = '<i class="chat-icon"></i>' + chat_lists;
            }*/
            isMobile() ? consultMobile(data) : consultPc(data);

            if (data.invite) {
                // 离线弹窗开启 或 在线状态 弹窗
                if (data.invite.isOfflineOpen == 1 || data.invite.online == 1) {
                    // 页面加载后多久弹窗
                    setTimeout(function () {
                        isMobile() ? showInviteMobile(data, urldata) : showInvite(data, urldata)
                    }, data.invite.startTime * 1000)
                }
            }

        };

    win.miniChat = new miniChat();
}(window);

function showInviteMobile(d, dataurl) {

    if (!document.getElementById('IM_chat-invite-mobile')) {
        var div = document.createElement('div');
        div.id = 'IM_chat-invite-mobile';
        div.className = d.invite.location == 2 ? 'IM-chat-invite-m-bottom' : 'IM-chat-invite-m-middle';
        div.innerHTML = '<iframe id="IM_chat-invite-iframe" src="' + d.invite.murl + '"></iframe>';
        document.body.appendChild(div);

        window.addEventListener('message', function (e) {
            switch (e.data.act) {
                case 'IM_CHILD_MESSAGE_1':
                    document.getElementById('IM_chat-invite-mobile').style.display = 'none';
                    break;
                case 'IM_CHILD_MESSAGE_2':
                    document.getElementById('IM_chat-invite-mobile').style.display = 'none';
                    var pNodes = document.getElementById('IM_sidebar_m').getElementsByTagName('a');
                    var firstNodes = '';
                    pNodes[0].click();
                    /*for( var i = 0 ; i < pNodes.length ; i++ ){
                        //console.log( pNodes[i].className )
                        if( pNodes[i].className == 'IM_chat-item'){
                            pNodes[i].click()
                            break;
                        }
                    }*/
                    break;
            }

        }, false)

    }
}

function showInvite(d, dataurl) {
    var closeTime = 0;
    var nextTimer;
    var styles = {
        1: 'IM_chat-invite-lt',
        2: 'IM_chat-invite-mt',
        3: 'IM_chat-invite-rt',
        4: 'IM_chat-invite-lm',
        5: 'IM_chat-invite-mm',
        6: 'IM_chat-invite-rm',
        7: 'IM_chat-invite-lb',
        8: 'IM_chat-invite-mb',
        9: 'IM_chat-invite-rb',
    }
    if (!document.getElementById('IM_chat-invite')) {
        var div = document.createElement('div');
        div.id = 'IM_chat-invite';
        div.className = styles[d.invite.location];
        div.innerHTML = '<iframe id="IM_chat-invite-iframe" src="' + d.invite.url + '"></iframe>';
        document.body.appendChild(div);

        var _invite = document.getElementById('IM_chat-invite');

        if (d.invite.locationOffsetX) {
            _invite.style.left = _invite.offsetLeft + parseInt(d.invite.locationOffsetX) + 'px';
        }

        if (d.invite.locationOffsetY) {
            _invite.style.top = _invite.offsetTop + parseInt(d.invite.locationOffsetY) + 'px';
        }

        window.addEventListener('message', function (e) {
            switch (e.data.act) {
                case 'IM_CHILD_MESSAGE_1':
                    document.getElementById('IM_chat-invite').style.display = 'none';
                    if (d.invite.nextTime > 0 && closeTime <= d.invite.closeTime) {
                        closeTime++;
                        nextTimer && clearTimeout(nextTimer);
                        nextTimer = setTimeout(function () {
                            document.getElementById('IM_chat-invite').style.display = 'block';
                        }, d.invite.nextTime * 1000)
                    }
                    break;
                case 'IM_CHILD_MESSAGE_2':
                    document.getElementById('IM_chat-invite').style.display = 'none' ;
                    var pNodes = document.getElementById('IM_sidebar').getElementsByTagName('a');
                    var firstNodes = '' ;
                    for( var i = 0 ; i < pNodes.length ; i++ ){
                        //console.log( pNodes[i].className )
                        if( pNodes[i].className == 'IM_sidebar_item'){
                            pNodes[i].click()
                            break;
                        }
                    }
                    break;
            }

        }, false)
    }

}

function say(ev, style) {
    var web = encodeURI(ev.getAttribute("tour"));
    var moblieweb = encodeURI(ev.getAttribute("minitour"));
    if (style == 1) {
        window.open(web);
    } else {
        if (isMobile()) {
            window.open(moblieweb);
        } else {
            var talk = document.getElementById('IM_chat-talk');
            if (!talk) {
                var div = document.createElement('div');
                div.id = "IM_chat-talk";
                document.body.appendChild(div);
                div.innerHTML = '<i class="IM_chat-jiao" id="jiao"></i><iframe id="IM_chat-iframe" src="' + moblieweb + '"></iframe>';
                document.getElementById('jiao').addEventListener('click', function (ev) {
                    jiao();
                });
            } else {
                talk.parentNode.removeChild(talk);
                say(ev, style);
            }
        }
    }
}

function isMobile() {
    return navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
}

function jiao() {
    document.getElementById('IM_chat-talk').style = "display:none";
}

function consultMobile(data){

    var sidebar = document.getElementById('IM_sidebar_m') ;

    if( !sidebar ){
        var div = document.createElement('div');
        div.id = "IM_sidebar_m";
        // 填充内容
        var li1 = '<li><a onclick="say(this,'+data.style+');" minitour="'+data.urls[0].minitour+'" tour="'+data.urls[0].tour+'" href="javascript:;"><img src="/static/common/images/sidebar/icon_zixun_1.png"/> <span>'+data.urls[0].name+'</span></a></li>';
        var li2 = [],li3 = [],li4 = [] ;
        var otherLink = '' ;

        if( data.sidebar.list && data.sidebar.list.length > 0){

            var list = data.sidebar.list ;
            for( var i = 0 ; i < list.length ; i++ ){
                if( list[i].mobile != 1 )
                    continue ;

                if( list[i].type == 0 ){
                    otherLink +='<li><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin='+list[i].id+'&site=qq&menu=yes"><img src="/static/common/images/sidebar/icon_qq.png"/><span>'+list[i].name+'</span></a></li>';
                    continue ;
                }

                if( list[i].type == 1 ){
                    otherLink +='<li><a target="_blank" href="//amos.alicdn.com/msg.aw?v=2&uid='+list[i].id+'&site=cnalichn&s=11&charset=utf-8"><img src="/static/common/images/sidebar/icon_wangwang.png"/><span>'+list[i].name+'</span></a></li>';
                    continue ;
                }

                if( list[i].type == 2 ){
                    otherLink +='<li><a target="_blank" href="'+list[i].id+'"><img src="/static/common/images/sidebar/icon_link.png"/><span>'+list[i].name+'</span></a></li>';
                    continue;
                }
            }
        }
        var className = data.sidebar.location == 1 ? 'top' : 'bottom' ;
        div.className = className ;

        var qr = '' ;

        if( data.sidebar.qr && data.sidebar.qrMobile == 1 ){
            data.sidebar.qrMobileText = data.sidebar.qrMobileText || '扫码';
            qr = '<li><a href="javascript:;" onclick="toggleQr()">' +
                '<img src="/static/common/images/sidebar/icon_qr.png"/><span>'+data.sidebar.qrMobileText+'</span>' +
                '</a>' +
                '<div class="qrImages"><div><img src="'+data.sidebar.qr+'" /><div class="jt"></div></div></div>'+
                '</li>'
        }

        document.body.appendChild(div);
        document.getElementById('IM_sidebar_m').innerHTML = '<ul>'+
            li1+
            otherLink+
            qr+
            '</ul>';
    }
}

function toggleQr(){
    var nodes = document.getElementById('IM_sidebar_m').getElementsByClassName('qrImages') ;
    if( nodes.length > 0 ){

        if( nodes[0].style.display == 'none' || !nodes[0].style.display ){
            nodes[0].style.display = 'block';
        }else{
            nodes[0].style.display = 'none';
        }
    }
}

// 悬浮窗收缩
function sidebarSwitch(obj,zoom){

    if( !zoom ) return false ;

    var sidebar = document.getElementById('IM_sidebar') ;
    var sidebarSwitchNodes = sidebar.getElementsByTagName('div');
    var sidebarSwitch ;
    for( var i = 0; i < sidebarSwitchNodes.length ; i++ ){
        if( sidebarSwitchNodes[i].className.indexOf('IM_sidebar_title') != -1 ){
            sidebarSwitch = sidebarSwitchNodes[i] ;
            break;
        }
    }

    var classList = sidebarSwitch.className ;
    var field = classList.indexOf('right') == -1 ? 'left' : 'right' ;
    if( !sidebar.style[field] || sidebar.style[field] == '0px'){
        sidebar.style[field]='-122px';
        sidebarSwitch.className = classList.replace(field+'_on',field+'_off')

    }else{
        sidebar.style[field]='0px';
        sidebarSwitch.className = classList.replace(field+'_off',field+'_on')
    }
}

// 判断是否ie8
function IEVersion() {
    var userAgent = navigator.userAgent;
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1;
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE;
    var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf("rv:11.0") > -1;
    if(isIE) {
        var reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        var fIEVersion = parseFloat(RegExp["$1"]);
        if(fIEVersion == 7) {
            return 7;
        } else if(fIEVersion == 8) {
            return 8;
        } else if(fIEVersion == 9) {
            return 9;
        } else if(fIEVersion == 10) {
            return 10;
        } else {
            return 6;//IE版本<=7
        }
    } else if(isEdge) {
        return 100;//'edge';//edge
    } else if(isIE11) {
        return 11; //IE11
    }else{
        return -1;//不是ie浏览器
    }
}


function contains(parentNode, childNode) {
    if (parentNode.contains) {
        return parentNode != childNode && parentNode.contains(childNode);
    } else {
        return !!(parentNode.compareDocumentPosition(childNode) & 16);
    }
}

// 兼容IE
function checkHover(e,target){
    var E = e||window.event;
    if(E.type != 'mouseover' && E.type != 'mouseout'){
        return false;
    }
    if (E.type=="mouseover")  {
        return !contains(target,E.relatedTarget||E.fromElement) && !((E.relatedTarget||E.fromElement)===target);
    } else {
        return !contains(target,E.relatedTarget||E.toElement) && !((E.relatedTarget||E.toElement)===target);
    }
}

function consultPc(data){
    // 新的悬浮
    var sidebar = document.getElementById('IM_sidebar') ;
    if( !sidebar ){
        var div = document.createElement('div');
        var lists = '<ul class="IM_sidebar_list">';
        // 默认咨询
        for (var i = 0; i < data.urls.length; i++) {
            lists += '<li><a class="IM_sidebar_item" onclick="say(this,'+data.style+');"minitour="'+data.urls[i].minitour+'" tour="'+data.urls[i].tour+'" href="javascript:;">' +
            '<img class="myIcon" src="/static/common/images/sidebar/icon_zixun.png"/>' +
            '<span>'+data.urls[i].name+'</span>' +
            '</a></li>';
        }
        // 插件咨询
        if( data.sidebar.list && data.sidebar.list.length > 0 ){
            var sidebarList = data.sidebar.list ;
            for( var i = 0 ; i < sidebarList.length ; i++ ){
                if( sidebarList[i].type == 0 ){
                    lists +='<li><a target="_blank" href="http://wpa.qq.com/msgrd?v=3&uin='+data.sidebar.list[i].id+'&site=qq&menu=yes">' +
                    '<img src="http://wpa.qq.com/pa?p=1:'+data.sidebar.list[i].id+':4"/>'+
                    '<span class="overline">'+data.sidebar.list[i].name+'</span>' +
                    '</a></li>';
                }else if( sidebarList[i].type == 1 ){
                    lists +='<li><a target="_blank" href="//amos.alicdn.com/msg.aw?v=2&uid='+data.sidebar.list[i].id+'&site=cnalichn&s=11&charset=utf-8">' +
                    '<img class="ali" src="http://amos.im.alisoft.com/online.aw?v=2&uid='+data.sidebar.list[i].id+'&site=cntaobao&s=2&charset=utf-8"/>'+
                    '<span class="overline">'+data.sidebar.list[i].name+'</span>' +
                    '</a></li>';
                }else if( sidebarList[i].type == 2 ){
                    lists +='<li><a target="_blank" href="'+data.sidebar.list[i].id+'">' +
                        '<img class="myIcon" src="/static/common/images/sidebar/icon_link.png"/>'+
                        '<span class="overline">'+data.sidebar.list[i].name+'</span>' +
                        '</a></li>';
                }
            }
        }
        lists += '</ul>';
        var sidebarLocation = { 1:'lt', 2:'lm', 3:'rt', 4:'rm' } ;
        div.id = "IM_sidebar";
        data.sidebar.location = ( data.sidebar.location && data.sidebar.location in sidebarLocation ) ?
            data.sidebar.location : 4 ;
        div.className= sidebarLocation[data.sidebar.location] ;
        // ⽅向
        var directionField = data.sidebar.location > 2 ? "right" : "left" ;
        var directionTitleClass = ( data.sidebar.defaultZoom || isMobile() ) ? directionField + '_off' :
            directionField + '_on' ;
        var sidebarBottom = '' ;
        var switchHtml = '' ;
        var switchObj = '' ;
        // ⼿机端强⾏⽣效
        if( data.sidebar.isZoom || isMobile() ) {
            switchObj = document.createElement('div');
            // 默认缩着
            if( data.sidebar.defaultZoom || data.sidebar.autoZoom || isMobile() ){
                div.style[directionField]='-122px';
            }
            switchObj.className = 'IM_sidebar_title '+directionField +' '+directionTitleClass ;
            if( !data.sidebar.autoZoom && !isMobile() ){
                switchObj.setAttribute('onclick','sidebarSwitch(this,'+data.sidebar.isZoom+')');
            }
            switchHtml = switchObj.outerHTML;
        }
        var img = '<div class="IM_images">' +
            '<img src="'+data.sidebar.avatar+'"/>' +
            '</div>';
        var qr = data.sidebar.qr
            ? '<div class="IM_qr">' +
            '<img src="'+data.sidebar.qr+'" />' +
            '</div>':'';
        var qrtext = data.sidebar.qrText ? '<p class="overline">'+data.sidebar.qrText+'</p>':'';
        var phone = data.sidebar.phone ? '<div class="IM_phone">' +
            '<img class="IM_icon" src="/static/common/images/sidebar/icon_phone.png"/>' +
            '<a href="tel:'+data.sidebar.phone+'">'+data.sidebar.phone+'</a>' +
            '</div>':'';
        if( qr || qrtext || phone ){
            sidebarBottom = '<div class="IM_sidebar_bottom">'+qr+qrtext+phone+'</div>';
        }
        // ⾃动隐藏开启绑定⽅法
        if( ( data.sidebar.isZoom && data.sidebar.autoZoom ) || isMobile() ){
            var flag = false ;
            div.onmouseover = function(e){
                if( checkHover(e,this) && !flag ){
                    flag = true;
                    setTimeout(function(){flag=false;},200) ;
                    sidebarSwitch(switchObj, data.sidebar.isZoom);
                }
            }
            div.onmouseout = function(e){
                if( checkHover(e,this) && !flag ){
                    flag = true;
                    setTimeout(function(){flag=false;},200) ;
                    sidebarSwitch(switchObj, data.sidebar.isZoom);
                }
            }
        }
        setTimeout(function(){
            document.body.appendChild(div);
            document.getElementById('IM_sidebar').innerHTML = '<div class="IM_sidebar">'+
                switchHtml+
                img+
                lists+
                sidebarBottom+
                '</div>';
            if( IEVersion() <= 8 && IEVersion() != -1 ){
                var top = ( document.getElementById('IM_sidebar').offsetHeight + 110 ) / 2 ;
                top += qr ? 110 : 0 ;
                document.getElementById('IM_sidebar').style.marginTop = -top+'px';
                if( IEVersion() < 8 && IEVersion() != -1){
                    console.log('您的浏览器版本过低');
                }
            }
        },100)
    }
}
