// Generated by CoffeeScript 1.12.8
(function() {
  var sendUrl, tryssl;

  tryssl = function(myevent) {
    var e, form, path;
    form = $(myevent.currentTarget).closest('form');
    path = window.location.pathname;
    console.log('path -> ', path);
    console.log('Call URL -> ', window.datas.sslHost);
    e = jQuery.Event("sslAttempt");
    $(document).trigger(e);
    if (!e.isDefaultPrevented()) {
      $.ajax(window.datas.sslHost, {
        dataType: 'json',
        xhrFields: {
          withCredentials: true
        },
        success: function(data) {
          console.log('Success -> ', data);
          e = jQuery.Event("sslSuccess");
          $(document).trigger(e, [data]);
          if (!e.isDefaultPrevented()) {
            if (data.ajax_auth_token) {
              form.find('input[name="ajax_auth_token"]').attr("value", data.ajax_auth_token);
            }
            return sendUrl(form, path);
          }
        },
        error: function(result) {
          console.log('Error during AJAX SSL authentication', result);
          e = jQuery.Event("sslFailure");
          $(document).trigger(e, [result]);
          if (!e.isDefaultPrevented()) {
            if (result.status === 0) {
              sendUrl(form, path);
            }
            if (result.responseJSON && 'error' in result.responseJSON && result.responseJSON.error === "9") {
              sendUrl(form, path);
            }
            if (result.responseJSON && 'html' in result.responseJSON) {
              $('#errormsg').html(result.responseJSON.html);
              return $(window).trigger('load');
            }
          }
        }
      });
    }
    return false;
  };

  sendUrl = function(form, path) {
    var form_url;
    form_url = form.attr('action');
    if (form_url.match(/^#$/)) {
      form_url = path;
    } else {
      form_url = form_url + path;
    }
    console.log('form action URL -> ', form_url);
    form.attr('action', form_url);
    return form.submit();
  };

  $(document).ready(function() {
    if (!window._ssl_js_done) {
      window._ssl_js_done = true;
      return $('.sslclick').on('click', tryssl);
    }
  });

}).call(this);
