let w = document.body.offsetWidth || document.body.clientWidth,
    h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight,
    _ = function (select) { return document.querySelector(select) },
    _$ = function (select) { return document.querySelectorAll(select)},
    clickEvent = (function() {
        if ('ontouchstart' in document.documentElement === true){
            return 'touchstart';
        }else{
            return 'mousedown';
        }
    })(),
    whenReady = (function() {               //这个函数返回whenReady()函数
        var funcs = [];             //当获得事件时，要运行的函数
        var ready = false;          //当触发事件处理程序时,切换为true
        //当文档就绪时,调用事件处理程序
        function handler(e) {
            if(ready) return;       //确保事件处理程序只完整运行一次
            
            //如果发生onreadystatechange事件，但其状态不是complete的话,那么文档尚未准备好
            if(e.type === 'onreadystatechange' && document.readyState !== 'complete') {
                return;
            }
            
            //运行所有注册函数
            //注意每次都要计算funcs.length
            //以防这些函数的调用可能会导致注册更多的函数
            for(var i=0; i<funcs.length; i++) {
                funcs[i].call(document);
            }
            //事件处理函数完整执行,切换ready状态, 并移除所有函数
            ready = true;
            funcs = null;
        }
        //为接收到的任何事件注册处理程序
        if(document.addEventListener) {
            document.addEventListener('DOMContentLoaded', handler, false);
            document.addEventListener('readystatechange', handler, false);            //IE9+
            window.addEventListener('load', handler, false);
        }else if(document.attachEvent) {
            document.attachEvent('onreadystatechange', handler);
            window.attachEvent('onload', handler);
        }
        //返回whenReady()函数
        return function whenReady(fn) {
            if(ready) { fn.call(document); }
            else { funcs.push(fn); }
        }
    })(),
    active = function(node,active){
        return node.classList.add(active); //添加类
    },
    inactive = function(node,active){  //移除类
        return node.classList.remove(active);
    },
    getScrollbarWidth = function() {    // 得到滚动条宽度
        const container = document.createElement('div');
        container.style.visibility = 'hidden';
        container.style.position = 'absolute';
        container.style.left = '-9999px';
        container.style.width = '100px';
        container.style.overflow = 'scroll';
        document.body.appendChild(container);
        const containerWidth = container.offsetWidth;
        const inner = document.createElement('div');
        inner.style.width = '100%';
        container.appendChild(inner);
        const innerWidth = inner.offsetWidth;
        container.parentNode.removeChild(container);
        return containerWidth - innerWidth;
    },
    scrollMarginRightTrue = function(){   // 禁止滚动
        if ('ontouchstart' in document.documentElement === false){
            _('html').style.marginRight = getScrollbarWidth() + 'px';
            document.documentElement.style.overflowY='hidden';
        }
    },
    scrollMarginRightFalse = function(){  // 开启滚动
        if ('ontouchstart' in document.documentElement === false){
            _('html').style.marginRight = 0;
            document.documentElement.style.overflowY = 'auto';
        }
    };

    document.oncontextmenu = function(){
        return false;
    };

const utils = (function(){
    const photoActives = (function(){ //给img添加动效 配合滚动使用
        let section = document.createElement('section');
        section.classList.add('photoActive');
        for(let i = 0 ;i < _$('.photoActives').length; i++){
            _$('.photoActives')[i].appendChild(section.cloneNode());
        }
    })();
    const maodianlink = (function(){  // 如果点击元素是锚点 先刷新下网页在进行跳转
        if(_$('.mobilelinkitems a')){
            let mao = _$('.mobilelinkitems a');
            for(let i = 0;i<mao.length;i++){
                mao[i].addEventListener('click',function(){
                    if(mao[i].href.match('#')){
                        location.reload();
                    };
                });
            };
        }
    })();
    const itemAnimates = (function (){ //对多个项目进行动画延迟处理
        let itemAnimates = _$(".itemAnimates");
        for (let i = 0; i < itemAnimates.length; i++) {
          let itemAnimate = itemAnimates[i].querySelectorAll('.itemAnimate'),
          delay = 0,
          delayCount = parseInt(itemAnimates[i].getAttribute('delay'));
          if(!delayCount){
            delayCount = 300;
          }
          for (let j = 0; j < itemAnimate.length; j++) {
            if(itemAnimates[i].getAttribute('random') == '1'){
                delay = Math.random() * itemAnimates[i].getAttribute('randomMax');
            }else{
                delay += delayCount;
            }
            itemAnimate[j].style.animationDelay = delay + "ms";
          }
        }
    })();
    const newsPaperTable = (function (){ // 对出现table标签进行父节点100%处理
        Array.prototype.forEach.call(_$('.newspaper table'), function(el) {  
            let section = document.createElement('section');
            section.className = 'tablebox';
            el.parentNode.replaceChild(section, el);
            section.appendChild(el);
        });
    })();
    const splitlist = function(splitlist,bool){   //分割文字  //true 开始随机速度
        Array.prototype.forEach.call(_$(splitlist), function (item) {
            let flag = false,
                isRandom = bool,
                delays = parseInt(item.getAttribute('delay')),
                speeds = parseInt(item.getAttribute('speed')),
                Arrays = item.innerHTML.replace(/<br>/g, "\n").replace(/<i>/g, "\\").replace(/<\/i>/g, "\t").replace(/&amp;/g, "&").split("");
            item.innerHTML = '';
            if(!delays){
                delays = 200
            }
            if(!speeds){
                speeds = 60
            }
            Array.prototype.forEach.call(Arrays,function(letter, i) {
                let span = document.createElement("span"),
                    br = document.createElement("br"),
                    random = 1;
                if(letter.indexOf("\n") >= 0){
                    item.appendChild(br);
                    return
                }
                if(letter.indexOf("\\") >= 0){
                    flag = true;
                    return
                }
                if(letter.indexOf("\t") >= 0){
                    flag = false;
                    return
                }
                if(flag){
                    span.className = 'letters';
                }
                if(isRandom){
                    random = Math.random();
                }
                delays += speeds;
                span.style.animationDelay = delays * random  + 'ms';
                span.innerHTML = letter;
                item.appendChild(span);
            });
        });
    };
    const hasChild = function(item){  //判断元素是否有子节点
        if(item){
            Array.prototype.forEach.call(item,function(slider){
                if(slider.hasChildNodes()){
                    active(slider,'hasChildActive');
                }
            });
        }
    };
    const mobileMenu = function (){ //移动端按钮弹出
        let menu = _('.mobileMenu'),
            nav =  _('.mobileNav'),
            header = _('header');
        if(menu && nav){
            nav.style.display = 'block';
            menu.addEventListener(clickEvent,function(){
                if(menu.classList.contains('active')){
                    inactive(menu,'active');
                    inactive(nav,'active');
                    inactive(header,'ov0');
                    scrollMarginRightFalse(); 
                }else{
                    active(menu,'active');
                    active(nav,'active');
                    active(header,'ov0');
                    scrollMarginRightTrue();
                }
            });
        }
    };
    const isAutoHeight = function(event,items,item,isTrue){   //用于'click'/'mouseover'事件时动画填充高度 true默认离开时高度归零
        let height = [],
            flag = isTrue,
            nodeFather;

        function publicIf(index){
            if(items[index].classList.contains('active')){
                item[index].style.height = height[index];
                items[index].classList.add('active');
            }
        };
        
        function public(index){
            for(let i =0;i<item.length;i++){
                nodeFather[i] = items[i].parentNode;
                item[i].style.height = 0;
                items[i].classList.remove('active');
                nodeFather[i].classList.remove('active');
            }
            item[index].style.height = height[index];
            items[index].classList.add('active');
            nodeFather.classList.add('active');
        };
        for(let j = 0;j<item.length;j++){
            item[j].style.height = 'auto';
            height.push(getComputedStyle(item[j]).height);
            item[j].style.height = '0px';
        }
        if(event == 'mouseover'){
            for(let i =0;i<items.length;i++){
                items[i].index = i;
                publicIf(i);
                items[i].addEventListener(event,function(){
                    nodeFather = items[this.index].parentNode;
                    public(this.index);
                });
                if(flag == true){
                    items[i].addEventListener('mouseout',function(){
                        item[this.index].style.height = 0 ;
                        items[this.index].classList.remove('active');
                    });
                };
            };
        };
        if(event == 'click'){
            for(let i =0;i<items.length;i++){
                items[i].index = i;
                publicIf(i);
                items[i].addEventListener(event,function(){
                    nodeFather = items[this.index].parentNode;
                    if (item[this.index].style.height == '0px'){
                        public(this.index);
                    }else{
                        item[this.index].style.height = 0 ;
                        items[this.index].classList.remove('active');
                        nodeFather.classList.remove('active');
                    }
                });
            }
        };
    };
    const needvideo = function (){   // 视频弹出层
        function need(){
            let root = document.body,
            rootSection = document.createElement('section'),
            rootDiv = document.createElement('div'),
            rootVideo =  document.createElement('video');
            rootRemove = document.createElement('i');
            rootRemove.className = 'iconfont';
            rootSection.className = 'videobox';
            rootDiv.className = 'bg';
            rootVideo.controls = true;
            rootVideo.loop = true;
            rootVideo.setAttribute('x5-video-player-type','h5');
            rootVideo.setAttribute('playsinline','true');
            rootVideo.setAttribute('webkit-playsinline','true');
            rootVideo.setAttribute('x5-video-player-fullscreen','true');
            rootVideo.setAttribute('x-webkit-airplay','true');
            root.appendChild(rootSection);
            rootSection.appendChild(rootDiv);
            rootSection.appendChild(rootVideo);
            rootSection.appendChild(rootRemove);
        };
        let needs = _$('.needVideo');
        if(needs.length > 0){
            need();
            let a = _('.videobox'),
                b = _('.videobox .bg'),
                c = _('.videobox video'),
                d = _('.videobox i');
            for(let i = 0;i<needs.length;i++){
                needs[i].addEventListener('click',function(e){
                    e.preventDefault();
                    c.src = needs[i].getAttribute('data-src');
                    d.innerHTML =  needs[i].getAttribute('data-icon');
                    a.classList.add('active');
                    c.play();
                    scrollMarginRightTrue();
                });
                b.addEventListener('click',function(){
                    c.load();
                    a.classList.remove('active');
                    scrollMarginRightFalse();
                });
                d.addEventListener('click',function(){
                    c.load();
                    a.classList.remove('active');
                    scrollMarginRightFalse();
                });
            }
        }
    };
    const needWechat = function (){   // 微信弹出层
        function need(){
            let root = document.body,
            rootSection = document.createElement('section'),
            rootDiv = document.createElement('div'),
            rootP = document.createElement('p'),
            rootImg =  document.createElement('img');
            rootSection.className = 'wechat';
            root.appendChild(rootSection);
            rootSection.appendChild(rootDiv);
            rootDiv.appendChild(rootImg);
            rootDiv.appendChild(rootP);
        };
        let needs = _$('.needWechat');
        if(needs.length > 0){
            need();
            let a = _('.wechat'),
                b = _('.wechat img'),
                c = _('.wechat p');
            for(let i = 0;i<needs.length;i++){
                needs[i].addEventListener(clickEvent,function(e){
                    e.preventDefault();
                    b.src = needs[i].getAttribute('data-src');
                    c.innerText = needs[i].getAttribute('data-text');
                    a.classList.add('active');
                    scrollMarginRightTrue();
                });
                a.addEventListener(clickEvent,function(){
                    a.classList.remove('active');
                    scrollMarginRightFalse();
                });
            }
        }
    };
    const popUp = function () { // XMLHttpRequest请求弹出层
        function init(){
            let root = document.body,
            rootSection = document.createElement('section'),
            rootbg = document.createElement('div'),
            rootBox = document.createElement('div');
            rootSection.className = 'popUp';
            rootbg.className = 'popUpBg';
            rootBox.className = 'popUpBox';
            root.appendChild(rootSection);
            rootSection.appendChild(rootbg);
            rootSection.appendChild(rootBox);
        }
        let need = _$('.xmlbox');
        if(need.length > 0){
            init();
            Array.prototype.forEach.call(need,function(items){
                let item = items.querySelectorAll('.xml');
                for(let i = 0;i<item.length;i++){
                    item[i].addEventListener('click',function(e){
                        e.stopPropagation();
                        scrollMarginRightTrue();
                        _('.popUp').classList.add('active');
                        let request = new XMLHttpRequest();
                        request.open('GET',item[i].getAttribute('data-url'), true);
                        request.onload = function() {
                            if (this.status >= 200 && this.status < 400) {
                                _('.popUpBox').innerHTML = this.response;
                            } else {
                                alert('error');
                            }
                        };
                        request.send();
                    });
                };
            });
            _('.popUpBg').addEventListener('click',function(){
                _('.popUp').classList.remove('active');
                scrollMarginRightFalse();
                if(_(".calendar-wrap")){
                    document.body.removeChild(_(".calendar-wrap"));
                }
            });
        }
    };
    const NodeObserver = function(node,fn){  // node 观察器
        let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver,
            target = node,
            observer = new MutationObserver(function (mutation) {
                mutation.forEach(function(mutation) {
                    if (mutation.type === 'childList') {
                        fn();
                    }else{
                        return
                    }
                });
            }),
            config = {
                childList : true,//子节点的变动
                // attributes : true,//属性的变动
                // characterData : true,//节点内容或节点文本的变动
                // subtree : true,//所有后代节点的变动
                // attributeOldValue : true,//表示观察attributes变动时，是否需要记录变动前的属性
                // characterDataOldValue : true//表示观察characterData变动时，是否需要记录变动前的值
            };
        observer.observe(target, config); 
    };
    const placeholder = function(){  //用于顶部导航占位
        if (_('.placeholder') && _('header')){
            _('.placeholder').style.height = _('header').offsetHeight + 'px';
        };
    };
    const scrollAnimate = function() {     // 滚动到可视区域出现效果
        Array.prototype.forEach.call(_$('.flags'),function(slider){
            const top = slider.getBoundingClientRect().top;
            if (top + 20 <= h ) {
                slider.classList.add('flag');
            }
        });
        Array.prototype.forEach.call(_$('.photoActives'),function(slider){
            const top = slider.getBoundingClientRect().top;
            if (top + 20 <= h ) {
                slider.classList.add('reset_photoActive');
            }
        });
    };
    const bannerimg = function(){    // 二级banner模拟定位
        Array.prototype.forEach.call(_$('.bannerimg img'),function(slider){
            let ScrollY = document.body.scrollTop || document.documentElement.scrollTop;
            slider.style.transform = 'translate3d(0,' + ScrollY / 2.3 + 'px,0)';
        });
    };
    const bindRaf = function (fn, throttle) {  // 回调 requestAnimationFrame
        var isRunning;
        var that;
        var args;
        var run = function() {
            isRunning = false;
            fn.apply(that, args);
        };
        return function() {
            that = this;
            args = arguments;
            if (isRunning && throttle) {
                return;
            }
            isRunning = true;
            requestAnimationFrame(run);
        };
    };
    const onlyActive = function (item,itemactive){   //仅允许出现一个激活块
        for(let i =0;i<item.length;i++){
            item[i].index = i;
            let flag;
            function headle(e){
                if(e.type === 'mouseover'){
                    onlys();
                }
                else{
                    onlys();
                }
            };

            function onlys(){
                for(let i =0;i<item.length;i++){
                    item[i].classList.remove('active');
                }
                item[i].classList.add('active');
            };

            item[i].addEventListener('click',function(e){
                headle(e);
            });
            item[i].addEventListener('mouseover',function(e){
                headle(e);
            });
            item[i].addEventListener('mouseout',function(e){
                for(let i =0;i<item.length;i++){
                    item[i].classList.remove('active');
                }
                if(itemactive){
                    itemactive.classList.add('active');
                }
            });
        }
    };

    return{
        mobileMenu : mobileMenu,
        split : splitlist,
        hasChild : hasChild,
        isAutoHeight : isAutoHeight,
        scrollAnimate : scrollAnimate,
        needVideo : needvideo,
        needWechat: needWechat,
        popUp : popUp,
        placeholder : placeholder,
        NodeObserver : NodeObserver,
        bannerimg: bannerimg,
        bindRaf : bindRaf,
        onlyActive : onlyActive
    }
})();


utils.mobileMenu();
utils.split('.splitlist',true);
utils.hasChild(_$('.mobilelinkitems'));
utils.needVideo();
utils.needWechat();
utils.popUp();
utils.bannerimg();
// utils.isAutoHeight('mouseover',_$('.mobileNavitems .item'),_$('.mobilelinkitems'),true); 
utils.onlyActive(_$('.subnavBody .w1488 a'),_('.subnavBody .w1488 a.active')); 

if(w<=1024){
    utils.isAutoHeight('click',_$('.mobileNavitems .item'),_$('.mobilelinkitems'),true); 
}
 

const createPlaceholder = (function(){
    if(_('.placeholder')){
        return
    }

    let flag = true;
    let div = document.createElement('div');
    div.className = 'placeholder';
    function create(){
        if(flag && w <= 750){
            _('.App').insertBefore(div,_('.App').children[0])
            flag = false;
        }
    };
    create();
    utils.placeholder();
    window.addEventListener('resize',function () {
        create();
        utils.placeholder();
    });
})();

function yqlj(){
    let a = _('.yqlj');
    let b = _('.yqlj ol');
    if(!a){return};
    a.addEventListener(clickEvent,function(){
        b.classList.add('active');
        a.classList.add('active');
    });
    document.body.addEventListener(clickEvent,function(){
        b.classList.remove('active');
        a.classList.remove('active');
    },true);
};
yqlj();

(function(){
    let title = _$('.prdJs .w1488 .prdlist h5'),
        littleitem = _$('.prdJs .w1488 .prdlistitems .prdlistitem');
    active(title[0],'active');
    for(let i = 0;i<littleitem.length;i++){
        littleitem[i].style.display = 'none';
        littleitem[0].style.display = 'flex';
        title[i].addEventListener('mouseover',function(){
            for(let i = 0;i<littleitem.length;i++){
                littleitem[i].style.display = 'none';
                inactive(title[i],'active');
            }
            active(title[i],'active');
            littleitem[i].style.display = 'flex';
        })
    }
})();

(function(){
    let items = _('.subnavBody .w1488'),
        item = _('.subnavBody .w1488 a.active');
    if(item){
        items.scrollLeft = item.offsetLeft - (w * 0.05);
    }
})();

window.onload = function(){
    utils.scrollAnimate();
    utils.placeholder();
};

window.addEventListener('scroll',function(){
    utils.bindRaf(utils.scrollAnimate());
    utils.bindRaf(utils.bannerimg());

    // headerScroll();
});
window.addEventListener('resize',function () {
    w = document.body.offsetWidth || document.body.clientWidth;
    h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;    
});

