// Generated by CoffeeScript 1.6.3
(function() {
  var CropTool, Dropzone, delay, _ref,
    __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    __hasProp = {}.hasOwnProperty,
    __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

  delay = function(ms, func) {
    return setTimeout(func, ms);
  };

  CropTool = (function() {
    function CropTool($el) {
      this.cropHandler = __bind(this.cropHandler, this);
      this.release = __bind(this.release, this);
      this.resizePreview = __bind(this.resizePreview, this);
      this.$img = $el;
      this.init();
    }

    CropTool.prototype.init = function() {
      var api, _image,
        _this = this;
      api = null;
      this.$img.Jcrop({
        bgColor: 'none',
        bgOpacity: 1,
        onChange: this.cropHandler,
        onSelect: this.cropHandler,
        onRelease: this.release
      }, function() {
        return api = this;
      });
      this.api = api;
      this.bounds = this.api.getBounds();
      _image = new Image;
      _image.src = this.$img.attr('src');
      return $(_image).load(function() {
        return _this.imageSize = {
          width: _image.width,
          height: _image.height
        };
      });
    };

    CropTool.prototype.destroy = function() {
      this.api.ui.holder.hide();
      return this.api.destroy();
    };

    CropTool.prototype.show = function() {
      this.api.enable();
      this.api.ui.holder.show();
      return this.$img.hide().css({
        visibility: 'hidden'
      });
    };

    CropTool.prototype.hide = function() {
      this.api.ui.holder.hide();
      this.api.disable();
      this.api.release();
      return this.$img.show().css({
        visibility: 'visible'
      });
    };

    CropTool.prototype.setAspectRatio = function(ratio) {
      return this.api.setOptions({
        aspectRatio: ratio
      });
    };

    CropTool.prototype.disableAspectRatio = function() {
      return this.setAspectRatio(0);
    };

    CropTool.prototype.createPreview = function() {
      var $image, image;
      console.log('new crop image preview');
      image = new Image;
      image.src = this.$img.attr('src');
      $image = $(image);
      this.preview = $image;
      this.previewContainer = $('<div>');
      this.previewContainer.css({
        overflow: 'hidden',
        display: 'inline-block'
      });
      this.previewContainer.append(image);
      return this.$img.trigger('crop:preview', this.previewContainer);
    };

    CropTool.prototype.setPreviewAttributes = function(attrs) {
      var attr, value, _results;
      if (this.preview == null) {
        this.createPreview();
      }
      _results = [];
      for (attr in attrs) {
        value = attrs[attr];
        _results.push(this.previewContainer.attr(attr, value));
      }
      return _results;
    };

    CropTool.prototype.resizePreview = function() {
      if (this.preview == null) {
        this.createPreview();
      }
      this.previewSize = {
        width: parseInt($('#field-width').val() || 0, 10),
        height: parseInt($('#field-height').val() || 0, 10)
      };
      return this.previewContainer.css({
        width: this.previewSize.width,
        height: this.previewSize.height
      });
    };

    CropTool.prototype.release = function() {
      if (this.previewSize) {
        return this.preview.css({
          width: this.previewSize.width + 'px',
          height: this.previewSize.height + 'px',
          marginLeft: 0,
          marginTop: 0
        });
      }
    };

    CropTool.prototype.cropPreview = function(coords) {
      var hr, rx, ry;
      if (!coords) {
        coords = this.api.tellSelect();
      }
      if (this.api.getOptions().aspectRatio === 0) {
        if (coords.w) {
          hr = coords.h / coords.w;
        } else {
          hr = this.bounds[1] / this.bounds[0];
        }
        $('#field-height').val(Math.round(this.previewSize.width * hr));
        this.resizePreview();
      }
      if (coords.w > 0) {
        rx = this.previewSize.width / coords.w;
        ry = this.previewSize.height / coords.h;
        return this.preview.css({
          width: Math.round(rx * this.bounds[0]) + 'px',
          height: Math.round(ry * this.bounds[1]) + 'px',
          marginLeft: '-' + Math.round(rx * coords.x) + 'px',
          marginTop: '-' + Math.round(ry * coords.y) + 'px'
        });
      } else {
        return this.release();
      }
    };

    CropTool.prototype.cropHandler = function(coords) {
      var $crop, box, rx, ry, x;
      if (this.preview == null) {
        this.createPreview();
        this.resizePreview();
      } else {
        this.cropPreview(coords);
      }
      $crop = $('#field-crop');
      if (coords.w) {
        rx = this.imageSize.width / this.bounds[0];
        ry = this.imageSize.height / this.bounds[1];
        box = [coords.x * rx, coords.y * ry, coords.x2 * rx, coords.y2 * ry];
        box = ((function() {
          var _i, _len, _results;
          _results = [];
          for (_i = 0, _len = box.length; _i < _len; _i++) {
            x = box[_i];
            _results.push(Math.round(x));
          }
          return _results;
        })()).join(',');
        $crop.val(box);
      } else {
        $crop.val('');
      }
      return $crop.change();
    };

    return CropTool;

  })();

  Dropzone = (function() {
    function Dropzone(config) {
      this.dragHandler = __bind(this.dragHandler, this);
      this.el = config.el;
      this.$el = $(config.el);
      this.$section = this.$el.find('section');
      this.startCallback = config.start;
      this.stopCallback = config.stop;
      $(document).bind('dragover', this.dragHandler);
      $(document).bind('drop dragover', function(event) {
        return event.preventDefault();
      });
    }

    Dropzone.prototype.hide = function() {
      console.log('Dropzone.hide(), hasError:', this.hasError());
      if (!this.hasError()) {
        return this.$el.hide();
      }
    };

    Dropzone.prototype.show = function() {
      return this.$el.show();
    };

    Dropzone.prototype.hasError = function() {
      return this.$section.hasClass('error');
    };

    Dropzone.prototype.resizeTo = function(target) {
      return this.$section.css({
        'height': "" + (target.outerHeight()) + "px",
        'line-height': "" + (target.outerHeight() - 6) + "px"
      });
    };

    Dropzone.prototype.dragStart = function() {
      this.$section.addClass('drag').removeClass('drag-over error');
      return this.$section.html('<i class="icon-circle-arrow-down"></i> Drop your image here');
    };

    Dropzone.prototype.dragOver = function() {
      this.$section.addClass('drag-over').removeClass('drag drop');
      return this.$section.html('<i class="icon-cloud-upload"></i> Release to upload');
    };

    Dropzone.prototype.dragDrop = function() {
      this.$section.addClass('drop').removeClass('drag-over');
      return this.$section.html('<i class="icon-spinner icon-spin icon-large"></i>');
    };

    Dropzone.prototype.dragError = function() {
      this.$section.addClass('error').removeClass('drag-over drop');
      return this.$section.html('<i class="icon-warning-sign"> Failed to upload image</i>');
    };

    Dropzone.prototype.dragStop = function() {
      if (!this.hasError()) {
        this.$section.removeClass('drag-over drop error');
        return this.$section.html('');
      }
    };

    Dropzone.prototype.dragHandler = function(event) {
      var zone,
        _this = this;
      this.startCallback();
      zone = this.$el;
      if (!this.dragId) {
        this.dragStart();
        zone.fadeIn('fast');
      } else {
        clearTimeout(this.dragId);
      }
      if (event.target === this.$section[0]) {
        this.dragOver();
      } else {
        this.dragStart();
      }
      return this.dragId = delay(100, function() {
        _this.dragId = null;
        _this.hide();
        _this.dragStop();
        return _this.stopCallback();
      });
    };

    return Dropzone;

  })();

  window.ImageEditor = (function(_super) {
    __extends(ImageEditor, _super);

    function ImageEditor() {
      this.uploadError = __bind(this.uploadError, this);
      this.uploadComplete = __bind(this.uploadComplete, this);
      this.uploadStart = __bind(this.uploadStart, this);
      this.prepareUpload = __bind(this.prepareUpload, this);
      this.toggleAspectRatio = __bind(this.toggleAspectRatio, this);
      this.resizeImage = __bind(this.resizeImage, this);
      _ref = ImageEditor.__super__.constructor.apply(this, arguments);
      return _ref;
    }

    ImageEditor.prototype.initialize = function(config) {
      var _this = this;
      ImageEditor.__super__.initialize.call(this, config);
      this.dropzone = new Dropzone({
        el: config.dropzone,
        start: function() {
          if (_this.crop != null) {
            return _this.crop.hide();
          }
        },
        stop: function() {
          if (_this.crop != null) {
            return _this.crop.show();
          }
        }
      });
      this.field = $(config.field);
      this.preview = $(config.preview);
      this.field.fileupload({
        dropZone: dropzone.el,
        drop: this.prepareUpload,
        send: this.uploadStart,
        done: this.uploadComplete,
        fail: this.uploadError,
        progressall: function(event, data) {
          return _this.progressbar.update(data);
        }
      });
      this.widthField = $('#field-width');
      this.heightField = $('#field-height');
      this.ratioButton = $('#ar-lock');
      $('.dimension').on('keyup', this.resizeImage);
      $('#html-pane input').on('keyup', function() {
        return _this.updateImageAttributes();
      });
      this.ratioButton.on('click', this.toggleAspectRatio);
      return this.ratioButton.tooltip();
    };

    ImageEditor.prototype.render = function(node) {
      console.log('ImageEditor.render()');
      ImageEditor.__super__.render.call(this, node);
      if (node && node.data) {
        this.updateForm(node.data);
        if (node.data.url) {
          this.dropzone.dragDrop();
          return this.renderThumbnail(node.data.url);
        } else {
          return this.dropzone.dragStart();
        }
      } else {
        this.updateForm({
          filename: '',
          width: '',
          height: '',
          id: '',
          'class': '',
          alt: ''
        });
        return this.removeThumbnail();
      }
    };

    ImageEditor.prototype.updateForm = function(data) {
      $("input[name='data[filename]']").val(data.filename);
      $("input[name='data[width]']").val(data.width);
      $("input[name='data[height]']").val(data.height);
      $("input[name='data[crop]']").val('');
      $("input[name='data[id]']").val(data.id);
      $("input[name='data[class]']").val(data["class"]);
      return $("input[name='data[alt]']").val(data.alt);
    };

    ImageEditor.prototype.renderThumbnail = function(url) {
      var $image, image,
        _this = this;
      console.log('ImageEditor.renderThumbnail()');
      image = new Image;
      image.src = url;
      image.className = 'original';
      $image = $(image);
      return $image.load(function() {
        _this.dropzone.hide();
        _this.preview.hide();
        _this.preview.html(image);
        return _this.preview.fadeIn(100, function() {
          $image.on('crop:preview', function(event, html) {
            return _this.triggerRender(html);
          });
          _this.crop = new CropTool($image);
          _this.updateImageAttributes();
          return _this.crop.resizePreview();
        });
      });
    };

    ImageEditor.prototype.removeThumbnail = function() {
      console.log('ImageEditor.removeThumbnail()');
      if (this.crop) {
        this.crop.destroy();
      }
      this.preview.empty();
      this.dropzone.show();
      return this.dropzone.dragStart();
    };

    ImageEditor.prototype.dimensions = function() {
      var h, w;
      w = parseInt(this.widthField.val(), 10) || 0;
      h = parseInt(this.heightField.val(), 10) || 0;
      return [w, h];
    };

    ImageEditor.prototype.resizeImage = function(event) {
      var h, keepRatio, ratio, w, _ref1;
      _ref1 = this.dimensions(), w = _ref1[0], h = _ref1[1];
      if (w && h) {
        keepRatio = this.ratioButton.hasClass('active');
        if (keepRatio) {
          ratio = this.ratioButton.data('ratio');
          if ($(event.target).attr('id') === 'field-width') {
            h = Math.round(w / ratio);
            this.heightField.val(h);
          } else {
            w = Math.round(h * ratio);
            this.widthField.val(w);
          }
        } else {
          ratio = w / h;
        }
        image.crop.setAspectRatio(ratio);
        if (!keepRatio) {
          image.crop.disableAspectRatio();
        }
      }
      this.crop.resizePreview();
      this.crop.cropPreview();
      return this.trigger('node:resize');
    };

    ImageEditor.prototype.getHtmlFields = function() {
      var attr, attrs, _i, _len, _ref1;
      attrs = {};
      _ref1 = ['id', 'class', 'alt'];
      for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
        attr = _ref1[_i];
        attrs[attr] = $("input[name='data[" + attr + "]']").val();
      }
      return attrs;
    };

    ImageEditor.prototype.updateImageAttributes = function() {
      this.crop.setPreviewAttributes(this.getHtmlFields());
      return this.trigger('node:resize');
    };

    ImageEditor.prototype.toggleAspectRatio = function() {
      var h, ratio, ratioInactive, w, _ref1;
      ratioInactive = this.ratioButton.hasClass('active');
      _ref1 = this.dimensions(), w = _ref1[0], h = _ref1[1];
      ratio = w && h ? w / h : 1;
      this.ratioButton.data('ratio', ratio);
      return this.crop.setAspectRatio(ratioInactive ? 0 : ratio);
    };

    ImageEditor.prototype.prepareUpload = function() {
      $('input[name="data[width]"]').val('');
      $('input[name="data[height]"]').val('');
      return this.trigger('form:change');
    };

    ImageEditor.prototype.uploadStart = function(event, response) {
      console.log('ImageEditor.uploadStart()');
      this.dropzone.dragDrop();
      this.progressbar.show();
      if (this.crop) {
        return this.crop.destroy();
      }
    };

    ImageEditor.prototype.uploadComplete = function(event, response) {
      var node;
      console.log('ImageEditor.uploadComplete()');
      this.progressbar.hide();
      node = this.setNode(response.result);
      return this.render(node);
    };

    ImageEditor.prototype.uploadError = function(event, response) {
      console.log('ImageEditor.uploadError()');
      this.progressbar.hide();
      return this.dropzone.dragError();
    };

    return ImageEditor;

  })(window.Editor);

}).call(this);
