$(function () {
    var error = $('<div class="alert alert-danger" role="alert"></div>');

   $('.magic-csr').click(function () {
       var name = $('#name').val();

       if (name.length === 0) {
           $('h2').after(error.text("Name can't be empty"));
           return;
       }
       
       if (!/^[A-Za-z0-9\-]+$/.test(name)) {
           $('h2').after(error.text("Only alphanumeric and - allowed in name"));
           return;
       }

       var user = $('#user-input').val();

       var keys = forge.pki.rsa.generateKeyPair(1024);
       var csr = forge.pki.createCertificationRequest();
       var commonName  = name + '.' + user;

       csr.publicKey = keys.publicKey;
       csr.setSubject([{
           name: 'commonName',
           value: commonName
       }]);
       csr.sign(keys.privateKey);
       var csrPem = forge.pki.certificationRequestToPem(csr);

       var newCertParams = {
           csr: csrPem,
           name: name
       };

       var keyPem = "";

       if ($('#wantsPassword').prop('checked')) {
           keyPem = forge.pki.encryptRsaPrivateKey(keys.privateKey, $('#password').val());
           newCertParams.key = keyPem;
       } else {
           keyPem = forge.pki.privateKeyToPem(keys.privateKey);
       }

       $.post('/panel/certificates/new', newCertParams, function (data) {
           if (data.success) {
               var zip = new JSZip();
               zip.file(commonName + '.key', keyPem);

               for(var file in data.zip) {
                   zip.file(file, data.zip[file]);
               }

               var content = zip.generate({type:"blob"});
               saveAs(content, commonName + '-vpn.zip');
               location.href = '/panel';
           } else {
               $('h2').after(error.text(data.error));
           }
       }, 'json');
   });

    $("#wantsPassword").change(function () {
        $('#password, #saveOnline').prop('disabled', !this.checked);
    });
});
