(function($){
"use strict";
$.maxmegamenu=function(menu, options){
var plugin=this;
var $menu=$(menu);
var $wrap=$(menu).parent();
var $toggle_bar=$menu.siblings(".mega-menu-toggle");
var html_body_class_timeout;
var defaults={
event: $menu.attr("data-event"),
effect: $menu.attr("data-effect"),
effect_speed: parseInt($menu.attr("data-effect-speed")),
effect_mobile: $menu.attr("data-effect-mobile"),
effect_speed_mobile: parseInt($menu.attr("data-effect-speed-mobile")),
panel_width: $menu.attr("data-panel-width"),
panel_inner_width: $menu.attr("data-panel-inner-width"),
mobile_force_width: $menu.attr("data-mobile-force-width"),
mobile_overlay: $menu.attr("data-mobile-overlay"),
mobile_state: $menu.attr("data-mobile-state"),
mobile_direction: $menu.attr("data-mobile-direction"),
second_click: $menu.attr("data-second-click"),
vertical_behaviour: $menu.attr("data-vertical-behaviour"),
document_click: $menu.attr("data-document-click"),
breakpoint: $menu.attr("data-breakpoint"),
unbind_events: $menu.attr("data-unbind"),
hover_intent_timeout: $menu.attr("data-hover-intent-timeout"),
hover_intent_interval: $menu.attr("data-hover-intent-interval")
};
plugin.settings={};
var items_with_submenus=$("li.mega-menu-megamenu.mega-menu-item-has-children," +
"li.mega-menu-flyout.mega-menu-item-has-children," +
"li.mega-menu-tabbed > ul.mega-sub-menu > li.mega-menu-item-has-children," +
"li.mega-menu-flyout li.mega-menu-item-has-children", $menu);
var collapse_children_parents=$("li.mega-menu-megamenu li.mega-menu-item-has-children.mega-collapse-children > a.mega-menu-link", $menu);
plugin.addAnimatingClass=function(element){
if(plugin.settings.effect==="disabled"){
return;
}
$(".mega-animating").removeClass("mega-animating");
var timeout=plugin.settings.effect_speed + parseInt(plugin.settings.hover_intent_timeout, 10);
element.addClass("mega-animating");
setTimeout(function(){
element.removeClass("mega-animating");
}, timeout);
};
plugin.hideAllPanels=function(){
$(".mega-toggle-on > a.mega-menu-link", $menu).each(function(){
plugin.hidePanel($(this), false);
});
};
plugin.expandMobileSubMenus=function(){
if(plugin.settings.mobile_direction!=='vertical'){
return;
}
$(".mega-menu-item-has-children.mega-expand-on-mobile > a.mega-menu-link", $menu).each(function(){
plugin.showPanel($(this), true);
});
if(plugin.settings.mobile_state=='expand_all'){
$(".mega-menu-item-has-children:not(.mega-toggle-on) > a.mega-menu-link", $menu).each(function(){
plugin.showPanel($(this), true);
});
}
if(plugin.settings.mobile_state=='expand_active'){
const activeItemSelectors=[
"li.mega-current-menu-ancestor.mega-menu-item-has-children > a.mega-menu-link",
"li.mega-current-menu-item.mega-menu-item-has-children > a.mega-menu-link",
"li.mega-current-menu-parent.mega-menu-item-has-children > a.mega-menu-link",
"li.mega-current_page_ancestor.mega-menu-item-has-children > a.mega-menu-link",
"li.mega-current_page_item.mega-menu-item-has-children > a.mega-menu-link"
];
$menu.find(activeItemSelectors.join(', ')).each(function(){
plugin.showPanel($(this), true);
});
}}
plugin.hideSiblingPanels=function(anchor, immediate){
anchor.parent().parent().find(".mega-toggle-on").children("a.mega-menu-link").each(function(){
plugin.hidePanel($(this), immediate);
});
};
plugin.isDesktopView=function(){
var width=Math.max(document.documentElement.clientWidth||0, window.innerWidth||0);
return width > plugin.settings.breakpoint;
};
plugin.isMobileView=function(){
return !plugin.isDesktopView();
};
plugin.showPanel=function(anchor, immediate){
if($.isNumeric(anchor)){
anchor=$("li.mega-menu-item-" + anchor, $menu).find("a.mega-menu-link").first();
}else if(anchor.is("li.mega-menu-item")){
anchor=anchor.find("a.mega-menu-link").first();
}
anchor.parent().triggerHandler("before_open_panel");
anchor.parent().find("[aria-expanded]").first().attr("aria-expanded", "true");
$(".mega-animating").removeClass("mega-animating");
if(plugin.isMobileView()&&anchor.parent().hasClass("mega-hide-sub-menu-on-mobile")){
return;
}
if(plugin.isDesktopView()&&($menu.hasClass("mega-menu-horizontal")||$menu.hasClass("mega-menu-vertical"))&&!anchor.parent().hasClass("mega-collapse-children")){
plugin.hideSiblingPanels(anchor, true);
}
if((plugin.isMobileView()&&$wrap.hasClass("mega-keyboard-navigation"))||plugin.settings.vertical_behaviour==="accordion"){
plugin.hideSiblingPanels(anchor, false);
}
plugin.calculateDynamicSubmenuWidths(anchor);
if(plugin.shouldUseSlideAnimation(anchor, immediate)){
var speed=plugin.isMobileView() ? plugin.settings.effect_speed_mobile:plugin.settings.effect_speed;
anchor.siblings(".mega-sub-menu").css("display", "none").animate({"height":"show", "paddingTop":"show", "paddingBottom":"show", "minHeight":"show"}, speed, function(){
$(this).css("display", "");
});
}
anchor.parent().addClass("mega-toggle-on").triggerHandler("open_panel");
};
plugin.shouldUseSlideAnimation=function(anchor, immediate){
if(immediate==true){
return false;
}
if(anchor.parent().hasClass("mega-collapse-children")){
return true;
}
if(plugin.isDesktopView()&&plugin.settings.effect==="slide"){
return true;
}
if(plugin.isMobileView()){
if(plugin.settings.effect_mobile==="slide"){
return true;
}
if(plugin.isMobileOffCanvas()){
return plugin.settings.mobile_direction!=="horizontal";
}}
return false;
};
plugin.hidePanel=function(anchor, immediate){
if($.isNumeric(anchor)){
anchor=$("li.mega-menu-item-" + anchor, $menu).find("a.mega-menu-link").first();
}else if(anchor.is("li.mega-menu-item")){
anchor=anchor.find("a.mega-menu-link").first();
}
anchor.parent().triggerHandler("before_close_panel");
anchor.parent().find("[aria-expanded]").first().attr("aria-expanded", "false");
if(plugin.shouldUseSlideAnimation(anchor)){
var speed=plugin.isMobileView() ? plugin.settings.effect_speed_mobile:plugin.settings.effect_speed;
anchor.siblings(".mega-sub-menu").animate({"height":"hide", "paddingTop":"hide", "paddingBottom":"hide", "minHeight":"hide"}, speed, function(){
anchor.siblings(".mega-sub-menu").css("display", "");
anchor.parent().removeClass("mega-toggle-on").triggerHandler("close_panel");
});
return;
}
if(immediate){
anchor.siblings(".mega-sub-menu").css("display", "none").delay(plugin.settings.effect_speed).queue(function(){
$(this).css("display", "").dequeue();
});
}
anchor.siblings(".mega-sub-menu").find(".widget_media_video video").each(function(){
this.player.pause();
});
anchor.parent().removeClass("mega-toggle-on").triggerHandler("close_panel");
plugin.addAnimatingClass(anchor.parent());
};
plugin.calculateDynamicSubmenuWidths=function(anchor){
if(anchor.parent().hasClass("mega-menu-megamenu")&&anchor.parent().parent().hasClass("max-mega-menu")&&plugin.settings.panel_width){
if(plugin.isDesktopView()){
var submenu_offset=$menu.offset();
var target_offset=$(plugin.settings.panel_width).offset();
if(plugin.settings.panel_width=='100vw'){
target_offset=$('body').offset();
anchor.siblings(".mega-sub-menu").css({
left: (target_offset.left - submenu_offset.left) + "px"
});
}else if($(plugin.settings.panel_width).length > 0){
anchor.siblings(".mega-sub-menu").css({
width: $(plugin.settings.panel_width).outerWidth(),
left: (target_offset.left - submenu_offset.left) + "px"
});
}}else{
anchor.siblings(".mega-sub-menu").css({
width: "",
left: ""
});
}}
if(anchor.parent().hasClass("mega-menu-megamenu")&&anchor.parent().parent().hasClass("max-mega-menu")&&plugin.settings.panel_inner_width&&$(plugin.settings.panel_inner_width).length > 0){
var target_width=0;
if($(plugin.settings.panel_inner_width).length){
target_width=parseInt($(plugin.settings.panel_inner_width).width(), 10);
}else{
target_width=parseInt(plugin.settings.panel_inner_width, 10);
}
anchor.siblings(".mega-sub-menu").css({
"paddingLeft": "",
"paddingRight": ""
});
var submenu_width=parseInt(anchor.siblings(".mega-sub-menu").innerWidth(), 10);
if(plugin.isDesktopView()&&target_width > 0&&target_width < submenu_width){
anchor.siblings(".mega-sub-menu").css({
"paddingLeft": (submenu_width - target_width) / 2 + "px",
"paddingRight": (submenu_width - target_width) / 2 + "px"
});
}}
};
plugin.bindClickEvents=function(){
if($wrap.data('has-click-events')===true){
return;
}
$wrap.data('has-click-events', true);
var dragging=false;
$(document).on({
"touchmove": function(e){ dragging=true; },
"touchstart": function(e){ dragging=false; }});
$(document).on("click touchend", function(e){
if(!dragging&&plugin.settings.document_click==="collapse"&&! $(e.target).closest(".mega-menu-wrap").length){
plugin.hideAllPanels();
plugin.hideMobileMenu();
}
dragging=false;
});
var clickable_parents=$("> a.mega-menu-link", items_with_submenus).add(collapse_children_parents);
clickable_parents.on("touchend.megamenu", function(e){
if(plugin.settings.event==="hover_intent"){
plugin.unbindHoverIntentEvents();
}
if(plugin.settings.event==="hover"){
plugin.unbindHoverEvents();
}});
clickable_parents.on("click.megamenu", function(e){
if($(e.target).hasClass('mega-indicator')){
return;
}
if(plugin.isDesktopView()&&$(this).parent().hasClass("mega-toggle-on")&&$(this).closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed")){
if(plugin.settings.second_click==="go"){
return;
}else{
e.preventDefault();
return;
}}
if(dragging){
return;
}
if(plugin.isMobileView()&&$(this).parent().hasClass("mega-hide-sub-menu-on-mobile")){
return;
}
if((plugin.settings.second_click==="go"||$(this).parent().hasClass("mega-click-click-go"))&&$(this).attr("href")!==undefined){
if(!$(this).parent().hasClass("mega-toggle-on")){
e.preventDefault();
plugin.showPanel($(this));
}}else{
e.preventDefault();
if($(this).parent().hasClass("mega-toggle-on")){
plugin.hidePanel($(this), false);
}else{
plugin.showPanel($(this));
}}
});
if(plugin.settings.second_click==="disabled"){
clickable_parents.off("click.megamenu");
}
$(".mega-close-after-click:not(.mega-menu-item-has-children) > a.mega-menu-link", $menu).on("click", function(){
plugin.hideAllPanels();
plugin.hideMobileMenu();
});
$("button.mega-close", $wrap).on("click", function(e){
plugin.hideMobileMenu();
});
};
plugin.bindHoverEvents=function(){
items_with_submenus.on({
"mouseenter.megamenu":function(){
plugin.unbindClickEvents();
if(! $(this).hasClass("mega-toggle-on")){
plugin.showPanel($(this).children("a.mega-menu-link"));
}},
"mouseleave.megamenu":function(){
if($(this).hasClass("mega-toggle-on")&&! $(this).hasClass("mega-disable-collapse")&&! $(this).parent().parent().hasClass("mega-menu-tabbed")){
plugin.hidePanel($(this).children("a.mega-menu-link"), false);
}}
});
};
plugin.bindHoverIntentEvents=function(){
items_with_submenus.hoverIntent({
over: function (){
plugin.unbindClickEvents();
if(! $(this).hasClass("mega-toggle-on")){
plugin.showPanel($(this).children("a.mega-menu-link"));
}},
out: function (){
if($(this).hasClass("mega-toggle-on")&&! $(this).hasClass("mega-disable-collapse")&&! $(this).parent().parent().hasClass("mega-menu-tabbed")){
plugin.hidePanel($(this).children("a.mega-menu-link"), false);
}},
timeout: plugin.settings.hover_intent_timeout,
interval: plugin.settings.hover_intent_interval
});
};
plugin.isMobileOffCanvas=function(){
return plugin.settings.effect_mobile==='slide_left'||plugin.settings.effect_mobile==='slide_right';
}
plugin.bindKeyboardEvents=function(){
const tab_key=9;
const escape_key=27;
const enter_key=13;
const left_arrow_key=37;
const up_arrow_key=38;
const right_arrow_key=39;
const down_arrow_key=40;
const space_key=32;
const $firstFocusable=$menu.find("a.mega-menu-link").first();
const $lastFocusable=$wrap.find("button.mega-close").first();
var isMobileOffCanvasHorizontal=function(){
return plugin.isMobileOffCanvas()&&plugin.settings.mobile_direction==='horizontal';
}
var shouldTrapFocusInCurrentSubMenu=function(){
return isMobileOffCanvasHorizontal()&&(keyCode===up_arrow_key||keyCode===down_arrow_key||keyCode===tab_key);
}
$lastFocusable.on('keydown.megamenu', function(e){
var keyCode=e.keyCode||e.which;
if(plugin.isMobileView()&&plugin.isMobileOffCanvas()&&keyCode===tab_key&&! e.shiftKey){
e.preventDefault();
$firstFocusable.trigger('focus');
}});
$firstFocusable.on('keydown.megamenu', function(e){
var keyCode=e.keyCode||e.which;
if(plugin.isMobileView()&&plugin.isMobileOffCanvas()&&keyCode===tab_key&&e.shiftKey){
e.preventDefault();
$lastFocusable.trigger('focus');
}});
$wrap.on("keyup.megamenu", ".max-mega-menu, .mega-menu-toggle", function(e){
var keyCode=e.keyCode||e.which;
var active_link=$(e.target);
if(keyCode===tab_key){
$wrap.addClass("mega-keyboard-navigation");
plugin.bindClickEvents();
if(plugin.isDesktopView()&&keyCode===tab_key&&active_link.is(".mega-menu-link")&&active_link.parent().parent().hasClass('max-mega-menu')){
plugin.hideAllPanels();
}}
});
$wrap.on("keydown.megamenu", "a.mega-menu-link, .mega-indicator, .mega-menu-toggle-block, .mega-menu-toggle-animated-block button, button.mega-close", function(e){
if(! $wrap.hasClass("mega-keyboard-navigation")){
return;
}
var keyCode=e.keyCode||e.which;
var active_link=$(e.target);
if(keyCode===space_key&&active_link.is(".mega-menu-link")){
e.preventDefault();
if(active_link.parent().is(items_with_submenus)){
if(active_link.parent().hasClass("mega-toggle-on")&&! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed")){
plugin.hidePanel(active_link);
}else{
plugin.showPanel(active_link);
}}
}
if(keyCode===space_key&&active_link.is("mega-indicator")){
e.preventDefault();
if(active_link.parent().parent().hasClass("mega-toggle-on")&&! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed")){
plugin.hidePanel(active_link.parent());
}else{
plugin.showPanel(active_link.parent());
}}
if(keyCode===escape_key){
var submenu_open=$(".mega-toggle-on", $menu).length!==0;
if(submenu_open){
var focused_menu_item=$menu.find(":focus");
if(focused_menu_item.closest('.mega-menu-flyout.mega-toggle-on').length!==0){
var nearest_parent_of_focused_item_li=focused_menu_item.closest('.mega-toggle-on');
var nearest_parent_of_focused_item_a=$("> a.mega-menu-link", nearest_parent_of_focused_item_li);
plugin.hidePanel(nearest_parent_of_focused_item_a);
nearest_parent_of_focused_item_a.trigger('focus');
}
if(focused_menu_item.closest('.mega-menu-megamenu.mega-toggle-on').length!==0){
var nearest_parent_of_focused_item_li=focused_menu_item.closest('.mega-menu-megamenu.mega-toggle-on');
var nearest_parent_of_focused_item_a=$("> a.mega-menu-link", nearest_parent_of_focused_item_li);
plugin.hidePanel(nearest_parent_of_focused_item_a);
nearest_parent_of_focused_item_a.trigger('focus');
}}
if(plugin.isMobileView()&&! submenu_open){
plugin.hideMobileMenu();
}}
if(keyCode===space_key||keyCode===enter_key){
if(active_link.is(".mega-menu-toggle-block button, .mega-menu-toggle-animated-block button")){
e.preventDefault();
if($toggle_bar.hasClass("mega-menu-open")){
plugin.hideMobileMenu();
}else{
plugin.showMobileMenu();
html_body_class_timeout=setTimeout(function(){
$menu.find("a.mega-menu-link").first().trigger('focus');
}, plugin.settings.effect_speed_mobile);
}}
}
if(keyCode===enter_key){
if(active_link.is(".mega-indicator")){
if(active_link.closest("li.mega-menu-item").hasClass("mega-toggle-on")&&! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed")){
plugin.hidePanel(active_link.parent());
}else{
plugin.showPanel(active_link.parent());
}
return;
}
if(active_link.parent().is(items_with_submenus)){
if(plugin.isMobileView()&&active_link.parent().is(".mega-hide-sub-menu-on-mobile")){
return;
}
if(active_link.is("[href]")===false){
if(active_link.parent().hasClass("mega-toggle-on")&&! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed")){
plugin.hidePanel(active_link);
}else{
plugin.showPanel(active_link);
}
return;
}
if(active_link.parent().hasClass("mega-toggle-on")&&! active_link.closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed")){
return;
}else{
e.preventDefault();
plugin.showPanel(active_link);
}}
}
if(shouldTrapFocusInCurrentSubMenu()){
var focused_item=$(":focus", $menu);
if(focused_item.length===0){
e.preventDefault();
$("> li.mega-menu-item:visible", $menu).find("> a.mega-menu-link, .mega-search span[role=button]").first().trigger('focus');
return;
}
var next_item_to_focus=focused_item.parent().nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
if(next_item_to_focus.length===0&&focused_item.closest(".mega-menu-megamenu").length!==0){
var all_li_parents=focused_item.parentsUntil(".mega-menu-megamenu");
if(focused_item.is(all_li_parents.find("a.mega-menu-link").last())){
next_item_to_focus=all_li_parents.find(".mega-back-button:visible > a.mega-menu-link").first();
}}
if(next_item_to_focus.length===0){
next_item_to_focus=focused_item.parent().prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
}
if(next_item_to_focus.length!==0){
e.preventDefault();
next_item_to_focus.trigger('focus');
}}
var shouldGoToNextTopLevelItem=function(){
return(( keyCode===right_arrow_key&&plugin.isDesktopView())||(keyCode===down_arrow_key&&plugin.isMobileView()) )&&$menu.hasClass("mega-menu-horizontal");
}
var shouldGoToPreviousTopLevelItem=function(){
return(( keyCode===left_arrow_key&&plugin.isDesktopView())||(keyCode===up_arrow_key&&plugin.isMobileView()) )&&$menu.hasClass("mega-menu-horizontal");
}
if(shouldGoToNextTopLevelItem()){
e.preventDefault();
var next_top_level_item=$("> .mega-toggle-on", $menu).nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
if(next_top_level_item.length===0){
next_top_level_item=$(":focus", $menu).parent().nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
}
if(next_top_level_item.length===0){
next_top_level_item=$(":focus", $menu).parent().parent().parent().nextAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").first();
}
plugin.hideAllPanels();
next_top_level_item.trigger('focus');
}
if(shouldGoToPreviousTopLevelItem()){
e.preventDefault();
var prev_top_level_item=$("> .mega-toggle-on", $menu).prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").last();
if(prev_top_level_item.length===0){
prev_top_level_item=$(":focus", $menu).parent().prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").last();
}
if(prev_top_level_item.length===0){
prev_top_level_item=$(":focus", $menu).parent().parent().parent().prevAll("li.mega-menu-item:visible").find("> a.mega-menu-link, .mega-search span[role=button]").last();
}
plugin.hideAllPanels();
prev_top_level_item.trigger('focus');
}});
$wrap.on("focusout.megamenu", function(e){
if($wrap.hasClass("mega-keyboard-navigation")){
setTimeout(function(){
var menu_has_focus=$wrap.find(":focus").length > 0;
if(! menu_has_focus){
$wrap.removeClass("mega-keyboard-navigation");
plugin.hideAllPanels();
plugin.hideMobileMenu();
}}, 10);
}});
};
plugin.unbindAllEvents=function(){
$("ul.mega-sub-menu, li.mega-menu-item, li.mega-menu-row, li.mega-menu-column, a.mega-menu-link, .mega-indicator", $menu).off().unbind();
};
plugin.unbindClickEvents=function(){
if($wrap.hasClass('mega-keyboard-navigation')){
return;
}
$("> a.mega-menu-link", items_with_submenus).not(collapse_children_parents).off("click.megamenu touchend.megamenu");
$wrap.data('has-click-events', false);
};
plugin.unbindHoverEvents=function(){
items_with_submenus.off("mouseenter.megamenu mouseleave.megamenu");
};
plugin.unbindHoverIntentEvents=function(){
items_with_submenus.off("mouseenter mouseleave").removeProp("hoverIntent_t").removeProp("hoverIntent_s");
};
plugin.unbindKeyboardEvents=function(){
$wrap.off("keyup.megamenu keydown.megamenu focusout.megamenu");
};
plugin.unbindMegaMenuEvents=function(){
if(plugin.settings.event==="hover_intent"){
plugin.unbindHoverIntentEvents();
}
if(plugin.settings.event==="hover"){
plugin.unbindHoverEvents();
}
plugin.unbindClickEvents();
plugin.unbindKeyboardEvents();
};
plugin.bindMegaMenuEvents=function(){
plugin.unbindMegaMenuEvents();
if(plugin.isDesktopView()&&plugin.settings.event==="hover_intent"){
plugin.bindHoverIntentEvents();
}
if(plugin.isDesktopView()&&plugin.settings.event==="hover"){
plugin.bindHoverEvents();
}
plugin.bindClickEvents();
plugin.bindKeyboardEvents();
};
plugin.checkWidth=function(){
if(plugin.isMobileView()&&$menu.data("view")==="desktop"){
plugin.switchToMobile();
}
if(plugin.isDesktopView()&&$menu.data("view")==="mobile"){
plugin.switchToDesktop();
}
plugin.calculateDynamicSubmenuWidths($("> li.mega-menu-megamenu > a.mega-menu-link", $menu));
};
plugin.reverseRightAlignedItems=function(){
if(! $("body").hasClass("rtl")&&$menu.hasClass("mega-menu-horizontal")&&$menu.css("display")!=='flex'){
$menu.append($menu.children("li.mega-item-align-right").get().reverse());
}};
plugin.addClearClassesToMobileItems=function(){
$(".mega-menu-row", $menu).each(function(){
$("> .mega-sub-menu > .mega-menu-column:not(.mega-hide-on-mobile)", $(this)).filter(":even").addClass("mega-menu-clear");
});
};
plugin.initDesktop=function(){
$menu.data("view", "desktop");
plugin.bindMegaMenuEvents();
plugin.initIndicators();
};
plugin.initMobile=function(){
plugin.switchToMobile();
};
plugin.switchToDesktop=function(){
$menu.data("view", "desktop");
plugin.bindMegaMenuEvents();
plugin.reverseRightAlignedItems();
plugin.hideAllPanels();
plugin.hideMobileMenu(true);
$menu.removeAttr('role');
$menu.removeAttr('aria-modal');
$menu.removeAttr('aria-hidden');
};
plugin.switchToMobile=function(){
$menu.data("view", "mobile");
if(plugin.isMobileOffCanvas()&&$toggle_bar.is(":visible")){
$menu.attr('role', 'dialog');
$menu.attr('aria-modal', 'true');
$menu.attr('aria-hidden', 'true');
}
plugin.bindMegaMenuEvents();
plugin.initIndicators();
plugin.reverseRightAlignedItems();
plugin.addClearClassesToMobileItems();
plugin.hideAllPanels();
plugin.expandMobileSubMenus();
};
plugin.initToggleBar=function(){
$toggle_bar.on("click", function(e){
if($(e.target).is(".mega-menu-toggle, .mega-menu-toggle-custom-block *, .mega-menu-toggle-block, .mega-menu-toggle-animated-block, .mega-menu-toggle-animated-block *, .mega-toggle-blocks-left, .mega-toggle-blocks-center, .mega-toggle-blocks-right, .mega-toggle-label, .mega-toggle-label span")){
e.preventDefault();
if($(this).hasClass("mega-menu-open")){
plugin.hideMobileMenu();
}else{
plugin.showMobileMenu();
}}
});
};
plugin.initIndicators=function(){
$menu.off('click.megamenu', '.mega-indicator');
$menu.on('click.megamenu', '.mega-indicator', function(e){
e.preventDefault();
e.stopPropagation();
if($(this).closest(".mega-menu-item").hasClass("mega-toggle-on")){
if(! $(this).closest("ul.mega-sub-menu").parent().hasClass("mega-menu-tabbed")||plugin.isMobileView()){
plugin.hidePanel($(this).parent(), false);
}}else{
plugin.showPanel($(this).parent(), false);
}});
};
plugin.hideMobileMenu=function(force){
force=force||false;
if(! $toggle_bar.is(":visible")&&! force){
return;
}
$menu.attr("aria-hidden", "true");
html_body_class_timeout=setTimeout(function(){
$("body").removeClass($menu.attr("id") + "-mobile-open");
$("html").removeClass($menu.attr("id") + "-off-canvas-open");
}, plugin.settings.effect_speed_mobile);
if($wrap.hasClass("mega-keyboard-navigation")){
$(".mega-menu-toggle-block button, button.mega-toggle-animated", $toggle_bar).first().trigger('focus');
}
$(".mega-toggle-label, .mega-toggle-animated", $toggle_bar).attr("aria-expanded", "false");
if(plugin.settings.effect_mobile==="slide"&&! force){
$menu.animate({"height":"hide"}, plugin.settings.effect_speed_mobile, function(){
$menu.css({
width: "",
left: "",
display: ""
});
$toggle_bar.removeClass("mega-menu-open");
});
}else{
$menu.css({
width: "",
left: "",
display: ""
});
$toggle_bar.removeClass("mega-menu-open");
}
$menu.triggerHandler("mmm:hideMobileMenu");
};
plugin.showMobileMenu=function(){
if(! $toggle_bar.is(":visible")){
return;
}
clearTimeout(html_body_class_timeout);
$("body").addClass($menu.attr("id") + "-mobile-open");
plugin.expandMobileSubMenus();
if(plugin.isMobileOffCanvas()){
$("html").addClass($menu.attr("id") + "-off-canvas-open");
}
if(plugin.settings.effect_mobile==="slide"){
$menu.animate({"height":"show"}, plugin.settings.effect_speed_mobile, function(){
$(this).css("display", "");
});
}
$(".mega-toggle-label, .mega-toggle-animated", $toggle_bar).attr("aria-expanded", "true");
$toggle_bar.addClass("mega-menu-open");
plugin.toggleBarForceWidth();
$menu.attr("aria-hidden", "false");
$menu.triggerHandler("mmm:showMobileMenu");
};
plugin.toggleBarForceWidth=function(){
if($(plugin.settings.mobile_force_width).length&&(plugin.settings.effect_mobile==="slide"||plugin.settings.effect_mobile==="disabled") ){
var submenu_offset=$toggle_bar.offset();
var target_offset=$(plugin.settings.mobile_force_width).offset();
$menu.css({
width: $(plugin.settings.mobile_force_width).outerWidth(),
left: (target_offset.left - submenu_offset.left) + "px"
});
}};
plugin.doConsoleChecks=function(){
if(plugin.settings.mobile_force_width!="false"&&! $(plugin.settings.mobile_force_width).length&&(plugin.settings.effect_mobile==="slide"||plugin.settings.effect_mobile==="disabled") ){
console.warn('Max Mega Menu #' + $wrap.attr('id') + ': Mobile Force Width element (' + plugin.settings.mobile_force_width + ') not found');
}
const cssWidthRegex=/^((\d+(\.\d+)?(px|%|em|rem|vw|vh|ch|ex|cm|mm|in|pt|pc))|auto)$/i;
if(plugin.settings.panel_width!==undefined&&! cssWidthRegex.test(plugin.settings.panel_width)&&! $(plugin.settings.panel_width).length){
console.warn('Max Mega Menu #' + $wrap.attr('id') + ': Panel Width (Outer) element (' + plugin.settings.panel_width + ') not found');
}
if(plugin.settings.panel_inner_width!==undefined&&! cssWidthRegex.test(plugin.settings.panel_inner_width)&&! $(plugin.settings.panel_inner_width).length){
console.warn('Max Mega Menu #' + $wrap.attr('id') + ': Panel Width (Inner) element (' + plugin.settings.panel_inner_width + ') not found');
}}
plugin.init=function(){
$menu.triggerHandler("before_mega_menu_init");
plugin.settings=$.extend({}, defaults, options);
if(window.console){
plugin.doConsoleChecks();
}
$menu.removeClass("mega-no-js");
plugin.initToggleBar();
if(plugin.settings.unbind_events==="true"){
plugin.unbindAllEvents();
}
$(window).on("load", function(){
plugin.calculateDynamicSubmenuWidths($("> li.mega-menu-megamenu > a.mega-menu-link", $menu));
});
if(plugin.isDesktopView()){
plugin.initDesktop();
}else{
plugin.initMobile();
}
$(window).on("resize", function(){
plugin.checkWidth();
});
$menu.triggerHandler("after_mega_menu_init");
};
plugin.init();
};
$.fn.maxmegamenu=function(options){
return this.each(function(){
if(undefined===$(this).data("maxmegamenu")){
var plugin=new $.maxmegamenu(this, options);
$(this).data("maxmegamenu", plugin);
}});
};
$(function(){
$(".max-mega-menu").maxmegamenu();
});
}(jQuery));
(function($){
"use strict";
$(function(){
$('body').on('edd_cart_item_added', function(event, data){
$('.mega-menu-edd-cart-total').html(data.total);
$('.mega-menu-edd-cart-count').html(data.cart_quantity);
});
});
$(".max-mega-menu").on("after_mega_menu_init", function(){
$('li.mega-menu-megamenu').on('open_panel', function(){
var placeholder=$(this).closest(".mega-menu-megamenu").find(".widget_maxmegamenu_image_swap img.mega-placeholder");
var default_src=placeholder.attr('data-default-src');
var default_alt=placeholder.attr('data-default-alt');
placeholder.attr('src', default_src);
placeholder.attr('alt', default_alt);
$('.mega-sub-menu [data-image-swap-url]', $(this)).not(['data-preloaded']).each(function(){
$('<img/>')[0].src=$(this).attr('data-image-swap-url');
$(this).attr('data-preloaded', 'true');
});
});
if(! $.isFunction($.fn.hoverIntent)){
return;
}
$('.mega-sub-menu [data-image-swap-url]').hoverIntent({
over: function (){
var placeholder=$(this).closest(".mega-menu-megamenu").find(".widget_maxmegamenu_image_swap img.mega-placeholder");
var new_src=$(this).attr('data-image-swap-url');
var new_alt=$(this).is("[data-image-swap-alt]") ? $(this).attr('data-image-swap-alt'):"";
placeholder.attr('src', new_src);
placeholder.attr('alt', new_alt);
},
out: function(){}});
});
})(jQuery);
(function($){
"use strict";
$.maxmegamenu_searchbox=function(form, options){
var plugin=this;
var form=$(form);
var $menu=form.parents('.max-mega-menu');
var $wrap=$menu.parent();
var breakpoint=$menu.attr('data-breakpoint');
var input=$('input[type=text]', form);
var icon=$('.search-icon', form);
plugin.isDesktopView=function(){
return Math.max(window.outerWidth, $(window).width()) >=breakpoint;
};
plugin.monitorView=function(){
if(typeof $menu.data("view")==='undefined'){
if(plugin.isDesktopView()){
$menu.data("view", "desktop");
}else{
$menu.data("view", "mobile");
}}
plugin.checkWidth();
$(window).resize(function(){
plugin.checkWidth();
});
};
plugin.checkWidth=function(){
var expanding_search=$("li.mega-menu-item .mega-search.expand-to-left input[type=text], li.mega-menu-item .mega-search.expand-to-right input[type=text]", $menu);
if($menu.data("view")==="mobile"){
var placeholder=expanding_search.attr('data-placeholder');
expanding_search.attr('placeholder', placeholder);
}
if($menu.data("view")==="desktop"){
expanding_search.attr('placeholder', '');
}};
plugin.close_search=function(moveFocus=true){
$menu.triggerHandler("mmm:closeSearch");
input.val("");
input.attr('placeholder', '');
input.attr('tabindex', '-1');
form.removeClass('mega-search-open');
form.addClass('mega-search-closed');
icon.attr('aria-expanded', 'false');
if(moveFocus){
icon.trigger("focus");
}}
plugin.open_search=function(){
$menu.triggerHandler("mmm:openSearch");
input.attr('placeholder', input.attr('data-placeholder'));
input.attr('tabindex', '0');
form.removeClass('mega-search-closed');
form.addClass('mega-search-open');
icon.attr('aria-expanded', 'true');
input.trigger("focus");
}
plugin.detect_background_click=function(){
var dragging=false;
$(document).on({
"touchmove": function(e){ dragging=true; },
"touchstart": function(e){ dragging=false; }});
$(document).on("click touchend", function(e){
if(form.parent().hasClass('mega-static')){
return;
}
if(! dragging&&! $(e.target).closest(".max-mega-menu li").length&&! $(e.target).closest(".mega-menu-toggle").length){
plugin.close_search(false);
}
dragging=false;
});
}
plugin.init_replacements_search=function(){
if($menu.data("view")==="mobile"){
input.attr('tabindex', '0');
$(".search-icon", $menu).on('click', function(e){
$(this).parents(".mega-search").submit();
});
}
if($menu.data("view")==="desktop"){
input.on('blur', function(e){
if($menu.parent().hasClass("mega-keyboard-navigation")&&input.val()==''&&! form.parent().hasClass('mega-static')&&form.hasClass('mega-search-open')){
plugin.close_search();
}});
icon.on('keypress click', function(e){
var enter_key=13;
var space_key=32;
if(e.which===enter_key||e.which===space_key||e.type==='click'){
e.preventDefault();
if(form.parent().hasClass('mega-static')){
form.submit();
return;
}
if(input.val()!=''){
form.submit();
return;
}
if(form.hasClass('mega-search-open')){
plugin.close_search();
return;
}
if(form.hasClass('mega-search-closed')){
plugin.open_search();
return;
}}
});
$menu.on('keydown', function(e){
var escape_key=27;
if(e.which===escape_key){
if(! form.parent().hasClass('mega-static')&&form.hasClass('mega-search-open')){
plugin.close_search();
return;
}}
});
}};
plugin.monitorView();
plugin.init_replacements_search();
plugin.detect_background_click();
};
$.fn.maxmegamenu_searchbox=function(options){
return this.each(function(){
if(undefined===$(this).data('maxmegamenu_searchbox')){
var plugin=new $.maxmegamenu_searchbox(this, options);
$(this).data('maxmegamenu_searchbox', plugin);
}});
};
$(".max-mega-menu").on("after_mega_menu_init", function(){
$(".mega-search", this).maxmegamenu_searchbox();
});
})(jQuery);
(function($){
"use strict";
$.maxmegamenu_toggle_searchbox=function(form, options){
var plugin=this;
var form=$(form);
var $wrap=form.parents('.mega-menu-wrap');
var input=$("input[type=text]", form);
var icon=$(".search-icon", form);
plugin.open_search=function(){
input.attr('placeholder', input.attr('data-placeholder'));
form.removeClass('mega-search-closed');
form.addClass('mega-search-open');
}
plugin.close_search=function(){
input.attr('placeholder', '');
form.removeClass('mega-search-open');
form.addClass('mega-search-closed');
}
plugin.init_toggle_search=function(){
input.val("");
input.on('focus', function(e){
if(! form.parent().hasClass('mega-static')&&form.hasClass('mega-search-closed')&&$wrap.hasClass('mega-keyboard-navigation')){
plugin.open_search();
}});
input.on('blur', function(e){
if(! form.parent().hasClass('mega-static')&&form.hasClass('mega-search-open')&&$wrap.hasClass('mega-keyboard-navigation')){
plugin.close_search();
}});
icon.on('click', function(e){
if(form.hasClass('static')){
form.submit();
}else if(form.hasClass('mega-search-closed')){
input.focus();
plugin.open_search();
}else if(input.val()==''){
plugin.close_search();
}else{
form.submit();
}});
};
plugin.init_toggle_search();
};
$.fn.maxmegamenu_toggle_searchbox=function(options){
return this.each(function(){
if(undefined===$(this).data('maxmegamenu_toggle_searchbox')){
var plugin=new $.maxmegamenu_toggle_searchbox(this, options);
$(this).data('maxmegamenu_toggle_searchbox', plugin);
}});
};
$(function(){
$(".mega-menu-toggle .mega-search").maxmegamenu_toggle_searchbox();
});
})(jQuery);
(function($){
"use strict";
$.maxmegamenu_sticky=function(menu, options){
var plugin=this;
var $menu=$(menu);
var $wrap=$menu.parent();
var breakpoint=$menu.attr('data-breakpoint');
var sticky_on_mobile=$menu.attr('data-sticky-mobile');
var sticky_on_desktop=$menu.attr('data-sticky-desktop');
var sticky_expand=$menu.attr('data-sticky-expand');
var sticky_expand_mobile=$menu.attr('data-sticky-expand-mobile');
var sticky_offset=isNaN(parseInt($menu.attr('data-sticky-offset'))) ? 0:parseInt($menu.attr('data-sticky-offset'));
var sticky_hide_until_scroll_up=$menu.attr('data-sticky-hide');
var sticky_hide_until_scroll_up_tolerance=isNaN(parseInt($menu.attr('data-sticky-hide-tolerance'))) ? 0:parseInt($menu.attr('data-sticky-hide-tolerance'));
var sticky_hide_until_scroll_up_offset=isNaN(parseInt($menu.attr('data-sticky-hide-offset'))) ? 0:parseInt($menu.attr('data-sticky-hide-offset'));
var sticky_transition=$menu.attr('data-sticky-transition');
var sticky_menu_offset_top;
var sticky_menu_offset_left;
var sticky_menu_width;
var sticky_menu_width_round_up;
var sticky_menu_height;
var is_stuck=false;
var admin_bar_height=0;
var last_scroll_top=0;
var saved_scroll_top=0;
var is_vertical=$menu.hasClass('mega-menu-vertical')||$menu.hasClass('mega-menu-accordion');
plugin.isDesktopView=function(){
return Math.max(window.outerWidth, $(window).width()) >=breakpoint;
};
var sticky_hide_until_scroll_up_enabled=function(){
return $menu.hasClass('mega-menu-horizontal')&&sticky_hide_until_scroll_up=="true";
}
var sticky_enabled=function(){
if(plugin.isDesktopView()){
return sticky_on_desktop==='true';
}else{
return sticky_on_mobile==='true';
}
return false;
};
plugin.calculate_menu_position=function(){
sticky_menu_offset_top=$wrap.offset().top;
if($('body').hasClass('admin-bar')&&$("#wpadminbar").is(":visible")&&$("#wpadminbar").css('top')=='0px'&&$("#wpadminbar").css('position')=='fixed'){
admin_bar_height=$('#wpadminbar').height();
sticky_menu_offset_top=sticky_menu_offset_top - admin_bar_height;
}
if(sticky_offset < 0){
sticky_menu_offset_top=sticky_menu_offset_top + sticky_offset;
}else{
sticky_menu_offset_top=sticky_menu_offset_top - sticky_offset;
}
sticky_menu_offset_left=$menu.parent().offset().left;
sticky_menu_width=window.getComputedStyle($wrap[0]).width;
sticky_menu_width_round_up=Math.ceil(parseFloat(sticky_menu_width));
sticky_menu_height=$wrap.height();
};
plugin.stick_menu=function(){
is_stuck=true;
var total_offset=parseInt(admin_bar_height, 10) + parseInt(sticky_offset, 10);
if(sticky_offset < 0){
total_offset=parseInt(admin_bar_height, 10);
}
var placeholder=$("<div />").addClass("mega-sticky-wrapper").css({
'height':sticky_menu_height + 'px',
'position' :'static'
});
$wrap.addClass('mega-sticky').wrap(placeholder).css({
'margin-top':total_offset + 'px'
});
$("body").addClass($menu.attr("id") + "-mega-sticky");
$menu.css({
'max-width':sticky_menu_width_round_up + 'px'
});
if(sticky_menu_offset_left > 0){
$menu.css({
'margin-left':sticky_menu_offset_left + 'px'
});
}
if(is_vertical||sticky_expand==='false'){
$wrap.css({
'margin-left':'0',
'margin-right':'0',
'width':sticky_menu_width_round_up + 'px',
'left':sticky_menu_offset_left + 'px'
});
$menu.css({
'margin-left':'0'
});
}
if($(window).width() <=breakpoint){
$wrap.css({
'width':sticky_menu_width_round_up + 'px'
});
if(sticky_expand_mobile==='true'){
$wrap.css({
'margin-left':'',
'margin-right':'',
'width':'',
'left':''
});
$menu.css({
'max-width':'',
'margin-left':'',
'width':'',
'left':''
});
}}
$wrap.delay(0).queue(function(next){
$(this).addClass('mega-stuck');
next();
});
};
plugin.unstick_menu=function(doing_resize){
doing_resize=doing_resize||false;
is_stuck=false;
$wrap.removeClass('mega-sticky').removeClass('mega-hide').css({
'margin':'',
'width':'',
'left': ''
});
$("body").removeClass($menu.attr("id") + "-mega-sticky");
if(! doing_resize){
$wrap.delay(0).queue(function(next){
$(this).removeClass('mega-stuck');
next();
});
}
$menu.css({
'margin-left':'',
'max-width':'',
'left':'',
'width':''
});
if($(window).width() <=breakpoint){
$menu.data('maxmegamenu').toggleBarForceWidth();
}
if(sticky_transition=='true'&&! doing_resize){
var delay=250;
}else{
var delay=0;
}
$wrap.delay(delay).queue(function(next){
$(this).unwrap();
next();
});
};
plugin.mega_sticky_on_scroll=function(){
if(! sticky_enabled()){
return;
}
var scroll_top=$(window).scrollTop();
if(scroll_top > sticky_menu_offset_top){
if(!is_stuck){
plugin.stick_menu();
}}else{
if(is_stuck){
plugin.unstick_menu();
}}
};
var mega_hide_on_scroll_up=function(){
if(sticky_hide_until_scroll_up_enabled()){
if($menu.data("view")==="mobile"&&$('.mega-menu-toggle', $wrap).hasClass('mega-menu-open')){
return;
}
var scroll_top=$(window).scrollTop();
if(scroll_top < sticky_hide_until_scroll_up_offset){
$wrap.removeClass('mega-hide');
$("body").removeClass($menu.attr("id") + "-mega-hide");
}
saved_scroll_top=last_scroll_top;
if(scroll_top < last_scroll_top){
if(saved_scroll_top - scroll_top > sticky_hide_until_scroll_up_tolerance){
$wrap.removeClass('mega-hide');
$("body").removeClass($menu.attr("id") + "-mega-hide");
}}else{
if(is_stuck&&scroll_top - saved_scroll_top > sticky_hide_until_scroll_up_tolerance){
$wrap.addClass('mega-hide');
$("body").addClass($menu.attr("id") + "-mega-hide");
}}
last_scroll_top=scroll_top;
}}
plugin.mega_sticky_on_resize=function(){
if($('input', $wrap).is(':focus')){
return;
}
if(sticky_enabled()){
if(is_stuck){
plugin.unstick_menu(true);
plugin.calculate_menu_position();
plugin.stick_menu();
}else{
plugin.calculate_menu_position();
plugin.mega_sticky_on_scroll();
}}else{
if(is_stuck){
plugin.unstick_menu();
}}
};
plugin.init=function(){
plugin.calculate_menu_position();
plugin.mega_sticky_on_scroll();
$('.mega-menu-accordion li.mega-menu-item').on('open_panel', function(){
plugin.calculate_menu_position();
});
var $window=$(window);
$window.scroll(function(){
plugin.mega_sticky_on_scroll();
mega_hide_on_scroll_up();
});
var windowWidth=$window.width();
var resizeTimer;
$window.resize(function(){
clearTimeout(resizeTimer);
resizeTimer=setTimeout(function(){
windowWidth=$window.width();
plugin.mega_sticky_on_resize();
}, 100);
});
};
plugin.init();
};
$.fn.maxmegamenu_sticky=function(options){
return this.each(function(){
if(undefined===$(this).data('maxmegamenu_sticky')){
var plugin=new $.maxmegamenu_sticky(this, options);
$(this).data('maxmegamenu_sticky', plugin);
}});
};
$(window).on('load', function (e){
$(".mega-menu[data-sticky-enabled]").maxmegamenu_sticky();
});
})(jQuery);
(function($){
$(function(){
var calculate_tabbed_sub_menu_widths=function(menu_item){
var menu=menu_item.parents('.max-mega-menu');
if($(menu.attr('data-panel-inner-width')).length > 0){
if(menu.data("view")==="desktop"){
$('> ul.mega-sub-menu', menu_item).each(function(){
var tab_content=$(this);
var parent_submenu_content_width=parseInt(tab_content.width());
var parent_submenu_left_padding=parseInt(tab_content.css('paddingLeft'));
var tabs_width=$(this).find('a.mega-menu-link').first().outerWidth();
$('> li.mega-menu-item > ul.mega-sub-menu', $(this)).each(function(){
$(this).css('width', parent_submenu_content_width - tabs_width + 'px');
$(this).css('left', parent_submenu_left_padding + tabs_width + 'px');
});
});
}else{
$('> ul.mega-sub-menu > li.mega-menu-item > ul.mega-sub-menu', menu_item).each(function(){
$(this).css('width', '');
$(this).css('left', '');
});
}}
}
var calculate_tabbed_sub_menu_heights=function(menu_item){
var menu=menu_item.parents('.max-mega-menu');
var max_height=0;
if(menu.data("view")==="desktop"){
$('> ul.mega-sub-menu', menu_item).css('minHeight', '');
$('> ul.mega-sub-menu > li.mega-menu-item > ul.mega-sub-menu', menu_item).each(function(){
var tab_content=$(this);
var this_height=parseInt(tab_content.css('height'));
if(this_height > max_height){
max_height=this_height;
}});
var border_top_width=parseInt($('> ul.mega-sub-menu', menu_item).css('borderTopWidth'),10);
var border_bottom_width=parseInt($('> ul.mega-sub-menu', menu_item).css('borderBottomWidth'),10);
$('> ul.mega-sub-menu', menu_item).css('minHeight', max_height + border_bottom_width + border_top_width);
}else{
$('> ul.mega-sub-menu', menu_item).css('minHeight', '');
}}
var $window=$(window);
var windowWidth=$window.width();
$window.resize(function(){
if($window.width()!=windowWidth){
calculate_tabbed_sub_menu_widths($('li.mega-menu-tabbed'));
calculate_tabbed_sub_menu_heights($('li.mega-menu-tabbed'));
}});
$('li.mega-menu-tabbed, li.mega-menu-tabbed li.mega-collapse-children').on('open_panel', function(){
var menu=$(this).parents('.max-mega-menu');
var menu_item=$(this).closest(".mega-menu-tabbed");
calculate_tabbed_sub_menu_widths(menu_item);
$("> ul.mega-sub-menu", $(this)).promise().done(function(){
calculate_tabbed_sub_menu_heights(menu_item);
});
if(menu.data('view')=='desktop'){
if($('> ul.mega-sub-menu > li.mega-menu-item-has-children.mega-toggle-on', menu_item).length==0){
if($('> ul.mega-sub-menu > li.mega-current-menu-item:visible', menu_item).length){
$('> ul.mega-sub-menu > li.mega-current-menu-item:visible', menu_item).first().addClass('mega-toggle-on');
}else if($('> ul.mega-sub-menu > li.mega-current-menu-ancestor:visible', menu_item).length){
$('> ul.mega-sub-menu > li.mega-current-menu-ancestor:visible', menu_item).first().addClass('mega-toggle-on');
}
if($('> ul.mega-sub-menu > li.mega-toggle-on', menu_item).length==0){
$('> ul.mega-sub-menu > li.mega-menu-item-has-children:visible', menu_item).first().addClass('mega-toggle-on');
}}
$('li.mega-menu-tabbed', menu).on('close_panel', function(){
$('li.mega-menu-tabbed .mega-toggle-on', menu).removeClass('mega-toggle-on');
});
}
$('li.mega-menu-tabbed li.mega-collapse-children').on('close_panel', function(){
var menu_item=$(this).closest('.mega-menu-tabbed');
$("> ul.mega-sub-menu", $(this)).promise().done(function(){
calculate_tabbed_sub_menu_heights(menu_item);
});
});
});
});
})(jQuery);
const ntaiWaNumber=ntaiData.waNumber;
const ntaiWaTemplate=ntaiData.waTemplate;
const ntaiAjaxUrl=ntaiData.ajaxUrl;
const ntaiHasPrices=(typeof window.ntDataCalc!=='undefined'&&window.ntDataCalc.kalkulasi_pax)||(ntaiData.pricesJSON&&Object.keys(ntaiData.pricesJSON).length > 0);
const ntaiFeaturedImage=ntaiData.featuredImage;
const ntaiRecommendedTours=ntaiData.recommendedTours;
const ntaiGreetingText=ntaiData.greetingText;
const ntaiSelInclude=ntaiData.selInclude;
const ntaiSelExclude=ntaiData.selExclude;
const ntaiSelItinerary=ntaiData.selItinerary;
const ntaiFollowupMsg=ntaiData.followupMsg;
const ntaiFollowupTimer=ntaiData.followupTimer;
let ntaiChatLog=[];
let ntaiNudgeTimer=null;
let ntaiHasNudged=false;
window.ntaiSearchMode=false;
window.ntaiConversationHistory=[];
let ntaiLeadScore=0;
setTimeout(()=> { ntaiLeadScore +=2; }, 120000);
let ntaiHistory=JSON.parse(localStorage.getItem('ntai_tour_history'))||[];
let rawDocTitle=document.title.replace(/\s*-\s*Paket Wisata[-\s]*Nusantaratrip.*/i, '').replace(/\s*\|\s*Nusantaratrip.*/i, '').trim();
let currentTourUrl=window.location.href;
if(ntaiHistory.length===0||ntaiHistory[ntaiHistory.length - 1].url!==currentTourUrl){
ntaiHistory.push({ title: rawDocTitle, url: currentTourUrl });
if(ntaiHistory.length > 3) ntaiHistory.shift();
localStorage.setItem('ntai_tour_history', JSON.stringify(ntaiHistory));
}
let historyText=ntaiHistory.map(h=> h.title).join(", ");
function initNtaiAgent(){
const wrapper=document.getElementById("ntai-system-wrapper");
if(wrapper&&document.body) document.body.appendChild(wrapper);
const floatingBtn=document.getElementById("ntai-floating-btn");
const aiModalOverlay=document.getElementById("ntai-modal-overlay");
const closeBtn=document.getElementById("ntai-close-chat");
const badge=document.getElementById("ntai-badge-notif");
const fsBtn=document.getElementById("ntai-toggle-fs");
const iconExpand=document.getElementById("ntai-icon-expand");
const iconCollapse=document.getElementById("ntai-icon-collapse");
const chatContainer=document.getElementById("ntai-chat-container");
if(fsBtn){
fsBtn.addEventListener("click", function(){
chatContainer.classList.toggle("ntai-fullscreen");
if(chatContainer.classList.contains("ntai-fullscreen")){
iconExpand.style.display="none";
iconCollapse.style.display="block";
}else{
iconExpand.style.display="block";
iconCollapse.style.display="none";
}
setTimeout(ntaiScrollToBottom, 300);
});
}
function ntaiOpenChat(){
if(aiModalOverlay) aiModalOverlay.classList.add("show");
if(badge) badge.style.display='none';
const nudge=document.getElementById('ntai-nudge');
if(nudge) nudge.style.display='none';
const ntBookFloat=document.querySelector('.nt-float-btn');
if(ntBookFloat){ ntBookFloat.style.opacity='0'; ntBookFloat.style.pointerEvents='none'; }
setTimeout(ntaiScrollToBottom, 300);
if(!ntaiHasNudged){
ntaiNudgeTimer=setTimeout(()=> {
ntaiShowTyping();
setTimeout(()=> {
ntaiHideTyping();
ntaiMsg(ntaiFollowupMsg + ntaiGetWaTemplate(), "ai", true);
ntaiHasNudged=true;
}, 1000);
}, ntaiFollowupTimer);
}}
function ntaiCloseChat(){
if(aiModalOverlay) aiModalOverlay.classList.remove("show");
const ntBookFloat=document.querySelector('.nt-float-btn');
if(ntBookFloat){ ntBookFloat.style.opacity=''; ntBookFloat.style.pointerEvents=''; }
if(chatContainer&&chatContainer.classList.contains("ntai-fullscreen")){
chatContainer.classList.remove("ntai-fullscreen");
iconExpand.style.display="block";
iconCollapse.style.display="none";
}}
if(floatingBtn) floatingBtn.addEventListener("click", ntaiOpenChat);
if(closeBtn) closeBtn.addEventListener("click", ntaiCloseChat);
if(aiModalOverlay){ aiModalOverlay.addEventListener("click", function(e){ if(e.target===this) ntaiCloseChat(); });}
setTimeout(()=> {
const nudge=document.getElementById('ntai-nudge');
const overlay=document.getElementById('ntai-modal-overlay');
if(nudge&&overlay&&!overlay.classList.contains('show')) nudge.classList.add('show-nudge');
}, 3000);
setInterval(function(){
if(!floatingBtn) return;
const modals=document.querySelectorAll('.nt-modal-overlay, #reviewModal');
let isAnyModalOpen=false;
modals.forEach(m=> {
const style=window.getComputedStyle(m);
if(style.display!=='none'&&style.opacity!=='0'&&style.visibility!=='hidden') isAnyModalOpen=true;
});
if(aiModalOverlay&&aiModalOverlay.classList.contains('show')) isAnyModalOpen=true;
if(isAnyModalOpen) floatingBtn.classList.add('ntai-hidden');
else floatingBtn.classList.remove('ntai-hidden');
}, 300);
const sendBtn=document.getElementById("ntai-send");
const inputField=document.getElementById("ntai-text");
setTimeout(()=> {
const jam=new Date().getHours();
let sapaanWaktu="Halo";
if(jam >=3&&jam < 11){ sapaanWaktu="Selamat Pagi"; }
else if(jam >=11&&jam < 15){ sapaanWaktu="Selamat Siang"; }
else if(jam >=15&&jam < 18){ sapaanWaktu="Selamat Sore"; }else{ sapaanWaktu="Selamat Malam"; }
let dynamicGreeting=ntaiGreetingText.replace(/paket wisata ini/gi, `paket wisata <strong>${rawDocTitle}</strong>`);
dynamicGreeting=dynamicGreeting.replace(/\[judul_paket\]/gi, `<strong>${rawDocTitle}</strong>`);
ntaiMsg(`<strong>${sapaanWaktu} Kak! 👋</strong> ${dynamicGreeting}`, "ai", true);
ntaiAppendQuickReplies();
}, 600);
function ntaiHandleUserInput(){
if(!inputField) return;
const q=inputField.value.trim();
if(!q) return;
const qrs=document.querySelectorAll('.ntai-quick-replies');
qrs.forEach(qr=> qr.remove());
inputField.value="";
clearTimeout(ntaiNudgeTimer);
ntaiHasNudged=true;
ntaiProcessApiRequest(q);
}
if(sendBtn) sendBtn.onclick=ntaiHandleUserInput;
if(inputField){
inputField.addEventListener("keypress", function(event){
if(event.key==="Enter"){ event.preventDefault(); ntaiHandleUserInput(); }});
}}
window.ntaiOpenWaChat=function(e){
if(e) e.preventDefault();
let waText=ntaiWaTemplate.replace(/\[judul_paket\]/g, rawDocTitle).replace(/\[url_paket\]/g, currentTourUrl);
if(ntaiChatLog.length > 0){
waText +=`*-- Riwayat Chat dengan AI --*\n`;
let recentChats=ntaiChatLog.slice(-6);
recentChats.forEach(chat=> {
let cleanMsg=chat.msg.replace(/<[^>]*>?/gm, '');
waText +=`_${chat.sender}_: ${cleanMsg}\n`;
});
}
if(ntaiLeadScore >=3){ waText +=`\n\n[Sistem: 🔥 Folow up Prioritas]`; }
if(typeof gtag!=='undefined'){ gtag('event', 'generate_lead', { 'event_category': 'WhatsApp', 'event_label': 'AI_Agent' });}
if(typeof fbq!=='undefined'){ fbq('track', 'Contact'); }
window.open(`https://wa.me/${ntaiWaNumber}?text=${encodeURIComponent(waText)}`, '_blank');
};
function ntaiGetWaTemplate(){
return `<div class="ntai-wa-action-box"><a class="ntai-wa-btn" href="#" onclick="window.ntaiOpenWaChat(event)"><svg width="18" height="18" viewBox="0 0 24 24" fill="white"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51a12.8 12.8 0 0 0-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 0 1-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 0 1-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 0 1 2.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0 0 12.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 0 0 5.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 0 0-3.48-8.413Z"/></svg> Konsultasi via WA</a></div>`;
}
const ntaiSvgSum=`<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>`;
const ntaiSvgItin=`<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>`;
const ntaiSvgFac=`<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>`;
const ntaiSvgPrice=`<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"></line><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"></path></svg>`;
const ntaiSvgRec=`<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg>`;
const ntaiSvgSearch=`<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>`;
const ntaiQuickRepliesTpl=`
<div class="ntai-quick-replies" id="ntai-qr-container">
<button class="ntai-qr-btn nt-trigger-wizard" style="border-color:#16a34a; color:#15803d; background:#f0fdf4; font-weight:800; width:100%; margin-bottom:8px; justify-content:center;">✨ Rancang Custom Tour Sendiri</button>
<button class="ntai-qr-btn" onclick="window.ntaiAction('summary')">${ntaiSvgSum} Ringkasan</button>
<button class="ntai-qr-btn" onclick="window.ntaiAction('itinerary')">${ntaiSvgItin} Itinerary</button>
<button class="ntai-qr-btn" onclick="window.ntaiAction('facility')">${ntaiSvgFac} Fasilitas</button>
<button class="ntai-qr-btn" onclick="window.ntaiAction('price')">${ntaiSvgPrice} Harga</button>
<button class="ntai-qr-btn" onclick="window.ntaiAction('recommendation')">${ntaiSvgRec} Paket Lain</button>
<button class="ntai-qr-btn" onclick="window.ntaiAction('search')">${ntaiSvgSearch} Cari Tour</button>
</div>
`;
function ntaiAppendQuickReplies(){
const existing=document.getElementById("ntai-qr-container");
if(existing) existing.remove();
const chat=document.getElementById("ntai-chat-body");
if(!chat) return;
const div=document.createElement("div");
div.innerHTML=ntaiQuickRepliesTpl;
chat.appendChild(div);
ntaiScrollToBottom();
}
function ntaiFormatText(text){
if(!text) return "";
let formatted=text.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
formatted=formatted.replace(/\*(.*?)\*/g, '<em>$1</em>');
formatted=formatted.replace(/(?:^|\n)\* (.*?)(?=\n|$)/g, '<li>$1</li>');
formatted=formatted.replace(/(?:^|\n)- (.*?)(?=\n|$)/g, '<li>$1</li>');
if(formatted.includes('<li>')){ formatted=formatted.replace(/(<li>.*<\/li>)/s, '<ul>$1</ul>'); }
formatted=formatted.replace(/\n/g, '<br>');
formatted=formatted.replace(/<br>\s*<ul>/g, '<ul>');
formatted=formatted.replace(/<\/ul>\s*<br>/g, '</ul>');
formatted=formatted.replace(/<br>\s*<li>/g, '<li>');
return formatted;
}
function ntaiScrollToBottom(){
const chat=document.getElementById("ntai-chat-body");
if(chat) chat.scrollTop=chat.scrollHeight;
}
function ntaiMsg(text, type, isHtmlRaw=false){
const chat=document.getElementById("ntai-chat-body");
if(!chat) return null;
const div=document.createElement("div");
div.className="ntai-msg " + (type==="user" ? "ntai-user-msg":"ntai-ai-msg");
if(type==="ai"){ div.innerHTML=isHtmlRaw ? text:ntaiFormatText(text); }else{ div.innerHTML=ntaiFormatText(text); }
chat.appendChild(div);
ntaiScrollToBottom();
return div;
}
function ntaiShowTyping(){
const chat=document.getElementById("ntai-chat-body");
if(!chat) return;
const div=document.createElement("div");
div.id="ntai-typing-indicator";
div.className="ntai-typing";
div.innerHTML="<span></span><span></span><span></span>";
chat.appendChild(div);
ntaiScrollToBottom();
}
function ntaiHideTyping(){
const indicator=document.getElementById("ntai-typing-indicator");
if(indicator) indicator.remove();
}
window.ntaiAction=function(actionType){
const qrs=document.querySelectorAll('.ntai-quick-replies');
qrs.forEach(qr=> qr.remove());
clearTimeout(ntaiNudgeTimer);
ntaiHasNudged=true;
if(actionType==='search'){
const userMsg="Cari Paket Wisata Lain";
ntaiMsg(userMsg, "user");
ntaiChatLog.push({sender: "Tamu", msg: userMsg});
ntaiConversationHistory.push({ role: "user", parts: [{ text: userMsg }] });
ntaiShowTyping();
setTimeout(()=> {
ntaiHideTyping();
window.ntaiSearchMode=true;
const responseText=`Tentu Kak! Silakan ketik kota atau destinasi yang Kakak cari (contoh: *Jogja*, *Bali*, *Bromo*):`;
ntaiMsg(ntaiFormatText(responseText), "ai", true);
ntaiChatLog.push({sender: "Sistem", msg: "Meminta keyword pencarian."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: responseText }] });
}, 500);
}
else if(actionType==='summary'){
const userMsg="Berikan Ringkasan Paket";
ntaiMsg(userMsg, "user");
ntaiChatLog.push({sender: "Tamu", msg: userMsg});
ntaiConversationHistory.push({ role: "user", parts: [{ text: userMsg }] });
ntaiShowTyping();
setTimeout(()=> {
ntaiHideTyping();
const excerptEl=document.getElementById("ntai-hidden-excerpt-data");
let summaryText=(excerptEl&&excerptEl.innerText.trim()!=="") ? excerptEl.innerText.trim().replace(/\n/g, '<br>'):"Ringkasan paket wisata ini belum tersedia.";
let responseHtml=`
<div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:12px; padding:14px; margin-bottom:12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);">
<div style="display:flex; align-items:center; gap:8px; margin-bottom:10px; border-bottom:1px dashed #cbd5e1; padding-bottom:10px;">
<span style="font-size:18px;">✨</span>
<h4 style="margin:0; color:#15803d; font-size:14.5px; font-weight:700;">Ringkasan Paket Wisata</h4>
</div>
<p style="margin:0; color:#334155; font-size:13.5px; line-height:1.6;">${summaryText}</p>
</div>`;
const newBubble=ntaiMsg(responseHtml + ntaiGetWaTemplate(), "ai", true);
setTimeout(()=> { if(newBubble) document.getElementById("ntai-chat-body").scrollTo({ top: newBubble.offsetTop - 15, behavior: 'smooth' });}, 300);
ntaiChatLog.push({sender: "Sistem", msg: "Menampilkan ringkasan UI Baru."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: summaryText }] });
ntaiAppendQuickReplies();
}, 500);
}
else if(actionType==='itinerary'){
ntaiLeadScore +=2;
const userMsg="Tampilkan Itinerary Perjalanan";
ntaiMsg(userMsg, "user");
ntaiChatLog.push({sender: "Tamu", msg: userMsg});
ntaiConversationHistory.push({ role: "user", parts: [{ text: userMsg }] });
ntaiShowTyping();
setTimeout(()=> {
ntaiHideTyping();
const itinRaw=document.querySelector(ntaiSelItinerary);
let itinText="Data itinerary detail belum tersedia di halaman ini.";
if(itinRaw){
const clone=itinRaw.cloneNode(true);
clone.style.position='absolute';
clone.style.left='-9999px';
const allElements=clone.querySelectorAll('*');
allElements.forEach(el=> { el.style.display='block'; el.style.visibility='visible'; el.style.height='auto'; });
document.body.appendChild(clone);
let rawText=clone.innerText.trim();
document.body.removeChild(clone);
rawText=rawText.replace(/^(Hari\s*(?:ke\s*-?\s*)?\d+.*)/gmi, '||HARI||$1');
rawText=rawText.replace(/^(Day\s*\d+.*)/gmi, '||HARI||$1');
let parts=rawText.split('||HARI||');
itinText=parts[0] ? `<p style="margin-bottom:12px; font-size:13.5px; color:#475569; padding-left:5px;">${parts[0].replace(/\n/g, ' ')}</p>`:'';
for(let i=1; i < parts.length; i++){
let splitPart=parts[i].split('\n');
let hariTitle=splitPart.shift().replace(/\*\*/g, '').trim();
let content=splitPart.join(' ').replace(/\s+/g, ' ').trim();
content=content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
content=content.replace(/(^|[^\d])(\d{2}[.:]\d{2}(?:\s*[-–]\s*\d{2}[.:]\d{2})?(?:\s*(?:WIB|WITA|WIT))?)(?!\d)/gi, '$1<div style="margin-top:10px; margin-bottom:4px;"><span style="display:inline-flex; align-items:center; background:#f1f5f9; color:#475569; padding:3px 10px; border-radius:6px; font-weight:800; font-size:11.5px; border:1px solid #cbd5e1;"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" style="margin-right:4px;"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg> $2</span></div>');
itinText +=`
<div style="margin-bottom: 14px; border-left: 2px dashed #16a34a; padding-left: 14px; margin-left: 8px; position:relative;">
<div style="position:absolute; left:-7.5px; top:2px; width:13px; height:13px; background:#16a34a; border-radius:50%; border:3px solid #ffffff;"></div>
<div style="background:#dcfce7; color:#15803d; display:inline-block; padding:4px 10px; border-radius:6px; font-weight:700; font-size:12.5px; margin-bottom:8px; margin-top:-4px; border:1px solid #bbf7d0;">📍 ${hariTitle}</div>
<div style="font-size:13px; color:#334155; line-height:1.6;">${content}</div>
</div>`;
}}
let imageHtml="";
if(ntaiFeaturedImage){
imageHtml=`<img src="${ntaiFeaturedImage}" alt="Destinasi Wisata" style="width: 100%; height: auto; max-height: 300px; object-fit: contain; border-radius: 8px; margin-bottom: 12px; border: 1px solid #e2e8f0; background: #f8fafc; display: block; margin-left: auto; margin-right: auto;">`;
}
let responseHtml=`
<div style="background:#ffffff; border:1px solid #e2e8f0; border-radius:12px; padding:14px; margin-bottom:12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);">
${imageHtml}
<div style="display:flex; align-items:center; gap:8px; margin-bottom:16px; border-bottom:1px dashed #cbd5e1; padding-bottom:10px;">
<span style="font-size:18px;">🗺️</span>
<h4 style="margin:0; color:#0f172a; font-size:14.5px; font-weight:700;">Detail Itinerary</h4>
</div>
<div style="margin-top:10px; padding-right:5px;">
${itinText==="Data itinerary detail belum tersedia di halaman ini." ? `<div style="background:#fef2f2; padding:10px; border-radius:8px; color:#b91c1c; font-size:13px; text-align:center;">${itinText}</div>`:itinText}
</div>
</div>`;
const newBubble=ntaiMsg(responseHtml + ntaiGetWaTemplate(), "ai", true);
setTimeout(()=> { if(newBubble) document.getElementById("ntai-chat-body").scrollTo({ top: newBubble.offsetTop - 15, behavior: 'smooth' });}, 300);
ntaiChatLog.push({sender: "Sistem", msg: "Menampilkan Itinerary UI Baru."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: "Ini adalah rincian itinerary yang bisa saya tampilkan." }] });
ntaiAppendQuickReplies();
}, 500);
}
else if(actionType==='facility'){
const userMsg="Cek Fasilitas Paket";
ntaiMsg(userMsg, "user");
ntaiChatLog.push({sender: "Tamu", msg: userMsg});
ntaiConversationHistory.push({ role: "user", parts: [{ text: userMsg }] });
ntaiShowTyping();
setTimeout(()=> {
ntaiHideTyping();
const incRaw=document.querySelector(ntaiSelInclude) ? document.querySelector(ntaiSelInclude).innerText:"Data tidak ditemukan.";
const excRaw=document.querySelector(ntaiSelExclude) ? document.querySelector(ntaiSelExclude).innerText:"Data tidak ditemukan.";
function formatListUi(text, isInclude){
if(text.includes("Data tidak ditemukan")) return `<p style="margin:0; font-size:13px; color:#64748b;">${text}</p>`;
let items=text.split('\n').filter(i=> i.trim()!=='');
let iconSvg=isInclude
? '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>'
: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#ef4444" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>';
let html='<div style="display:flex; flex-direction:column; gap:8px;">';
items.forEach(item=> {
item=item.replace(/^[-*•]\s*/, '').replace(/^\d+[\.\)]\s*/, '').trim();
if(item){ html +=`<div style="display:flex; align-items:flex-start; gap:10px; font-size:13.5px; color:#334155; line-height:1.5;"><span style="flex-shrink:0; margin-top:1px;">${iconSvg}</span> <span>${item}</span></div>`; }});
html +='</div>';
return html;
}
let responseHtml=`
<div style="margin-bottom:12px;">
<div style="background:#f0fdf4; border:1px solid #bbf7d0; border-radius:12px; padding:14px; margin-bottom:12px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
<h4 style="margin:0 0 12px 0; color:#15803d; font-size:14.5px; font-weight:700; border-bottom:1px dashed #bbf7d0; padding-bottom:8px;">✅ Termasuk (Include)</h4>
${formatListUi(incRaw, true)}
</div>
<div style="background:#fef2f2; border:1px solid #fecaca; border-radius:12px; padding:14px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
<h4 style="margin:0 0 12px 0; color:#b91c1c; font-size:14.5px; font-weight:700; border-bottom:1px dashed #fecaca; padding-bottom:8px;">❌ Belum Termasuk (Exclude)</h4>
${formatListUi(excRaw, false)}
</div>
</div>`;
const newBubble=ntaiMsg(responseHtml + ntaiGetWaTemplate(), "ai", true);
setTimeout(()=> { if(newBubble) document.getElementById("ntai-chat-body").scrollTo({ top: newBubble.offsetTop - 15, behavior: 'smooth' });}, 300);
ntaiChatLog.push({sender: "Sistem", msg: "Menampilkan daftar fasilitas UI Baru."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: "Ini adalah daftar fasilitas include dan exclude." }] });
ntaiAppendQuickReplies();
}, 500);
}
else if(actionType==='price'){
ntaiLeadScore +=2;
const userMsg="Cek Daftar Harga";
ntaiMsg(userMsg, "user");
ntaiChatLog.push({sender: "Tamu", msg: userMsg});
ntaiConversationHistory.push({ role: "user", parts: [{ text: userMsg }] });
ntaiShowTyping();
setTimeout(()=> {
ntaiHideTyping();
let priceHtml="";
const sourceTable=document.querySelector('.nt-table-wrapper');
if(sourceTable){
priceHtml=`
<div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:12px; padding:14px; margin-bottom:12px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05);">
<div style="display:flex; align-items:center; gap:8px; margin-bottom:12px; border-bottom:1px dashed #cbd5e1; padding-bottom:10px;">
<span style="font-size:18px;">💰</span>
<h4 style="margin:0; color:#15803d; font-size:14.5px; font-weight:700;">Daftar Harga Per Orang</h4>
</div>
<div style="overflow-x:auto; margin-bottom:10px;">
${sourceTable.outerHTML}
</div>
<div style="margin-top:12px; padding-top:10px; border-top:1px dashed #cbd5e1; font-size:11.5px; color:#64748b; line-height:1.5;">
<span style="color:#ef4444; font-weight:700;">*Note:</span> Harga dapat menyesuaikan jika ada permintaan <em>Custom Tour</em> atau saat <em>High Season</em>. Anak < 6 Th dikenakan biaya tiket masuk saja.
</div>
</div>`;
}else{
priceHtml=`
<div style="background:#fef2f2; border:1px solid #fecaca; border-radius:12px; padding:14px; text-align:center; margin-bottom:12px;">
<span style="font-size:24px;">💸</span>
<p style="margin:8px 0 0 0; color:#b91c1c; font-size:13.5px; line-height:1.5;">Maaf Kak, daftar harga detail belum tersedia di halaman ini. Silakan langsung hubungi Admin ya.</p>
</div>`;
}
const newBubble=ntaiMsg(priceHtml + ntaiGetWaTemplate(), "ai", true);
setTimeout(()=> { if(newBubble) document.getElementById("ntai-chat-body").scrollTo({ top: newBubble.offsetTop - 15, behavior: 'smooth' });}, 300);
ntaiChatLog.push({sender: "Sistem", msg: "Menampilkan tabel harga Matrix."});
const taraRef=document.getElementById('tara-reference-data');
let memoryPriceText=taraRef ? "Tampilkan UI Harga. Gunakan data berikut untuk info selanjutnya: " + taraRef.innerText:"Menampilkan UI Tabel Harga.";
ntaiConversationHistory.push({ role: "model", parts: [{ text: memoryPriceText }] });
ntaiAppendQuickReplies();
}, 500);
}
else if(actionType==='recommendation'){
const userMsg="Cek Paket Tour Lainnya";
ntaiMsg(userMsg, "user");
ntaiChatLog.push({sender: "Tamu", msg: userMsg});
ntaiConversationHistory.push({ role: "user", parts: [{ text: userMsg }] });
ntaiShowTyping();
setTimeout(()=> {
ntaiHideTyping();
let recHtml="Tentu Kak! Berdasarkan destinasi ini, kami merekomendasikan paket tour pilihan berikut:<br><br>";
if(ntaiRecommendedTours&&ntaiRecommendedTours.length > 0){
ntaiRecommendedTours.forEach(tour=> {
recHtml +=`
<a href="${tour.url}" class="ntai-rec-card" target="_blank">
<img src="${tour.thumb}" class="ntai-rec-img" alt="Thumbnail">
<h4 class="ntai-rec-title">${tour.title}</h4>
</a>`;
});
recHtml +="<br><span style='font-size:13px;'>Silakan klik kartu paket di atas untuk melihat rinciannya ya, atau hubungi Admin jika ingin *Custom Tour*!</span>";
}else{
recHtml="Maaf Kak, saat ini belum ada rekomendasi paket di destinasi yang sama. Silakan klik tombol WA di bawah untuk ngobrol dengan Admin kami ya.";
}
const newBubble=ntaiMsg(recHtml + ntaiGetWaTemplate(), "ai", true);
setTimeout(()=> { if(newBubble) document.getElementById("ntai-chat-body").scrollTo({ top: newBubble.offsetTop - 15, behavior: 'smooth' });}, 300);
ntaiChatLog.push({sender: "Sistem", msg: "Menampilkan rekomendasi tour sesuai destinasi."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: "Ini daftar rekomendasi tour lainnya." }] });
ntaiAppendQuickReplies();
}, 500);
}};
function ntaiGetPayloadData(q){
let qLower=q.toLowerCase();
let contentArr=[`Judul: ${rawDocTitle}`];
let priceDataFormatted="Harga tidak tersedia.";
if(qLower.match(/harga|biaya|orang|pax|anak|balita|berapa|tambahan|jemput|kota|area|hotel/)){
const taraRef=document.getElementById('tara-reference-data');
if(taraRef){
priceDataFormatted=taraRef.innerText;
}}
function getCleanText(element){
if(!element) return "Data tidak ditemukan.";
const clone=element.cloneNode(true);
const tables=clone.querySelectorAll('.tablepress, table');
tables.forEach(t=> t.remove());
return clone.innerText.replace(/\s+/g, ' ').trim();
}
if(qLower.match(/jadwal|jam|itinerary|rute|kapan|kemana|hari|jemput|kota|area/)){
let routeFound=false;
const jsonLdScripts=document.querySelectorAll('script[type="application/ld+json"]');
jsonLdScripts.forEach(script=> {
try {
const schemaData=JSON.parse(script.innerText);
if(schemaData['@type']==='TouristTrip'&&schemaData.itinerary){
let ruteArr=[];
schemaData.itinerary.itemListElement.forEach(item=> {
if(item.item&&item.item.name){
ruteArr.push(item.item.name.trim());
}});
contentArr.push(`Rute Perjalanan: ${ruteArr.join(" ➡️ ")}`);
routeFound=true;
}} catch (e){  }});
if(!routeFound){
const excerptEl=document.querySelector("#ntai-hidden-excerpt-data");
if(excerptEl) contentArr.push(`Ringkasan Itinerary: ${getCleanText(excerptEl).substring(0, 500)}`);
}}
if(qLower.match(/fasilitas|termasuk|include|exclude|makan|hotel|tiket|dapat/)){
const incEl=document.querySelector(ntaiSelInclude);
const excEl=document.querySelector(ntaiSelExclude);
if(incEl) contentArr.push(`Inc: ${getCleanText(incEl).substring(0, 300)}`);
if(excEl) contentArr.push(`Exc: ${getCleanText(excEl).substring(0, 300)}`);
}
const customInfos=document.querySelectorAll('.ntai-custom-info');
customInfos.forEach(info=> {
const title=info.getAttribute('data-title')||'Info Penting';
const contentBox=info.querySelector('.nt-info-app');
if(contentBox){
const text=getCleanText(contentBox);
if(text) contentArr.push(`${title}: ${text.substring(0, 1200)}`);
}});
if(ntaiRecommendedTours&&ntaiRecommendedTours.length > 0){
let recNames=ntaiRecommendedTours.map(tour=> tour.title).join(", ");
contentArr.push(`Rekomendasi Paket Lain di Area Ini: ${recNames}`);
}
return { priceStr: priceDataFormatted, contentStr: contentArr.join(" | ") };}
function ntaiProcessApiRequest(q){
let qLower=q.toLowerCase();
ntaiMsg(q, "user");
ntaiChatLog.push({sender: "Tamu", msg: q});
ntaiShowTyping();
ntaiConversationHistory.push({ role: "user", parts: [{ text: q }] });
let isSearchIntent=window.ntaiSearchMode||qLower.startsWith('cari ')||qLower.includes('wisata ke')||qLower.includes('tour ke')||qLower.includes('paket ke');
if(isSearchIntent){
window.ntaiSearchMode=false;
let searchKeyword=q.replace(/cari|paket|wisata|tour|ke|untuk/gi, '').trim();
if(!searchKeyword) searchKeyword=q;
let formData=new FormData();
formData.append('action', 'ntai_global_search');
formData.append('keyword', searchKeyword);
fetch(ntaiAjaxUrl, { method: 'POST', body: formData })
.then(r=> r.json())
.then(resData=> {
ntaiHideTyping();
let replyHtml="";
if(resData.success&&resData.data.length > 0){
replyHtml=`Ini daftar rekomendasi **${searchKeyword.toUpperCase()}** yang saya temukan untuk Kakak:<br><br>`;
resData.data.forEach(tour=> {
replyHtml +=`
<a href="${tour.url}" class="ntai-rec-card" target="_blank">
<img src="${tour.thumb}" class="ntai-rec-img" alt="Thumbnail">
<h4 class="ntai-rec-title">${tour.title}</h4>
</a>`;
});
replyHtml +=`<br><span style='font-size:13px;'>Silakan klik kartu di atas untuk rincian itinerary, atau hubungi kami untuk konfirmasi ketersediaan.</span>` + ntaiGetWaTemplate();
}else{
replyHtml=`Maaf Kak, saat ini saya belum menemukan paket untuk destinasi **"${searchKeyword}"** di database otomatis kami.<br><br>Tapi tenang, Tim Konsultan kami siap merancangkan Custom Itinerary khusus untuk Kakak! 😊` + ntaiGetWaTemplate();
}
const newBubble=ntaiMsg(replyHtml, "ai", true);
setTimeout(()=> { if(newBubble) document.getElementById("ntai-chat-body").scrollTo({ top: newBubble.offsetTop - 15, behavior: 'smooth' });}, 300);
ntaiChatLog.push({sender: "Sistem", msg: "Menampilkan hasil pencarian global."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: "Ini daftar rekomendasi yang saya temukan." }] });
ntaiAppendQuickReplies();
})
.catch(err=> {
ntaiHideTyping();
ntaiMsg(`Sistem pencarian kami sedang ada sedikit gangguan koneksi nih Kak 🙏. Silakan klik tombol WA di bawah ya agar dibantu cari langsung oleh Admin kami.` + ntaiGetWaTemplate(), "ai", true);
ntaiAppendQuickReplies();
});
return;
}
if(qLower.includes('pesan')||qLower.includes('booking')||qLower.includes('daftar')||qLower.includes('reservasi')||qLower.includes('book')){
setTimeout(()=> {
ntaiHideTyping();
let reply="Wah, mantap! 🎉 Untuk proses booking, reservasi, dan pengecekan ketersediaan jadwal, Kakak bisa langsung terhubung dengan Admin Reservasi kami ya.<br><br>Yuk klik tombol WhatsApp di bawah ini agar ketersediaannya bisa segera kami amankan!";
ntaiMsg(ntaiFormatText(reply) + ntaiGetWaTemplate(), "ai", true);
ntaiChatLog.push({sender: "Sistem", msg: "Diarahkan ke WA untuk booking."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: reply }] });
ntaiAppendQuickReplies();
}, 600);
return;
}
if(qLower.includes('tersedia')||qLower.includes('ketersediaan')||qLower.includes('slot')||qLower.includes('kuota')||qLower.includes('kosong')||qLower.includes('sisa')){
setTimeout(()=> {
ntaiHideTyping();
let reply="Berdasarkan sistem kami, untuk saat ini jadwal tersebut **sementara masih tersedia** Kak. ✅<br><br>Namun karena pergerakan kuota kami sangat cepat dan sering penuh, kami sangat menyarankan untuk segera melakukan *booking*.<br><br>Yuk amankan ketersediaan Kakak dengan menghubungi Admin Reservasi kami via WhatsApp di bawah ini!";
ntaiMsg(ntaiFormatText(reply) + ntaiGetWaTemplate(), "ai", true);
ntaiChatLog.push({sender: "Sistem", msg: "Menjawab ketersediaan (FOMO) & arahkan ke WA."});
ntaiConversationHistory.push({ role: "model", parts: [{ text: reply }] });
ntaiAppendQuickReplies();
}, 600);
return;
}
const payload=ntaiGetPayloadData(q);
fetch("/wp-json/nt-ai/v1/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
question: q,
conversation_history: ntaiConversationHistory.slice(-6),
price_data: payload.priceStr,
content_data: payload.contentStr,
history_data: historyText,
user: "Tamu",
url: window.location.href
})
})
.then(r=> r.json())
.then(res=> {
ntaiHideTyping();
let answer=res.answer||"";
let cleanAiAnswer=answer.replace(/\*/g, '').replace(/\n/g, ' ').substring(0, 100);
if(answer.length > 100) cleanAiAnswer +='...';
ntaiChatLog.push({sender: "Sistem", msg: cleanAiAnswer});
ntaiConversationHistory.push({ role: "model", parts: [{ text: answer }] });
if(answer.toLowerCase().includes("tidak tersedia")||answer.toLowerCase().includes("tidak menemukan")||answer.length < 5){
ntaiMsg(`Wah, maaf Kak, untuk info sedetail itu kebetulan belum tercatat di panduan singkat saya 😅.<br><br>Biar informasinya lebih akurat dan pasti, yuk langsung ngobrol sama Tim Admin kami via tombol WhatsApp di bawah ini!` + ntaiGetWaTemplate(), "ai", true);
}else{
ntaiMsg(ntaiFormatText(answer) + ntaiGetWaTemplate(), "ai", true);
}
ntaiAppendQuickReplies();
})
.catch(err=> {
ntaiHideTyping();
ntaiMsg(`Waduh Kak, sinyal internetnya sepertinya lagi kurang bersahabat nih 😅. Coba kirim ulang pertanyaannya ya, atau langsung klik tombol WA di bawah biar aman.` + ntaiGetWaTemplate(), "ai", true);
ntaiAppendQuickReplies();
});
}
let ntaiInitDone=false;
function triggerNtaiInit(){
if(ntaiInitDone) return;
ntaiInitDone=true;
initNtaiAgent();
window.removeEventListener('scroll', triggerNtaiInit);
window.removeEventListener('mousemove', triggerNtaiInit);
window.removeEventListener('touchstart', triggerNtaiInit);
document.removeEventListener('click', triggerNtaiInit);
}
window.addEventListener('scroll', triggerNtaiInit, { passive: true });
window.addEventListener('mousemove', triggerNtaiInit, { passive: true });
window.addEventListener('touchstart', triggerNtaiInit, { passive: true });
document.addEventListener('click', triggerNtaiInit, { passive: true });
setTimeout(triggerNtaiInit, 4000);
document.addEventListener('click', function(e){
const wizardBtn=e.target.closest('.nt-trigger-wizard');
if(wizardBtn){
e.preventDefault();
const aiModalOverlay=document.getElementById("ntai-modal-overlay");
if(aiModalOverlay) aiModalOverlay.classList.remove("show");
const ntBookFloat=document.querySelector('.nt-float-btn');
if(ntBookFloat){ ntBookFloat.style.opacity=''; ntBookFloat.style.pointerEvents=''; }
const chatContainer=document.getElementById("ntai-chat-container");
const iconExpand=document.getElementById("ntai-icon-expand");
const iconCollapse=document.getElementById("ntai-icon-collapse");
if(chatContainer&&chatContainer.classList.contains("ntai-fullscreen")){
chatContainer.classList.remove("ntai-fullscreen");
if(iconExpand) iconExpand.style.display="block";
if(iconCollapse) iconCollapse.style.display="none";
}
setTimeout(function(){
const wizOverlay=document.getElementById('nt-wizard-overlay');
if(wizOverlay){
wizOverlay.style.zIndex='2147483647';
wizOverlay.classList.add('show');
document.body.style.overflow='hidden';
}}, 50);
}});