/**
 * trainify custom.js
 *
 * @package MatrixAddons
 * @subpackage trainify
 * @version 1.0.0
 *
 * Contains handlers to make trainify WordPress theme custom javascript
 */
 ( function( $ ) {

 	'use strict';
 	var tff_document = $(document);
 	var tff_window = $(window);
    var trainifyLastFocusableEl;
    var trainify = {

 		Snipits:{

            Variables: function(){
                //Write your global variable here
            },

 			AppendData: function(){
 				//responsive sub menu toggle
 				$( '#site-navigation .menu-item-has-children, #site-navigation .page_item_has_children').append( '<span class="sub-toggle"> <i class="fa fa-angle-right"></i> </span>' );
 			},

 			Preloader: function(){
			    var preloader = $('#trainify_preloader_wrapper');
			    preloader.remove();
 			},

 			VisibilityScroller: function(){
 				if($(this).scrollTop()>1000){
 					$('#tff-scrollup').fadeIn('slow');
 				}else{
 					$('#tff-scrollup').fadeOut('slow');
 				}
 			},

 			ScrollTop: function(evt){
 				$("html, body").animate({
 					scrollTop: 0
 				}, 600);
 				return false;
 			},

 			SearchToggle: function(evt){
                evt.preventDefault();
                $('.search-form-main').toggleClass('active-search');
                
                if ($('.search-form-main').hasClass('active-search')) {
                    // When opening search, focus the search input after a short delay
                    setTimeout(function() {
                        $('.search-form-main .search-field').focus();
                    }, 10);
                } else {
                    // When closing search, return focus to the toggle button
                    $('.tff-header-search-wrapper .search-main').focus();
                }
                
                // Handle ESC key press to close search
                $(document).off('keydown.searchEscape').on('keydown.searchEscape', function(e) {
                    if (e.keyCode === 27 && $('.search-form-main').hasClass('active-search')) {
                        $('.search-form-main').removeClass('active-search');
                        $('.tff-header-search-wrapper .search-main').focus();
                    }
                });
            },

 			MenuToggle: function(evt){
 				$('.tff-header-menu-wrapper #site-navigation').slideToggle('slow');
 			},

 			SubToggle: function( evt ){

 				$(this).parent('.menu-item-has-children').children('ul.sub-menu').first().slideToggle('1000');
 				$(this).parent('.page_item_has_children').children('ul.children').first().slideToggle('1000');
 				$(this).children('.fa-angle-right').first().toggleClass('fa-angle-down');
                
 			},

 			Sliders: function(){

 				/**
				 * Notice script
				 */
                var $notice_obj = $('#newsNotice');
                if($notice_obj.length){
                    var noticeArgs = $notice_obj.data( 'notice' );
                    noticeArgs.onSliderLoad = function () {
                        $('#tff-newsNotice').removeClass('cS-hidden');
                    };
                    noticeArgs.prevHtml = '<i class="fa fa-chevron-left"></i>';
                    noticeArgs.nextHtml = '<i class="fa fa-chevron-right"></i>';
                    $notice_obj.lightSlider(noticeArgs);

                    $('.video-button a').magnificPopup({
                        disableOn: 700,
                        type: 'iframe',
                        mainClass: 'mfp-fade',
                        removalDelay: 160,
                        preloader: false,
                        fixedContentPos: false
                    });
                }
				/**
				 * Block carousel layout
				 */
				$( '.trainify-block-carousel' ).each(function(){
                    
                    var this_carousel = $(this);
                    var carousel_args = this_carousel.data('carousel');
                    if( this_carousel.closest('.widget-area').hasClass('sidebar-main-area') ){
                       carousel_args.item=1;
                    }
                    if( this_carousel.closest('.widget-area').hasClass('footer-sidebar-area') ){
                       carousel_args.item=1;
                    }
                    carousel_args.onSliderLoad = function(){
                        this_carousel.removeClass('cS-hidden');
                    }
                    var carousel_obj = this_carousel.lightSlider(carousel_args);
                    var carousel_wrapper = this_carousel.closest('.tff-block-posts-wrapper');
                    carousel_wrapper.find('.tff-navPrev').click(function () {
                        carousel_obj.goToPrevSlide();
                    });
                    carousel_wrapper.find('.tff-navNext').click(function () {
                        carousel_obj.goToNextSlide();
                    });

                });

                $( '.trainify-main-banner' ).each(function(){
                    
                    var this_banner = $(this);
                    var banner_args = this_banner.data('carousel');
                    banner_args.onSliderLoad = function(){
                        this_banner.removeClass('cS-hidden');
                    }
                    var carousel_obj = this_banner.lightSlider(banner_args);
                    var carousel_wrapper = this_banner.closest('.main-banner-slider-wrapper');
                    carousel_wrapper.find('.cycle-prev').click(function () {
                        carousel_obj.goToPrevSlide();
                    });
                    carousel_wrapper.find('.cycle-next').click(function () {
                        carousel_obj.goToNextSlide();
                    });

                });

 			},

            TabbedWidget: function(evt){
                
                evt.preventDefault();

                if($(this).closest('li').hasClass('active-item')){
                    return;
                }
                
                var tabbed_content_id = $(this).attr( 'href' );
                var tabbed_wrapper = $(this).closest('.tff-default-tabbed-wrapper');

                tabbed_wrapper.find( 'li' ).removeClass( 'active-item' );
                $(this).closest('li').addClass( 'active-item' );

                tabbed_wrapper.find('.tff-tabbed-section').removeClass('active-content');
                $(tabbed_content_id).addClass('active-content');

            },

 			Widget_Title_Tab: function(evt){

                evt.preventDefault();
                var tab_item = $(this);
                if( tab_item.closest( '.wdgt-tab-term' ).hasClass( 'active-item' ) ){
                    return;
                }
                var widget_title_tabs =  tab_item.closest('.wdgt-title-tabs');
                if( widget_title_tabs.attr( 'data-loading' ) == 1 ){
                    return;
                }

                var tab_content_class = tab_item.data('tab');
                var widget_title = tab_item.closest('.trainify-block-title');
                var block_post_widget = tab_item.closest('.widget');
                
                widget_title_tabs.find('.wdgt-tab-term').removeClass('active-item');
                tab_item.closest('li').addClass('active-item');
                block_post_widget.find('.tff-block-posts-wrapper').removeClass( 'tab-active' );
                if( block_post_widget.find( '.' + tab_content_class ).length ){
                    block_post_widget.find( '.' + tab_content_class ).addClass( 'tab-active' );
                    return;
                }
                var ajax_args = $(this).data('ajax-args');
                ajax_args.beforeSend = function(){
                    widget_title_tabs.attr( 'data-loading', 1 );
                    block_post_widget.find('.hmrcls-wdgt-preloader').removeClass('hidden');
                };
                ajax_args.success = function(data, status, settings){
                    widget_title_tabs.attr( 'data-loading', 0 );
                    block_post_widget.find('.hmrcls-wdgt-preloader').addClass('hidden');
                    var widget_html = data.widget_html;
                    if(widget_html){
                        block_post_widget.find('.trainify-framework-tab-alldata').after(widget_html);
                    }else{
                        console.warn('Sorry faild to retrive widget html data on ajax call');    
                    }
                };
                ajax_args.fail = function( xhr, textStatus, errorThrown ){
                    widget_title_tabs.attr( 'data-loading', 0 );
                    console.warn('Sorry faild widget tab ajax call');
                };
                $.ajax(ajax_args);                

            },
            Accessibility: function () {
                var mainNavigation = $('#site-navigation');
                
                // Trap focus within a container element when needed
                function trapFocus(element, openClass) {
                    var focusableEls = element.querySelectorAll('a[href]:not([disabled]), button:not([disabled]), textarea:not([disabled]), input[type="text"]:not([disabled]), input[type="search"]:not([disabled]), input[type="radio"]:not([disabled]), input[type="checkbox"]:not([disabled]), select:not([disabled])'),
                        firstFocusableEl = focusableEls[0];
                    trainifyLastFocusableEl = focusableEls[focusableEls.length - 1];
                    var KEYCODE_TAB = 9;
                    element.addEventListener('keydown', function (e) {
                        var isTabPressed = (e.key === 'Tab' || e.keyCode === KEYCODE_TAB);
        
                        if (!isTabPressed) {
                            return;
                        }
                        if (!element.classList.contains(open_class)) {
                            element.removeEventListener('keydown', this);
                            return;
        
                        }
        
                        if (e.shiftKey) /* shift + tab */ {
                            if (document.activeElement === firstFocusableEl) {
                                trainifyLastFocusableEl.focus();
                                e.preventDefault();
                            }
                        } else /* tab */ {
        
                            if (document.activeElement === trainifyLastFocusableEl) {
                                firstFocusableEl.focus();
                                e.preventDefault();
                            }
                        }
        
                    });              
                }
                
                // Add focus class to all menu items
                mainNavigation.find('li.menu-item, li.page_item').each(function() {
                    var $menuItem = $(this);
                    var $anchor = $menuItem.children('a');
                    var $submenu = $menuItem.children('ul.sub-menu, ul.children');
                    
                    // Add focus class when anchor is focused
                    $anchor.on('focus', function() {
                        $menuItem.addClass('menu-item-focused');
                    });
                    $anchor.on('focusout', function() {
                        $menuItem.removeClass('menu-item-focused');
                    });
                    
                    // If this is a parent menu item with submenu
                    if ($menuItem.hasClass('menu-item-has-children') || $menuItem.hasClass('page_item_has_children')) {
                        
                        // Add "submenu-open" class when parent gets focus
                        $menuItem.on('focusin', function() {
                            $submenu.addClass('submenu-open');
                            
                        });
                        
                        // Keyboard navigation: open submenu with Down Arrow, Space or Enter
                        $anchor.on('keydown', function(e) {
                            if (e.keyCode === 40 || e.keyCode === 32 || e.keyCode === 13) {
                                e.preventDefault();
                                e.stopPropagation();
                                $submenu.addClass('submenu-open');
                            
                                
                                // Move focus to first submenu item
                                setTimeout(function() {
                                    $submenu.find('li:first-child > a').focus();
                                }, 10);
                            }
                        });
                        
                        // Ensure Shift+Tab from first submenu item goes to parent link
                        $submenu.find('li:first-child > a').on('keydown', function(e) {
                            if (e.keyCode === 9 && e.shiftKey) {
                                e.preventDefault();
                                $anchor.focus();
                            }
                        });
                        
                        // ESC key should close submenu and return focus to parent link
                        $submenu.find('a').on('keydown', function(e) {
                            if (e.keyCode === 27) {
                                e.preventDefault();
                                e.stopPropagation();
                                $submenu.removeClass('submenu-open');
                               
                                $anchor.focus();
                            }
                        });
                        $menuItem.on('focusout', function() {
                            $submenu.removeClass('submenu-open');
                        
                        });
                    }
                });
                
                // When focus leaves a menu item's tree, close all submenus
                mainNavigation.on('focusout', function(e) {
                    // Check if the newly focused element is still within the navigation
                    if (!mainNavigation.has(e.relatedTarget).length) {
                        mainNavigation.find('.menu-item-focused').removeClass('menu-item-focused');
                        mainNavigation.find('.submenu-open').removeClass('submenu-open').css({
                            'opacity': '0',
                            'visibility': 'hidden'
                        });
                    }
                });
                
                // Search button focus styles
                $('.tff-header-search-wrapper .search-main').on('focus', function() {
                    $(this).addClass('search-focused');
                }).on('blur', function() {
                    $(this).removeClass('search-focused');
                });
                
                // Search toggle functionality with keyboard support
                $('.tff-header-search-wrapper .search-main').on('keydown', function(e) {
                    // Activate search on Enter or Space
                    if (e.keyCode === 13 || e.keyCode === 32) {
                        e.preventDefault();
                        trainify.Snipits.SearchToggle(e);
                    }
                });
                
                // Trap focus within search form when open
                var searchForm = document.querySelector('.search-form-main');
                if (searchForm) {
                    trapFocus(searchForm, 'active-search');
                }
            },

 		},

 		Events: function(){

 			var __this = trainify;
 			var snipits = __this.Snipits;

            snipits.Accessibility();

 			var widget_title_tab = snipits.Widget_Title_Tab;
            tff_document.on( 'click', '.dgwidgt-title-tab', widget_title_tab );

 			var trainify_scroll_top = snipits.ScrollTop;
 			$('#tff-scrollup').on('click', trainify_scroll_top);

 			var trainify_search_toggle = snipits.SearchToggle;
 			$( '.tff-header-search-wrapper .search-main' ).on( 'click', trainify_search_toggle );

 			//responsive menu toggle
 			var trainify_menu_toggle = snipits.MenuToggle;
 			$('.tff-header-menu-wrapper .menu-toggle').on( 'click', trainify_menu_toggle );

 			var trainify_subtoggle = snipits.SubToggle;
 			tff_document.on( 'click', '#site-navigation .sub-toggle', trainify_subtoggle );

            var tabbed_widget = snipits.TabbedWidget;
            tff_document.on( 'click', '.tff-widget-tab a', tabbed_widget );
 		},

 		Ready: function(){

 			var __this = trainify;
 			var snipits = __this.Snipits;
            snipits.Variables();
 			__this.Events();
 			snipits.AppendData();
 			snipits.ScrollTop();
 			snipits.Sliders();
 		},

 		Load: function(){

            var __this = trainify;
            var snipits = __this.Snipits;
            snipits.Preloader();
            
 		},

 		Resize: function(){
 		},

 		Scroll: function(){
 			var __this = trainify;
 			var snipits = __this.Snipits;
 			snipits.VisibilityScroller();
 		},

 		Init: function(){

 			var __this = trainify;
 			var load, ready, resize, scroll;

 			ready = __this.Ready;
 			load = __this.Load;
 			resize = __this.Resize;
 			scroll = __this.Scroll;
 			
 			tff_document.ready(ready);
 			tff_window.load(load);
 			tff_window.resize(resize);
 			tff_window.scroll(scroll);

 		},

 	};


 	trainify.Init();

    
 } )( jQuery );