//const zhTw = require("../../vendor/fullcalendar/locale/zh-tw");

(function ($, document) {
    (function ($) {
        $.UrlParam = function (name) {
            //宣告正規表達式
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            /*
             * window.location.search 獲取URL ?之後的參數(包含問號)
             * substr(1) 獲取第一個字以後的字串(就是去除掉?號)
             * match(reg) 用正規表達式檢查是否符合要查詢的參數
            */
            var r = window.location.search.substr(1).match(reg);
            //如果取出的參數存在則取出參數的值否則回穿null
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    if ($.cookie) {
        $.cookieKey = function (CookieName, KeyName, Value, Options) {
            var reg = new RegExp("(?:([^=]+)=([^&]*)&?)", "ig"),
                match = null,
                matches = [];
            var cookieVal = $.cookie(CookieName);
            while (match = reg.exec(cookieVal)) {
                if (KeyName.toLowerCase() == match[1].toLowerCase()) {
                    if (Value) { //we are updating, collect all values
                        matches.push([match[1], Value]);
                    }
                    else {
                        return match[2]; //we are getting, sub key found just return it
                    }
                }
                else if (Value) { //we are updating, collect all values
                    matches.push([match[1], match[2]]);
                }
            }

            if (Value) { //we are updating, update values
                updatedValue = "",
                    sep = "";
                for (i = 0; i < matches; i++) {
                    updatedValue += sep + matches[i][0] + "=" + matches[i][1];
                    sep = "&"
                }
                $.cookie(CookieName, updatedValue, Options);
            }
            else return null;//we are getting, value not found
        }
    }
})(jQuery, document);

// 對Date的擴充套件，將 Date 轉化為指定格式的String
// 月(M)、日(d)、小時(h)、分(m)、秒(s)、季度(q) 可以用 1-2 個佔位符，
// 年(y)可以用 1-4 個佔位符，毫秒(S)只能用 1 個佔位符(是 1-3 位的數字)
// 例子：
// (new Date()).format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).format("yyyy-M-d hⓜ️s.S")   ==> 2006-7-2 8:9:4.18
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小時
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

Date.prototype.addSeconds = function (seconds) {
    this.setSeconds(this.getSeconds() + seconds);
    return this;
}

Date.prototype.addMinutes = function (minutes) {
    this.setMinutes(this.getMinutes() + minutes);
    return this;
}

Date.prototype.addHours = function (hours) {
    this.setHours(this.getHours() + hours);
    return this;
}

Date.prototype.addDays = function (days) {
    this.setDate(this.getDate() + days);
    return this;
}

Date.prototype.addMonths = function (months) {
    this.setMonth(this.getMonth() + months);
    return this;
}

Date.prototype.addYears = function (years) {
    this.setFullYear(this.getFullYear() + years);
    return this;
}

function diffSeconds(milliseconds) {
    return Math.floor(milliseconds / 1000);
}

function diffMinutes(milliseconds) {
    return Math.floor(milliseconds / 1000 / 60);
}

function diffHours(milliseconds) {
    return Math.floor(milliseconds / 1000 / 60 / 60);
}

function diffDays(milliseconds) {
    return Math.floor(milliseconds / 1000 / 60 / 60 / 24);
}

function padding(num, length) {
    for (var len = (num + "").length; len < length; len = num.length) {
        num = "0" + num;
    }
    return num;
}

function clearChildren(element) {
    for (var i = 0; i < element.childNodes.length; i++) {
        var e = element.childNodes[i];
        if (e.tagName) switch (e.tagName.toLowerCase()) {
            case 'input':
                switch (e.type) {
                    case "radio":
                    case "checkbox": break;
                    case "hidden": e.value = ''; break;
                    case "button":
                    case "submit":
                    case "text": e.value = ''; break;
                    case "image": break;
                    default: if (e.type != "checkbox") { e.value = ''; }; break;
                }
                break;
            case 'select': e.selectedIndex = 0; break;
            case 'textarea': e.innerHTML = ''; break;
            default: clearChildren(e);
        }
    }

    $(element).children().find('textarea').each(function () {
        $(this).val('');
    });

    $(element).children().find('select').each(function () {
        $(this).prop('selectedIndex', 0);
    });
}



$(document).ready(function () {
    $('.modal').on("hidden.bs.modal", function (e) {
        clearChildren(this);
        if ($('.modal:visible').length) {
            $('.modal-backdrop').first().css('z-index', parseInt($('.modal:visible').last().css('z-index')) - 10);
            $('body').addClass('modal-open');
        }

        
    }).on("show.bs.modal", function (e) {
        if ($('.modal:visible').length) {
            $('.modal-backdrop.in').first().css('z-index', parseInt($('.modal:visible').last().css('z-index')) + 10);
            $(this).css('z-index', parseInt($('.modal-backdrop.in').first().css('z-index')) + 10);
        }
    });

    (function ($) {
        $.UrlParam = function (name) {
            //宣告正規表達式
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
            /*
             * window.location.search 獲取URL ?之後的參數(包含問號)
             * substr(1) 獲取第一個字以後的字串(就是去除掉?號)
             * match(reg) 用正規表達式檢查是否符合要查詢的參數
            */
            var r = window.location.search.substr(1).match(reg);
            //如果取出的參數存在則取出參數的值否則回穿null
            if (r != null) return unescape(r[2]); return null;
        }
    })(jQuery);

    

});

function logout() {

    if (confirm('確認要登出系統?')) {
        $.ajax({
            url: "/AuthApi/logout",
            type: "POST",
            data: null,
            success: function (data, textStatus, jqXHR) {
                if (data.ret == "yes") {
                    location.href = "/Home/Login";
                    //location.href = "/BackEnd/nounsList";

                } else {
                    alert(data.message);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert('網路或伺服器發生錯誤，請稍後重試!');
            }
        });
    }
    
}
String.prototype.isDate = function () {
    var p;
    var re1 = /(\d{4})[年./-](\d{1,2})[月./-](\d{1,2})[日]?$/;
    var re2 = /(\d{1,2})[月./-](\d{1,2})[日./-](\d{2})[年]?$/;
    var re3 = /(\d{1,2})[月./-](\d{1,2})[日./-](\d{4})[年]?$/;
    if (re1.test(this)) {
        p = re1.exec(this);
        return new Date(p[1], p[2], p[3]);
    }
    if (re2.test(this)) {
        p = re2.exec(this);
        return new Date(p[3], p[1], p[2]);
    }
    if (re3.test(this)) {
        p = re3.exec(this);
        return new Date(p[3], p[1], p[2]);
    }
    return "";
}

String.prototype.isDigit = function () {
    var s = this.Trim();
    return (s.replace(/\d/g, "").length == 0);
}

/*** 檢查是否由數字字母和下劃線組成 ***/
String.prototype.isAlpha = function () {
    return (this.replace(/\w/g, "").length == 0);
}

/*** 檢查是否為數 ***/
String.prototype.isNumber = function () {
    var s = this.Trim();
    return (s.search(/^[+-]?[0-9.]*$/) >= 0);
}

/*** 返回字節數 ***/
String.prototype.lenb = function () {
    return this.replace(/[^\x00-\xff]/g, "**").length;
}

/*** 檢查是否包含漢字 ***/
String.prototype.isInChinese = function () {
    return (this.length != this.replace(/[^\x00-\xff]/g, "**").length);
}

/*** 刪除首尾空格 ***/
String.prototype.Trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
const apiUrl = '' /*** 有值的話需要斜線結尾喔 **/

/*** 簡單的email檢查 ***/
String.prototype.isEmail = function () {
    var strr;
    var mail = this;
    var re = /(\w+@\w+\.\w+)(\.{0,1}\w*)(\.{0,1}\w*)/i;
    re.exec(mail);
    if (RegExp.$3 != "" && RegExp.$3 != "." && RegExp.$2 != ".")
        strr = RegExp.$1 + RegExp.$2 + RegExp.$3;
    else
        if (RegExp.$2 != "" && RegExp.$2 != ".")
            strr = RegExp.$1 + RegExp.$2;
        else
            strr = RegExp.$1;
    return (strr == mail);
}

function checkUrl(url) {
    var pattern = new RegExp('^(https?:\\/\\/)?' + // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain name
        '((\\d{1,3}\\.){3}\\d{1,3}))' + // OR ip (v4) address
        '(\\:\\d+)?(\\/[-a-z\\d@%_.~+]*)*' + // port and path
        '(\\?[;&a-z\\d@%_.~+=-]*)?' + // query string
        '(\\#[-a-z\\d@_]*)?$', 'i'); // fragment locator
    return !!pattern.test(url);
}

//數字處理為有千分位
function AppendComma(number) {
    var parts = number.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
function AppendComma2(n) {
    if (!/^((-*\d+)|(0))$/.test(n)) {
        var newValue = /^((-*\d+)|(0))$/.exec(n);
        if (newValue != null) {
            if (parseFloat(newValue, 10)) {
                n = newValue;
            }
            else {
                n = '0';
            }
        }
        else {
            n = '0';
        }
    }
    if (parseFloat(n, 10) == 0) {
        n = '0';
    }
    else {
        n = parseFloat(n, 10).toString();
    }

    n += '';
    var arr = n.split('.');
    var re = /(\d{1,3})(?=(\d{3})+$)/g;
    return arr[0].replace(re, '$1,') + (arr.length == 2 ? '.' + arr[1] : '');
}
//將有千分位的數值轉為一般數字
function RemoveComma(n) {
    return n.replace(/[,]+/g, '');
}
//調整千分位
function AdjustComma(item, length) {
    var originalValue = $.trim($(item).val()).length > length
        ? $.trim($(item).val()).substr(0, length)
        : $.trim($(item).val());

    $(item).val(AppendComma(originalValue));
}
//動態調整輸入欄位的長度
function TextAreaLength(item, length) {
    if (item.value.length > length) {
        item.value = item.value.substring(0, length);
    }
}

function thousands(value) {
    if (value) {
        value += "";
        var arr = value.split(".");
        var re = /(\d{1,3})(?=(\d{3})+$)/g;

        return arr[0].replace(re, "$1,") + (arr.length == 2 ? "." + arr[1] : "");
    } else {
        return ''
    }
}