///GLOBAL_VARIABLE///
var g_initiated_complete = false;
/*Data value and row separator*/
const g_sign_ok = "ok";
const g_sign_fail = "fa";
const g_sign_pageconfig = "pageconfig";
const g_sign_columnconfig = "columnconfig";
const gIdCombineChar = "_";
const g_retprefixok = "ok";
const g_showpricethousandask = true;
const g_moneyRoundBase = 100;
/*UI*/
var g_ui_cmdwidth = "40";
var g_ui_rowheight = "30";
var g_ui_expandsignwidth = "16";
var g_viewmode = 0;//0:mobile,1:desktop,2:tablet
var g_viewlayout = 0;//0: sub-right, main-left,1:sub-left, main-right
const g_pane_sub_width = 400;//do rong cua pane_sub
const g_pane_main_minwidth = 500;//do rong toi thieu cua pane_main
const g_viewmode_mobile = 600; //max width to mobile view mode, between is tablet
const g_viewmode_desktop = 900;//min-width to desktop view mode
/*Special char*/
const g_char_yes = "&#10003;";
const g_char_x = "&#x2715;";
const g_char_menu = "&#9783"
const g_colors = ['#04AA6D', '#f2f2f2'];
const g_char_rightarrow = "&#8594";
const g_char_leftarrow = "&#8592";
const g_char_uparrow = "&#8593";
const g_char_downarrow = "&#8595";
const g_char_enter = "&#8626";
const g_prefixlable_lang = "idvlang";
const g_charspace = "&nbsp;";
/*special id*/
const g_id_alertcount = "idglobalalertcount";
/*Window Tabs*/
var g_window_tabs = [];//content window tab contents (innerHTML of div tab)
var g_window_tabs_status = [];//content input value inside div tab
var g_window_page = "";//current div tab name
var g_window_pageparam = "";
var g_window_width = null;//chieu rong cua document gan day nhat
/*aray object wrap javascript function for each div - tab. Main page content multiple div - tab with the same function*/
var g_pageobj = [];

/*Modal dialog*/
var g_dlgstack = [];//chuoi cac modal dialog chong len nhau
var g_showmodalblock = false;
var g_showmodalblockresult = false;
var g_showmodalstart = null;
/*Data*/
var g_language = new Map();//
var g_data = [];
var g_jsloaded = "";
var g_cssloaded = "";
/*Status*/
var g_menubarfixeddata = "";
var g_waitstatusid = "";
var g_waitstatusimage = "";
var g_dropdownrect = null;
var g_dropdowndiv = null;
/*Scanner Camera*/
var g_scanner = null;
/*Speech*/
var SpeechRecognition = null;
let g_isRecording = false;
var g_speechIdInput = "";
var g_recognition = null;
var g_idButtonMic = "";
/****************************************************/
function isNative() {
    if (typeof ISHOPMANX === 'object' && ISHOPMANX !== null) {
        return true;
    }
    return false;

}
function setAppMode(val) {
    g_appmode = val;
}
//ishopmanxclient load
function isAppModeClient() {
    if (typeof (g_appmode) === "undefined") return false;
    return (g_appmode == 1);
}
function gCallInteropDone(ret, message) {
    if (ret == 0) {
        showMsg([itxt("thatbai"), message]);
    } else {
        if (!isEmpty(message))
            showMsg(message);
        else
            hideModalBlock();
    }
}
//Load UI	
//common function
function gCallInterop(message) {
    if (isAppModeClient()) g_sessionid = "101";
    if (isEmpty(g_sessionid)) {
        showMsg([itxt("loi"), itxt("khongxacdinhsesionid")], itxt("loi"), 1500);
        return;
    }
    if (typeof ISHOPMANX === 'object' && ISHOPMANX !== null) {

        ISHOPMANX.postMessage(g_sessionid + g_split_row + message);
    }
}
function gLoadUI() {
    var bwidemode = true;
    var obj = document.querySelector(".home");
    if (obj == null) {
        obj = document.getElementById("window_initpage");
    }
    if (obj == null) {
        obj = document.body;
    }
    bwidemode = obj.offsetWidth > g_viewmode_mobile;
    var iddivshow = "idpopupmenucompact";
    var iddivshowobj = document.getElementById(iddivshow);
    if (isEmpty(iddivshowobj)) {
        var htmldiv = "<div id=\"" + iddivshow + "\" class=\"dropdown-content\"></div>";
        $(htmldiv).appendTo(document.body).html(menuBuildPopup("idpopupmenucompact", bwidemode));
    } else {
        iddivshowobj.innerHTML = menuBuildPopup("idpopupmenucompact", bwidemode);
    }

    gLayout();
    //gLoadUI_SW();
    if (!isEmpty(g_homepage)) {
        window_newtab(g_homepage);
    }
}

function gLoadUI_SW() {
    //
    //console.log("service worker not use in dev");
    //return;
    // Registering Service Worker
    if ('serviceWorker' in navigator) {
        // Register a service worker hosted at the root of the
        // site using the default scope.
        navigator.serviceWorker.register('indexsw.js')
            .then(
                function (registration) {

                    console.log('Service worker ok :', registration);

                },
                /*catch*/
                function (error) {
                    console.log('Service worker fail:', error);
                }
            );
    }
    else {
        console.log('Service workers not support.');
    }
}

function getDocumentSize() {
    var w = window, d = document, e = d.documentElement, g = d.getElementsByTagName('body')[0];
    var x = w.innerWidth || e.clientWidth || g.clientWidth;
    var y = w.innerHeight || e.clientHeight || g.clientHeight;
    return { width: x, height: y }
}
function gLayout(bForce) {
    var size = getDocumentSize();
    if (isEmpty(g_window_width)) {
        g_window_width = size.width;
    } else {
        //khong thay doi chieu rong, khong resize lai
        if (g_window_width == size.width) {
            if (bForce != true) {
                return;
            }
        }
    }
    var home = document.querySelector(".home");
    if (isEmpty(home)) home = document.body;

    var scrollwidth = home.scrollHeight - home.clientHeight;
    if (scrollwidth > 0)
        scrollwidth = home.offsetWidth - home.clientWidth + 2;
    var newwidth = home.offsetWidth - g_pane_sub_width - scrollwidth - 1;

    g_viewmode = 0;
    if (home.clientWidth > g_viewmode_mobile) {
        if (home.clientWidth > g_viewmode_desktop)
            g_viewmode = 1;
        else
            g_viewmode = 2;
    }

    //menu full-compact
    var curWindowCount = getInnerById("window_tablistbutton");
    setInnerById("iddropdownmenubarmain", menuBuildMain(home.offsetWidth));
    setInnerById("window_tablistbutton", curWindowCount);
    //layout one/two column
    var floatmain = 'left', floatsub = 'right';
    if (g_viewlayout == 1) {
        floatmain = 'right';
        floatsub = 'left';
    }
    if (newwidth >= g_pane_main_minwidth) {
        $('.pane_main').css('width', 'calc(100% - ' + g_pane_sub_width + 'px').css('float', floatmain).css('margin', '0px').css('padding-bottom', '0px');
        $('.pane_sub').css('width', g_pane_sub_width + 'px').css('float', floatsub).css('margin', '0px').css('padding-bottom', '0px');
        $('.pane_bottom').css('width', '100%');
        $('.pane_block').css('width', '50%').css('float', 'left').css('margin', '0px');
    }
    else {
        $('.pane_main').css('width', '100%').css('float', floatmain).css('margin', '0px').css('padding-bottom', '0px');
        $('.pane_sub').css('display', 'block').css('float', floatsub).css('width', '100%').css('margin', '0px').css('padding-bottom', '0px');//tru khoang trong bottom
        $('.pane_bottom').css('width', '100%').css('left', '0px');
        $('.pane_block').css('width', '100%').css('float', 'left').css('margin', '0px');
    }
    //header
    gLayoutPageHeader();
}
//idpageheaderglobal la id cua div tren menubar
//idpageheaderlocal la id cua div nam trong page
//moi page co 1 div co id idpageheaderlocal de chua header che do full mode
//tieu de la link <a> khi click se refresh trang (co the confirm?)
function gLayoutPageHeader(bFullMode) {
    if (isEmpty(bFullMode)) bFullMode = false;
    var pageheader = window_tablistgetpagetitle(g_window_page, g_window_pageparam);
    if (isEmpty(pageheader)) pageheader = "iShopmanX";
    if (bFullMode) {
        var idpageheaderlocal = document.getElementById("idpageheaderlocal");
        if (!isEmpty(idpageheaderlocal)) {
            idpageheaderlocal.style.display = "block";
            idpageheaderlocal.innerHTML = "<a href='javascript:void(0)' onclick='window_refresh()'><span class='pageheader_title'>" + pageheader + "</span></a>" + idpageheaderlocal.innerHTML;
        }
    } else {
        setInnerById("idpageheaderglobal", "<a class='pageheader_title' href='javascript:void(0)' onclick='window_refresh()'>" + pageheader + "</a>");
        var idpageheaderlocal = document.getElementById("idpageheaderlocal");
        if (!isEmpty(idpageheaderlocal)) {
            idpageheaderlocal.style.display = "none";
        }
    }
}

//isrestore=0:show, <>0: restore
function showWaitStatus(isrestore = 1, idshow = null, imagerestore = null) {
    if (isrestore == 0) {
        var obj = document.getElementById(idshow);
        if (isEmpty(obj)) {
            g_waitstatusid = null;
            g_waitstatusimage = null;
            return;
        }
        g_waitstatusid = idshow;
        g_waitstatusimage = imagerestore;
        setBackgroundImageById(idshow, "imgs/bt_loading.gif");
    }
    else {
        if (isEmpty(g_waitstatusid)) return;
        setBackgroundImageById(g_waitstatusid, g_waitstatusimage);
        g_waitstatusid = null;
        g_waitstatusimage = null;
    }

}
/////////////////////
function getDataOk(recdata) {
    var nlensign = g_sign_ok.length;
    var nlendata = recdata.length;
    if (nlensign > nlendata)
        return "";
    if (recdata.substr(0, nlensign) != g_sign_ok)
        return "";
    return recdata.substr(nlensign, nlendata - nlensign);
}
function getDataFail(recdata) {
    var nlensign = g_sign_fail.length;
    var nlendata = recdata.length;
    if (nlensign > nlendata)
        return recdata;
    if (recdata.substr(0, nlensign) != g_sign_fail)
        return recdata;
    return recdata.substr(nlensign, nlendata - nlensign);
}
function increaseValById(idname, val_increase) {
    var val = getValById(idname);
    setValById(idname, parseInt(val) + val_increase);
}
function isDataFail(recdata) {
    var nlensign = g_sign_fail.length;
    var nlendata = recdata.length;
    if (nlensign > nlendata)
        return false;
    if (recdata.substr(0, nlensign) != g_sign_fail)
        return false;
    return true;
}
//item: char/num, listitem: item1,item2,item3..
function isItemInList(item, listitem) {
    if (isEmpty(item) || isEmpty(listitem)) return false;
    var items = listitem.split(",");
    for (var i = 0; i < items.length; i++) {
        if (item == items[i]) return true;
    }
    return false;
}
function isInAndroidApp() {
    if (typeof ISHOPMAN_APP_ANDROID === 'object' && ISHOPMAN_APP_ANDROID !== null)
        return true;
    return false;
}
function getDataSkipStartWith(data, start) {
    var nlensign = start.length;
    var nlendata = data.length;
    if (nlensign > nlendata)
        return "";
    if (data.substr(0, nlensign) != start)
        return "";
    return data.substr(nlensign, nlendata - nlensign);
}

function isDataStartWith(data, start) {
    if (data === undefined) return false; if (data === null) return false;
    var nlensign = start.length;
    var nlendata = data.length;
    if (nlensign > nlendata)
        return false;
    if (data.substr(0, nlensign) != start)
        return false;
    return true;
}

function isDataOk(recdata) {
    var nlensign = g_sign_ok.length;
    var nlendata = recdata.length;
    if (nlensign > nlendata)
        return false;
    if (recdata.substr(0, nlensign) != g_sign_ok)
        return false;
    return true;
}
function itxtLangParse(strContent) {
    var arLines = strContent.split('\n');

    var nPos = 0;
    var strKey, strVal;
    var nCount = 0;
    for (var i = 0; i < arLines.length; i++) {
        strVal = arLines[i];

        if (strVal.length == 0) continue;
        if (strVal.substring(0, 1) == ";") continue;

        nPos = arLines[i].indexOf(" "); //space

        if (nPos > 0) {
            strKey = arLines[i].substring(0, nPos).trim();
            strVal = arLines[i].substring(nPos + 1).trim();
            g_language.set(strKey, strVal);
        }
    }

}
//init: load language (success) -> load ui -> success -> lay out -> load event alert
function gInit(fnOnInitComplete) {

    if (g_language.size > 0) {
        return;
    }
    var url = "?page=initdata";
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                console.log("gInit-error");
                showMsg("Lỗi/Error!");
                return;
            }
            var vals = getDataOk(data).split(g_split_group);
            if (vals.length == 3) {
                itxtLangParse(vals[0]);
                //index.html
                if (typeof g_menubar_pin !== "undefined") {
                    var style = vals[1] + vals[2];
                    style = style.replaceAll("_ROWHEIGHT_", g_ui_rowheight + "px");
                    var styletag = document.createElement('style');
                    styletag.innerHTML = style;
                    document.head.appendChild(styletag);
                    gLoadUI();
                    window.addEventListener('resize', function (event) {
                        gLayout();
                    }, true);
                    //load script ishopmands.js only one time
                    //depend on g_viewmode
                    var script = document.createElement("script");  // create a script DOM node
                    script.src = "ishopmands.js";  // set its src to the provided URL
                    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
                }
                g_initiated_complete = true;
                if (typeof fnOnInitComplete !== "undefined") {
                    eval(fnOnInitComplete)();
                }
            } else {
                showMsg("Lỗi dữ liệu khởi tạo/ Error startup data!");
            }
        },
        error: function () {
            showMsg("Lỗi/Error!");
        }
    });
}
function itxt(key) {
    key = key.trim();
    if (g_language.has(key))
        return g_language.get(key);
    else
        return key;
}
function roundNumber(value, decimals) {
    if (typeof decimals === "undefined") decimals = 0;
    return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
function sleep(sleepDuration) {
    sleepDuration = 500;
    var now = new Date().getTime();
    while (new Date().getTime() < now + sleepDuration) {
        /* Do nothing */
    }
}
function arrayToStringAsList(ar) {
    if (Array.isArray(ar) != true) return "";
    var ret = "";
    for (var i = 0; i < ar.length; i++) {
        if (i > 0) ret += ",";
        if (Array.isArray(ar[i])) {
            ret += "[" + arrayToStringAsList(ar[i]) + "]";
        }
        else if (isEmpty(ar[i])) {
            ret += "''";
        } else {
            if (isString(ar[i]))
                ret += "'" + escapeJS(ar[i]) + "'";
            else
                ret += ar[i];
        }
    }
    return ret;
}
function addDaysToDate(date, days) {
    var result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
}
function formatDate(x) {
    return x.getDate() + "/" + x.getMonth() + "/" + x.getFullYear();
}
function getNumberNZ(x) {
    if (!x) return "";
    if (parseInt(x) == 0) return "";
    return x;
}
//x la number native
function formatNumber(x, zeroasemtpy) {
    if (!x) {
        if (zeroasemtpy) return "";
        return "0";
    }
    if (isNaN(x)) {
        if (zeroasemtpy) return "";
        return "0";
    }
    if (x == "0") {
        if (zeroasemtpy) return "";
        return "0";
    }
    x = roundNumber(x, 3);
    x = x.toString();
    x = x.replace(".", ",");
    return x.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
    //return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}
//x la number native
function formatNumberZS(x) {
    if (x == 0) return "";
    var ret = formatNumber(x, true);
    if (ret == "") return "";//&nbsp;
    return ret;
}
function parseNumber(x, defaultRet) {
    if (typeof (defaultRet) === "undefined") defaultRet = 0;
    var ret = Number(x);
    if (isNaN(ret)) {
        return defaultRet;
    }
    return ret;
}
//x la chuoi so kieu vn
function parseNumberVn(x) {
    if (x === undefined) return 0;
    if (x === null) return 0;
    if (x.length == 0) return 0;
    x = x.toString();
    x = x.replace(/\./g, "");
    x = x.replace(/ /g, "");
    x = x.replace(",", ".");
    var ret = Number(x);
    if (isNaN(ret)) { return 0; }
    return ret;
}
function parseDate(x) {
    if (x === undefined) return null;
    if (x.length < 3) return null;
    var vals = x.split("/");
    if (vals.length != 3) vals = x.split("-");
    if (vals.length != 3) return null;

    return new Date(vals[2], vals[1], vals[0]);
}
//chuoi html: & < > " '
function escapeHTML(x) {
    if (isEmpty(x)) return x;
    if (!isString(x)) return x;
    return x
        .replaceAll(/&/g, "&amp;")
        .replaceAll(/</g, "&lt;")
        .replaceAll(/>/g, "&gt;")
        .replaceAll(/"/g, "&quot;")
        .replaceAll(/'/g, "&#039;");
}

//chuoi js
function escapeJS(x) {
    if (isEmpty(x)) return x;
    if (!isString(x)) return x;
    x = x.replaceAll("'", "&#039;");
    x = x.replaceAll("\\", "\\\\");
    x = x.replace(/'/g, "\\\'");
    x = x.replace(/"/g, "\\\"");
    x = x.replace(/"/g, "\"");
    x = x.replace(/''/g, "\\\'\\\'");
    x = x.replace(/(?:\r\n|\r|\n)/g, '\\\r\\\n');
    //x = escape(x);
    return x;
}
//tao noi dung html bang JS, trong do se goi ham JS voi tham so
function escapeHtmlJs(x) {
    return escapeHTML(escapeJS(x));
}
function getCurDate() {
    var today = new Date();
    var dd = String(today.getDate()).padStart(2, '0');
    var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
    var yyyy = String(today.getFullYear());
    today = dd + '-' + mm + '-' + yyyy;
    return today.toString();
}
function getCurDateTime() {
    var now = new Date();
    return now.getHours() + ":" + now.getMinutes() + "' " + now.getDate().toString().padStart(2, "0") + "/" + (now.getMonth() + 1).toString().padStart(2, "0") + "/" + now.getFullYear();
}
/////////////////////
function errorAlert(s) {
    alert(s);
}
function execFn(fnNameString, fnParamArray) {
    var fn = eval(fnNameString);
    fn(fnParamArray);
}
function eleEnable(nameid, enable) {
    var ele = document.getElementById(nameid);
    if (isEmpty(ele)) return;
    if (enable)
        ele.disabled = false;
    else
        ele.disabled = true;
}
function eleShowHide(nameid, bshow) {
    var ele = document.getElementById(nameid);
    if (isEmpty(ele)) return;
    if (bshow)
        ele.style.display = "block";
    else
        ele.style.display = "none";
}
function ajaxOnReturn() {
    if (req.readyState == 4) { // Complete
        if (req.status == 200) {
            alert('please define local function ajaxOnReturn');
            //ajaxOnReturnOK(req.dataExtra,req.responseText);
        }
        else {
        }
    }
}
function ajaxGetURL(url, dataExtra, functionCallback) {
    //typeof functionCallback === 'undefined'
    functionCallback = functionCallback || ajaxOnReturn;

    if (window.XMLHttpRequest) { // Non-IE browsers & New IE
        req = new XMLHttpRequest();
        req.onreadystatechange = functionCallback;
        req.dataExtra = dataExtra;
        try {

            req.open("GET", url, true);
            req.setRequestHeader("Cache-Control", "no-cache");
            req.setRequestHeader("Pragma", "no-cache");
            req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
        }
        catch (e) {
            alert(e);
        }
        req.send(null);
    }
    else if (window.ActiveXObject) { // OLD IE
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.dataExtra = dataExtra;
            req.onreadystatechange = ajaxOnReturn;
            req.open("GET", url, true);
            req.send();
        }
    }
}
function genIdRow(id, source_data) {
    return "idrow" + source_data + "_" + id;
}
function genIdCombine(id1, id2) {
    return id1 + gIdCombineChar + id2;
}
function getInnerById(id) {
    var obj = document.getElementById(id);
    if (obj === null)
        return "";
    else
        return obj.innerHTML;
}
function getFirstCharOfWords(strWords, maxReturnChars) {
    var nLen = strWords.length;
    var nI = 0;
    var strRet = "";
    while (nI < nLen) {
        strRet += strWords.substr(nI, 1);
        if (!isEmpty(maxReturnChars)) {
            if (strRet.length >= maxReturnChars) return strRet;
        }
        nI = strWords.indexOf(" ", nI + 1);
        if (nI < 0) break;
        //co the co khieu khoang trong giua 2 tu
        nI++;
        while (nI < nLen) {
            if (strWords.substr(nI, 1) == " ") nI++;
            else
                break;
        }
    }
    return strRet;
}
function getId(nameorid) {
    if (isString(nameorid))
        return document.getElementById(nameorid);
    else
        return nameorid;
}
function getIdEle(id, prefix) {
    return "idele" + prefix + id;
}

function getValById(id) {
    var obj = document.getElementById(id);
    if (obj === null)
        return "";
    else
        return obj.value;
}
function setWidthById(id, percent) {
    var obj = document.getElementById(id);
    if (obj === null)
        return;
    obj.style.width = percent;
}
function setOuterById(id, val) {
    var obj = document.getElementById(id);
    if (obj === null)
        return;
    else {
        if (val === undefined)
            obj.outerHTML = "";
        else
            obj.outerHTML = val;
    }
}
function setInnerById(id, val) {
    var obj = document.getElementById(id);
    if (obj === null)
        return;
    else {
        if (val === undefined)
            obj.innerHTML = "";
        else
            obj.innerHTML = val;
    }
}

function setNumById(id, number) {
    var obj = document.getElementById(id);
    if (obj === null)
        return;
    else {
        if ((number === undefined) || (number == null))
            obj.value = "";
        else if (number == "")
            obj.value = "";
        else if (number == "0")
            obj.value = "";
        else
            obj.value = number;
    }
}
function setInputPlaceholder(idinput, strText) {
    var input = document.getElementById(idinput);
    if (isEmpty(input)) return;
    input.value = "";
}
function setFocus(idstring) {
    var obj = document.getElementById(idstring);
    if (obj === null)
        return;
    else {
        obj.focus();
    }
}
function setBackgroundImageById(id, urlimage) {
    var obj = null;
    if (isString(id))
        obj = document.getElementById(id);
    else
        obj = id;
    if (isEmpty(obj)) return;
    obj.style.backgroundImage = "url(" + urlimage + ")";
}
function setTitleById(id, val) {
    var idele = document.getElementById(id);
    if (idele == null) return;
    idele.title = val;
}
function setPlaceholderById(id, val) {
    var idele = document.getElementById(id);
    if (idele == null) return;
    idele.placeholder = val;
}
function setValChangeById(idstr, intchange, intmin) {
    var obj = document.getElementById(idstr);
    if (isEmpty(obj)) return;
    var curVal = parseNumberVn(obj.value);
    curVal += parseNumberVn(intchange);
    if (!isEmpty(intmin)) {
        if (curVal < parseNumberVn(intmin)) curVal = parseNumberVn(intmin);
    }
    obj.value = curVal;
}
function setValById(id, val) {
    var obj = document.getElementById(id);
    if (obj === null)
        return;
    else {
        if ((val === undefined) || (val == null))
            obj.value = "";
        else
            obj.value = val;
    }
}
function getSelectVal(selectid) {
    var selectobj = document.getElementById(selectid);
    if (selectobj === null)
        return 0;
    else
        return selectobj.value;
}
function getSelectText(selectid) {
    var selectobj = null;
    if (isString(selectid))
        selectobj = document.getElementById(selectid);
    else
        selectobj = selectid;
    if (selectobj === null)
        return "";
    var text = "";
    if (selectobj.selectedIndex !== null)
        text = selectobj.options[selectobj.selectedIndex].text;
    return text;
}
function selectShowDropDown(idselect) {
    var obj = document.getElementById(idselect);
    obj.size = 5;
}
function selectHideDropDown(idselect) {
    var obj = document.getElementById(idselect);
    obj.size = 1;
}
function selectItemByValue(selectid, value) {
    var selectobj = document.getElementById(selectid);

    if (!isEmpty(selectobj)) selectobj.value = value;
}
function setActiveControlText(text) {
    document.activeElement.value = text;
}
//val: chuoi da dinh dang vn
function strZeroAsEmpty(val) {
    if (val == "0") return "";
    if (!isString(val)) return val;
    var sign = "";
    if (val.substr(0, 1) == "-") {
        sign = "-";
        val = val.substr(1);
    }
    if (parseNumberVn(val) == 0) return "";
    return sign + val;
}
function strIfEmpty(testval, retifempty) {
    if (isEmpty(testval)) return retifempty;
    return testval;
}
function strBool(boolval) {
    if (boolval) return "1";
    return "0";
}
function strChecked(val) {
    if (isEmpty(val)) return "";
    if (val == true) return " checked ";
    return "";
}
function strSelected(val1, val2) {
    if (isEmpty(val1) && isEmpty(val2)) return " selected";
    if (val1 == val2)
        return " selected";
    return "";
}
function uriEncode(text) {
    if (isEmpty(text)) return "";
    if (text.constructor.name !== "String") text = text.toString();
    text = text.replaceAll("&", "%26");
    text = text.replaceAll("@", "%40");
    text = text.replaceAll("%", "%25");
    text = text.replaceAll("#", "%23");
    text = text.replaceAll("+", "%2B");
    text = text.replaceAll("=", "%3D");
    return text;
}
function isString(x) {
    if (x === undefined) return false;
    if (x === null) return false;
    if (x.constructor.name === "String")
        return true;
    return false;
}
function isVisiableKeyCode(keycode) {

    var valid =
        (keycode > 47 && keycode < 58) || // number keys
        (keycode == 32) || // spacebar & return key(s) (if you want to allow carriage returns)
        (keycode > 64 && keycode < 91) || // letter keys
        (keycode > 95 && keycode < 112) || // numpad keys
        (keycode > 185 && keycode < 193) || // ;=,-./` (in order)
        (keycode > 218 && keycode < 223) || // [\]' (in order)
        (keycode > 128);

    return valid;

}
function isScrollBarVisible() {
    if (document.scrollHeight > document.innerHeight)
        return false;
    return true;

}

//detect if element inside container is visible
function isEleVisible(elementSelector, containerSelector) {
    var rcele = elementSelector.getBoundingClientRect();
    var rccon = containerSelector.getBoundingClientRect();
    if ((rcele.top >= rccon.top) && (rcele.bottom <= rccon.bottom) && (rcele.left >= rccon.left) && (rcele.right <= rccon.right))
        return true;
    return false;
}

function isEmpty(value) {
    if (typeof (value) === 'undefined') return true;
    return (value === null || value === '');
}
function isObject(value) {
    return (typeof value === 'object' && value !== null);
}
/***************************************CONTROL******/

/*****************************MODAL DIALOG*************************/
function showMsg(msg, header, autohideaftermiliseconds, modalWidth, bShowError) {
    eleShowHide("myModalHeadShare", false);
    eleShowHide("myModalHeadCopy", false);
    var myModalHead = document.getElementById("myModalHead");
    myModalHead.style.width = "calc(100% - 36px)";
    //xoa cho hien thi wait modal
    g_modalblock_startwait = "";

    if (isEmpty(modalWidth)) {
        if (g_viewmode)
            modalWidth = "600px";
        else
            modalWidth = "96%";
    }

    var msgShow = msg;
    //tach array msg
    if (Array.isArray(msg)) {
        msgShow = '';
        for (i = 0; i < msg.length; i++) {
            if (msgShow.length > 0) msgShow += "<br>";
            msgShow += msg[i];
        }
    }
    if (bShowError) {
        msgShow = "<font color='red'>" + msgShow + "</font>";
    }
    g_showmodalblock = false;
    myModalHead = document.getElementById("myModalHead");
    if (typeof header !== 'undefined')
        myModalHead.innerHTML = header;
    else
        myModalHead.innerHTML = "iShopmanX";
    var modal = document.getElementById('myModal');
    var myModalContent = document.getElementById("myModalContent");
    myModalContent.innerHTML = "<div style='padding:8px;width:100%;-moz-box-sizing:border-box;box-sizing:border-box;text-align:center'>" + msgShow + "</div>";
    myModalContent.style.paddingTop = "32px";
    modal.style.display = "block";




    var modalClient = document.getElementById("myModalClient");
    modalClient.style.width = modalWidth;

    if (!isEmpty(autohideaftermiliseconds)) {
        autohideaftermiliseconds = parseNumberVn(autohideaftermiliseconds);

        if (autohideaftermiliseconds > 5000) autohideaftermiliseconds = 5000;
        g_showmodalstart = Date.now();

        setTimeout(showMsgHide, autohideaftermiliseconds, g_showmodalstart);
    }
}
function showMsgHide(timestart) {
    if (timestart == g_showmodalstart) {
        g_showmodalstart = null;
        hideModal();
    }
}
function setModalHeading(heading) {
    myModalHead = document.getElementById("myModalHead");
    myModalHead.innerHTML = heading;
}
function showModalBlock(msg, header, idfocus, execscriptinsidehtml) {
    //xoa cho hien thi wait modal
    g_modalblock_startwait = "";

    if (typeof header === 'undefined') header = "iShopmanOS";
    myModalHead = document.getElementById("myModalHead");
    myModalHead.innerHTML = header;
    g_showmodalblock = true;
    var modal = document.getElementById('myModal');
    var myModalContent = document.getElementById("myModalContent");
    myModalContent.innerHTML = msg;
    myModalContent.style.top = "0px";
    modal.style.display = "block";
    if (!isEmpty(idfocus)) {
        document.getElementById(idfocus).focus();
    }
    if (execscriptinsidehtml !== undefined) {
        var arr = myModalContent.getElementsByTagName('script')
        for (var n = 0; n < arr.length; n++)
            eval(arr[n].innerHTML)//run script inside div
    }
}
function hideModalBlock(result) {
    g_showmodalblockresult = result;
    g_showmodalblock = false;
    hideModal();
}
function showModalBlockEnd(result, functionCallback) {
    g_showmodalblockresult = result;
    g_showmodalblock = false;
    hideModal();

    if (!isEmpty(functionCallback))
        functionCallback();
}
//dat vao che do cho hien thi
//sau thoi gian neu xong roi thi o dau do call hideModal -> tat trang thai can hien thi
//neu van con can  hien thi thi se hien thi
var g_modalblock_startwait = "";
function showWaitModal(block, lateshowmiliseconds, title) {
    if (isEmpty(lateshowmiliseconds)) lateshowmiliseconds = 0;
    g_modalblock_startwait = Date.now();
    //document.body.style.cursor = "wait";
    if (block == 1 || block == true) { } else {
        if (lateshowmiliseconds == 0) lateshowmiliseconds = 500;
    }
    setBackgroundImageById("idpageheaderlocal", "/imgs/bt_loading.gif");
    setTimeout(showWaitModalDo, lateshowmiliseconds, g_modalblock_startwait, block, title);
}
function showWaitModalDo(startwait, block, title) {
    if (g_modalblock_startwait != startwait) {
        g_modalblock_startwait = "";
        return;
    }
    var content = "<div style='width:100%;justify-content:center;align-items:center;height:auto;display:flex;padding:24px;overflow-y:auto; -moz-box-sizing: border-box;box-sizing: border-box;'>" +
        "<div id=\"loading-spinner\"></div><p id=\"loading-text\">Đang xử lý...</p></div>";
    //var content = "<div style='width:100%;text-align:center;'><p>Đang xử lý...</p><img src='imgs/bt_loading.gif' style='float:center'></div>";
    if (isEmpty(title)) title = "::";
    if (block == 1 || block == true)
        showModalBlock(content, title);
    else
        showModal(content, title, null, "400px");

}
function showModalCaption(caption) {
    var myModalHead = document.getElementById("myModalHead");
    myModalHead.innerHTML = caption;
}
function isVisiable(idelename) {
    var ele = document.getElementById(idelename);
    if (isEmpty(ele)) return false;
    if (isEmpty(ele.style)) return false;
    if (ele.style.display == "block") return true;
    return false;
}
function isModalVisible() {
    var modal = document.getElementById('myModal');
    if (modal === null)
        return false;
    return (modal.style.display == "block");
}
function showModalUpdateHeader(header) {
    setInnerById("myModalHead", header);
}
//modalWidth: "80%","100px"
function showModal(msg, header, execscriptinsidehtml, modalWidth, bshowshare) {
    var modal = document.getElementById('myModal');
    if (typeof modal === 'undefined') return;//call before load
    var myModalHead = document.getElementById("myModalHead");
    if (typeof myModalHead === 'undefined') return;//call before load

    if (isEmpty(modalWidth)) {
        if (g_viewmode)
            modalWidth = "80%";
        else
            modalWidth = "96%";
    }
    if (g_viewmode == 0) modalWidth = "96%";
    //xoa cho hien thi wait modal
    g_modalblock_startwait = "";
    g_showmodalblock = false;
    if (header === undefined) header = "iShopmanX";
    if (typeof header !== 'undefined')
        myModalHead.innerHTML = header;
    else
        myModalHead.innerHTML = "iShopmanX";
    var modalClient = document.getElementById("myModalClient");
    var myModalContent = document.getElementById("myModalContent");
    if (g_viewmode)
        modalClient.style.width = modalWidth;
    else
        modalClient.style.width = modalWidth;

    var myModalHeadShare = document.getElementById("myModalHeadShare");
    var myModalHeadCopy = document.getElementById("myModalHeadCopy");
    if (bshowshare) {
        myModalHeadShare.style.display = "block";
        myModalHeadCopy.style.display = "block";
        myModalHead.style.width = "calc(100% - 108px)"
    } else {
        myModalHeadShare.style.display = "none";
        myModalHeadCopy.style.display = "none";
        myModalHead.style.width = "calc(100% - 36px)"
    }
    myModalHead.style.overflow = "hidden";
    myModalHead.style.whiteSpace = "nowrap";
    myModalHead.style.textOverflow = "ellipsis";

    //myModalContent.style.top="100px";
    myModalContent.innerHTML = msg;
    modal.style.display = "block";

    if (execscriptinsidehtml !== undefined) {
        var arr = myModalContent.getElementsByTagName('script')
        for (var n = 0; n < arr.length; n++)
            eval(arr[n].innerHTML)//run script inside div
    }
}

function hideModal() {
    g_modalblock_startwait = "";
    if (g_showmodalblock == true)
        return;
    var modal = document.getElementById('myModal');
    modal.style.display = "none";
}


/*****************************END-MODAL*************************/
/*********************************MENU********************/
/*Hide all popup menu if show*/
function window_menuhide(iddivshowcurrent) {
    var dropdowns = document.getElementsByClassName("dropdown-content");
    var i;
    for (i = 0; i < dropdowns.length; i++) {
        var openDropdown = dropdowns[i];
        if ((!isEmpty(iddivshowcurrent)) && (openDropdown.id == iddivshowcurrent.id))
            continue;
        openDropdown.style.display = "none";
    }
}
/* When the user clicks on the button, toggle between hiding and showing the dropdown content */
function window_menushow(iddivshow) {
    if (!isObject(iddivshow))
        iddivshow = document.getElementById(iddivshow);
    if (isEmpty(iddivshow)) return;
    if (isEmpty(iddivshow.style)) return;
    window_menuhide(iddivshow);
    if (iddivshow.style.display != "block") {
        iddivshow.style.display = "block";
        iddivshow.style.width = iddivshow.parentElement.style.width;
        iddivshow.style.zIndex = 1;
        //$(iddivshow).appendTo(document.body);
    }
    else {
        iddivshow.style.display = "none";
    }
}

/*********************************WINDOW TAB********************/
function window_tablistgetpagetitle(page, param = "") {
    var itemtext = "";
    var i = 0;
    var nitem = g_menubar_popup_items.length - 1;
    while (i < nitem) {
        if (g_menubar_popup_items[i + 2] == page) {
            itemtext = g_menubar_popup_items[i + 3];
            break;
        }
        i += 4;
    }
    if (itemtext.length <= 0)
        itemtext = itxt(page);
    if (param.length > 0) {
        var suffix = param.replaceAll("invoice_id=", "");
        itemtext += " [" + suffix + "]";
    }
    return itemtext;
}
function window_tablistadd(page, param = "") {
    var itemtext = window_tablistgetpagetitle(page, param);
    if (itemtext.length < 1)
        return;
    var iddropdownwindowtablist = document.getElementById("iddropdownwindowtablist");
    var pagekey = window_getKey(page, param);
    var htmlitem = "<div id=\"windowtablist" + pagekey + "\" class=\"divtablist\">";
    htmlitem += "<div class=\"divtablisttitle\" onclick=\"window_newtab('" + page + "','" + param + "')\">" + itemtext + "</div>";
    htmlitem += "<div class=\"divtablistbuttonclose\" onclick=\"window_tablistclose('" + page + "','" + param + "')\">&times;</div>";
    htmlitem += "</div>";

    iddropdownwindowtablist.innerHTML += htmlitem;

    window_tablistactive(page, param);
    var window_tablistbutton = document.getElementById("window_tablistbutton");
    if (isEmpty(window_tablistbutton)) return;
    var cur = parseNumberVn(window_tablistbutton.innerHTML);
    if (cur < 0) cur = 0;
    cur = cur + 1;
    window_tablistbutton.innerHTML = cur;
}
function window_tablistactive(page, param = "") {
    var pagekey = window_getKey(page, param);
    var tablistitem = document.getElementsByClassName("divtablist focus");
    for (i = 0; i < tablistitem.length; i++) {
        tablistitem[i].classList = "divtablist";
    }
    var tablistitemcur = document.getElementById("windowtablist" + pagekey);
    if (!isEmpty(tablistitemcur))
        tablistitemcur.classList = "divtablist focus";
    gLayoutPageHeader();
}
function window_tablistclose(page, param = "") {
    var pagekey = window_getKey(page, param);
    var curpagekey = window_getKey(g_window_page, g_window_pageparam);

    var window_tablistbutton = document.getElementById("window_tablistbutton");
    var cur = parseNumberVn(window_tablistbutton.innerHTML);
    cur = cur - 1;
    if (cur < 0) cur = 0;
    window_tablistbutton.innerHTML = cur;


    document.getElementById("windowtablist" + pagekey).remove();
    if (g_window_tabs[pagekey]) {
        delete g_window_tabs[pagekey];
    }
    if (g_window_tabs_status[pagekey]) {
        delete g_window_tabs_status[pagekey];
    }
    if (pagekey == curpagekey) {
        g_window_page = "";
        g_window_pageparam = "";
        var pageclose = document.getElementById("window_" + curpagekey);
        if (pageclose)
            pageclose.remove();
    }
    else
        return;
    //xem con tab nao hay khong
    var bhas = false;
    for (pagekey in g_window_tabs) {
        window_showpage(pagekey);
        window_tablistactive(pagekey);
        bhas = true;
        break;
    }
    //neu khong con tab nao
    if (bhas == false) {
        g_window_page = "";
        g_window_pageparam = "";
        var pageclose = document.getElementById("window_" + pagekey);
        if (pageclose)
            pageclose.remove();
    }
    gLayoutPageHeader();
}
//Get status value of input inside div
function window_formToString(filledForm) {
    formObject = new Object;
    filledForm.find("input, select, textarea").each(function () {
        if (this.id) {
            elem = $(this);
            if (elem.attr("type") == 'checkbox' || elem.attr("type") == 'radio') {
                formObject[this.id] = elem.attr("checked");
            } else {
                formObject[this.id] = elem.val();
            }
        }
    });
    formString = JSON.stringify(formObject);
    return formString;
}
//Restore input value status inside div
function window_stringToForm(formString, unfilledForm) {
    if (isEmpty(formString))
        return;
    if (unfilledForm === null)
        return;
    formObject = JSON.parse(formString);
    unfilledForm.find("input, select, textarea").each(function () {
        if (this.id) {
            id = this.id;
            elem = $(this);
            if (elem.attr("type") == "checkbox" || elem.attr("type") == "radio") {
                elem.attr("checked", formObject[id]);
            } else {
                elem.val(formObject[id]);
            }
        }
    });
}
function window_refresh() {
    //var ret=confirm(itxt("naplaisemathetdulieudangnhap"));
    //if(ret===false)return;

    window_menuhide();
    if (isEmpty(g_window_page))
        return;
    showWaitModal();
    ajaxGetURL("/?page=" + g_window_page + "&" + g_window_pageparam, "window_refresh" + g_split_val + g_window_page + g_split_val + g_window_pageparam, window_ajaxOnReturn);
}
function window_showpage(page, param = "") {

    var pagekey = window_getKey(page, param);
    if ((g_window_page == "") && (page != "")) {
        var pagecur = document.getElementById("window_initpage");
        if (!isEmpty(pagecur))
            pagecur.remove();
    }
    var curpagekey = window_getKey(g_window_page, g_window_pageparam);

    //neu trung voi hien tai, bo qua
    if (pagekey == curpagekey)
        return;

    //save current tab
    if (g_window_page.length > 0) {
        var pagecur = document.getElementById("window_" + curpagekey);

        g_window_tabs[curpagekey] = pagecur.innerHTML;
        g_window_tabs_status[curpagekey] = window_formToString($("#window_" + curpagekey));
        pagecur.remove();
    }
    g_window_page = page;
    g_window_pageparam = param;
    var htmldiv = "<div id='window_" + pagekey + "' class='home'></div>";//class="divtab"
    $(htmldiv).appendTo(document.body).html(g_window_tabs[pagekey]).fadeIn('fast');
    window_stringToForm(g_window_tabs_status[pagekey], $("#window_" + pagekey));
}
function window_showpagecurrentcontent(value) {
    if (g_window_page.length < 1)
        return;
    var curpagekey = window_getKey(g_window_page, g_window_pageparam);
    var pagecur = document.getElementById("window_" + curpagekey);
    pagecur.innerHTML = value;
}
function window_getKey(page, param = "") {
    if (param == "") return page;
    param = param.replaceAll("=", "");
    param = param.replaceAll("+", "");
    param = param.replaceAll("-", "");
    param = param.replaceAll("x", "");
    param = param.replaceAll(":", "");
    return page + param;
}
//same page same tab, if other param open other tab
//data give to page
function window_newtab(page, param = "", data = "") {
    if (page == "ht_dangxuat") {
        window.open("?page=ht_dangxuat", "_self");
        return false;
    }
    if (isEmpty(g_window_tabs[window_getKey(page, param)])) {
        showWaitModal();
        //ajaxGetURL("?page=" + page + "&action=search&" + param + data, "window_newtab" + g_split_val + page + g_split_val + param, window_ajaxOnReturn);
        ajaxGetURL("?page=" + page + "&" + param + data, "window_newtab" + g_split_val + page + g_split_val + param, window_ajaxOnReturn);
    }
    else {
        window_showpage(page, param);
        window_tablistactive(page, param);
    }
}
function window_newtabreceive(page, value, param) {
    hideModal();
    g_window_tabs[window_getKey(page, param)] = value;
    window_showpage(page, param);
    window_tablistadd(page, param);
}
function window_showrefresh(page, value, param = "") {
    hideModal();
    var pagekey = window_getKey(page, param);
    var curpagekey = window_getKey(g_window_page, g_window_pageparam);

    if (g_window_page.length < 1)
        return;
    if (pagekey != curpagekey)
        return;

    var pagecur = document.getElementById("window_" + curpagekey);
    pagecur.remove();

    g_window_tabs[curpagekey] = value;
    g_window_tabs_status[curpagekey] = "";

    var htmldiv = "<div id='window_" + curpagekey + "' class='home'></div>";
    $(htmldiv).appendTo(document.body).html(g_window_tabs[curpagekey]).fadeIn('fast');
    gLayoutPageHeader();
    gLayout();
}
function window_ajaxOnReturn() {
    //trang thai: 1->2, neu khong thanh cong bi mat mang hay server down se khong toi 3-4
    if (req.readyState == 4) {
        if (req.status == 200) {
            var arparams = req.dataExtra.split(g_split_val);
            if (arparams.length == 3) {
                if (arparams[0] == "window_newtab")
                    window_newtabreceive(arparams[1], req.responseText, arparams[2]);
                else if (arparams[0] == "window_refresh")
                    window_showrefresh(arparams[1], req.responseText, arparams[2]);
                else
                    hideModal();
            }
        }
    }
    // Network error (i.e. connection refused, access denied due to CORS, etc.)
    else if (req.readyState == 0) {

    }
    else {

    }
}
//******************************************************************************************************************/
//common function
function gViewContactInfo(contact_id) {
    showWaitModal();
    var url = "?page=list_details&pagesub=contact";
    var dataString = "contact_id=" + contact_id;

    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            hideModal();
            showMsg(data, "Xem đối tác");
        },
        error: function () {
            hideModal();
            showMsg(itxt("thatbai"), "Xem đối tác");
        }
    });
    return false;
}
function clone(obj) {
    var copy;
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;
    // Handle Date
    if (obj instanceof Date) {
        copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }
    // Handle Array
    if (obj instanceof Array) {
        copy = [];
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }
    // Handle Object
    if (obj instanceof Object) {
        copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }
    throw new Error("Unable to copy obj! Its type isn't supported.");
}
function cloneArrayObj(arrObj) {
    var newarr = Array.from(arrObj);
    for (var i = 0; i < arrObj.length; i++) {
        newarr[i] = clone(arrObj[i]);
    }
    return newarr;
}
function divToggle(idheader, idcontent, fnCallBack, fnCallBackParamArray) {

    var eleHeader = document.getElementById(idheader);
    if (isEmpty(eleHeader)) return;
    eleHeader.classList.toggle("active");
    eleContent = document.getElementById(idcontent);
    if (isEmpty(eleContent)) return;
    if ((eleContent.style.display == "block") || ((eleContent.className == "collapsiblecontentexpand") && (isEmpty(eleContent.style.display)))) {
        eleContent.style.display = "none";
    }
    else {
        eleContent.style.display = "block";
        if (!isEmpty(fnCallBack)) {
            execFn(fnCallBack, fnCallBackParamArray);
        }
    }
}

function divToggleNext(ele, functionCallback) {
    //var ele = document.getElementById(elementId);
    if (isEmpty(ele))
        return;
    ele.classList.toggle("active");
    ele = ele.nextElementSibling;
    if (isEmpty(ele))
        return;
    if ((ele.style.display == "block") || ((ele.className == "collapsiblecontentexpand") && (ele.style.display == ""))) {
        ele.style.display = "none";
    }
    else {
        ele.style.display = "block";
    }
    if (!isEmpty(functionCallback))
        eval(functionCallback);
}

function ajaxJQuery() {
    var url = "?page=getlist&type=store_list";
    var dataString = "";
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "GET",
        success: function (data) {
            if (!isDataOk(data)) {
                showMsg([itxt("loi"), getDataFail(data)]);
                return;
            }
            data = getDataOk(data);
        },
        error: function () {
            showMsg(itxt("loi"));
        }
    });
}
function ajaxJQueryForm(f) {
    var type_id = f.elements.namedItem("type_id").value;
    var type = f.elements.namedItem("type").value;
    var form = $(f);
    var url = form.attr('action');
    var dataString = form.serialize();
    jQuery.ajax({
        url: url,
        data: dataString,
        type: "POST",
        success: function (data) {

        },
        error: function () {
            hideModal();
            showMsg(itxt("thatbai"), "");
        }
    });
    return false;
}
//UI_SHOW_END
function DlgInput(arFields, prompt, fnCallBack) {
    var retparam = "";
    var html = "<div style='width:100%;-moz-box-sizing:border-box;box-sizing:border-box;padding:5px;line-height:150%'>";
    html += "<p>" + prompt + "</p>";
    for (var i = 0; i < arFields.length; i++) {
        var id = "g_inputdialog_text" + i;
        if (retparam != "") retparam += ","; retparam += id;
        html += arFields[i] + ": <input type=\"text\" id=\"" + id + "\" prompt=\"\" style=\"width:100%;margin-bottom:5px\"><br>";
    }
    html += "</div>";
    html += "<input type=\"button\" class=\"btndlg cancel\" style=\"width:50%\" value=\"Bỏ qua\" onclick=\"hideModalBlock(false)\">";
    html += "<input type=\"button\" class=\"btndlg ok\" style=\"width:50%\" value=\"Đồng ý\" onclick=\"return " + fnCallBack + "(" + retparam + ")\">";

    showModalBlock(html, 'Nhập', "g_inputdialog_text0");
}
//fnParamArray: Array or Value
function DlgGetText(prompt, fnCallBack, fnParamArray, isGetNumber, initText, numOfTextRows) {
    var oku = "";
    if (isEmpty(initText)) initText = "";
    if (isGetNumber) oku = "return fi_doFormat(this)";
    var html = "<div style='width:100%;-moz-box-sizing:border-box;box-sizing:border-box;padding:5px;line-height:150%'>";
    html += "<p>" + prompt + "</p>";
    if (!isEmpty(numOfTextRows))
        html += "<textarea id=\"g_inputdialog_text\" style=\"width:100%;margin-bottom:5px\" rows=\"" + numOfTextRows + "\">" + initText + "</textarea><br>";
    else
        html += "<input type=\"text\" class=\"input_invoice\" onkeyup=\"" + oku + "\" id=\"g_inputdialog_text\" value=\"" + initText + "\" style=\"width:100%;margin-bottom:5px\"><br>";
    html += "</div>";
    html += "<input type=\"button\" class=\"btndlg cancel\" style=\"width:50%\" value=\"Bỏ qua\" onclick=\"hideModalBlock(false)\">";
    html += "<input type=\"button\" class=\"btndlg ok\" style=\"width:50%\" value=\"Đồng ý\" onclick=\"hideModalBlock(false);eval('" + escapeJS(fnCallBack) + "')(getValById('g_inputdialog_text')";
    if (Array.isArray(fnParamArray)) {
        for (i = 0; i < fnParamArray.length; i++) {
            if (isString(fnParamArray[i]))
                html += ",'" + escapeJS(fnParamArray[i]) + "'";
            else
                html += "," + (fnParamArray[i]);
        }
    } else if (!isEmpty(fnParamArray)) {
        html += ",'" + escapeJS(fnParamArray) + "'";
    }
    html += ")\">";
    showModalBlock(html, 'Nhập', "g_inputdialog_text");
}

//DLG_STACK
function dlgGetNewId() {
    if (isEmpty(g_dlgstack)) {
        g_dlgstack = [];
    }
    var id = 'iddlgstack' + g_dlgstack.length;
    return id;
}
function dlgShow(content, header, iddlgshow) {

    var width = '96%';
    var obj = document.querySelector(".home");
    if (!isEmpty(obj)) {
        if (obj.offsetWidth > 1024) {
            width = '1024px';
        } else {
            width = '96%';
        }
    }
    //var myModalHead = document.getElementById("myModalHead");
    //myModalHead.style.width = "calc(100% - 36px)";
    //margin:48px auto
    var html = '<div class="modal-content" style="width:' + width + ';">'
        + '<div class="head" id="' + idhead + '">'
        + '<span class="text" style="width: calc(100% - 36px)">' + header + '</span>'
        + '<span class="button" onclick="dlgRemove()" style="font-size:26px">&times;</span>'
        + '</div>'
        + '<div id="' + idContent + '" style="height:auto;padding-top: 32px;" >' + content
        //+'<input type="button" style="width:50%;height:50px;top:0px" value="new_dlg" onclick="return dlgShow()">'
        //+'<input type="button" style="width:50%;height:50px;top:0px" value="close_dlg" onclick="return dlgRemove()">'
        + '</div>';
    +'</div>';

    if (isEmpty(g_dlgstack)) {
        g_dlgstack = [];
    }
    if (isEmpty(iddlgshow)) {
        var id = 'iddlgstack' + g_dlgstack.length;
        var idhead = id + 'head';
        var idContent = id + 'content';
        var elemDiv = document.createElement('div');
        elemDiv.id = id;
        elemDiv.className = "modal";
        document.body.appendChild(elemDiv);

        if (header === undefined) header = 'iShopmanX';
        if (content === undefined) content = id;

        elemDiv.innerHTML = html;
        elemDiv.style.display = "block";
        g_dlgstack[g_dlgstack.length] = id;
        return id;
    } else {
        setInnerById(iddlgshow, html);
        return iddlgshow;
    }
}

function dlgRemove() {
    if (g_dlgstack.length < 1) return;
    var el = g_dlgstack[g_dlgstack.length - 1];
    var elemDiv = document.getElementById(el);
    if (elemDiv !== null) elemDiv.remove();
    g_dlgstack.pop();
}

function dlgConfirm(strMes, strCaption, fnCallBackName, fnCallBackParamArray) {
    var paramString = arrayToStringAsList(fnCallBackParamArray);
    if (paramString.length < 1)
        paramString = "true";
    else
        paramString += ",true";

    var html = "<div style='-moz-box-sizing:border-box;box-sizing:border-box;padding:8px;text-align:center;width:100%'>" + strMes + "</div>";
    html += "<button class='btndlg cancel' style='width:50%' value='' onclick='dlgRemove();'>Cancel</button>";
    html += "<button class='btndlg ok' style='width:50%' value='' onclick=\"dlgRemove();" + fnCallBackName + "(" + paramString + ")\">OK</button>";
    dlgShow(html, strCaption);
}
//DLG_STACK_END
/*INIT_CODE*/


function defineStaticField(cls, prop, value) {
    Object.defineProperty(cls, prop, {
        value,
        writable: true,
        configurable: true,
        enumerable: true,
    });
}

if (typeof String.prototype.replaceAll === "undefined") {
    String.prototype.replaceAll = function (match, replace) {
        //return this.replace(new RegExp(match, "g"), () => replace);
        return this.replace("/" + match + "/g", () => replace);
    }
}
if (typeof String.prototype.left === "undefined") {
    String.prototype.left = function (n) {
        return this.substring(0, n);
    }
}
if (typeof String.prototype.right === "undefined") {
    String.prototype.right = function (n) {
        var len = this.length;
        if (n >= len) return this;
        return this.substring(len - n, len);
    }
}
function loadCss(cssFilePathFull) {

    if (g_cssloaded.indexOf(cssFilePathFull) !== -1) return;

    var head = document.getElementsByTagName('head')[0]
    var style = document.createElement('link');
    style.href = cssFilePathFull;
    style.type = 'text/css';
    style.rel = 'stylesheet';
    head.append(style);

    if (g_cssloaded != "") g_cssloaded += ",";
    g_cssloaded += cssFilePathFull;
}

function loadJs(jsFilePathFull) {
    //check if loaded
    if (g_cssloaded.indexOf(jsFilePathFull) !== -1) return;

    var script = document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", jsFilePathFull);
    document.getElementsByTagName("head")[0].appendChild(script);

    if (g_jsloaded != "") g_jsloaded += ",";
    g_jsloaded += jsFilePathFull;
}
// Close the dropdown menu if the user clicks outside of it
document.onclick = function (event) {
    if (!isEmpty(g_dropdownrect)) {
        if ((event.x >= g_dropdownrect.left) && (event.x <= g_dropdownrect.right)
            && (event.y >= g_dropdownrect.top) && (event.y <= g_dropdownrect.bottom)
        )
            return;
        if (!isEmpty(g_dropdowndiv)) {
            g_dropdownrect = null;
            g_dropdowndiv.style.display = "none";
            return;
        }
    }
    // Get the modal
    var modal = document.getElementById('myModal');
    if ((event.target == modal) && (!g_showmodalblock)) {
        hideModal();
    }
    if (event.target.classList == 'overlay') {
        var idpopupwindow = document.getElementById("popupwindow");
    }
    var checkcl = event.target.classList.toString();
    if (checkcl === undefined) checkcl = "";

    if ((checkcl != 'dropbtn') && (checkcl != 'dropbtn compact') && (checkcl != 'dropbtn search') && (checkcl != 'dropbtn favorite')
        && (checkcl.indexOf('pinpopup') < 0)
        && (checkcl != 'divtablistbuttonclose') && (checkcl != 'divtablist')
    ) {
        var dropdowns = document.getElementsByClassName("dropdown-content");
        var i;
        for (i = 0; i < dropdowns.length; i++) {
            var openDropdown = dropdowns[i];
            openDropdown.style.display = "none";
        }
        menuUIUpdateMenuButton();
    }
}
