function preloadimages(obj, complete_cb, progress_cb) {
    var loaded = 0;
    var toload = 0;
    var images = obj instanceof Array ? [] : {};
    toload = obj.length;
    for (var i = 0; i < obj.length; i++) {
        images[i] = new Image();
        images[i].src = obj[i];
        // console.log(obj[i]);
        images[i].onload = load;
        images[i].setAttribute('crossOrigin', 'anonymous');
        images[i].onerror = load;
        images[i].onabort = load;
    }
    if (obj.length == 0) {
        complete_cb(images);
    }

    function load() {
        ++loaded;
        if (progress_cb) {
            progress_cb(loaded / toload);
        }
        if (loaded >= toload) {
            complete_cb(images);
        }
    }
}

var picUrl = window.base_resource_url + '/images/';

var preloadImageList = [
    // picUrl + 'share.png',
];
if ($('div').length > 0) {
    $.each($('div'), function (index, val) {
        var img = $(val).css('background-image').replace(/^url\((['"]?)(.*)\1\)$/, '$2');
        img = $.trim(img);
        if (img && img.match(/[^/]+(jpg|png|gif)$/)) {
            preloadImageList.push(img);
        }
    });
}



var myCanvas;
var ctx;
var imgInfo = {};
// var username = '';

preloadimages(preloadImageList, function () {
    
}, function (progress) {
    
});

// $('input[name=username]').attr('placeholder','点击输入您的名字');
$('.canvas-block').html('<canvas id="myCanvas" width="'+ 330 +'" height="'+ 330 +'"></canvas>');

$('.page1').show();


$(document).ready(function () {
    $("input").on("blur",function(){
        window.scroll(0,0);//失焦后强制让页面归位
    });

    $('.logo-top').css('top',getTranslateDistance(30)); 
    $('.logo-bottom').css('top',parseInt(getTranslateDistance($('.wrap').height())) - 50 + 'px'); 

    $('.btn-go').on('click',homeBtnGoHandleClick);

    $('[name=btn-tocreate]').change(function() {
        initCanvas();
        imgInfo.rotation = 0;
        imgInfo.x = 0;
        imgInfo.y = 0;
        imgInfo.scale = 1;
        event.preventDefault();
        var imgData = this.files[0];
        EXIF.getData(imgData, function() {
            //获取旋转信息
            var orientation = EXIF.getTag(this, "Orientation");
            switch (orientation) {
                case 3:
                    imgInfo.rotation = 180;
                    break;
                case 6:
                    imgInfo.rotation = 90;
                    break;
                case 8:
                    imgInfo.rotation = 270;
                    break;
                default:
                    imgInfo.rotation = 0;
            }
            if (navigator.userAgent.indexOf('iPhone') > -1) {
                imgInfo.rotation = 0;
            }
            lrz(imgData, { width: 640 }, function(results) {
                img = new Image();
                img.onload = function() {
                    $('.btn_test').hide();
                    $('.btn_holder').show();
                    $('.page_test .picture').css({
                        'opacity': 0,
                        '-webkit-animation': 'none',
                        'animation': 'none',
                        'z-index': 9
                    });
                    drawImage();
                    $('.copywriting2,.btn-tocreate').fadeOut(300);
                    $('.upload-page').delay(200).fadeIn(300);
                    results = null;
                    imgData = null;
                };
                img.src = results.base64;
            });
        });
        return false;
    });

    var mc = new Hammer($('.template1').get(0));
    mc.get('pan').set({ direction: Hammer.DIRECTION_ALL });
    mc.get('pinch').set({ enable: true });
    mc.get('rotate').set({ enable: true });
    var oldpoz = {};
    mc.on('panstart panmove panend', function(event) {
        if (!img) {
            return;
        }
        if (event.type == 'panstart' || event.type == 'panend') {
            oldpoz.x = 0;
            oldpoz.y = 0;
        } else {
            var movedX = (event.deltaX - oldpoz.x);
            var movedY = (event.deltaY - oldpoz.y);
            oldpoz.x = event.deltaX;
            oldpoz.y = event.deltaY;
            //console.log("movedX:" + movedX + ' movedY:' + movedY + 'event.deltaX:' + event.deltaX + ' event.deltaY:' + event.deltaY + "\r\n");
            imgInfo.x += movedX;
            imgInfo.y += movedY;
            drawImage();
        }
    });
    var oldScale = 1;
    mc.on('pinchstart pinchmove pinchend', function(event) {
        if (!img) {
            return;
        }
        if (event.type == 'pinchstart' || event.type == 'pinchend') {
            oldScale = 1;
        } else {
            var nowScale = event.scale / oldScale;
            oldScale = event.scale;
            imgInfo.scale *= nowScale;
            drawImage();
        }
    });
    var oldRotation = 0;
    mc.on('rotatestart rotatemove rotateend', function(event) {
        if (!img) {
            return;
        }
        if (event.type == 'rotatestart' || event.type == 'rotateend') {
            oldRotation = 0;
        } else {
            nowRotation = event.rotation - oldRotation;
            oldRotation = event.rotation;
            imgInfo.rotation += nowRotation;
            drawImage();
        }
    });
});

function homeBtnGoHandleClick() 
{
    $('.subtitle,.copywriting1,.btn-go').fadeOut(300);
    $('.btn-tocreate,.copywriting2').delay(200).fadeIn(300);
}

function drawImage() {
    ctx.save();
    ctx.clearRect(0, 0, myCanvas.width, myCanvas.height);
    ctx.translate(myCanvas.width / 2, myCanvas.height / 2);
    ctx.translate(imgInfo.x, imgInfo.y);
    ctx.rotate(Math.PI / 180 * imgInfo.rotation);
    ctx.scale(imgInfo.scale, imgInfo.scale);
    ctx.drawImage(img, -img.width / 2, -img.height / 2);
    ctx.restore();
}

function checkWord(name,callback) {
    $.ajax({
        url: 'index/checkWord',
        type: 'POST',        data:{
            name:name
        },
        success: function(resp){
            if(resp.status == 1)
            {
                callback();
            }
            else 
            {
                $('#notification_area').remove();
                my_notify(resp.msg);
            }
        }
    })
}

function getManBase64() {
    return myCanvas.toDataURL('image/png');
}

function txtDraw(ctx, content, x, y, fontsize, fontweight, color) {
    x = x * 4;
    y = y * 4;
    fontsize = fontsize * 4;
    ctx.font = fontweight + ' '+fontsize+'px fzlt';
    var width = ctx.measureText(content).width;
    var cx = x - width / 2;

    ctx.fillStyle = color;

    ctx.fillText(content, cx, y);

    // var contentArr = content.split('');

    // var width = ctx.measureText(content).width;
    // var cx = x - width / 2 - ((pxchange(0) * (contentArr.length - 1)) / 2);
    // var onewidth = ctx.measureText(contentArr[0]).width;
    // ctx.fillStyle = color;

    // for(var i = 0; i < contentArr.length;i++)
    // {
    //     ctx.fillText(contentArr[i], cx, y);
    //     cx = cx + pxchange(0) + onewidth;
    // }
}

function initCanvas() {
    myCanvas = $('#myCanvas')[0];
    ctx = myCanvas.getContext("2d");
    ctx.scale(2,2);
    myCanvas.width = 660;
    myCanvas.height = 660;
}

function getTranslateDistance(cardinal = 0) {
    var wrapInnerTransform = $('.wrap-inner').css('transform');
    var wrapInnertop = parseFloat($('.wrap-inner').css('top'));
    wrapInnerTransform = wrapInnerTransform.match(/^matrix\(1,\s0,\s0,\s1,\s0,\s\-?(\d+)/);
    wrapInnerTransform = parseFloat(wrapInnerTransform[1]);
    var wrapInnerjl = Math.abs(wrapInnertop - wrapInnerTransform);
    return wrapInnerjl + cardinal + 'px';
}

//获取随机数方法
//min 最小值
//max 最大值
function RandomNumBoth(Min,Max){
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}