/**
 * Created by Administrator on 2016/9/1.
 */
var cropbox = function(options){
    var el = document.querySelector(options.imageBox),
        obj =
        {
            state : {},
            ratio : 1,
            options : options,
            imageBox : el,
            thumbBox : el.querySelector(options.thumbBox),
            spinner : el.querySelector(options.spinner),
            image : new Image(),
            getDataURL: function ()
            {
                var width = this.thumbBox.clientWidth,
                    height = this.thumbBox.clientHeight,
                    canvas = document.createElement("canvas"),
                    dim = el.style.backgroundPosition.split(' '),
                    size = el.style.backgroundSize.split(' '),
                    dx = parseInt(dim[0]) - el.clientWidth/2 + width/2,
                    dy = parseInt(dim[1]) - el.clientHeight/2 + height/2,
                    dw = parseInt(size[0]),
                    dh = parseInt(size[1]),
                    sh = parseInt(this.image.height),
                    sw = parseInt(this.image.width);

                canvas.width = width;
                canvas.height = height;
                var context = canvas.getContext("2d");
                context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh);
                var imageData = canvas.toDataURL('image/png');
                return imageData;
            },
            getBlob: function()
            {
                var imageData = this.getDataURL();
                var b64 = imageData.replace('data:image/png;base64,','');
                var binary = atob(b64);
                var array = [];
                for (var i = 0; i < binary.length; i++) {
                    array.push(binary.charCodeAt(i));
                }
                return  new Blob([new Uint8Array(array)], {type: 'image/png'});
            },
            zoomIn: function ()
            {
                this.ratio*=1.1;
                setBackground();
            },
            zoomOut: function ()
            {
                this.ratio*=0.9;
                setBackground();
            }
        },
        attachEvent = function(node, event, cb)
        {
            if (node.attachEvent)
                node.attachEvent('on'+event, cb);
            else if (node.addEventListener)
                node.addEventListener(event, cb);
        },
        detachEvent = function(node, event, cb)
        {
            if(node.detachEvent) {
                node.detachEvent('on'+event, cb);
            }
            else if(node.removeEventListener) {
                node.removeEventListener(event, render);
            }
        },
        stopEvent = function (e) {
            if(window.event) e.cancelBubble = true;
            else e.stopImmediatePropagation();
        },
        setBackground = function()
        {
            var w =  parseInt(obj.image.width)*obj.ratio;
            var h =  parseInt(obj.image.height)*obj.ratio;

            var pw = (el.clientWidth - w) / 2;
            var ph = (el.clientHeight - h) / 2;
            el.setAttribute('style',
                'background-image: url(' + obj.image.src + '); ' +
                'background-size: ' + w +'px ' + h + 'px; ' +
                'background-position: ' + pw + 'px ' + ph + 'px; ' +
                'background-repeat: no-repeat');
        },
        imgMouseDown = function(e)
        {
            stopEvent(e);

            obj.state.dragable = true;
            obj.state.mouseX = e.clientX;
            obj.state.mouseY = e.clientY;
        },
        imgMouseMove = function(e)
        {
            stopEvent(e);
            if (obj.state.dragable)
            {
                var x = e.clientX - obj.state.mouseX;
                var y = e.clientY - obj.state.mouseY;
                var bg = el.style.backgroundPosition.split(' ');
                var bgX = x + parseInt(bg[0]);
                var bgY = y + parseInt(bg[1]);
                el.style.backgroundPosition = bgX +'px ' + bgY + 'px';
                obj.state.mouseX = e.clientX;
                obj.state.mouseY = e.clientY;
            }
        },
        imgMouseUp = function(e)
        {
            stopEvent(e);
            obj.state.dragable = false;
        },
        zoomImage = function(e)
        {
            var evt=window.event || e;
            var delta=evt.detail? evt.detail*(-120) : evt.wheelDelta;
            delta > -120 ? obj.ratio*=1.1 : obj.ratio*=0.9;
            setBackground();
        };

    obj.spinner.style.display = 'block';
    obj.image.onload = function() {
        obj.spinner.style.display = 'none';
        setBackground();

        attachEvent(el, 'mousedown', imgMouseDown);
        attachEvent(el, 'mousemove', imgMouseMove);
        attachEvent(document.body, 'mouseup', imgMouseUp);
        var mousewheel = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel';
        attachEvent(el, mousewheel, zoomImage);
    };
    obj.image.src = options.imgSrc;
    attachEvent(el, 'DOMNodeRemoved', function(){detachEvent(document.body, 'DOMNodeRemoved', imgMouseUp)});
    return obj;
};



/**
 * @param base64Codes
 *            图片的base64编码
 */
function sumitImageFile(base64Codes){
    var form=document.forms[0];

    var formData = new FormData(form);   //这里连带form里的其他参数也一起提交了,如果不需要提交其他参数可以直接FormData无参数的构造函数

    //convertBase64UrlToBlob函数是将base64编码转换为Blob
    formData.append("imageName",convertBase64UrlToBlob(base64Codes));  //append函数的第一个参数是后台获取数据的参数名,和html标签的input的name属性功能相同

    //ajax 提交form
    $.ajax({
        url : form.action,
        type : "POST",
        data : formData,
        dataType:"text",
        processData : false,         // 告诉jQuery不要去处理发送的数据
        contentType : false,        // 告诉jQuery不要去设置Content-Type请求头

        success:function(data){
            window.location.href="${ctx}"+data;
        },
        xhr:function(){            //在jquery函数中直接使用ajax的XMLHttpRequest对象
            var xhr = new XMLHttpRequest();

            xhr.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
                    console.log("正在提交."+percentComplete.toString() + '%');        //在控制台打印上传进度
                }
            }, false);

            return xhr;
        }

    });
}

/**
 * 将以base64的图片url数据转换为Blob
 * @param urlData
 *            用url方式表示的base64图片数据
 */
function convertBase64UrlToBlob(urlData){

    var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte

    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }

    return new Blob( [ab] , {type : 'image/png'});
}