(function($) {
    "use strict";

    // AUTO LOAD NEXT POST
    $('body').on( 'alnp-post-loaded', function( e, params ) {
        loadUpdateInit();
        loadCitationInit();
        loadSupportersInit('supporters');
        loadSupportersInit('donors');
        shortlinkInit();
        guestSignAddressAutocomplete();
    });

    function loadBlockPreview() {
        initVictoryPetitionSlider();
    }

    // Run when a block preview is done loading.
    $( document ).on( 'mb_blocks_preview/victory-slider', loadBlockPreview );

    // SHOW RESER PASSWORD MODAL
    function urlParam(name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results == null) {
            return null;
        } else {
            return results[1] || 0;
        }
    }

    function getPathFromUrl(url) {
        return url.split("?")[0];
    }

    function re_init_lazy_load() {
        $('.lazy').Lazy({
            effect: 'fadeIn',
            onFinishedAll: function() {
                $('.lazy').removeClass('lazy')
            }
        });

        // re init avatar popup
        $('.supporter-avatar').popup();
    }

    // get form data
    function getFormObj(formId, post_id = '') {
        var formObj = {};
        var inputs = $('#' + formId + post_id).serializeArray();
        $.each(inputs, function (i, input) {
            formObj[input.name] = input.value;
        });
        return formObj;
    }

    // SIGN PETITION AS GUEST
    function guestSign(petition_id, submitBtnId = 'submitSign', signMessage = 'signMessage', guestSignForm = '') {
        var security = $('#securitySignup').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        if (guestSignForm == '') {
            var guestSignForm = getFormObj('guestSignForm', petition_id);
        }

        var name = guestSignForm.nameSign;
        if (name == '') {
            var name = guestSignForm.firstnameSign + ' ' + guestSignForm.lastnameSign;
        }
        
        var email = guestSignForm.emailSign;
        var username = generateUsername(email);
        var pass = guestSignForm.passSign;
        var address = guestSignForm.addressSign;
        var city = guestSignForm.citySign;
        var state = guestSignForm.stateSign;
        var neighborhood = guestSignForm.neighborhoodSign;
        var country = guestSignForm.countrySign;
        var lat = guestSignForm.latSign;
        var lng = guestSignForm.lngSign;
        var zip = guestSignForm.zipSign;
        var phone_code = guestSignForm.phonecodeSign;
        var phone = guestSignForm.phoneSign;
        var comment = guestSignForm.signComment;
        var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();

        if (guestSignForm.emailNotice == 'on') {
            var notice = 1;
        } else {
            var notice = 0;
        }

        if (guestSignForm.signAnonymous != 'on') {
            var anonymous = 1;
        } else {
            var anonymous = 0;
        }

        if (guestSignForm.citationInstant == 'on') {
            var citation_instant = true;
        } else {
            var citation_instant = false;
        }

        $('#' + submitBtnId + petition_id).addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_user_signup_form',
                'signup_user': username,
                'signup_name': name,
                'signup_email': email,
                'signup_pass': pass,
                'signup_repass': pass,
                'signup_address': address,
                'signup_city': city,
                'signup_state': state,
                'signup_neighborhood': neighborhood,
                'signup_country': country,
                'signup_lat': lat,
                'signup_lng': lng,
                'signup_zip': zip,
                'signup_phone_code': phone_code,
                'signup_phone': phone,
                'petition_id': petition_id,
                'comment': comment,
                'notice': notice,
                'anonymous': anonymous,
                'g-recaptcha-response': grecaptcha_res,
                'security': security
            },
            success: function(data) {
                $('#' + submitBtnId + petition_id).removeClass('loading disabled');

                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
                if (data.status === true) {
                    $('#submitSignin').attr('data-id', petition_id);
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="notched circle loading icon"></i>' + data.message +
                        '</div>';
                    $('#usernameSignin').val(data.username);
                    $('#passwordSignin').val(pass);
                    $('#signSignin').val(1);
                    $('#' + signMessage + petition_id).empty().append(message);
                    if (!services_vars.is_user_logged_in && $('.citation-form').length && citation_instant == true) {
                        $('#citationModal').attr('data-id', petition_id).modal('show');
                        $('.submitCitation').attr('data-id', petition_id);
                        services_vars.user_id = data.ID;
                    } else {
                        userSignin(0, petition_id, guestSignForm);
                    }
                } else {
                    var message = '<div class="ui ' + ((data.verification === true) ? 'success' : 'warning') + ' message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                    $('#' + signMessage + petition_id).empty().append(message);

                    if (data.verification === true) {
                        $('#usernameSignin').val(data.username);
                        $('#passwordSignin').val(pass);
                        $('#submitSignin').attr('data-id', petition_id);
                        $('#signSignin').val(2);

                        if (!services_vars.is_user_logged_in && $('.citation-form').length && citation_instant == true) {
                            $('#citationModal').attr('data-id', petition_id).modal('show');
                            $('.submitCitation').attr('data-id', petition_id);
                            services_vars.user_id = data.ID;
                        } else {
                            userSignin(0, petition_id, guestSignForm);
                        }
                    }

                    if ($('#accord-guest-sign').children().hasClass('active') == false) {
                        $('#accord-guest-sign').children().trigger('click')
                    }

                    // redirect if user sign petition without login
                    if (data.add_sign == 'nologin') {
                        if (services_vars.action_after_sign == 'refresh') {
                            document.location.href = window.location.href;
                        } else if (services_vars.action_after_sign == 'redirect') {
                            document.location.href = $('#sign-successful-url' + petition_id).val();
                        } else if (services_vars.action_after_sign == 'modal') {
                            $('#sign-successful-modal' + petition_id).modal('show');
                            $('.social-share .button').popup();
                        }
                    }
                }
            },
            error: function(errorThrown) {
                $('#' + submitBtnId + petition_id).removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
            }
        });
    }

    // Loop init submit sign form
    var elements = [
        {
          class: '.submitSign',
          form: 'guestSignForm',
          action: 'submitSign',
          message: 'signMessage'
        },
        {
          class: '.submitSignSC',
          form: 'guestSignFormSC',
          action: 'submitSignSC',
          message: 'signMessageSC'
        },
        {
          class: '.submitSignSidebar',
          form: 'guestSignFormSidebar',
          action: 'submitSignSidebar',
          message: 'signMessageSidebar'
        }
    ];
      
    elements.forEach(function(element) {
        $(document).on('click', element.class, function() {
            var petition_id = $(this).attr('data-id');
            var guestSignForm = getFormObj(element.form, petition_id);
            guestSign(petition_id, element.action, element.message, guestSignForm);
        });
    });      

    $('#nameSign, #firstnameSign, #lastnameSign, #emailSign, #passSign').keydown(function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            guestSign();
            $('.ui.form.guest-sign').form('validate form');
        }
    });

    // USER SIGN UP
    function userSignup() {
        var name = $('#nameSignup').val();
        var email = $('#emailSignup').val();
        var username = generateUsername(email);
        var pass = $('#passSignup').val();
        var repass = $('#repassSignup').val();
        var strength = $('#strengthSignup').val();
        var phone_code = $('#phoneCode').val();
        var phone_number = $('#phoneSignup').val();
        var gender = $('#genderSignup').val();
        var birthday = $('#birthdaySignup').val();
        var address = $('#addressSignup').val();
        var zip = $('#zipSignup').val();
        var city = $('#citySignup').val();
        var state = $('#stateSign').val();
        var neighborhood = $('#neighborhoodSignup').val();
        var country = $('#countrySignup').val();
        var lat = $('#latSignup').val();
        var lng = $('#lngSignup').val();
        var newsletter = $('#signupNewsletter').is(':checked');
        var form_referrent = $('#formReferrent').val();
        var security = $('#securitySignup').val();
        var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        if (name == '') {
            var name = $('#firstnameSignup').val() + ' ' + $('#lastnameSignup').val();
        }

        if (newsletter) {
            newsletter = 1;
        } else {
            newsletter = 0;
        }

        $('#submitSignup').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_user_signup_form',
                'signup_user': username,
                'signup_name': name,
                'signup_email': email,
                'signup_pass': pass,
                'signup_repass': repass,
                'signup_strength': strength,
                'signup_phone_code': phone_code,
                'signup_phone': phone_number,
                'signup_birthday': birthday,
                'signup_gender': gender,
                'signup_address': address,
                'signup_zip': zip,
                'signup_city': city,
                'signup_state': state,
                'signup_neighborhood': neighborhood,
                'signup_country': country,
                'signup_lat': lat,
                'signup_lng': lng,
                'signup_newsletter': newsletter,
                'form_referrent': form_referrent,
                'g-recaptcha-response': grecaptcha_res,
                'security': security
            },
            success: function(data) {
                $('#submitSignup').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#usernameSignin').val(data.username);
                    $('#passwordSignin').val(pass);
                    $('#signSignin').val(0);
                    $('#signinMessage, #signMessage').empty().append(message);
                    userSignin(0);
                } else {
                    var message = '<div class="ui ' + ((data.verification === true) ? 'success' : 'error') + ' message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                    $('#signinMessage').empty().append(message);

                    if (data.verification === true) {
                        $('#usernameSignin').val(data.username);
                        $('#passwordSignin').val(pass);
                        userSignin(0);
                    }
                }
            },
            error: function(errorThrown) {
                $('#submitSignup').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
            }
        });
    }

    $('#submitSignup').on('click', function() {
        userSignup();
    });

    $('#nameSignup, #firstnameSignup, #lastnameSignup, #emailSignup, #passSignup, #repassSignup').keydown(function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            userSignup();
            $('.ui.form.sign-up').form('validate form');
        }
    });

    // GENERATE USERNAME FROM EMAIL OR USE FIELD
    function sanitizeUser(username, strict = true) {
        let rawUsername = username;
        let sanitizedUsername = username
          .replace(/<\/?[^>]+(>|$)/g, "") // Remove any HTML tags
          .replace(/%([a-f0-9]{2})/gi, "") // Remove URL-encoded octets
          .replace(/&.+?;/g, "") // Remove HTML entities
          .normalize("NFD")
          .replace(/[\u0300-\u036f]/g, ""); // Remove diacritical marks
      
        if (strict) {
          sanitizedUsername = sanitizedUsername.replace(/[^a-z0-9 _.\-@]/gi, ""); // Remove non-alphanumeric, space, underscore, period, hyphen, or at symbol
        }
      
        sanitizedUsername = sanitizedUsername.trim().replace(/\s+/g, " "); // Trim and collapse multiple spaces into a single space
      
        return sanitizedUsername;
    }

    function generateUsername(email = false) {
        if ($('#usernameSignup').length > 0) {
            var username = $('#usernameSignup').val();
            if (username == '') {
                username = email.split('@', 2);
                username = username[0];
            }
        } else {
            var username = email.split('@', 2);
                username = username[0];
        }
        
        var random_number = Math.floor(1000 + Math.random() * 9000);
        var username = sanitizeUser(username);
        return username + random_number;
    }

    // USER LOGIN
    function userSignin(recaptcha = 1, petition_id = '', form_data = '') {
        var comment = '';
        if (petition_id != '') {
            var recaptcha = 0;
            var guestSignForm = form_data;
            var comment = guestSignForm.signComment;

            if (guestSignForm.emailNotice == 'on') {
                var notice = 1;
            } else {
                var notice = 0;
            }

            if (guestSignForm.signAnonymous != 'on') {
                var anonymous = 1;
            } else {
                var anonymous = 0;
            }

            var remember = $('#rememberSigninPetition').val();
        } else {
            var petition_id = $('#petition_id').val();
            if (petition_id == '') {
                petition_id = services_vars.post_id;
            }

            if ($('.email-notice').length && $('.email-notice').hasClass('checked')) {
                var notice = 1;
            } else {
                var notice = 0;
            }

            if ($('.sign-anonymous').length && !$('.sign-anonymous').hasClass('checked')) {
                var anonymous = 1;
            } else {
                var anonymous = 0;
            }

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

        var username = $('#usernameSignin').val();
        var password = $('#passwordSignin').val();
        var security = $('#securitySignin').val();
        var referent = window.location.href;
        var signature = $('#signSignin').val();
        var referer_id = $('#refererID').val();
        
        var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        $('#submitSignin').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_user_signin_form',
                'post_id': petition_id,
                'signin_user': username,
                'signin_pass': password,
                'remember': remember,
                'referent': referent,
                'referer_id': referer_id,
                'signature': signature,
                'comment': comment,
                'recaptcha': recaptcha,
                'g-recaptcha-response': grecaptcha_res,
                'notice': notice,
                'anonymous': anonymous,
                'security': security
            },
            success: function(data) {
                $('#submitSignin').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#signinMessage, #signMessage' + petition_id).empty().append(message);
                    document.location.href = data.referent;
                } else {
                    if (data.provider != false) {
                        var message = '<div class="ui info message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                        $('#signinMessage').empty().append(message);
                        document.location.href = data.redirect;
                    } else {
                        var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                        $('#signinMessage').empty().append(message);
                    }
                }
            },
            error: function(errorThrown) {
                $('#submitSignin').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
            }
        });
    }

    $('#submitSignin').on('click', function() {
        var petition_id = $(this).attr('data-id');
        userSignin(0, petition_id);
    });

    $('#usernameSignin, #passwordSignin').keydown(function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            userSignin();
            $('.ui.form.sign-in').form('validate form');
        }
    });

    // FORGOT PASSWORD
    function forgotPassword() {
        var email = $('#emailForgot').val();
        var postID = $('#postID').val();
        var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();
        var security = $('#securityForgot').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        $('#submitForgot').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_forgot_pass_form',
                'forgot_email': email,
                'security': security,
                'g-recaptcha-response': grecaptcha_res,
                'postid': postID
            },

            success: function(data) {
                $('#submitForgot').removeClass('loading disabled');
                $('#emailForgot').val('');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#forgotMessage, #resetPassMessage').empty().append(message)
                    $('#forgot-password').modal('hide')
                    $('#resetpass').modal('show')
                    $('#resetLogin').val(data.login)

                    if ($('#reset_pass_link').length) {
                        document.location.href = $('#reset_pass_link').val() + '&username=' + email;
                    }
                } else {
                    var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                    $('#forgotMessage').empty().append(message)
                }
            },
            error: function(errorThrown) {
                $('#submitForgot').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
            }
        });
    }

    $('#submitForgot').on('click', function() {
        forgotPassword();
    });

    $('#emailForgot').keydown(function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            forgotPassword();
        }
    });


    if (urlParam('action') && urlParam('action') == 'rp') {
        setTimeout(function(){
            $('#resetpass').modal('show')
            $('#resetKey').val(urlParam('key')).parent().addClass('disabled')
        }, 600)
    }

    // RESET PASSWORD
    function resetPassword() {
        var pass_1 = $('#resetPass_1').val();
        var pass_2 = $('#resetPass_2').val();
        var key = urlParam('key') || $('#resetKey').val();
        var login = urlParam('login') || $('#resetLogin').val();
        var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();
        var security = $('#securityResetpass').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var toast_settings = $.parseJSON(services_vars.toast);

        if ($('#username').length) {
            login = $('#username').val();
        }

        $('#submitResetPass').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_reset_pass_form',
                'pass_1': pass_1,
                'pass_2': pass_2,
                'key': key,
                'login': login,
                'g-recaptcha-response': grecaptcha_res,
                'security': security
            },

            success: function(data) {
                $('#submitResetPass').removeClass('loading disabled');
                $('#resetPass_1').val('');
                $('#resetPass_2').val('');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#resetpass').modal('hide');
                    $('#signinModal').modal('show').on('shown.bs.modal', function(e) {
                        $('#signinMessage').empty().append(message);
                    });
                    $('#signinModal').modal('show');
                    $('#userLoginForm').removeClass('display none').addClass('display block');
                    $('#userSignupForm').removeClass('display block').addClass('display none');
                    $('#signin-button').removeClass('display block').addClass('display none');
                    $('#signup-button').removeClass('display none').addClass('display inline-block');

                    if ($('#login_page_link').length) {
                        document.location.href = $('#login_page_link').val();
                    }

                    if (data.reset == false) {
                        $('#toast-reset-pass-success').toast({
                            position: toast_settings.position,
                            transition: toast_settings.transition,
                            displayTime: toast_settings.displayTime,
                            newestOnTop: toast_settings.newestOnTop,
                            compact: toast_settings.compact,
                        });
                    }
                } else {
                    var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                    $('#resetPassMessage').empty().append(message);
                }
            },
            error: function(errorThrown) {
                $('#submitResetPass').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
            }
        });
    }

    $('#submitResetPass').on('click', function() {
        resetPassword();
    });

    $('#resetKey, #resetPass_1, #resetPass_2').keydown(function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
            resetPassword();
        }
    });


    // RESEN VERIFICATION EMAIL
    $(document).on('click', '#resend-email', function() {
        $('#resend-email').addClass('loading disabled');
        resendVerificationEmail('new');
    });

    function resendVerificationEmail(type = 'new') {
        var security = $('#securityResendVerification').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var success = false;
        var toast_settings = $.parseJSON(services_vars.toast);

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_resend_verification_email',
                'user_id': services_vars.user_id,
                'type': type,
                'security': security
            },

            success: function(data) {
                $('#resend-email').removeClass('loading disabled');
                success = true;
                if (data.status === true) {
                    $('#resend-email').children('i').removeClass('send').addClass('checkmark');
                    $('#toast-resend-email-success').toast({
                        position: toast_settings.position,
                        transition: toast_settings.transition,
                        displayTime: toast_settings.displayTime,
                        newestOnTop: toast_settings.newestOnTop,
                        compact: toast_settings.compact,
                    });
                } else {
                    $('#resend-email').children('i').removeClass('send').addClass('remove');
                    $('#toast-resend-email-failed').toast({
                        position: toast_settings.position,
                        transition: toast_settings.transition,
                        displayTime: toast_settings.displayTime,
                        newestOnTop: toast_settings.newestOnTop,
                        compact: toast_settings.compact,
                    });
                }
            },
            error: function(errorThrown) {
                $('#resend-email').removeClass('loading disabled');
                $('#resend-email').children('i').removeClass('send').addClass('remove');
            }
        });

        return success;
    }

    // FACEBOOK LOGIN
    $('#fbLoginBtn').on('click', function() {
        $('.signinFBText').addClass('loading disabled');
        fbLogin();
    });

    function fbLogin(connect = false) {
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                var newUser = getUserInfo(function(user) {
                    var newUserAvatar = getUserPhoto(function(photo) {
                        wpFBLogin(user, photo);
                    });
                });
            } else if (response.status === 'not_authorized') {
                FB.login(function(response) {
                    if (response.authResponse) {
                        var newUser = getUserInfo(function(user) {
                            var newUserAvatar = getUserPhoto(function(photo) {
                                wpFBLogin(user, photo);
                            });
                        });
                    } else {
                        $('.signinFBText').removeClass('loading disabled');
                        var message = '<div class="ui error message">' +
                            '<i class="close icon"></i><i class="warning circle icon"></i>' + services_vars.fb_login_error +
                            '</div>';
                        $('#signinMessage').empty().append(message);
                    }
                }, {
                    scope: 'email, public_profile'
                });
            } else {
                FB.login(function(response) {
                    if (response.authResponse) {
                        var newUser = getUserInfo(function(user) {
                            var newUserAvatar = getUserPhoto(function(photo) {
                                wpFBLogin(user, photo);
                            });
                        });
                    } else {
                        $('.signinFBText').removeClass('laoding disabled');
                        var message = '<div class="ui error message">' +
                            '<i class="close icon"></i><i class="warning circle icon"></i>' + services_vars.fb_login_error +
                            '</div>';
                        $('#signinMessage').empty().append(message);
                    }
                }, {
                    scope: 'email, public_profile'
                });
            }
        });
    }

    function getUserInfo(callback) {
        FB.api('/me', {
            fields: 'name, first_name, middle_name, last_name, email, cover'
        }, function(response) {
            callback(response);
        });
    }

    function getUserPhoto(callback) {
        FB.api(
            '/me/picture',
            'GET',
            {"redirect":"false", "type":"large"},
            function(response) {
                callback(response.data.url);
            }
        )
    }

    function wpFBLogin(user, photo) {
        var userid = user.id;
        var username = user.first_name;
        username = username.toLowerCase().replace(' ', '') + userid;
        var cover = '';
        var referent = $('input[name="_wp_http_referer"]').val();
        var security = $('#securitySignin').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        if ($('.socialConnect').length > 0) {
            wpSocialConnect(user.email, 'facebook_connection');
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_facebook_login',
                'user_id': userid,
                'signin_user': username,
                'full_name': user.name,
                'first_name': user.first_name,
                'last_name': user.last_name,
                'email': user.email,
                'birthday': user.birthday,
                'gender': user.gender,
                'cover': cover,
                'avatar': photo,
                'security': security
            },
            success: function(data) {
                $('.signinFBText').removeClass('laoding disabled');
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#signinMessage').empty().append(message);
                    if (services_vars.oauth_url) {
                        document.location.href = services_vars.oauth_url + '?redirect=' + referent;
                    }
                } else {
                    var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                    $('#signinMessage').empty().append(message);
                }
            },
            error: function(errorThrown) {
                $('.signinFBText').removeClass('laoding disabled');
            }
        });
    }

    // GOOGLE SIGN IN
    var oneTapClient = undefined;
    if (services_vars.is_user_logged_in == 0 && services_vars.google_signin == 1 || services_vars.is_account_page == 1) {
        $(window).on('load', function() {
            onLibraryLoaded()
        });

        function onLibraryLoaded() {
            google.accounts.id.initialize({
                client_id: services_vars.google_client_id,
                callback: handleCredentialResponse
            });

            if (services_vars.is_account_page == 1) {
                google.accounts.id.renderButton(
                    document.getElementById("googleConnectButton"),
                    { theme: "outline", size: "large", text: "continue_with", locale: services_vars.site_locale, shape: "pill"}  // customization attributes
                );
                google.accounts.id.renderButton(
                    document.getElementById("googleDisconnectButton"),
                    { theme: "filled_blue", size: "large", text: "continue_with", locale: services_vars.site_locale, shape: "pill"}  // customization attributes
                );
            } else {
                google.accounts.id.renderButton(
                    document.getElementById("googleSigninButton"),
                    { theme: "filled_blue", size: "large", text: "continue_with", locale: services_vars.site_locale, shape: "pill"}  // customization attributes
                );
                oneTapClient = google.accounts.id.prompt();
            }
        }
    }

    function handleCredentialResponse(response) {
        if (response.credential) {
            var credential = response.credential;
            var credential = JSON.parse(atob(credential.split('.')[1]));
            var resp = {
                id: credential.sub,
                fullname: credential.name,
                give_name: credential.given_name,
                family_name: credential.family_name,
                avatar: credential.picture,
                email: credential.email
        };

        handleGoogleResponse(resp);
        }
    }

    // Function isUserSignedIn() and showCurrentUserInfo() can be removed as they are not used in the new flow.

    function signOut() {
    google.accounts.id.disableAutoSelect();
    // Additional sign-out logic if needed
    }

    // Remaining code stays the same
    function handleGoogleResponse(resp) {
    var userid = resp.id;
    var username = resp.give_name;
    var fullname = resp.fullname;
    var firstname = resp.give_name;
    var lastname = resp.family_name;
    var email = resp.email;
    var avatar = resp.avatar;
    var referent = $('input[name="_wp_http_referer"]').val();
    var security = $('#securitySignin').val();
    var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

    if ($('.socialConnect').length > 0) {
        wpSocialConnect(email, 'google_connection');
    }

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: ajaxURL,
        data: {
        'action': 'conikal_google_signin',
        'userid': userid,
        'signin_user': username,
        'full_name': fullname,
        'first_name': firstname,
        'last_name': lastname,
        'email': email,
        'avatar': avatar,
        'security': security
        },
        success: function(data) {
        $('#googleSigninBtn').removeClass('loading disabled');
        if (data.status === true) {
            var message = '<div class="ui success message">' +
                '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                '</div>';
            $('#signinMessage').empty().append(message);
            if (services_vars.oauth_url) {
            document.location.href = services_vars.oauth_url + '?redirect=' + referent;
            }
        } else {
            var message = '<div class="ui error message">' +
                '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                '</div>';
            $('#signinMessage').empty().append(message);
        }
        },
        error: function(errorThrown) {
        $('#googleSigninBtn').removeClass('loading disabled');
        }
    });
    }


    function wpSocialConnect(email, social = 'facebook_connection') {
        var referent = $('input[name="_wp_http_referer"]').val();
        var security = $('#securitySignin').val();
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_social_connection',
                'user_id': services_vars.user_id,
                'social': social,
                'email': email,
                'security': security
            },
            success: function(data) {
                $('.socialConnect').removeClass('laoding disabled');
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#signinMessage').empty().append(message);
                    document.location.href = referent;
                } else {
                    var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                    $('#signinMessage').empty().append(message);
                }
            },
            error: function(errorThrown) {
                $('.socialConnect').removeClass('laoding disabled');
            }
        });
    }

    /* FACEBOOK PUBLISH TO WALL
    function fbPublish() {
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                fbPost();
            } else if (response.status === 'not_authorized') {
                FB.login(function(response) {
                    if (response.authResponse) {
                        fbPost();
                    }
                }, {
                    scope: 'publish_actions'
                });
            } else {
                FB.login(function(response) {
                    if (response.authResponse) {
                        fbPost();
                    }
                }, {
                    scope: 'publish_actions'
                });
            }
        });
    }


    function fbPost() {
        var content = $('.sign-comment').val();
        if (content == '') {
            content = $('.fb-message-share').val();
        }
        var url = $('#petition_url').val();

        FB.api('/me/feed', 'POST', {
                message: content,
                link: url
            },
            function(response) {
                if (response && !response.error) {
                    $('.postFB').removeClass('disabled loading');
                    $('.postFB').children('i').removeClass('facebook').addClass('checkmark');
                } else {
                    $('.postFB').removeClass('disabled loading');
                }
            });
    }*/

    // FACEBOOK SHARING POPUP
    function fbSharing(petition_id) {
        // url post
        var url = $('#petition_url' + petition_id).val();
        if (!url) {
            url = window.location.href;
        }
        // content message share
        var content = $('#sign-comment' + petition_id).val();
        if (content == '') {
            content = $('#fb-message-share' + petition_id).val();
        }
        // post hastags
        var hashtag = $('#hashtag' + petition_id).val();

        FB.ui({
            method: 'share',
            display: 'popup',
            href: url,
            quote: content,
            hashtag: hashtag,
        }, function(response){
            console(response);
        });
    }

    $(document).on('click', '.share-facebook', function(){
        var petition_id = $(this).attr('data-id');
        var social      = $(this).data('social');
        shareCounterUpdate(petition_id, social);
        fbSharing(petition_id);
    });

    // FACEBOOK SEND MESSAGE POPUP
    function fbSending(petition_id) {
        var url = $('#petition_url' + petition_id).val();
        if (!url) {
            url = window.location.href;
        }
        FB.ui({
            method: 'send',
            link: url,
        }, function(response){
            console(response);
        });
    }

    $(document).on('click', '.send-message', function(){
        var petition_id = $(this).attr('data-id');
        var social      = $(this).data('social');
        shareCounterUpdate(petition_id, social);
        fbSending(petition_id);
    });

    function handleNoGeolocation(errorFlag) {
        if (errorFlag) {
            alert('Error: The Geolocation service failed.');
        } else {
            alert('Error: Your browser doesn\'t support geolocation.');
        }
    }

    function formatPrice(nStr) {
        nStr += '';
        var x = nStr.split('.');
        var x1 = x[0];
        var x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    }

    // NOTIFICATION SEEN
    var toast_settings = $.parseJSON(services_vars.toast);
    $('#toast-welcome').toast({
        position: toast_settings.position,
        transition: toast_settings.transition,
        displayTime: toast_settings.displayTime,
        closeIcon: true,
        newestOnTop: toast_settings.newestOnTop,
        compact: toast_settings.compact,
        onApprove : function() {
            notificationSeen('user_welcome_seen');
        },
        onDeny : function() {
            notificationSeen('user_welcome_seen');
        }
    });

    function notificationSeen(type) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityNotificationSeen').val();

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_notification_seen',
                'user_id': services_vars.user_id,
                'notification': type,
                'security': security
            },
            success: function(data) {

            }
        });
    }

    // USER'S OPTIONS SAVE
    function signUserOption(id, option, checkbox = true, reload = false) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityGeneral').val();

        var user_id = $(id).attr('data-post-id');
        if (!user_id) {
            var user_id = services_vars.user_id;
        }

        if (checkbox == true) {
            if ($(id + ' :input').is(":checked")) {
                var value = 1;
            } else {
                var value = 0;
            }
        } else {
            var value = $(id).val();
        }

        var result = false;
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_set_sign_user_option',
                'user_id': user_id,
                'option': option,
                'value': value,
                'security': security
            },
            success: function(data) {
                var result = true;
                if (reload && data.status == true) {
                    document.location.href = window.location.href;
                }
            }
        });

        return result;
    }

    if (services_vars.is_user_logged_in) {
        $(document).on('click', '.fb-publish', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption('#fb-publish' + petition_id, 'fb_publish') 
        });
        $(document).on('click', '.citation-instant', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption('#citation-instant' + petition_id, 'citation_instant')
        });
        $(document).on('click', '.email-notice', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption('#email-notice' + petition_id, 'notice') 
        });
        $(document).on('click', '.sign-anonymous', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption('#sign-anonymous' + petition_id, 'anonymous') });
        $(document).on('click', '.show-phone', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption( '.show-phone', 'show_phone')
        });
        $(document).on('click', '.show-birthday', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption('.show-birthday', 'show_birthday') 
        });
        $(document).on('click', '.show-join-date', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption('.show-join-date', 'show_join_date') 
        });
        $(document).on('click', '.show-visitor-statistics', function() { 
            var petition_id = $(this).attr('data-id')
            signUserOption('.show-visitor-statistics', 'show_visitor_statistics') 
        });
    }

    $(document).on('change', '#country-selected', function() {
        var country_code = $('#country-selected').val();
        if (country_code.length <= 2 || country_code == 'WORLD') {
            if (services_vars.is_user_logged_in) {  
                var setCountrySelected = signUserOption('#country-selected', 'country_selected', false, true);
            } else {
                // remember country selected in 7 days
                setCookie('conikal_country_selected', country_code, (7 * 60 * 24))
                document.location.href = window.location.href;
            }
        }
    });

    // GET BITLY SHORT URL
    // shortlinkInit();
    function shortlinkInit(){
        $('.short-link').each(function() {
            var petition_id = $(this).attr('data-id');
            var on_load = $(this).attr('data-load');
            if (on_load != 1) {
                get_short_url(petition_id);
            }
        });
    }
    
    function get_short_url(petition_id) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        if (petition_id == '') {
            petition_id = services_vars.post_id;
        }
        
        var security = $('#securityShare' + petition_id).val();

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_share_counter',
                'post_id': petition_id,
                'security': security
            },
            success: function(data) {
                $('#short-link' + petition_id).attr('data-load', 1);
                if (data.status === true) {
                    $('#short-link' + petition_id).val(data.url).attr('data-load', 1);
                }
            }
        });
    }

    // UPDATE SHARE COUNTER
    $(document).on('click', '.share-button-counter', function() {
        var id      = $(this).data('id');
        var social  = $(this).data('social');
        shareCounterUpdate(id, social);
    });
    
    function shareCounterUpdate(petition_id, social = 'facebook') {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        if (petition_id == '') {
            petition_id = services_vars.post_id;
        }
        
        var security = $('#securityShare' + petition_id).val();

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_share_counter',
                'post_id': petition_id,
                'social': social,
                'security': security
            },
            success: function(data) {
                if (data.status === true) {
                    // Update new total share number to divicer counter
                    $('#share-number' + petition_id + ', #share-numberSC' + petition_id + ', #share-numberSidebar' + petition_id).text(' ' + data.total);
                
                    // Get the string containing the number
                    var share_element = $('#' + social + '-share-button' + petition_id + ', #' + social + '-share-buttonSC' + petition_id + ', #' + social + '-share-buttonSidebar' + petition_id);
                    var share_counter = $('#' + social + '-share-counter' + petition_id + ', #' + social + '-share-counterSC' + petition_id + ', #' + social + '-share-counterSidebar' + petition_id);
                    var share_string  = share_element.data('content');
                    
                    if (!share_string) {
                        share_string = share_counter.text();
                    }

                    // Use a regular expression to replace the number with a new value
                    var newShareNumber = data.counter[social]; // The new number you want to replace with
                    var updatedString = share_string.replace(/\d+/, newShareNumber);

                    // Update the string in the element using jQuery
                    if (share_element.data('content')) {
                        $(share_element).attr('data-content', updatedString);
                    } else {
                        $(share_counter).text(updatedString);
                    }
                }
            }
        });
    }

    // UPDATE INDENTIFY DOCUMENT
    if (urlParam('tab') == 'indentify') {
        $('.updateIndentifyBtn').on('click', function() {
            var document_side = urlParam('upload');
            var upload_action = $(this).attr('upload-action');
            var field_required = 1;
            if (upload_action == 1) {
                field_required = 0;
            }
            updateIndentifyDocument(document_side, field_required);
        });
    }

    function updateIndentifyDocument(document_side, field_required = 1) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityUserProfile').val();
        var indentifyForm = getFormObj('indentifyForm');

        $('#up_response').empty();
        $('.updateIndentifyBtn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_update_indentify_document',
                'user_id': services_vars.user_id,
                'field_required': field_required,
                'indentify_type': indentifyForm.indentify_type,
                'indentify_name': indentifyForm.indentify_name,
                'indentify_id': indentifyForm.indentify_id,
                'indentify_country_issue': indentifyForm.indentify_country_issue,
                'document_side': document_side,
                'document_url': indentifyForm.new_gallery,
                'document_attch_id': indentifyForm.new_attach,
                'security': security
            },
            success: function(data) {
                $('.updateIndentifyBtn').attr('upload-action', 0).removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                } else {
                    var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                }
                $('#up_response').empty().html(message)
                $('html,body').animate({ scrollTop: 0 }, 300)
            }
        });
    }


    // UPDATE PROFILE
    $('.updateProfileBtn').on('click', function() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityUserProfile').val();
        var typeUser = $('input[name="typeUser"]:checked').val();
        $('#up_response').empty();
        $('.updateProfileBtn').addClass('loading disabled');
        var toast_settings = $.parseJSON(services_vars.toast);

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_update_user_profile',
                'user_id': $('#idUser').val(),
                'type': typeUser,
                'name': $('#nameUser').val(),
                'firstname': $('#firstnameUser').val(),
                'lastname': $('#lastnameUser').val(),
                'gender': $('#genderUser').val(),
                'nickname': $('#nicknameUser').val(),
                'email': $('#emailUser').val(),
                'birthday': $('#birthdayUser').val(),
                'address': $('#addressUser').val(),
                'neighborhood': $('#neighborhoodUser').val(),
                'state': $('#stateUser').val(),
                'city': $('#cityUser').val(),
                'country': $('#countryUser').val(),
                'lat': $('#latUser').val(),
                'lng': $('#lngUser').val(),
                'zip': $('#zipUser').val(),
                'phone_code': $('#phoneCode').val(),
                'phone': $('#phoneUser').val(),
                'organization_name': $('#organizationName').val(),
                'website': $('#websiteUser').val(),
                'bio': $('#bioUser').val(),
                'old_password': $('#oldpassUser').val(),
                'new_password': $('#newpassUser').val(),
                're_password': $('#repassUser').val(),
                'avatar': $('#new_gallery').val(),
                'avatar_id': $('#new_attach').val(),
                'decision_id': $('#decision_id').val(),
                'decision_title': $('#titleUser').val(),
                'decision_organization': $('#organizationUser').val(),
                'security': security
            },
            success: function(data) {
                $('.updateProfileBtn').removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';

                    // send new verification email
                    if ($('#emailUser').val() != $('#oldemailUser').val()) {
                        resendVerificationEmail('change');
                        $('#oldemailUser').val($('#emailUser').val());
                    }

                    $('#toast-update-profile-success').toast({
                        position: toast_settings.position,
                        transition: toast_settings.transition,
                        displayTime: toast_settings.displayTime,
                        newestOnTop: toast_settings.newestOnTop,
                        compact: toast_settings.compact,
                    });
                } else {
                    var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                }
                $('#up_response').empty().html(message)
                $('#decision_id').val(data.decision_id)
                if (data.decision_id != '') {
                    $('#indentify-tab-link').removeClass('display none');
                } else {
                    $('#indentify-tab-link').addClass('display none');
                }

                if (typeUser === 'petitioner') $('#decision_status').empty()
                $('html,body').animate({ scrollTop: 0 }, 300)
            },
            error: function(errorThrown) {
                $('.updateProfileBtn').removeClass('loading disabled');
            }
        });
    });

    // DELETE ACCOUNT
    $('#delAccountBtn').on('click', function() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityUserProfile').val();
        $('#delete-account-response').empty();
        $('#delAccountBtn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_delete_account',
                'user_id': services_vars.user_id,
                'confirm_password': $('#confirm_password').val(),
                'reassign': $('#reassign').val(),
                'security': security
            },
            success: function(data) {
                $('#delAccountBtn').removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    document.location.href = services_vars.home_url;
                } else {
                    var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                }
                $('#delete-account-response').empty().html(message)
            },
            error: function(errorThrown) {
                $('#delAccountBtn').removeClass('loading disabled');
            }
        });
    });

    // UPDATE FINANCIAL INFOMATION
    $('#saveFinancialBtn').on('click', function() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityFinancial').val();
        $('#financial-response').empty();
        $('#saveFinancialBtn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_financial_infomation',
                'user_id': services_vars.user_id,
                'paypal_fullname': $('#fn_paypal_fullname').val(),
                'paypal_email': $('#fn_paypal_email').val(),
                'payoneer_email': $('#fn_payoneer_email').val(),
                'payoneer_card': $('#fn_payoneer_card').val(),
                'bitcoin_network': $('#fn_bitcoin_network').val(),
                'bitcoin_address': $('#fn_bitcoin_address').val(),
                'bank_fullname': $('#fn_bank_fullname').val(),
                'bank_user_address': $('#fn_bank_user_address').val(),
                'bank_name': $('#fn_bank_name').val(),
                'bank_address': $('#fn_bank_address').val(),
                'bank_swift_code': $('#fn_bank_swift_code').val(),
                'bank_account_number': $('#fn_bank_account_number').val(),
                'confirm_password': $('#fn_confirm_password').val(),
                'security': security
            },
            success: function(data) {
                $('#saveFinancialBtn').removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                } else {
                    var message = '<div class="ui warning message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                }
                $('#financial-response').empty().html(message)
                $('html,body').animate({ scrollTop: 0 }, 300)
            },
            error: function(errorThrown) {
                $('#saveFinancialBtn').removeClass('loading disabled');
            }
        });
    });

    // SUBMIT WITHDRAW
    $('#submitWithdrawBtn').on('click', function() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityWithdraw').val();
        $('#withdraw-response').empty();
        $('#submitWithdrawBtn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_submit_withdraw',
                'user_id': services_vars.user_id,
                'withdraw_amount': $('#withdraw_amount').val(),
                'withdraw_type': $('input[name="withdraw_type"]:checked').val(),
                'withdraw_method': $('input[name="withdraw_method"]:checked').val(),
                'confirm_password': $('#confirm_password').val(),
                'security': security
            },
            success: function(data) {
                $('#submitWithdrawBtn').removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    var message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    document.location.href = window.location.href
                } else {
                    var message = '<div class="ui warning message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                }
                $('#withdraw-response').empty().html(message)
                $('html,body').animate({ scrollTop: 0 }, 300)
            },
            error: function(errorThrown) {
                $('#submitWithdrawBtn').removeClass('loading disabled');
            }
        });
    });

    // GET CONTENT OF PETITION
    function get_tinymce_content(id) {
        if ($('#isDesc').length > 0) {
            var content;
            var inputid = id;
            tinyMCE.triggerSave();
            var editor = tinyMCE.get(inputid);
            var textArea = jQuery('textarea#' + inputid);
            if (textArea.length > 0 && textArea.is(':visible')) {
                content = textArea.val();
            } else {
                content = editor.getContent();
            }
            return content;
        } else {
            return '';
        }
    }

    // SUBMIT PETITION
    $('#finish-btn').on('click', function() {
        if ($('#new_gallery').prop('required') == true && $('#new_id').val() == '') {
            if ($('#new_gallery').val() != '' || $('#video_url').val() != '') {
                submitPetition();
            }
        } else {
            submitPetition();
        }
    });

    if ($("#new_content").length && services_vars.editor_style == 'markdown') {
        var petitionContent = new SimpleMDE({ 
            element: $("#new_content")[0],
            spellChecker: services_vars.spell_checker == 1 ? true : false,
        });

        // update content to hidden textarea
        petitionContent.codemirror.on("change", function(){
            $("#new_content").val(petitionContent.value());
        });
    }

    if ($("#new_letter").length && services_vars.editor_style == 'markdown') {
        var letterContent = new SimpleMDE({ 
            element: $("#new_letter")[0],
            spellChecker: services_vars.spell_checker == 1 ? true : false,
        });
    }

    function submitPetition() {
        if (services_vars.editor_style == 'markdown') {
            var new_content = petitionContent.value();
        } else {
            var new_content = get_tinymce_content('new_content');
        }

        var receiver = '';
        $('input[name="new_receiver[]"]').each(function(index) {
            receiver += $(this).val() + ',';
        });
        var position = '';
        $('input[name="new_position[]"]').each(function(index) {
            position += $(this).val() + ',';
        });
        var decisionmakers = '';
        $('input[name="new_decisionmakers[]"]').each(function(index) {
            decisionmakers += $(this).val() + ',';
        });
        var category_ids = '';
        if ($('#category_id').length > 0) {
            category_ids = $('#new_category').val();
        } else if ($('#new_category').val() != '') {
            $('#new_category').each(function(index) {
                category_ids += $(this).val() + ',';
            });
        }

        var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();

        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securitySubmitPetition').val();
        $('#finish-btn').addClass('loading disabled');

        var request_params = {
            'action': 'conikal_save_petition',
            'new_id': $('#new_id').val(),
            'user': $('#current_user').val(),
            'title': $('#new_title').val(),
            'content': new_content,
            'heading': $('#new_heading').val(),
            'excerpt': $('#new_excerpt').val(),
            'category': category_ids,
            'topics': $('#new_topics').val(),
            'city': $('#new_city').val(),
            'lat': $('#new_lat').val(),
            'lng': $('#new_lng').val(),
            'address': $('#new_address').val(),
            'neighborhood': $('#new_neighborhood').val(),
            'state': $('#new_state').val(),
            'country': $('#new_country').val(),
            'zip': $('#new_zip').val(),
            'receiver': receiver,
            'position': position,
            'decisionmakers': decisionmakers,
            'goal': $('#new_goal_d').val(),
            'video': $('#new_video').val(),
            'thumb': $('#new_thumb').val(),
            'thumb_small': $('#new_thumb_small').val(),
            'gallery': $('#new_gallery').val(),
            'attach': $('#new_attach').val(),
            'status': $('#new_status').val(),
            'sendinblue_list': $('#sendinblue_list').val(),
            'g-recaptcha-response': grecaptcha_res,
            'security': security
        }

        if ($('#new_letter').length) { 
            if (services_vars.editor_style == 'markdown') {
                var new_letter = letterContent.value();
            } else {
                var new_letter = get_tinymce_content('new_letter');
            }
            // add letter content if letter form exist
            request_params.letter = new_letter;
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: request_params,
            success: function(data) {
                var message = '';
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
                if (data.status === true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';
                    $('#save-response').empty().append(message);
                    if (services_vars.fundraising_step == 1 && $('.step-five').length > 0 && $('#new_id').val() == '') {
                        $('#petition_id').val(data.petition_id);
                        submitContribute();
                    } else {
                        $('#finish-btn').removeClass('loading disabled');
                        
                        // redirect after submit
                        document.location.href = data.propLink;
                    }
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle large icon"></i>' + data.message +
                        '</div>';
                    $('#save-response').empty().append(message);
                    $('#finish-btn').removeClass('loading disabled');
                }
                $('#save_response').html(message);
                $('html,body').animate({ scrollTop: 0 }, 300);
            },
            error: function(errorThrown) {
                $('#finish-btn').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
            }
        });
    }

    // SUBMIT CONTRIBUTE & DONATION
    $('#submit-contribute').on('click', function() {
        if ($('#new_gallery').prop('required') == true && $('#form_id').val() == '') {
            if ($('#new_gallery').val() != '' || $('#video_url').val() != '') {
                submitContribute();
            }
        } else {
            submitContribute();
        }
    });

    if ($("#form_content").length && services_vars.editor_style == 'markdown') {
        var formContent = new SimpleMDE({ 
            element: $("#form_content")[0],
            spellChecker: services_vars.spell_checker == 1 ? true : false,
        });

        // update content to hidden textarea
        formContent.codemirror.on("change", function(){
            $("#form_content").val(formContent.value());
        });
    }

    function submitContribute() {
        if ($("#form_content").length && services_vars.editor_style == 'markdown') {
            var form_content = formContent.value();
        } else if ($("#form_content").length) {
            var form_content = get_tinymce_content('form_content');
        } else {
            var form_content = '';
        }

        var amount_level = $('input[name="amount_level[]"]').map(function () {
            return $(this).val();
        }).get();

        var name_level = $('input[name="name_level[]"]').map(function () {
            return $(this).val();
        }).get();

        var description_level = $('textarea[name="description_level[]"]').map(function () {
            return $(this).val();
        }).get();

        var goal_option = 'disabled';
        if ( $('#goal_option').checkbox('is checked') ) {
            goal_option = 'enabled';
        }

        var draft_status = '';
        if ( $('#draft_status').checkbox('is checked') ) {
            draft_status = 'draft';
        }

        var form_title = $('#give_title').val();
        if (form_title == '') {
            form_title = $('#new_title').val();
        }

        var category_ids = '';
        if ($('#category_id').length > 0) {
            category_ids = $('#new_category').val();
        } else if ($('#new_category').val() != '') {
            $('#new_category').each(function(index) {
                category_ids += $(this).val() + ',';
            });
        }

        var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();

        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securitySubmitContribute').val();
        $('#submit-contribute').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_give_save_form',
                'user_id': services_vars.user_id,
                'form_id': $('#form_id').val(),
                'petition_id': $('#petition_id').val(),
                'title': form_title,
                'category': category_ids,
                'tags': $('#new_tags').val(),
                'city': $('#new_city').val(),
                'lat': $('#new_lat').val(),
                'lng': $('#new_lng').val(),
                'address': $('#new_address').val(),
                'neighborhood': $('#new_neighborhood').val(),
                'state': $('#new_state').val(),
                'country': $('#new_country').val(),
                'zip': $('#new_zip').val(),
                'excerpt': $('#give_excerpt').val(),
                'goal_option': goal_option,
                'draft_status': draft_status,
                'set_goal': $('#set_goal').val(),
                'goal_format': $('#goal_format').val(),
                'button_label': $('#button_label').val(),
                'close_form_when_goal_achieved': $('#close_form_when_goal_achieved').val(),
                'goal_achieved_message': $('#goal_achieved_message').val(),
                'amount_level': amount_level,
                'name_level': name_level,
                'description_level': description_level,
                'custom_amount_minimum': $('#custom_amount_minimum').val(),
                'form_content': form_content,
                'video': $('#new_video').val(),
                'thumb': $('#new_thumb').val(),
                'thumb_small': $('#new_thumb_small').val(),
                'gallery': $('#new_gallery').val(),
                'attach': $('#new_attach').val(),
                'g-recaptcha-response': grecaptcha_res,
                'security': security
            },
            success: function(data) {
                $('#submit-contribute, #finish-btn').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
                var message = '';
                if (data.status == true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';
                    $('#save-response').empty().append(message);

                    // redirect after submit
                    document.location.href = data.link;
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle large icon"></i>' + data.message +
                        '</div>';
                    $('#save-response').empty().append(message);
                }
                $('#save_response').html(message);
                $('html,body').animate({ scrollTop: 0 }, 300);
            },
            error: function(errorThrown) {
                $('#submit-contribute').removeClass('loading disabled');
                if (services_vars.recaptcha == 1) {
                    conikalReCaptchaReset();
                }
            }
        });
    }

    // SET NEW GOAL
    $('#approve-goal').on('click', function() {
        var post_id = $(this).attr('data-id');
        var goal = $('#new-goal').val();
        setGoal(post_id, goal);
    });

    function setGoal(post_id, goal) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        $('#approve-goal').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_set_goal',
                'post_id': post_id,
                'goal': goal,
                'security': security
            },
            success: function(data) {
                $('#approve-goal').removeClass('loading disabled');
            },
            error: function(errorThrown) {
                $('#approve-goal').removeClass('loading disabled');
            }
        });
    }

    // SET AUTO INCREASE GOAL PERCENT
    $('#set-auto-increase-btn').on('click', function() {
        var post_id = $(this).attr('data-id');
        var percent = $('#increase-percent').val();
        setIncreasePercent(post_id, percent);
    });

    function setIncreasePercent(post_id, percent) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        $('#set-auto-increase-btn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_set_auto_increase_goal_percent',
                'post_id': post_id,
                'percent': percent,
                'security': security
            },
            success: function(data) {
                $('#set-auto-increase-btn').removeClass('loading disabled');
                $('#set-auto-increase-confirm').modal('hide')
            },
            error: function(errorThrown) {
                $('#set-auto-increase-btn').removeClass('loading disabled');
            }
        });
    }

    // ADD CO-AUTHOR
    $('#add-co-author-btn').on('click', function() {
        var post_id = $(this).attr('data-id');
        var co_author = $('#co_author').val();
        addCoAuthor(post_id, co_author, 'add');
    });

    $('#remove-co-author-btn').on('click', function() {
        var post_id = $(this).attr('data-id');
        var co_author = $(this).attr('data-author');
        $(this).addClass('loading disabled');
        addCoAuthor(post_id, co_author, 'remove');
    });

    function addCoAuthor(post_id, co_author, type) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        $('#add-co-author-btn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_add_co_author',
                'post_id': post_id,
                'type': type,
                'co_author': co_author,
                'security': security
            },
            success: function(data) {
                var message = '';
                $('#add-co-author-btn').removeClass('loading disabled');
                if (data.status === true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';
                    $('#add-co-author-modal').modal('hide')
                    document.location.href = window.location.href;
                    
                    if(type == 'remove') {
                        $('#co-author-' + co_author).empty();
                        $('#remove-co-author-btn').removeClass('loading disabled');
                    }
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';
                }
                $('#add-co-author-response').empty().append(message);
            },
            error: function(errorThrown) {
                $('#add-co-author-btn').removeClass('loading disabled');
            }
        });
    }

    // REOPEN AND CLOSE PETITION
    $('#approve-reopen').on('click', function() {
        var post_id = $(this).attr('data-id');
        statusPetition('#approve-reopen', post_id, 0);
    });

    $('#approve-close').on('click', function() {
        var post_id = $(this).attr('data-id');
        statusPetition('#approve-close', post_id, 2);
    });

    function statusPetition(id, post_id, status) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        $(id).addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_status_petition',
                'post_id': post_id,
                'status': status,
                'security': security
            },
            success: function(data) {
                $(id).removeClass('loading disabled');
                document.location.href = data.link;
            },
            error: function(errorThrown) {
                $(id).removeClass('loading disabled');
            }
        });
    }

    // ADD UPDATE PETITION
    $('#submitUpdate').on('click', function() {
        postUpdate();
    });

    if ($("#update_content").length && services_vars.editor_style == 'markdown') {
        var updateContent = new SimpleMDE({ 
            element: $("#update_content")[0],
            spellChecker: services_vars.spell_checker == 1 ? true : false,
        });
    }

    function postUpdate() {
        if (services_vars.editor_style == 'markdown') {
            var update_content = updateContent.value();
        } else {
            var update_content = get_tinymce_content('update_content');
        }

        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityUpdate').val();
        $('#submitUpdate').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_add_update_petition',
                'user_id': services_vars.user_id,
                'post_id': services_vars.post_id,
                'update_id': $('#update_id').val(),
                'petition_status': $('#petition_status').val(),
                'title': $('#update_title').val(),
                'content': update_content,
                'type': $('#update_type').val(),
                'media': $('#update_media').val(),
                'graph_title': $('#graph_title').val(),
                'graph_description': $('#graph_description').val(),
                'graph_image': $('#graph_image').val(),
                'graph_site': $('#graph_site').val(),
                'petition_id': $('#petition_id').val(),
                'gallery': $('#new_gallery').val(),
                'video': $('#new_video').val(),
                'thumb': $('#new_thumb').val(),
                'thumb_small': $('#new_thumb_small').val(),
                'attach': $('#new_attach').val(),
                'notification': $('input[name="update_notification"]:checked').val(),
                'scheduled': $('#update_scheduled').val(),
                'campaign_id': $('#campaign_id').val(),
                'campaign_status': $('#campaign_status').val(),
                'security': security
            },
            success: function(data) {
                var message = '';
                var campaign_message = '';
                var update = '';
                $('#submitUpdate').removeClass('loading disabled');
                if (data.status === true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';

                    if (data.campaign != false) {
                        if (data.campaign.status == true) {
                            campaign_message = '<div class="ui success message display block">' +
                            '<i class="close icon"></i><i class="check circle large icon"></i>' + data.campaign.message +
                            '</div>';
                        } else {
                            campaign_message = '<div class="ui error message display block">' +
                            '<i class="close icon"></i><i class="check circle large icon"></i>' + data.campaign.message +
                            '</div>';
                        }
                    }
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';
                    $('html,body').animate({ scrollTop: 0 }, 300);
                }
                $('#update-response').empty().append(message);
                $('#campaign-response').empty().append(campaign_message);

                if (data.status == true) {
                    $('#update_id').val(data.ID);
                    if(data.status == true && (data.campaign == false || data.campaign.status == true)) {
                        document.location.href = data.link;
                    }
                }
            },
            error: function(errorThrown) {
                $('#submitUpdate').removeClass('loading disabled');
            }
        });
    }

    // DELETE UPDATE PETITION
    $(document).on('click', 'a.delete-update', function() {
        var update_id = $(this).attr('data-id');
        deleteUpdate(update_id);
    });

    function deleteUpdate(update_id) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityUpdate').val();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_delete_update',
                'update_id': update_id,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {
                    $('#update-' + update_id).fadeOut(300);
                }
            }
        });
    }

    // ADD CITATION
    $(document).on('click', '.submitCitation', function() {
        var petition_id = $(this).attr('data-id');
        if (petition_id == '' || petition_id == 'undefined') {
            petition_id = $('#petition_id').val();
        }
        var redirection = $(this).attr('data-redirection');
        addCitation(petition_id, redirection);
    });

    if ($("#citation_content").length && services_vars.editor_style == 'markdown') {
        var citationContent = new SimpleMDE({ 
            element: $("#citation_content")[0],
            spellChecker: services_vars.spell_checker == 1 ? true : false,
        });
    }

    function addCitation(petition_id = '', redirection = 0) {
        if (services_vars.editor_style == 'markdown') {
            var citation_content = citationContent.value();
        } else {
            var citation_content = get_tinymce_content('citation_content');
        }

        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityCitation').val();
        $('.submitCitation').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_add_citation_petition',
                'user_id': services_vars.user_id,
                'post_id': services_vars.post_id,
                'citation_id': $('#citation_id').val(),
                'title': $('#citation_title').val(),
                'content': citation_content,
                'opinion': $('input[name=citation_opinion' + petition_id + ']:checked').val(),
                'reference': $('#citation_reference').val(),
                'graph_title': $('#graph_title').val(),
                'graph_description': $('#graph_description').val(),
                'graph_image': $('#graph_image').val(),
                'graph_site': $('#graph_site').val(),
                'petition_id': petition_id,
                'gallery': $('#new_gallery').val(),
                'video': $('#new_video').val(),
                'thumb': $('#new_thumb').val(),
                'thumb_small': $('#new_thumb_small').val(),
                'attach': $('#new_attach').val(),
                'security': security
            },
            success: function(data) {
                var message = '';
                var campaign_message = '';
                var update = '';
                $('.submitCitation').removeClass('loading disabled');
                if (data.status === true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';

                    if ($('#citation_id').val() != '' || redirection == 1) {
                        document.location.href = data.link;
                    } else {
                        // hide modal
                        setTimeout(function() {
                            $('#citationModal').modal('hide');
                        }, 300)

                        if ($('#signBtn' + petition_id).length) {
                            $('#citation-opinion' + petition_id).addClass('display none');
                            $('#citationBtn' + petition_id).parent().addClass('display none');
                            $('#signBtn' + petition_id).trigger('click').parent().removeClass('display none');
                        }

                        $('#citation-opinion-progress' + petition_id).attr('data-value', data.opinion_number.yes).attr('data-total', data.opinion_number.total).progress();
                        $('#citation-fact-score' + petition_id).text(data.opinion_number.percent);

                        $('#citations' + petition_id).removeClass('display none');
                        $('#citation-list' + petition_id).empty();
                        loadCitations(0, petition_id);

                        // remove value input
                        $(".citation-form input").each(function(){
                            $(this).val('');
                        });
                        $('#citation-link-preview').addClass('display none');
                        citationContent.value('');

                        // hide sign sidebar on mobile
                        $('#sign-sidebar' + petition_id).sidebar('toggle');

                        var $target = $('#citations' + petition_id);
                        $('html, body').stop().animate({
                            'scrollTop': ($target !== 'undefined' && $target.length ? $target.offset().top-100 : '')
                        }, 600, 'swing');

                        if (!services_vars.is_user_logged_in && $('#citation-form').length) {
                            userSignin(0, petition_id); 
                        }

                        if (services_vars.is_mobile) {
                            $('#close-mobile-sign').trigger('click')
                        }
                    }
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="check circle large icon"></i>' + data.message +
                        '</div>';
                }
                $('#citation-response').empty().append(message);
            },
            error: function(errorThrown) {
                $('.submitCitation').removeClass('loading disabled');
            }
        });
    }

    // EDIT CITATION
    $(document).on('click', 'a.edit-citation', function() {
        var citation_id = $(this).attr('data-id');
         $('#citationModal').modal('show');
    });

    // DELETE CITATION
    $(document).on('click', 'a.delete-citation', function() {
        var citation_id = $(this).attr('data-id');
        deleteCitation(citation_id);
    });

    function deleteCitation(citation_id) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityCitation').val();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_delete_citation',
                'citation_id': citation_id,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {
                    $('#citation-' + citation_id).fadeOut(300);
                }
            }
        });
    }

    // LOAD MORE CITATIONS
    loadCitationInit()
    function loadCitationInit() {
        if ($('.citation-list').length) {
            $('.citation-list').each(function(id) {
                var petition_id = $(this).attr('data-id');
                var on_load = $(this).attr('data-load');
                if (on_load != 1) {
                    loadCitations(0, petition_id);
                }
            });
        }
    }

    $(document).on('click', '.citations-more', function() {
        var petition_id = $(this).attr('data-id');
        var offset = $(this).attr('data-offset');
        loadCitations(offset, petition_id);
    }); 

    function loadCitations(offset, petition_id) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityCitation').val();

        $('#citations-more' + petition_id).addClass('loading disabled');

        if (petition_id == '') {
            var petition_id = services_vars.post_id;
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_load_citations_petition',
                'user_id': services_vars.user_id,
                'post_id': petition_id,
                'offset': offset,
                'security': security
            },
            success: function(data) {
                $('#citations-more' + petition_id).removeClass('loading disabled');
                $('#citation-list' + petition_id).parent().attr('data-load', 1)
                if (data.status == true) {
                    var html = '';
                    $.each(data.citations, function(id, citation) {
                        html += '<div class="ui fluid card citation-card" id="citation-' + citation.id +'">' +
                            '<div class="content">' +
                                '<div class="description">' +
                                '<div class="ui grid">' +
                                    '<div class="three wide center aligned column computer only">' +
                                        '<a href="' + citation.link + '">';
                                        if (citation.thumbnail) {
                                            html += '<img class="ui fluid rounded image lazy" data-src="' + citation.thumbnail + '" src="' + citation.lazy_placeholder + '">';
                                        } else {
                                            html += '<img class="ui fluid rounded image lazy" data-src="' + citation.avatar + '" data-retina="' + citation.avatar_retina + '" src="' + citation.lazy_placeholder + '">';
                                        }
                                        html += '</a>' +
                                    '</div>' +
                                    '<div class="thirteen wide mobile fourteen tablet eleven wide computer column citation-list-content-left">' +
                                        '<div class="ui small header">' +
                                            '<div class="content">';
                                            html += '<span class="ui tiny label ' + citation.opinion_color + '">' + citation.opinion_text + '</span>';
                                            if (citation.status == 'pending') {
                                                html += citation.title;
                                            } else {
                                                html += '<a href="' + citation.link + '" data-bjax>' + citation.title + '</a> ';
                                            }
                                            if (citation.status == 'pending') {
                                                html += '<span class="ui primary tiny label">' + citation.status_label + '</span>';
                                            } 
                                            if (citation.reference) {
                                                html += '<div class="sub header"><a href="' + citation.reference + '" class="text grey" target="' + ((services_vars.external_link != 0) ? '_blank' : '_self') + '">' + citation.site_domain + ' <i class="external alternate icon"></i></a></div>';
                                            }
                                        html += '</div>' +
                                        '</div>' +
                                        '<p class="text grey font small">' + citation.excerpt + '</p>' +
                                    '</div>' +
                                    '<div class="three wide mobile two tablet two wide computer center aligned column citation-list-content-right">' +
                                        '<div class="ui vertical icon mini buttons citation-vote-buttons">' +
                                            '<button class="citation-vote-' + citation.id + ' up ui ' + (citation.vote_type == 'up' ? 'primary ' : '') + 'button' + (!citation.vote_type && services_vars.is_user_logged_in ? ' citation-vote' : '') + '" id="citation-vote-up-' + citation.id + '" data-id="' + citation.id + '"><i class="angle up icon"></i></button>' +
                                            '<button class="ui button" id="citation-vote-num-' + citation.id + '">' + citation.vote_score + '</button>' +
                                            '<button class="citation-vote-' + citation.id + ' down ui ' + (citation.vote_type == 'down' ? 'primary ' : '') + 'button' + (!citation.vote_type && services_vars.is_user_logged_in ? ' citation-vote ' : '') + '" id="citation-vote-down-' + citation.id + '" data-id="' + citation.id + '"><i class="angle down icon"></i></button>' +
                                        '</div>' +
                                    '</div>' +
                                '</div>' +
                                '</div>' +
                            '</div>' +
                            '<div class="extra content font small">' +
                                '<span class="right floated">' + services_vars.posted_by + ' <a href="' + citation.author_link + '" data-bjax>' + citation.author_name + '</a> ' + citation.time;
                                if (citation.modify) {
                                html += '<div class="ui icon top right pointing dropdown edit-citation">' +
                                        '<i class="angle down icon"></i>' +
                                        '<div class="menu">';
                                        if (citation.status != 'pending') {
                                            html += '<a href="' + citation.edit_link + '" class="item" data-bjax>' + services_vars.edit + '</a>';
                                        }
                                        html += '<a href="javascript:void(0)" class="item delete-citation" data-id="' + citation.id + '">' + services_vars.delete + '</a>' +
                                        '</div>' +
                                    '</div>';
                                }
                                html += '</span>' +
                                '<span>';
                                if (citation.comments > 0) {
                                    html += '<i class="comments icon"></i><a href="' + citation.link + '" data-bjax>' + citation.comments_label + '</a>';
                                }
                                html += '</span>' +
                            '</div>' +
                        '</div>';
                    });

                    $('#citation-list' + petition_id).append(html);
                    $('#citations-more' + petition_id).attr('data-offset', (parseInt(offset) + parseInt(data.per_page)));
                    if (parseInt(data.citations.length) < parseInt(data.per_page)) {
                        $('#citations-more' + petition_id).addClass('display none');
                    }
                    $('.edit-citation').dropdown();

                    // re init lazy load
                    re_init_lazy_load();
                } else {
                    $('#citations-more' + petition_id).addClass('display none');
                    if ($('#citation-list' + petition_id).children().length < 1) {
                        $('#citations' + petition_id).addClass('display none');
                        $('#navlink-citations' + petition_id).remove();
                    }
                }
            },
            error: function(errorThrown) {
                $('#citations-more').removeClass('loading disabled');
            }
        });
    }

    // Petition Setting
    $('.petition-setting').on('change', function() {
        var post_id = $(this).attr('data-id');
        var setting_name = $(this).attr('data-setting');
        var status = $(this).is(':checked');
        statusCitation('#' + setting_name, post_id, setting_name, status);
    });

    function statusCitation(id, post_id, setting_name, status) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_petition_save_setting',
                'post_id': post_id,
                'setting_name': setting_name,
                'status': status,
                'security': security
            },
            success: function(data) {
                // document.location.href = data.link;
            },
            error: function(errorThrown) {}
        });
    }

    // load open graph
    $('#citation_reference, #update_media').bind('paste', function() {
        setTimeout(function() {
            loadOpenGraph($('#citation_reference, #update_media').val(), '#citation-link-preview, #article-link-preview');
        }, 300)
    });

    $('#citation_reference, #update_media').keydown(function(e) {
        if (e.keyCode === 13) {
            e.preventDefault();
               setTimeout(function() {
                loadOpenGraph($('#citation_reference, #update_media').val(), '#citation-link-preview, #article-link-preview');
            }, 300)
        }
    });

    function loadOpenGraph(url, element_id) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityOpenGraph').val();

        if (url.length == 0) {
            $(element_id).addClass('display none')
            $('#graph_title').val('');
            $('#graph_image').val('');
            $('#graph_description').val('');
            $('#graph_site').val('');
            return;
        }

        $(element_id).removeClass('display none')
        $(element_id).children().removeClass('loading segment').addClass('loading segment');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_open_graph_data',
                'url': url,
                'security': security
            },
            success: function(data) {
                var html = '';
                if (data.status == true) {
                    if (data.graph != '') {
                        html += '<div class="ui items">' +
                            '<div class="item">';
                                if (data.graph.image) {
                                    html += '<div class="ui tiny image"><img src="' + data.graph.image + '"></div>';
                                }
                                html += '<div class="content">' +
                                    '<a class="header">' + data.graph.title + '</a>' +
                                    '<div class="meta"><span></span></div>' +
                                    '<div class="description">' + data.graph.description + '</div>' +
                                    '<div class="extra">' + data.graph.site_name + '</div>' +
                                '</div>' +
                            '</div></div>';
                    }
                    $(element_id).children().removeClass('loading segment').addClass('segment').html(html);
                    $('#graph_title').val(data.graph.title);
                    if (data.graph.image) {
                        $('#graph_image').val(data.graph.image);
                    }
                    $('#graph_description').val(data.graph.description);
                    $('#graph_site').val(data.graph.site_name);

                    // set graph description for content
                    if ($('#citation_id').val() == '') {
                        $('#citation_title').val(data.graph.title);
                        citationContent.value(data.graph.description);
                    }
                } else {
                    $(element_id).addClass('display none');
                }

            }
        });
    }

    // VOTE CITATION
    function voteCitation(citation_id, type) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityCitation').val();

        var vote_plus = 1;
        if ($('.citation-vote-' + citation_id).hasClass('primary')) {
            vote_plus = 2;
        }
        var vote_number = $('#citation-vote-num-' + citation_id).text();
        if (type == 'up') {
            vote_number = (parseInt(vote_number) + vote_plus);
            $('#citation-vote-num-' + citation_id).text(vote_number);
            $('#citation-vote-up-' + citation_id).removeClass('button citation-vote').addClass('primary button');
            $('#citation-vote-down-' + citation_id).removeClass('primary button').addClass('button citation-vote');
        } else if (type == 'down') {
            vote_number = (parseInt(vote_number) - vote_plus);
            $('#citation-vote-num-' + citation_id).text(vote_number);
            $('#citation-vote-up-' + citation_id).removeClass('primary button').addClass('button citation-vote');
            $('#citation-vote-down-' + citation_id).removeClass('button citation-vote').addClass('primary button');
        }
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_vote_citation',
                'user_id': services_vars.user_id,
                'post_id': services_vars.post_id,
                'citation_id': citation_id,
                'type': type,
                'vote_number': vote_number,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {

                }
            },
            error: function() {

            }
        });
    }

    $(document).on('click', 'button.citation-vote', function() {
        var citation_id = $(this).attr('data-id');
        if ($(this).hasClass('up')) {
            voteCitation(citation_id, 'up');
        } else if ($(this).hasClass('down')) {
            voteCitation(citation_id, 'down');
        }

    });

    // Load supporters list
    loadSupportersInit('supporters');
    loadSupportersInit('donors');
    function loadSupportersInit(type = 'supporters') {
        if (type == 'supporters') {
            var classes = '.supporters-section';
        } else {
            var classes = '.donors-section';
        }

        if ($(classes).length) {
            $(classes).each(function(id) {
                var petition_id = $(this).attr('data-id');
                var on_load = $(this).attr('data-load');
                if (on_load != 1) {
                    loadSupporters(type, petition_id);  
                }
            });
        }
    }

    function loadSupporters(type, petition_id = '') {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securitySupporters').val();

        if (petition_id == '') {
            var petition_id = services_vars.post_id;
        }

        if (type == 'supporters') {
            var action_name = 'conikal_supporters_list';
        } else {
            var action_name = 'conikal_donors_list';
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': action_name,
                'user_id': services_vars.user_id,
                'post_id': petition_id,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {
                    var html = '';
                    $.each(data.users, function(id, user) {
                        if (services_vars.supporters_donors_style == 'avatar') {
                        html += '<a href="' + user.user_link + '" data-bjax>' +
                            '<img class="ui circular image supporter-avatar lazy" ' +
                            'data-src="' + user.user_avatar + '" ' +
                            'data-retina="' + user.user_avatar_retina + '" ' +
                            'src="' + user.user_avatar_lazy + '" ' +
                            'alt="' + user.user_name + '" ' + 
                            'data-title="' + user.user_name + '" data-content="' + user.subheading_label + '"></a>';
                        } else if (services_vars.supporters_donors_style == 'list') {
                            html += '<div class="item">' +
                            '<img class="ui avatar image supporter-avatar lazy" ' +
                            'data-src="' + user.user_avatar + '" ' +
                            'data-retina="' + user.user_avatar_retina + '" ' +
                            'src="' + user.user_avatar_lazy + '" ' +
                            'alt="' + user.user_name + '">' +
                            '<div class="content"><a href="' + user.user_link + '" class="header truncate" data-bjax>' + user.user_name + '</a>' +
                            '<div class="description truncate">' + user.subheading_label + '</div>' +
                            '</div>' +
                            '</div>';
                        }
                    });

                    if (type == 'supporters') {
                        $('#recent-supporters-list' + petition_id).html(html).parent().attr('data-load', 1);
                    } else {
                        $('#recent-donors-list' + petition_id).html(html).parent().attr('data-load', 1);
                    }

                    // re init lazy load
                    re_init_lazy_load();
                } else {
                    if (type == 'supporters') {
                        $('#supporters-section' + petition_id).remove();
                    } else {
                        $('#donors-section' + petition_id).remove();
                    }
                }
            }
        });
    }

    // LOAD MORE UPDATES
    loadUpdateInit();
    function loadUpdateInit() {
        if ($('.update-list').length) {
            $('.update-list').each(function(id) {
                var petition_id = $(this).attr('data-id');
                var on_load = $(this).attr('data-load');
                if (on_load != 1) {
                    loadUpdates(0, petition_id);
                }
            });
        }
    }

    $(document).on('click', '.updates-more', function() {
        var petition_id = $(this).attr('data-id');
        var offset = $(this).attr('data-offset');
        loadUpdates(offset, petition_id);
    });

    function loadUpdates(offset, petition_id = 0) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityUpdate').val();

        if (petition_id == '') {
            var petition_id = services_vars.post_id;
        }

        $('#updates-more' + petition_id).addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_load_updates_petition',
                'user_id': services_vars.user_id,
                'post_id': petition_id,
                'offset': offset,
                'security': security
            },
            success: function(data) {
                $('#updates-more' + petition_id).removeClass('loading disabled');
                $('#update-list' + petition_id).parent().attr('data-load', 1)
                if (data.status == true) {
                    var html = '';
                    $.each(data.updates, function(id, update) {
                        if (update.type == 'victory') {
                        html += '<div class="ui fluid card update-card" id="update-' + update.id + '">' +
                            '<div class="content">';
                        if (update.modify) {
                        html += '<div class="right floated meta">' +
                            '<div class="ui icon top right pointing dropdown edit-update">' +
                            '<i class="angle down icon"></i>' +
                            '<div class="menu">' +
                            '<a href="' + update.edit_link + '" class="item" data-bjax>' + services_vars.edit + '</a>' +
                            '<a href="javascript:void(0)" class="item delete-update" data-id="' + update.id + '">' + services_vars.delete + '</a>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        }
                        html += '<div class="ui huge icon header victory-update-title">' + update.icon_victory +
                                    '<div class="content">' +
                                        '<a href="' + update.link + '" data-bjax>' + update.title + '</a>' +
                                        '<div class="sub header">' + update.date + '</div>' +
                                    '</div>' +
                                '</div>' +
                                '<div class="description font medium">' + update.excerpt + '</div>' +
                            '</div>' +
                        '</div>';
                        } else {
                        html += '<div class="ui fluid card update-card" id="update-' + update.id + '">' +
                            '<div class="content">';
                        if (update.modify) {
                        html += '<div class="right floated meta">' +
                            '<div class="ui icon top right pointing dropdown edit-update">' +
                            '<i class="angle down icon"></i>' +
                            '<div class="menu">' +
                            '<a href="' + update.edit_link + '" class="item" data-bjax>' + services_vars.edit + '</a>' +
                            '<a href="javascript:void(0)" class="item delete-update" data-id="' + update.id + '">' + services_vars.delete + '</a>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                        }
                        html += '<div class="meta">' +
                            '<i class="' + update.icon + '"></i>' + update.feed +
                            '<div class="ui divider"></div>' +
                            '</div>' +
                            '<div class="description">' +
                            '<div class="ui grid">' +
                            '<div class="sixteen wide mobile sixteen tablet thirteen wide computer column">' +
                            '<div class="ui header list-petition-title">' +
                            '<a href="' + update.link + '" data-bjax>' + update.title + '</a>' +
                            '</div>' +
                            '<p class="text grey">' + update.excerpt + '</p>' +
                            '</div>';
                        if (update.thumbnail != '') {
                        html += '<div class="three wide column computer only">' +
                            '<a href="' + update.link + '" data-bjax>' +
                            '<img class="ui fluid rounded image lazy" data-src="' + update.thumbnail + '" src="' + update.lazy_placeholder + '">' +
                            '</a>' +
                            '</div>';
                        }
                        html += '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="extra content">';
                        if (update.comments > 0) {
                            html += '<a href="' + update.link + '" data-bjax><span>' +
                                '<i class="comments icon"></i>' +
                                update.comments_label +
                                '</span></a>';
                        }
                        if (update.status == 'pending') {
                            html += '<span class="ui primary tiny label">' + update.status_label + '</span>';
                        } 
                        html += '<span class="right floated">' + update.time + '</span>' +
                            '</div>' +
                            '</div>';
                        }
                    });

                    $('#update-list' + petition_id).append(html);
                    $('#updates-more' + petition_id).attr('data-offset', (parseInt(offset) + parseInt(data.per_page)));
                    if (parseInt(data.updates.length) < parseInt(data.per_page)) {
                        $('#updates-more' + petition_id).addClass('display none');
                    }
                    $('.edit-update').dropdown();

                    // re init lazy load
                    re_init_lazy_load();
                } else {
                    $('#updates-more' + petition_id).addClass('display none');
                    if ($('#update-list' + petition_id).children().length < 1) {
                        $('#updates' + petition_id).remove();
                        $('#navlink-update' + petition_id).remove();
                    }
                    
                }
            },
            error: function(errorThrown) {
                $('#updates-more' + petition_id).removeClass('loading disabled');
            }
        });
    }

    // Loop Sign element button
    var elements = [
        {
          class: '.signBtn',
          form: 'signPetitionForm',
          idPrefix: '#signBtn'
        },
        {
          class: '.signBtnSC',
          form: 'signPetitionFormSC',
          idPrefix: '#signBtnSC'
        },
        {
          class: '.signBtnSidebar',
          form: 'signPetitionFormSidebar',
          idPrefix: '#signBtnSidebar'
        }
    ];
      
    elements.forEach(function(element) {
        $(document).on('click', element.class, function() {
          var petition_id = $(this).attr('data-id');
          var signPetitionForm = getFormObj(element.form, petition_id);
          signPetition(element.idPrefix + petition_id, petition_id, signPetitionForm);
        });
    });
      

    if (urlParam('success') && urlParam('success') != '') {
        setTimeout(function(){
            $('#sign-successful-modal' + urlParam('success')).modal('show');
            $('.social-share .button').popup();
            fbSharing(urlParam('success'));
        }, 1000);
    }

    showFBSharing();
    function showFBSharing() {
        if (urlParam('petition_id') && urlParam('petition_id') != '' && urlParam('share') && urlParam('share') == 'on') {
            setTimeout(function(){
                fbSharing(urlParam('petition_id'));
            }, 1000);
        }
    }

    /*
    $('.postFB').on('click', function() {
        if ($('.postFB').children('i').hasClass('facebook')) {
            $('.postFB').addClass('disabled loading');
            fbPublish();
        }
    });
    */

    // UPDATE SIGNATURES NUMBER
    (function updateSignatures() {
        if ($('.fav_no').length && parseInt(services_vars.signature_update_time) != 0) {
            var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
            

            $('.fav_no').each(function() {
                var petition_id = $(this).attr('data-id');
                var security = $('#securitySign' + petition_id).val();

                $.ajax({
                    type: 'POST',
                    dataType: 'json',
                    url: ajaxURL,
                    data: {
                        'action': 'conikal_get_signatures_number',
                        'user_id': services_vars.user_id,
                        'post_id': petition_id,
                        'security': security
                    },
                    success: function(data) {
                        if (data.status === true) {
                            $('#fav_no' + petition_id).html(data.signature);
                            $('#ned_no' + petition_id).html(data.need);
                            $('#petition-goal' + petition_id).progress('increment').attr('data-value', parseInt(data.number) );
                        }
                    },
                    complete: function() {
                        // Schedule the next request when the current one's complete
                        if (parseInt(services_vars.signature_update_time) != 0) {
                            setTimeout(updateSignatures, parseInt(services_vars.signature_update_time) * 60 * 1000);
                        }
                    }
                });
            });
        }
    })();

    // SIGN PETITION
    function signPetition(id, petition_id, signPetitionForm = '') {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';

        if (signPetitionForm == '') {
            var signPetitionForm = getFormObj('signPetitionForm', petition_id);
        }

        if (petition_id == '') {
            petition_id = services_vars.post_id;
        }
        var comment = signPetitionForm.signComment;
        var security = $('#securitySign' + petition_id).val();

        // email notice checkbox value
        if (signPetitionForm.emailNotice == 'on') {
            var notice = 1;
        } else {
            var notice = 0;
        }

        // sign as anonymous checkbox
        if (signPetitionForm.signAnonymous != 'on') {
            var anonymous = 1;
        } else {
            var anonymous = 0;
        }

        $(id).addClass('loading disabled');
        if ($(id).hasClass('signPetition')) {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajaxURL,
                data: {
                    'action': 'conikal_add_to_signatures',
                    'user_id': services_vars.user_id,
                    'post_id': petition_id,
                    'comment': comment,
                    'anonymous': anonymous,
                    'notice': notice,
                    'security': security
                },
                success: function(data) {
                    $(id).removeClass('loading disabled');
                    if (data.status === true) {
                        $('#fav_no' + petition_id).html(data.signature);
                        $('#ned_no' + petition_id).html(data.need);
                        if (services_vars.unsign == 0) {
                            $(id).removeClass('signPetition');
                        } else {
                            $(id).removeClass('signPetition').addClass('signedPetition');
                        }
                        $(id).children('i').removeClass('write').addClass('checkmark');
                        $('#petition-goal' + petition_id).progress('increment').attr('data-value', parseInt(data.number) );

                        if (services_vars.action_after_sign == 'refresh') {
                            document.location.href = window.location.href;
                        } else if (services_vars.action_after_sign == 'redirect') {
                            document.location.href = $('#sign-successful-url' + petition_id).val() + '&share=' + signPetitionForm.fbPublish;
                        } else if (services_vars.action_after_sign == 'modal') {
                            $('#sign-successful-modal' + petition_id).modal('show');
                            $('.social-share .button').popup();

                            // show facebook sharing popup
                            if (signPetitionForm.fbPublish == 'on') {
                                fbSharing(petition_id);
                            }
                        }
                    } else {
                        var message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                        $('#sign-response').empty().append(message);
                    }
                },
                error: function(errorThrown) {
                    $(id).removeClass('loading disabled');
                }
            });
        } else if ($(id).hasClass('signedPetition')) {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajaxURL,
                data: {
                    'action': 'conikal_remove_from_signatures',
                    'user_id': services_vars.user_id,
                    'post_id': petition_id,
                    'security': security
                },
                success: function(data) {
                    $(id).removeClass('loading disabled');
                    if (data.status === true) {
                        $('#fav_no' + petition_id).html(data.signature);
                        $('#ned_no' + petition_id).html(data.need);
                        $(id).removeClass('signedPetition').addClass('signPetition');
                        $(id).children('i').removeClass('checkmark').addClass('write');
                        $('#petition-goal' + petition_id).progress('increment').attr('data-value', parseInt(data.number) );
                    }
                },
                error: function(errorThrown) {
                    $(id).removeClass('loading disabled');
                }
            });
        } else {
            $(id).removeClass('loading disabled');
        }
    }

    // BOOKMARK PETITION
    function bookmarkPetition(petition_id) {
        if (petition_id) {
            var post_id = petition_id;
        } else {
            var post_id = services_vars.post_id;
        }
        var classes = '#bookmark-' + post_id;
        var type = $(classes).attr('data-type');
        var user_id = services_vars.user_id;
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityBookmark').val();

        if ($(classes).hasClass('bookmarkPetition')) {
            $(classes).removeClass('bookmarkPetition').addClass('bookmarkedPetition').attr('data-content', services_vars.unsave_this);
            $(classes).children('i').removeClass('bookmark outline icon').addClass('bookmark icon');
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajaxURL,
                data: {
                    'action': 'conikal_add_to_bookmarks',
                    'user_id': user_id,
                    'post_id': post_id,
                    'type': type,
                    'security': security
                },
                success: function(data) {

                }
            });
        } else if ($(classes).hasClass('bookmarkedPetition')) {
            $(classes).removeClass('bookmarkedPetition').addClass('bookmarkPetition').attr('data-content', services_vars.save_this);
            $(classes).children('i').removeClass('bookmark icon').addClass('bookmark outline icon');
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajaxURL,
                data: {
                    'action': 'conikal_remove_from_bookmarks',
                    'user_id': user_id,
                    'post_id': post_id,
                    'type': type,
                    'security': security
                },
                success: function(data) {

                }
            });
        }
    }

    $(document).on('click', 'a.bookmarkBtn', function() {
        var petition_id = $(this).attr('data-id');
        bookmarkPetition(petition_id);
    });

    // FOLLOW USER
    function followUser(follow_id, type) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityFollow').val();

        if (type == 'follow') {
            $.post(ajaxURL, {'action': 'conikal_follow_user', 'user_id': services_vars.user_id, 'follow_id': follow_id, 'type': 'follow', 'security': security})
        } else if (type == 'unfollow') {
            $.post(ajaxURL, {'action': 'conikal_follow_user', 'user_id': services_vars.user_id, 'follow_id': follow_id, 'type': 'unfollow', 'security': security})
        }
    }

    $(document).on('click', 'a.follow-user', function() {
        var follow_id = $(this).attr('data-id');
        if ($(this).hasClass('follow')) {
            $(this).removeClass('basic button follow-user follow').addClass('primary button follow-user following').html('<i class="checkmark icon"></i>')
            followUser(follow_id, 'follow')
        } else if ($(this).hasClass('following')) {
            $(this).removeClass('primary button follow-user following').addClass('basic button follow-user follow').html('<i class="plus icon"></i>')
            followUser(follow_id, 'unfollow');
        }
    });

    $(document).on('click', 'a.follow-profile', function() {
        var follow_id = $(this).attr('data-id');
        if ($(this).hasClass('follow')) {
            $(this).removeClass('inverted button follow-profile follow').addClass('primary button follow-profile following').html('<i class="checkmark icon"></i>' + services_vars.following)
            followUser(follow_id, 'follow')
        } else if ($(this).hasClass('following')) {
            $(this).removeClass('primary button follow-profile following').addClass('inverted button follow-profile follow').html('<i class="plus icon"></i>' + services_vars.follow)
            followUser(follow_id, 'unfollow');
        }
    });

    $(document).on('click', 'a.follow-page', function() {
        var follow_id = $(this).attr('data-id');
        if ($(this).hasClass('follow')) {
            $(this).removeClass('basic button follow-page follow').addClass('primary button follow-page following').html('<i class="checkmark icon"></i>' + services_vars.following)
            followUser(follow_id, 'follow')
        } else if ($(this).hasClass('following')) {
            $(this).removeClass('primary button follow-page following').addClass('basic button follow-page follow').html('<i class="plus icon"></i>' + services_vars.follow)
            followUser(follow_id, 'unfollow');
        }
    });

    // FOLLOW TOPIC
    function followtopic(topic_id, type) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityFollow').val();

        if (type == 'follow') {
            $.post(ajaxURL, {'action': 'conikal_follow_topic', 'user_id': services_vars.user_id, 'topic_id': topic_id, 'type': 'follow', 'security': security})
        } else if (type == 'unfollow') {
            $.post(ajaxURL, {'action': 'conikal_follow_topic', 'user_id': services_vars.user_id, 'topic_id': topic_id, 'type': 'unfollow', 'security': security})
        }
    }

    $(document).on('click', 'button.follow-topic', function() {
        var follow_id = $(this).attr('data-id');
        if ($(this).hasClass('follow')) {
            $(this).removeClass('follow-topic follow').addClass('follow-topic following').html(services_vars.following)
            followtopic(follow_id, 'follow')
        } else if ($(this).hasClass('following')) {
            $(this).removeClass('follow-topic following').addClass('follow-topic follow').html(services_vars.follow)
            followtopic(follow_id, 'unfollow');
        }
    });

    $(document).on('click', 'a.follow-topic', function() {
        var follow_id = $(this).attr('data-id');
        if ($(this).hasClass('follow')) {
            $(this).removeClass('inverted button follow-topic follow').addClass('primary button follow-topic following').html('<i class="checkmark icon"></i>' + services_vars.following)
            followtopic(follow_id, 'follow')
        } else if ($(this).hasClass('following')) {
            $(this).removeClass('primary button follow-topic following').addClass('inverted button follow-topic follow').html('<i class="plus icon"></i>' + services_vars.follow)
            followtopic(follow_id, 'unfollow');
        }
    });

    // ADD COMMENT
    function addComment(post_id, id, submit, parent, sign, anonymous) {
        if ($(id).val().length > 0) {
            var grecaptcha_res = $('input[name="g-recaptcha-response"]').val();
            var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
            var security = $('#securityComment').val();
            var content = $(id).val();
            if (!parent) {
                parent = 0;
            }
            var count = $('#comment-count' + post_id).text();
            anonymous = anonymous || 0;

            $(submit).addClass('loading disabled');
            $('#send-comment-button' + post_id).addClass('loading disabled');

            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: ajaxURL,
                data: {
                    'action': 'conikal_add_comments',
                    'user_id': services_vars.user_id,
                    'post_id': post_id,
                    'fullname': $('#comment-fullname' + post_id).val(),
                    'email': $('#comment-email' + post_id).val(),
                    'cookies_consent': $('#comment-cookies-consent' + post_id).is(':checked'),
                    'content': content,   
                    'parent': parent,
                    'anonymous': anonymous,
                    'g-recaptcha-response': grecaptcha_res,
                    'security': security
                },
                success: function(data) {
                    $(submit).removeClass('loading disabled');
                    $('#send-comment-button' + post_id).removeClass('loading disabled');
                    if (services_vars.recaptcha == 1) {
                        conikalReCaptchaReset();
                    }
                    if (data.status == true) {
                        var comment = '<div class="comment" id="comment-' + data['details'].comment_ID + '">' +
                            '<a class="avatar"><img src="' + data['details'].comment_author_avatar + '"></a>' +
                            '<div class="content">' +
                            '<a class="author" href="' + data['details'].comment_author_link + '" data-bjax>' + data['details'].comment_author_name + '</a>' +
                            '<div class="metadata">' +
                            '<div class="date">' + data.time + '</div>' +
                            '<div class="date"> · </div>' +
                            '<div class="rating"><span id="vote-num-' + data['details'].comment_ID + '">0</span> ' + services_vars.comment_vote + '</div>' +
                            '</div>' +
                            '<div class="text">' + data['details'].comment_content + '</div>' +
                            '<div class="actions">' +
                            '<a href="javascript:void(0)" class="vote up" id="vote-' + data['details'].comment_ID + '" data-author="' + data['details'].comment_author_name + '" data-id="' + data['details'].comment_ID + '"><i class="thumbs up icon"></i>' + services_vars.comment_up_vote + '</a>' +
                            '<a href="javascript:void(0)" class="reply" id="comment-reply" data-author="' + data['details'].comment_author_name + '" data-id="' + parent + '" data-post-id="' + post_id + '"><i class="reply icon"></i>' + services_vars.comment_reply + '</a>' +
                            '<a href="javascript:void(0)" class="edit" id="edit-' + data['details'].comment_ID + '" data-author="' + data['details'].comment_author_name + '" data-id="' + data['details'].comment_ID + '"><i class="pencil icon"></i>' + services_vars.edit + '</a>' +
                            '<a href="javascript:void(0)" class="delete" id="delete-' + data['details'].comment_ID + '" data-author="' + data['details'].comment_author_name + '" data-id="' + data['details'].comment_ID + '"><i class="delete icon"></i>' + services_vars.delete + '</a>' +
                            '</div>' +
                            '</div>';
                        if (data['details'].comment_parent == 0) {
                            comment += '<div class="comments" id="replies-' + data['details'].comment_ID + '"></div>';
                        }
                        comment += '</div>';
                        if (data['details'].comment_parent == 0) {
                            $('#comments-list' + post_id).append(comment);
                        } else {
                            $('#replies-' + data['details'].comment_parent).append(comment);
                        }
                        if (isNaN(parseInt(count))) {
                            $('#comment-count' + post_id).text('1');
                        } else {
                            $('#comment-count' + post_id).text(parseInt(count) + 1);
                            $('#comment-count-text' + post_id).text(services_vars.comments);
                        }
                        $('#no-comment' + post_id).empty();
                        $('#content-comment' + post_id).attr('placeholder', services_vars.comment_placeholder).removeAttr('style');
                        $('#comment-parent' + post_id).val('');
                        $(id).val('');
                        $('#commentMessage' + post_id).empty()
                    } else {
                        var message = '<div class="ui error message">' +
                            '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                            '</div>';
                        $('#commentMessage' + post_id).empty().append(message);
                    }
                },
                error: function() {
                    $(submit).removeClass('loading disabled');
                    $('#send-comment-button' + post_id).removeClass('loading disabled');
                    if (services_vars.recaptcha == 1) {
                        conikalReCaptchaReset();
                    }
                }
            });
        } else {
            if (sign == false) {
                $('#field-comment').addClass('error');
            }
        }
    }

    enterAddComment();
    function enterAddComment() {
        $(document).on('keydown', '.content-comment', function(e) {
            if (e.keyCode == 13 && !e.shiftKey && services_vars.is_mobile == 'false') {
                var post_id = $(this).parent().attr('data-id');
                var parent_id = $('#comment-parent' + post_id).val();
                addComment(post_id, '#content-comment' + post_id, '#send-comment' + post_id, parent_id, false);
                e.preventDefault();
            }
        });
    }

    $(document).on('click', '.send-comment', function(){
        var post_id = $(this).attr('data-id');
        var parent_id = $('#comment-parent' + post_id).val();
        addComment(post_id, '#content-comment' + post_id, '#send-comment' + post_id, parent_id, false);
    });

    $('.content-comment').on('click', function() {
        $('#field-comment').removeClass('error');
    });

    // UPVOTE COMMENT
    function voteComment(comment_id, type) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityComment').val();

        var vote_number = $('#vote-num-' + comment_id).text();
        if (type == 'up') {
            vote_number = (parseInt(vote_number) + 1);
            $('#vote-num-' + comment_id).text(vote_number);
            $('#vote-' + comment_id).removeClass('up').addClass('down').html('<i class="thumbs down icon"></i>' + services_vars.comment_down_vote);
        } else if (type == 'down') {
            vote_number = (parseInt(vote_number) - 1);
            $('#vote-num-' + comment_id).text(vote_number);
            $('#vote-' + comment_id).removeClass('down').addClass('up').html('<i class="thumbs up icon"></i>' + services_vars.comment_up_vote);
        }
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_vote_comment',
                'user_id': services_vars.user_id,
                'post_id': services_vars.post_id,
                'comment_id': comment_id,
                'type': type,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {

                }
            },
            error: function() {

            }
        });
    }

    $(document).on('click', 'a.vote', function() {
        var comment_id = $(this).attr('data-id');
        if ($(this).hasClass('up')) {
            voteComment(comment_id, 'up');
        } else if ($(this).hasClass('down')) {
            voteComment(comment_id, 'down');
        }

    });

    // UPDATE COMMENT
    function updateComment(comment_id) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityComment').val();
        var content = $('#comment-editor-' + comment_id).val();

        $('#comment-edit-submit-' + comment_id).addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_update_comment',
                'user_id': services_vars.user_id,
                'post_id': services_vars.post_id,
                'comment_id': comment_id,
                'content': content,
                'security': security
            },
            success: function(data) {
                $('#comment-edit-submit-' + comment_id).removeClass('loading disabled');
                if (data.status == true) {
                    $('#comment-content-' + comment_id).html(data.content);
                } else {
                    var message = '<div class="ui small error message">' +
                        '<i class="close icon"></i><i class="warning circle icon"></i>' + data.message +
                        '</div>';
                    $('#comment-edit-message-' + comment_id).html(message);
                }
            },
            error: function() {

            }
        });
    }

    $(document).on('click', 'a.comment-edit-submit', function() {
        var comment_id = $(this).attr('data-id');
        updateComment(comment_id);
    });

    // DELETE COMMENT
    function deleteComment(comment_id) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityComment').val();

        var count = $('#comment-count').text();
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_delete_comment',
                'user_id': services_vars.user_id,
                'post_id': services_vars.post_id,
                'comment_id': comment_id,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {
                    $('#comment-' + data.id).fadeOut(200);
                    $('#comment-count').text(parseInt(count) - 1);
                    if (parseInt(count) <= 2) {
                        $('#comment-count-text').text(services_vars.comment);
                    }
                }
            }
        });
    }

    $(document).on('click', 'a.delete', function() {
        var comment_id = $(this).attr('data-id');
        deleteComment(comment_id);
    });

    // LOAD MORE COMMENT
    function loadComments(comment_order, replies_order, petition_id, parent_id, offset) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var comment_number = $('#comment-number' + petition_id).val();
        var reply_number = $('#reply-number' + petition_id).val();

        if (parent_id == 0) {
            $('#comment-more' + petition_id).addClass('loading disabled');
            var offset = $('#comment-offset' + petition_id).val();
        } else {
            var offset = 0;
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_load_comments',
                'user_id': services_vars.user_id,
                'post_id': petition_id,
                'parent_id': parent_id,
                'offset': offset
            },
            success: function(data) {
                $('#comment-more' + petition_id).removeClass('loading disabled');
                if (data.status == true) {
                    var more_replies = '';
                    var html = '';
                    $.each(data.comments, function(id, comment) {
                        html += '<div class="comment" id="comment-' + comment.comment_ID + '">';
                        if (comment.comment_type == 'comment') {
                            html += '<a href="' + comment.comment_author_link + '" class="avatar ' + comment.comment_level_badge + '" data-bjax><img class="lazy" data-src="' + comment.comment_author_avatar + '" data-retina="' + comment.comment_author_avatar_retina + '" src="' + comment.comment_placeholder_avatar + '" alt="' + comment.comment_author_name + '"></a>';
                        }
                        html += '<div class="content">' +
                            '<a href="' + comment.comment_author_link + '" class="author" data-bjax>' + comment.comment_author_name + '</a>' +
                            '<div class="metadata">' +
                            '<div class="date">' + comment.comment_time + '</div>' +
                            '<div class="date"> · </div>' +
                            '<div class="rating"><span id="vote-num-' + comment.comment_ID + '">' + comment.comment_vote + '</span> ' + comment.comment_vote_label + '</div>' +
                            '</div>' +
                            '<div class="text" id="comment-content-' + comment.comment_ID + '"><p>' + comment.comment_content + '</p></div>' +
                            '<div class="actions">';
                        if (comment.comment_voted == true) {
                            html += '<a href="javascript:void(0)" class="vote down" id="vote-' + comment.comment_ID + '" data-author="' + comment.comment_author_name + '" data-id="' + comment.comment_ID + '"><i class="thumbs down icon"></i>' + services_vars.comment_down_vote + '</a>';
                        } else {
                            html += '<a href="javascript:void(0)" class="vote up" id="vote-' + comment.comment_ID + '" data-author="' + comment.comment_author_name + '" data-id="' + comment.comment_ID + '"><i class="thumbs up icon"></i>' + services_vars.comment_up_vote + '</a>';
                        }
                        if (services_vars.is_user_logged_in) {
                            html += '<a href="javascript:void(0)" class="reply" id="reply-' + comment.comment_ID + '" data-author="' + comment.comment_author_name + '" data-id="' + comment.comment_ID + '" data-post-id="' + petition_id + '"><i class="reply icon"></i>' + services_vars.comment_reply + '</a>';
                            if (services_vars.user_id == comment.user_id || services_vars.administrator == 1 || services_vars.co_author == 1) {
                                html += '<a href="javascript:void(0)" class="edit" id="edit-' + comment.comment_ID + '" data-author="' + comment.comment_author_name + '" data-id="' + comment.comment_ID + '"><i class="pencil icon"></i>' + services_vars.edit + '</a>';
                                html += '<a href="javascript:void(0)" class="delete" id="delete-' + comment.comment_ID + '" data-author="' + comment.comment_author_name + '" data-id="' + comment.comment_ID + '"><i class="delete icon"></i>' + services_vars.delete + '</a>';
                            }
                        }
                        html += '</div>' +
                            '</div>';
                        if (parent_id == 0) {
                            html += '<div class="comments">';
                        }

                        if (comment.replies) {
                            more_replies += '<a href="javascript:void(0)" class="hide-replies display none" id="hide-' + comment.comment_ID + '" data-id="' + comment.comment_ID + '"><i class="angle up icon"></i>' + services_vars.comment_replies_hide + '</a>';
                            more_replies += '<a href="javascript:void(0)" class="more-replies" id="more-' + comment.comment_ID + '" data-id="' + comment.comment_ID + '" data-post-id="' + petition_id + '"><i class="angle down icon"></i>' + services_vars.comment_view_all + ' ' + (parseInt(comment.replies.length) + parseInt(data.per_comment)) + ' ' + services_vars.comment_replies + '</a>';
                            more_replies += '<div class="ui active mini inline loader display none" id="loading-' + comment.comment_ID + '"></div>';
                        }
                        if (replies_order == 'oldest' && comment.replies_total > parseInt(reply_number)) {
                            html += more_replies;
                        }
                        html += '<div class="replies" id="replies-' + comment.comment_ID + '">';
                        if (comment.replies) {
                            $.each(comment.replies, function(id, reply) {
                                html += '<div class="comment" id="comment-' + reply.comment_ID + '">';
                                if (reply.comment_type == 'comment') {
                                    html += '<a href="' + reply.comment_author_link + '" class="avatar ' + reply.comment_level_badge + '" data-bjax><img class="lazy" data-src="' + reply.comment_author_avatar + '" data-retina="' + reply.comment_author_avatar_retina + '" src="' + comment.comment_placeholder_avatar + '" alt="' + reply.comment_author_name + '"></a>';
                                }
                                html += '<div class="content">' +
                                    '<a href="' + reply.comment_author_link + '" class="author" data-bjax>' + reply.comment_author_name + '</a>' +
                                    '<div class="metadata">' +
                                    '<div class="date">' + reply.comment_time + '</div>' +
                                    '<div class="date"> · </div>' +
                                    '<div class="rating"><span id="vote-num-' + reply.comment_ID + '">' + reply.comment_vote + '</span> ' + reply.comment_vote_label + '</div>' +
                                    '</div>' +
                                    '<div class="text" id="comment-content-' + reply.comment_ID + '"><p>' + reply.comment_content + '</p></div>' +
                                    '<div class="actions">';
                                if (reply.comment_voted == true) {
                                    html += '<a href="javascript:void(0)" class="vote down" id="vote-' + reply.comment_ID + '" data-author="' + reply.comment_author_name + '" data-id="' + reply.comment_ID + '"><i class="thumbs down icon"></i>' + services_vars.comment_down_vote + '</a>';
                                } else {
                                    html += '<a href="javascript:void(0)" class="vote up" id="vote-' + reply.comment_ID + '" data-author="' + reply.comment_author_name + '" data-id="' + reply.comment_ID + '"><i class="thumbs up icon"></i>' + services_vars.comment_up_vote + '</a>';
                                }
                                if (services_vars.is_user_logged_in) {
                                    html += '<a href="javascript:void(0)" class="reply" id="reply-' + comment.comment_ID + '" data-author="' + reply.comment_author_name + '" data-id="' + comment.comment_parent + '" data-post-id="' + petition_id + '"><i class="reply icon"></i>' + services_vars.comment_reply + '</a>';
                                    if (services_vars.user_id == reply.user_id || services_vars.administrator == 1 || services_vars.co_author == 1) {
                                        html += '<a href="javascript:void(0)" class="edit" id="edit-' + reply.comment_ID + '" data-author="' + reply.comment_author_name + '" data-id="' + reply.comment_ID + '"><i class="pencil icon"></i>' + services_vars.edit + '</a>';
                                        html += '<a href="javascript:void(0)" class="delete" id="delete-' + reply.comment_ID + '" data-author="' + reply.comment_author_name + '" data-id="' + reply.comment_ID + '"><i class="delete icon"></i>' + services_vars.delete + '</a>';
                                    }
                                }
                                html += '</div>' +
                                    '</div>' +
                                    '</div>';
                            });
                        }
                        html += '</div>';
                        if (replies_order == 'newest' && comment.replies_total > parseInt(reply_number)) {
                            html += more_replies;
                        }
                        if (parent_id == 0) {
                            html += '</div>';
                        }
                        html += '</div>';
                    });

                    if (parent_id == 0) {
                        if (comment_order == 'oldest') {
                            $('#comments-list' + petition_id).prepend(html);
                        } else {
                            $('#comments-list' + petition_id).append(html);
                        }
                        $('#comment-offset' + petition_id).val((parseInt(offset) + parseInt(data.per_page)));
                    } else {
                        $('#hide-' + parent_id).removeClass('display none').addClass('display block');
                        $('#more-' + parent_id).removeClass('display block').addClass('display none');
                        $('#loading-' + parent_id).removeClass('display block').addClass('display none');
                        $('#replies-' + parent_id).html(html);
                    }

                    if ((data.comments.length < $('#comment-number' + petition_id).val()) && parent_id == 0) {
                        $('#comment-more' + petition_id).remove();
                    }
                } else {
                    $('#comment-more' + petition_id).remove();
                }
                
                re_init_lazy_load();
            },
            error: function() {
                $('#comment-more' + petition_id).removeClass('loading disabled');
            }
        });
    }

    $(document).on('click', '.comment-more', function() {
        var petition_id = $(this).attr('data-id');
        var comment_order = $(this).attr('data-order');
        var replies_order = $(this).attr('data-replies-order');
        loadComments(comment_order, replies_order, petition_id, 0);
    });

    $(document).on('click', 'a.more-replies', function() {
        var petition_id = $(this).attr('data-post-id');
        var parent_id = $(this).attr('data-id');
        var offset = $(this).attr('data-offset');
        var comment_order = $(this).attr('data-order');
        var replies_order = $(this).attr('data-replies-order');
        loadComments(comment_order, replies_order, petition_id, parent_id, offset);
        $('#loading-' + parent_id).removeClass('display none').addClass('display block');

    });

    $(document).on('click', 'a.hide-replies', function() {
        var parent_id = $(this).attr('data-id');
        $('#more-' + parent_id).removeClass('display none').addClass('display block');
        $('#hide-' + parent_id).removeClass('display block').addClass('display none');
        $('#replies-' + parent_id).html('');
    });

    // REPLY COMMENT
    $(document).on('click', 'a.reply', function() {
        var post_id = $(this).attr('data-post-id'),
            comment_id = $(this).attr('data-id'),
            author_name = $(this).attr('data-author');
        $('#comment-parent' + post_id).val(comment_id);
        $('#content-comment' + post_id).attr('placeholder', services_vars.comment_reply_to + ' ' + author_name).focus();
    });

    // EDIT CUSTOM HEADING FOR SHARING
    function editCustomHeading(petition_id = '') {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityHeading').val();
        var heading = $('#custom-heading' + petition_id).val();

        if (petition_id == '') {
            petition_id = services_vars.post_id;
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_update_custom_heading',
                'user_id': services_vars.user_id,
                'post_id': petition_id,
                'heading': heading,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {
                    $('#heading-sharing' + petition_id).removeClass('display none').addClass('display block').text(data.heading)
                    $('#edit-heading' + petition_id).removeClass('display block').addClass('display none').removeClass('error')
                } else {
                    $('#edit-heading' + petition_id).addClass('error');
                }
            },
            error: function() {
                $('#edit-heading' + petition_id).addClass('error');
            }
        });
    }

    $(document).on('keydown', '.custom-heading', function(e) {
        if (e.keyCode == 13 && !e.shiftKey) {
            var petition_id = $(this).attr('data-id');
            editCustomHeading(petition_id);
            e.preventDefault();
        }
    });

    // LOAD FEATURED VICTORY PETITION
    initVictoryPetitionSlider();
    function initVictoryPetitionSlider() {
        if ((services_vars.is_front_page && !services_vars.is_home || services_vars.page_template == 'homepage.php') && services_vars.home_victory == 1 && services_vars.home_victory_hide_logined != 1) {
            if (!services_vars.is_user_logged_in) {
                loadVictoryPetitions('.feature-petition', '.feature-navigation');
            }
        } else if ((services_vars.is_front_page && !services_vars.is_home || services_vars.page_template == 'homepage.php') && services_vars.home_victory == 1) {
            loadVictoryPetitions('.feature-petition', '.feature-navigation');
        }

        if ($('.victory-slider').length) {
            $('.victory-slider').each(function () {
                var order = $(this).attr('data-order');
                var orderby = $(this).attr('data-orderby');
                var posts_per_page = $(this).attr('data-show');

                loadVictoryPetitions('.victory-slider-petition', '.victory-slider-navigation', orderby, order, posts_per_page);
            });
        }
    }

    // Victory petition request and render
    function loadVictoryPetitions(id, navigation_id, orderby = 'data', order = 'DESC', posts_per_page = 7) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityVictoryPetitions').val();

        $.ajax({
            type: 'GET',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_load_victory_petitions',
                'orderby': orderby,
                'order': order,
                'posts_per_page': posts_per_page,
                'security': security
            },
            success: function(data) {
                if (data.status == true) {
                    var html = '';
                    var navigation = '';
                    $.each(data.petitions, function(id, petition) {
                        html += '<div class="home-feature-item"><div class="ui grid">' +
                                    '<div class="sixteen wide mobile eight wide tablet eight wide computer column"><a class="ui fluid image" href="' + petition.link + '" data-bjax>';
                                if (parseInt(petition.sign) >= parseInt(petition.goal) || petition.status == '1') {
                                    html += '<div class="ui primary large ribbon label victory-label">' + services_vars.victory_icon + services_vars.victory_text + '</div>';
                                }
                                    html += '<img class="featured-image" data-lazy="' + petition.thumbnail_medium + '" src="' + petition.lazy_placeholder_medium + '" alt="' + petition.title + '">' +
                                    '</a></div>' +
                                '<div class="sixteen wide mobile eight wide tablet eight wide computer column">' +
                                    '<div class="ui basic segment feature-right-content">' +
                                        '<div class="feature-content">' +
                                            '<div class="ui grid">' +
                                                '<div class="sixteen wide column tablet computer only">' +
                                                    '<h2 class="ui header victory-title">' +
                                                        '<div class="content">' +
                                                            '<div class="sub header truncate petition-to">' + services_vars.send_icon + services_vars.petition_to.replace(/%s/g, petition.receiver) + '</div>' +
                                                            '<a href="' + petition.link + '" data-bjax>' + petition.title + '</a>' +
                                                        '</div>' +
                                                    '</h2>' +
                                                '</div>' +
                                                '<div class="sixteen wide column computer only excerpt">' +
                                                    '<div class="text grey">' + petition.excerpt + '</div>' +
                                                '</div>' +
                                            '</div>' +
                                        '</div>' +
                                        '<div class="ui grid computer only">' +
                                            '<div class="feature-footer">' +
                                                '<div class="sixteen wide column">' +
                                                    '<div class="text grey place"><i class="map marker icon"></i>' + (petition.city ? petition.city + ', ' : '') + (petition.state ? petition.state + ', ' : '') + (petition.country ? petition.country : '') + '</div>' +
                                                    '<div class="ui indicating tiny primary progress petition-goal" data-value="' + petition.sign + '" data-total="' + (petition.status == '1' ? petition.sign : petition.goal) + '">' +
                                                        '<div class="bar">' +
                                                            '<div class="progress"></div>' +
                                                        '</div>' +
                                                    '</div>' +
                                                '</div>' +
                                                '<div class="sixteen wide">' +
                                                    '<a class="ui primary label petition-label-supporters" href="' + petition.link + '" data-bjax>' + services_vars.supporter_icon + petition.supporter_label + '</a> ';
                                                    if (petition.category_name) {
                                                        html += '<a class="ui label petition-label-category" href="' + petition.category_link + '" data-bjax><i class="tag icon"></i>' + petition.category_name + '</a> ';
                                                    }
                                                    if (petition.comments > 0) {
                                                        html += '<a class="ui label petition-label-comments" href="' + petition.link + '#comments' + petition.id + '" data-bjax><i class="comments icon"></i>' + petition.comments_label + '</a>';
                                                    }
                                                    html += '<a class="float right" href="' + petition.author_link + '" data-bjax>' +
                                                    '<img class="ui avatar image petition-author-avatar lazy" data-lazy="' + petition.author_avatar + '" src="' + petition.lazy_placeholder_avatar + '" alt="' + petition.author_name + '" data-title="' + petition.author_name + '" data-content="' + (petition.city ? petition.city + ', ' : '') + (petition.state ? petition.state + ', ' : '') + (petition.country ? petition.country : '') + '" />' +
                                                    '</a>' +
                                                '</div>' +
                                            '</div>' +
                                        '</div>' +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                        '</div>';

                        navigation += '<div><img class="ui fluid image" data-lazy="' + petition.thumbnail_small + '" src="' + petition.lazy_placeholder + '" alt="' + petition.title + '"></div>';

                    });

                    $(id).html(html);
                    $(navigation_id).html(navigation);

                    var settings_rtl_mode = ((services_vars.rtl_mode != 0) ? true : false);
                    $(id).slick({
                        rtl: settings_rtl_mode,
                        adaptiveHeight: true,
                        lazyLoad: 'ondemand',
                        asNavFor: navigation_id
                    });

                    $(navigation_id).slick({
                        rtl: settings_rtl_mode,
                        slidesToShow: 6,
                        slidesToScroll: 1,
                        asNavFor: id,
                        centerMode: true,
                        centerPadding: '40px',
                        appendArrows: '',
                        focusOnSelect: true
                    });

                    // Init Popup
                    $('.petition-author-avatar').popup();

                    // Refresh progress
                    $('.petition-goal').progress({
                        'label': false
                    });
                }
            },
            error: function() {}
        });
    }


    // LOAD MORE PETITION
    function loadPetitions(id, context) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityPetitions').val();
        var post_number = $(id).attr('data-number');
        var typed = $(id).attr('data-type');
        var author = $(id).attr('data-author');
        var paged = $(id).attr('data-page');
        var order = $(id).attr('data-order');
        var orderby = $(id).attr('data-orderby');
        var country = $(id).attr('data-country');

        $(id).addClass('loading disabled');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': typed,
                'user_id': services_vars.user_id,
                'author_id': author,
                'paged': paged,
                'order': order,
                'orderby': orderby,
                'country': country,
                'security': security
            },
            success: function(data) {
                $(id).removeClass('loading disabled');
                if (data.status == true) {
                    var html = '';
                    $.each(data.petitions, function(id, petition) {
                        html += '<div class="ui segments petition-list-card">';
                        if (petition.approved == 'pending') {
                            html += '<div class="ui active centered inverted dimmer"><div class="content"><div class="center">' +
                                '<h2 class="ui icon header"><i class="warning icon"></i>' + services_vars.pending_approval + '</h2>' +
                                '</div></div></div>';
                        }
                        html += '<div class="ui padded segment">';
                        if (parseInt(petition.sign) >= parseInt(petition.goal) || petition.status == '1') {
                            html += '<div class="ui primary right corner large label victory-label">' + services_vars.victory_icon + '</div>';
                        }
                        html += '<div class="ui grid">' +
                            '<div class="sixteen wide mobile ten wide tablet ten wide computer column">' +
                            '<div class="petition-content">' +
                            '<div class="ui grid">' +
                            '<div class="sixteen wide column">' +
                            '<div class="ui large header list-petition-title">' +
                            '<div class="content">' +
                            '<div class="sub header truncate petition-to">' + services_vars.send_icon + services_vars.petition_to.replace(/%s/g, petition.receiver) + '</div>' +
                            '<a href="' + petition.link + '" data-bjax>' + petition.title + '</a>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="sixteen wide column tablet computer only excerpt">' +
                            '<div class="text grey">' + petition.excerpt + '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="ui grid">' +
                            '<div class="petition-footer">' +
                            '<div class="sixteen wide column">' +
                            '<span class="text grey place">';
                            if (petition.city || petition.state || petition.country) {
                            html += '<i class="map marker icon"></i>' + (petition.city ? petition.city + ', ' : '') + (petition.state ? petition.state + ', ' : '') + (petition.country ? petition.country : '');
                            }
                            html += '</span>' +
                            '<div class="ui tiny indicating primary progress petition-goal" id="petition-goal" data-value="' + petition.sign + '" data-total="' + (petition.status == '1' ? petition.sign : petition.goal) + '">' +
                            '<div class="bar">' +
                            '<div class="progress"></div>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="sixteen wide mobile six wide tablet six wide computer column">';
                        if (petition.thumbnail) {
                            html += '<a class="ui fluid rounded image petition-thumbnail" href="' + petition.link + '" target="' + ((services_vars.external_link != 0) ? '_blank' : '_self') + '" ' + ((services_vars.external_link != 0) ? '' : 'data-bjax') + '>' +
                            '<div class="ui dimmer">' +
                            '<div class="content">' +
                            '<div class="center">' +
                            '<div class="ui icon inverted circular large button"><i class="external icon"></i></div>' +
                            '</div>';
                            if (services_vars.view_counter == 1 && petition.view != '') {
                                html += '<div class="view-counter">' +
                                '<i class="eye icon"></i>' + petition.view +
                                '</div>';
                            }
                            html += '</div>' +
                            '</div>' +
                            '<img class="ui fluid rounded image lazy" data-src="' + petition.thumbnail + '" data-retina="' + petition.thumbnail_retina + '" src="' + petition.lazy_placeholder + '" alt="' + petition.title + '">' +
                            '</a>';
                        } else if (services_vars.is_mobile == 'false') {
                            html += '<div class="ui placeholder segment no-thumbnail">' +
                            '<a class="ui icon circular basic large button" href="' + petition.link + '" target="' + ((services_vars.external_link != 0) ? '_blank' : '_self') + '" ' + ((services_vars.external_link != 0) ? '' : 'data-bjax') + '><i class="external alternate icon"></i></a>';
                            if (services_vars.view_counter == 1 && petition.view != '') {
                                html += '<div class="view-counter">' +
                                '<i class="eye icon"></i>' + petition.view +
                                '</div>';
                            }
                            html += '</div>';
                        }
                            html += '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div class="ui padded segment footer-border">' +
                            '<div class="ui grid">' +
                            '<div class="ten wide tablet ten wide computer column tablet computer only">' +
                            '<span class="ui primary label petition-label-supporters">' + services_vars.supporter_icon + petition.supporter_label + '</span> ';
                        if (petition.category_name) {
                            html += '<a class="ui label petition-label-category" href="' + petition.category_link + '" data-bjax><i class="tag icon"></i>' + petition.category_name + '</a> ';
                        }
                        if (petition.comments > 0) {
                            html += '<a href="' + petition.link + '#comments' + petition.id + '" class="ui label petition-label-comments" data-bjax><i class="comments icon"></i>' + petition.comments_label + '</a>';
                        }
                        html += '</div>' +
                            '<div class="six wide tablet six wide computer right aligned column tablet computer only">';
                        html += '<a class="float right" href="' + petition.author_link + '" data-bjax>' +
                            '<img class="ui avatar image petition-author-avatar lazy" data-src="' + petition.author_avatar + '" data-retina="' + petition.author_avatar_retina + '" src="' + petition.lazy_placeholder_avatar + '" alt="' + petition.author_name + '" data-title="' + petition.author_name + '" data-content="' + (petition.city ? petition.city + ', ' : '') + (petition.state ? petition.state + ', ' : '') + (petition.country ? petition.country : '') + '" />' +
                            '</a>' +
                            '</div>' +
                            '<div class="thirteen wide column mobile only">' +
                            '<span class="ui primary label petition-label-supporters">' + services_vars.supporter_icon + petition.supporter_label_compact + '</span> ';
                        if (petition.comments > 0) {
                            html +='<a href="' + petition.link + '#comments' + petition.id + '" class="ui label petition-label-comments" data-bjax><i class="comments icon"></i>' + petition.comments_fomated + '</a>';
                        }
                        html += '</div>' +
                            '<div class="three wide right aligned column mobile only">';
                        html += '<a class="float right" href="' + petition.author_link + '" data-bjax>' +
                            '<img class="ui avatar image petition-author-avatar lazy" data-src="' + petition.author_avatar + '" data-retina="' + petition.author_avatar_retina + '" src="' + petition.lazy_placeholder_avatar + '" alt="' + petition.author_name + '" data-title="' + petition.author_name + '" data-content="' + (petition.city ? petition.city + ', ' : '') + (petition.state ? petition.state + ', ' : '') + (petition.country ? petition.country : '') + '" />' +
                            '</a>' +
                            '</div>' +
                            '</div>' +
                            '</div>' +
                            '</div>';
                    });

                    $(id).attr('data-page', (parseInt(paged) + 1));
                    $(id).attr('data-number', (parseInt(post_number) + data.found_posts));

                    // Append content
                    $(context).append(html);

                    // re init lazy load
                    re_init_lazy_load();

                    // Refresh progress
                    $('.petition-goal').progress({
                        'label': false
                    });

                    // Dimmer
                    $('.petition-list-card .ui.image, .petition-card .image')
                    .dimmer({
                        on: 'hover'
                    });

                    // hidden load more button
                    if (data.found_posts < data.per_page || (post_number + data.found_posts) == data.total) {
                        $(id).css('display', 'none');
                    }

                    // Init Popup
                    $('.petition-author-avatar').popup();

                    loadMoreVisibleHandle(id, context);
                } else {
                    $(id).removeClass('loading disabled').css('display', 'none');
                }

                // hide placeholder
                setTimeout(function() {
                    $('.content-placeholder').addClass('display none');
                }, 100);
            },
            error: function() {}
        });
    }

    function loadMoreClickHandle(ele = '#load-more', target = '#content') {
        $(ele).on('click', function() {
            loadPetitions(ele, target);
        });
    }

    function loadMoreVisibleHandle(ele = '#load-more', target = '#content') {
        $(ele).visibility({
            once: false,
            observeChanges: true,
            offset: 400,
            onTopVisible: function() {
                loadPetitions(ele, target);
            }
        });
    }

    function loadPeittionTabTrigger(eleTab, eleBtn, eleContent) {
        $(eleTab).on('click', function() {
            if ($(eleContent).text() == '') {
                $('.content-placeholder').removeClass('display none');
                $(eleBtn).trigger('click');
            }
        })
    }

    if ($('#load-more').length) {
        loadMoreClickHandle();
        loadMoreVisibleHandle();
    }

    // preload newsfeed petition
    if ($('#load-newsfeed').length) {
        if ($('#content-newsfeed').is(':visible')) {
            loadPetitions('#load-newsfeed', '#content-newsfeed');
        }

        loadMoreClickHandle('#load-newsfeed', '#content-newsfeed');
        loadMoreVisibleHandle('#load-newsfeed', '#content-newsfeed');
        loadPeittionTabTrigger('#tab-menu-newsfeed', '#load-newsfeed', '#content-newsfeed');
    }

    // load trending petition homepage
    if ($('#load-trending').length) {
        if ($('#content-trending').is(':visible')) {
            loadPetitions('#load-trending', '#content-trending');
        }

        loadMoreClickHandle('#load-trending', '#content-trending');
        loadMoreVisibleHandle('#load-trending', '#content-trending');
        loadPeittionTabTrigger('#tab-menu-trending', '#load-trending', '#content-trending');
    }

    // load recent petition homepage
    if ($('#load-recent').length) {
        if ($('#content-recent').is(':visible')) {
            loadPetitions('#load-recent', '#content-recent');
        }

        loadMoreClickHandle('#load-recent', '#content-recent');
        loadMoreVisibleHandle('#load-recent', '#content-recent');
        loadPeittionTabTrigger('#tab-menu-recent', '#load-recent', '#content-recent');
    }

    // SEND MESSAGE TO US
    $('#sendContactMessageBtn').on('click', function() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityContactPage').val();
        $('#cp_response').empty();
        $('#sendContactMessageBtn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_send_message_to_company',
                'company_email': $('#company_email').val(),
                'name': $('#cp_name').val(),
                'email': $('#cp_email').val(),
                'subject': $('#cp_subject').val(),
                'message': $('#cp_message').val(),
                'security': security
            },
            success: function(data) {
                $('#sendContactMessageBtn').removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#cp_name').val('');
                    $('#cp_email').val('');
                    $('#cp_subject').val('');
                    $('#cp_message').val('');
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                }

                $('#cp_response').html(message);
            },
            error: function(errorThrown) {
                $('#sendContactMessageBtn').removeClass('loading disabled');
            }
        });
    });

    // SEND MESSAGE TO USER
    $('#sendBtn').on('click', function() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityContactUser').val();
        $('#contact-response').empty();
        $('#sendBtn').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_send_message_to_user',
                'user_email': $('#user_email').val(),
                'name': $('#contact_name').val(),
                'email': $('#contact_email').val(),
                'subject': $('#contact_subject').val(),
                'message': $('#contact_message').val(),
                'security': security
            },
            success: function(data) {
                $('#sendBtn').removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                    $('#contact_subject').val('');
                    $('#contact_message').val('');
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                }

                $('#contact-response').html(message);
            },
            error: function(errorThrown) {
                $('#sendBtn').removeClass('loading disabled');
            }
        });
    });

    // SEND INVITATION LETTER
    $('#send-invite').on('click', function() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityInvitation').val();

        $('#invitation-response').empty();
        $('#send-invite').addClass('loading disabled');

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_send_invatation',
                'user_email': $('#user_email').val(),
                'name': $('#invite_name').val(),
                'email': $('#invite_email').val(),
                'decision_name': $('#invite_decision_name').val(),
                'title': $('#invite_title').val(),
                'subject': $('#invite_subject').val(),
                'message': $('#invite_message').val(),
                'link': $('#invite_link').val(),
                'security': security
            },
            success: function(data) {
                $('#send-invite').removeClass('loading disabled');
                var message = '';
                if (data.status === true) {
                    message = '<div class="ui success message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                } else {
                    message = '<div class="ui error message">' +
                        '<i class="close icon"></i><i class="check circle icon"></i>' + data.message +
                        '</div>';
                }

                $('#invitation-response').html(message);
            },
            error: function(errorThrown) {
                $('#send-invite').removeClass('loading disabled');
            }
        });
    });

    // SEARCH DECISION MAKERS
    if ($('.decision-search').length) {
        decisionMakerSearch('.decision-search');
    }

    $(document).on('click', '.decision-search', function() {
        decisionMakerSearch('.decision-search');
    });

    function decisionMakerSearch(element) {
        $(element).search({
            showNoResults: false,
            transition: services_vars.modal_transition,
            minCharacters : services_vars.min_characters,
            maxResults : services_vars.max_results,
            apiSettings: {
              url: services_vars.api_url + '?type=decisionmakers&q={query}'
            },
            fields: {
              results: 'results',
              title: 'name',
              description: 'description',
              image: 'avatar'
            },
            onSelect: function(result, response) {
                $(this).find('.decision-title').val(result.description)
                $(this).find('.new_decisionmakers').val(result.id)
            },
            onResults: function(response) {
                $(this).find('.new_decisionmakers').val('');
            }
        });
        $(this).find('.decision-title, .prompt').change(function() {
            var decisionmakers = $(this).next().val()
            if (decisionmakers) {
                $(this).next().val('')
            }
        });
    }

    // SEARCH PETITION AUTOCOMPLETE
    var search_settings = $.parseJSON( services_vars.search_settings );
    var suggest_fiels = {
        results : 'results',
        title : 'title'
    }

    if (search_settings.conikal_s_link_field == 1) { suggest_fiels.url = 'link' }
    if (services_vars.is_mobile == 'false') {
        if (search_settings.conikal_s_description_field == 1) { suggest_fiels.description = 'excerpt' }
        if (search_settings.conikal_s_image_field == 1) { suggest_fiels.image = 'thumbnail' }
        if (search_settings.conikal_s_supporters_field == 1) { suggest_fiels.price = 'sign_compact' }
    }

    if ($('.search-form').length) {
        $('.search-form').search({
            minCharacters : services_vars.min_characters,
            transition: services_vars.modal_transition,
            type: services_vars.search_type,
            apiSettings: {
                onResponse: function(petitionResponse) {
                    $('.search-input').keydown(function(e){
                        if (e.keyCode === 13) {
                            e.preventDefault();
                            document.location.href = petitionResponse.action.url;
                        }
                    })
                    if (services_vars.search_type == 'category') {
                        var response = {
                                results : {},
                                action : petitionResponse.action
                            };
                        $.each(petitionResponse.results, function(index, item) {
                          var
                            category   = item.category_name || 'Unknown',
                            maxResults = services_vars.max_results
                          ;
                          if(index >= maxResults) {
                            return false;
                          }
                          // create new category
                          if(response.results[category] === undefined) {
                            response.results[category] = {
                              name    : category,
                              results : []
                            };
                          }
                          // add result to category
                          response.results[category].results.push({
                            title           : item.title,
                            excerpt         : item.excerpt,
                            link            : item.link,
                            thumbnail       : item.thumbnail,
                            sign_compact    : item.sign_compact
                          });
                        });
                    } else {
                        response = petitionResponse;
                    }
                    return response;
                },
                url: services_vars.api_url + '?type=petition&q={query}'
            },
            fields: suggest_fiels
        });
    }

    function searchResultHTML(data) {
        var html = '';
        $.each(data, function(index, item) {
            html += '<div class="item search-results-item">';
                        html += '<a href="' + item.link + '" class="image" data-bjax>';
                        if ( parseInt(item.sign) >= parseInt(item.goal) || item.status == '1') {
                            html += '<div class="ui primary left corner label victory-label"> ' + services_vars.victory_icon + '</div>';
                        }
                        html += '<img class="ui fluid rounded image lazy" src="' + item.thumbnail_retina + '" alt="' + item.author_name + '"/>' +
                        '</a>' +
                        '<div class="middle aligned content">' +
                            '<a class="header" href="' + item.link + '" data-bjax>' + item.title + '</a>' +
                            '<div class="meta">' +
                                '<span class="receiver truncate petition-to">' + services_vars.send_icon + ' ' + services_vars.petition_to.replace(/%s/g, item.receiver) + '</span>' +
                            '</div>' +
                            '<div class="description">' +
                                '<div class="text grey">' + item.excerpt_short + '</div>' +
                            '</div>' +
                            '<div class="extra display-computer only display-tablet only">' +
                                '<div class="ui right floated tiny header">' +
                                    '<a href="' + item.author_link + '" data-bjax>' +
                                        ' <img class="ui avatar image supporter-avatar lazy" src="' + item.author_avatar_retina + '" alt="' + item.author_name + '" data-title="' + item.author_name + '"';
                                        if (item.author_city || item.author_state || item.author_country) {
                                            html += ' data-content="' + (item.author_city ? item.author_city + ', ' : '') + (item.author_state ? item.author_state + ', ' : '') + (item.author_country ? item.author_country : '') + '"'
                                        }
                                        html += '/>' +
                                    '</a>' +
                                '</div>' +
                                '<span class="ui primary label">' + services_vars.supporter_icon + item.sign_fomated + ' ' + services_vars.supporters + '</span> ' +
                                '<span class="ui label"><i class="comments icon"></i>' + item.comments_label + '</span>';
                                if (item.category_name) {
                                    html += '<a class="ui label" href="' + item.category_link + '" data-bjax><i class="tag icon"></i>' + item.category_name + '</a>';
                                }
                            html += '</div>' +
                            '<div class="extra display-mobile only">' +
                                '<div class="ui right floated tiny header">' +
                                    '<a href="' + item.author_link + '" data-bjax>' +
                                        '<img class="ui avatar image" src="' + item.author_avatar + '" />' +
                                    '</a>' +
                                '</div>' +
                                '<span class="ui primary label">' + services_vars.supporter_icon + item.sign_fomated + ' ' + services_vars.supporters + '</span> ' +
                                '<span class="ui label"><i class="comments icon"></i>' + item.comments + '</span>' +
                            '</div>' +
                        '</div>' +
                    '</div>';
        });

        return html;
    }

    // PETITION SEARCH REAL-TIME
    if ($('.page-search').length) {
        $('.page-search').search({
            minCharacters : services_vars.min_characters,
            maxResults : services_vars.max_results,
            transition: services_vars.modal_transition,
            apiSettings: {
                url: services_vars.api_url + '?type=petition&q={query}',
                onResponse: function(response) {
                    var html = searchResultHTML(response.results);
                    $('.results-number').text(response.total);
                    $('#search-results').html(html);
                    re_init_lazy_load();

                    $('.search-input').keydown(function(e){
                        if (e.keyCode === 13) {
                            e.preventDefault();
                            document.location.href = response.action.url;
                        }
                    });

                    window.history.pushState({href: response.action.url}, '', response.action.url);
                }
            }
        });
    }

    // SET VIEWERS LIST
    $('#media-embed').on('click', function() {
        setTimeout(function() {
            setViewersList('players')
        }, parseInt(services_vars.video_watching_time) * 1000);
    });

    if($('#securityViews').length) {
        setViewersList('visitors')
    }

    function setViewersList(type) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityViews').val();

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_unique_post_visitors',
                'user_id': services_vars.user_id,
                'post_id': services_vars.post_id,
                'type': type,
                'security': security
            },
            success: function(data) {
                
            }
        });
    }

    // LOAD USERS VISIT
    if($('#viewsChart').length) {
        usersVisit('visitors', 1);
        usersVisit('players', 1);

        $('#load-more-visitors, #load-more-players').on('click', function() {
            var type = $(this).attr('data-type');
            var paged = $(this).attr('data-paged');
            usersVisit(type, parseInt(paged));
        });
    }

    function usersVisit(type, paged) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        $('#load-more-' + type).addClass('loading disabled');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_petition_users_visitors',
                'id': $('#petition_id').val(),
                'type': type,
                'paged': paged,
                'security': security
            },
            success: function(data) {
                $('#load-more-' + type).removeClass('loading disabled');

                if (data.status == 1) {
                    // recent viewers
                    var html = '';
                    $.each(data.users, function(index, item) {
                        html += '<div class="item"><div class="right floated content">' + item.visit_time + '</div>' +
                            '<img class="ui avatar image lazy" data-src="' + item.user_avatar + '" data-retina="' + item.user_avatar_retina + '" src="' + item.user_avatar_lazy + '" />' +
                            '<div class="content">' +
                            '<a href="' + item.user_link + '" class="header" data-bjax>' + item.user_name + '</a>';
                        if (item.user_ip) {
                            html += '<span class="text grey">' + item.user_ip + '</span>';
                        } else {
                            html += '<span class="text grey">' + (item.user_city ? item.user_city + ', ' : '') + (item.user_state ? item.user_state + ', ' : '') + (item.user_country ? item.user_country : '') + '</span>';
                        }
                        html += '</div></div>';
                    });
                    $('#users-' + type + '-list').append(html);
                    $('#number-' + type).text(data.total);
                    $('#load-more-' + type).attr('data-paged', parseInt(paged) + 1);

                    re_init_lazy_load();
                } else {
                    $('#load-more-' + type).removeClass('loading disabled').addClass('display none');
                }
            },
            error: function(errorThrown) {
                $('#load-more-' + type).removeClass('loading disabled');
            }
        });
    }


    // PETITION VISITORS CHART INIT
    if ($('#viewsChart').length) {
        loadVisitorChart();
        $('#visitor_chart_date').on('change', function() {
            loadVisitorChart(false)
            $('#visitor_chart_date_range_start, #visitor_chart_date_range_end').val('')
        })

        $('#visitor_chart_date_apply').on('click', function() {
            var date_start  = $('#visitor_chart_date_range_start').val()
            var date_end    = $('#visitor_chart_date_range_end').val()
            if (date_start && date_end) {
                loadVisitorChart(true)
            }
        });
    }

    function loadVisitorChart(range_mode = false) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        var date_start  = '';
        var date_end    = '';
        if (range_mode) {
            var date_start  = $('#visitor_chart_date_range_start').val()
            var date_end    = $('#visitor_chart_date_range_end').val()
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_petition_visitors_chart_js',
                'id': $('#petition_id').val(),
                'date_range': $('#visitor_chart_date').val(),
                'date_start': date_start,
                'date_end': date_end,
                'security': security
            },
            success: function(data) {
            if (data.status == 1) {
                // chart initial
                var myChart = new Chart(document.getElementById("viewsChart"), {
                    type: "bar",
                    data: {
                        labels: data.visitors_date,
                        datasets: [
                        {
                            type: 'line',
                            label: data.conversion_title,
                            data: data.conversions_data,
                            fill: false,
                            lineTension: 0,
                            backgroundColor: data.colors.main_color,
                            borderColor: data.colors.main_color,
                            borderWidth: 3,
                            yAxisID: 'B',
                        }, {
                            label: data.visitors_title,
                            data: data.visitors_data,
                            fill: false,
                            lineTension: 0,
                            backgroundColor: data.colors.chart_color_1,
                            borderColor: data.colors.chart_color_1,
                            borderWidth: 3,
                            yAxisID: 'A',
                        }, {
                            label: data.players_title,
                            data: data.players_data,
                            fill: false,
                            lineTension: 0,
                            backgroundColor: data.colors.chart_color_2,
                            borderColor: data.colors.chart_color_2,
                            borderWidth: 3,
                            yAxisID: 'A',
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                id: 'A',
                                type: 'linear',
                                position: 'left',
                                ticks: {
                                    beginAtZero:true
                                }
                            }, {
                                id: 'B',
                                type: 'linear',
                                position: 'right',
                                ticks: {
                                  max: 100,
                                  min: 0
                                }
                            }]
                        }
                    }
                });
            }
            },
            error: function(errorThrown) {
            }
        });
    }


    // PETITION CHART INIT
    if ($('#securityDashboard').length) {
        loadSupporterChart()
        $('#supporter_chart_date').on('change', function() {
            loadSupporterChart(false)
            $('#supporter_chart_date_range_start, #supporter_chart_date_range_end').val('')
        });

        $('#supporter_chart_date_apply').on('click', function() {
            var date_start  = $('#supporter_chart_date_range_start').val()
            var date_end    = $('#supporter_chart_date_range_end').val()
            if (date_start && date_end) {
                loadSupporterChart(true)
            }
        });
    }

    function loadSupporterChart(range_mode = false) {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securityDashboard').val();

        var date_start  = '';
        var date_end    = '';
        if (range_mode) {
            var date_start  = $('#supporter_chart_date_range_start').val()
            var date_end    = $('#supporter_chart_date_range_end').val()
        }

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_petition_chart_js',
                'id': $('#petition_id').val(),
                'date_range': $('#supporter_chart_date').val(),
                'date_start': date_start,
                'date_end': date_end,
                'security': security
            },
            success: function(data) {
            if (data.status == 1) {
                // chart initial
                var myChart = new Chart(document.getElementById("supportersChart"), {
                    type: "line",
                    data: {
                        labels: data.supporter_date,
                        datasets: [{
                            label: data.supporter_title,
                            data: data.supporter_data,
                            fill: false,
                            lineTension: 0,
                            backgroundColor: data.colors.main_color,
                            borderColor: data.colors.main_color,
                            borderWidth: 3
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero:true
                                }
                            }]
                        }
                    }
                });

                // Regions bar chart
                var myBarChart = new Chart(document.getElementById("regionsChart"), {
                    type: "horizontalBar",
                    data: {
                        labels: data.regions_labels,
                        datasets: [
                            {
                                data: data.regions_data,
                                label: data.regions_title,
                                backgroundColor: [
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color
                                ],
                                borderColor: [
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color
                                ],
                                borderWidth: 1,
                            }
                        ]
                    },
                    options: {
                        elements: {
                            arc: {
                                borderColor: "#ffffff"
                            }
                        }
                    }
                });

                // Gender pie chart
                var myPieChart = new Chart(document.getElementById("genderChart"),{
                    data: {
                        datasets: [{
                            data: data.gender_data,
                            label: data.gender_title,
                            backgroundColor: [
                                data.colors.chart_color_1,
                                data.colors.chart_color_2,
                                data.colors.main_color,
                            ]
                        }],
                        labels: data.gender_labels
                    },
                    type: "pie",
                    options: {
                        elements: {
                            arc: {
                                borderColor: "#ffffff"
                            }
                        }
                    }
                });

                // Age bar chart
                var myBarChart = new Chart(document.getElementById("ageChart"), {
                    type: "horizontalBar",
                    data: {
                        labels: data.age_labels,
                        datasets: [
                            {
                                data: data.age_data,
                                label: data.age_title,
                                backgroundColor: [
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color
                                ],
                                borderColor: [
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color,
                                    data.colors.main_color
                                ],
                                borderWidth: 1,
                            }
                        ]
                    },
                    options: {
                        elements: {
                            arc: {
                                borderColor: "#ffffff"
                            }
                        }
                    }
                });


                // recent supporter
                var html = '';
                $.each(data.recent_supporters, function(index, item) {
                    html += '<div class="item"><div class="right floated content">' +
                        item.sign_date + '</div>' +
                        '<img class="ui avatar image supporter-avatar lazy" data-src="' + item.user_avatar + '" data-retina="' + item.user_avatar_retina + '" src="' + item.user_avatar_lazy + '" />' +
                        '<div class="content">' +
                        '<a href="' + item.user_link + '" class="header" data-bjax>' + item.user_name + '</a>';
                    if (item.user_city || item.user_state || item.user_country) {
                        html += '<span class="text grey">' + (item.user_city ? item.user_city + ', ' : '') + (item.user_state ? item.user_state + ', ' : '') + (item.user_country ? item.user_country : '') + '</span>';
                    }
                    html += '</div></div>';
                });
                $('#supporters-list').html(html);

                re_init_lazy_load();
            }
            },
            error: function(errorThrown) {
            }
        });
    }
    

    // FILTER SEARCH
    $('#search_order, #search_orderby, input[name="search_topics[]"], input[name="search_category[]"], input[name="search_neighborhood[]"], input[name="search_city[]"], input[name="search_state[]"], #search_country').change(function(){
        filter_search()
    });

    function filter_search() {
        var ajaxURL = services_vars.admin_url + 'admin-ajax.php';
        var security = $('#securitySearch').val();

        var topics = '',
            category = '',
            neighborhood = '',
            city = '',
            state = '',
            country = $('#search_country option:selected').val(),
            order = $('#search_order').val(),
            orderby = $('#search_orderby').val();

        $('input[name="search_topics[]"]').each(function(index) { topics += $(this).val() + ',' })
        $('input[name="search_category[]"]:checked').each(function(index) { category += $(this).val() + ',' })
        $('input[name="search_neighborhood[]"]:checked').each(function(index) { neighborhood += $(this).val() + ',' })
        $('input[name="search_city[]"]:checked').each(function(index) { city += $(this).val() + ',' })
        $('input[name="search_state[]"]:checked').each(function(index) { state += $(this).val() + ',' })

        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: ajaxURL,
            data: {
                'action': 'conikal_load_search_petitions',
                'search_keyword': $('.search-input').val(),
                'search_topics': topics,
                'search_category': category,
                'search_neighborhood': neighborhood,
                'search_city': city,
                'search_state': state,
                'search_country': country,
                'search_order': order,
                'search_orderby': orderby,
                'security': security
            },
            success: function(response) {
                var html = searchResultHTML(response.petitions);
                $('.results-number').text(response.total);
                $('#search-results').html(html);
                $('html,body').animate({ scrollTop: 0 }, 300)
            }
        });
    }

    $('#reset-filter').on('click', function() {
        $('#form-filter')[0].reset()
        $('#search_country').dropdown('restore defaults')
        $('#search_topics').dropdown('restore defaults')
        filter_search()
    });

    // PLACE AUTOCOMPLATE
    if ($('#new_address').length > 0) {
        var stateOptions = {
            strictBounds: false,
            types: [services_vars.google_place_types],
            language: [services_vars.site_locale]
        }
        var address = document.getElementById('new_address');
        var addressAuto = new google.maps.places.Autocomplete(address, stateOptions);
        google.maps.event.addListener(addressAuto, 'place_changed', function() {
            var place = addressAuto.getPlace();
            $('#new_address').blur();
            //setTimeout(function() { $('#new_address').val(place.name); }, 1);
            var lat = place.geometry.location.lat,
                lng = place.geometry.location.lng;

            for (var i = 0; i < place.address_components.length; i++) {
                var addressType = place.address_components[i].types[0];

                var val = place.address_components[i].short_name;

                if (addressType === 'administrative_area_level_1') {
                    $('#new_state').val(val);
                } else if (addressType === 'administrative_area_level_2') {
                    $('#new_city').val(val);
                } else if (addressType === 'locality') {
                    $('#new_city').val(val);
                } else if (addressType === 'sublocality') {
                    $('#new_neighborhood').val(val);
                } else if (addressType === 'neighborhood') {
                    $('#new_neighborhood').val(val);
                } else if (addressType === 'sublocality_level_1') {
                    $('#new_neighborhood').val(val);
                } else if (addressType === 'country') {
                    $('#new_country').val(val);
                } else if (addressType === 'postal_code') {
                    $('#new_zip').val(val);
                }

            }

            $('#new_lat').val(lat);
            $('#new_lng').val(lng);

            return false;
        });
    }

    $('#new_address').keydown(function(){
        if ($(this).val().length <= 1) {
            $('#new_country').val('');
            $('#new_state').val('');
            $('#new_city').val('');
            $('#new_neighborhood').val('');
            $('#new_zip').val('');
            $('#new_lat').val('');
            $('#new_lng').val('');
        }
    });

    function place_autocomplete(id) {
        var stateOptions = {
            strictBounds: false,
            types: [services_vars.google_place_types],
            language: [services_vars.site_locale]
        }
        if ($('#address' + id).length > 0) {
            var address = document.getElementById('address' + id);
            var addressAuto = new google.maps.places.Autocomplete(address, stateOptions);
            google.maps.event.addListener(addressAuto, 'place_changed', function() {
                var place = addressAuto.getPlace();
                $('#address' + id).blur();
                //setTimeout(function() { $('#new_address').val(place.name); }, 1);
                var lat = place.geometry.location.lat,
                    lng = place.geometry.location.lng;

                for (var i = 0; i < place.address_components.length; i++) {
                    var addressType = place.address_components[i].types[0];

                    var val = place.address_components[i].short_name;

                    if (addressType === 'administrative_area_level_1') {
                        $('#state' + id).val(val);
                    } else if (addressType === 'administrative_area_level_2') {
                        $('#city' + id).val(val);
                    } else if (addressType === 'locality') {
                        $('#city' + id).val(val);
                    } else if (addressType === 'sublocality') {
                        $('#neighborhood' + id).val(val);
                    } else if (addressType === 'neighborhood') {
                        $('#neighborhood' + id).val(val);
                    } else if (addressType === 'sublocality_level_1') {
                        $('#neighborhood' + id).val(val);
                    } else if (addressType === 'country') {
                        $('#country' + id).val(val);
                    } else if (addressType === 'postal_code') {
                        $('#zip' + id).val(val);
                    }

                }
                $('#lat' + id).val(lat);
                $('#lng' + id).val(lng);
                return false;
            });
        }
        $('#address' + id).keydown(function(){
            if ($(this).val().length <= 1) {
                $('#country' + id).val('');
                $('#state' + id).val('');
                $('#city' + id).val('');
                $('#neighborhood' + id).val('');
                $('#zip' + id).val('');
                $('#lat' + id).val('');
                $('#lng' + id).val('');
            }
        });
    }

    guestSignAddressAutocomplete();
    function guestSignAddressAutocomplete() {
        $('.guest-sign').each(function() {
            var petition_id =  $(this).attr('data-id');
            place_autocomplete('Sign' + petition_id);
            place_autocomplete('SignSidebar' + petition_id);
            place_autocomplete('SignSC' + petition_id);
        });
    }

    place_autocomplete('Signup');
    place_autocomplete('User');
    place_autocomplete('Search');


    // 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');
    }

})(jQuery);
