(function() {
  $(document).on('initialize', '#proxy', function() {
    var compareHttpHosts, extractHost, form, host_header_warning, input_changed_from_default, reset_proxy_input, toggle_form_changed_ui, toggle_host_header_warning, toggle_reset_buttons;
    toggledInputsInit();
    $("input.error").tipsy({
      trigger: "focus"
    });
    $("form.proxy").on("change keyup", 'input, select', function() {
      var code, code_production, credentials, el, el_production, extheaders, k, param, param_name, path, proxy, proxy_production, q, query, ref, v, value;
      if ($("#proxy_api_test_path").val()) {
        $("#client-request").show();
        $("#proxy_api_test_path_input > .inline-hints").html("Optional GET request to a API gateway endpoint. We will use this call\nto validate your API gateway setup using credentials of the first live\napplication. You can try it yourself by copying the following command\ninto your shell:");
        el = $('#api-test-curl');
        el_production = $('#api-production-curl');
        proxy = $('#proxy_sandbox_endpoint').val();
        proxy_production = $('#proxy_hosted_proxy_endpoint').val();
        path = $('#proxy_api_test_path').val();
        extheaders = ' ';
        credentials = {};
        ref = el.data('credentials');
        for (param in ref) {
          value = ref[param];
          param_name = $("#proxy_auth_" + param).val() || param;
          credentials[param_name] = value;
        }
        if ($("#proxy_credentials_location_input input:checked").val() === 'headers') {
          for (k in credentials) {
            v = credentials[k];
            extheaders += "-H '" + k + ": " + v + "' ";
          }
          query = '';
        } else {
          q = path.match(/\?/) ? '&' : '?';
          query = "" + q + ($.param(credentials));
          extheaders = '';
        }
        code = "curl \"" + proxy + path + query + "\" " + extheaders;
        el.html(code);
        code_production = "curl \"" + proxy_production + path + query + "\" " + extheaders;
        return el_production.html(code_production);
      } else {
        $("#proxy_api_test_path_input > .inline-hints").html("Optional GET request to a API gateway endpoint. This call\nhas been left blank and therefore it will not be possible to\ntest if the connection between client, proxy & API is working\ncorrectly.");
        $(".feedback").addClass("no-test");
        return $("#client-request").hide();
      }
    });
    $("input.destroyer[value=\"1\"]:not(:disabled)").closest("tr").addClass("deleted");
    $("a[href=\"#add-proxy-rule\"]").live("click", function() {
      var rule, timestamp;
      rule = $("#new-proxy-rule-template").html();
      timestamp = new Date().getTime();
      rule = rule.replace(/\{new_id_.*\}/g, timestamp);
      rule = $("<tr>").append(rule);
      rule.find("input:not(.destroyer),select").removeAttr("disabled");
      $("table#proxy-rules > tbody").append(rule);
      rule.find('.pattern input:first').focus();
      return false;
    });
    $("a[href=\"#delete-proxy-rule\"]").live("click", function() {
      var tr;
      tr = $(this).closest("tr");
      if (tr.hasClass("deleted")) {
        tr.removeClass("deleted");
        tr.find("input.proxy_rule_id, .destroyer").attr("disabled", "disabled");
      } else {
        tr.addClass("deleted");
        tr.find("input, select").attr("disabled", "disabled");
        tr.find("input.proxy_rule_id, .destroyer").removeAttr("disabled");
      }
      tr.find("input").trigger("proxy.rule.change");
      return false;
    });
    $("a[href=\"#edit-proxy-rule\"]").live("click", function() {
      var tr;
      tr = $(this).closest("tr");
      if (!tr.hasClass("deleted")) {
        tr.find("select,input:not(.destroyer)").removeAttr("disabled");
      }
      return false;
    });
    host_header_warning = $('<span class="warning-host-header" title="Your URL does not match the custom Host Header in Authentication Settings section"><i class="fa fa-exclamation-triangle"></i></span>');
    $('#proxy_sandbox_endpoint').after('<span class="undo"><i class="fa fa-undo"></i> Use Default URL</span>');
    $('#proxy_api_backend').after('<a href class="undo"><i class="fa fa-undo"></i> Use Echo API</a>').after(host_header_warning);
    $('#proxy_endpoint').after('<a href class="undo"><i class="fa fa-undo"></i> Use Default URL</a>');
    toggle_host_header_warning = function() {
      var api_backend, host_header, valid;
      host_header = $('#proxy_hostname_rewrite').val();
      api_backend = $('#proxy_api_backend').val();
      valid = host_header.length === 0 || extractHost(api_backend) === host_header;
      return host_header_warning.toggle(!valid);
    };
    input_changed_from_default = function(input) {
      return !compareHttpHosts(input.val(), input.data('default'));
    };
    toggle_reset_buttons = function() {
      return $('form.proxy input[data-default]').each(function() {
        var input, undo_button;
        input = $(this);
        undo_button = input.siblings('.undo');
        undo_button.toggle(input_changed_from_default(input));
        return input.siblings('.inline-hints').find('span').toggle(input_changed_from_default(input));
      });
    };
    reset_proxy_input = function(event) {
      var input;
      input = $(this).siblings('input');
      input.val(input.data('default'));
      toggle_form_changed_ui();
      toggle_reset_buttons();
      toggle_host_header_warning();
      return event.preventDefault();
    };
    extractHost = function(url) {
      var link;
      link = document.createElement('a');
      link.href = url;
      return link.hostname;
    };
    compareHttpHosts = function(a, b) {
      return extractHost(a) === extractHost(b);
    };
    extractHost = function(url) {
      var link;
      link = document.createElement('a');
      link.href = url;
      return link.hostname;
    };
    compareHttpHosts = function(a, b) {
      return extractHost(a) === extractHost(b);
    };
    toggle_reset_buttons();
    toggle_host_header_warning();
    form = $("form.staging-settings");
    form.data("old-settings", form.serialize());
    toggle_form_changed_ui = function() {
      var new_settings, old_settings;
      form = $("form.staging-settings");
      new_settings = form.serialize();
      old_settings = form.data("old-settings");
      $('#integration-tabs').toggleClass('changed', new_settings !== old_settings);
      if (new_settings === old_settings) {
        if (!$("#proxy_api_test_path").val()) {
          $(".feedback-summary").html("The API test GET request has been left blank. You should set it before checking the connections between client, proxy & API.");
        } else {
          $(".feedback-summary").html("Hit the test button to check the connections between client, gateway & API.");
        }
      } else {
        if (!$("#proxy_api_test_path").val()) {
          $(".feedback-summary").html("The API test GET request has been left blank. You should set it before checking the connections between client, proxy & API.");
        } else {
          $(".feedback-summary").html("Hit the test button to check the connections between client, gateway & API.");
        }
      }
      return toggle_reset_buttons();
    };
    form.on("proxy.rule.change", toggle_form_changed_ui);
    form.on("click", "input[type=\"radio\"]", toggle_form_changed_ui);
    form.on('change keyup', '#proxy_hostname_rewrite, #proxy_api_backend', toggle_host_header_warning);
    form = $("form.proxy");
    form.on("change keyup", "input, select", toggle_form_changed_ui);
    form.on("click", ".undo", reset_proxy_input);
    $("a[href=\"#traffic-check-trigger\"]").click(function() {
      $("#traffic-check-widget .charts").trigger("chart:reload");
      return false;
    });
    return $(document).on('change', 'input[name="proxy[credentials_location]"]', function(event) {
      var name;
      name = document.getElementById('proxy_auth_user_key');
      name.value = (function() {
        switch (this.value) {
          case 'headers':
            return name.value.replace('_', '-');
          case 'query':
            return name.value.replace('-', '_');
        }
      }).call(this);
      return toggle_form_changed_ui();
    });
  });

  $(function() {
    return $('#proxy').trigger('initialize');
  });

}).call(this);
