// Generated by CoffeeScript 1.7.1
(function() {
  $(function() {
    var attach, setup;
    attach = function($fileInput, policy_url, $el) {
      $fileInput.fileupload({
        paramName: "file",
        autoUpload: true,
        dataType: "xml",
        fileInput: $fileInput,
        dropZone: $fileInput,
        add: function(e, data) {
          $(".submit-row input[type=submit]").prop("disabled", true);
          $el.attr("class", "s3file progress-active");
          $.ajax({
            url: policy_url,
            type: "POST",
            data: {
              type: data.files[0].type,
              name: data.files[0].name
            },
            success: function(fields) {
              $el.find("input[type=hidden]").val(fields.key);
              data.url = fields.form_action;
              delete fields.form_action;
              data.formData = fields;
              data.submit();
            }
          });
        },
        progress: function(e, data) {
          var progress;
          progress = parseInt(data.loaded / data.total * 100, 10);
          $el.find(".progress-bar").css({
            width: progress + "%"
          }).html(progress + "%");
        },
        error: function(e, data) {
          alert("Oops, file upload failed, please try again");
          $el.attr("class", "s3file form-active");
        },
        done: function(e, data) {
          var file_name, url;
          url = $(data.result).find("Location").text().replace(/%2F/g, "/");
          file_name = url.replace(/^.*[\\\/]/, "");
          $el.find(".link").attr("href", url).text(file_name);
          $el.attr("class", "s3file link-active");
          $el.find(".progress-bar").css({
            width: "0%"
          });
          $(".submit-row input[type=submit]").prop("disabled", false);
        }
      });
    };
    setup = function(el) {
      var $el, $fileInput, class_, file_url, id, policy_url;
      $el = $(el);
      policy_url = $el.data("url");
      id = $el.data("target");
      file_url = $el.find("#" + id).val();
      $fileInput = $el.find("#s3-" + id);
      class_ = (file_url === "" ? "form-active" : "link-active");
      $el.attr("class", "s3file " + class_);
      $el.find(".remove").click(function(e) {
        e.preventDefault();
        $el.find("input[type=hidden]").val("");
        $el.attr("class", "s3file form-active");
      });
      attach($fileInput, policy_url, $el);
    };
    $(".s3file").each(function(i, el) {
      setup(el);
    });
    $(document).bind("DOMNodeInserted", function(e) {
      var elements;
      elements = $(e.target).find(".s3file");
      if (elements.length) {
        setup(elements.get(0));
      }
    });
  });

}).call(this);

//# sourceMappingURL=s3file.map
