(function($) {
  if(typeof(Boxy) == undefined) {
    alert('Cropper dependent on jquery.boxy.js.');
    return;
  }
  $.Cropper = function(url,options) {
    //console.debug($('#cropper-container'));
    if(typeof options == "function") {
      options = {callback: options};
    }
    var _this = this;
    this.options = $.extend(
      {
        width:100,
        height:100,
        imageWidth:300
      },options || {});
    this.url = url;
    //console.debug("this.options",this.options);
    //console.debug("this.options.container",this.options.container);
    //console.debug("container",this.container);
    this.result = {_method:'put',url:url};
    this.width = this.options.width;
    this.height = this.options.height;
    this.imageWidth = this.options.imageWidth;
    this.aspectRatio = this.width / this.height;

    this.showDialog = function() {
      //console.debug(this);
      if(this.boxy) {
        this.boxy.show();
      } else {
        this.container = $("<div class='cropper-container'></div>");
        this.boxy = new Boxy(
          this.container,
          {
            title:'裁剪图片',
            fixed:false,
            afterShow: function(boxy){
            }
          });
        //console.debug("boxy",this.boxy);
      }
    }

    this.hide = function(){
      this.boxy.hide();
    }

    this.showConfirm = function(url){
      //是否切割
      this.hideUploader();

      var dom = $("<div><img width='300' src='" + url + "'><br>是否剪切？<br><button name='yes'>是</button><button name='no'>否</button></div>");
      dom.children("button[name=yes]").click(function(){
        _this.show(url);
        dom.hide();
      });
      dom.children("button[name=no]").click(function(){
        _this.hide();
        _this.execCallback(url);
      });

      this.confirmDom = dom;
      this.container.append(dom);
    }

    // 将数据提交
    this.submit = function(){

      var result = this.result;

      $.post("/ext/cropper.json",{
        '_method':'put',
        'cropper[zoom]':result.zoom,
        'cropper[zoom2]':result.zoom2,
        'cropper[fix_size]':true,
        'cropper[file]':result.url,
        'cropper[x]':result.x,
        'cropper[y]':result.y,
        'cropper[x2]':result.x2,
        'cropper[y2]':result.y2,
        'cropper[width]':result.width,
        'cropper[height]':result.height
        },function(responseText){
        var json = $.evalJSON(responseText);
        if(json.error) {
          alert(json.error);
        } else {
          //success
          _this.execCallback(json.file);
          _this.hide();
        }
      },"put");
    }

    this.updatePreview = function(coords) {

      //更新数据
      this.result['x']     = coords.x;
      this.result['y']     = coords.y;
      this.result['x2']    = coords.x2;
      this.result['y2']    = coords.y2;
      //不使用选择器的数据
      this.result['width'] = coords.w;
      this.result['height']= coords.h;

      //保持比例？
      var zoom2 = _this.width * 100 / coords.w ;
      this.result['zoom2'] = zoom2;



      //更新预览图片
      var rx = this.width / coords.w;
      var ry = this.height / coords.h;
      var origImgWidth = this.cropImage.width();
      var origImgHeight = this.cropImage.height();
      //console.debug('rx:',rx,'ry:',ry,'oW:',origImgWidth,'oH:',origImgHeight,'w:',this.width,'h:',this.height,'c:',coords);
      this.previewImage.css({
        width: Math.round(rx * origImgWidth) + 'px',
        height: Math.round(ry * origImgHeight) + 'px',
        marginLeft: '-' + Math.round(rx * coords.x) + 'px',
        marginTop: '-' + Math.round(ry * coords.y) + 'px'
      });
    }

    this.show = function(url){
      //console.debug("show",url)
      this.url = url;
      this.result['url'] = url;
      this.image = $(new Image()).attr('src',this.url);
      this.createCropper();
      this.zoom =  100 * this.cropImage.width() / this.image.attr('width') ;
      this.result['zoom'] = this.zoom;
      this.startJcrop();
    }


    this.startJcrop = function(){
      if(this.jcrop) { this.jcrop.destroy() }
      this.jcrop = new $.Jcrop(this.cropImage,{
        //setSelect:[0,0,200,200],
        minSize:[100,100],
        aspectRatio:this.aspectRatio,
        //onChange: showPreview,
        onSelect:function(coords){
        /*
          _this.result['x']     = coords.x;
          _this.result['y']     = coords.y;
          _this.result['x2']    = coords.x2;
          _this.result['y2']    = coords.y2;
          //不使用选择器的数据
          _this.result['width'] = coords.w;
          _this.result['height']= coords.h;

          //保持比例？
          var zoom2 = _this.width * 100 / coords.w ;
          _this.result['zoom2'] = zoom2;
          */

          _this.updatePreview(coords);
        }
      });
      this.jcrop.setSelect([0,0,200,200]);
      this.jcrop.animateTo([0,0,200,200]);
      var coords = this.jcrop.tellSelect();
      this.updatePreview(coords);
      //console.debug(coords);
    }

    this.hideUploader = function(){
      if(this.uploader) {
        this.uploader.hide();
      }
    };

    this.showUploader = function(){
      //alert("show uploader");
      this.hideCropper();
      if(this.uploader) {
        this.uploader.show();
      } else {
        var form = $("<form action='/ext/cropper' method='post'><div class='remote'>远程图片URL:<input type='text' name='url'><input type='button' class='sure' value='确定'></div><div class='local'><input type='file' name='cropper[file]'><input type='submit' value='上传'></div></form>");
        form.ajaxForm({success: function(responseText){
            try{
              var json = $.evalJSON(responseText);
              if(json.error) {
                alert(json.error);
              } else {
                _this.showConfirm(json.file);
                form[0].reset();
              }
              } catch(e) {
              alert(e.message);
            }
            },beforeSubmit: function(a){
            var value = form.children("input[type=file]").val()
            if( value == "") {
              alert('请选择文件');
              return false;
              } else {
            }
        }});
        this.container.append(form);
        form.find(".sure").click(function(){
          var value = form.find("input[name=url]").val();
          if(/^http:\/\/.+\.(jpg|png|gif)$/.test(value)) {
            _this.showConfirm(value);
          } else {
            alert("请输入一个正确的URL\n比如http://example.com/logo.gif");
            return;
          }

          _this.showConfirm(form.find("input[name=url]").val());
        });
        this.uploader = form;
      }
    }

    this.initialize = function(){
      this.showDialog();
      var url = this.url;
      //console.debug("initialize",url,typeof(url));
      if(url) {
        var image = $(new Image());
        image.attr('src',url);
        image.bind('load',function(){
          //alert("load");
          //_this.show(url);
        });
        image.bind('error',function(){
          alert('can not load url:' + url + ' as an image');
        });
        _this.show(url);
      } else {
        //console.debug("show uploader");
        this.showUploader();
      }
      //alert("end");
    }

    this.execCallback = function(url){
      //console.debug("exec callback",url)
      //console.debug("cropper.oncrop",url)
      //cropper.oncrop(url,this.url);
      this.options.callback && this.options.callback(url,this.url,this);
    }


    this.previewDiv = function(){
      var div = $("<div></div>");
      div.css('overflow','hidden');
      div.css('width',this.width);
      div.css('height',this.height);
      this.previewImage = $(new Image());
      div.append(this.previewImage);
      return div;
    }

    this.hideCropper = function(){
      this.cropDiv && this.cropDiv.hide();
    }

    this.createCropper = function(){
      if(this.cropDiv) {
        //console.debug("only show crop div");
        this.cropDiv.show();
      } else {
        this.cropDiv = $("<div></div>");
        var oprationDiv = $("<div><button name='crop'>开始切割</button><button name='upload'>重新上传</button></div>");
        oprationDiv.children('button[name=crop]').click(function(){
          _this.submit();
        });
        oprationDiv.children('button[name=upload]').click(function(){
          //console.debug('upload');
          _this.showUploader();
        });
        oprationDiv.appendTo(this.cropDiv);
        this.previewDiv().appendTo(this.cropDiv);
        this.cropImage = $(new Image());
        this.cropImage.appendTo(this.cropDiv);
        this.container.append(this.cropDiv);
      }

      //console.debug("crop image attr",this.url);

      if(this.imageWidth){
        this.cropImage.attr('src',this.url)
          .attr('width',this.imageWidth)
          .attr('height',this.imageWidth/this.image.attr('width') * this.image.attr('height'));
      }
      this.previewImage.attr('src',this.url).attr('width',this.cropImage.attr('width'));
      //this.previewImage.attr('src',this.url);

    }

    this.initialize();
    return this;
  }


  jQuery.startUploader = function(div,options) {
    var options = $.extend({},options || {});
    var div = $(div);
    var img = div.find("img");
    var container = div.find(".cropper-field-container");
    var hidden = div.find("input[type=hidden]");
    var width =  options.width;
    var height = options.height;
    var callback = function(thumbUrl,origUrl,cropper) {
      if(thumbUrl != '' && thumbUrl != null) { 
        //console.debug("container",container);
        container.html("<img width='" + cropper.options.width + "' height='" + cropper.options.height + "' src='" + thumbUrl + "' origSrc='" + (origUrl || '') + "'/>上传");
        hidden.val(thumbUrl);
      } else {
        container.html('上传');
      }
    }
    var cropper = div.data("cropper");
    if(cropper) {
      if(!cropper.boxy.visible) {
        cropper.boxy.show();
      }
    } else {
      var cropper = new jQuery.Cropper(img.attr("origSrc") || div.attr("url"),{callback: callback,width: width,height: height});
      div.data("cropper",cropper);
    }
    return cropper;
  }

})(jQuery);
