// 百度Push
function baiduPush() {
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
}

// sideTab回到顶部事件处理
function backTopByClick() {
    $('#back').click(function () {
        $('body,html').animate({ scrollTop: 0 }, 200);
    });
    $('#backMobile').click(function () {
        $('body,html').animate({ scrollTop: 0 }, 200);
    });
}

const productSpecial = {
    bind: function () {
        // 监听li的click事件
        $('.product-special_list li').click(item => {
            // 缓存当前node
            const currentNode = item.currentTarget;
            // 缓存当前节点的父节点
            const parentNode = item.currentTarget.parentNode;
            // 缓存父节点下的所有一级子节点
            const childNodeArray = Array.from(parentNode.children);
            // 记录当前节点在父节点的位置（下标）
            const index = childNodeArray.indexOf(currentNode);
            // icon上固定的类名
            const commonClass = 'product-special_list-active';

            /*
              icon重新赋值类名
              两个判断条件，为了避免做不必要元素的类名更新
             */
            $('.product-special_list li').each((elementIndex, element) => {
                if (elementIndex != index && element.className != '') {
                    element.classList.remove(commonClass);
                } else if (elementIndex == index && element.className == '') {
                    element.className = commonClass;
                }
            });

            // 切换内容
            $('.product-special_content').children('div').each((elementIndex, element) => {
                if (elementIndex != index) {
                    element.className = 'flex-none fade';
                } else {
                    element.className = 'flex-row justify-center align-center fade';
                }
            });
        });
    }
}

function getParameterByName(name, url = window.location.href) {
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

// 判断访问设备
function judgementAccessDevice() {
    const userAgent = navigator.userAgent;
    if (/(iPhone|iPad|iPod|iOS)/i.test(userAgent)) {
        return 'ios';
    } else if (/(Android)/i.test(userAgent)) {
        return 'android';
    } else if (/(Macintosh|MacIntel|MacPPC|Mac68K|Mac OS X)/i.test(userAgent)) {
        return 'macOS';
    }
    return 'pc';
}

// 不同设备改变下载url
function changeDownloadUrlByDevice() {
    const tid1 = getParameterByName('tid1') || '';
    const tid2 = getParameterByName('tid2') || '';

    const urlArray = [
        'https://www.kingpdf.cn/', 'http://www.kingpdf.cn/',
        'https://www.kingpdf.cn/about.html', 'http://www.kingpdf.cn/about.html',
        'https://www.kingpdf.cn/404/', 'http://www.kingpdf.cn/404/'
    ];

    const productFeatureUrlArray = [
        'https://www.kingpdf.cn/editor.html', 'https://www.kingpdf.cn/reader.html',
        'https://www.kingpdf.cn/exchange.html', 'https://www.kingpdf.cn/page.html',
        'https://www.kingpdf.cn/combine.html', 'https://www.kingpdf.cn/ocr.html',
        'https://www.kingpdf.cn/protect.html', 'https://www.kingpdf.cn/translator.html'
    ]
    $('.J_download').each(function () {
        let device = judgementAccessDevice();

        // 除了数组中的页面，其他页面暂时不做判断
        if (!judgeUrl(urlArray, location.href)) {
            device = 'pc';
        }

        if (device === 'pc' || device === 'macOS') {
            // 不判断macOS
            // device = judgementAccessDevice();
            // if (device === 'macOS' && !this.className.includes('window-download-btn') || this.className.includes('mac-download-btn')) {
            //     this.href = 'https://download.52pcfree.com/fastpdf/JGPDFReader_1_2.dmg'
            //     return
            // }
            if (judgeUrl(productFeatureUrlArray, location.href)) {
                this.href = 'https://download.52pcfree.com/fastpdf/JGChannel_PDF_ver23083014.277.3.1.1.exe'
                return
            }
            if (tid1 === '' || tid2 === '') {
                this.href = '//download.52pcfree.com/fastpdf/JGPDF_Home_1_2.exe';
                if (['bdjyhb0708', 'bdjyzh0708', 'bdjywz0708'].includes(getParameterByName('from'))) {
                    this.href = '//download.52pcfree.com/fastpdf/JGPDF_Home_258_3.exe';
                }
            } else {
                this.href = `//download.52pcfree.com/fastpdf/JGPDF_Home_${tid1}_${tid2}.exe`;
            }
        } else if (device === 'android') {
            this.href = '//download.52pcfree.com/fastpdf/app/jgpdf_64_cn99999.apk';
            $(this).children()[0] && $($(this).children()[0]).css({
                'background': 'url(../static/images/android-logo.png) no-repeat',
                'background-size': '100%'
            });
            $('#device-text') && $('#device-text').text('适用于Android系统，安全无毒');
        } else if (device === 'ios') {
            $(this).children()[0] && $($(this).children()[0]).css({
                'background': 'url(../static/images/android-logo.png) no-repeat',
                'background-size': '100%'
            });
            $('#device-text') && $('#device-text').text('适用于Android系统，安全无毒');
            this.href = 'javaScript:void(0)';
            this.removeAttribute('download');
            this.setAttribute('iosdownload', '');
        }
        
        // android & ios 隐藏mac下载按钮
        if (['android', 'ios'].includes(device)) {
            if ($('.mac-download-btn').length != 0) {
                $('.download-group')[0].style.justifyContent = 'center';
                $('.mac-download-btn')[0].style.display = 'none';
            }
        }
    });
}

// 导航鼠标enter/leave事件
function changeNavByMouseEnterAndLeave() {
    const navHeaderDom = $("#J_headerNav")[0];
    const needShadowDomArray = $('.need-shadow');

    if (needShadowDomArray.length > 0) {
        navHeaderDom.addEventListener('mouseenter', () => {
            $(".header").addClass('header-shadow');
        });
        navHeaderDom.addEventListener('mouseleave', () => {
            $(".header").removeClass('header-shadow');
        });
    }

    $("#J_headerNav_ul .li").each((index, item) => {
        item.addEventListener('mouseenter', () => {
            $(item).addClass('hover');
        });
        item.addEventListener('mouseleave', () => {
            $(item).removeClass('hover');
        });
    });
}

// IOS设备下载点击事件
function clickDownLoadByIOS() {
    $('a[iosdownload]').click(() => {
        $('.ios-device').show();
    });
    $('.close-ios-device').click(() => {
        $('.ios-device').hide();
    });
}

// 判断链接是否在指定链接数组中
function judgeUrl(urlArray, url) {
    return urlArray.includes(url.split('?')[0])
}

$(function () {
    baiduPush();
    backTopByClick();

    // product special的icon点击显示对应内容
    productSpecial.bind();

    changeDownloadUrlByDevice();
    changeNavByMouseEnterAndLeave();
    clickDownLoadByIOS();

    // android & ios 首页首屏下载按钮文本更改
    if (['android', 'ios'].includes(judgementAccessDevice()) && $('.window-download-text')[0]) {
        $('.window-download-text')[0].innerHTML = '免费下载'
    }
    if (judgementAccessDevice() === 'macOS' && $('.download-group')[0]) {
        $('.download-group')[0].style.flexDirection = 'row-reverse';
    }
})