$(function () {
    var errorDiv = $('<div>').addClass('error-message');

    function error(msg) {
        $('.title').after(errorDiv.text(msg));
    }

    $('.save').click(function () {
        save(function(){});
    });

    $('.save-and-sign').click(function () {
       save(function () {
           sign();
       })
    });

    function save(callback) {
        var fingerprint = $('.server-form').data('fingerprint');

        var data = $('.server-form input,.server-form select').serializeArray();

        $.post('/panel/server/' + fingerprint + '/edit', data, function (data) {
            if (!data.success) {
                error(data.error);
                return;
            }

            callback();
        }, 'json');
    }

    function sign() {
        var fingerprint = $('.server-form').data('fingerprint');
        $.post(
            '/panel/server/sign',
            {
                fingerprint: fingerprint
            },
            function (data) {
                if (!data.success) {
                    error(data.error);
                    return;
                }

                location.reload();
            },
            'json'
        );
    }
});