// Util functions part
var groupBy = function (xs, key) {
    return xs.reduce(function (rv, x) {
        (rv[x[key].trim()] = rv[x[key].trim()] || []).push(x);
        return rv;
    }, {});
};
function extractTimestampFromString(inputString) {
    var regex = /\/Date\((\d+)\)\//;
    var match = regex.exec(inputString);
    if (match && match[1]) return match[1];
    return null;
}
function extractValueFromQueryString(inputString) {
    var regex = /v=([^&]+)/;
    var match = regex.exec(inputString);
    if (match && match[1]) return match[1];
    else return 0;
}
function getTimestampServerCache() {
    var scriptElements = document.getElementsByTagName('script');
    for (var i = 0; i < scriptElements.length; i++) {
        var scriptSrc = scriptElements[i].getAttribute('src');
        if (scriptSrc && scriptSrc.indexOf('header.menu.vue') > -1)
            return extractValueFromQueryString(scriptSrc);
    }
    return 0;
}
function getQueryParam(paramName) {
    var url_string = isHeaderPage() ? window.parent.location.href : window.location.href
    var url = new URL(url_string);
    var paramValue = url.searchParams.get(paramName);
    return paramValue;
}
let addPrefix = (variableName) =>
    isNaN(variableName.substring(0, 1)) ? '' : '_';

function changeHeaderHeight(height) {
    try {
        window.parent.document.getElementsByClassName('divHeader')[0].style = 'height:' + height + 'px';
    }
    catch (err) {
        console.log(err)
    }
}
var isMobileDevice = function () {
    var check = false;
    (function (a) { if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a) || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0, 4))) check = true; })(navigator.userAgent || navigator.vendor || window.opera);
    return check;
}
// Vue App and Components part
const { createApp, ref, onMounted, computed, onBeforeMount } = Vue;
const SpanArrow = {
    template: '<span class="arrow-down-submenu">▼</span>',
};
const DivArrow = {
    template: '<div class="arrow-down"></div>',
};
const TextArrow = {
    template: '▼',
};
const DownArrow = {
    props: {
        type: String,
        hasSubGame: Boolean,
        gameType: String,
        isGuest: Boolean,
        hideOnMobileResponsive: {
            type: Boolean,
            default: false
        }
    },
    components: {
        SpanArrow,
        DivArrow,
        TextArrow,
    },
    computed: {
        getArrowComponent() {
            switch (this.type) {
                case 'span':
                    return SpanArrow;
                case 'div':
                    return DivArrow;
                case 'text':
                    return TextArrow;
            }
        },
        isVisible() {
            if (isMobileDevice() && this.hideOnMobileResponsive)
                return false;
            return this.isGuest ? (this.hasSubGame ? true : false) : (this.gameType.toLowerCase() === 'afbsb' ? (this.hasSubGame ? true : false) : false);
        }
    },
    template: `
    <component :is="getArrowComponent" v-if="isVisible"></component>
  `,
};
const ImageItem = {
    props: {
        className: {
            type: String,
            required: false,
        },
        cacheVersion: {
            type: Number,
            required: false,
        },
        imageData: {
            type: Object,
            required: true,
        },
        isSubmenu: {
            type: Boolean,
            required: false,
        },
        width: {
            type: String,
            required: false,
        },
        height: {
            type: String,
            required: false,
        },
    },
    computed: {
        src() {
            let hostType = location.hostname;
            let hostName = 'https://';
            if (hostType.indexOf('localhost') > -1)
                hostName += 'imgtest.playliga.com'
            else if (hostType.indexOf('playliga.com') > -1)
                hostName += 'imguat.playliga.com'
            else
                hostName += 'imgshare.iuf-cfl.cloud';

            let staticImageHost = localStorage.getItem('cdnImageHost') || hostName;
            var dbTimestamp = +extractTimestampFromString(
                this.imageData.HeaderLastUpdatedTime
            );
            var serverTimeStamp = +this.cacheVersion;
            var latestTimestamp =
                dbTimestamp > serverTimeStamp ? dbTimestamp : serverTimeStamp;
            let srcImage = '';
            if (!this.isSubmenu)
                srcImage = `${staticImageHost}/headergames/${this.imageData.CTId}/MenuIcon_${this.imageData.GameType}.${this.imageData.ImageType}?v=${latestTimestamp}`;
            else
                srcImage = `${staticImageHost}/headergames/SubMenuIcon_${this.imageData.HGameId}_${this.imageData.GameName}.png?v=${latestTimestamp}`;
            return srcImage;
        },
        style() {
            return `width:${this.width || 'auto'}; height:${this.height || 'auto'}`
        }
    },
    template: `<img :style="style" :class="className" :src="src" :alt="imageData.GameMenuDisplayName"/>`,
};
const MenuItem = {
    props: {
        name: String,
        className: String,
        onclickHandler: Function,
        isGuest: Boolean,
        hrefs: Object
    },
    computed: {
        formattedClassName() {
            let prefix = addPrefix(this.name);
            return `${this.className ? this.className : ''
                } ${prefix}${this.name.toLowerCase()}-game`;
        },
        formattedName() {
            return this.name.toLowerCase();
        },
        href() {
            if (this.isGuest) {
                if (this.name.toLowerCase() === 'afbsb') {
                    if (isHeaderPage())
                        return this.hasSubGameSport ? '#' : '_View/RMOdds1.aspx';
                    return getQueryParam('ref') ? 'Main.aspx?ref=' + getQueryParam('ref') : 'Main.aspx';
                }
                return '#';
            }
            else
                switch (this.name.toLowerCase()) {
                    case 'afbsb':
                        return this.hasSubGameSport ? '#' : '_View/RMOdds1.aspx';
                    case 'poker':
                    case 'tangkas':
                        return this.hrefs[this.name.toLowerCase()];
                    default:
                        return 'LobbyGames.aspx?type=' + this.name;
                }
        },
        target() {
            return this.href === '#' ? '' : (isHeaderPage() ? 'fraMain' : '_parent');
        },
        hasSubGameSport() {
            return JSON.parse(localStorage.getItem('menuMap'))['AFBSB'][0].HasSubGame;
        }
    },
    template: `<a :href="href" :target="target" :class="formattedClassName" :name="formattedName">
                <slot></slot>
            </a>`,
};
const SubMenuContainer = {
    props: ['name', 'className'],
    computed: {
        id() {
            return 'sub-menu-' + this.name.toLowerCase();
        },
        formattedClass() {
            return `sub-menu ${this.className || ''}`;
        },
    },
    template: `
      <div :id="id" :class="formattedClass">
          <div class="main_width">
          <ul class="gameNav">
              <slot></slot>
          </ul>
          </div>
      </div>
  `,
};
const SubMenuItem = {
    props: ['name', 'type', 'isGuest'],
    computed: {
        href() {
            if (this.isGuest) {
                if (this.type.toLowerCase() === 'afbsb') {
                    if (isHeaderPage()) {
                        switch (this.name.toLowerCase()) {
                            case 'liga sb': return 'LobbyGames.aspx?type=' + this.type;
                            //case 'sport': return '_View/RMOdds1.aspx';
                            default: return '_View/RMOdds1.aspx';
                        }
                    }
                    else { // default page
                        let hrefMain = getQueryParam('ref') ? 'Main.aspx?ref=' + getQueryParam('ref') : 'Main.aspx'
                        switch (this.name.toLowerCase()) {
                            case 'liga sb': return hrefMain + (hrefMain.indexOf('?') > -1 ? '&': '?') + 'launch=ligasb';
                            //case 'sport': return '_View/RMOdds1.aspx';
                            default: return hrefMain;
                        }
                    }
                }
                return '#';
            }
            else
                switch (this.name.toLowerCase()) {
                    case 'liga sb':
                        return 'LobbyGames.aspx?type=' + this.type;
                    case 'sport':
                        return '_View/RMOdds1.aspx';
                    default:
                        return '#';
                }
        },
        target() {
            return this.href === '#' ? '' : (isHeaderPage() ? 'fraMain' : '_parent');
        },
    },
    template: `
    <li>
        <a :type="type" style="background:none!important" :href="href" :target="target">
            <slot></slot>
            {{name}}
        </a>
    </li>
  `,
};

const SubMenu = {
    props: {
        className: String,
        submenuData: Object,
        isGuest: Boolean,
        cacheVersion: Number,
        hideOnMobileResponsive: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        isSubMenu() {
            return true;
        },
        isVisible() {
            if (isMobileDevice() && this.hideOnMobileResponsive)
                return false;
            return this.isGuest ? (this.submenuData[0].HasSubGame ? true : false) : (this.gameType === 'afbsb' ? (this.submenuData[0].HasSubGame ? true : false) : false);
        },
       
        gameType() {
            return this.submenuData[0].GameType.toLowerCase();
        }
    },
    template: `
        <submenu-container v-if="isVisible" :class-name="className" :name="submenuData[0].GameType">
            <submenu-item v-for="(record, index) in submenuData"
                            :type="record.GameType" 
                            :is-guest="isGuest"
                            :name="record.GameName">
                <image-item :image-data="record" :key="index" :is-submenu="isSubMenu" :cache-version="cacheVersion" />
                <img title="hot" v-if="record.IsHotGame" src="css/submenu/hot-icon.gif?v=1721039259665" style="width: 36px!important;height: 36px;position: absolute;top: -12px;left: 12px;">
            </submenu-item>
        </submenu-container>
  `,
};

function createMenu() {
    const refText = 'Referral';
    return createApp({
        methods: {
            getGameMenuDisplayNameByLang(menuData, lang) {
                let name = menuData.GameMenuDisplayName;
                if (!lang)
                    lang = getQueryParam('lang')
                switch (lang) {
                    case 'ZH-CN': name = this.getValidName(menuData, 'GameMenuDisplayNameC'); break;
                    case 'TH-TH': name = this.getValidName(menuData, 'GameMenuDisplayNameT'); break;
                    case 'EN-IE': name = this.getValidName(menuData, 'GameMenuDisplayNameV'); break;
                    case 'EN-TT': name = this.getValidName(menuData, 'GameMenuDisplayNameK'); break;
                    case 'EN-AU': name = this.getValidName(menuData, 'GameMenuDisplayNameI'); break;
                }
                return name;
            },
            getValidName(menuData, key) {
                if (menuData[key] && menuData[key] !== '')
                    return menuData[key]
                return menuData.GameMenuDisplayName;
            }
        },
        setup() {
            let data = ref({});
            let dataFetched = ref(false);
            let appId = ref('');
            let cacheVersion = ref(0);
            let isGuest = ref(true);
            let hideSubmenuMobileResponsive = ref(false);
            let hiddenReferralMenu = ref(false)
            let menuUrls = ref({});
            
            const fetchMenuData = (callback) => {
                const queryString = window.location.search.substring(1);
                const apiUrl = 'public/GameGen.ashx?cmd=GetHeaderMenuGames&' + queryString;
                $.ajax({
                    url: apiUrl,
                    method: 'GET',
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (response) {
                        let menuData = response.menus
                        if (response && response.success) {
                            if (!isGuest.value) {
                                if (response.hasReferral && !hiddenReferralMenu.value) {
                                    const lastRecord = menuData.at(-1)
                                    menuData.push({
                                        ...lastRecord,
                                        Id: lastRecord.Id + 1,
                                        GameType: refText,
                                        GameMenuDisplayName: refText,
                                        GameMenuDisplayNameC: refText,
                                        GameMenuDisplayNameT: refText,
                                        GameMenuDisplayNameV: refText,
                                        GameMenuDisplayNameK: refText,
                                        GameMenuDisplayNameC: refText,
                                        GameMenuDisplayNameI: refText,
                                    })
                                }
                            }
                            let menuMap = groupBy(menuData, 'GameType');
                            localStorage.setItem('menuMap', JSON.stringify(menuMap));
                            if (isGuest.value || !isHeaderPage()) {
                                delete menuMap['ALLGAMES'];
                                delete menuMap[refText];
                            }
                            console.log(menuMap)

                            Object.assign(data.value, menuMap);
                            dataFetched.value = true;
                            if (typeof callback === 'function') {
                                callback({ menuMap, hasReferral: response.hasReferral, isSWAccount: response.isSWAccount, CTId: +response.CTId, hasLigaSBRecord: response.menus.find(menu => menu.GameName.toLowerCase().indexOf('liga sb') > -1)});
                            }
                        } else {
                            alert(JSON.stringify(response));
                        }
                    },
                    error: function (error) {
                        console.error('Error fetchMenuData():', error);
                    },
                });
            };
            const fetchMenuUrls = (callback) => {
                const queryString = window.location.search.substring(1);
                const apiUrl = 'public/GameGen.ashx?cmd=GetHeaderMenuUrls&' + queryString;
                $.ajax({
                    url: apiUrl,
                    method: 'GET',
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (response) {
                        if (response && response.success) {
                            Object.assign(menuUrls.value, response.urls);
                            if (typeof callback === 'function') {
                                callback(response);
                            }
                        } else {
                            console.log(response.text)
                        }
                    },
                    error: function (error) {
                        console.error('Error fetchMenuUrls() :', error);
                    },
                });
            };
            const genStyleSubMenu = (menuMap, mainMenuId) => {
                let tagParentSubMenu = document
                    .getElementById(mainMenuId)
                    .getAttribute('tag-parent-sub-menu');
                let htmlStyles = ``;
                for (const gameType in menuMap) {
                    htmlStyles += `${tagParentSubMenu}.${addPrefix(
                        gameType
                    )}${gameType.toLowerCase()}-game:hover > #sub-menu-${gameType.toLowerCase()} {display: inline-block}\r\n`;
                }
                //console.log(htmlStyles);
                const styleElement = document.createElement('style');
                styleElement.textContent = htmlStyles;
                document.body.appendChild(styleElement);
            };
            function handleMouseOver(e) {
                var className = $(e).attr('name');
                var height = $('#sub-menu-' + className).outerHeight();
                if (className === '365slot') $('#sub-menu-365slot').css('padding-bottom', '40px');
                changeHeaderHeight(HEADER_HEIGHT + height);
            }

            const runScriptSubMenu = (menuMap) => {
                var listNameSubMenu = Object.keys(menuMap)
                listNameSubMenu = listNameSubMenu.filter(name => (menuMap[name] && menuMap[name].length >= 1 && menuMap[name][0].HasSubGame))
                listNameSubMenu = listNameSubMenu.map(name => `.${addPrefix(name)}${name.toLowerCase().replaceAll(" ", "-")}-game`);

                $(`${listNameSubMenu.toString().trim()}`).mouseover(function () {
                    handleMouseOver($(this))
                });
                $(`${listNameSubMenu.toString().trim()}`).mouseout(function () {
                   // Fix for desktop site: when mousing over the SPORT submenu again after login, it will show.
                   // Need to add this statement because the submenu is automatically hidden for both desktop and mobile sites.
                   // By default, desktop uses CSS to hide/show the submenu. Therefore, hiding the submenu automatically needs to be handled by JavaScript code ($('#sub-menu-afbsb').hide() was called at runScriptUseSport3rdParty()), which will add a style attribute inline "style=display:none".
                   // Consequently, the submenu will not show when moused over again, as inline CSS takes priority over <style> tags and imported CSS files. Then it("style=display:none".) will be removed to reset everything as the start.
                    $('#sub-menu-afbsb').removeAttr('style');

                    changeHeaderHeight(HEADER_HEIGHT)
                });
            };
            const runScriptSubMenuDefaultPage = (menuMap) => {
                var listNameSubMenu = Object.keys(menuMap)
                listNameSubMenu = listNameSubMenu.filter(name => (menuMap[name] && menuMap[name].length >= 1 && menuMap[name][0].HasSubGame))
                listNameSubMenu = listNameSubMenu.map(name => `.${addPrefix(name)}${name.toLowerCase().replaceAll(" ", "-")}-game`);

                $(`${listNameSubMenu.toString().trim()}`).mouseover(function () {
                    var className = $(this).attr('name');
                    if (className === '365slot') $('#sub-menu-365slot').css('padding-bottom', '40px');
                    //console.log('%s: %s', className, height)
                });
            };
            const appendSWLigaSBScript = () => {
                $('a').on('click touchstart', function () {
                    try {
                        var parent = window.parent.document;
                        var href = $(this).attr('href')
                        var target = $(this).attr('target')
                        //console.log(href)
                        if (href !== '#' && target !== '_blank') {
                            if (href.indexOf('LobbyGames.aspx?type=AFBSB') > -1) {
                                $(parent).find('.divPanel').hide('fast');
                                let width = isMobileDevice() ? 'width: 100% !important;' : 'width: 1024px !important;';
                                console.log(width);
                                $(parent).find('.divMain')[0].style.cssText = width;
                            } else {
                                $(parent).find('.divPanel').show('fast');
                                $(parent).find('.divMain').css('width', 'calc(100% - 205px)');
								// reset 
								localStorage.setItem('ligaSbHost', '')
								$('#accTpLst', window.parent.frames["fraHeader"].document).attr('onchange','top.location.href = this.form.accTpLst.options[this.form.accTpLst.selectedIndex].value; return false;')
                            }

                            // hide submenu of sport-game when click to other game on main menu
                            if (isHeaderPage()) {
                                setTimeout(function () {
                                    $('#sub-menu-afbsb').hide();
                                    changeHeaderHeight(HEADER_HEIGHT)
                                }, 500)
                                $('#sub-menu-afbsb').on('touchstart', function (event) {
                                    event.stopPropagation();
                                });
                            }

                            var fraMainIframe = parent.querySelector('iframe[name="fraMain"]');
                            if (fraMainIframe.onload === null)
                                fraMainIframe.onload = function () {
                                    if (href.indexOf('LobbyGames.aspx?type=AFBSB') === -1) {
                                        //$(parent).find('.divPanel').show('fast');
                                        //$(parent).find('.divMain').css('width', 'calc(100% - 205px)');
                                    }
                                    //fraMainIframe.onload = null;
                                }
                        }
                    }
                    catch (e) {
                        console.log(e)
                    }
                });
                if (isHeaderPage()) {
                    $('.afbsb-game').on('touchstart', function (event) {
                        event.preventDefault();
                        var subMenu = $(this).find('.sub-menu');
                        subMenu.toggle();
                        if (subMenu.is(':visible'))
                            handleMouseOver($(this))
                         else
                            changeHeaderHeight(HEADER_HEIGHT)
                    });

                    $('#sub-menu-afbsb').on('touchstart', function (event) {
                        event.stopPropagation();
                    });
                }
            }
            const appendTWLigaSBScript = (CTId) => {
                let arrowType = 'text';
                switch (CTId) {
                    //case 54:
                    case 64:
                    case 114:
                    case 264:
                    case 265:
                        arrowType = 'span'; break;
                    case 52:
                    //case 57:
                    case 69:
                    case 87:
                    //case 109:
                    case 123:
                    case 256:
                    case 263:
                    case 279: // SW WL
                        arrowType = 'div'; break;
                    case 99:
                    case 100:
                        arrowType = 'none'; break;
                }
                let aTagIsParentMenu = false
                switch (CTId) {
                    case 124:
                    case 135:
                    case 208:
                    case 218:
                    case 227:
                    case 244:
                    case 245:
                    case 260:
                        aTagIsParentMenu = true; break;
                }
                var scriptTagArrow = $('<script></script>').attr('type', 'text/javascript').html(`var arrowOption = '${arrowType}'; var aTagIsParentMenu = ${aTagIsParentMenu}`);
                $(mountEl).append(scriptTagArrow);
                var scriptTagSubmenuGen = $('<script></script>').attr({
                    type: 'text/javascript',
                    src: 'js/header.submenu.gen.js?v=13'
                });
                $(mountEl).append(scriptTagSubmenuGen);

            }

            const isExistReferralAuto = () => {
                try {
                    const listItems = $(mountEl).find('li');
                    for (let i = 0; i < listItems.length; i++) {
                        let aTag = $(listItems[i]).find('a');
                        if (aTag && aTag.attr('href') && aTag.attr('href').toLowerCase() === 'lobbygames.aspx?type=referral') {
                            return true;
                        }
                    }
                    return false;
                } catch (error) {
                    console.log(error);
                    return false;
                }
            }

            const removeDuplicatedReferralMenu = () => {
                $(mountEl).find('li').each(function () {
                    let aTag = $(this).find('a')
                    if (aTag && aTag.attr('href') && aTag.attr('href').toLowerCase() === '_view/referral.aspx') {
                        $(this).remove();
                    }
                });
            }
            // move whitelist WL from Util.Header.Menu.cs function IsActivatedSubMenuSport
            const manualAppendLigaSBScriptCTIds = [
                 269
            ]
            
            const launchGuestLigaSb = () => {
                if (getQueryParam('launch') === 'ligasb') {
                    // Only redirect from Alert.aspx and Default.aspx just launch auto ligasb
                    // Alert one time 
                    // Default page many time
                    if (localStorage.getItem('isALLGSb') === 'true' || isGuest.value) {
                        var parent = window.parent.document;
                        $(parent).find('.divPanel').hide('fast');
                        let width = isMobileDevice() ? 'width: 100% !important;' : 'width: 1024px !important;';
                        $(parent).find('.divMain')[0].style.cssText = width;
                        window.open("LobbyGames.aspx?type=AFBSB", 'fraMain')
                        localStorage.setItem('isALLGSb', false)
                    }
                    else
                        // before login 
                        localStorage.removeItem('isALLGSb')
                }
            }

            onMounted(() => {
                // Load menu from local storage for faster access
                if (localStorage.getItem('menuMap')) {
                    let menuMap = JSON.parse(localStorage.getItem('menuMap'))
                    if (isGuest.value || !isHeaderPage()) {
                        delete menuMap['ALLGAMES'];
                        delete menuMap[refText];
                    }
                    Object.assign(data.value, menuMap);
                }

                fetchMenuData(({ menuMap, isSWAccount, hasReferral, CTId, hasLigaSBRecord }) => {
                    genStyleSubMenu(menuMap, appId.value);
                    if (isHeaderPage()) {
                        runScriptSubMenu(menuMap)

                        // make sure it works smoothly after page load successfully 
                        setTimeout(function () {
                            // conditions ref menu item if the ref item auto is added
                            if (!isGuest.value && hasReferral && isExistReferralAuto())
                                removeDuplicatedReferralMenu()

                            // conditions append tw liga sb script manually 
                            // prevent duplicated trigger event of Liga SB launching script
                            if (!isGuest.value && !isSWAccount && !manualAppendLigaSBScriptCTIds.includes(CTId) && hasLigaSBRecord) // TW WLs and TW WLs has been appeneded ligasb script manually
                                appendTWLigaSBScript(CTId);
                            else if (isGuest.value || isSWAccount)
                                appendSWLigaSBScript() // SW WL
                        }, 1111)
                       
                        launchGuestLigaSb()
                    }
                    else
                        runScriptSubMenuDefaultPage(menuMap) 
                });
                if(!isGuest.value){
					fetchMenuUrls();
					// after login always run at header page
					$().ready(function(){
						getMailInfo();
						let ligaSbHost = localStorage.getItem('ligaSbHost');
						let fraMain = window.parent.frames["fraMain"]
						let fraHeaderDocument = window.parent.frames["fraHeader"].document
						// set new onchange for accTpLst if it use LigaSB
						if (ligaSbHost !== '') {
							
							$('#accTpLst', fraHeaderDocument).removeAttr('onchange')
							$('#accTpLst', fraHeaderDocument).on('change', function () {
								console.log('changeOddStyle: %s', ligaSbHost)
								let sentObj = {
									ACT: "ChangeOddsType",
									value: $('#accTpLst').val().slice(-2),
								}
								fraMain.postMessage(
									JSON.stringify(sentObj),
									'https://' + ligaSbHost
								);
							})
						}
						// reset onchange accTpLst again if use original SPORT 
                        console.log(fraMain.location.href.toLowerCase())
                        if (fraMain.location.href.toLowerCase().indexOf("rmodds") > -1 || fraMain.location.href.toLowerCase().indexOf('about:blank') > -1){
							localStorage.setItem('ligaSbHost', '')
							$('#accTpLst', fraHeaderDocument).attr('onchange','top.location.href = this.form.accTpLst.options[this.form.accTpLst.selectedIndex].value; return false;')
						}
					})
				}
            });
            onBeforeMount(() => {
                appId.value = mountEl.dataset.id;
                isGuest.value = mountEl.dataset.isGuest === "true";

                if (mountEl.dataset.hideSubmenuMobileResponsive)
                    hideSubmenuMobileResponsive.value = mountEl.dataset.hideSubmenuMobileResponsive === "true"
                if (mountEl.dataset.hiddenReferralMenu)
                    hiddenReferralMenu.value = mountEl.dataset.hiddenReferralMenu === "true"

                cacheVersion.value = +getTimestampServerCache();
                //console.log(mountEl.dataset.id);
                //console.log(mountEl.dataset.isGuest);
                //console.log(mountEl.dataset.hideSubmenuMobileResponsive);
                //console.log(hideSubmenuMobileResponsive.value);
            });
            const computedProps = {};
            return {
                menus: data.value,
                menuUrls: menuUrls.value,
                dataFetched,
                ...computedProps,
                cacheVersion,
                isGuest,
                hideSubmenuMobileResponsive,
                hiddenReferralMenu
            };
        },
    });
}
var menu = createMenu();
menu.component('image-item', ImageItem);
menu.component('down-arrow', DownArrow);
menu.component('menu-item', MenuItem);
menu.component('submenu-container', SubMenuContainer);
menu.component('submenu-item', SubMenuItem);
menu.component('submenu', SubMenu);
