﻿(function () {
    $(document).ready(function () {
        $('#btn_Login_User').click(function () {
            if ($('#ownerSystem').val() == "") {
                redirect("../Login/Index");
            }
            else {
                var ls_url = of_clientDomXss($('#ownerSystem').val()) + "/Login/Index";
                redirect(ls_url);
            }
            return false;
        });
        $('#btn_Logout_User').click(function () {
            if ($('#ownerSystem').val() == "") {
                redirect("../Logout/Index");
            }
            else {
                var ls_url = of_clientDomXss($('#ownerSystem').val()) + "/Logout/Index";
                redirect(ls_url);
            }
            return false;
        });
        $('#btn_language').change(function () {

            $('<input>').attr({
                type: 'hidden',
                id: 'culture',
                name: 'culture',
                value: $('#btn_language').val()
            }).appendTo(document.forms[0]);

            $('<input>').attr({
                type: 'hidden',
                id: 'returnUrl',
                name: 'returnUrl',
                value: $('#returnUrl').val()
            }).appendTo(document.forms[0]);
            window.location.reload()
            //if ($('#ownerSystem').val() == "") {
            //    $(document.forms[0]).attr('action', "../Home/SetCulture");
            //}
            //else {
            //    $(document.forms[0]).attr('action', $('#ownerSystem').val() + "/Home/SetCulture");

            //}
            //javascript: $(document.forms[0]).submit();
        });
        $('#btn_ShoppingBag').click(function () {
            if ($('#ownerSystem').val() == "") {
                $(document.forms[0]).attr('action', "../ShoppingBag/Index");
            }
            else {
                $(document.forms[0]).attr('action', $('#ownerSystem').val() + "/ShoppingBag/Index");
            }
            javascript: $(document.forms[0]).submit();

            return false;
        });
        //// cookie policy
        //$('.fixed-gdpr').click(function () {
        //    $('.fixed-gdpr').hide();
        //    return false;
        //});
        //使用者按下查詢按鈕
        $('#btn_search').click(function () {
            if (of_checkErrorChar2($('#txt_search').val()) == false) {
                of_searchClick($('#txt_search').val(), true);
               // $('#txt_search').val("");
                of_searchShowAll($('#txt_search').val());
            }
            return false;
        });
        $('#txt_search').keydown(function (event) {
            if (event.which == 13) {
                if (of_checkErrorChar2($('#txt_search').val()) == false) {
                    of_searchHistory($('#txt_search').val(), $('#domain').val());
                  //  of_searchClick($('#txt_search').val(), true);
                   // $('#txt_search').val("");
                    of_searchShowAll($('#txt_search').val());
                }
                return false;
            }
           
        });
        $('#txt_search').keyup(function (event) {
            if (event.which != 13) {
                if (of_checkErrorChar2($('#txt_search').val()) == true) {
                    alertMsg(of_clientDomXss($('#MagCheckErrorChar').val()));
                    //alertMsg(($('#MagCheckErrorChar').val()));
                    m_return = false;
                }
                else {
                    of_searchClick($('#txt_search').val(), false);
                }
                return true;
            }
        });
        $.cookie("_shoppingHistory", "", { secure: true, path: "/", expires:10 });
        var ls_shoppingHistory = $.cookie("_shoppingHistory");
        if ((ls_shoppingHistory != "") && (ls_shoppingHistory != undefined)) {
            var li_qty = 0;
            var lo_sH = ls_shoppingHistory.split(',');
            for (var ls_shItem in lo_sH) {
                if (lo_sH[ls_shItem] != "") {
                    var lo_sHP = lo_sH[ls_shItem].split('*');
                    li_qty += parseInt(lo_sHP[2]);
                }
            }
            if (li_qty != 0) {
                $('.badge-info').html(li_qty.toString()); //顯示購物車數量   
            }
            $('#shoppingHistory').val(ls_shoppingHistory);
        }
    });

})();
function of_clientPotentialXss(as_value) {
       // 建立一個暫存的div元素，並使用text()將內容存成html編碼文字後再用html()取出
   // return as_value.replace(/</g, '&;lt;').replace(/>/g, '&;gt;');
   // var div = document.createElement('div');
   // div.appendChild(document.createTextNode(as_value));
  //  as_value= div.innerText;
    return as_value;
}
function of_owl_carousel2(as_object, as_attr) {
    as_value = $(as_object).attr(as_attr);
    return as_value;
}
function of_clientDomXss(as_href)
{
    var ls_href = encodeURI(as_href.replace(/#.*?$/, "").replace(/<[^>]*>/g, "").replace(/([\('\)])/g, "\\$1").replace(/ /g, "%20"));
    return(ls_href);
}
//語系切換中文 of_Client_DOM_XSS(window.location.href)
function of_cultureClick(kind, url)
{
    $('<input>').attr({
        type: 'hidden',
        id: 'culture',
        name: 'culture',
        value: kind
    }).appendTo(document.forms[0]);

    $('<input>').attr({
        type: 'hidden',
        id: 'returnUrl',
        name: 'returnUrl',
        value: url
    }).appendTo(document.forms[0]);
    //window.location.reload();
    if ($('#ownerSystem').val() == "") {
        $(document.forms[0]).attr('action', "../Home/SetCulture");
    }
    else {
        $(document.forms[0]).attr('action', $('#ownerSystem').val() + "/Home/SetCulture");

    }
    javascript: $(document.forms[0]).submit();
}
// value: of_Client_DOM_XSS(window.location.href)
function of_cookieAcceptClick( url) {

    $('<input>').attr({
        type: 'hidden',
        id: 'returnUrl',
        name: 'returnUrl',
        value: url
    }).appendTo(document.forms[0]);

    if ($('#ownerSystem').val() == "") {
        $(document.forms[0]).attr('action', "../Home/SetCookieAccept");
    }
    else {
        $(document.forms[0]).attr('action', $('#ownerSystem').val() + "/Home/SetCookieAccept");

    }
    //window.jxcsaoptIn();
    //console.log(window.jxcsaoptIn());
    javascript: $(document.forms[0]).submit();
}

//數字檢查
function of_check9Char(substring) {
    if (substring != "") {
        var noSpecialCharRegEx = /^[0-9.]+$/;
        if (noSpecialCharRegEx.test(substring)) {
            return false;
        } else {
            return true;
        }
    }
    else {
        return false;
    }        
}
//文數字檢查
function of_checkAz9Char(substring) {
    if (substring != "") {
        var noSpecialCharRegEx = /^[0-9a-zA-Z]+$/;
        if (noSpecialCharRegEx.test(substring)) {
            return false;
        } else {
            return true;
        }
    }else
    {
        return false;
    }
}
//文字檢查
function of_checkAzChar(substring) {
    if (substring != "") {
        var noSpecialCharRegEx = /^[ a-zA-Z]+$/;
        if (noSpecialCharRegEx.test(substring)) {
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}
//特殊字檢查  <>"'%;)(&+-:/
function of_checkErrorChar(substring) {
    if (substring != "") {
        var noSpecialCharRegEx = /[ <>"'%;)(&+-/\\:/]/;
        if (!noSpecialCharRegEx.test(substring)) {
            return false;
        }
        else {
            return true;
        }
    }
    else
    {
        return false;
    }
}
//特殊字檢查 <>"'%;)(&+-:/  (可空白)
function of_checkErrorChar2(substring) {
    if (substring != "") {
        var noSpecialCharRegEx = /[\\<>"'%;)(&+-/:/]/;
        if (!noSpecialCharRegEx.test(substring)) {
           
                return false;
           
        }
        else {
            return true;
        }
    }
    else
    {
        return false;
    }
}
//清除查詢記錄
function of_searchClear(domain) {
    var ls_path = "/";
  //  $(".search-list").html("");
    $('.list-chip > li').each(function () {
        $(this).remove();
    });
    $('.list-chip').parent().find('.title').hide();
    $('.search-area .func-tool').hide();
    $.cookie("_searchHistory", "", {
        expires: 10,           // Expires in 10 days

        path: ls_path,          // The value of the path attribute of the cookie
        // (Default: path of page that created the cookie).

        domain: domain, // The value of the domain attribute of the cookie
        // (Default: domain of page that created the cookie).

        secure: true          // If set to true the secure attribute of the cookie
        // will be set and the cookie transmission will
        // require a secure protocol (defaults to false).
    });
}
//查詢快捷
function of_searchClick(search, isEnter) {
    search = $.trim(search);
    var ls_url = "";
    if ($('#ownerSystem').val() == "") {
        ls_url = "../Search/of_ajaxList" ;
    }
    else {
        ls_url = $('#ownerSystem').val() + "/Search/of_ajaxList";
    }
    if (isEnter == true) {
        $("#modal_msg_loading").modal('show');//載入load畫面
        //最近搜尋紀錄(最多5個)
        of_searchHistory(search, $('#domain').val());
    }
    //blockUI();
    // $('#modal_msg_loading').modal('show');
    $.ajax({
        type: 'POST',
        url: ls_url,
        datatype: "json",
        contentType: "application/json;charset=utf-8",
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials(ajax回傳)
        },
        data: JSON.stringify({
            searchKey: search,
            language: $('#language').val()
        }),
        success: function (data) {
            var datams = $.parseJSON(data); //解析回傳資料json格式
            if (datams.return == true) {
                $(".search-list").html(datams.message);//把回傳的資料 加入網頁                                          
            }
            else {
                alertMsg(datams.message);
            }
            if (isEnter == true) {
                //最近搜尋紀錄(最多5個)
                of_searchHistory(search, datams.domain);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            // alert(XMLHttpRequest.status);
            //  alert(XMLHttpRequest.readyState);
            // alert(textStatus);
        },
        //執行完成之後要做什麼動作
        complete: function (XMLHttpRequest, textStatus) {
            if (isEnter == true) {
                $("#modal_msg_loading").modal('hide'); //關閉load畫面
            }
            // unblockUI();
            // $('#modal_msg_loading').modal('hide');
        }
    });
    return false;
}
//最近搜尋紀錄(最多5個)


function of_searchHistory(search, domain) {
    var ls_path = "/";
    var li_no = 0;
    var ls_sh = "";
    if (search != "") {
        $('.list-chip').parent().find('.title').hide();
      
        $('.list-chip > li').each(function () {
            var currentLiText = $(this).text(),
                showCurrentLi = currentLiText.indexOf(search) !== -1;
            if (showCurrentLi == true) {
                $(this).remove();
            }
            else {
                li_no++;
            }
            if (li_no > 4) {
                $(this).remove();
            }
        });
       
        ls_sh = "";
        $('.list-chip > li').each(function () {
            if (ls_sh != "") {
                ls_sh += "*";
            }
            ls_sh += $(this).text();
        });
        if (ls_sh != "") {
            ls_sh += "*";
        }
        ls_sh += search;
        $.cookie("_searchHistory", ls_sh, {
            expires: 10,           // Expires in 10 days

            path: ls_path,          // The value of the path attribute of the cookie
            // (Default: path of page that created the cookie).

            domain: domain, // The value of the domain attribute of the cookie
            // (Default: domain of page that created the cookie).

            secure: true          // If set to true the secure attribute of the cookie
            // will be set and the cookie transmission will
            // require a secure protocol (defaults to false).
        });
        var ls_shtemp = $.cookie("_searchHistory");
       
        if (ls_shtemp == undefined) {
            $.cookie("_searchHistory", ls_sh, {
                expires: 10,           // Expires in 10 days

                path: ls_path,          // The value of the path attribute of the cookie
                // (Default: path of page that created the cookie).

                domain: domain, // The value of the domain attribute of the cookie
                // (Default: domain of page that created the cookie).

                secure: true          // If set to true the secure attribute of the cookie
                // will be set and the cookie transmission will
                // require a secure protocol (defaults to false).
            });
        }
        
    }
    else {
        ls_sh = "";
        $('.list-chip > li').each(function () {
            if (ls_sh != "") {
                ls_sh += "*";
            }
            ls_sh += $(this).text();
        });
        if ((ls_sh != "") && ($.cookie("_searchHistory") == undefined))
        {
            $.cookie("_searchHistory", ls_sh, {
                expires: 10,           // Expires in 10 days

                path: ls_path,          // The value of the path attribute of the cookie
                // (Default: path of page that created the cookie).

                domain: domain, // The value of the domain attribute of the cookie
                // (Default: domain of page that created the cookie).

                secure: true          // If set to true the secure attribute of the cookie
                // will be set and the cookie transmission will
                // require a secure protocol (defaults to false).
            });
        }
    }

    ls_sh = $.cookie("_searchHistory");
    $('.list-chip').parent().find('.title').hide();
    $('.search-area .func-tool').hide();
    if (ls_sh == undefined) {
        ls_sh = "";
    }
    var lo_sh = ls_sh.split("*")
   
    $('.list-chip > li').each(function () {
        $(this).remove();
    });
    if (ls_sh != "") {
        $('.list-chip').parent().find('.title').show();
        $.each(lo_sh, function (index, value) {
            $('.list-chip').append('<li><a href="#"  onclick="javascript:of_searchClick(\'' + value + '\', true); Cel_HistoryItemClick( \'' + value + '\'); ">' + value + '</a></li>');
        });
        $('.search-area .func-tool').show();
    }
    if (search != "") {
       
    }
}
//顯示完整搜尋結果
function of_searchShowAll(searchKey) {
    if (searchKey == undefined) {
        $('<input>').attr({
            type: 'hidden',
            id: 'searchKey',
            name: 'searchKey',
            value: $('.list-chip li:eq(0)').text()
        }).appendTo(document.forms[0]);
    }
    else {
        $('<input>').attr({
            type: 'hidden',
            id: 'searchKey',
            name: 'searchKey',
            value: searchKey
        }).appendTo(document.forms[0]);
    }
    if ($('#ownerSystem').val() == "") {
        $(document.forms[0]).attr('action', "../Search/List");
    }
    else {
        $(document.forms[0]).attr('action', $('#ownerSystem').val() + "/Search/List");

    }
    javascript: $(document.forms[0]).submit();

    return false;
}

function redirect(url) {
    var ua = navigator.userAgent.toLowerCase(),
        isIE = ua.indexOf('msie') !== -1,
        version = parseInt(ua.substr(4, 2), 10);

    // Internet Explorer 8 and lower
    if (isIE && version < 9) {
        var link = document.createElement('a');
        link.href = url;
        document.body.appendChild(link);
        link.click();
    }

        // All other browsers can use the standard window.location.href (they don't lose HTTP_REFERER like Internet Explorer 8 & lower does)
    else {
        window.location.href = url;
    }
}
var getExplorer = (function () {
    var explorer = window.navigator.userAgent,
    compare = function (s) { return (explorer.indexOf(s) >= 0); },
    ie11 = (function () { return ("ActiveXObject" in window) })();
    if (compare("MSIE") || ie11) { return 'ie'; }
    else if (compare("Firefox") && !ie11) { return 'Firefox'; }
    else if (compare("Chrome") && !ie11) { return 'Chrome'; }
    else if (compare("Opera") && !ie11) { return 'Opera'; }
    else if (compare("Safari") && !ie11) { return 'Safari'; }
})()

function checkDefaultBrowse(url) {
    if (getExplorer == 'ie') {
        window.location.href = url;
    }  
}
// 鎖定畫面
function blockUI() {
    try {
        if ($('div.growlUI').length == 0) {
            $("Body").append('<div class="growlUI loop" style="cursor: default;"></div>');
        }
        $('div.growlUI').text("畫面載入中.請稍待!....");
        $.blockUI({
            message: $('div.growlUI'),
            fadeIn: 0,
            fadeOut: 0,
            //    timeout: 2000,
            showOverlay: true,
            centerY: false,
            async: true,
            css: {
                'font-size': '16px',
                width: '350px',
                top: '10px',
                left: '',
                right: '10px',
                border: 'none',
                padding: '5px',
                backgroundColor: '#444444',//'#000',
                '-webkit-border-radius': '10px',
                '-moz-border-radius': '10px',
                // 透明度
                opacity: 1,
                color: '#fff'
            },
            overlayCSS: {
                backgroundColor: '#EDEDED',
                opacity: 0.2,
                cursor: 'wait'
            }
        });
    } catch (e) {

        console.log(e);
    }
}
// 解除鎖定畫面
function unblockUI() {
    try {
        $.unblockUI();
    } catch (e) {
        console.log(e);
    }
}
//訊息顯示
function alertMsg(msg) {
    $('#txt_alert').html(decodeURI(msg));
    $("#modal_alert").modal('show');//載入load畫面
}
function alertMsgClear() {    
    $("#modal_alert").modal('hide');//關閉load畫面
   // $('.modal-backdrop').remove();
}
//訊息顯示並重新整理頁面
function alertMsgE(msg) {
    $('#txt_alertE').html(decodeURI(msg));
    $("#modal_alertE").modal('show');//載入load畫面
}
function alertMsgClearE() {
    $("#modal_alertE").modal('hide');//關閉load畫面
    window.location.replace($('#ownerSystem').val() + "/ShoppingBag/Index");
    // $('.modal-backdrop').remove();
}
//訊息顯示並重新整理頁面
function alertMsgC(msg) {
    $('#txt_alertC').html(decodeURI(msg));
    $("#modal_alertC").modal('show');//載入load畫面
}
function alertMsgClearC() {
    $("#modal_alertC").modal('hide');//關閉load畫面
    window.location.replace($('#ownerSystem').val() + "/ShoppingBag/Index");
    // $('.modal-backdrop').remove();
}

//查詢欄位失焦時觸發
function Cel_TextChange(e) {

    var ls_isCelebrus = $(e).attr("data-isCelebrus");
    if (ls_isCelebrus == "T") {
        var lo_targetObj = new Object();
        lo_targetObj.name = 'KeyWord';
        lo_targetObj.id = 'beSearchListInput';
        lo_targetObj.type = 'text';
        lo_targetObj.tagName = 'input';
        lo_targetObj.value = $(e).val();
        //if (window.jxcsaclick) {
        //    window.jxcsaclick(lo_targetObj);
        //}
        if (window.jxcsatextchange) {
            window.jxcsatextchange(lo_targetObj);
        }
        console.log("celebrus(product):targetName=" + $(e).val() + ',targetId=' + 'beSearchListInput')
    }
}

//點擊查詢下方"最近搜尋紀錄"
function Cel_HistoryItemClick(key) {

    var ls_isCelebrus = $('.list-chip').attr('data-iscelebrus');
    if (ls_isCelebrus == "T") {
        var lo_targetObj = new Object();
        lo_targetObj.name = key;
        lo_targetObj.id = 'beSearchListRecord';
        lo_targetObj.alt = '';
        lo_targetObj.tagName = '';
        if (window.jxcsaclick) {
            window.jxcsaclick(lo_targetObj);
        }
        console.log("celebrus(product):name=" + key + ',targetId=' + 'beSearchListRecord')
    }
}



//點擊查詢下方預覽
function Cel_ItemClick(e, key, ProductItem) {

    var ls_isCelebrus = $(e).attr("data-isCelebrus");
    if (ls_isCelebrus == "T") {
        var lo_targetObj = new Object();
        lo_targetObj.name = key + '_' + ProductItem;
        lo_targetObj.id = 'beSearchListItem';
        lo_targetObj.alt = '';
        lo_targetObj.tagName = '';
        if (window.jxcsaclick) {
            window.jxcsaclick(lo_targetObj);
        }
        //if (window.jxcsatextchange) {
        //    window.jxcsatextchange(lo_targetObj);
        // }
        console.log("celebrus(product):name=" + key + '_' + ProductItem + ',targetId=' + 'beSearchListItem');
    }
}

