$(document).ready(function () {
    "use strict";

    if (typeof ipAdminIsAutogenerated !== "undefined") {
        $(document.body).append(ipAdminIsAutogenerated);
    }

    // Do not allow to close popup, except through confirmation or changing credentials
    var $modal = $('.ipsModuleAdminIsAutogeneratedModal');
    $modal.modal({
//        backdrop: 'static',
//        keyboard: false
    });

    // Changing means removing temporary data and redirecting to Administrators page
    $modal.find('.ipsChange').on('click', function (e) {
        e.preventDefault();
        removeAdminIsAutogeneratedAjax('change');
    });
    // Confirming means removing temporary data and closing popup
    $modal.find('.ipsConfirm').on('click', function (e) {
        e.preventDefault();
        removeAdminIsAutogeneratedAjax('close');
    });


    function removeAdminIsAutogeneratedAjax(action) {
        var postData = {
            'aa': 'Admin.removeAdminIsAutogeneratedAjax',
            'action': action,
            'securityToken': ip.securityToken,
            'jsonrpc': '2.0'
        };

        $.ajax({
            url: ip.baseUrl,
            data: postData,
            dataType: 'json',
            type: 'POST',
            success: function (response) {
                if (response && response.result) {
                    if (response.result.redirect) {
                        document.location = response.result.redirect;
                    } else if (response.result.close) {
                        // Closing popup
                        $modal.modal('hide');
                    }
                } else if (response && response.error && response.error.message) {
                    alert(response.error.message);
                } else {
                    alert(response.responseText);
                }
            },
            error: function (response) {
                alert('Unexpected error.' + response.responseText);
            }
        });
    }
});
