(function($) {
    "use strict";

    // INIT LAZY LOAD
    lazyLoad();
    function lazyLoad() {
        $('.lazy, .supporter-avatar').Lazy({
            effect: 'fadeIn',
            onFinishedAll: function() {
                $('.lazy').removeClass('lazy')
            }
        });

        $('.feature-post-lazy').lazy({
            effect: 'fadeIn',
            onFinishedAll: function() {
                $('.feature-post-lazy').removeClass('feature-post-lazy')
            },
            delay: 600
        });
    }

    // AUTO LOAD NEXT POST
    $('body').on( 'alnp-post-loaded', function( e, params ) {
        lazyLoad();
        initCarousel();
        initDimmer();
        initPopup();
        phoneCodeDropdown();
        stickyInitAll();
        progressBarInit();
        accordionInit();
        modalInit();
        checkboxInit();
        citationLabelInit();
        changeCloseIcon();
        signSidebarInit();
        dropdownInit();
        supporterCounterAnimation();
        initCounterAnimation();
        updatePhoneFormat('phoneSign');
    });

    // BJAX INIT
    if (main_vars.ajax_pages == 1) {
        $(document).on('click', '[data-bjax]', function(e) {
            new Bjax(this);
            $('.bjax-backdrop').append('<div class="bjax-loading-wrapper">' + main_vars.html_preloader + '</div>');
            $('html,body').animate({
                scrollTop: $('html,body').offset().top - 120
            }, 300);
            e.preventDefault();
        });
    }

    // GUTENBERG BLOCKS
    // Run when a document ready on the front end.
    // $( document ).ready( initCarousel );
    function loadBlockPreview() {
        initCarousel();
        lazyLoad();
        initDimmer();
        progressBarInit();
        initCounterAnimation();
    }

    // Run when a block preview is done loading.
    $( document ).on( 'mb_blocks_preview/sign-share', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/blog-posts', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/petitions', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/fundraising', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/supporters-list', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/progressive-bar', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/supporters-counter', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/team_members', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/testimonials', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/update-timeline', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/victory-slider', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/icon-box', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/comments-list', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/category-grid', loadBlockPreview );
    $( document ).on( 'mb_blocks_preview/promo-banner', loadBlockPreview );

    // DIMMER
    initDimmer();
    function initDimmer() {
        $('.blogs.post .image, .team, .petition-list-card .ui.image, .petition-card .image, .post-card .image, .list-post-thumbnail .image, .give-level, .product-card .image')
        .dimmer({
            on: 'hover'
        });
    }

    // EMBED VIDEO
    $('.promo-video').embed();

     // HEADER PROMO
     $('.close-promo').on('click', function() {
        $('.header-promo').transition('slide down')
        setCookie('conikal_close_promo', 1, (main_vars.close_promo_time == 'session' ? '' : (parseInt(main_vars.close_promo_time) * 60 * 24)))
     });

    // POPUP
    initPopup();
    function initPopup() {
        $('#share-message').popup();
        $('.social-share .button, .social-share .item, .supporter-avatar, .contributer-avatar, .withdraw-notes, .fee-note, .status-label, .withdraw-notes, .bookmark-popup').popup();
        $('.cart-contents').popup({
            inline     : true,
            hoverable  : true,
            position   : 'bottom right',
        });    
        $('.admin-settings-btn, .petition-settings, .post-more-categories').popup({
            variation   : 'very wide',
            position    : 'bottom left',
            popup       : $('.admin-settings.popup, .petition-settings.popup, .more-categories.popup'),
            on          : 'click'
        });
    }

    $('.searchBtn, .searchBtnMobile').on('click', function() {
        $('.search-menu').removeClass('display none').addClass('display block').css('top', $('.header-promo-segment').height());
        $('#leftside-menu').sidebar('hide')
        $('#search-input').focus()
    });

    $('#closeSearch').on('click', function() {
        $('.search-menu').removeClass('display block').addClass('display none')
    });

    // TYPE USER BUTTON
    $('.typeUser').on('click', function() {
        var typeUser = $("input[name='typeUser']:checked").val();
        if ( typeUser == 'decisioner' ) {
            $('#decision-fields').removeClass('none').addClass('flex')
        } else {
            $('#decision-fields').removeClass('flex').addClass('none')
        }

        if ( typeUser == 'organization' ) {
            $('#organization-fields').removeClass('none').addClass('block')
        } else {
            $('#organization-fields').removeClass('block').addClass('none')
        }
    });

    // DROPDOWN MENU
    $(document).ready(function() {
        $('.gt_selector, .notranslate, #lang_choice_polylang-2').addClass('ui tiny dropdown gtranslate-dropdown');
        $('.gt_selector, .notranslate, #lang_choice_polylang-2').dropdown();
        $('#flaggedc_reason, #wpas_department, #wpas_product').addClass('ui fluid dropdown');
    });
    
    dropdownInit();
    function dropdownInit() {
        $('.edit-update, .edit-citation, .profile-menu-dropdown, .more-share, #search_topics, select.dropdown, .give-type-button, .search-category, .woocommerce-filter-dropdown, .export-signature-btn, .country-search, .search-order, .search-orderby, .acf-input > select, .widget_polylang, .woocommerce div.product form.cart .variations select, .wp-block-archives select, .wp-block-categories select, .widget select, .wc-block-sort-select__select').dropdown();
        $('.user-menu, .header-submenu, .more-share, .nav-submenu, .supporter-chart-date, .visitor-chart-date, .petition-order, .petition-orderby').dropdown({on: 'hover'});

        $('.footer-nav-submenu').dropdown({
            on: 'hover',
            direction: 'upward',
        });
    }

    // RATING STAR
    $('.review-rating, .average-rating, .product-star-rating').each(function() {
        $(this).rating('disable', true);
    });

    // SUPPORTER COUNTER ANIMATION
    initCounterAnimation();
    function initCounterAnimation() {
        supporterCounterAnimation('fav_no');
        supporterCounterAnimation('ned_no');
        supporterCounterAnimation('sc_fav_no');
        supporterCounterAnimation('sc_ned_no');
    }

    function supporterCounterAnimation(classes) {
        if (main_vars.is_mobile == 'false' && parseInt(main_vars.supporter_counter_animation) != 0) {
            $('.' + classes).each(function () {
                var petition_id = $(this).attr('data-id');
                var count = $(this).data('value');
                $(this).prop('Counter',0).animate({
                    Counter: parseInt(count)
                }, {
                    duration: parseInt(main_vars.supporter_counter_animation),
                    easing: 'swing',
                    step: function (now) {
                        $(this).text(Math.ceil(now));
                    }
                });

                setTimeout(function() { 
                    $('#' + classes + petition_id).text($('#' + classes + petition_id).data('format'))
                }, parseInt(main_vars.supporter_counter_animation) + 300);
            });
        }
    }

    // FORMAT PHONE NUMBER
    function formatPhoneNumber(phoneNumberString) {
        var cleaned = ('' + phoneNumberString).replace(/\D/g, '');
        var match = cleaned.match(/^(0|)?(\d{3})(\d{3})(\d{4})$/);
        if (match) {
            var intlCode = (match[1] ? '' : '');
            return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('');
        }
        return null;
    }

    updatePhoneText('.author-phone-number', 'text');
    updatePhoneText('.phoneUser', 'input');
    function updatePhoneText(classes, ele_type = 'text') {
        if ($(classes).length > 0) {
            if (ele_type == 'text') {
                var phoneNumber = $(classes).text();
            } else {
                var phoneNumber = $(classes).val();
            }
            
            var formatNumber = formatPhoneNumber(phoneNumber);
    
            if (formatNumber != null) {
                if (ele_type == 'text') {
                    $(classes).text(formatNumber);
                } else {
                    $(classes).val(formatNumber);
                }
            }
        }
    }

    updatePhoneFormat('phoneSign');
    updatePhoneFormat('phoneUser');
    function updatePhoneFormat(classes) {
        $(document).on('change paste keyup', '.' + classes, function() {
            var petition_id = $(this).data('id');
            var phoneNumber = $('#' + classes + petition_id).val();
            var formatNumber = formatPhoneNumber(phoneNumber);
    
            if (formatNumber != null) {
                $('#' + classes + petition_id).replaceWith($('#' + classes + petition_id).clone().attr('type', 'text'));
                $('#' + classes + petition_id).val(formatNumber).focus();
            }
        });
    }

    // UPDATE MAIL SHARING CONTENT
    updateCustomMailContent('sign-comment');
    function updateCustomMailContent(classes) {
        $(document).on('change paste keyup', '.' + classes, function() {
            var petition_id     = $(this).data('id');
            var share_message   = $(this).val();

            // create custom sharing mail
            var primary_element_mail = $('#mail-primary-button' + petition_id + ', #mail-primary-buttonSC' + petition_id + ', #mail-primary-buttonSidebar' + petition_id);
            var secondary_element_mail = $('#mail-share-button' + petition_id + ', #mail-share-buttonSC' + petition_id + ', #mail-share-buttonSidebar' + petition_id);

            if ($('#mail-primary-button' + petition_id).length) {
                var mail_button = primary_element_mail;
            } else {
                var mail_button = secondary_element_mail;
            }
            var subject         = mail_button.data('subject');
            var custom_mail     = mail_button.data('custom');
            var default_mail    = mail_button.data('mail');

            if (share_message != '') {
                var new_mail        = custom_mail.replace('{message}', share_message);
                var new_mail_url    = 'mailto://?subject=' + subject + '&body=' + new_mail;
            } else {
                var new_mail_url    = 'mailto://?subject=' + subject + '&body=' + default_mail;
            }
            // update new custom mail to url
            primary_element_mail.attr('href', new_mail_url);
            secondary_element_mail.attr('href', new_mail_url);

            // create custom tweet
            var primary_element_twitter     = $('#twitter-primary-button' + petition_id + ', #twitter-primary-buttonSC' + petition_id + ', #twitter-primary-buttonSidebar' + petition_id);
            var secondary_element_twitter   = $('#twitter-share-button' + petition_id + ', #twitter-share-buttonSC' + petition_id + ', #twitter-share-buttonSidebar' + petition_id);

            if ($('#twitter-primary-button' + petition_id).length) {
                var twtitter_button = primary_element_twitter;
            } else {
                var twtitter_button = secondary_element_twitter;
            }

            var petition_title    = twtitter_button.data('heading');
            var petition_link     = twtitter_button.data('link');

            if (share_message != '') {
                var new_twitter_url    = '//twitter.com/share?url=' + petition_link + '&text=' + share_message;
            } else {
                var new_twitter_url    = '//twitter.com/share?url=' + petition_link + '&text=' + petition_title;
            }

            // update new custom mail to url
            primary_element_twitter.attr('href', new_twitter_url);
            secondary_element_twitter.attr('href', new_twitter_url);

            // create custom tweet
            var primary_element_gmail = $('#gmail-primary-button' + petition_id + ', #gmail-primary-buttonSC' + petition_id + ', #gmail-primary-buttonSidebar' + petition_id);
            var secondary_element_gmail = $('#gmail-share-button' + petition_id + ', #gmail-share-buttonSC' + petition_id + ', #gmail-share-buttonSidebar' + petition_id);
            
            if (primary_element_gmail.length) {
                var gmail_button = primary_element_gmail;
            } else {
                var gmail_button = secondary_element_gmail;
            }

            var gmail_subject         = gmail_button.data('subject');
            var gmail_custom_mail     = gmail_button.data('custom');
            var gmail_default_mail    = gmail_button.data('mail');

            if (share_message != '') {
                var new_gmail        = gmail_custom_mail.replace('{message}', share_message);
                var new_gmail_url    = 'https://mail.google.com/mail/u/0/?to&su=' + gmail_subject + '&body=' + new_gmail + '&bcc&cc&fs=1&tf=cm';
                
            } else {
                var new_gmail_url    = 'https://mail.google.com/mail/u/0/?to&su=' + gmail_subject + '&body=' + gmail_default_mail + '&bcc&cc&fs=1&tf=cm';
            }

            // update new custom gmail to url
            primary_element_gmail.attr('href', new_gmail_url);
            secondary_element_gmail.attr('href', new_gmail_url);
        });
    }

    // NOTIFICATION TOAST
    var toast_settings = $.parseJSON(main_vars.toast);
    
    $('#toast-email-verify').toast({
        transition: {
          showMethod   : toast_settings.transition.showMethod,
          showDuration : toast_settings.transition.showDuration - 300,
          hideMethod   : toast_settings.transition.hideMethod,
          hideDuration : toast_settings.transition.hideDuration,
          closeEasing  : toast_settings.transition.closeEasing
        },
        position: toast_settings.position,
        displayTime: 0,
        closeIcon: true,
        newestOnTop: toast_settings.newestOnTop,
        compact: toast_settings.compact,
        onDeny    : function(){
            setCookie('conikal_toast_remind_email_verify', '1', toast_settings.remind)
        },
    });

    $('#toast-petition-signed').toast({
        transition: {
          showMethod   : toast_settings.transition.showMethod,
          showDuration : toast_settings.transition.showDuration - 300,
          hideMethod   : toast_settings.transition.hideMethod,
          hideDuration : toast_settings.transition.hideDuration,
          closeEasing  : toast_settings.transition.closeEasing
        },
        position: toast_settings.position,
        displayTime: 0,
        closeIcon: true,
        newestOnTop: toast_settings.newestOnTop,
        compact: toast_settings.compact,
    });

    $('#toast-update-profile').toast({
        transition: {
          showMethod   : toast_settings.transition.showMethod,
          showDuration : toast_settings.transition.showDuration - 150,
          hideMethod   : toast_settings.transition.hideMethod,
          hideDuration : toast_settings.transition.hideDuration,
          closeEasing  : toast_settings.transition.closeEasing
        },
        position: toast_settings.position,
        displayTime: 0,
        closeIcon: true,
        newestOnTop: toast_settings.newestOnTop,
        compact: toast_settings.compact,
        onDeny    : function(){
            setCookie('conikal_toast_remind_update_profile', '1', toast_settings.remind)
        },
        onApprove : function() {
            return false;
        }
    });

    $('#toast-set-password').toast({
        transition: {
          showMethod   : toast_settings.transition.showMethod,
          showDuration : toast_settings.transition.showDuration,
          hideMethod   : toast_settings.transition.hideMethod,
          hideDuration : toast_settings.transition.hideDuration,
          closeEasing  : toast_settings.transition.closeEasing
        },
        position: toast_settings.position,
        displayTime: 0,
        closeIcon: true,
        newestOnTop: toast_settings.newestOnTop,
        compact: toast_settings.compact,
        onDeny    : function(){
            setCookie('conikal_toast_remind_set_password', '1', toast_settings.remind)
        },
        onApprove : function() {
            $('#resetpass').modal('show');
        }
    });

    // COOKIE NOTICE
    var cookie_settings = $.parseJSON(main_vars.cookie_setting);
    if (cookie_settings.cookie_notice == 1) {
        $('.cookie.nag').nag({
            key      : 'conikal_accepts_cookies',
            value    : true
        });

        $('#accept-cookie').on('click', function() {
            $('.cookie.nag').nag('hide')
            setCookie('conikal_accepts_cookies', true, (parseInt(cookie_settings.cookie_notice_time) * 60 * 24) )
        });

        $('#ignore-cookie').on('click', function() {
            $('.cookie.nag').nag('hide')
            setCookie('conikal_accepts_cookies', true, 0 )
        });

        $('#toast-cookie-notice').toast({
            transition: {
                showMethod   : cookie_settings.transition.showMethod,
                showDuration : toast_settings.transition.showDuration,
                hideMethod   : cookie_settings.transition.hideMethod,
                hideDuration : toast_settings.transition.hideDuration,
                closeEasing  : toast_settings.transition.closeEasing
            },
            position: cookie_settings.cookie_position,
            displayTime: 0,
            closeIcon: true,
            newestOnTop: toast_settings.newestOnTop,
            compact: toast_settings.compact,
            onDeny    : function(){
                setCookie('conikal_accepts_cookies', true, 0 )
            },
            onApprove : function() {
                setCookie('conikal_accepts_cookies', true, (parseInt(cookie_settings.cookie_notice_time) * 60 * 24) )
            }
        });

        // hide cookie notice when scroll down
        if (cookie_settings.cookie_hidden_type == 'scroll') {
            if ($('.toast-cookie-notice, .sidebar-cookie-notice').length) {
                scrollHideCookie();
            }
        }
    }

    // HIDE COOKIE NOTICE WHEN SCROLL DOWN
    function scrollHideCookie() {
        var cookie_settings = $.parseJSON(main_vars.cookie_setting);
        var lastScrollTop = 0;
        $(window).scroll(function(event){
            var st = $(this).scrollTop();
            if (st > lastScrollTop){
                if (!$('.toast-cookie-notice, .sidebar-cookie-notice').hasClass('closed')) {
                    setTimeout(function() {
                        $('.toast-container').empty().hide();
                    }, 600);
                    setCookie('conikal_accepts_cookies', true, (parseInt(cookie_settings.cookie_notice_time) * 60 * 24) )
                }
            }
        lastScrollTop = st;
        });
    }

    // GET PHONE CODE DATA AND INITIAL DOWNDROP
    phoneCodeDropdown();
    function phoneCodeDropdown() {
        $('.phone-code-dropdown').dropdown({
            apiSettings: {
              url: main_vars.api_url + '?type=phone_code',
              filterRemoteData: true,
              saveRemoteData: true
            },
        });

        var phone_code = $('#phoneCode').val();
        $('.phone-code-dropdown').dropdown('set selected', phone_code);
    }

    // GET COUNTRY DATA AND INITIAL DOWNDROP
    countrySelectionDropdown();
    function countrySelectionDropdown() {
        $('.country-selection, .language-selection').dropdown();

        var country_code = $('#country-selected').val();
        if (country_code != '') {
            $('.country-selection').dropdown('set selected', country_code);
        }
    }

    // CATEGORY DROPDOWN
    if (main_vars.maximum_category > 1) {
        $('.category-select').dropdown({
            hideAdditions: false,
            maxSelections: main_vars.maximum_category,
        });
    }

    if ($('#category_id').length > 0) {
        $('.category-select').dropdown('set selected', $('#category_id').val());
    } else {
        var set_categories = [];
        $('input[name="category_ids[]"]').each(function(index) {
            var category = $(this).val();
            set_categories.push(category);
        });
        $('.category-select').dropdown('set exactly', set_categories);
    }

    // SEARCH TAGS AUTOCOMPLETE
    if ($('#topics-search').length) {
        tagsSearch('#topics-search', 'topics');
    }
    if ($('#give-tags-search').length) {
        tagsSearch('#give-tags-search', 'give_tags');
    }
    function tagsSearch(id, type) {
        $(id).dropdown({
            apiSettings: {
                url: main_vars.api_url + '?type=' + type + '&q={query}'
            },
            allowReselection: true,
            allowAdditions: true,
            hideAdditions: false,
            maxSelections: main_vars.maximum_topics,
        });

        var set_topics = [];
        $('input[name="current_topics[]"]').each(function(index) {
            var topic = $(this).val();
            set_topics.push(topic);
        });
        $(id).dropdown('set exactly', set_topics);
    }

    $('.search-petition').keyup(function(){
        var keyword = $(this).val();
        $('.search-keywords').text(keyword);
    });

    // SEARCH ORGANIZATION DECISION MAKER
    $('#organization-search').dropdown({
        apiSettings: {
            url: main_vars.api_url + '?type=organizations&q={query}'
        },
        allowReselection: true,
        allowAdditions: true,
        hideAdditions: false,
        maxSelections: 1
    });
    $('#organization-search').dropdown('set selected', $('#decision_organization_name').val() );

    $('#position-search').dropdown({
        apiSettings: {
            url: main_vars.api_url + '?type=position&q={query}'
        },
        allowReselection: true,
        allowAdditions: true,
        hideAdditions: false,
        maxSelections: 1
    });
    $('#position-search').dropdown('set selected', $('#decision_title_id').val() );

    // COUNTRY SET SELECT
    setSelectCountry();
    function setSelectCountry() {
        $('.country-search').each(function() {
            var petition_id = $(this).attr('data-id');
            if (!petition_id) {
                petition_id = '';
            }

            var country_ele = '#countrySign' + petition_id;
            $('#addressSign' + petition_id + ', #addressUser, #addressSignup').on('change', function() {
                setTimeout(function() {
                    $('#country-search' + petition_id).dropdown('set selected', $(country_ele).val());
                    if ($('.country-search').length > 0) {
                        $('.country-search').dropdown('set selected', $('#countryUser, #countrySignup').val());
                    }
                }, 300)
            })
        });
    }

    // SIDEBAR MENU
    $('#left-menu-btn').on('click', function() {
        if (main_vars.mobile_sign_style == 'sidebar') {
            $('.sign-sidebar').each(function(){
                var petition_id = $(this).attr('data-id');
                if ($('#sign-sidebar' + petition_id).hasClass('visible') == true) {
                    $('#close-mobile-sign' + petition_id).trigger('click');
                }
            });
        }
        $('#leftside-menu').sidebar({mobileTransition: main_vars.mobile_menu_animation}).sidebar('toggle');
    });

    $('#leftside-menu').sidebar({
        onHide: function() {
            $('#left-menu-btn').children('i').removeClass('arrow left large icon').addClass('sidebar large icon');
        },
        onShow: function() {
            $('#left-menu-btn').children('i').removeClass('sidebar large icon').addClass('arrow left large icon');
        },
    });

    $('#dashboard-sidebar-btn').on('click', function() {
        $('#dashboard-sidebar-menu').sidebar({transition: 'overlay', dimPage: false}).sidebar('toggle')
    });

    $('.search-filter-btn').on('click', function() {
        $('#search-filter-sidebar').sidebar({mobileTransition: main_vars.mobile_menu_animation}).sidebar('toggle')
    });

    // Sign Sidebar
    signSidebarInit();
    function signSidebarInit() {
        var sign_sidebar_settings = {
            transition: 'overlay',
            closable: false,
            dimPage: false,
            silent: true,
        }

        $(document).on('click', '.mobile-sign-btn, .tablet-sign-btn', function() {
            var petition_id = $(this).attr('data-id');
            $('#sign-sidebar' + petition_id).sidebar(sign_sidebar_settings).sidebar('toggle')
        });

        $(document).on('click', '.close-mobile-sign', function() {
            var petition_id = $(this).attr('data-id');
            console.log(petition_id);
            $('#sign-sidebar' + petition_id).sidebar(sign_sidebar_settings).sidebar('toggle').attr('data-closed', 1)
        });
    }

    // Change sign sidebar icon when toggle action
    changeCloseIcon();
    function changeCloseIcon() {
        $('.sign-sidebar').each(function() {
            var petition_id = $(this).attr('data-id');
            $('#sign-sidebar' + petition_id).sidebar({
                onChange: function() {
                    if ($('#sign-sidebar' + petition_id).hasClass('visible')) {
                        $('#close-mobile-sign' + petition_id).children('i').removeAttr('class').addClass('angle up icon');
                    } else {
                        $('#close-mobile-sign' + petition_id).children('i').removeAttr('class').addClass('angle down icon');
                    }
                }
            });
        });
    }
    
    $('.verificaton-notice.sidebar')
    .sidebar('setting', 'transition', main_vars.verify_transition)
    .sidebar('setting', 'closable', (main_vars.verify_closable == 1 ? true : false))
    .sidebar('setting', 'dimPage', (main_vars.verify_dimmer == 1 ? true : false))
    .sidebar('setting', 'transition', main_vars.verify_transition)
    .sidebar('toggle');

    // MESSAGE CLOSE
    $(document).on('click', '.message .close', function() {
        $('.message .close').closest('.message').transition(main_vars.modal_transition);
    });

    // TRANSITION
    $('.new-comment').transition(main_vars.modal_transition);

    // ACCORDION
    accordionInit();
    function accordionInit() {
        $('.ui.accordion').accordion();
    }

    // PROGRESS
    progressBarInit();
    function progressBarInit() {
        $('.petition-goal, #profile-progress-bar').progress({
            'label': false
        });
        $('.citation-opinion-progress').progress({
            'autoSuccess': false,
            'label': true
        });
    }

    // STICKY
    // update sticky when content dom is change
    $('#content, #content-trending, #content-recent').on('change', function(e) {
        sidebarStickyInit('', '#main-content, .main-content');
    });

    // upate sticky when tab was changed
    $('#home-petition-tab .item').on('click', function(e) {
        var tab_name = $(this).attr('data-tab');
        var tab_target = '#tab-' + tab_name;
        setTimeout(function() {
            sidebarStickyInit('', tab_target);
            navigationStickyInit('', tab_target);
        }, 100);
    });

    stickyInitAll();
    function stickyInitAll() {
        $('.ui.sticky').each(function() {
            var petition_id = $(this).attr('data-id');
            var on_init = $(this).attr('data-init');
            if (on_init != 1) {
                stickyInit(petition_id);
            }
        });
    }

    function sidebarStickyInit(petition_id = '', target = '') {
        var header_height = $('.header-menu, .home-menu').height();
        if (target == '') {
            if (window.matchMedia('(min-width: 991px)').matches) {
                target = '.home-tab, #content' + petition_id;
            } else {
                target = '';
            }
        }

        $('#sign-sticky' + petition_id + ', #donate-sticky' + petition_id + ', #sign-category, #about-sticky, #share-post, #post-ads-banner, #profile-tips, #review-form').attr('data-init', 1).sticky({
            context: target,
            offset: header_height + 50,
            observeChanges: true,
            silent: true,
        });
    }

    function navigationStickyInit(petition_id = '', target = '') {
        var header_height = $('.header-menu, .home-menu').height();

        // offset for sticky menu when header is fixed
        if (main_vars.type_menu == 'fixed') {
            var tab_sticky_offset = header_height;
        } else {
            var tab_sticky_offset = 0;
        }

        // add margin top if top menu enabled
        if (main_vars.top_menu == 1 && main_vars.type_menu != 'none') {
            tab_sticky_offset = tab_sticky_offset + 40;
        }

        if (target == '') {
            target = '.home-tab, #content' + petition_id;
        }

        $('#home-tab-sticky, #navigation-sticky' + petition_id).attr('data-init', 1).sticky({
            context: target,
            offset: tab_sticky_offset,
            observeChanges: true,
            onStick: function() {
                $(this).addClass('color white');
            },
            onUnstick: function() {
                $(this).removeClass('color white');
            }
        });
    }

    function stickyInit(petition_id = '') {
        // init sidebar sticky
        sidebarStickyInit(petition_id);
        
        // init home tab sticky and navigation sticky
        navigationStickyInit(petition_id);

        // FIX SIGN MENU ON MOBILE
        var sign_sidebar_settings = {
            transition: 'overlay',
            closable: false,
            dimPage: false,
            silent: true,
        }

        if (main_vars.mobile_sign_scroll == 1) {
            $('#content' + petition_id).visibility({
                once: false,
                onPassing: function() {
                    $('#mobile-sign-btn' + petition_id + ', #tablet-sign-btn' + petition_id).removeClass('sticky').addClass('fixed bottom sticky').css('width', '100%');
                    if (main_vars.mobile_sign_style == 'sidebar' && $('#sign-sidebar' + petition_id).attr('data-closed') == 0) {
                        $('#sign-sidebar' + petition_id).sidebar(sign_sidebar_settings).sidebar('show')
                    }
                },
                onPassingReverse: function() {
                    $('#mobile-sign-btn' + petition_id + ', #tablet-sign-btn' + petition_id).removeClass('fixed bottom sticky').addClass('sticky').removeAttr("style");
                    if (main_vars.mobile_sign_style == 'sidebar') {
                        $('#sign-sidebar' + petition_id + ', #tablet-sign-btn' + petition_id).sidebar(sign_sidebar_settings).sidebar('hide')
                    }
                }
            });
        } else {
            $('#mobile-sign-btn' + petition_id + ', #tablet-sign-btn' + petition_id).removeClass('sticky').addClass('fixed bottom sticky').css('width', '100%');
            if (main_vars.mobile_sign_style == 'sidebar' && $('#sign-sidebar' + petition_id).attr('data-closed') == 0) {
                $('#sign-sidebar' + petition_id).sidebar(sign_sidebar_settings).sidebar('toggle')
            }
        }
    }

    // ADD RECEIDER
    var max_fields = 10; //maximum input boxes allowed
    var wrapper = $(".input-fields-wrap"); //Fields wrapper
    var add_button = $(".add-field-button"); //Add button ID
    var add_button_level = $(".add-level-button"); //Add level button ID

    var x = 1; //initlal text box count
    $(add_button).on('click', function(e) { //on add input button click
        e.preventDefault();
        if (x < max_fields) { //max input box allowed
            x++; //text box increment
            $('#new-decision-makers').append('<div class="ui grid search decision-search">' +
                '<div class="sixteen wide mobile eight wide tablet eight wide computer column">' +
                '<div class="ui large fluid input">' +
                '<input class="prompt" type="text" id="new_receiver" name="new_receiver[]" placeholder="' + main_vars.full_name_holder + '" value="">' +
                '<input class="new_decisionmakers" type="hidden" name="new_decisionmakers[]" value="">' +
                '</div>' +
                '</div>' +
                '<div class="sixteen wide mobile eight wide tablet eight wide computer column">' +
                '<div class="ui large fluid input">' +
                '<input class="decision-title" type="text" id="new_postion" name="new_position[]" placeholder="' + main_vars.position_holder + '" value="">' +
                '</div>' +
                '</div>' +
                '<div class="results"></div>' +
                '<a href="#" class="remove-field"><i class="inverted circular close link icon"></i></a>' +
                '</div>'); //add input box
        }
    });

    // ADD CONTRIBUTE LEVEL
    var level_number = 1; //initlal text box count
    $(add_button_level).on('click', function(e) { //on add input button click
        e.preventDefault();
        if (level_number < max_fields) { //max input box allowed
            level_number++; //text box increment

            var label_postition = 'left';
            if (main_vars.give_currency_position == 'after') {
                label_postition = 'right';
            }

            var html = '';
                html += '<div class="ui grid search">' +
                '<div class="sixteen wide mobile eight wide tablet eight wide computer column">' +
                '<div class="ui large fluid ' + label_postition + ' labeled input">';
                if (main_vars.give_currency_position == 'before') {
                    html += '<label for="amount_level" class="ui label">' + main_vars.give_currency_symbol + '</label>';
                }
                html += '<input type="text" id="amount_level" name="amount_level[]" placeholder="' + main_vars.amount_level_holder + '" value="">';
                if (main_vars.give_currency_position == 'after') {
                    html += '<label for="amount_level" class="ui label">' + main_vars.give_currency_symbol + '</label>';
                }
                html += '</div>' +
                '</div>' +
                '<div class="sixteen wide mobile eight wide tablet eight wide computer column">' +
                '<div class="ui large fluid input">' +
                '<input type="text" id="name_level" name="name_level[]" placeholder="' + main_vars.level_name_holder + '" value="">' +
                '</div>' +
                '</div>' +
                '<div class="results"></div>' +
                '<a href="#" class="remove-field"><i class="inverted circular close link icon"></i></a>' +
                '<div class="sixteen wide column field">' +
                '<textarea name="description_level[]" id="description_level" placeholder="' + main_vars.level_description_holder + '" rows="3"></textarea>' +
                '</div>' +
                '</div>';
            $('#new-donate-level').append(html); //add input box
        }
    });

    $(wrapper).on("click", ".remove-field", function(e) { //user click on remove text
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    });

    // SHOW PASSWORD
    $(".toggle-password").click(function() {
        $(this).toggleClass("eye eye slash");
        var input = $(this).prev();
        if (input.attr("type") == "password") {
            input.attr("type", "text");
        } else {
            input.attr("type", "password");
        }
    });

    // SETTING CAROWSEL
    // get column
    function getCarouselColumn(id, column = '') {
        if (column == '') {
            var column = $(id).attr('data-column');
        }

        if (column == 'one') {
            column = 1;
        } else if (column == 'two') {
            column = 2;
        } else if (column == 'four') {
            column = 4;
        } else if (column == 'five') {
            column = 5;
        } else {
            column = 3;
        }

        return column;
    }

    initCarousel();
    function initCarousel() {
        var settings_rtl_mode = ((main_vars.rtl_mode != 0) ? true : false);
        var carousel_classes = ['.testimonial-carousel', '.post-carousel', '.related-product', '.related-posts', '.fundraising-carousel'];

        for (var i = 0; i < carousel_classes.length; i++) {
            if (carousel_classes[i].length) {
                $(carousel_classes[i]).not('.slick-initialized').slick({
                    rtl: settings_rtl_mode,
                    dots: true,
                    infinite: true,
                    slidesToShow: getCarouselColumn(carousel_classes[i]),
                    slidesToScroll: getCarouselColumn(carousel_classes[i]),
                    adaptiveHeight: true,
                    responsive: [
                        {
                          breakpoint: 1280,
                          settings: {
                            slidesToShow: getCarouselColumn(carousel_classes[i]) - 1,
                            slidesToScroll: getCarouselColumn(carousel_classes[i]) - 1,
                            infinite: true,
                            dots: true
                          }
                        },
                        {
                          breakpoint: 991,
                          settings: {
                            slidesToShow: getCarouselColumn(carousel_classes[i] - 1, 'two'),
                            slidesToScroll: getCarouselColumn(carousel_classes[i] - 1, 'two'),
                            infinite: true,
                            dots: true,
                            arrows: true
                          }
                        },
                        {
                          breakpoint: 767,
                          settings: {
                            slidesToShow: 1,
                            slidesToScroll: 1,
                            infinite: true,
                            dots: true,
                            arrows: false
                          }
                        }
                      ]
                });

                // reinit avatar popup
                setTimeout(() => {
                    $('.supporter-avatar').popup();
                }, 600);
            }
        }

        $('.blog-feature').slick({
            dots: true,
            infinite: true,
            vertical: true,
            verticalSwiping: true,
            swipeToSlide: true,
            adaptiveHeight: true,
            variableWidth: false,
        });
    }

    // MODAL SETTING
    modalInit();
    function modalInit() {
        $('.ui.modal').modal({
            transition: main_vars.modal_transition
        });

        $('.signin-btn, .submit-signin-btn').on('click', function() {
            $('#signinModal').modal('show');
            $('#userLoginForm').removeClass('display none').addClass('display block');
            $('#userSignupForm').css('display', 'none');
            $('#signin-button').css('display', 'none');
            $('#signup-button').css('display', 'inline-block');
            $('#refererID').val($(this).attr('data-id'));
        });
        $('.signup-btn, .signup-guest').on('click', function() {
            $('#signinModal').modal('show');
            $('#userLoginForm').removeClass('display block').addClass('display none');
            $('#userSignupForm').css('display', 'block');
            $('#signin-button').css('display', 'inline-block');
            $('#signup-button').css('display', 'none');
        });
        $('.forgot-password').on('click', function() {
            $('#forgot-password').modal('show');
        });
        $(document).on('click', '.embed-campaign', function() {
            var petition_id = $(this).attr('data-id');
            $('#embed-modal' + petition_id).modal('show');
        });
        $('#set-goal').on('click', function() {
            $('#set-goal-confirm').modal('show');
            $('#goal-number').text($('#new-goal').val());
            $('#goal-response').empty();
        });
        $('#set-auto-increase').on('click', function() {
            $('#set-auto-increase-confirm').modal('show');
        });
        $('#reopen-petition').on('click', function() {
            $('#reopen-confirm').modal('show')
        });
        $('#close-petition').on('click', function() {
            $('#close-confirm').modal('show')
        });
        $('#contact-btn').on('click', function() {
            $('#contact-user').modal('show')
        });
        $('.invite-decision-response').on('click', function() {
            var email   = $(this).attr('data-email');
            var name    = $(this).attr('data-name');
            $('#invite-modal').modal('show')
            $('#invitation-response').empty();
            $('#invite_email').val(email);
            $('#invite_decision_name').val(name);
        });
        $('#invita-cancel').on('click', function() {
            $('#invite-modal').modal('hide')
        });
        $('.add-co-author').on('click', function() {
            $('#add-co-author-modal').modal('show')
        });
        $('#add-co-author-cancel').on('click', function() {
            $('#add-co-author-modal').modal('hide')
        });
        $('.remove-co-author').on('click', function() {
            var post_id = $(this).attr('data-id');
            var co_author = $(this).attr('data-author');
            var co_author_name = $(this).attr('data-name');
            $('#remove-co-author-confirm').modal('show')
            $('#remove-co-author-btn').attr({'data-id': post_id, 'data-author': co_author});
            $('#co-author-name').text(co_author_name);
        });
        $(document).on('click', '.skip-after-sign', function() {
            var petition_id = $(this).attr('data-id');
            $('#sign-successful-modal' + petition_id).modal('hide')
            $('#sign-sidebar' + petition_id).sidebar('hide')
        });
        $('#delete-account-btn').on('click', function() {
            $('#delete-account-confirm').modal('show')
        });
        $('#cancel-delete-account').on('click', function() {
            $('#delete-account-confirm').modal('hide')
        });

        if (!main_vars.is_user_logged_in) {
            $('#citationModal').modal({
                onHidden: function() {
                    if ($('#usernameSignin').val() != '' && $('#passwordSignin').val() != '') {
                        $('#submitSignin').trigger('click')
                    }
                }
            });
        }
        
        // PROMPT ACTION
        var prompt_action = $.parseJSON(main_vars.prompt_action);
        if (prompt_action.prompt_status == 1) {
            if ($('.signBtn').length || $('.submitSign').length || $('.prompt-action').length) {
                $('.prompt-action').each(function(id) {
                    var petition_id = $(this).attr('data-id');
                    var on_load = $(this).attr('data-load');
                    if (on_load != 1) {
                        var prompt_action = $.parseJSON(main_vars.prompt_action);
                        setTimeout(function() {
                            $('#prompt-action' + petition_id).modal({inverted: true }).attr('data-load', 1).modal('show');
                        }, parseInt(prompt_action.show_time) * 60 * 1000);

                        $(document).on('click', '.letSign', function() {
                            var sign_id = $(this).attr('data-id');
                            $('#prompt-action' + sign_id).modal('hide')
                            $('#sign-sticky' + sign_id).transition('bounce')
                            $('#sign-share-block' + sign_id).transition('bounce')
                            setCookie('conikal_prompt_action_remind', '1', (prompt_action.remind_time == 'session' ? '' : parseInt(prompt_action.remind_time)))
                            
                            // open sidebar on mobile
                            var sign_sidebar_settings = {
                                transition: 'overlay',
                                closable: false,
                                dimPage: false,
                                silent: true,
                            }
                            
                            if (!$('#sign-sidebar' + sign_id).hasClass('visible')) {
                                $('#sign-sidebar' + sign_id).sidebar(sign_sidebar_settings).sidebar('toggle')
                            }
                        });
                    }
                });
            }
        }
    } // end modal init

    // CONTENT SUBMIT EDITOR HEIHGT
    $('#next-three').on('click', function() {
        $('#new_content_ifr, #form_content_ifr').css('height', '300px');
    })
    $('#edit-letter').on('click', function() {
        $('#new_letter_ifr').css('height', '300px');
    })

    // CHECKBOX
    checkboxInit();
    function checkboxInit() {
        $('.ui.checkbox').checkbox();
    }
    
    // INIT TAB
    $('#home-petition-tab .item, #profile-tab .item, .product-tab .item, #petition-edit-tab .item, #contribute-tab .item, .woocommerce-login-tab .item, .embed-tab .item').tab();
    $('#home-petition-tab .item').on('click', function(){
        $('html,body').animate({
            scrollTop: $('#main-content, .main-content').offset().top - 120
        }, 300);
    });

    // Hidden save button when on infomations tab
    $('#petition-edit-tab .item').on('click', function(){
        var tab_name = $(this).attr('data-tab')
        if (tab_name == 'infomations') {
            $('#finish-btn').addClass('display none');
        } else {
            $('#finish-btn').removeClass('display none');
        }
    });

    // CONTACT FORM 7 
    if ($('.wpcf7').length > 0) {
        var wpcf7Elm = document.querySelector( '.wpcf7' );
 
        wpcf7Elm.addEventListener( 'wpcf7submit', function( event ) {
            $('.wpcf7-submit').removeClass('loading');
        }, false );

        $('.wpcf7-submit').on('click', function() {
            $(this).addClass('loading');
            if ($(this).prop('tagName') == 'BUTTON') {
                $('.wpcf7-spinner').addClass('display none');
            }
        })
    }
    

    // CITATION OPINION
    citationLabelInit();
    function citationLabelInit() {
        $(document).on('click', '.citation-opinion-btn, .citationBtn', function() {
            var petition_id = $(this).attr('data-id');
            $('#citation-opinion' + petition_id + ' input').on('change', function() {
                var opinion = $('input[name=citation_opinion' + petition_id + ']:checked').val();
                if (opinion == 'no') {
                    $('#opinion-selected-yes').removeClass('display inline-block').addClass('display none');
                    $('#opinion-selected-no').removeClass('display none').addClass('display inline-block');
                } else {
                    $('#opinion-selected-no').removeClass('display inline-block').addClass('display none');
                    $('#opinion-selected-yes').removeClass('display none').addClass('display inline-block');
                }
            });
        });
    }

    $('.citation-opinion-btn, .accord-guest-sign').on('click', function() {
        if ($('.accord-sign-options, .accord-guest-sign').children().hasClass('active') == false) {
            $('.accord-sign-options, .accord-guest-sign').children().trigger('click')
        }
    });

    $(document).on('click', '.open-share-box', function() {
        var petition_id = $(this).attr('data-id');

        $('#accord-contribute-share' + petition_id).children().trigger('click')
        if ($('#accord-donate' + petition_id).children().hasClass('active')) {
            $('#accord-donate' + petition_id).children().trigger('click')
        }
        if ($('#accord-sign-parent' + petition_id).children().hasClass('active')) {
            $('#accord-sign-parent' + petition_id).children().trigger('click')
        }

        $(this).addClass('display none')
        $('#open-sign-box' + petition_id).removeClass('display none')
        if ($('#accord-donate' + petition_id).length) {
            $('#open-donate-box' + petition_id).removeClass('display none')
        }
    });

    $(document).on('click', '.open-donate-box', function() {
        var petition_id = $(this).attr('data-id');

        if ($('#accord-donate' + petition_id).length) {
            $(this).addClass('display none')
            $('#accord-donate' + petition_id).children().trigger('click')
            if ($('#accord-contribute-share' + petition_id).children().hasClass('active')) {
                $('#accord-contribute-share' + petition_id).children().trigger('click')
                $('#open-share-box' + petition_id).removeClass('display none')
            }
            if ($('#accord-sign-parent' + petition_id).children().hasClass('active')) {
                $('#accord-sign-parent' + petition_id).children().trigger('click')
                $('#open-sign-box' + petition_id).removeClass('display none')
            }
        } else {
            $(this).addClass('display none')
            if ($('#accord-sign-parent' + petition_id).length) {
                $('#accord-sign-parent' + petition_id).children().trigger('click')
                $('#open-sign-box' + petition_id).addClass('display none')
            } else {
                $('#accord-contribute-share' + petition_id).children().trigger('click')
                $('#open-share-box' + petition_id).addClass('display none')
            }
        }
        
        $('#spead-campaign-buttons' + petition_id).removeClass('display none')
        $('#spead-campaign-cta' + petition_id).addClass('display none')
    });

    $(document).on('click', '.open-sign-box', function() {
        var petition_id = $(this).attr('data-id');

        if ($('#accord-contribute-share' + petition_id).children().hasClass('active')) {
            $('#accord-contribute-share' + petition_id).children().trigger('click')
        }
        if ($('#accord-donate' + petition_id).children().hasClass('active')) {
            $('#accord-donate' + petition_id).children().trigger('click')
        }

        $(this).addClass('display none')
        $('#open-share-box' + petition_id).removeClass('display none')
        if ($('#accord-donate' + petition_id).length) {
            $('#open-donate-box' + petition_id).removeClass('display none')
        }
    });

    $(document).on('click', '.citationBtn', function() {
        var petition_id = $(this).attr('data-id');
        var redirection = $(this).attr('data-redirection');

        if (redirection == 1) {
            $('.submitCitation').attr('data-redirection', 1);
        }

        if ($('#citation-instant' + petition_id).hasClass('checked')) {
            var citation_instant = true;
        } else {
            var citation_instant = false;
        }

        if ($('#signBtn' + petition_id).length) {
            if (citation_instant == true) {
                $('#citationModal').attr('data-id', petition_id).modal('show');
                $('.submitCitation').attr('data-id', petition_id);
            } else {
                $('#citation-opinion').addClass('display none');
                $(this).parent().addClass('display none');
                $('#signBtn' + petition_id).trigger('click').parent().removeClass('display none');
            }
        } else {
            $('#citationModal').attr('data-id', petition_id).modal('show');
            $('.submitCitation').attr('data-id', petition_id);
        }
        $('#citation-response').empty();
    });

    // STEP BY STEP SUBMIT
    function stepbystep(current) {
        var one = 'step-one',
            two = 'step-two',
            three = 'step-three',
            four = 'step-four',
            five = 'step-five';

        $('html,body').animate({
            scrollTop: 0
        }, 500);

        if (current === one) {
            $.tab('change tab', one);
            $('#step-one').addClass('active').removeClass('completed');
            $('#step-two').removeClass('active completed');
            $('#step-three').removeClass('active completed');
            $('#step-four').removeClass('active completed');
            $('#step-five').removeClass('active completed');

            $('#next-two').removeClass('display none').addClass('display inline-block');
            $('#next-three').removeClass('display inline-block').addClass('display none');
            $('#next-four').removeClass('display inline-block').addClass('display none');
            $('#next-five').removeClass('display inline-block').addClass('display none');
            $('#finish-btn, #submit-contribute').removeClass('display inline-block').addClass('display none');

            $('#back-one').removeClass('display inline-block').addClass('display none');
            $('#back-two').removeClass('display inline-block').addClass('display none');
            $('#back-three').removeClass('display inline-block').addClass('display none');
            $('#back-four').removeClass('display inline-block').addClass('display none');

            $('.step-one').transition(main_vars.modal_transition);
            $('.step-two').transition('hide');
            $('.step-three').transition('hide');
            $('.step-four').transition('hide');
            $('.step-five').transition('hide');
        } else if (current === two) {
            $.tab('change tab', two);
            $('#step-one').removeClass('active').addClass('completed');
            $('#step-two').addClass('active').removeClass('completed disabled');
            $('#step-three').removeClass('active completed');
            $('#step-four').removeClass('active completed');
            $('#step-five').removeClass('active completed');

            $('#next-two').removeClass('display inline-block').addClass('display none');
            $('#next-three').removeClass('display none').addClass('display inline-block');
            $('#next-four').removeClass('display inline-block').addClass('display none');
            $('#next-five').removeClass('display inline-block').addClass('display none');
            $('#finish-btn, #submit-contribute').removeClass('display inline-block').addClass('display none');

            $('#back-one').removeClass('display none').addClass('display inline-block');
            $('#back-two').removeClass('display inline-block').addClass('display none');
            $('#back-three').removeClass('display inline-block').addClass('display none');
            $('#back-four').removeClass('display inline-block').addClass('display none');

            $('.step-one').transition('hide');
            $('.step-two').transition(main_vars.modal_transition);
            $('.step-three').transition('hide');
            $('.step-four').transition('hide');
            $('.step-five').transition('hide');
        } else if (current === three) {
            $.tab('change tab', three);
            $('#step-one').removeClass('active').addClass('completed');
            $('#step-two').removeClass('active').addClass('completed');
            $('#step-three').addClass('active').removeClass('completed disabled');
            $('#step-four').removeClass('active completed');
            $('#step-five').removeClass('active completed');

            $('#next-two').removeClass('display inline-block').addClass('display none');
            $('#next-three').removeClass('display inline-block').addClass('display none');
            $('#next-four').removeClass('display none').addClass('display inline-block');
            $('#next-five').removeClass('display inline-block').addClass('display none');
            $('#finish-btn, #submit-contribute').removeClass('display inline-block').addClass('display none');

            $('#back-one').removeClass('display inline-block').addClass('display none');
            $('#back-two').removeClass('display none').addClass('display inline-block');
            $('#back-three').removeClass('display inline-block').addClass('display none');
            $('#back-four').removeClass('display inline-block').addClass('display none');

            $('.step-one').transition('hide');
            $('.step-two').transition('hide');
            $('.step-three').transition(main_vars.modal_transition);
            $('.step-four').transition('hide');
            $('.step-five').transition('hide');
        } else if (current === four) {
            $.tab('change tab', four);
            $('#step-one').removeClass('active').addClass('completed');
            $('#step-two').removeClass('active').addClass('completed');
            $('#step-three').removeClass('active').addClass('completed');
            $('#step-four').addClass('active').removeClass('completed disabled');
            $('#step-five').removeClass('active completed');

            $('#next-two').removeClass('display inline-block').addClass('display none');
            $('#next-three').removeClass('display inline-block').addClass('display none');
            $('#next-four').removeClass('display inline-block').addClass('display none');
            $('#next-five').removeClass('display none').addClass('display inline-block');
            $('#finish-btn, #submit-contribute').removeClass('display none').addClass('display inline-block');

            $('#back-one').removeClass('display inline-block').addClass('display none');
            $('#back-two').removeClass('display inline-block').addClass('display none');
            $('#back-three').removeClass('display none').addClass('display inline-block');
            $('#back-four').removeClass('display inline-block').addClass('display none');

            $('.step-one').transition('hide');
            $('.step-two').transition('hide');
            $('.step-three').transition('hide');
            $('.step-four').transition(main_vars.modal_transition);
            $('.step-five').transition('hide');
        } else {
            $.tab('change tab', five);
            $('#step-one').removeClass('active').addClass('completed');
            $('#step-two').removeClass('active').addClass('completed');
            $('#step-three').removeClass('active').addClass('completed');
            $('#step-four').removeClass('active').addClass('completed');
            $('#step-five').addClass('active').removeClass('completed disabled');

            $('#next-two').removeClass('display inline-block').addClass('display none');
            $('#next-three').removeClass('display inline-block').addClass('display none');
            $('#next-four').removeClass('display inline-block').addClass('display none');
            $('#next-five').removeClass('display inline-block').addClass('display none');
            $('#finish-btn, #submit-contribute').removeClass('display none').addClass('display inline-block');

            $('#back-one').removeClass('display inline-block').addClass('display none');
            $('#back-two').removeClass('display inline-block').addClass('display none');
            $('#back-three').removeClass('display inline-block').addClass('display none');
            $('#back-four').removeClass('display none').addClass('display inline-block');

            $('.step-one').transition('hide');
            $('.step-two').transition('hide');
            $('.step-three').transition('hide');
            $('.step-four').transition('hide');
            $('.step-five').transition(main_vars.modal_transition);
        }
    }

    $('.step-two').transition('hide');
    $('.step-three').transition('hide');
    $('.step-four').transition('hide');
    $('#step-one').on('click', function() {
        stepbystep('step-one');
        if (main_vars.receiver_step != 1) {
            $('#next-three').removeClass('display none').addClass('display inline-block')
        }   
    });
    $('#step-two').on('click', function() {
        stepbystep('step-two');
    });
    $('#step-three').on('click', function() {
        stepbystep('step-three');
    });
    $('#step-four').on('click', function() {
        stepbystep('step-four');
        if (main_vars.fundraising_step == 1 && $('.step-five').length > 0) {
            $('#finish-btn').removeClass('display inline-block').addClass('display none')
        }
    });
    $('#step-five').on('click', function() {
        stepbystep('step-five');
    });

    // next step two
    $('#next-two').on('click', function() {
        // validate fields in current tab
        var validateFields = {
            new_title       : 'empty',
            new_category    : 'empty',
            new_goal_d      : 'empty',
        }
        var element_btn = false;

        // add field if submit fundraising
        if ($('#form_content').length) {
            validateFields.give_title   = 'empty';
            validateFields.set_goal     = 'empty';
            validateFields.new_address  = 'empty';

            element_btn = '.ui.form.submit-contribute';
        }

        var validateForm = valideFormSubmit(validateFields, element_btn);

        if (validateForm) {
            stepbystep('step-two');
        }
    });

    // next step three
    $('#next-three').on('click', function() {
        // validate fields in current tab
        var validateFields = {
            new_receiver    : 'empty',
            new_position    : 'empty', 
            new_address     : 'empty'
        }

        var element_btn = false;

        // add address field if receive step is enable
        if (main_vars.receiver_step == 0) {
            var validateFields = {
                new_title       : 'empty',
                new_category    : 'empty', 
                new_goal_d      : 'empty',
                new_address     : 'empty', 
            }
        }

        // add field if submit fundraising
        if ($('#form_content').length) {
            validateFields.amount_level             = 'empty';
            validateFields.name_level               = 'empty';
            validateFields.custom_amount_minimum    = 'empty';

            element_btn = '.ui.form.submit-contribute';
        }

        var validateForm = valideFormSubmit(validateFields, element_btn);

        if (validateForm) {
            stepbystep('step-three');
        }
    });

    // next step four
    $('#next-four').on('click', function() {
        // validate fields in current tab
        var validateFields = {
            new_topics    : 'empty',
            new_content   : 'empty'
        }

        var element_btn = false;

        // add field if submit fundraising
        if ($('#form_content').length) {
            validateFields.form_content             = 'empty';
            validateFields.new_tags                 = 'empty';
            validateFields.goal_achieved_message    = 'empty';

            element_btn = '.ui.form.submit-contribute';
        }

        var validateForm = valideFormSubmit(validateFields, element_btn);

        if (validateForm) {
            stepbystep('step-four');
            if (main_vars.fundraising_step == 1 && $('.step-five').length > 0) {
                $('#finish-btn').removeClass('display inline-block').addClass('display none')
            }
        }
    });

    // next step five
    $('#next-five').on('click', function() {
        // validate fields in current tab
        var validateFields = {
            new_gallery : 'empty',
            video_url   : 'empty'
        }

        valideFormSubmit(validateFields);

        if ($('#new_gallery').prop('required') == true) {
            if ($('#new_gallery').val() != '' || $('#video_url').val() != '') {
                stepbystep('step-five');
            }
        } else {
            stepbystep('step-five');
        }
    });

    $('#back-one').on('click', function() {
        stepbystep('step-one');
    });
    $('#back-two').on('click', function() {
        if (main_vars.receiver_step == 1) {
            stepbystep('step-two');
        } else {
            stepbystep('step-one');
            $('#next-three').removeClass('display none').addClass('display inline-block')
        }
    });
    $('#back-three').on('click', function() {
        stepbystep('step-three');
    });

    $('#back-four').on('click', function() {
        stepbystep('step-four');
        if (main_vars.fundraising_step == 1 && $('.step-five').length > 0) {
            $('#finish-btn').removeClass('display inline-block').addClass('display none')
        }
    });

    // DISABLED BUTTON IF NOT VERIFY EMAIL
    if (main_vars.email_verify == 1) {
        $('#next-two, .signBtn, .citationBtn').addClass('disabled')
    }

    //SHADOW IMAGE
    if ($('#slideshow > div').length > 1) {
        $("#slideshow > div:gt(0)").hide();

        setInterval(function() {
            $('#slideshow > div:first')
                .fadeOut(1000)
                .next()
                .fadeIn(1000)
                .end()
                .appendTo('#slideshow');
        }, 6000);
    }

    // FIX MENU WHEN PASSED
    if (main_vars.type_menu != 'none') {
        $('.masthead').visibility({
            once: false,
            onBottomPassed: function() {
                $('.menu-home').removeClass('menu home-menu').addClass('fixed menu header-menu');
                $('.fixed-logo').transition('fade in').removeClass('display none').addClass('display block');
                $('.inverted-logo').transition('hide');

                if ( $('.signup-btn, .signup-btn-link').hasClass('inverted') && $('.signin-btn, .signin-btn-link').hasClass('inverted') ) {
                    $('.signup-btn, .signup-btn-link').removeClass('inverted button').addClass('green button signup-btn-style')
                    $('.signin-btn, .signin-btn-link').removeClass('inverted button').addClass('primary button');
                }
                if ( $('#add-petition-btn').hasClass('inverted') && main_vars.header_color == '#FFFFFF' ) {
                    $('#add-petition-btn').removeClass('inverted button').addClass('primary button submit-petition-btn');
                }
            },
            onBottomPassedReverse: function() {
                $('.menu-home').removeClass('fixed menu header-menu').addClass('menu home-menu');
                $('.fixed-logo').transition('hide').removeClass('display block').addClass('display none');
                $('.inverted-logo').transition('fade in');

                if ( !$('.signup-btn, .signup-btn-link').hasClass('inverted') && !$('.signin-btn, .signin-btn-link').hasClass('inverted') && main_vars.home_text_color == '#FFFFFF') {
                    $('.signup-btn, .signup-btn-link').removeClass('green button signup-btn-style').addClass('inverted button')
                    $('.signin-btn, .signin-btn-link').removeClass('primary button').addClass('inverted button')
                    $('.btn-modal').removeClass('inverted button').addClass('button signup-btn-style');
                }

                if ( !$('#add-petition-btn').hasClass('inverted') && main_vars.home_text_color == '#FFFFFF' ) {
                    $('#add-petition-btn').removeClass('primary button submit-petition-btn').addClass('inverted button');
                }
            }
        });
    }

    // FIX COMMENT BOX WHEN PASSED
    if (main_vars.is_mobile == 'false') {
        var comment_width = $('#content').width();
        var comments_list_height = $('#comments-list').height();
        var comment_content = $('#content-comment').val();
        $('#comments-list').visibility({
            once: false,
            onTopVisible: function() {
                if (comments_list_height > 600) {
                    $('#comment-sticky').removeClass('sticky').addClass('fixed bottom sticky').css('width', comment_width);
                    if (!comment_content) {
                        $('#content-comment').attr('rows', '1');
                    }

                    $('.comment-guest-info').transition('show').transition(main_vars.modal_transition);
                }
            },
            onTopVisibleReverse: function() {
                if (comments_list_height > 600) {
                    $('#comment-sticky').removeClass('fixed bottom sticky').addClass('sticky').removeAttr("style");
                    if (!comment_content) {
                        $('#content-comment').attr('rows', '5');
                    }

                    $('.comment-guest-info').transition('hide').transition(main_vars.modal_transition);
                }
            }
        });
    }

    // COMMENT FOLLOW HEIGHT
    $('.auto-height').bind('keydown', autosize);

    function autosize() {
        var el = this;
        setTimeout(function() {
            el.style.cssText = 'height:' + (el.scrollHeight + 2) + 'px;';
        }, 0);
    }

    // COMMENT GUEST
    $('#content-comment').on('click', function() {
        if ($('#comment-sticky').hasClass('fixed') && $('.comment-guest-info').hasClass('hidden')) {
            $('.comment-guest-info').transition(main_vars.modal_transition);
        }
    });

    $('#content-comment').on('keydown', function() {
        $('.send-comment').removeClass('button').addClass('primary button');
    });

    // GIVE TRIGGER OPEN MODAL WHEN CHANGE LEVEL
    $('.give-modal-strigger').on('click', function() {
        var level = $(this).attr('data-level');

        $('.give-btn.give-btn-modal').trigger('click');
        $('.give-btn-level-' + level).trigger('click')
    });

    // HIDEN NAVIGATION WHEN SCROLL
    var lastScrollTop = 0;
    var navHeight = $('.header-menu, .menu-home').height();
    $(window).scroll(function(event){
        var st = $(this).scrollTop();
        if (st > lastScrollTop && st >= navHeight){
            if (main_vars.type_menu == 'scroll') {
                $('.header-menu, .menu-home').removeClass('nav-down').addClass('nav-up');
            } else if (main_vars.type_menu == 'fixed') {
                $('#tab-sticky, #navigation-sticky').removeClass('nav-down').addClass('nav-up');
            }
            if (main_vars.mobile_sign_scroll == 1) {
                $('.mobile-sign-btn, .tablet-sign-btn').removeClass('sign-btn-down').addClass('sign-btn-up');
            }
        } else {
            if (main_vars.type_menu == 'scroll') {
                $('.header-menu, .menu-home').removeClass('nav-up').addClass('nav-down');
            } else if (main_vars.type_menu == 'fixed') {
                $('#tab-sticky, #navigation-sticky').removeClass('nav-up').addClass('nav-down');
            }
            if (main_vars.mobile_sign_scroll == 1) {
                $('.mobile-sign-btn, .tablet-sign-btn').removeClass('sign-btn-up').addClass('sign-btn-down');
            }
        }

        if (main_vars.type_menu == 'scroll') { 
            if (st < 80) {
                $('.header-menu').removeClass('header-shadow').addClass('header-border');
                $('.menu-home').removeClass('header-border header-shadow');
            } else {
                $('.header-menu').removeClass('header-border').addClass('header-shadow');
                $('.menu-home').removeClass('header-border').addClass('header-shadow');
            }
        }
        lastScrollTop = st;
    });

    // MENU NAVIGATION ACTIVE
    $(document).on("scroll", onScroll);

    function onScroll(event){
        var scrollPos = $(document).scrollTop();

        $('.navigation-menu a[href*=\\#]').each(function () {
            var currLink = $(this);
            var petition_id = currLink.attr('data-id');
            var refElement = $(currLink.attr("href"));
            if (refElement.length) {
                if (refElement.offset().top <= scrollPos && refElement.offset().top + refElement.height() > scrollPos) {
                    $('#navigation-menu' + petition_id + ' a').removeClass("active");
                    currLink.addClass("active");
                } else {
                    currLink.removeClass("active");
                }
            }
        });
    }

    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");
        
        $('a').each(function () {
            $(this).removeClass('active');
        })
        $(this).addClass('active');
        var target = this.hash,
        menu = target,
        $target = $(target);
              
       $('html, body').stop().animate({
            'scrollTop': ($target !== 'undefined' && $target.length ? $target.offset().top+2 : '')
        }, 600, 'swing', function () {
            window.location.hash = target;
            $(document).on("scroll", onScroll);
        });
    });

    // BACK TO TOP
    if ($('#back-to-top').length) {
        var scrollTrigger = 100, // px
            backToTop = function() {
                var scrollTop = $(window).scrollTop();
                if (scrollTop > scrollTrigger) {
                    $('#back-to-top').addClass('show');
                } else {
                    $('#back-to-top').removeClass('show');
                }
            };
        backToTop();
        $(window).on('scroll', function() {
            backToTop();
        });
        $('#back-to-top').on('click', function(e) {
            e.preventDefault();
            $('html,body').animate({
                scrollTop: 0
            }, 600);
        });
    }

    // LETTER EDIT FORM
    $('#edit-letter').on('click', function() {
        $('#content-letter').removeClass('display block').addClass('display none');
        $('.letter-editor').removeClass('display none').addClass('display block');
        $('#save-letter').removeClass('display none').addClass('display block');
        $('#edit-letter').removeClass('display block').addClass('display none');
    });

    // EDIT CUSTOM HEADING FOR SHARING
    $(document).on('click', '.heading-sharing', function() {
        var petition_id = $(this).attr('data-id');
        var heading = $(this).text();
        $(this).removeClass('display block').addClass('display none');
        $('#edit-heading' + petition_id).removeClass('display none').addClass('display block');
        $('#custom-heading' + petition_id).focus()
    });
    $(document).on('click', '.edit-heading', function() {
        $(this).removeClass('error');
    });
    
    // EDIT COMMENT FORM
    $(document).on('click', 'a.edit', function() {
        var comment_id = $(this).attr('data-id');
        var content_height = $('#comment-content-' + comment_id).height() + 20;
        var comment_content = $('#comment-content-' + comment_id).find('p').text();
        var html = '<div class="respon-message" id="comment-edit-message-' + comment_id + '"></div>' +
            '<div class="ui form"><div class="field">' +
            '<textarea rows="1" class="auto-height" id="comment-editor-' + comment_id + '" style="width: 100%; height: ' + content_height + 'px">' + comment_content + '</textarea>' +
            '</div>' +
            '<a href="javascript:void(0)" class="ui right floated mini button comment-edit-cancel" id="comment-edit-cancel-' + comment_id + '" data-id="' + comment_id + '">' + main_vars.cancel + '</a>' +
            ' <a href="javascript:void(0)" class="ui primary right floated mini button comment-edit-submit" id="comment-edit-submit-' + comment_id + '" data-id="' + comment_id + '"><i class="save icon"></i>' + main_vars.save + '</a>' +
            '</div>';
        $('#comment-content-' + comment_id).html(html).focus();
    });

    $(document).on('click', 'a.comment-edit-cancel', function() {
        var comment_id = $(this).attr('data-id');
        var content = $('#comment-editor-' + comment_id).val();
        content = content.replace(/\n\r?/g, '<br/>');
        $('#comment-content-' + comment_id).html(content);
    });

    // COPY TO CLIPBOARD
    $(document).on('click', '.copy-link', function() {
        var petition_id = $(this).attr('data-id');
        var prefix = $(this).attr('data-prefix');
        if (!prefix) {
            prefix = '';
        }
        copyToClipboardMsg(document.getElementById("short-link" + prefix + petition_id), 'msg-copy' + prefix + petition_id, '#copy-link' + prefix + petition_id);
    });
    $(document).on('click', '.copy-embed', function() {
        var petition_id = $(this).attr('data-id');
        copyToClipboardMsg(document.getElementById("embed-code" + petition_id), 'msg-embed-copy' + petition_id, '#copy-embed' + petition_id);
    });

    $(document).on('click', '.copy-html-embed', function() {
        var petition_id = $(this).attr('data-id');
        copyToClipboardMsg(document.getElementById("embed-html-code" + petition_id), 'msg-embed-copy' + petition_id, '#copy-html-embed' + petition_id);
    });

    $(document).on('click', '.copy-embed-share', function() {
        var petition_id = $(this).attr('data-id');
        copyToClipboardMsg(document.getElementById("embed-code-share" + petition_id), 'msg-embed-copy-share' + petition_id, '#copy-embed-share' + petition_id);
    });

    $(document).on('click', '.copy-html-embed-share', function() {
        var petition_id = $(this).attr('data-id');
        copyToClipboardMsg(document.getElementById("embed-html-code-share" + petition_id), 'msg-embed-copy-share' + petition_id, '#copy-html-embed-share' + petition_id);
    });

    // CALENDAR INIT
    $('#up_birthday').calendar({
        startMode: 'year',
        type: 'date',
    });

    var today = new Date();
    $('#update_scheduled_calendar').calendar({
        minDate: new Date(today.getFullYear(), today.getMonth(), today.getDate()),
    });

    // UPDATE DISPLAY NAME SELECTION
    function updateDisplayName() {
        $('.display-name').dropdown({
            values: [
                {
                    name: $('#firstnameUser').val(),
                    value: $('#firstnameUser').val(),
                },
                {
                    name     : $('#lastnameUser').val(),
                    value    : $('#lastnameUser').val(),
                },
                {
                    name: $('#firstnameUser').val() + ' ' + $('#lastnameUser').val(),
                    value: $('#firstnameUser').val() + ' ' + $('#lastnameUser').val(),
                    selected : true
                },
                {
                    name: $('#lastnameUser').val() + ' ' + $('#firstnameUser').val(),
                    value: $('#lastnameUser').val() + ' ' + $('#firstnameUser').val(),
                },
                {
                    name: $('#firstnameUser').val() + ' ' + $('#lastnameUser').val().charAt(0),
                    value: $('#firstnameUser').val() + ' ' + $('#lastnameUser').val().charAt(0),
                },
                {
                    name: $('#lastnameUser').val() + ' ' + $('#firstnameUser').val().charAt(0),
                    value: $('#lastnameUser').val() + ' ' + $('#firstnameUser').val().charAt(0),
                },
                {
                    name: $('#firstnameUser').val().charAt(0) + ' ' + $('#lastnameUser').val(),
                    value: $('#firstnameUser').val().charAt(0) + ' ' + $('#lastnameUser').val(),
                },
                {
                    name: $('#lastnameUser').val().charAt(0) + ' ' + $('#firstnameUser').val(),
                    value: $('#lastnameUser').val().charAt(0) + ' ' + $('#firstnameUser').val(),
                },
            ]
        });
    }

    $(document).on('change paste keyup', '#firstnameUser, #lastnameUser', function() {
        updateDisplayName();
    });

    // UPDATE VALUE TO FULL NAME FIELD
    function updateFullnameField(element_id) {
        var firstname = $(element_id.firstname).val();
        var lastname = $(element_id.lastname).val();
        $(element_id.fullname).val(firstname + ' ' + lastname);
    }

    $(document).on('change paste keyup', '.firstnameSign, .lastnameSign', function() {
        var petition_id = $(this).attr('data-id');
        updateFullnameField({
            firstname: '#firstnameSign' + petition_id,
            lastname: '#lastnameSign' + petition_id,
            fullname: '#nameSign' + petition_id,
        });
    });

    $(document).on('change paste keyup', '#firstnameSignup, #lastnameSignup', function() {
        updateFullnameField({
            firstname: '#firstnameSignup',
            lastname: '#lastnameSignup',
            fullname: '#nameSignup'
        });
    });

    // SLIMESCROLL
    $('#supporters-list, #region-list, #users-visitors-list, #users-players-list').slimScroll({
        height: '450px',
        size: '3px',
    });

    // GIVE TERM CHECK BUTTON
    if ($('input[name="give_agree_to_terms"]').length > 0) {
        $('#give-purchase-button').addClass('disabled');
        $(document).on('click', '.give-gateway-option', function() {
            $(document).ajaxStop(function() {
                if($('input[name="give_agree_to_terms"]').prop('checked')){       
                    $('#give-purchase-button').removeAttr('disabled').removeClass('disabled');
                } else {        
                    $('#give-purchase-button').attr("disabled", "disabled");   
                }
            });
        });
        $(document).on('click', 'input[name="give_agree_to_terms"]', function(){
            if($(this).prop('checked')){       
                $('#give-purchase-button').removeAttr('disabled').removeClass('disabled');
            } else {        
                $('#give-purchase-button').attr("disabled", "disabled");   
            }
        });
    }


    // FORM VALIDATION
    $('.send-comment').on('click', function() {
        $('.ui.form.comment-label').form({
            keyboardShortcuts: false,
            fields: {
              content_comment   : 'empty',
              comment_fullname  : 'empty',
              comment_email     : 'email',
            }
        });
        $('.ui.form.comment-label').form('validate form');
    });

    $('#finish-btn').on('click', function() {
        valideFormSubmit();
    });

    // validate submit donation form
    $('#submit-contribute').on('click', function() {
        valideFormSubmit({
            give_title                : 'empty',
            new_category              : 'empty',
            new_address               : 'empty',
            set_goal                  : 'empty',
            amount_level              : 'empty',
            custom_amount_minimum     : 'empty',
            name_level                : 'empty',
            form_content              : 'empty',
            new_tags                  : 'empty',
            goal_achieved_message     : 'empty',
            new_gallery               : 'empty',
            video_url                 : 'empty',
          }, 
          '.ui.form.submit-contribute',
        );
    });

    // validate submit petition form
    function valideFormSubmit(form_fields = false, element = false) {
        if (form_fields == false) {
            var form_fields = {
                new_title     : 'empty',
                new_category  : 'empty',
                new_goal_d    : 'empty',
                new_receiver  : 'empty',
                new_position  : 'empty',
                new_address   : 'empty',
                new_topics    : 'empty',
                new_content   : 'empty', 
                new_gallery   : 'empty',
                video_url     : 'empty',
            }
        }

        if (element == false) {
            element = '.ui.form.submit-petition';
        }

        // check required property
        $.each(form_fields, function(key, value) {
            if ($('#' + key).prop('required') == false) {
                delete form_fields[key];
            }
        });

        $(element).form({
            keyboardShortcuts: false,
            fields: form_fields,
        });
        $(element).form('validate form');

        return $(element).form('is valid');
    }

    // profile form validate fields
    var user_form_validation = $.parseJSON(main_vars.user_form_validation);

    $('.updateProfileBtn').on('click', function() {
        $('.ui.form.update-profile').form({
            keyboardShortcuts: false,
            fields: {
              firstnameUser     : 'empty',
              lastnameUser      : 'empty',
              emailUser         : ['email', 'empty'], 
              genderUser        : user_form_validation.gender,
              birthdayUser      : user_form_validation.birthday, 
              addressUser       : user_form_validation.address,
              countryUser       : user_form_validation.country,
              phoneUser         : user_form_validation.phone,
              phoneCode         : user_form_validation.phoneCode,
              zipUser           : user_form_validation.zip
            }
        });
        $('.ui.form.update-profile').form('validate form');
    });

    // sign update validate fields
    $('#submitSignup').on('click', function() {
        $('.ui.form.sign-up').form({
            keyboardShortcuts: false,
            fields: {
                firstnameSignup : 'empty',
                lastnameSignup  : 'empty',
                nameSignup      : 'empty',
                usernameSignup  : 'empty',
                emailSignup     : ['email', 'empty'],
                passSignup      : ['minLength[6]', 'empty'],
                repassSignup    : 'match[passSignup]',
                phoneSignup     : user_form_validation.phone,
                phoneCode       : user_form_validation.phoneCode,
                birthdaySignup  : user_form_validation.birthday,
                genderSignup    : user_form_validation.gender,
                addressSignup   : user_form_validation.address,
                countrySignup   : user_form_validation.country,
                zipSignup       : user_form_validation.zip,
            }
        });
        $('.ui.form.sign-up').form('validate form');
    });

    // check repeat password when type is match
    repeatPasswordValidation('passSignup', 'repassSignup', '.ui.form.sign-up');
    repeatPasswordValidation('newpassUser', 'repassUser', '.ui.form.change-password');
    function repeatPasswordValidation(password, repeatPassword, formClass) {
        $('#' + repeatPassword).on("change paste keyup", function(){
            $(formClass).form({
                keyboardShortcuts: false,
                fields: {
                    match: {
                        identifier  : repeatPassword,
                        rules: [
                          {
                            type   : 'match[' + password + ']',
                            prompt : main_vars.repeat_password_wrong,
                          }
                        ]
                    },
                }
            });
    
            if ($(this).val().length >= 8) {
                $(formClass).form('validate form');
            }
        });
    }

    // sign in form validate fields
    $('#submitSignin').on('click', function() {
        $('.ui.form.sign-in').form({
            keyboardShortcuts: false,
            fields: {
              usernameSignin  : 'empty',
              passwordSignin  : 'empty',
            }
        });

        $('.ui.form.sign-in').form('validate form');
    });

    // guest sign petition form validate fields
    $(document).on('click', 'a.submitSign, a.submitSignSC, a.submitSignSidebar', function() {
        var petition_id = $(this).attr('data-id');
        var guest_form_validation = $.parseJSON(main_vars.guest_form_validation);

        var validate_fields = {
            keyboardShortcuts: false,
            fields: {
                firstnameSign   : 'empty',
                lastnameSign    : 'empty',
                nameSign        : 'empty',
                emailSign       : 'empty',
                addressSign     : guest_form_validation.addressSign,
                zipSign         : guest_form_validation.zipSign,
                countrySign     : guest_form_validation.countrySign,
                phonecodeSign   : guest_form_validation.phonecodeSign,
            }
        };
        
        $('#guestSignForm' + petition_id + ', #guestSignFormSC' + petition_id + ', #guestSignFormSidebar' + petition_id).form(validate_fields);
        $('#guestSignForm' + petition_id + ', #guestSignFormSC' + petition_id + ', #guestSignFormSidebar' + petition_id).form('validate form');
    });

    // submit citation form validate fieds
    $('.submitCitation').on('click', function() {
        $('.ui.form.citation-form').form({
            keyboardShortcuts: false,
            fields: {
                citation_title      : 'empty',
                citation_content    : 'empty',
                citation_reference  : 'empty',
            }
        });
        $('.ui.form.citation-form').form('validate form');
    });


    // COOKIE SET GET
    function setCookie(key, value, expiry) {
        var expires = new Date();
        expires.setTime(expires.getTime() + (expiry * 60 * 1000));
        document.cookie = key + '=' + value + ';expires=' + expires.toUTCString() + ';path=/';
    }

    function getCookie(key) {
        var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
        return keyValue ? keyValue[2] : null;
    }

    function eraseCookie(key) {
        var keyValue = getCookie(key);
        setCookie(key, keyValue, '-1');
    }

    // PASSWORD STRENGTH CHECKER
    var password_strength_text = $.parseJSON(main_vars.password_strength_text);
    if (password_strength_text.password_strength == 1) {
        passwordStrengthChecker('.password-strength', '.password-strength-progress');
    }

    function passwordStrengthChecker(element, progress_element) {
        let state = false;
        let password = $(element);

        password.on("change paste keyup", function(){
            let pass = $(element).val();
            checkStrength(pass, progress_element);
        });
    }

    function checkStrength(password, element) {
        var password_strength_text = $.parseJSON(main_vars.password_strength_text);

        let passwordStrength = $(element);
        let passwordStrengthLabel = $(element + '-label');
        let passwordStrengthLevel = $('.password-strength-level');
        let lowUpperCase = $(".low-upper-case i");
        let number = $(".one-number i");
        let specialChar = $(".one-special-char i");
        let eightChar = $(".eight-character i");

        let strength = 0;

        //If password contains both lower and uppercase characters
        if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) {
            strength += 1;
            lowUpperCase.removeClass('dot');
            lowUpperCase.addClass('check green');
        } else {
            lowUpperCase.addClass('dot');
            lowUpperCase.removeClass('check green');
        }
        //If it has numbers and characters
        if (password.match(/([0-9])/)) {
            strength += 1;
            number.removeClass('dot');
            number.addClass('check green');
        } else {
            number.addClass('dot');
            number.removeClass('check green');
        }
        //If it has one special character
        if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) {
            strength += 1;
            specialChar.removeClass('dot');
            specialChar.addClass('check green');
        } else {
            specialChar.addClass('dot');
            specialChar.removeClass('check green');
        }
        //If password is greater than 7
        if (password.length > 7) {
            strength += 1;
            eightChar.removeClass('dot');
            eightChar.addClass('check green');
        } else {
            eightChar.addClass('dot');
            eightChar.removeClass('check green');   
        }

        // If value is less than 2
        if (strength == 1) {
            passwordStrength.progress({
                percent: 20,
                label: ''
            });
            passwordStrengthLabel.text(password_strength_text.very_weak)
            passwordStrengthButton(strength)
        } else if (strength == 2) {
            passwordStrength.progress({
                percent: 40,
                label: ''
            });
            passwordStrengthLabel.text(password_strength_text.weak)
            passwordStrengthButton(strength)
        } else if (strength == 3) {
            passwordStrength.progress({
                percent: 70,
                label: '',
            });
            passwordStrengthLabel.text(password_strength_text.medium)
            passwordStrengthButton(strength)
        } else if (strength == 4) {
            passwordStrength.progress({
                percent: 100,
                label: '',
            });
            passwordStrengthLabel.text(password_strength_text.strong)
            passwordStrengthButton(strength)
        }

        // append strength index to input field
        passwordStrengthLevel.val(strength);
    }

    function passwordStrengthButton(strength) {
        var password_strength_text = $.parseJSON(main_vars.password_strength_text);
        let passwordStrengthBtn = $('.password-strength-btn');

        if (strength < password_strength_text.acceptable_strength) {
            passwordStrengthBtn.addClass('disabled')
        } else {
            passwordStrengthBtn.removeClass('disabled')
        }
    }


    // COPY TO CLIPBOARD
    function copyToClipboardMsg(elem, msgElem, btnElem) {
        var succeed = copyToClipboard(elem);
        var msg;
        var msg_text;

        if (!succeed) {
            msg = '<i class="remove icon"></i>' + main_vars.copy_clipboard_err;
            mes_text =  main_vars.copy_clipboard_err;
        } else {
            msg = '<i class="checkmark icon"></i>' + main_vars.copy_clipboard;
            msg_text = main_vars.copy_clipboard;
        }
        if (typeof msgElem === "string") {
            msgElem = document.getElementById(msgElem);
        }
        $(btnElem).attr('data-tooltip', msg_text);
        $(btnElem).attr('data-inverted', true);
        $(btnElem).attr('data-position', 'top right');

        // msgElem.innerHTML = msg;
        setTimeout(function() {
            // msgElem.innerHTML = "";
            $(btnElem).removeAttr('data-tooltip').removeAttr('aria-label').removeAttr('data-inverted').removeAttr('data-position');
            $(btnElem).removeClass('hint--top');
        }, 2000);
    }

    function copyToClipboard(elem) {
        // create hidden text element, if it doesn't already exist
        var targetId = "_hiddenCopyText_";
        var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
        var origSelectionStart, origSelectionEnd;
        if (isInput) {
            // can just use the original source element for the selection and copy
            target = elem;
            origSelectionStart = elem.selectionStart;
            origSelectionEnd = elem.selectionEnd;
        } else {
            // must use a temporary form element for the selection and copy
            target = document.getElementById(targetId);
            if (!target) {
                var target = document.createElement("textarea");
                target.style.position = "absolute";
                target.style.left = "-9999px";
                target.style.top = "0";
                target.id = targetId;
                document.body.appendChild(target);
            }
            target.textContent = elem.textContent;
        }
        // select the content
        var currentFocus = document.activeElement;
        target.focus();
        target.setSelectionRange(0, target.value.length);

        // copy the selection
        var succeed;
        try {
            succeed = document.execCommand("copy");
        } catch (e) {
            succeed = false;
        }
        // restore original focus
        if (currentFocus && typeof currentFocus.focus === "function") {
            currentFocus.focus();
        }

        if (isInput) {
            // restore prior selection
            elem.setSelectionRange(origSelectionStart, origSelectionEnd);
        } else {
            // clear temporary content
            target.textContent = "";
        }
        return succeed;
    }

    // RESPONSIVE 
    $(window).resize(function() {
        var width = $(window).width();
        if (width < 991) {
            $('#dashboard-sidebar-menu').sidebar({transition: 'overlay', dimPage: false}).sidebar('hide')
            $('.sign-sticky, .review-form, .donate-sticky').removeClass('ui sticky')

            setTimeout(function() {
                $('.sign-sticky, .review-form, .donate-sticky').parent().removeAttr('style')
            }, 600);            
        }
        if (width > 991) {
            $('#dashboard-sidebar-menu').sidebar({transition: 'overlay', dimPage: false, duration: 0}).sidebar('show')
            $('.sign-sticky, .review-form, .donate-sticky').addClass('ui sticky')
        }
    });
    if ($(window).width() < 991) {
        $('#dashboard-sidebar-menu').sidebar({transition: 'overlay', dimPage: false}).sidebar('hide')
    }
    
})(jQuery);