<?php
/* Prohibit direct script loading */
defined('ABSPATH') || die('No direct script access allowed!');

$pluginName = esc_html__('WP Meta SEO Pro', 'wpmsPro');
$logoTextFile = WPMETASEO_ADDON_PLUGIN_URL . 'assets/images/joomunited.svg';
$logoFile = WPMETASEO_ADDON_PLUGIN_URL . 'assets/images/joomunited-logo.svg';
$backUrl = '';
$tabs_data = array(
    array(
        'id'    => 'general',
        'title' => __('General', 'wpmsPro'),
        'icon'  => 'home',
        'desc' => __('Manage and activate essential SEO features.', 'wpmsPro'),
    )
);
$tabs_data[] = array(
    'id'    => 'local_business',
    'title' => __('Local business', 'wpmsPro'),
    'icon'  => 'account_circle',
    'desc' => __('Propose business local information to Google. When users search for businesses on Google Search or Maps, search results may display a prominent Google knowledge panel with details about a business that matched the query.', 'wpmsPro'),
);
$tabs_data[] = array(
    'id'    => 'redirections_404',
    'title' => __('404 & Redirect', 'wpmsPro'),
    'icon'  => 'directions',
    'desc' => __('404 error handling and redirect options.', 'wpmsPro'),
);
$tabs_data[] = array(
    'id'    => 'search_console',
    'title' => __('Google Search Console', 'wpmsPro'),
    'icon'  => 'extension',
    'desc' => __('Manage the Google Search Console connection here. It will help with getting Google search engine user queries detailed information. You can also use them in the page optimizer.', 'wpmsPro'),
    'link' => 'https://www.joomunited.com/wordpress-documentation/wp-meta-seo/684-wp-meta-seo-google-search-console',
    'link_desc' => __('Check the documentation to configure the connection >>', 'wpmsPro'),
);
$tabs_data[] = array(
    'id'    => 'breadcrumb',
    'title' => __('Breadcrumb', 'wpmsPro'),
    'icon'  => 'horizontal_split',
    'desc' => __("A breadcrumb trail on a page indicates the page's position in the site hierarchy, and it may help users understand and explore a site effectively.", 'wpmsPro'),
);
$tabs_data[] = array(
    'id'    => 'send_email',
    'title' => __('Send Email', 'wpmsPro'),
    'icon'  => 'email',
    'desc' => __('Optional. Used to send SEO report, if activated.', 'wpmsPro'),
);
$tabs_data[] = array(
    'id'    => 'social',
    'title' => __('Social', 'wpmsPro'),
    'icon'  => 'share',
    'desc' => __('Customize social networks appearance when a user shares a page from your website.', 'wpmsPro'),
);
$tabs_data[] = array(
    'id'       => 'image_compression',
    'title'    => __('Image compression', 'wpmsPro'),
    'icon'     => 'compare'
);
$tabs_data[] = array(
    'id'       => 'jutranslation',
    'title'    => __('Translation', 'wpmsPro'),
    'icon'     => 'format_color_text'
);
$tabs_data[] = array(
    'id' => 'system_license',
    'title' => __('System and License', 'wpmsPro'),
    'content' => 'system-license',
    'icon' => 'verified_user',
    'sub_tabs' => array(
        'system_check'      => __('System check', 'wpmsPro'),
        'account_license'   => __('Account license', 'wpmsPro')
    )
);
$setting_switch_fields = array(
    'metaseo_showkeywords'   => array(
        'label' => __('Meta keywords', 'wpmsPro'),
        'help'  => __('Active the meta keyword edition feature', 'wpmsPro'),
    ),
    'metaseo_metatitle_tab'  => array(
        'label' => __('Meta title as page title', 'wpmsPro'),
        'help'  => __('When meta title is filled use it as page title instead of the content title', 'wpmsPro'),
    ),
    'metaseo_showtmetablock' => array(
        'label' => __('Meta block edition', 'wpmsPro'),
        'help'  => __('Activate the OnPage analysis and meta edition below the content', 'wpmsPro'),
    ),
    'metaseo_linkfield'      => array(
        'label' => __('Link text field', 'wpmsPro'),
        'help'  => __('Add back the missing title field in the Insert/Edit URL box', 'wpmsPro'),
    ),
    'metaseo_seovalidate'    => array(
        'label' => __('Force SEO validation', 'wpmsPro'),
        'help'  => __('Allow user to force on page SEO criteria validation by clicking on the icon', 'wpmsPro'),
    ),
    'metaseo_index'          => array(
        'label' => __('Post/Page index', 'wpmsPro'),
        'help'  => __('Add an option to say to search engine: hey!
                 Do not index this content', 'wpmsPro'),
    ),
    'metaseo_follow'         => array(
        'label' => __('Post/Page follow', 'wpmsPro'),
        'help'  => __('Add an option to setup Follow/Nofollow instruction for each content', 'wpmsPro'),
    ),
    'metaseo_overridemeta'   => array(
        'label' => __('Use image information from bulk editor', 'wpmsPro'),
        'help'  => __('Override the image information (Alt text) with image bulk editor content', 'wpmsPro'),
    ),
    'metaseo_canonical'   => array(
        'label' => __('Canonical URL', 'wpmsPro'),
        'help'  => __('Add an option to force a canonical URL in each content. WordPress handles it by default but it can be useful in some 3rd party plugins.', 'wpmsPro'),
    ),
    'metaseo_removecatprefix'   => array(
        'label' => __('Remove category archive', 'wpmsPro'),
        'help'  => __('Remove category prefix (category/) in Category URLs', 'wpmsPro'),
    ),
    'metaseo_linkeditor'   => array(
        'label' => __('Link Editor', 'wpmsPro'),
        'help'  => __('Activate the link editor to edit link titles in your content for additional SEO performance', 'wpmsPro'),
    )
);
?>
<!-- Left panel -->
<div id="rdju-left-panel" class="flex bottom-0 top-8 flex-col justify-between pt-6 delay-250 transition-width bg-base-100 rdju-panel-menu bg-white"
  role="tablist" style="display: none; height: calc(100% - 32px); position: fixed; overflow: auto; z-index: 15; border-right: solid 1px #E6E8EC;">
  <div class="rdju-tablist" role="tablist">
    <!-- Panel Title (Visible when expanded) -->
    <div class="px-4 pb-2 flex flex-col rdju-logo-container">
        <h2 id="panel-title" class="!mb-0 !mt-2 !text-lg !font-bold !text-black">
          <?php echo $pluginName; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- It's already escaped ?>
        </h2>
        <img id="panel-logo" src="<?php echo $logoFile; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- No need ?>" alt="Joomunited Logo">
    </div>

    <!-- Back to previous -->
    <?php if ($backUrl) : ?>
    <a class="rdju-panel-link flex gap-x-2 items-center py-2 text-base font-semibold px-4 justify-start" href="/">
      <svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 0 24 24" width="20px" fill="#5f6368">
        <path d="M0 0h24v24H0V0z" fill="none" opacity=".87"/><path d="M17.51 3.87L15.73 2.1 5.84 12l9.9 9.9 1.77-1.77L9.38 12l8.13-8.13z"/>
      </svg>
      <span class="nav-text"><?php echo esc_html__('Back', 'wpmsPro'); ?></span>
    </a>
    <?php endif; ?>
    
    <div class="flex gap-x-2 items-center py-2 text-base font-medium justify-start rdju-menu-search-container">
        <svg class="h-[1.5em] rdju-menu-search-icon" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M14 16C12.3333 16 10.9167 15.4167 9.75 14.25C8.58333 13.0833 8 11.6667 8 10C8 8.33333 8.58333 6.91667 9.75 5.75C10.9167 4.58333 12.3333 4 14 4C15.6667 4 17.0833 4.58333 18.25 5.75C19.4167 6.91667 20 8.33333 20 10C20 11.6667 19.4167 13.0833 18.25 14.25C17.0833 15.4167 15.6667 16 14 16ZM14 18C16.2333 18 18.125 17.225 19.675 15.675C21.225 14.125 22 12.2333 22 10C22 7.76667 21.225 5.875 19.675 4.325C18.125 2.775 16.2333 2 14 2C11.7667 2 9.875 2.775 8.325 4.325C6.775 5.875 6 7.76667 6 10C6 10.9333 6.14567 11.8127 6.437 12.638C6.72833 13.4633 7.141 14.2173 7.675 14.9L2 20.6L3.4 22L9.1 16.325C9.78333 16.8583 10.5373 17.271 11.362 17.563C12.1867 17.855 13.066 18.0007 14 18Z" fill="#777886"/>
        </svg>
        <label class="rdju-input rdju-input-group rdju-menu-search gap-0">
          <svg class="h-[1.5em]" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M14 16C12.3333 16 10.9167 15.4167 9.75 14.25C8.58333 13.0833 8 11.6667 8 10C8 8.33333 8.58333 6.91667 9.75 5.75C10.9167 4.58333 12.3333 4 14 4C15.6667 4 17.0833 4.58333 18.25 5.75C19.4167 6.91667 20 8.33333 20 10C20 11.6667 19.4167 13.0833 18.25 14.25C17.0833 15.4167 15.6667 16 14 16ZM14 18C16.2333 18 18.125 17.225 19.675 15.675C21.225 14.125 22 12.2333 22 10C22 7.76667 21.225 5.875 19.675 4.325C18.125 2.775 16.2333 2 14 2C11.7667 2 9.875 2.775 8.325 4.325C6.775 5.875 6 7.76667 6 10C6 10.9333 6.14567 11.8127 6.437 12.638C6.72833 13.4633 7.141 14.2173 7.675 14.9L2 20.6L3.4 22L9.1 16.325C9.78333 16.8583 10.5373 17.271 11.362 17.563C12.1867 17.855 13.066 18.0007 14 18Z" fill="#777886"/>
            </svg>
          <input type="text" class="grow ju-menu-search-input" placeholder="<?php esc_attr_e('Search settings', 'wpmsPro') ?>" />
        </label>
    </div>

    <!-- Menu Items -->
    <?php foreach ($tabs_data as $panel_menu) : ?>
        <?php $has_sub_tabs = !empty($panel_menu['sub_tabs']); ?>
        <div class="rdju-menu-panel-container<?php echo $has_sub_tabs ? ' has-submenu' : ''; ?>">  
            <a class="rdju-panel-link flex gap-x-2 items-center py-2 text-base font-medium px-4 justify-between"
                href="#<?php echo esc_attr($panel_menu['id']); ?>">
                <div class="flex gap-x-2 justify-start items-center">
                    <i class="rdju-tab-icon material-icons menu-tab-icon"><?php echo esc_html($panel_menu['icon']) ?></i>
                    <span class="nav-text">
                        <?php echo esc_html($panel_menu['title']); ?>
                    </span>
                </div>
                <?php if ($has_sub_tabs) : ?>
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M5.69995 10L11.7 16L17.7 10L16.3 8.6L11.7 13.2L7.09995 8.6L5.69995 10Z" fill="#777886"/>
                    </svg>
                <?php endif; ?>
            </a>
            <?php if ($has_sub_tabs) : ?>
                <div class="rdju-sub-panel-container">
                    <div class="rdju-sub-panel-links">
                        <?php foreach ($panel_menu['sub_tabs'] as $sub_tab_id => $sub_tab_title) : ?>
                            <a class="rdju-sub-panel-link" href="#<?php echo esc_attr($sub_tab_id); ?>">
                                <?php echo esc_html($sub_tab_title); ?>
                                </a>
                        <?php endforeach; ?>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    <?php endforeach; ?>
</div>
  
<!-- Collapse Button -->
<div class="mb-3">
    <div class="mb-0 mt-2 rdju-divider"></div>
        <button id="toggle-collapse" class="rdju-panel-link flex gap-x-2 items-center py-3 w-full text-base font-medium px-5 justify-start">
            <svg class="collapse-icon" width="20" height="20" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">
              <path d="M8.93331 2.40008L2.33331 9.00008L8.93331 15.6001L10.1083 14.4167L5.52498 9.83341H17.3333V8.16675H5.52498L10.1083 3.58341L8.93331 2.40008ZM2.33331 9.00008V17.3334H0.666647V0.666748H2.33331V9.00008Z" fill="#5F6368"/>
            </svg>
            <span class="nav-text font-medium text-base"><?php echo esc_html__('Collapse', 'wpmsPro'); ?></span>
        </button>
    </div>
</div>

<!-- Content Section -->
<div id="rdju-content-area">
    <!-- Subpages Container -->
    <form method="post" actions="" id="rdju-settings-form">
        <?php
        // Load all sub-pages inside the form
        foreach ($tabs_data as $panel_menu) {
            $has_sub_tabs = !empty($panel_menu['sub_tabs']);
            $file_path = WPMETASEO_ADDON_PLUGIN_DIR . '/inc/pages/settings/' . $panel_menu['id'] . '.php';
            if (file_exists($file_path)) {
                echo '<div id="' . esc_attr($panel_menu['id']) . '" class="rdju-sub-page" style="display: none;">';
                ?>
                <?php if (!$has_sub_tabs) : ?>
                <div class="px-10 py-5">
                    <h1 class="rdju-subpage-title !mb-2"><?php echo esc_html($panel_menu['title']) ?></h1>
                    <?php if (isset($panel_menu['desc'])) : ?>
                        <p class="rdju-subpage-desc !mt-2 <?php echo (isset($panel_menu['link']) && $panel_menu['link']) ? 'mb-1' : '' ; ?>"><?php echo esc_html($panel_menu['desc']) ?></p>
                    <?php endif; ?>
                    <?php if (isset($panel_menu['link']) && $panel_menu['link']) : ?>
                        <a class="!text-base font-semibold wpms-text-blue mt-2 mb-4 rdju-subpage-link" target="__blank" href="<?php echo esc_attr($panel_menu['link']); ?>" ><?php echo esc_html($panel_menu['link_desc']); ?></a>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
                <?php
                include_once($file_path);
                echo '</div>';
            }
        }
        ?>
        <!-- Submit Button -->
<!--
        <div class="rdju-form-footer">
            <?php submit_button(); ?>
        </div>
-->
    </form>
</div>

<script>
(function ($) {
    $(document).ready(function() {
        let hasUnsavedChanges = false;
        let leftPanelCollapsed = false;
        let nextPage = "";
        let trainingMenuVisible = false;
        const collapseSvg = '<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M8.93331 2.40008L2.33331 9.00008L8.93331 15.6001L10.1083 14.4167L5.52498 9.83341H17.3333V8.16675H5.52498L10.1083 3.58341L8.93331 2.40008ZM2.33331 9.00008V17.3334H0.666647V0.666748H2.33331V9.00008Z" fill="#5F6368"/></svg>';
        const expandSvg = '<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.06666 2.40008L15.6667 9.00008L9.06666 15.6001L7.89166 14.4167L12.475 9.83341H0.666656V8.16675H12.475L7.89166 3.58341L9.06666 2.40008ZM15.6667 9.00008V17.3334H17.3333V0.666748H15.6667V9.00008Z" fill="#5F6368"/></svg>';
        let collapseToggle = ''
        const juTextLogo = "<?php echo $logoTextFile; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- It's already escaped ?>"
        const juLogo = "<?php echo $logoFile; //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- It's already escaped ?>"
    
        // Initialize panel
        function initPanel() {
            const width = $(window).width();
            leftPanelCollapsed = width < 1280;
            checkCollapseState();
            updatePanelLayout();
            $('#rdju-left-panel').show();
            if ($('#rdju-left-panel')[0]) {
                hasScrollbar($('#rdju-left-panel')[0]);
            }

            var currentHash = showCurrentPage();
            var panelMenu = $('.rdju-tablist .rdju-panel-link[href=#' + currentHash + ']:not(#toggle-collapse)');
            if (panelMenu.length) {
                panelMenu.click();
            }
        }
      
        function hasScrollbar(element) {
            hasScroll = element.scrollHeight > element.clientHeight;
            if (hasScroll) {
                $(element).addClass('rdju-has-scroll');
            } else {
                $(element).removeClass('rdju-has-scroll');
            }
        }
        
        function checkCollapseState() {
            if (leftPanelCollapsed) {
                collapseToggle = expandSvg;
                $('#panel-title').hide();
                $('#panel-logo').attr("src", juLogo);
                $('#panel-logo').addClass("!mt-2");
                $('#rdju-content-area').addClass("rdju-content-area-collapsed");
                $('.rdju-logo-container').addClass("items-center");
            } else {
                collapseToggle = collapseSvg;
                $('#panel-title').show();
                $('#panel-logo').attr("src", juTextLogo);
                $('#panel-logo').removeClass("!mt-2");
                $('#rdju-content-area').removeClass("rdju-content-area-collapsed");
                $('.rdju-logo-container').removeClass("items-center");
            }
            $('#toggle-collapse svg.collapse-icon').html(collapseToggle)
        }
    
        // Update panel layout
        function updatePanelLayout() {
            const panel = $('#rdju-left-panel');
            panel.toggleClass('rdju-collapsed', leftPanelCollapsed);
            $('.nav-text, .rdju-dropdown-icon').toggle(!leftPanelCollapsed);

            if (!panel.hasClass('rdju-collapsed')) {
                const activeMenu = $('.rdju-menu-panel-container.has-submenu');
                if (activeMenu.length) {
                    activeMenu.find('.rdju-sub-panel-container').removeAttr('style');
                }
            }
        }
      
        function navigateTo(path) {
            window.history.pushState({}, '', path);
            // Add your page content loading logic here
        }
    
        // Function to show the appropriate sub-page based on the hash
        function showCurrentPage() {
            var hash = window.location.hash.substring(1); // Remove the '#'
            if (!hash) {
                hash = 'general'; // Default to 'general' if no hash is present
            }

            // Hide all sub-pages
            $('.rdju-sub-page, .ju-sub-tab-content').hide();

            // Show the current sub-page
            $('#' + hash).show();
            $('#' + hash).closest('.rdju-sub-page').show();

            $('.rdju-menu-panel-container').removeClass('rdju-menu-panel-active');

            var subLink = $(`.rdju-sub-panel-container a[href="#${hash}"]`);
            if (subLink.length) {
                subLink.closest('.rdju-menu-panel-container').addClass('rdju-menu-panel-active');
                subLink.closest('.rdju-menu-panel-container').find('.rdju-panel-link').addClass('rdju-menu-active');
                subLink.addClass('rdju-menu-active');

                return hash;
            }

            var mainLink = $(`.rdju-menu-panel-container:not(.has-submenu) > a[href="#${hash}"]`);
            if (mainLink.length) {
                mainLink.closest('.rdju-menu-panel-container').addClass('rdju-menu-panel-active');
                mainLink.addClass('rdju-menu-active');

                return hash;
            }
            
            return hash;
        }
    
        // Navigation handling
        $('.rdju-panel-link, .rdju-dropdown-submenu a, .rdju-sub-panel-link').on('click', function(e) {
            e.preventDefault();

            if ($(this).is('#toggle-collapse')) {
                return;
            }

            $('.rdju-menu-active').removeClass('rdju-menu-active');
            $(this).addClass('rdju-menu-active');
            $('.rdju-menu-panel-container').removeClass('rdju-menu-panel-active');
            $(this).closest('.rdju-menu-panel-container').addClass('rdju-menu-panel-active');

            if ($(this).hasClass('rdju-panel-link') && $(this).closest('.rdju-menu-panel-container').hasClass('has-submenu')) {
                var item = $(this).closest('.rdju-menu-panel-container');
                var firstSubLink = item.find('.rdju-sub-panel-container .rdju-sub-panel-link:first-child');
                var target = firstSubLink.attr('href');
                firstSubLink.addClass('rdju-menu-active');
            } else {
                var target = $(this).attr('href');
            }

            navigateTo(target);
        });
      
      
        $('#rdju-left-panel').on('click', '.rdju-menu-search-container', function (){
            if ($('#rdju-left-panel.rdju-collapsed').length > 0) {
                $('#rdju-left-panel').removeClass('rdju-collapsed');
                $('#toggle-collapse').click();
            }
            $('.ju-menu-search-input').focus();
        });
        
        // Function for searching menus
        $('.ju-menu-search-input').on('input', function () {
            //~ $('.ju-right-panel .ju-settings-option').removeClass('search-result');
            $('.rdju-tablist .rdju-panel-link').show();

            var searchKey = $(this).val().trim().toLowerCase();
            if (searchKey === '') {
                $('.rdju-tablist .rdju-panel-link').show();
                return false;
            }

            $('.rdju-tablist .rdju-panel-link:not(#toggle-collapse)').each(function () {
                var href = $(this).attr('href');
                var text = $(this).text().trim().toLowerCase();
                var dataHref = $(this).data('href');

                if (href !== undefined) {
                    href = href.replace(/#/g, '');
                }

                if (dataHref !== undefined) {
                    dataHref = dataHref.replace(/#/, '');
                }

                if (text.indexOf(searchKey) < 0 && href.indexOf(dataHref) < 0) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
        });
    
        // Collapse toggle
        $('#toggle-collapse').click(() => {
            leftPanelCollapsed = !leftPanelCollapsed;
            updatePanelLayout();
            checkCollapseState();
        });
    
        // Training menu hover
        $('div.rdju-dropdown-panel:has(.rdju-dropdown-toggle)').mouseover(
            () => leftPanelCollapsed && $('.rdju-dropdown-hover').stop().slideDown(200)
        );
        $('div.rdju-dropdown-panel:has(.rdju-dropdown-toggle)').mouseout(
            () => leftPanelCollapsed && $('.rdju-dropdown-hover').stop().slideUp(200)
        );
      
        // Listen for hash changes
        $(window).on('hashchange', function() {
            showCurrentPage();
        });
      
        // Handle clicks on the sidebar links
        $('.rdju-panel-link:not(#toggle-collapse), .rdju-sub-panel-link').on('click', function(e) {
            e.preventDefault(); // Prevent default anchor behavior
            if ($(this).hasClass('rdju-panel-link') && $(this).closest('.rdju-menu-panel-container').hasClass('has-submenu')) {
                var item = $(this).closest('.rdju-menu-panel-container');
                var firstSubLink = item.find('.rdju-sub-panel-container .rdju-sub-panel-link:first-child');
                var subPage = firstSubLink.attr('href').substring(1);
            } else {
                var subPage = $(this).attr('href').substring(1); // Remove the '#' to get the ID
            }
            window.location.hash = subPage; // Update the hash
            // Force hashchange event if needed
            $(window).trigger('hashchange');
        });

        $('.rdju-menu-panel-container.has-submenu').hover(function () {
            var wrapper = $('#rdju-left-panel');
            if (!wrapper.hasClass('rdju-collapsed')) return;

            var item = $(this);
            var itemWidth = item.outerWidth();
            var itemHeight = item.outerHeight();
            var itemOffset = item.offset();
            var itemRect = item[0].getBoundingClientRect();
            var submenu = item.find('.rdju-sub-panel-container');

            submenu.css({ display: 'block', visibility: 'hidden' });

            var submenuHeight = submenu.outerHeight();
            var windowHeight = window.innerHeight;

            submenu.css({ display: 'none', visibility: '', top: '', bottom: '' });

            var cssProps = {
                display: 'block',
                left: itemOffset.left + itemWidth + 'px'
            };

            if (itemRect.bottom + submenuHeight > windowHeight) {
                var distanceFromBottom = windowHeight - itemRect.bottom;
                cssProps.bottom = distanceFromBottom + 'px';
            } else {
                cssProps.top = item.position().top + itemHeight - 12 + 'px';
            }

            submenu.css(cssProps);
        }, function () {
            var wrapper = $('#rdju-left-panel');
            if (!wrapper.hasClass('rdju-collapsed')) return;

            var submenu = $(this).find('.rdju-sub-panel-container');

            submenu.hide().css({ top: '', bottom: '' });
        });

        // Window resize handler
        $(window).resize(initPanel);
        initPanel();

        $('.wpms_save_settings404').on('click', function () {
            var home_redirected = $('.wpms_redirect_homepage').val();
            var type_404 = $('.wpms_type_404').val();
            var page_redirected = $('.wpms_page_redirected').val();

            if ($('#scanlinkenable').is(":checked")) {
                var enable = 1;
            } else {
                enable = 0;
            }

            if ($('#wpms_redirect_homepage').is(":checked")) {
                home_redirected = 1;
            }

            $.ajax({
                url: ajaxurl,
                method: 'POST',
                dataType: 'json',
                data: {
                    'action': 'wpms',
                    'task': 'save_settings404',
                    'wpms_redirect[wpms_redirect_homepage]': home_redirected,
                    'wpms_redirect[wpms_type_404]': type_404,
                    'wpms_redirect[wpms_page_redirected]': page_redirected,
                    'enable': enable,
                    'numberFrequency': $('#numberFrequency').val(),
                    'showlinkFrequency': $('#showlinkFrequency').val(),
                    'wpms_nonce': wpms_localize.wpms_nonce
                },
                success: function (res) {
                    if (res) {
                        $('.message_saved').fadeIn(10).delay(2000).fadeOut(2000);
                    } else {
                        alert('Save errors !')
                    }
                }
            });
        });

        $('.wpms_type_404').on('change', function () {
            var type_404 = $(this).val();
            if (type_404 === 'wp-meta-seo-page' || type_404 === 'none') {
                $('.wpms_page_redirected').prop('disabled', true);
            } else if (type_404 === 'custom_page') {
                $('.wpms_page_redirected').prop('disabled', false);
            }
        });

        $('.cb_option').off('click').on('click', function () {
            var check = $(this).attr('checked');
            var type = $(this).attr('type');
            var value;
            if (type === 'checkbox') {
                if (check === 'checked') {
                    value = 1;
                } else {
                    value = 0;
                }
                $('input[name="wpms_redirect[' + $(this).data('label') + ']"]').val(value);

                if ($(this).data('label') === 'wpms_redirect_homepage') {
                    if (check === 'checked') {
                        $('.wpms_type_404,.wpms_page_redirected').prop('disabled', true);
                    } else {
                        $('.wpms_type_404,.wpms_page_redirected').prop('disabled', false);
                    }
                }
            }
        });

        $('.wpms_save_settings_breadcrumb').on('click', function () {
            var separator = $('#breadcrumbs_separator').val();
            var home_text = $('#breadcrumbs_home_text').val();
            if ($('#include_home').is(":checked")) {
                var include_home = 1;
            } else {
                include_home = 0;
            }

            if ($('#clickable').is(":checked")) {
                var clickable = 1;
            } else {
                clickable = 0;
            }

            if ($('#home_text_default').is(":checked")) {
                var home_text_default = 1;
            } else {
                home_text_default = 0;
            }

            $.ajax({
                url: ajaxurl,
                method: 'POST',
                dataType: 'json',
                data: {
                    'action': 'wpms',
                    'task': 'save_settings_breadcrumb',
                    'separator': separator,
                    'home_text': home_text,
                    'include_home': include_home,
                    'clickable': clickable,
                    'home_text_default': home_text_default,
                    'wpms_nonce': wpms_localize.wpms_nonce
                },
                success: function (res) {
                    if (res) {
                        $('.message_saved').fadeIn(10).delay(2000).fadeOut(2000);
                    } else {
                        alert('Save errors !')
                    }
                }
            });
        });

        $('.wpms_save_settingemail').on('click', function () {
            if ($('#showSmtpenable').is(":checked")) {
                var enable = 1;
            } else {
                enable = 0;
            }

            if ($('#showautentication').is(":checked")) {
                var showautentication = 'yes';
            } else {
                showautentication = 'no';
            }


            var $this = $(this);
            $.ajax({
                url: ajaxurl,
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'wpms_save_settingemail',
                    enable: enable,
                    host: $('#showSmtpHost').val(),
                    type_encryption: $('[name="wpms_email_settings[type_encryption]"]:checked').val(),
                    port: $('#showSmtpPort').val(),
                    autentication: showautentication,
                    username: $('#showSmtpUser').val(),
                    password: $('#showSmtpPass').val(),
                    wpms_nonce: wpms_localize.wpms_nonce
                },
                success: function (res) {
                    if (res) {
                        $this.closest('.content-box').find('.message_saved').fadeIn(10).delay(2000).fadeOut(2000);
                    } else {
                        alert('Save errors !')
                    }
                }
            });
        });

        $('.wpms_local_business').on('click', function () {
            if ($('#local_business_enable').is(":checked")) {
                var enable = 1;
            } else {
                enable = 0;
            }
            $this = $(this);
            $.ajax({
                url: ajaxurl,
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'wpms_save_local_business',
                    enable: enable,
                    logo: $('#wpms_local_business_logo').val(),
                    type_name: $('#wpms_local_business_type_name').val(),
                    country: $('#wpms_local_business_country').val(),
                    address: $('#wpms_local_business_address').val(),
                    city: $('#wpms_local_business_city').val(),
                    state: $('#wpms_local_business_state').val(),
                    phone: $('#wpms_local_business_phone').val(),
                    pricerange: $('#wpms_local_business_pricerange').val(),
                    wpms_nonce: wpms_localize.wpms_nonce
                },
                success: function (res) {
                    if (res) {
                        $this.closest('.content-box').find('.message_saved').fadeIn(10).delay(2000).fadeOut(2000);
                    } else {
                        alert('Save errors !')
                    }
                }
            });
        });

        $(".wpms-seoImgAdd").on("click", function () {
            var file_frame,
                $this = $('.local-business-bar');
            if (undefined !== file_frame) {
                file_frame.open();
                return;
            }
            file_frame = wp.media.frames.file_frame = wp.media({
                title: 'Select or Upload Media For your profile gallery',
                button: {
                    text: 'Use this media'
                },
                multiple: false
            });
            file_frame.on('select', function () {
                var attachment = file_frame.state().get('selection').first().toJSON(),
                    imgId = attachment.id;
                if (typeof attachment.sizes.thumbnail === "undefined") {
                    imgUrl = attachment.url;
                } else {
                    imgUrl = attachment.sizes.thumbnail.url;
                }
                var imgInfo = "<span><strong>URL: </strong>" + attachment.sizes.full.url + "</span>";
                imgInfo = imgInfo + "<span><strong>Width: </strong>" + attachment.sizes.full.width + "px</span>";
                imgInfo = imgInfo + "<span><strong>Height: </strong>" + attachment.sizes.full.height + "px</span>";
                $this.find('#wpms_local_business_logo').val(imgId);
                $this.find('.wpms-seoImgRemove').removeClass('wpms-seo-hidden');
                $this.find('img').remove();
                $this.find('.wpms-seo-image-preview').html("<img src='" + imgUrl + "' />");
                $this.parents('.wpms-seo-image').find('.image-info').html(imgInfo);
            });
            // Now display the actual file_frame
            file_frame.open();
        });

        $(".wpms-seoImgRemove").on("click", function (e) {
            e.preventDefault();
            if (confirm("Are you sure?")) {
                var $this = $('.local-business-bar');
                $this.find('input').val('');
                $this.find('.wpms-seoImgRemove').addClass('wpms-seo-hidden');
                $this.find('.wpms-seo-image-preview').html('<i class="material-icons business-img-default">photo</i>');
                $this.parents('.wpms-seo-image').find('.image-info').html('');
            }
        });
    });
}(jQuery));
</script>
