function saveChallenge() {
    jQuery('#loading').show();
    var nonce = jQuery('.nonce').val(),
        hashtag = jQuery('#fe-hashtag').val(),
        description = jQuery('#fe-description').val();

    jQuery.ajax({
        type : "post",
        dataType : "json",
        url : challengesAjax.ajaxurl,
        data : {action: "save_challenge", nonce: nonce, hashtag: hashtag, description: description},
        success: function(response) {
            if(response.type == "success") {
                jQuery('#loading').hide();
                window.location.reload();
            }
            else {
                alert("Error - Insert all required fields!")
            }
        }
    });
    return false;
}

function lockChallenge() {
    jQuery('#loading').show();
    var nonce = jQuery(this).attr('data-nonce'),
        post_id = jQuery(this).attr('data-id'),
        status = jQuery(this).attr('data-status'),
        invert_status = ((status == "active")?"archive":"active"),
        status_button_text = ((invert_status == "active")?"Lock":"Unlock"),
        clicked_item = jQuery(this);

    jQuery.ajax({
        type : "post",
        dataType : "json",
        url : challengesAjax.ajaxurl,
        data : {action: "lock_challenge", nonce: nonce, post_id: post_id, status: status},
        success: function(response) {
            if(response.type == "success") {
                clicked_item.closest('.challenge').removeClass(status).addClass(invert_status);
                clicked_item.html(status_button_text).attr('data-status', invert_status);
                clicked_item.parent().parent().find('.challenge-admin-close').trigger('click');
                jQuery('#loading').hide();
            }
            else {
                alert("Error - Insert all required fields!")
            }
        }
    });
    return false;
}

function hideChallenge() {
    jQuery('#loading').show();
    var nonce = jQuery(this).attr('data-nonce'),
        post_id = jQuery(this).attr('data-id');

    jQuery.ajax({
        type : "post",
        dataType : "json",
        url : challengesAjax.ajaxurl,
        data : {action: "hide_challenge", nonce: nonce, post_id: post_id},
        success: function(response) {
            if(response.type == "success") {
                jQuery('#loading').hide();
                window.location.reload();
            }
            else {
                alert("Error - Insert all required fields!")
            }
        }
    });
    return false;
}

(function(jQuery){
    "use strict";

    jQuery(document).ready(function(){
        jQuery('#save-challenge').click(saveChallenge);
        jQuery('.challenge-admin-lock').click(lockChallenge);
        jQuery('.challenge-admin-hide').click(hideChallenge);
    });

})(jQuery);