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 uploadCanvas;
var headimgCanvas;
var uploadctx;
var headimgctx;
var imgInfo = {};
var nowTemplate = 1;

preloadimages(preloadImageList, function () {

}, function (progress) {

});

$('input[name=customize]').attr('placeholder','输入自定义文字（仅限四个字）').attr('maxlength','4');
$('.canvas-block').html('<canvas id="uploadCanvas" width="'+ 330 +'" height="'+ 330 +'"></canvas>');
$('.headimg-canvas-block').html('<canvas id="headimgCanvas" width="'+ 330 +'" height="'+ 330 +'"></canvas><img id="headimg" />');

$('.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);

    $('.btn-slideleft').on('click',slidePrevTemplate);
    $('.btn-slideright').on('click',slideNextTemplate);

    $('.btn-toheadimg').on('click',createHeadimg);

    $('[name=btn-tocreate]').change(function() {
        var canvasinfo = initCanvas('#uploadCanvas',660,660);
        uploadCanvas = canvasinfo[0];
        uploadctx = canvasinfo[1];
        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);
                    initGame();
                    results = null;
                    imgData = null;
                };
                img.src = results.base64;
            });
        });
        return false;
    });

    var mc = new Hammer($('.hammer-block').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 createHeadimg() {
    var headimgObj = new Image();
    headimgObj.src = getManBase64(uploadCanvas);

    var canvasinfo = initCanvas('#headimgCanvas',660,660);
    headimgCanvas = canvasinfo[0];
    headimgctx = canvasinfo[1];

    headimgObj.onload = function() {
        headimgctx.drawImage(headimgObj,0,0,headimgCanvas.width,headimgCanvas.height);

        var frameimg = new Image();
        frameimg.src = '/Public/static/image2/frame' + nowTemplate + '.png';

        frameimg.onload = function() {
            headimgctx.drawImage(frameimg,0,0,headimgCanvas.width,headimgCanvas.height);

            $('#headimg').attr('src'.getManBase64(headimgCanvas));

            $('.upload-page').fadeOut(300);
            $('.headimg-page').delay(200).fadeIn(300);
        }
    }
}

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

function slidePrevTemplate() {
    if(nowTemplate - 1 <= 0)
    {
        nowTemplate = 6;
    }
    nowTemplate -= 1;
    $('.template').hide();
    $('.template' + nowTemplate).show();
    if(nowTemplate == 5) $('.customize').show();
    else $('.customize').hide();
}

function slideNextTemplate() {
    if(nowTemplate + 1 >= 6)
    {
        nowTemplate = 0;
    }
    nowTemplate += 1;
    $('.template').hide();
    $('.template' + nowTemplate).show();
    if(nowTemplate == 5) $('.customize').show();
    else $('.customize').hide();
}

function drawImage() {
    uploadctx.save();
    uploadctx.clearRect(0, 0, uploadCanvas.width, uploadCanvas.height);
    uploadctx.translate(uploadCanvas.width / 2, uploadCanvas.height / 2);
    uploadctx.translate(imgInfo.x, imgInfo.y);
    uploadctx.rotate(Math.PI / 180 * imgInfo.rotation);
    uploadctx.scale(imgInfo.scale, imgInfo.scale);
    uploadctx.drawImage(img, -img.width / 2, -img.height / 2);
    uploadctx.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(canvas) {
    return canvas.toDataURL('image/png');
}

function initGame() {
    $('.template').hide();
    $('.template' + nowTemplate).show();
    $('.customize').hide();
}

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(id,canvasWidth,canvasHeight) {
    canvas = $(id)[0];
    ctx = canvas.getContext("2d");
    ctx.scale(2,2);
    canvas.width = canvasWidth;
    canvas.height = canvasHeight;
    return [canvas, ctx];
}

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;
}