(function (factory) {
  if (typeof define === "function" && define.amd) {
    // AMD. Register as anonymous module.
    define(["jquery"], factory);
  } else if (typeof exports === "object") {
    // Node / CommonJS
    factory(require_once("jquery"));
  } else {
    // Browser globals.
    factory(jQuery);
  }
})(function ($) {
  "use strict";

  var console = window.console || { log: function () {} };

  function Cropafl2($element) {
    this.$container = $element;

    this.$afl2View = this.$container.find("#afl2-view");
    this.$afl2 = this.$afl2View.find("img");
    this.$afl2Modal = this.$container.find("#afl2-modal");
    this.$loading = this.$container.find(".loading");

    this.$afl2Form = this.$afl2Modal.find("#afl2-form");
    this.$afl2Upload = this.$afl2Form.find(".afl-upload");
    this.$afl2Src = this.$afl2Form.find(".afl-src");
    this.$afl2Data = this.$afl2Form.find(".afl-data");
    this.$afl2Input = this.$afl2Form.find("#afl2-input");
    this.$afl2Save = this.$afl2Form.find(".afl-save");
    this.$afl2Btns = this.$afl2Form.find(".afl-btns");
    this.$afl2Ratio = this.$afl2Form.find(".afl-ratio").val();

    this.$afl2Wrapper = this.$afl2Modal.find(".afl-wrapper");
    this.$afl2Preview = this.$afl2Modal.find(".afl-preview");

    this.init();
  }

  Cropafl2.prototype = {
    constructor: Cropafl2,

    support: {
      fileList: !!$('<input type="file">').prop("files"),
      blobURLs: !!window.URL && URL.createObjectURL,
      formData: !!window.FormData,
    },

    init: function () {
      this.support.datauri = this.support.fileList && this.support.blobURLs;

      if (!this.support.formData) {
        this.initIframe();
      }

      this.initTooltip();
      this.initModal();
      this.addListener();
    },

    addListener: function () {
      this.$afl2View.on("click", $.proxy(this.click, this));
      this.$afl2Input.on("change", $.proxy(this.change, this));
      this.$afl2Form.on("submit", $.proxy(this.submit, this));
      this.$afl2Btns.on("click", $.proxy(this.rotate, this));
    },

    initTooltip: function () {
      this.$afl2View.tooltip({
        placement: "bottom",
      });
    },

    initModal: function () {
      this.$afl2Modal.modal({
        show: false,
      });
    },

    initPreview: function () {
      var url = this.$afl2.attr("src");

      this.$afl2Preview.html('<img src="' + url + '">');
    },

    initIframe: function () {
      var target = "upload-iframe-" + new Date().getTime();
      var $iframe = $("<iframe>").attr({
        name: target,
        src: "",
      });
      var _this = this;

      // Ready ifrmae
      $iframe.one("load", function () {
        // respond response
        $iframe.on("load", function () {
          var data;

          try {
            data = $(this).contents().find("body").text();
          } catch (e) {
            console.log(e.message);
          }

          if (data) {
            try {
              data = $.parseJSON(data);
            } catch (e) {
              console.log(e.message);
            }

            _this.submitDone(data);
          } else {
            _this.submitFail("Image upload failed!");
          }

          _this.submitEnd();
        });
      });

      this.$iframe = $iframe;
      this.$afl2Form.attr("target", target).after($iframe.hide());
    },

    click: function () {
      this.$afl2Modal.modal("show");
      this.initPreview();
    },

    change: function () {
      var files;
      var file;

      if (this.support.datauri) {
        files = this.$afl2Input.prop("files");

        if (files.length > 0) {
          file = files[0];

          if (this.isImageFile(file)) {
            if (this.url) {
              URL.revokeObjectURL(this.url); // Revoke the old one
            }

            this.url = URL.createObjectURL(file);
            this.startCropper();
          }
        }
      } else {
        file = this.$afl2Input.val();

        if (this.isImageFile(file)) {
          this.syncUpload();
        }
      }
    },

    submit: function () {
      if (!this.$afl2Src.val() && !this.$afl2Input.val()) {
        return false;
      }

      if (this.support.formData) {
        this.ajaxUpload();
        return false;
      }
    },

    rotate: function (e) {
      var data;

      if (this.active) {
        data = $(e.target).data();

        if (data.method) {
          this.$img.cropper(data.method, data.option);
        }
      }
    },

    isImageFile: function (file) {
      if (file.type) {
        return /^image\/\w+$/.test(file.type);
      } else {
        return /\.(jpg|jpeg|png|gif)$/.test(file);
      }
    },

    startCropper: function () {
      var _this = this;
      var ratio = this.$afl2Ratio.split("|");
      //alert(ratio[0])
      if (this.active) {
        this.$img.cropper("replace", this.url);
      } else {
        this.$img = $('<img src="' + this.url + '">');
        this.$afl2Wrapper.empty().html(this.$img);
        this.$img.cropper({
          aspectRatio: ratio[0] / ratio[1],
          preview: this.$afl2Preview.selector,
          crop: function (e) {
            var json = ['{"x":' + e.x, '"y":' + e.y, '"height":' + e.height, '"width":' + e.width, '"rotate":' + e.rotate + "}"].join();

            _this.$afl2Data.val(json);
          },
        });

        this.active = true;
      }

      this.$afl2Modal.one("hidden.bs.modal", function () {
        _this.$afl2Preview.empty();
        _this.stopCropper();
      });
    },

    stopCropper: function () {
      if (this.active) {
        this.$img.cropper("destroy");
        this.$img.remove();
        this.active = false;
      }
    },

    ajaxUpload: function () {
      var url = this.$afl2Form.attr("action");
      var data = new FormData(this.$afl2Form[0]);
      var _this = this;

      $.ajax(url, {
        type: "post",
        data: data,
        dataType: "json",
        processData: false,
        contentType: false,

        beforeSend: function () {
          _this.submitStart();
        },

        success: function (data) {
          _this.submitDone(data);
        },

        error: function (XMLHttpRequest, textStatus, errorThrown) {
          _this.submitFail(textStatus || errorThrown);
        },

        complete: function () {
          _this.submitEnd();
        },
      });
    },

    syncUpload: function () {
      this.$afl2Save.click();
    },

    submitStart: function () {
      this.$loading.fadeIn();
    },

    submitDone: function (data) {
      console.log(data);

      if ($.isPlainObject(data) && data.state === 200) {
        if (data.result) {
          this.url = data.result;

          if (this.support.datauri || this.uploaded) {
            this.uploaded = false;
            this.cropDone();
          } else {
            this.uploaded = true;
            this.$afl2Src.val(this.url);
            this.startCropper();
          }

          this.$afl2Input.val("");
        } else if (data.message) {
          this.alert(data.message);
        }
      } else {
        this.alert("Failed to response");
      }
    },

    submitFail: function (msg) {
      this.alert(msg);
    },

    submitEnd: function () {
      this.$loading.fadeOut();
    },

    cropDone: function () {
      this.$afl2Form.get(0).reset();
      this.$afl2.attr("src", this.url);
      this.stopCropper();
      this.$afl2Modal.modal("hide");
    },

    alert: function (msg) {
      var $alert = ['<div class="alert alert-danger afl2-alert alert-dismissable">', '<button type="button" class="close" data-dismiss="alert">&times;</button>', msg, "</div>"].join("");

      this.$afl2Upload.after($alert);
    },
  };

  $(function () {
    return new Cropafl2($("#crop-afl2"));
  });
});
