var license = null;

(function ($) {

    "use strict";

    $(function () {

        var SchematicAdminInstallation = (function () {

            $('#schematic_verify_api_key').click(function () {
                var button = $(this);

                if (!button.val()) {
                    return false;
                }

                if (button.attr('disabled')) {
                    return false;
                }

                button.attr('disabled', 'disabled');
                button.val('Verifying KEY... Please wait.')

                var data = {
                    action: "schematic_verify_api_key",
                    _schematic_api_key: $('#schematic_key').val(),
                    _ajax_nonce: $('#schematicNonce').val()

                };

                $.post(ajaxurl, data, function (response) {
                    if (response.status == 'success') {
                        $('#schematic_key').attr('disabled', 'disabled');

                        button.val('Key Verified!');
                        $('#api_key_error').hide();
                        $('#api_key_success').html(response.data);
                        $('#api_key_success_proceed').show();

                        license = response.key;

                    } else {
                        if (response.success == false) {
                            $('#api_key_error').html(response.data).show();
                            button.removeAttr('disabled');
                            button.val('VERIFY KEY');
                            return false;
                        }

                        button.removeAttr('disabled');
                        button.val('VERIFY KEY');
                        $('#api_key_error').html(response.data).show();

                        setTimeout(function () {
                            $('#api_key_error').fadeOut(1500, function () {
                                $('#api_key_error').html();
                            });
                        }, 3500);
                    }
                });
            });

            $('#schematic_api_key_save').click(function () {
                $('#api_key_success').remove();
                $('#api_key_success_proceed').html('Loading... Please wait');

                var data = {
                    action: "schematic_save_api_key",
                    _schematic_api_key: $('#schematic_key').val(),
                    key: license,
                    _ajax_nonce: $('#schematicNonce').val()
                };

                $.post(ajaxurl, data, function (response) {
                  //if (response.success) {
                        window.location.replace($('#redirect_url').val());
                  //  }
                });
            });

        }(SchematicAdminInstallation));

    });

})(jQuery);