/**
 * Created by fuyifan on 2021/3/31.
 */
window.Element.prototype.addEvent = function(type,fn,capture) {
    var el = this;
    if (window.addEventListener) {
        el.addEventListener(type,function(e) {
            fn.call(el,e);
        },capture);
    }else if (window.attachEvent) {
        el.attachEvent("on" + type,function(e) {
            fn.call(el,e);
        });
    }
};
//IE添加数组IndexOf方法
if (!Array.prototype.indexOf){
    Array.prototype.indexOf = function(elt){
        var len = this.length >>> 0;
        var from = Number(arguments[1]) || 0;
        from = (from < 0) ? Math.ceil(from) : Math.floor(from);
        if (from < 0)from += len;
        for (; from < len; from++){
            if (from in this && this[from] === elt)
                return from;
        }
        return -1;
    };
}
if (!("classList" in document.documentElement)) {
    Object.defineProperty(window.Element.prototype, 'classList', {
        get: function() {
            var self = this;
            function update(fn) {
                return function(value) {
                    var classes = self.className.split(/\s+/g),
                        index = classes.indexOf(value);
                    fn(classes, index, value);
                    self.className = classes.join(" ");
                }
            }
            return {
                add: update(function(classes, index, value) {
                    if (!~index) classes.push(value);
                }),

                remove: update(function(classes, index) {
                    if (~index) classes.splice(index, 1);
                }),

                toggle: update(function(classes, index, value) {
                    if (~index)
                        classes.splice(index, 1);
                    else
                        classes.push(value);
                }),
                contains: function(value) {
                    return !!~self.className.split(/\s+/g).indexOf(value);
                },

                item: function(i) {
                    return self.className.split(/\s+/g)[i] || null;
                }
            };
        }
    });
}
/*工具类方法
 ------------------------------------------------*/
//检测是否移动设备来访
function browserRedirect() {
    var sUserAgent= navigator.userAgent.toLowerCase();
    var bIsIpad= sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs= sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp= sUserAgent.match(/midp/i) == "midp";
    var bIsUc7= sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc= sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid= sUserAgent.match(/android/i) == "android";
    var bIsCE= sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM= sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
        return true;
    } else {
        return false;
    }
}
/*滑动逻辑，参数1，this，参数2，e事件，参数3，偏移量，参数4，向右滑动，参数5，向左滑动*/
function touchStart(self,e,deviationX,fun1,fun2) {
    var startX,startY,moveX,moveY,ol,or,l,R;
    startX = e.targetTouches[0].pageX;
    startY = e.targetTouches[0].pageY;
    ol = self.offsetLeft;
    or = self.offsetTop;
    var touchEnd = function(e){
        moveX = e.changedTouches[0].pageX - startX;
        moveY = e.changedTouches[0].pageY - startY;
        if (moveX > deviationX && typeof fun1 === "function") {
            fun1();
        } else if (moveX < -deviationX && typeof fun2 === "function") {
            fun2();
        }
        self.removeEventListener('touchend',touchEnd);
    };
    self.addEventListener('touchend', touchEnd);
}
/*轮播图方法*/
HTMLDivElement.prototype.banner = function(obj){
    var el = this,
        ms = /^([1-9]|10)$/.test(obj.ms) ? obj.ms*1000 : 5000,
        index = obj.index,
        arrow = obj.arrow,
        effect = obj.effect,
        autoPlay = obj.autoPlay,
        touch = obj.touch,
        list = el.getElementsByTagName('ul')[0],
        item = list.getElementsByTagName('li'),
        length = item.length,
        slideX = 0,slideY = 0,
        slide,play,auto,timer,ol,li,prev,next,attribute;

    attribute = (effect === "updown") ? 'top' : 'left';
    ol = document.createElement('ol');
    for(var i = 0; i<length; i++){
        li = document.createElement('li');
        li.index = i;
        li.onclick = function(){
            auto(slideX%length,this.index);
            slideX = this.index;
        };
        ol.appendChild(li);
    }
    if(index === true){
        ol.children[0].classList.add('active');
        el.appendChild(ol);
    }
    if(arrow === true){
        prev = document.createElement('b');
        prev.classList.add('prev');
        prev.onclick = function(){
            slide(true);
        };
        next = document.createElement('b');
        next.classList.add('next');
        next.onclick = function(){
            slide();
        };
        el.appendChild(prev);
        el.appendChild(next);
    }
    if(effect !== "fade") list.innerHTML = item[length-1].outerHTML + list.innerHTML + list.innerHTML;
    else item[0].classList.add('active');
    play = function(x){
        list.classList.add('active');
        list.style[attribute] = -x * 100 + '%';
        list.offsetWidth;// 强制浏览器reflow
        list.classList.remove('active');
        auto(slideY,slideX);
    };
    slide = function(direction){
        slideY = slideX;
        direction ? slideX-- : slideX++;
        if(effect === "fade"){
            slideX = (slideX+length)%length;
            auto(slideY,slideX);
        }else{
            if(slideX>=length){
                slideX = 0;
                play(0);
            }else if(slideX<0){
                slideX += length;
                play(length+1);
            }else { auto(slideY,slideX); }
        }
    };
    auto = function(x,y){
        if(effect === "fade"){
            item[x].classList.remove('active');
            item[y].classList.add('active');
        }else{
            list.style[attribute] = -(y+1) * 100 + '%';
        }
        ol.children[x].classList.remove('active');
        ol.children[y].classList.add('active');
    };
    if(autoPlay !== false){
        timer = setInterval(slide,ms);
        el.onmouseenter = function () {
            clearInterval(timer);
        };
        el.onmouseleave = function () {
            timer = setInterval(slide,ms);
        };
    }
    if(browserRedirect() && touch !== false){
        list.addEventListener('touchstart',function(e){
            e.stopPropagation();
            clearInterval(timer);
            touchStart(this,e,30,function(){
                slide(true);
                if(autoPlay !== false)timer = setInterval(slide,ms);
            },function(){
                slide();
                if(autoPlay !== false)timer = setInterval(slide,ms);
            });
        });
    }
};

/*手机端滑动栏目导航*/
function slideSide(){
    var wrap = document.querySelector('.wrap');
    var m_map = document.querySelector('.m_map');
    var m_shade = document.querySelector('.m_shade');
    var slideBar = function(){
        wrap.classList.toggle('active');
        m_map.classList.toggle('active');
        m_shade.classList.toggle('active');
    };
    document.querySelector('.m_navbar').onclick = slideBar;
    document.querySelector('.m_shade').onclick = slideBar;

    m_map.addEvent('touchstart',function(e){
        touchStart(this,e,60,function(){
            slideBar();
        });
    });
    m_shade.addEvent('touchstart',function(e){
        touchStart(this,e,30,function(){
            slideBar();
        });
    });
    wrap.addEvent('touchstart',function(e){
        touchStart(this,e,60,null,function(){
            slideBar();
        });
    });
}
slideSide();

function ajaxJsonp(opt) {
    var funName, script, jsonp;
    funName = opt.callback || '_ajaxJsonp' + (Math.random().toFixed(6) * 1000000);
    jsonp = opt.jsonp || 'callback';
    window[funName] = function (data) {
        if (typeof opt.success == 'function') {
            opt.success(data);
        }
        window[funName] = null;
        //delete window[funName];
        document.body.removeChild(script);
        script = null;
    };
    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = opt.url + (opt.url.indexOf('?') > -1 ? '&' : '?') + jsonp + '=' + funName;
    document.body.appendChild(script);
    script.addEvent('error', function () {
        window[funName] = null;
        //delete window[funName];
        if (typeof opt.error == 'function') {
            opt.error();
        }
        document.body.removeChild(script);
        script = null;
    });
}
function govAjax(num){
    ajaxJsonp({
        url: 'https://www.gov.cn/pushinfo/v150203/pushinfo.jsonp',
        callback: 'pushInfoJsonpCallBack',
        success: function (data) {
            var ul = document.querySelector('.govMsg');
            var lis = '';
            for (var i = 0; i<num; i++){
                lis += '<li><a href="'+data[i].link+'" target="_blank" title="'+data[i].title+'">'+data[i].description+'</a><span>'+data[i].pubDate.slice(5)+'</span></li>';
            }
            ul.innerHTML = lis;
        },
        error: function () {
            console.log('request error!');
        }
    });
}
function getNextNode(ele){
    if(ele.nextElementSibling!== undefined){
        return ele.nextElementSibling;
    }else{
        var item = ele.nextSibling ;
        while(item && item.nodeType !=1){
            item = item.nextSibling ;
        }
        return item;
    }
}
function getPrevNode(ele){
    if(ele.previousElementSibling!== undefined){
        return ele.previousElementSibling;
    }else{
        var item = ele.previousSibling;
        while(item && item.nodeType !=1){
            item = item.previousSibling ;
        }
        return item;
    }
}
function removeElement(ele) {
    document.querySelector(ele).remove();
}
/*通用tab选项卡切换*/
function tabToggle(){
    var tabTitle = document.querySelectorAll('.tab-active');
    var tabMsg = [];
    var eventListener = browserRedirect()?'click':'mouseenter';
    var titles;
    var ary = [];
    var fun = function(i,j,k){
        var tabTitles = tabTitle[i].querySelectorAll('.tab-item');
        var tabMsgs = tabMsg[i].children;
        var moreList = tabTitle[i].querySelectorAll('.more a');
        tabMsgs[j].classList.add('active');
        tabMsgs[k].classList.remove('active');
        tabTitles[j].classList.add('active');
        tabTitles[k].classList.remove('active');
        if(moreList.length !== 0){
            moreList[j].classList.add('active');
            moreList[k].classList.remove('active');
        }
    };
    for (var i=0; i<tabTitle.length; i++){
        tabTitle[i].index = i;
        tabMsg[i] = getNextNode(tabTitle[i]);
        ary[i] = 0;
        titles = tabTitle[i].querySelectorAll('.tab-item');
        for (var j=0; j<titles.length; j++){
            titles[j].index = j;
            if(titles[j].classList.contains('active')) ary[i] = j;
            titles[j].addEvent(eventListener,function(e){
                if(eventListener == 'click'){
                    e.preventDefault();
                }
                var indexNum = this.parentNode.index;
                if(this.index != ary[indexNum]){
                    fun(indexNum,this.index,ary[indexNum]);
                    ary[indexNum] = this.index;
                }
            })
        }
    }
}
if(document.querySelectorAll('.tab-active').length !== 0) tabToggle();


function httpPostServer(url,data,fun) {
    if (data.length == 0) { return; }
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.withCredentials = true;
    xmlhttp.open("POST", url, true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(data);
    xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
            fun(xmlhttp.responseText);
        }
    }
}

/*搜索联想*/
function pdsSearch(val,channelID) {
        var data = 'word='+val+'&siteId=1';
    var url = 'https://user.pds.gov.cn/api/User/HotSearch?'+data;

    httpPostServer(url,data,function(data){
        data = JSON.parse(data);
        var lis = '';
        for(var i=0; i<data.fullTextContentInfos.length; i++){
            lis += '<li><a href="/utils/search.html?isAllSites=false&word='+data.fullTextContentInfos[i].RealTilte.replace(/<span style="color:#cc0000">/g,'').replace(/<\/span>/,'')+'&channelID='+channelID+'">'+data.fullTextContentInfos[i].Title+'</a></li>';
        }
        document.querySelector('.commonSearch ul').innerHTML = lis;
    })
}

/*通用栏目页栏目导航*/
(function(){
    var channelBar = document.querySelector('.channel-title .channel-bars');
    if(channelBar){
        channelBar.onclick = function () {
            document.querySelector('.channelNames').classList.toggle('active');
        };
        document.querySelector('.channelNames').addEvent('touchstart',function(e){
            touchStart(this,e,30,function(){
                document.querySelector('.channelNames').classList.toggle('active');
            });
        })
    }
}());

/*showLoadingTemplate*/
function showLoading(id){
    var loadingTemplate = document.getElementById(id);
    loadingTemplate.classList.add('active');
    loadingTemplate.onclick = function (){
        this.classList.remove('active');
    }
    loadingTemplate.querySelector('.templateWrap').onclick=function (e){
        e.stopPropagation();
    }
}

/*纠错*/
function LinkZ(siteCode){
    var url = window.location.href;
    window.location.href = "/ErrorCorrection/ErrorCorrection.html?site_code="+siteCode+"&url="+url;
}