www.hdfsdfsdg.top Open in urlscan Pro
2606:4700:3030::ac43:8716  Public Scan

Submitted URL: http://www.hdfsdfsdg.top/includes/templates/zz/js/public.js
Effective URL: https://www.hdfsdfsdg.top/includes/templates/zz/js/public.js
Submission: On February 25 via api from US — Scanned from US

Form analysis 0 forms found in the DOM

Text Content

function wish_add(products_id, products_price, products_name, products_images, url) //框架原有函数,不做改动
{
    // wish_url = url.replace('http:',protocol)
    $.ajax({
        url: wish_url,
        type: 'post',
        async: false,
        data: {
            products_id: products_id,
            products_price: products_price,
            products_name: products_name,
            products_images: products_images,
            wish_action: 'wish_add'
        },
        cache: false,
        dataType: 'json',
        success: function (json) {


            if (json.result == 'success') {
                prompt_box(json.show_info);
            } else if (json.result == 'error') {
                prompt_box1(json.show_info);
            }
        }

    });
}

function prompt_box(arr) //框架原有函数,不做改动
{
    if (document.getElementById('prompt')) {
        return;
    }
    var box = document.createElement('div');
    box.className = 'prompt';
    box.id = 'prompt';
    box.style.left = (document.documentElement.clientWidth < 410 ? 0 : Math.ceil(document.documentElement.clientWidth / 2) - 205) + 'px';
    var s_top = document.documentElement.clientHeight < 240 ? 0 : Math.ceil(document.documentElement.clientHeight * 0.44) - 80;
    if (s_top > 370) {
        s_top = 370;
    }
    box.style.top = s_top + 'px';
    var html = '<div><h6><span></span>Message</h6>';
    if (typeof (arr) === 'string') {
        html += '	<dt>' + arr + '</dt>';
        html += '	<dd><span>Close</span></dd>';
    }
    html += '</div>';
    box.innerHTML = html;
    document.documentElement.appendChild(box);
    var spans = box.getElementsByTagName("span");
    spans[0].onclick = spans[1].onclick = function () {
        document.documentElement.removeChild(document.getElementById('prompt'));
    }
}

function prompt_box1(arr) //框架原有函数,不做改动
{
    if (document.getElementById('prompt')) {
        return;
    }
    var box = document.createElement('div');
    box.className = 'prompt';
    box.id = 'prompt';
    box.style.left = (document.documentElement.clientWidth < 410 ? 0 : Math.ceil(document.documentElement.clientWidth / 2) - 205) + 'px';
    var s_top = document.documentElement.clientHeight < 240 ? 0 : Math.ceil(document.documentElement.clientHeight * 0.44) - 80;
    if (s_top > 370) {
        s_top = 370;
    }
    box.style.top = s_top + 'px';
    var html = '<div><h6><span></span>Message</h6>';
    if (typeof (arr) === 'string') {
        html += '	<dt>' + arr + '</dt>';
        html += '	<dd><a href="' + login_url + '">Sing in</a><span>Close</span></dd>';
    }
    html += '</div>';
    box.innerHTML = html;
    document.documentElement.appendChild(box);
    var spans = box.getElementsByTagName("span");
    spans[0].onclick = spans[1].onclick = function () {
        document.documentElement.removeChild(document.getElementById('prompt'));
    }
}

function wish_remove(products_id, obj, url) //框架原有函数,不做改动
{
    // wish_url = url.replace('http:',protocol)
    if (obj.parentNode.className == 'del') {
        obj.parentNode.className = 'del-ing';
    } else {
        $.ajax({
            url: wish_url,
            type: 'post',
            async: false,
            data: {products_id: products_id, wish_action: 'wish_remove'},
            cache: false,
            dataType: 'json',
            success: function (json) {
                if (json.result == 'success') {
                    obj.parentNode.parentNode.parentNode.removeChild(obj.parentNode.parentNode);
                    if (document.getElementById('wish-list').getElementsByTagName('li').length == 0) {
                        location.replace(location.href);
                    }
                } else if (json.result == 'error') {
                    prompt_box1(json.show_info);
                }
            }
        });
    }
}

date = new Date().getTime();
expireTime = date + 1000 * 60 * 60 * 24;

const foowwLocalStorage = {
    set: function (key, value, ttlMs) {
        let data = {value: value, expirse: new Date(ttlMs).getTime()};
        localStorage.setItem(key, JSON.stringify(data));
    },
    get: function (key) {
        let data = JSON.parse(localStorage.getItem(key));
        if (data !== null) {
            //debugger
            if (data.expirse != null && data.expirse < new Date().getTime()) {
                localStorage.removeItem(key);
            } else {
                return data.value;
            }
        }
        return null;
    }
}

function pageCartRender(productsData, data)
{
    let cartContentText = JSON.parse(data)['cart_content_text']
    let [emptyText, continueText, checkoutText] = [cartContentText[0], cartContentText[1], cartContentText[2]]
    let [products, loginStatus] = []

    if (localStorage.getItem('logged') <= 0) {
        products = foowwLocalStorage.get('product')
    } else {
        products = productsData.contents
        loginStatus = 1
    }

    let cartTitle = cartContentText[3]
    $(".page-cart-title").html(cartTitle)

    let html = ''
    if (products == null || products.length == 0) {
        html = '<h2>' + emptyText + '</h2>'
    } else {
        let [itemPrice, subPrice, subTotal] = [0, 0, 0.00]
        let language = JSON.parse(data)['language_data']['language']
        let currency = JSON.parse(data)['currency_data']['currency_iso']
        $.each(products, function (i, item) {
            if (typeof (item.currency) == "undefined") {
                item.currency = 'USD'
            }
            //计算商品总价
            itemPrice = item.price
            itemPrice = convertedPrice(itemPrice, currency, item.currency)
            itemPrice = standardPrice(language, currency, itemPrice)

            subPrice = item.price
            subPrice = convertedPrice(subPrice, 'USD', item.currency)
            subTotal = math.evaluate(parseFloat(subPrice) * item.qty + subTotal)

            //绘制购物车的商品列表
            html += '<div class="cart-row bold-row">\n' +
                '<div class="grid">\n' +
                '<div class="col-2_sm-12 padding">\n' +
                '<a class="cart-product-image" href="' + item.app + '">\n' +
                '<img src=" ' + item.image + '" onerror="" width="200" alt="product_img">\n' +
                '</a>\n' +
                '</div>\n' +
                '<div class="col-5_sm-12 padding cart-padding text-center-sm">\n' +
                '<h3 class="cart-product-title">\n' +
                '<a href="' + item.app + '">' + item.title + '</a>\n' +
                '</h3>\n' +
                '<ul>\n' +
                '<li></li>\n' +
                '</ul>' +
                '</div>\n' +
                '<div class="col-2_sm-4 padding cart-padding text-center-sm" data-push-left="off-0_sm-4"></div>\n' +
                '<div class="col-3_sm-12 padding cart-padding text-right text-center-sm">\n' +
                '<h3 class="cart-price">\n' +
                itemPrice + " * " + item.qty

            if (loginStatus == 1) {
                html += '<a class="cart-drawer-remove remove-item bold-ro-remove" href="/archive_cart?action=delete&prid=' + i + '">\n' +
                    '<i class="icomoon-close"></i>\n'
            } else {
                html += '<a class="cart-drawer-remove remove-item bold-ro-remove">\n' +
                    '<i class="icomoon-close" onclick="removeItem(' +
                    '\'' + item.product_id + '\''
                    + ');"></i>\n'
            }

            html += '</a>\n' +
                '</h3>\n' +
                '</div>\n' +
                '</div>\n' +
                '</div>'
        })
        subTotal = math.format(subTotal, {precision: 14})

        if (subTotal > 0) {
            subTotal = convertedPrice(subTotal, currency, 'USD')
            subTotal = standardPrice(language, currency, subTotal)

            let total = '<div class="styled-card cart-sidebar">\n' +
                '<div class="grid">\n' +
                '<!--bof subtotal--><div class="col-4 padding">\n' +
                '<h6 class="cart-drawer-subtotal-title">Sub-Total:</h6>\n' +
                '</div>\n' +
                '<div class="col-8 text-right padding">\n' +
                '<h3 class="cart-drawer-subtotal-price">' + subTotal + '</h3>\n' +
                '</div>\n' +
                '<!--eof subtotal--><!--bof btn--><div class="col-12">\n' +
                '<a href="javascript:window.location.href=document.referrer" class="cart-drawer-continue cart-drawer-close button">\n' +
                '<i class="icomoon-reply"></i>' + continueText + '</a>\n' +
                '<a href="/index.php?main_page=checkout_shipping" class="cart-drawer-continue cart-drawer-close button">' + checkoutText + '</a>\n' +
                '</div>\n' +
                '<!--eof btn--></div>\n' +
                '</div>'

            $(".col-3_md-4_sm-12").html(total)
        } else {
            html = '<h2>' + emptyText + '</h2>'
        }
    }
    $(".col-9_md-8_sm-12").html(html)
}

function navCartRender(productsData, data)
{
    let language = JSON.parse(data)['language_data']['language']
    let currency = JSON.parse(data)['currency_data']['currency_iso']
    let navCartText = JSON.parse(data)['nav_cart_text']
    let [headerCartText, productUnitText] = [navCartText[0], navCartText[1]]
    let products
    if (localStorage.getItem('logged') <= 0) {
        products = foowwLocalStorage.get('product')
    } else {
        products = productsData.contents
    }

    let [qtyTotal, price, subTotal] = [0, 0, 0.00]
    if (products != null && products != "") {
        $.each(products, function (i, item) {
            if (typeof (item.currency) == "undefined") {
                item.currency = 'USD'
            }
            price = item.price
            qtyTotal = item.qty + qtyTotal
            price = convertedPrice(price, 'USD', item.currency)
            subTotal = math.evaluate(price * item.qty + subTotal)
        })
    }
    subTotal = convertedPrice(subTotal, currency, 'USD')
    subTotal = math.format(subTotal, {precision: 14})
    subTotal = standardPrice(language, currency, subTotal)
    let html = '<span><a href="shopping_cart.html">' + headerCartText + '</a></span>' +
        '<a style="margin-bottom: 5px" href="shopping_cart.html">' + qtyTotal + productUnitText + subTotal + '</a>'

    $(".cart-bg").html(html)
}

function removeItem(key)
{
    if (localStorage.getItem('logged') <= 0) {
        let products = foowwLocalStorage.get('product')
        let productsId = foowwLocalStorage.get('product_id')

        //删除localStorage products指定商品数据
        delete products[key]
        productsId.splice(key, 1)//删除指定key对应的值

        //重新写入缓存
        foowwLocalStorage.set('product', products, expireTime)
        foowwLocalStorage.set('product_id', productsId, expireTime)

        location.reload();
    }
}

function findKey(obj, value, compare = (a, b) => a === b)
{
    return Object.keys(obj).find(k => compare(obj[k], value))
}

function isCustomerLogin(loginStatus)
{
    if (loginStatus === true) {
        localStorage.setItem('logged', '1')
    } else {
        localStorage.setItem('logged', '0')
    }
}

multidataTime = date + 1000 * 3600 * 24 * 7

function getBrowserUseragent()
{
    if (foowwLocalStorage.get('isGetNavigator') == null) {
        //获取user-agent进行规则匹配
        let userAgent = navigator.userAgent;
        const reg = new RegExp('googlebot|bingbot|yandexbot', 'i');
        if (!reg.test(userAgent)) {
            let userLanguage = navigator.language;//获取浏览器语言
            if (userLanguage) {
                let ulArr = userLanguage.split('-');
                if (ulArr.length == 1) {
                    languageMapSet(ulArr[0]);
                } else {
                    lanAreaMapSet(ulArr[0], ulArr[1]);
                }
            } else {
                areaMapSet();
            }
        }
        foowwLocalStorage.set('isGetNavigator', 1, multidataTime)
    }
}

//语言校验,判断该语言是否可用
function languageValidation(lan)
{
    const languageArr = ['en', 'fr', 'de', 'it', 'es', 'nl']
    for (let i in languageArr) {
        if (lan.indexOf(languageArr[i]) != -1) {
            return lan
        }
    }
}

//地区校验,判断通过该地区获取到的货币是否可用
function countryValidation(area, type)
{
    const areaISO2 = {
        HK: {currency: 'HKD', language: 'en'},
        HU: {currency: 'HUF', language: ''},
        JP: {currency: 'JPY', language: ''},
        NO: {currency: 'NOK', language: ''},
        PL: {currency: 'PLN', language: ''},
        RU: {currency: 'RUB', language: ''},
        SE: {currency: 'SEK', language: ''},
        SG: {currency: 'SGD', language: 'en'},
        IL: {currency: 'ILS', language: ''},
        TH: {currency: 'THB', language: ''},
        TW: {currency: 'TWD', language: ''},
        MY: {currency: 'MYR', language: ''},
        BR: {currency: 'BRL', language: 'es'},
        DK: {currency: 'DKK', language: ''},
        BO: {currency: 'EUR', language: 'es'},
        CR: {currency: 'EUR', language: 'es'},
        EC: {currency: 'USD', language: 'es'},
        ES: {currency: 'EUR', language: 'es'},
        GT: {currency: 'EUR', language: 'es'},
        HN: {currency: 'EUR', language: 'es'},
        MX: {currency: 'MXN', language: 'es'},
        NI: {currency: 'EUR', language: 'es'},
        PA: {currency: 'EUR', language: 'es'},
        PR: {currency: 'USD', language: 'es'},
        PY: {currency: 'EUR', language: 'es'},
        SV: {currency: 'EUR', language: 'es'},
        VE: {currency: 'EUR', language: 'es'},
        AU: {currency: 'AUD', language: 'en'},
        BZ: {currency: 'USD', language: 'en'},
        CB: {currency: 'USD', language: 'en'},
        GB: {currency: 'GBP', language: 'en'},
        IE: {currency: 'EUR', language: 'en'},
        JM: {currency: 'USD', language: 'en'},
        NZ: {currency: 'NZD', language: 'en'},
        PH: {currency: 'PHP', language: 'en'},
        TT: {currency: 'USD', language: 'en'},
        US: {currency: 'USD', language: 'en'},
        ZW: {currency: 'USD', language: 'en'},
        AT: {currency: 'EUR', language: 'de'},
        DE: {currency: 'EUR', language: 'de'},
        LI: {currency: 'CHF', language: 'de'},
        FR: {currency: 'EUR', language: 'fr'},
        MC: {currency: 'EUR', language: 'fr'},
        IT: {currency: 'EUR', language: 'it'},
        NL: {currency: 'EUR', language: 'nl'},
        CA: {currency: 'CAD', language: 'en'},
        LU: {currency: 'EUR', language: 'de'},
        BE: {currency: 'EUR', language: 'fr'},
        CH: {currency: 'CHF', language: 'de'}
    }
    for (let i in areaISO2) {
        if (area.indexOf(i) != -1) {
            switch (type) {
                case 'lan':
                case 'lan-area':
                    return areaISO2[i].currency
                case 'area':
                    if (areaISO2[i].language) {
                        $.cookie('language', areaISO2[i].language, {expires: 7, path: '/'});
                        $.cookie('currency', areaISO2[i].currency, {expires: 7, path: '/'});
                    } else {
                        $.cookie('currency', areaISO2[i].currency, {expires: 7, path: '/'});
                    }
                    break;
            }
        }
    }
}

//根据语言映射设置语言、货币
function languageMapSet(language)
{
    const languagesArr = {
        en: "USD",
        es: "MXN",
        fr: "EUR",
        it: "EUR",
        nl: "EUR",
        de: "EUR"
    }
    $.ajax({
        url: '/api/country',
        type: 'get',
        data: '',
        async: false,
        dataType: 'json',
        success: function (res) {
            let isoCode = res.data.country.iso_code
            let lan = languageValidation(language)
            let iso = countryValidation(isoCode, 'lan')
            if (lan && !iso) {
                iso = languagesArr[lan]
            }
            setMultidata(lan, iso)
        }
    })
}

//根据语言-地区映射设置语言、货币
function lanAreaMapSet(language, area)
{
    let lan = languageValidation(language)
    let iso = countryValidation(area, 'lan-area')
    setMultidata(lan, iso)
}

//根据地区映射设置语言、货币
function areaMapSet()
{
    $.ajax({
        url: '/api/country',
        type: 'get',
        data: '',
        async: false,
        dataType: 'json',
        success: function (res) {
            let isoCode = res.data.country.iso_code
            countryValidation(isoCode, 'area')
        }
    })
}

//通过获取到语言和货币确定post请求的数据
function setMultidata(lan, iso)
{
    let [lanNum, isoNum] = [0, 0]
    if (lan) {
        lanNum = 1
    }
    if (iso) {
        isoNum = 2
    }
    let sum = lanNum + isoNum
    switch (sum) {
        case 1:
            $.cookie('language', lan, {expires: 7, path: '/'});
            break;
        case 2:
            $.cookie('currency', iso, {expires: 7, path: '/'});
            break;
        case 3:
            $.cookie('language', lan, {expires: 7, path: '/'});
            $.cookie('currency', iso, {expires: 7, path: '/'});
            break;
    }
}

//多语言-菜单栏
function navMenu(json)
{
    let navMenuText = JSON.parse(json)['nav_menu_text']
    let [homeText, wishText, contactText] = [navMenuText[0], navMenuText[1], navMenuText[2]]
    let homeUrl = host
    let wishUrl = host + 'index.php?main_page=wish'
    let contactUrl = host + 'contact_us.html'
    let loginHtml = '<a  href="' + homeUrl + '" rel="nofollow">' + homeText + '</a>\n' +
        '<a  href="' + wishUrl + '" rel="nofollow">' + wishText + '</a>\n' +
        '<a  href="' + contactUrl + '" rel="nofollow">' + contactText + '</a>\n'

    let logMenuText = JSON.parse(json)['log_menu_text']
    if (localStorage.getItem('logged') <= 0) {
        let logInText = logMenuText[0]
        let createAccountText = logMenuText[1]
        let loginUrl = host + "index.php?main_page=login"
        let createUrl = host + "index.php?main_page=create_account"
        loginHtml += '<a  href="' + loginUrl + '" rel="nofollow">' + logInText + '</a>\n' +
            '<a  href="' + createUrl + '">' + createAccountText + '</a>'
    } else {
        let logOffText = logMenuText[2]
        let myAccountText = logMenuText[3]
        let logOffUrl = host + "index.php?main_page=logoff"
        let accountUrl = host + "index.php?main_page=account"
        loginHtml += '<a  href="' + logOffUrl + '" rel="nofollow">' + logOffText + '</a>\n' +
            '<a  href="' + accountUrl + '">' + myAccountText + '</a>'
    }
    $("#hcl").html(loginHtml)
}

//多语言-语言菜单-渲染选中的语言
function selectedLanguage(data)
{
    let languageData = JSON.parse(data)['language_data']
    $("#language").children("span").text(languageData['language'])
    $("#language").children("img").attr("alt",'selected-language')
    $("#language").children("img").attr("src", "includes/languages/" + languageData['language'] + "/images/icon.gif")
}

const languageMap = [
    {'language_code': 'en', 'language': 'english'},
    {'language_code': 'fr', 'language': 'french'},
    {'language_code': 'de', 'language': 'german'},
    {'language_code': 'it', 'language': 'italian'},
    {'language_code': 'es', 'language': 'spanish'},
    {'language_code': 'nl', 'language': 'dutch'}
]

//多语言-语言菜单
function languageMenu()
{
    let htmlLanguage = ''
    for (let i = 0; i < languageMap.length; i++) {
        let language = languageMap[i]['language']
        htmlLanguage += '<li><div class="lan">'
        htmlLanguage += '<img src="/includes/languages/' + language + '/images/icon.gif" alt="' + language + '">'
        htmlLanguage += '<input type="hidden" value="' + i + '">'
        htmlLanguage += '<span>' + language + '</span>'
        htmlLanguage += '</div></li>'
    }

    $("#language-drop-menu").html(htmlLanguage)

    //点击显示/隐藏下拉菜单
    $("#language-menu").on("click", "#language", function () {
        $(this).next('#language-drop-menu').slideToggle(500);
    })

    //切换语言
    $("#language-drop-menu > li").on("click", function () {
        foowwLocalStorage.set('isGetNavigator', 1, multidataTime)
        let languageNo = $(this).children(".lan").children("input").attr("value")
        $.cookie('language', languageMap[languageNo]['language_code'], {expires: 7, path: '/'});
        languageClickEvent()
    })
}

function languageClickEvent()
{
    if (url.indexOf('archive') != -1 || host == url || url.indexOf('shopping_cart') != -1) {
        $.post("index.php?main_page=selected_data", {}, function (data) {
            globalRender(data, '', 'language')
        })
    } else {
        location.reload()
    }
}

//多语言-免邮标准
function freeShippingNotice(data)
{
    let price = 39.99
    let language = JSON.parse(data)['language_data']['language']
    let currency = JSON.parse(data)['currency_data']['currency_iso']
    price = restorePrice(price, language, currency, 'USD')
    let freeShippingStandard = JSON.parse(data)['free_shipping_standard'] + price + " !"
    $(".shipping-standard").text(freeShippingStandard)
}

//底部广告渲染
function footerAdRender(json)
{
    let footerText = JSON.parse(json)['footer_ad_text']
    $(".we-are-professional").html(footerText[0])
    $(".we-guarantee-a-safe").html(footerText[1])
    $(".our-goal-customer-first").html(footerText[2])
    $(".powerful-customer-service").html(footerText[3])
}

//多语言-详情页
function pageArchiveRender(json)
{
    let archiveDataText = JSON.parse(json)['archive_data']

    $(".addtocart").text(archiveDataText[0])
    $(".selected").text(archiveDataText[1])
    $(".centerBoxHeading").text(archiveDataText[2])
}

//多语言-底部菜单
function boxInformation(json)
{
    let boxInformationText = JSON.parse(json)['box_information_text']
    boxInformationText = HTMLDecode(boxInformationText).split(",")
    let [contactText, privacyText, shippingText] = [boxInformationText[0], boxInformationText[1], boxInformationText[2]]

    let contactUrl = host + "contact_us.html"
    let privacyUrl = host + "privacy.html"
    let shippingUrl = host + "shippinginfo.html"
    let footerMenu = '<li><a class="first"  href="' + contactUrl + '" rel="nofollow">' + contactText + '</a></li>\n' +
        '<li><a  href="' + privacyUrl + '" rel="nofollow">' + privacyText + '</a></li>\n' +
        '<li><a  href="' + shippingUrl + '" rel="nofollow">' + shippingText + '</a></li>\n' +
        buildPromoteLabel(JSON.parse(json)['promote']);

    $("#box-information").html(footerMenu)
}

function buildPromoteLabel(promote)
{
    if (promote && Array.isArray(promote) && promote.some(element => element !== '')) {
        let result = '';
        promote.forEach(function (url) {
            result += '<li><a href = "https://' + url + '"></a></li> ';
        });
        return result;
    }
    return '';
}

//多语言-公共列表 home标题和more标题
function publicList(json)
{
    let commonListText = JSON.parse(json)['common_list_text']

    $("#first > a").text(commonListText[0])
    $("#last > a").text(commonListText[1])
}

//多语言-列表页
function pageCategoriesTitle(json)
{
    let categoriesTitle = JSON.parse(json)['categories_title']
    $(".innerbox1").text(categoriesTitle)
}

//HTML反转义
function HTMLDecode(text)
{
    let temp = document.createElement("div");
    temp.innerHTML = text;
    let output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}

//多语言-列表页、详情页规范价格显示
function renderProductPrice(json)
{
    let language = JSON.parse(json)['language_data']['language']
    let currency = JSON.parse(json)['currency_data']['currency_iso']
    let productOriginalPrice = document.getElementsByClassName("original_price")
    let productSalePrice = document.getElementsByClassName("sale_price")
    let productOriginalCurrency = document.getElementsByClassName("original_currency")

    let productNormalPrice = document.getElementsByClassName("normalprice")
    let productSpecialPrice = document.getElementsByClassName("productSpecialPrice")

    for (let i = 0; i < productOriginalPrice.length; i++) {
        let originalPrice = productOriginalPrice[i].value
        let salePrice = productSalePrice[i].value
        let originalCurrency = productOriginalCurrency[i].value

        let normalPrice = restorePrice(originalPrice, language, currency, originalCurrency)
        productNormalPrice[i].innerText = normalPrice

        let specialPrice = restorePrice(salePrice, language, currency, originalCurrency)
        productSpecialPrice[i].innerText = specialPrice
    }
}

//还原价格
function restorePrice(price, language, currency, originalCurrency)
{
    price = Number(price)

    //价格换算,加上货币符号,规范价格
    price = convertedPrice(price, currency, originalCurrency)
    price = standardPrice(language, currency, price)

    return price
}

//还原带符号的价格
function restoreSymbolPrice(price, language, currency)
{
    price = price.replace(/[^0-9]/g, "")
    if (price != '') {
        price = price.substring(0, price.length - 2) + '.' + price.substr(price.length - 2, price)
    }
    price = convertedPrice(price, currency, 'USD')
    price = standardPrice(language, currency, price)

    return price
}

//根据汇率换算价格
function convertedPrice(price, currency, originalCurrency)
{
    //获取汇率
    let rates = foowwLocalStorage.get("rates")
    //如果初始货币单位代码不是USD,则将其换成以USD为单位的价格
    if (originalCurrency != 'USD') {
        let value = rates[originalCurrency]
        price = math.evaluate(price / value)
        price = Math.floor(price * 100) / 100
        price = math.round(price, 2)
    }

    //如果当前货币单位代码不是USD,则将其换成以当前货币为单位的价格
    if (currency != 'USD') {
        let currentValue = rates[currency]
        price = math.evaluate(price * currentValue)
    }

    price = Math.floor(price * 100) / 100
    price = math.round(price, 2)

    return price
}

//多语言-按语言规范价格
function standardPrice(language, currency, price)
{
    price = Number(price)
    if (price < 0) {
        return false;
    }
    if (currency == 'HUF') {
        price = Math.round(price, 2)
    }
    switch (language) {
        case 'english':
            price = price.toLocaleString('en-US', {style: 'currency', currency: currency})
            price = standardCurrencySymbol(price)
            break;
        case 'french':
            price = price.toLocaleString('fr-FR', {style: 'currency', currency: currency})
            price = standardCurrencySymbol(price)
            break;
        case 'german':
            price = price.toLocaleString('de-DE', {style: 'currency', currency: currency})
            price = standardCurrencySymbol(price)
            break;
        case 'italian':
            price = price.toLocaleString('it-IT', {style: 'currency', currency: currency})
            price = standardCurrencySymbol(price)
            break;
        case 'spanish':
            price = price.toLocaleString('es-ES', {style: 'currency', currency: currency})
            price = standardCurrencySymbol(price)
            break;
        case 'dutch':
            price = price.toLocaleString('nl-NL', {style: 'currency', currency: currency})
            price = standardCurrencySymbol(price)
            break;
        default:
            return false;
    }
    return price
}

//规范货币单位
function standardCurrencySymbol(price)
{
    const symbolMap = {
        "CAD": "$", "CA$": "$", "$CA": "$", "C$": "$", "AUD": "$", "AU$": "$",
        "$AU": "$", "A$": "$", "CZK": "Kč", "DKK": "kr", "GBP": "£", "£GB": "£",
        "HKD": "HK$", "HUF": "Ft", "JPY": "Â¥", "JPÂ¥": "Â¥", "NOK": "kr", "NZD": "$",
        "NZ$": "$", "$NZ": "$", "PLN": "zł", "RUB": "₽", "SEK": "kr", "USD": "$",
        "US$": "$", "$US": "$", "SGD": "$", "$SG": "$", "MXN": "$", "MX$": "$",
        "$MX": "$", "COP": "$", "$CO": "$", "ARS": "$", "$AR": "$", "PEN": "S/",
        "CLP": "$", "$CL": "$", "ILS": "₪", "PHP": "₱", "THB": "฿", "TWD": "NT$",
        "MYR": "RM", "BRL": "R$", "KRW": "₩", "EGP": "£", "IDR": "Rp", "INR": "₹",
        "PKR": "₨", "RON": "lei", "TRY": "₺", "UAH": "₴", "UYU": "$U", "$UY": "$U",
        "VND": "â‚«", "ZAR": "R",
    }

    for (let i in symbolMap) {
        if (price.indexOf(i) !== -1) {
            price = price.replace(i, symbolMap[i])
        }
    }
    return price
}

//邮费页规范价格显示
function renderShippingPrice(json)
{
    let language = JSON.parse(json)['language_data']['language']
    let currency = JSON.parse(json)['currency_data']['currency_iso']

    let shippingPrice = $(".shipping_price").next("input").attr("value")
    shippingPrice = restoreSymbolPrice(shippingPrice, language, currency)

    $(".shipping_price").text(shippingPrice)
}

//结算页规范价格显示
function renderPaymentPrice(json)
{
    let language = JSON.parse(json)['language_data']['language']
    let currency = JSON.parse(json)['currency_data']['currency_iso']

    let subtotal = $("#otsubtotal > div:first").next("input").attr("value")
    subtotal = restoreSymbolPrice(subtotal, language, currency)
    $("#otsubtotal > div:first").text(subtotal)
    let shipping = $("#otshipping > div:first").next("input").attr("value")
    shipping = restoreSymbolPrice(shipping, language, currency)
    $("#otshipping > div:first").text(shipping)
    let total = $("#ottotal > div:first").next("input").attr("value")
    total = restoreSymbolPrice(total, language, currency)
    $("#ottotal > div:first").text(total)
}

//当用户选择支付方式为paypal时,如果当前货币为paypal不支持的类型,则给予提示
/*
    1.初次进入,支付方式默认为paypal
    2.切换支付方式为paypal,重新获取货币,判断是否支持
    3.切换货币,当前支付方式为paypal时,判断是否支持
*/
function paySupportNotice(data)
{
    let currency = JSON.parse(data)['currency_data']['currency_iso']
    const noSupportMap = {
        "AED": "error", "SAR": "error", "COP": "error",
        "ARS": "error", "PEN": "error", "CLP": "error",
        "KRW": "error", "EGP": "error", "IDR": "error",
        "INR": "error", "MAD": "error", "PKR": "error",
        "RON": "error", "TRY": "error", "UAH": "error",
        "UYU": "error", "VND": "error", "ZAR": "error"
    }

    let payment = $("input[type='radio']")
    let selectedPayment = ""
    if (payment.length > 1) {
        selectedPayment = $("input:radio:checked").val()
    } else {
        selectedPayment = $(".payment > input").val()
    }

    if (selectedPayment === "pstandcard") {
        for (let i in noSupportMap) {
            if (currency.indexOf(i) !== -1) {
                $("#checkout-btn").attr({disabled:"true",style:"cursor:not-allowed"})
                noticeAlert(data)
                return true
            }
        }
        $("#checkout-btn").removeAttr("disabled style")
    } else {
        $("#checkout-btn").removeAttr("disabled style")
    }
}

//根据当前语言,弹窗展示不同的文字
function noticeAlert(data)
{
    let language = JSON.parse(data)['language_data']['language']
    let currency = JSON.parse(data)['currency_data']['currency_iso']
    let [leftNotice, rightNotice] = ["", ""]
    switch (language) {
        case 'english':
            leftNotice = "Sorry, PayPal does not support "
            rightNotice = ",please switch to another currency"
            break;
        case 'french':
            leftNotice = "Désolé, PayPal ne prend pas en charge "
            rightNotice = ",veuillez changer de monnaie."
            break;
        case 'german':
            leftNotice = "PayPal unterstützt leider nicht "
            rightNotice = ", bitte wechseln Sie zu einer anderen Währung"
            break;
        case 'italian':
            leftNotice = "Spiacenti, PayPal non supporta "
            rightNotice = ", si prega di passare a un'altra valuta"
            break;
        case 'spanish':
            leftNotice = "Lo sentimos, PayPal no admite "
            rightNotice = ", por favor, cambie a otra moneda"
            break;
        case 'dutch':
            leftNotice = "Sorry, PayPal ondersteunt geen "
            rightNotice = ", gelieve een andere valuta te kiezen"
            break;
        default:
            return false;
    }
    alert(leftNotice + currency + rightNotice)
}

function selectedPayMethod(data)
{
    paySupportNotice(data)

    $("input[type='radio']").on("click", function () {
        $.post("index.php?main_page=selected_data", {}, function (data) {
            paySupportNotice(data)
        })
    })
}

//多语言-语言菜单-渲染选中的语言
function selectedCurrency(data)
{
    let currencyData = JSON.parse(data)['currency_data']
    let currencyIso = currencyData['currency_iso']
    let currencySymbol = new String()
    objCurrency.forEach((value) => {
        if (value.ISO == currencyIso) {
            currencySymbol = value.symbol
        }
    })

    $("#currency").children("span:first").text(currencyIso)
    $("#currency").children("span:last").text(currencySymbol)
}

const objCurrency = [
    {"ISO":"AUD","symbol":"$"},{"ISO":"BRL","symbol":"R$"},{"ISO":"CAD","symbol":"$"},{"ISO":"CHF","symbol":"CHF"},{"ISO":"CZK","symbol":"Kč"},{"ISO":"DKK","symbol":"kr"},
    {"ISO":"EUR","symbol":"€"},{"ISO":"GBP","symbol":"£"},{"ISO":"HKD","symbol":"HK$"},{"ISO":"HUF","symbol":"Ft"},{"ISO":"ILS","symbol":"₪"},{"ISO":"JPY","symbol":"¥"},
    {"ISO":"MXN","symbol":"$"},{"ISO":"MYR","symbol":"RM"},{"ISO":"NOK","symbol":"kr"},{"ISO":"NZD","symbol":"$"},{"ISO":"PHP","symbol":"₱"},{"ISO":"PLN","symbol":"zł"},
    {"ISO":"RUB","symbol":"₽"},{"ISO":"SEK","symbol":"kr"},{"ISO":"SGD","symbol":"$"},{"ISO":"THB","symbol":"฿"},{"ISO":"TWD","symbol":"NT$"},{"ISO":"USD","symbol":"$"}
]

//多货币-货币菜单
function currencyMenu()
{
    let htmlCurrency = ''
    for (let i = 0; i < objCurrency.length; i++) {
        let currency = objCurrency[i]
        htmlCurrency += '<li><div class="lan">'
        htmlCurrency += '<input type="hidden" value="' + i + '">'
        htmlCurrency += '<span>' + currency.ISO + '</span>'
        htmlCurrency += '<span>' + currency.symbol + '</span>'
        htmlCurrency += '</div></li>'
    }
    $("#currency-drop-menu").html(htmlCurrency)

    //点击显示/隐藏下拉菜单
    $("#currency-menu").on("click", "#currency", function () {
        $(this).next('#currency-drop-menu').slideToggle(500);
    })

    //切换货币
    $("#currency-drop-menu > li").on("click", function () {
        foowwLocalStorage.set('isGetNavigator', 1, multidataTime)
        let currencyNo = $(this).children(".lan").children("input").attr("value")
        $.cookie('currency', objCurrency[currencyNo]['ISO'], {expires: 7, path: '/'});
        currencyClickEvent()
    })
}

function currencyClickEvent()
{
    $.post("index.php?main_page=selected_data", {}, function (data) {
        if (url.search("checkout_payment") != -1 && url.search("order_id") == -1) {//结算页
            paySupportNotice(data)
        }
        globalRender(data, '', 'currency')
    })
}

domain = window.location.host
protocol = document.location.protocol
host = protocol + "//" + domain + "/"
url = document.location.toString()

//渲染集合
function globalRender(data, status, type)
{
    publicSection(data, type)
    cartRelatedRender(data, status)
    currentPageRender(data, type)
}

//小购物车、购物车页渲染,判断登陆状态后决定数据源
function cartRelatedRender(data, logStatus)
{
    let status
    if (logStatus != '') {
        status = logStatus
    } else {
        status = localStorage.getItem('logged')
    }

    if (status == 1) {
        $.post("index.php?main_page=archive_cart_server", {}, function (productsData) {
            navCartRender(productsData, data)
            if (url.indexOf('shopping_cart.html') != -1) {
                pageCartRender(productsData, data)
            }
        }, "json")
    } else {
        navCartRender('', data)
        if (url.indexOf('shopping_cart.html') != -1) {
            pageCartRender('', data)
        }
    }
}

//判断当前页面后,进行相应渲染
function currentPageRender(data, type = 'language')
{
    if (url.indexOf('archive') != -1 || host == url) {//首页、列表页、详情页
        renderProductPrice(data)
        if (type == 'language') {
            pageArchiveRender(data)
            pageCategoriesTitle(data)
        }
    } else if (url.search("checkout_shipping") != -1) {//邮费页
        renderShippingPrice(data)
    } else if (url.search("checkout_payment") != -1 && url.search("order_id") == -1) {//结算页(排除历史订单)
        renderPaymentPrice(data)
    }
}

//多语言-公共部分
function publicSection(data, type)
{
    //多语言、多货币菜单
    selectedCurrency(data)
    selectedLanguage(data)
    //免邮信息
    freeShippingNotice(data)
    //底部广告
    footerAdRender(data)
    if (type == 'language') {
        //头部菜单
        navMenu(data)
        //公共列表
        publicList(data)
        //底部菜单
        boxInformation(data)
    }
}

function htmlRender()
{
    $.post("index.php?main_page=selected_data", {}, function (data) {
        let rates = foowwLocalStorage.get("rates")
        if (!rates) {
            foowwLocalStorage.set("rates", JSON.parse(data)['rate'].rates, new Date().getTime() + 15 * 60 * 60 * 1000)
        }
        if (localStorage.getItem('logged') <= 0) {
            localStorage.setItem('sync_status', '0');
            globalRender(data, 0, 'language')
        } else {
            if ((localStorage.getItem('sync_status') != 1) && (foowwLocalStorage.get('product') != null && foowwLocalStorage.get('product') != '')) {
                let products = foowwLocalStorage.get('product')
                for (let key in products) {
                    if (typeof (products[key].currency) == "undefined") {
                        products[key].currency = 'USD'
                    }
                }
                $.post("index.php?main_page=archive_cart_sync", {"products": JSON.stringify(products)}, function (data) {
                }).done(function () {
                    localStorage.setItem('sync_status', '1');// 1-->已同步
                    //localstorage的product相关数据改为同步完成后清空
                    localStorage.removeItem("product_id");
                    localStorage.removeItem("product");
                    globalRender(data, 1, 'language')
                })
            } else {
                globalRender(data, 1, 'language')
                if (url.search("checkout_payment") != -1 && url.search("order_id") == -1) {//结算页
                    selectedPayMethod(data)
                }
            }
        }
    })
}

/**
 * 在表单提交后,禁用提交按钮10s
 * @param formId 表单id名
 * @param btnId  提交按钮id名
 */
function disabledFormBtn(formId, btnId)
{
    $(`${formId}`).submit(function (e) {
        $(`${btnId}`).attr({disabled:"true",style:"cursor:not-allowed"})
        const timing = setTimeout(() => {
            $(`${btnId}`).removeAttr("disabled style")
        }, 10000);
    })
}