//var naviman_domain = 'https://naviman.shopifas.com/'; // TODO: GOLIVE
var naviman_domain = 'https://a0a1-27-71-45-121.ngrok-free.app/';
/**********************************************************************************************************************
Functions.
**********************************************************************************************************************/
var naviman = (function(){
var VERTICAL_CHILDREN_WIDTH = 200;
var DESKTOP_MAX_WIDTH = 400;
var SCROLL_TO_HIDE = 100;
var BOX_SHADOW = 'box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.10);';
var shop = '';
var embed_id = '';
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
var cartCount = 0;
var BADGE_HIDE = 0;
var BADGE_DOT = 1;
var BADGE_ISCART_WITHCOUNT = 2;
var clearCSS_JS = function (css) {
if (typeof css == 'undefined')
return "";
css = css.trim();
css = css.strReplace('', '');
css = css.strReplace('', '');
return css;
};
var isHadValue = function(checkVar) {
if (typeof (checkVar) == 'undefined')
return false;
if (checkVar.toString().trim() == "")
return false;
return true;
};
var defaultValue = function( str, defaultValue ) {
if (typeof str == 'undefined')
return defaultValue;
if( str.toString().trim() == "" )
return defaultValue;
return str;
};
var standardizeCSS = function(rules, className){
if( rules == "" ) return rules;
if( rules.length >= className.length + 1 )
if( rules.substring(0, className.length + 1) == '.' + className )
return rules;
var classLen = className.length,
char, nextChar, isAt, isIn;
// makes sure the className will not concatenate the selector
className = '#' + className + ' ';
// removes comments
rules = rules.replace( /\/\*(?:(?!\*\/)[\s\S])*\*\/|[\r\n\t]+/g, '' );
// makes sure nextChar will not target a space
rules = rules.replace( /}(\s*)@/g, '}@' );
rules = rules.replace( /}(\s*)}/g, '}}' );
for (var i = 0; i < rules.length-2; i++) {
char = rules[i];
nextChar = rules[i+1];
if (char === '@' && nextChar !== 'f') isAt = true;
if (!isAt && char === '{') isIn = true;
if (isIn && char === '}') isIn = false;
if (
!isIn &&
nextChar !== '@' &&
nextChar !== '}' &&
(
char === '}' ||
char === ',' ||
((char === '{' || char === ';') && isAt)
)
) {
rules = rules.slice(0, i+1) + className + rules.slice(i+1);
i += classLen;
isAt = false;
}
};
// prefix the first select if it is not `@media` and if it is not yet prefixed
if (rules.indexOf(className) !== 0 && rules.indexOf('@') !== 0) rules = className+rules;
return rules;
};
var isMobileMode = function () {
if (windowWidth <= 600)
return true;
return false;
};
var getCurrentTemplate = function () {
let path = window.location.pathname.toUpperCase().trim();
if (path == '/' || path == '')
return "index";
if (path.includes('PRODUCTS'))
return "products";
if (path.includes('COLLECTIONS'))
return "collections";
if (path.includes('PAGES'))
return "pages";
if (path.includes('BLOGS'))
return "blogs";
return "others";
};
var jsonp = function(uri) {
return new Promise(function(resolve, reject) {
var id = '_' + Math.round(10000 * Math.random());
var callbackName = 'jsonp_callback_' + id;
window[callbackName] = function(data) {
delete window[callbackName];
var ele = document.getElementById(id);
ele.parentNode.removeChild(ele);
resolve(data);
}
var src = uri + '&callback=' + callbackName;
var script = document.createElement('script');
script.src = src;
script.id = id;
script.addEventListener('error', reject);
(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
});
};
var displayElement = function( el, display ) {
if( isNull(el)) return;
if( isNull(el.style)) return;
if( display )
el.style.display = "block";
else
el.style.display = "none";
};
var isNull = function( object ) {
if ( object == null ) return true;
if ( typeof object == "undefined" ) return true;
return false;
};
String.prototype.strReplace = function(strReplace, strWith) {
var esc = strReplace.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var reg = new RegExp(esc, 'ig');
return this.replace(reg, strWith);
};
var itemMedia = function(icon, image, naviman_domain)
{
let isHadImage = true;
if (typeof (image) === 'undefined')
isHadImage = false;
else if (image.trim() == "")
isHadImage = false;
if (!isHadImage) {
return '' + '' + '';
} else
return '' + '' + '';
};
var defaultMarginPadding = function( marginPadding ) {
if( marginPadding == null ) marginPadding = {
'top' : 0, 'right' : 0, 'bottom' : 0, 'left' : 0
};
if(marginPadding['top'] == '') marginPadding['top'] = 0;
if(marginPadding['right'] == '') marginPadding['right'] = 0;
if(marginPadding['bottom'] == '') marginPadding['bottom'] = 0;
if(marginPadding['left'] == '') marginPadding['left'] = 0;
return marginPadding;
};
var generateCSS = function(naviman_appItem, embed_id, setting, dragdrop, isNaviBlock) {
// Set default values for some textfield
setting['submenuWidth'] = defaultValue(setting['submenuWidth'], 200);
setting['textSize'] = defaultValue( setting['textSize'], 10);
setting['spaceTextIcon'] = defaultValue(setting['spaceTextIcon'], 2);
setting['iconSize'] = defaultValue(setting['iconSize'], 22);
setting['height'] = defaultValue(setting['height'], 54);
setting['borderRadius'] = defaultValue(setting['borderRadius'], 0);
setting['opacity'] = defaultValue(setting['opacity'], 100);
setting['bottomMargin'] = defaultValue(setting['bottomMargin'], "");
setting['settingMargin'] = defaultMarginPadding( setting['settingMargin'] );
setting['settingPadding'] = defaultMarginPadding( setting['settingPadding'] );
let html = '';
naviman_appItem.insertAdjacentHTML('beforebegin', fontFamily_css);
}
// Submenu ---------------------------------------------------------
if (isHadValue(setting['submenuTextColor'])) {
html += cssNaviPrefix + ' ul li.item ul li.child .name { color: ' + setting['submenuTextColor'] + '; } ';
html += cssNaviPrefix + ' ul li.item a { color: ' + setting['submenuTextColor'] + '; } ';
html += cssNaviPrefix + ' ul li.item ul li.child .description { color: ' + setting['submenuTextColor'] + '; } ';
}
if (isHadValue(setting['submenuIconColor']))
html += cssNaviPrefix + ' ul li.item ul li.child .icon i { color: ' + setting['submenuIconColor'] + '; } ';
if (isHadValue(setting['submenuBackgroundColor']))
html += cssNaviPrefix + ' ul li ul.children { background: ' + setting['submenuBackgroundColor'] + ' } ';
if (isHadValue(setting['submenuDividerColor']))
html += cssNaviPrefix + ' ul li.child_divider { border-color: ' + setting['submenuDividerColor'] + '; } ';
// Layout ---------------------------------------------------------
if (setting['layout'] == 2) {
if (setting['iconSize'].trim() != "")
html += cssNaviPrefix + ' ul li.item_primary .inner { left: calc(50% - 26px); position: absolute; padding-top: ' + (16 - (setting['iconSize'] - 22) / 2) + 'px; } ';
if (setting['highlightColor'].trim() != "")
html += cssNaviPrefix + ' ul li.item_primary .inner { background: ' + setting['highlightColor'] + '; } ';
if (setting['highlightIconColor'].trim() != "")
html += cssNaviPrefix + ' ul li.item_primary .inner i { color: ' + setting['highlightIconColor'] + '; } ';
}
if (setting['layout'] == 3) {
if (setting['borderRadius'] != 0 )
html += ' .naviman_layout3 ul li ul.children { border-radius: ' + setting['borderRadius'] + 'px; } ';
if (setting['bottomMargin'] != "") {
html += '.naviman_layout3 { bottom: ' + setting['bottomMargin'] + 'px; } ';
}
}
if (setting['layout'] == 1 || setting['layout'] == 2) {
if (setting['borderRadius'] != 0 )
html += cssNaviPrefix + ' ul li ul.children { border-radius: ' + setting['borderRadius'] + 'px; } ';
}
// Kiem tra cho Float button
if (setting['layout'] == 4) {
html += cssNaviPrefix + ' { width: ' + navi_height + 'px; left: initial; right: 16px; height: ' + parseInt(navi_height) + 'px; width: ' + (parseInt(navi_height) * dragdrop.length) + 'px; } ';
html += cssNaviPrefix + ' ul li.item { border-radius: ' + setting['borderRadius'] + 'px; } ';
html += cssNaviPrefix + ' ul li.item .inner { padding: 8px 0px 0px 0px; } ';
html += cssNaviPrefix + ' ul li ul.children { left: initial; right: 0px; bottom: 4px; width: ' + setting['submenuWidth'] + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children { ' + BOX_SHADOW + ' border-radius: ' + (setting['borderRadius'] / 2) + 'px;} ';
if (setting['bottomMargin'] != "")
html += cssNaviPrefix + ' { bottom: ' + (parseInt(setting['bottomMargin'])) + 'px; } ';
}
// Don't display text ---------------------------------------------------------
if (setting['textHide'] == "true" || setting['textHide'] == true) {
html += cssNaviPrefix + ' ul li.item .name { display:none; } ';
html += cssNaviPrefix + 'ul li.item .inner { padding-top: ' + ((navi_height - 50) / 2 + 8 + (setting['textSize'] / 2)) + 'px } ';
if (setting['layout'] != 4) {
let isVertical = false;
if (isMobileMode())
if (setting['mobilePosition'] == 3 || setting['mobilePosition'] == 4 || setting['mobilePosition'] == 5 || setting['mobilePosition'] == 6)
isVertical = true;
if (!isMobileMode()) // Desktop mode
if (setting['desktopPosition'] == 5 || setting['desktopPosition'] == 6 || setting['desktopPosition'] == 7 || setting['desktopPosition'] == 8)
isVertical = true;
if (isVertical) {
let itemHeight = (parseInt(navi_height) - setting['textSize']);
html += cssNaviPrefix + ' ul li.item { height: ' + itemHeight + 'px !important; } ';
html += cssNaviPrefix + '{ height: ' + itemHeight * dragdrop.length + 'px !important; } ';
}
}
}
// Set width of item (%) ---------------------------------------------------------
// Default is 100/item numbers
html += cssNaviPrefix + ' ul li.item { width: ' + (100 / dragdrop.length) + '%; } ';
// Mobile ---------------------------------------------------------
html += ' @media only screen and (max-width: 600px) {';
// If added by block, forget this code
//if( !isNaviBlock ) {
if (setting['mobileDisplay'] == "false" || setting['mobileDisplay'] == false)
html += cssNaviPrefix + ' { display: none; }';
if( !isMobileMode() )
html += cssNaviPrefix + ' { display: none; }';
//}
if (setting['mobileAutoHide'] == "true" || setting['mobileAutoHide'] == true) {
if (setting['mobileDisplay'] == "true" || setting['mobileDisplay'] == true)
scrollToHide("mobile", cssNaviPrefix);
}
html += '} ';
if (setting['layout'] != 4) // Bỏ qua tất cả nếu là mode float button
{
html += ' @media only screen and (max-width: 600px) {';
html += generateMobileCSS(cssNaviPrefix, setting, dragdrop);
html += '}';
}
// Desktop ---------------------------------------------------------
html += ' @media only screen and (min-width: 601px) {';
// If added by block, forget this code
//if( !isNaviBlock ) {
if (setting['desktopDisplay'] == "false" || setting['desktopDisplay'] == false)
html += cssNaviPrefix + ' { display: none; }';
if( isMobileMode() )
html += cssNaviPrefix + ' { display: none; }';
//}
if (setting['desktopAutoHide'] == "true" || setting['desktopAutoHide'] == true) {
//console.log(setting['desktopPosition']);
if( setting['desktopDisplay'] == "true" || setting['desktopDisplay'] == true )
if (setting['desktopPosition'] != 7 && setting['desktopPosition'] != 8 && setting['desktopPosition'] != 9 && setting['desktopPosition'] != 10)
scrollToHide("desktop", cssNaviPrefix);
}
html += '} ';
if (setting['layout'] != 4) {
html += ' @media only screen and (min-width: 601px) {';
html += generateDesktopCSS(cssNaviPrefix, setting, dragdrop);
html += '}';
}
html += '';
naviman_appItem.insertAdjacentHTML('beforebegin', html);
// JS / jQuery ---------------------------------------------------------
let jsCode = clearCSS_JS(setting['jsCode']);
//naviman_appItem.insertAdjacentHTML('beforebegin', jsCode);
var jsScript = document.createElement('script');
jsScript.textContent = jsCode;
document.body.appendChild(jsScript);
// CSS ---------------------------------------------------------
let cssCode = '';
naviman_appItem.insertAdjacentHTML('beforebegin', cssCode);
let cssCodeGlobal = '';
naviman_appItem.insertAdjacentHTML('beforebegin', cssCodeGlobal);
};
var generateMobileCSS = function(cssNaviPrefix, setting, dragdrop) {
let html = "";
let navi_height = setting['height'];
if (isMobileMode()) { // Đôi khi ko phải là .footer thì sao?
if (setting['mobilePosition'] == 1) { // Thêm footer padding-bottom
if (setting['mobileAutoHide'] != "true" && setting['mobileAutoHide'] != true) {
html += ' body { padding-bottom: ' + (parseInt(navi_height) + 0) + 'px; }';
}
html += cssNaviPrefix + ' { box-shadow: 0px -4px 8px 0px rgba(0, 0, 0, 0.05); } '; // Nếu vị trí 1 thì hất bóng lên.
}
if (setting['mobilePosition'] == 2) {
html += cssNaviPrefix + ' { bottom: initial; top:0px; } body {padding-top: ' + navi_height + 'px;} ';
html += cssNaviPrefix + ' ul li ul.children { bottom: initial; top: ' + (parseInt(navi_height) + 0) + 'px; ' + BOX_SHADOW + ' } ';
html += cssNaviPrefix + ' { border-radius: 0px 0px ' + setting['borderRadius'] + 'px ' + setting['borderRadius'] + 'px } ';
if (setting['layout'] == 2)
html += cssNaviPrefix + ' ul li.item_primary .inner { margin-top: 0px } ';
if (setting['layout'] == 3) {
if (setting['bottomMargin'] != 0) {
html += cssNaviPrefix + ' { bottom: initial; top: ' + (parseInt(setting['bottomMargin'])) + 'px; } ';
html += cssNaviPrefix + ' { border-radius: ' + setting['borderRadius'] + 'px } ';
html += ' body {padding-top: ' + (parseInt(navi_height) + parseInt(setting['bottomMargin']) + 8) + 'px} ';
}
}
html += cssNaviPrefix + ' ul li ul.children { border-top: solid 1px rgba(0,0,0,0.05); border-bottom:0px; } '; // Thêm cái line ở giữa level 1 và 2
}
if (setting['mobilePosition'] == 1 || setting['mobilePosition'] == 2) {
if( setting['settingMargin']['left'] != 0 || setting['settingMargin']['right'] != 0) {
html += cssNaviPrefix + ' { width: calc( 100% - ' + (parseInt(setting['settingMargin']['left']) + parseInt(setting['settingMargin']['right'])) + 'px) }; ';
}
}
if (setting['mobilePosition'] == 3 || setting['mobilePosition'] == 5) {
html += cssNaviPrefix + ' { width: ' + navi_height + 'px; left: initial; right: 0px; height: ' + ((parseInt(navi_height) + 8) * dragdrop.length) + 'px } ';
html += cssNaviPrefix + ' ul li.item { width: ' + navi_height + 'px; height: ' + (parseInt(navi_height) + 8) + 'px; } ';
html += cssNaviPrefix + ' { top: ' + ((windowHeight - ((parseInt(navi_height) + 8) * dragdrop.length)) / 2) + 'px; }';
html += cssNaviPrefix + ' { border-radius: ' + setting['borderRadius'] + 'px 0px 0px ' + setting['borderRadius'] + 'px } ';
html += cssNaviPrefix + ' ul li ul.children { left: -201px; bottom: initial; margin-top: -' + (parseInt(navi_height) + 8) + 'px; width: ' + VERTICAL_CHILDREN_WIDTH + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children { box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.10); } ';
if (setting['layout'] == 2)
html += cssNaviPrefix + ' ul li.item_primary .inner { margin-top: 0px; margin-left: -8px } ';
if (setting['layout'] == 3) {
if (setting['bottomMargin'] != "") {
html += cssNaviPrefix + ' { right: ' + (parseInt(setting['bottomMargin'])) + 'px; } ';
html += cssNaviPrefix + ' { border-radius: ' + setting['borderRadius'] + 'px } ';
}
}
if (setting['mobilePosition'] == 5) {
html += cssNaviPrefix + ' { top: initial; bottom: 24px; } ';
}
}
if (setting['mobilePosition'] == 4 || setting['mobilePosition'] == 6) {
html += cssNaviPrefix + ' { width: ' + navi_height + 'px; right: initial; left: 0px; height: ' + ((parseInt(navi_height) + 8) * dragdrop.length) + 'px } ';
html += cssNaviPrefix + ' ul li.item { width: ' + navi_height + 'px; height: ' + (parseInt(navi_height) + 8) + 'px; } ';
html += cssNaviPrefix + ' { top: ' + ((windowHeight - ((parseInt(navi_height) + 8) * dragdrop.length)) / 2) + 'px; }';
html += cssNaviPrefix + ' { border-radius: 0px ' + setting['borderRadius'] + 'px ' + setting['borderRadius'] + 'px 0px } ';
html += cssNaviPrefix + ' ul li ul.children { left: ' + (parseInt(navi_height) + 1) + 'px; bottom: initial; margin-top: -' + (parseInt(navi_height) + 8) + 'px; width: ' + VERTICAL_CHILDREN_WIDTH + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children { box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.10); } ';
if (setting['layout'] == 2)
html += cssNaviPrefix + ' ul li.item_primary .inner { margin-top: 0px; margin-left: 1px } ';
if (setting['layout'] == 3) {
if (setting['bottomMargin'] != "") {
html += cssNaviPrefix + ' { left: ' + (parseInt(setting['bottomMargin'])) + 'px; } ';
html += cssNaviPrefix + ' { border-radius: ' + setting['borderRadius'] + 'px } ';
}
}
if (setting['mobilePosition'] == 6) {
html += cssNaviPrefix + ' { top: initial; bottom: 24px; } ';
}
}
if (setting['mobilePosition'] == 3 || setting['mobilePosition'] == 4 || setting['mobilePosition'] == 5 || setting['mobilePosition'] == 6) {
if (isHadValue(setting['dividerColor']))
html += cssNaviPrefix + ' ul li.item_divider { border-right: 0px; margin-right: 0px; border-bottom: solid 1px ' + setting['dividerColor'] + '; margin-bottom: -1px; } ';
html += cssNaviPrefix + ' ul li ul.children {width: ' + setting['submenuWidth'] + 'px; } ';
if (setting['mobilePosition'] == 3 || setting['mobilePosition'] == 5)
html += cssNaviPrefix + ' ul li ul.children {left: ' + (-(setting['submenuWidth']) - 1) + 'px; } ';
if (setting['layout'] != 2)
html += cssNaviPrefix + ' ul li.item .inner { padding: 8px 0px 0px 0px; } ';
}
if (setting['mobilePosition'] == 5 || setting['mobilePosition'] == 6) { // cho level 2 quay ngược lên trên
html += cssNaviPrefix + ' ul li.item { position: relative; } ';
html += cssNaviPrefix + ' ul li ul.children { margin-top: initial; bottom: 0px; top: initial; } ';
}
}
return html;
};
var generateDesktopCSS = function (cssNaviPrefix, setting, dragdrop) {
let html = "";
let navi_height = setting['height'];
if (!isMobileMode()) {
if (setting['desktopPosition'] == 1)
html += cssNaviPrefix + ' { width: ' + DESKTOP_MAX_WIDTH + 'px; left: ' + ((windowWidth - DESKTOP_MAX_WIDTH) / 2) + 'px; } ';
if (setting['desktopPosition'] == 2)
html += cssNaviPrefix + ' { width: ' + DESKTOP_MAX_WIDTH + 'px; left: initial; right: 16px; } ';
if (setting['desktopPosition'] == 3)
html += cssNaviPrefix + ' { width: ' + DESKTOP_MAX_WIDTH + 'px; left: 16px; } ';
if (setting['desktopPosition'] == 4)
html += cssNaviPrefix + ' .navigation { width: ' + (DESKTOP_MAX_WIDTH * 2) + 'px; left: ' + ((windowWidth - DESKTOP_MAX_WIDTH * 2) / 2) + 'px } ';
if (setting['desktopPosition'] == 1 || setting['desktopPosition'] == 2 || setting['desktopPosition'] == 3 || setting['desktopPosition'] == 4) {
html += cssNaviPrefix + ' ul li.item{ position: relative; } ';
html += cssNaviPrefix + ' ul li ul.children{ left: initial; right: 0px; bottom: ' + (parseInt(navi_height) + 1) + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children {width: ' + setting['submenuWidth'] + 'px; } ';
}
if (setting['desktopPosition'] == 5) {
html += cssNaviPrefix + ' { width: ' + navi_height + 'px; left: initial; right: 0px; height: ' + ((parseInt(navi_height) + 8) * dragdrop.length) + 'px } ';
html += cssNaviPrefix + ' ul li.item { width: ' + navi_height + 'px; height: ' + (parseInt(navi_height) + 8) + 'px; } ';
html += cssNaviPrefix + ' { top: ' + ((windowHeight - ((parseInt(navi_height) + 8) * dragdrop.length)) / 2) + 'px; }';
html += cssNaviPrefix + ' { border-radius: ' + setting['borderRadius'] + 'px 0px 0px ' + setting['borderRadius'] + 'px } ';
html += cssNaviPrefix + ' ul li ul.children { left: -201px; bottom: initial; margin-top: -' + (parseInt(navi_height) + 8) + 'px; width: ' + VERTICAL_CHILDREN_WIDTH + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children { ' + BOX_SHADOW + ' } ';
if (setting['layout'] == 2)
html += cssNaviPrefix + ' ul li.item_primary .inner { margin-top: 0px; margin-left: -8px } ';
if (setting['layout'] == 3) {
if (setting['bottomMargin'] != "") {
html += cssNaviPrefix + ' { right: ' + (parseInt(setting['bottomMargin'])) + 'px; } ';
html += cssNaviPrefix + ' { border-radius: ' + setting['borderRadius'] + 'px } ';
}
}
}
if (setting['desktopPosition'] == 6) { /* = mobile(4) */
html += cssNaviPrefix + ' { width: ' + navi_height + 'px; right: initial; left: 0px; height: ' + ((parseInt(navi_height) + 8) * dragdrop.length) + 'px } ';
html += cssNaviPrefix + ' ul li.item { width: ' + navi_height + 'px; height: ' + (parseInt(navi_height) + 8) + 'px; } ';
html += cssNaviPrefix + ' { top: ' + ((windowHeight - ((parseInt(navi_height) + 8) * dragdrop.length)) / 2) + 'px; }';
html += cssNaviPrefix + ' { border-radius: 0px ' + setting['borderRadius'] + 'px ' + setting['borderRadius'] + 'px 0px } ';
html += cssNaviPrefix + ' ul li ul.children { left: ' + (parseInt(navi_height) + 1) + 'px; bottom: initial; margin-top: -' + (parseInt(navi_height) + 8) + 'px; width: ' + VERTICAL_CHILDREN_WIDTH + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children { ' + BOX_SHADOW + ' } ';
if (setting['layout'] == 2)
html += cssNaviPrefix + ' ul li.item_primary .inner { margin-top: 0px; margin-left: 1px } ';
if (setting['layout'] == 3) {
if (setting['bottomMargin'] != "") {
html += cssNaviPrefix + ' { left: ' + (parseInt(setting['bottomMargin'])) + 'px; } ';
html += cssNaviPrefix + ' { border-radius: ' + setting['borderRadius'] + 'px } ';
}
}
}
if (setting['desktopPosition'] == 5 || setting['desktopPosition'] == 6 || setting['desktopPosition'] == 7 || setting['desktopPosition'] == 8 || setting['desktopPosition'] == 9 || setting['desktopPosition'] == 10) {
if (isHadValue(setting['dividerColor']))
html += cssNaviPrefix + ' ul li.item_divider { border-right: 0px; margin-right: 0px; border-bottom: solid 1px ' + setting['dividerColor'] + '; margin-bottom: -1px; } ';
if (setting['layout'] != 2) // Nếu là layout 2 thì ko làm việc này.
html += cssNaviPrefix + ' ul li.item .inner {width: initial; } ';
let submenuWidth = (-setting['submenuWidth'] - 1);
if (setting['desktopPosition'] == 6) submenuWidth = (parseInt(navi_height) + 1);
html += cssNaviPrefix + ' ul li ul.children {width: ' + setting['submenuWidth'] + 'px; left: ' + submenuWidth + 'px; } ';
html += cssNaviPrefix + ' ul li.item { width: 100%; } ';
}
if (setting['desktopPosition'] == 7 || setting['desktopPosition'] == 8) {
html += ' body {width: calc(100% - '+ navi_height +'px); margin-left: '+ navi_height +'px; } ';
html += cssNaviPrefix + ' { width: ' + navi_height + 'px; right: initial; left: 0px; top: 0px; height: 100vh; padding-top: 16px; } ';
html += cssNaviPrefix + ' ul li.item { width: ' + navi_height + 'px; height: ' + (parseInt(navi_height) + 8) + 'px; } ';
html += cssNaviPrefix + ' { border-radius: 0px; } ';
html += cssNaviPrefix + ' ul li ul.children { left: ' + (parseInt(navi_height) + 1) + 'px; bottom: initial; margin-top: -' + (parseInt(navi_height) + 8) + 'px; width: ' + VERTICAL_CHILDREN_WIDTH + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children { ' + BOX_SHADOW + ' } ';
if (setting['desktopPosition'] == 7 )
html += cssNaviPrefix + ' { padding-top: 16px; } ';
else
if (setting['desktopPosition'] == 8 ) {
let bodyPaddingTop = (window.innerHeight - (parseInt(navi_height) + 8) * dragdrop.length) / 2;
html += cssNaviPrefix + ' { padding-top: '+ bodyPaddingTop +'px; } ';
}
html += cssNaviPrefix + ' ul li.item { width: 100%; min-width: 24px; } '; // Fix lỗi nếu padding quá lớn thì bị dồn cục
}
if (setting['desktopPosition'] == 9 || setting['desktopPosition'] == 10) {
html += ' body {width: calc(100% - '+ navi_height +'px); margin-right: '+ navi_height +'px; } ';
html += cssNaviPrefix + ' { width: ' + navi_height + 'px; right: 0; left: initial; top: 0px; height: 100vh; padding-top: 16px; } ';
html += cssNaviPrefix + ' ul li.item { width: ' + navi_height + 'px; height: ' + (parseInt(navi_height) + 8) + 'px; } ';
html += cssNaviPrefix + ' { border-radius: 0px; } ';
html += cssNaviPrefix + ' ul li ul.children { right: ' + (parseInt(navi_height) + 1) + 'px; bottom: initial; margin-top: -' + (parseInt(navi_height) + 8) + 'px; width: ' + VERTICAL_CHILDREN_WIDTH + 'px; } ';
html += cssNaviPrefix + ' ul li ul.children { ' + BOX_SHADOW + ' } ';
let submenuWidth = (-setting['submenuWidth'] - 1);
html += cssNaviPrefix + ' ul li ul.children {width: ' + setting['submenuWidth'] + 'px; left: ' + submenuWidth + 'px; } ';
if (setting['desktopPosition'] == 9 )
html += cssNaviPrefix + ' { padding-top: 16px; } ';
else
if (setting['desktopPosition'] == 10 ) {
let bodyPaddingTop = (window.innerHeight - (parseInt(navi_height) + 8) * dragdrop.length) / 2;
html += cssNaviPrefix + ' { padding-top: '+ bodyPaddingTop +'px; } ';
}
html += cssNaviPrefix + ' ul li.item { width: 100%; min-width: 24px; } '; // Fix lỗi nếu padding quá lớn thì bị dồn cục
}
}
return html;
};
var init = function () {
};
var drawBottomNav = function (response, naviman_domain, var_shop, var_embed_id) {
var naviman_app = document.getElementById("naviman_app");
shop = var_shop;
embed_id = var_embed_id;
function encodeBody( url ) {
var output = url;
const words = output.split('body=');
if( words.length == 2 ) {
//console.log( words );
var body = encodeURIComponent(words[1]);
output = words[0] + 'body=' + body;
}
return output;
}
function isUrlContain(keywordsSetting) {
var url = window.location.pathname + window.location.search; //window.location.href.toLowerCase();
url = url.toLowerCase()
var keywords = keywordsSetting.split(',');
for (let i = 0; i < keywords.length; i++) {
keywords[i] = keywords[i].trim().toLowerCase();
if( keywords[i] != '' ) {
if( url.includes( keywords[i] ) )
return true;
}
}
return false;
}
function generaChildrenTree(children, naviItem) {
var html = '
';
children.forEach((child) => {
let is_parent = false;
if (typeof (child["children"]) !== 'undefined')
if (child["children"].length > 0)
is_parent = true;
let child_url = naviLanguage.stringByLanguage(child["url"]);
if( child_url.length == 10 ) // open:Inbox
if( child_url.substring(0, 10).toLowerCase() == "open:inbox" )
if( document.querySelector('#ShopifyChat') != null )
document.querySelector('#ShopifyChat').style.visibility = "hidden";
let isTel = false;
if( child_url.length >= 4 ) // tel
if( child_url.substring(0, 4).toLowerCase() == "tel:" )
isTel = true;
let isSMS = false;
if( child_url.length >= 4 ) // sms
if( child_url.substring(0, 4).toLowerCase() == "sms:" )
isSMS = true;
let child_css = "child ";
if (child["divider"] == 1) child_css += "child_divider ";
if (child["badge"] == 1) child_css += "child_badge ";
var onclick = 'onclick="return naviman.gotoUrl(event, this, '+ is_parent +', \'' + child_url + '\', \''+ naviItem["embed_id"] +'\')"';
if( isTel || isSMS ) onclick = "";
var style_positive = "";
if( isTel || isSMS ) style_positive = ' style="position:relative" ';
html += '- ';
html += itemMedia(child['icon'], child['image'], naviman_domain);
html += '
';
html += '
';
html += naviLanguage.stringByLanguage(child["name"]);
html += '
';
if (child["description"] != "")
html += '
' + naviLanguage.stringByLanguage(child["description"]) + '
';
html += '
';
// TODO: Check and optimize
if( isTel || isSMS ) {
html += '';
html += ''
html += '';
}
// Children -------------------<
if (is_parent)
html += generaChildrenTree(child["children"], naviItem);
html += ' ';
});
html += '
';
return html;
}
var isNaviBlock = (embed_id != '' )
response.forEach((naviItem) => {
var isDisplayed = true;
if (typeof (DEPLOY_ENVIROIMENT) == 'undefined')
if (naviItem["data"]["setting"]["displayGlobal"] == "1") {
let displayGlobalPages = naviItem["data"]["setting"]["displayGlobalPages"];
let currentTemplate = getCurrentTemplate();
if (!displayGlobalPages.includes(currentTemplate))
isDisplayed = false;
}
// Publish contain/ Don't contain Keyword ------------------------------------------------------
if (isHadValue(naviItem["data"]["setting"]['publishContainKeyword'])) {
if( isUrlContain( naviItem["data"]["setting"]['publishContainKeyword'] ) )
isDisplayed = true;
else
isDisplayed = false;
}
if (isHadValue(naviItem["data"]["setting"]['publishDontContainKeyword'])) {
if( isUrlContain( naviItem["data"]["setting"]['publishDontContainKeyword'] ) )
isDisplayed = false;
else
isDisplayed = true;
}
if (isDisplayed) {
let data = naviItem["data"];
naviman_app.insertAdjacentHTML('beforeend', '');
var naviman_appItem = document.getElementById(naviItem["embed_id"]);
if (data["setting"]['layout'] == 2) {
var item_primary = 0;
if (data["dragdrop"].length == 7 || data["dragdrop"].length == 5 || data["dragdrop"].length == 3)
item_primary = (data["dragdrop"].length + 1) / 2;
}
naviman_appItem.classList.add('naviman_layout' + data["setting"]['layout']);
generateCSS(naviman_appItem, naviItem["embed_id"], data["setting"], data["dragdrop"], isNaviBlock);
// Increase visit count -------------------------------------------------
jsonp(naviman_domain + 'ajax-visit.php?action=increateVisitCount' + '&shop=' + shop).then(function(data){
//console.log("Navi+ is generated!");
});
let item_count = 0;
var html = '';
data["dragdrop"].forEach((item) => {
item_count++;
let is_parent = false;
if (typeof (item["children"]) !== 'undefined')
if (item["children"].length > 0)
is_parent = true;
let item_css = "item ";
if (item_primary == item_count) item_css += "item_primary ";
if (item["divider"] == 1) item_css += "item_divider ";
/** Badge beg ********************************/
var isShowBadge = BADGE_HIDE;
if (item["badge"] == 1) {
if( isHadValue (item["badgeiscart"]) ) {
if (item["badgeiscart"] == 0)
isShowBadge = BADGE_HIDE;
else {
isShowBadge = BADGE_ISCART_WITHCOUNT;
}
}else
isShowBadge = BADGE_DOT;
}
if (item["badge"] == 1) {
item_css += " item_badge";
if( isHadValue (item["badgeiscart"]) ) {
if (item["badgeiscart"] == 1) {
item_css += " item_badge_withcount ";
if (item["badgecartcount"] == 1)
item_css += "";
else
item_css += " item_badge_withcount item_badge_withcount_hide";
}
}
}
else
item_css += ""; // Do nothing
/*if( isShowBadge == BADGE_DOT ) item_css += " item_badge item_badge_withcount item_badge_withcount_hide";
if( isShowBadge == BADGE_ISCART_WITHCOUNT ) item_css += " item_badge item_badge_withcount ";*/
/** Badge end ********************************/
//console.log( item );
let item_url = naviLanguage.stringByLanguage(item["url"]);
if( item_url.length == 10 ) // open:Inbox
if( item_url.substring(0, 10).toLowerCase() == "open:inbox" )
if( document.querySelector('#ShopifyChat') != null )
document.querySelector('#ShopifyChat').style.visibility = "hidden";
let isTel = false;
if( item_url.length >= 4 ) // tel
if( item_url.substring(0, 4).toLowerCase() == "tel:" )
isTel = true;
let isSMS = false;
if( item_url.length >= 4 ) // tel
if( item_url.substring(0, 4).toLowerCase() == "sms:" )
isSMS = true;
html += '- ';
html += '';
// Children -------------------<
if (is_parent)
html += generaChildrenTree(item["children"], naviItem);
html += '
';
});
html += '
';
naviman_appItem.insertAdjacentHTML('beforeend', html );
} // isDisplayed
});
};
var saveLog = function(logShop, logToUrl, logFromUrl, logItemName, logEmbedId, logPlatform ) {
let tranferData = {
shop: logShop,
to_url: logToUrl,
from_url: logFromUrl,
item_name: logItemName,
embed_id: logEmbedId,
platform: logPlatform
};
const params = new URLSearchParams(tranferData);
// console.log(naviman_domain + 'ajax-dataWH.php?action=saveLog' + '&' + params.toString());
jsonp(naviman_domain + 'ajax-dataWH.php?action=saveLog' + '&' + params.toString()).then(function(data){
});
};
var gotoUrl = function (event, item, is_parent, url, embed_id) {
//console.log( item );
if (!is_parent) {
if (typeof DEPLOY_ENVIROIMENT != 'undefined')
if (DEPLOY_ENVIROIMENT == "DESIGNING")
return false;
let logShop = shop;
let logFromUrl = window.location.href;
let logItemName = item.dataset.name;
let logEmbedId = embed_id; // Lỗi ở đây rồi
let logPlatform = "M";
if( window.innerWidth > 600 )
logPlatform = "D";
let openNewTab = false;
if( url.toLowerCase().includes("@new") ) {
openNewTab = true;
url = url.replace(/@new/gi, '');
}
if(url.substring(0, 13).toLowerCase() == "https://m.me/")
openNewTab = true;
if(url.substring(0, 14).toLowerCase() == "https://wa.me/")
openNewTab = true;
let logDomain = "https://" + window.location.hostname;
url = url.trim();
if( url == "" ) { // Home page
saveLog( logShop, logDomain, logFromUrl, logItemName, logEmbedId, logPlatform );
if( openNewTab )
window.open(logDomain );
else
window.location.href = logDomain;
}
if( url == "#" ) { // Do nothing
saveLog( logShop, url, logFromUrl, logItemName, logEmbedId, logPlatform );
return false;
}
if( url.length > 1 ) {
if( url.charAt(0) == "#" ) { // #gotoAnchor
let logTo = logFromUrl + url;
saveLog( logShop, logTo, logFromUrl, logItemName, logEmbedId, logPlatform );
window.location.href = logTo;
}
if( url.length >= 4 ) // tel
if( url.substring(0, 4).toLowerCase() == "tel:" ) {
//window.open( url );
//window.location.href = url;
return false;
}
if( url.length >= 4 ) // sms
if( url.substring(0, 4).toLowerCase() == "sms:" ) {
//window.open( url );
//window.location.href = url;
return false;
}
if( url.length >= 5 ) // open
if( url.substring(0, 5).toLowerCase() == "open:" ) {
jsFunction = url.strReplace(':', '');
saveLog( logShop, url, logFromUrl, logItemName, logEmbedId, logPlatform );
eval("naviman." + jsFunction)();
return false;
}
if( url.length >= 7 ) // mailto
if( url.substring(0, 7).toLowerCase() == "mailto:" ) {
window.open( url );
return false;
}
if( url.length >= 11 ) // javascript
if( url.substring(0, 11).toLowerCase() == "javascript:" )
{
let jsFunction = url.substring(11, url.length );
jsFunction = jsFunction.strReplace('(', '').replaceAll(')', '');
saveLog( logShop, 'js/' + jsFunction, logFromUrl, logItemName, logEmbedId, logPlatform );
console.log("Call function: " + jsFunction);
eval(jsFunction)();
event.preventDefault(); // Ko có tác dụng mấy
return false;
}
let isHadDomain = false;
if( url.length >= 4 )
if( url.substring(0, 4).toLowerCase() == "http" )
isHadDomain = true;
if( !isHadDomain ) {
if( url.charAt(0) != "/" )
url = "/" + url;
url = logDomain + url;
}
saveLog( logShop, url, logFromUrl, logItemName, logEmbedId, logPlatform );
if( openNewTab )
window.open(url );
else
window.location.href = url;
}
} else {
if( item.classList.contains("child") )
showLevelMultiItems( item );
else
showLevel1Items( item );
}
// Tránh việc gọi ông con thì lại gọi thêm ông bố
event.stopPropagation();
};
var showLevelMultiItems = function( menuItem ) {
var ulParent = menuItem.parentElement;
let ulChildrent = menuItem.querySelector('ul.children');
var liTitle = document.createElement("li");
liTitle.setAttribute("class", "overlay-container");
liTitle.innerHTML = '';
ulParent.appendChild(liTitle);
displayElement( ulChildrent, true );
var ulLength = 8;
let liChildrent = ulChildrent.querySelectorAll("li.child");
for( i = 0; i < liChildrent.length; i ++ )
ulLength += liChildrent[i].offsetHeight;
// Expand menu height
menuItem.parentElement.style.height = ulLength + "px"; //(8 + ulChildrent.querySelector( 'li.child' ).offsetHeight * ulChildrent.querySelectorAll("li.child").length) + "px";
menuItem.parentElement.scrollTop = 0;
menuItem.parentElement.style.overflow = "hidden";
// Fix level 3 menu
if( ulChildrent.style.zIndex != 3 ) {
// 1. Cập nhật chiều cao của level 3 bằng level 2
ulChildrent.style.height = ulLength + "px";
// 2. Cập nhật top của level 3 bằng 0/level 2
ulChildrentTopFixed = ulChildrent.getBoundingClientRect().top - ulChildrent.parentElement.parentElement.getBoundingClientRect().top;
ulChildrent.style.top = (-ulChildrentTopFixed) + "px";
// 3. Đánh dấu là đã cập nhật rồi, ko cần update lại
ulChildrent.style.zIndex = 3;
}
}
var backToLevel1 = function ( event, item ) {
// Hide all level 2
var level1Childrens = item.parentElement.parentElement.getElementsByClassName("children");
for(var i = 0; i < level1Childrens.length; i++){
displayElement( level1Childrens[i], false );
}
var parrent = item.parentElement.parentElement;
parrent.style.height = "initial";
parrent.style.overflow = "auto";
// Remove overlay
var overlay = item.parentElement;
overlay.remove();
event.stopPropagation();
}
var resetAllItems = function() {
document.querySelectorAll('#naviman_app ul.children').forEach((item) => {
item.style.display = "none";
});
document.querySelectorAll('#naviman_app span.arrow').forEach((item) => {
item.style.display = "none";
});
document.querySelectorAll('#naviman_app ul.children').forEach((item) => {
item.style.height = "initial";
});
document.querySelectorAll('#naviman_app li.overlay-container').forEach((item) => {
item.remove();
});
}
var showLevel1Items = function( menuItem ) {
// 1. Kiểm tra xem có những menu item nào đang được hiện không
var is_showing = true;
if (menuItem != null )
is_showing = (menuItem.querySelector('ul.children').style.display === "block");
// 2. Xoá sạch trạng thái hiện tại đi
resetAllItems();
// 3. Kiểm tra nếu chưa hiện thì hiện các ông con
if (menuItem != null ) {
if (!is_showing) {
displayElement( menuItem.querySelector('ul.children'), true );
displayElement( menuItem.querySelector('span.arrow'), true );
menuItem.querySelector('ul.children').style.overflow = "auto";
} else {
displayElement( menuItem.querySelector('ul.children'), false );
displayElement( menuItem.querySelector('span.arrow'), false );
}
}
};
var openMobileMenu = function() {
const divMenu = document.querySelector('.header__icon--menu');
divMenu.addEventListener('click', () => {}); // Xem lai cho false nay
divMenu.click();
};
var openCart = function() {
const divMenu = document.querySelector('.header__icon--cart');
divMenu.addEventListener('click', () => {});
divMenu.click();
};
var openSearch = function() {
var isDawnFamily = true;
if(document.querySelector('details-modal.header__search') == null)
isDawnFamily = false;
if(document.querySelector('details-modal.header__search').querySelector("details") == null)
isDawnFamily = false;
// Dawn
if( isDawnFamily ) {
const divMenu = document.querySelector('details-modal.header__search').querySelector("details");
divMenu.setAttribute("open", "true");
divMenu.querySelector("input").focus();
}else {
const divMenu = document.querySelector('.header__icon--search');
divMenu.addEventListener('click', () => {});
divMenu.click();
}
};
var scrollToHide = function (screen, cssNaviPrefix) {
let autoHide = false;
if (screen == "mobile") {
if (isMobileMode())
autoHide = true;
} else {
if (!isMobileMode())
autoHide = true;
}
let obj = document.getElementsByClassName(cssNaviPrefix.substr(1) )[0]; // SF-1234567890
if (autoHide) {
window.addEventListener('scroll',
function (e) {
var scrollTop = document.documentElement.scrollTop;
if (scrollTop > SCROLL_TO_HIDE) {
obj.style.display = 'none';
} else {
obj.style.display = 'block';
}
});
}
};
var openInbox_loopHideChat = function () {
var isLoop = true;
//console.log("loopHideChat");
if( document.querySelector('#ShopifyChat').getAttribute("is-open") == "false" )
if( document.querySelector('#ShopifyChat').style.visibility == "visible" ) {
document.querySelector('#ShopifyChat').style.visibility = "hidden";
isLoop = false;
}
if( isLoop ) {
setTimeout(function () {
openInbox_loopHideChat();
}, 200);
}
};
var openInbox = function() {
if( document.querySelector('#ShopifyChat') == null ) {
console.log("Navi+: Shopify inbox is not installed. Read document here");
}
var divMenu = document.querySelector('#ShopifyChat').shadowRoot.querySelector('.chat-toggle');
document.querySelector('#ShopifyChat').style.visibility = "visible";
divMenu.addEventListener('click', () => {});
divMenu.click();
setTimeout(function() {
openInbox_loopHideChat();
}, 200);
};
var openInboxWithoutReplace = function() {
if( document.querySelector('#ShopifyChat') == null ) {
console.log("Navi+: Shopify inbox is not installed. Read document here");
}
var divMenu = document.querySelector('#ShopifyChat').shadowRoot.querySelector('.chat-toggle');
document.querySelector('#ShopifyChat').style.visibility = "visible";
divMenu.addEventListener('click', () => {});
divMenu.click();
};
var asyncGetCart = async function() {
const result = await fetch(window.Shopify.routes.root + 'cart.json');
if (result.status === 200) {
return result.json();
}
throw new Error(`Failed to get request, Shopify returned ${result.status} ${result.statusText}`);
};
var updateCartCount = function() {
asyncGetCart().then( function(result) {
var span = document.querySelectorAll('li.item_badge_withcount span.cart_count');
for (var i = 0; i < span.length; i++) {
span[i].textContent = result.item_count;
}
var span_hide = document.querySelectorAll('li.item_badge_withcount');
if( result.item_count == 0) {
console.log(span_hide);
/*for (var i = 0; i < span_hide.length; i++) {
span_hide[i].querySelector('.icon::before').style.display = "none";
}*/
}else {
}
});
};
/*window.addEventListener('SCE:mutate', (event) => {
updateCartCount();
});*/
/** Library for cart event listener ********************/
(function () {
if (!window || !window.Shopify) return;
const CartEvents = {
add: "SCE:add",
update: "SCE:update",
change: "SCE:change",
clear: "SCE:clear",
mutate: "SCE:mutate",
};
const ShopifyCartURLs = [
"/cart/add",
"/cart/update",
"/cart/change",
"/cart/clear",
"/cart/add.js",
"/cart/update.js",
"/cart/change.js",
"/cart/clear.js",
];
function isShopifyCartURL(url) {
if (!url) return false;
if (typeof url === 'string' || url instanceof String) {
const path = url.split("/").pop();
return ShopifyCartURLs.includes(`/cart/${path}`);
}
return false;
}
function updateType(url) {
if (!url) return false;
if (url.includes("cart/add")) {
return "add";
} else if (url.includes("cart/update")) {
return "update";
} else if (url.includes("cart/change")) {
return "change";
} else if (url.includes("cart/clear")) {
return "clear";
} else return false;
}
function dispatchEvent(url, detail) {
if (typeof detail === "string") {
try {
detail = JSON.parse(detail);
console.log( detail );
} catch {}
}
window.dispatchEvent(new CustomEvent(CartEvents.mutate, { detail }));
const type = updateType(url);
switch (type) {
case "add":
window.dispatchEvent(new CustomEvent(CartEvents.add, { detail }));
break;
case "update":
window.dispatchEvent(new CustomEvent(CartEvents.update, { detail }));
break;
case "change":
window.dispatchEvent(new CustomEvent(CartEvents.change, { detail }));
break;
case "clear":
window.dispatchEvent(new CustomEvent(CartEvents.clear, { detail }));
break;
default:
break;
}
}
function XHROverride() {
if (!window.XMLHttpRequest) return;
const originalOpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function () {
const url = arguments[1];
this.addEventListener("load", function () {
if (isShopifyCartURL(url)) {
dispatchEvent(url, this.response);
}
});
return originalOpen.apply(this, arguments);
};
}
function fetchOverride() {
if (!window.fetch || typeof window.fetch !== "function") return;
const originalFetch = window.fetch;
window.fetch = function () {
const response = originalFetch.apply(this, arguments);
//console.log(arguments);
if (isShopifyCartURL(arguments[0])) {
response.then((res) => {
res
.clone()
.json()
.then((data) => dispatchEvent(res.url, data));
});
}
return response;
};
}
fetchOverride();
XHROverride();
})();
/******** Active menu item: beg ***********/
function trimChar(str, ch) {
var start = 0,
end = str.length;
while(start < end && str[start] === ch)
++start;
while(end > start && str[end - 1] === ch)
--end;
return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
function topContain( str, compare ) {
str = str.toLowerCase().trim();
compare = compare.toLowerCase().trim();
// console.log(str + " | " + compare);
if( str.trim() == "" )
if( compare.trim() == "" )
return true;
if( str.trim() != "" )
if( compare.trim() == "" )
return false;
if( str.length < compare.length )
return false;
if (str.substring(0, compare.length).includes(compare)) {
return true;
}
return false;
}
/******** Active menu item: end ***********/
var generateActiveItems = function() {
var pathName = trimChar(window.location.pathname, '/');
var naviItems = document.querySelectorAll(".naviItem");
for (navi_item = 0; navi_item < naviItems.length; navi_item++) { // Tìm tất cả các naviItem
const listItems = naviItems[navi_item].querySelectorAll('li');
//console.log(listItems);
for (let i = 0; i < listItems.length; i++) { // Tìm trong tất cả các li
/* Lọc ra url---------------------------------------------------------------*/
var url = listItems[i].getAttribute("linkto");
url = trimChar(url.replace(/^.*\/\/[^\/]+/, ''), '/');
if (topContain(pathName, url)) {
listItems[i].classList.add("navi-active");
var parent = listItems[i];
for (parent_index = 0; parent_index < 10; parent_index++) {
parent = parent.parentElement;
if (parent.tagName == "LI")
parent.classList.add("navi-active");
if (parent.className.includes('naviItem'))
break;
}
}
}
}
}
var setCartCount = function(count)
{
cartCount = count;
};
return {
Name: "Naviman Libraries",
drawBottomNav: drawBottomNav,
init: init,
gotoUrl: gotoUrl,
backToLevel1: backToLevel1,
// public JS functions
openMobileMenu: openMobileMenu,
openCart: openCart,
openSearch: openSearch,
// Work with other applications
openInbox: openInbox,
openInboxWithoutReplace: openInboxWithoutReplace,
isHadValue: isHadValue,
// Cart
setCartCount: setCartCount,
asyncGetCart:asyncGetCart,
updateCartCount:updateCartCount,
generateActiveItems:generateActiveItems,
};
})();
document.onclick=function(event){
if( event.target.closest("#naviman_app ul li ul.children") == null && event.target.closest("#naviman_app .naviItem") == null ) {
document.querySelectorAll('#naviman_app ul li ul.children').forEach((item) => {
item.style.display = "none";
});
}
}
/************** LANGUAGE *************/
var naviLanguage = (function(){
var countryList = {
'ab' : 'Abkhazian',
'aa' : 'Afar',
'af' : 'Afrikaans',
'ak' : 'Akan',
'sq' : 'Albanian',
'am' : 'Amharic',
'ar' : 'Arabic',
'an' : 'Aragonese',
'hy' : 'Armenian',
'as' : 'Assamese',
'av' : 'Avaric',
'ae' : 'Avestan',
'ay' : 'Aymara',
'az' : 'Azerbaijani',
'bm' : 'Bambara',
'ba' : 'Bashkir',
'eu' : 'Basque',
'be' : 'Belarusian',
'bn' : 'Bengali',
'bh' : 'Bihari languages',
'bi' : 'Bislama',
'bs' : 'Bosnian',
'br' : 'Breton',
'bg' : 'Bulgarian',
'my' : 'Burmese',
'ca' : 'Catalan, Valencian',
'km' : 'Central Khmer',
'ch' : 'Chamorro',
'ce' : 'Chechen',
'ny' : 'Chichewa, Chewa, Nyanja',
'zh' : 'Chinese',
'cu' : 'Church Slavonic, Old Bulgarian, Old Church Slavonic',
'cv' : 'Chuvash',
'kw' : 'Cornish',
'co' : 'Corsican',
'cr' : 'Cree',
'hr' : 'Croatian',
'cs' : 'Czech',
'da' : 'Danish',
'dv' : 'Divehi, Dhivehi, Maldivian',
'nl' : 'Dutch, Flemish',
'dz' : 'Dzongkha',
'en' : 'English',
'eo' : 'Esperanto',
'et' : 'Estonian',
'ee' : 'Ewe',
'fo' : 'Faroese',
'fj' : 'Fijian',
'fi' : 'Finnish',
'fr' : 'French',
'ff' : 'Fulah',
'gd' : 'Gaelic, Scottish Gaelic',
'gl' : 'Galician',
'lg' : 'Ganda',
'ka' : 'Georgian',
'de' : 'German',
'ki' : 'Gikuyu, Kikuyu',
'el' : 'Greek (Modern)',
'kl' : 'Greenlandic, Kalaallisut',
'gn' : 'Guarani',
'gu' : 'Gujarati',
'ht' : 'Haitian, Haitian Creole',
'ha' : 'Hausa',
'he' : 'Hebrew',
'hz' : 'Herero',
'hi' : 'Hindi',
'ho' : 'Hiri Motu',
'hu' : 'Hungarian',
'is' : 'Icelandic',
'io' : 'Ido',
'ig' : 'Igbo',
'id' : 'Indonesian',
'ia' : 'Interlingua (International Auxiliary Language Association)',
'ie' : 'Interlingue',
'iu' : 'Inuktitut',
'ik' : 'Inupiaq',
'ga' : 'Irish',
'it' : 'Italian',
'ja' : 'Japanese',
'jv' : 'Javanese',
'kn' : 'Kannada',
'kr' : 'Kanuri',
'ks' : 'Kashmiri',
'kk' : 'Kazakh',
'rw' : 'Kinyarwanda',
'kv' : 'Komi',
'kg' : 'Kongo',
'ko' : 'Korean',
'kj' : 'Kwanyama, Kuanyama',
'ku' : 'Kurdish',
'ky' : 'Kyrgyz',
'lo' : 'Lao',
'la' : 'Latin',
'lv' : 'Latvian',
'lb' : 'Letzeburgesch, Luxembourgish',
'li' : 'Limburgish, Limburgan, Limburger',
'ln' : 'Lingala',
'lt' : 'Lithuanian',
'lu' : 'Luba-Katanga',
'mk' : 'Macedonian',
'mg' : 'Malagasy',
'ms' : 'Malay',
'ml' : 'Malayalam',
'mt' : 'Maltese',
'gv' : 'Manx',
'mi' : 'Maori',
'mr' : 'Marathi',
'mh' : 'Marshallese',
'ro' : 'Moldovan, Moldavian, Romanian',
'mn' : 'Mongolian',
'na' : 'Nauru',
'nv' : 'Navajo, Navaho',
'nd' : 'Northern Ndebele',
'ng' : 'Ndonga',
'ne' : 'Nepali',
'se' : 'Northern Sami',
'no' : 'Norwegian',
'nb' : 'Norwegian Bokmål',
'nn' : 'Norwegian Nynorsk',
'ii' : 'Nuosu, Sichuan Yi',
'oc' : 'Occitan (post 1500)',
'oj' : 'Ojibwa',
'or' : 'Oriya',
'om' : 'Oromo',
'os' : 'Ossetian, Ossetic',
'pi' : 'Pali',
'pa' : 'Panjabi, Punjabi',
'ps' : 'Pashto, Pushto',
'fa' : 'Persian',
'pl' : 'Polish',
'pt' : 'Portuguese',
'qu' : 'Quechua',
'rm' : 'Romansh',
'rn' : 'Rundi',
'ru' : 'Russian',
'sm' : 'Samoan',
'sg' : 'Sango',
'sa' : 'Sanskrit',
'sc' : 'Sardinian',
'sr' : 'Serbian',
'sn' : 'Shona',
'sd' : 'Sindhi',
'si' : 'Sinhala, Sinhalese',
'sk' : 'Slovak',
'sl' : 'Slovenian',
'so' : 'Somali',
'st' : 'Sotho, Southern',
'nr' : 'South Ndebele',
'es' : 'Spanish, Castilian',
'su' : 'Sundanese',
'sw' : 'Swahili',
'ss' : 'Swati',
'sv' : 'Swedish',
'tl' : 'Tagalog',
'ty' : 'Tahitian',
'tg' : 'Tajik',
'ta' : 'Tamil',
'tt' : 'Tatar',
'te' : 'Telugu',
'th' : 'Thai',
'bo' : 'Tibetan',
'ti' : 'Tigrinya',
'to' : 'Tonga (Tonga Islands)',
'ts' : 'Tsonga',
'tn' : 'Tswana',
'tr' : 'Turkish',
'tk' : 'Turkmen',
'tw' : 'Twi',
'ug' : 'Uighur, Uyghur',
'uk' : 'Ukrainian',
'ur' : 'Urdu',
'uz' : 'Uzbek',
've' : 'Venda',
'vi' : 'Vietnamese',
'vo' : 'Volap_k',
'wa' : 'Walloon',
'cy' : 'Welsh',
'fy' : 'Western Frisian',
'wo' : 'Wolof',
'xh' : 'Xhosa',
'yi' : 'Yiddish',
'yo' : 'Yoruba',
'za' : 'Zhuang, Chuang',
'zu' : 'Zulu'
};
function stringByLanguage( str ) {
let arr = str.match(/<.*?>/g);
if( arr == null )
return str;
if( arr.length == 0 )
return str;
// 1. Loại bỏ các phần có
let localizeStr = str;
arr.forEach((item) => {
localizeStr = localizeStr.replace( item, "" );
});
localizeStr = localizeStr.trim();
// 2. Tạo một array gồm language_code:string
langStr = [];
langStr.push(["localize", localizeStr]);
arr.forEach((item) => {
let child = item.replace( "<", "" ).replace( "/>", "" ).replace( ">", "" );
var index = child.indexOf(':');
if( index > -1 ) {
var child_array = [child.slice(0, index).trim(), child.slice(index + 1).trim()];
if(child_array.length == 2)
if( child_array[0] != "" )
langStr.push([child_array[0], child_array[1]]);
}
});
// 3. So sánh trong danh sách trả về
let currentLang = currentLanguage();
//console.log( langStr );
var output = localizeStr;
langStr.forEach((lang) => {
if( lang[0] == currentLang ) {
output = lang[1];
return;
}
});
return output;
}
function currentLanguage() {
let pathName = document.location.pathname;
if( pathName.length < 3 )
return "localize";
for (var lang in countryList) {
var langCom = "/" + lang;
if( pathName.substring(0, 3).toLowerCase() == langCom.toLowerCase() ) {
if( pathName.length == 3 )
return lang;
if( pathName.length > 3 )
if( pathName[3] == "/" || pathName[3] == "&" || pathName[3] == "#" || pathName[3] == "?" || pathName[3] == "%" )
return lang;
}
}
return "localize";
}
return {
Name: "Naviman Language",
stringByLanguage: stringByLanguage,
currentLanguage: currentLanguage,
};
})();
var naviman_runApp = function (e) {
/** 1.Link CSS & icons **************************************/
function linkCSSToHead( href ) {
const link = document.createElement('link');
link.href = href;
link.rel = 'stylesheet';
document.getElementsByTagName('head')[0].appendChild( link );
}
// TODO: GOLIVE
linkCSSToHead( naviman_domain + "uigen.css?v=" + Math.random() );
//linkCSSToHead( "https://naviplus.b-cdn.net/naviplus/golive/uigen-v1.2.4.css" );
/** 2.Get variables **************************************/
let shop = document.currentScript.getAttribute('shop');
let embed_id = '';
if(document.currentScript.getAttribute('embed_id') != null)
embed_id = document.currentScript.getAttribute('embed_id');
let api_url = naviman_domain + "api.php?shop=" + shop;
if( embed_id != '' )
api_url += '&embed_id=' + embed_id;
/** 3.Get API data **************************************/
function jsonp(uri) {
return new Promise(function(resolve, reject) {
var id = '_' + Math.round(10000 * Math.random());
var callbackName = 'jsonp_callback_' + id;
window[callbackName] = function(data) {
delete window[callbackName];
var ele = document.getElementById(id);
ele.parentNode.removeChild(ele);
resolve(data);
}
var src = uri + '&callback=' + callbackName;
var script = document.createElement('script');
script.src = src;
script.id = id;
script.addEventListener('error', reject);
(document.getElementsByTagName('head')[0] || document.body || document.documentElement).appendChild(script)
});
}
function isNeedCartCount( data ) {
var isNeed = false;
data.forEach((naviItem) => {
var dragdrop = naviItem["data"]["dragdrop"];
dragdrop.forEach((item) => {
//console.log( item["badgeiscart"] );
if( naviman.isHadValue( item["badgeiscart"] ))
if( item["badgeiscart"] == 1 )
isNeed = true;
})
});
return isNeed;
}
jsonp(api_url).then(function(data){
//console.log(data);
naviman.init();
if( isNeedCartCount(data) ) {
naviman.asyncGetCart().then( function(result) {
console.log("Cart count: " + result.item_count );
window.addEventListener('SCE:mutate', (event) => {
naviman.updateCartCount();
});
naviman.setCartCount( result.item_count );
naviman.drawBottomNav(data, naviman_domain, shop, embed_id);
naviman.generateActiveItems();
});
}else {
console.log("No need cart count");
naviman.drawBottomNav(data, naviman_domain, shop, embed_id);
naviman.generateActiveItems();
}
});
};
naviman_runApp();