var loadedImages = {};

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].crossOrigin = "Anonymous";
        images[i].setAttribute('crossOrigin', 'anonymous');
        images[i].url = obj[i];
        images[i].src = obj[i];

        //console.log( images[i].src );
        images[i].onload = load;
        images[i].onerror = load;
        images[i].onabort = load;
    }
    if (obj.length == 0) {
        complete_cb(images);
    }

    function load() {
        loadedImages[this.url] = this;
        ++loaded;
        if (progress_cb) {
            progress_cb(loaded / toload);
        }
        if (loaded >= toload) {
            complete_cb(images);
        }
    }
}
preloadImageList = []
preloadImageList.push('/Public/static/image2/cover/1.jpg');
// for (var i = 3; i <= 4; i++) {
//     preloadImageList.push('/Public/static/image2/cover/' + i + '.png');
// }
preloadimages(preloadImageList, function () {
    // init();
}, function (progress) {});

var canvas = false,
    ctx = false,
    imgInfo = false,
    oldpoz = false,
    inited = false,
    firstSwiper, images = [],
    custom = false,
    uploadedImg = false;
$(document).ready(function () {
    if ($('.page').height() < document.documentElement.clientHeight) {
        var scale = document.documentElement.clientHeight / $('.page').height();
        $('.bg').css({
            'transform': 'scale(1,' + scale + ')'
        });
    }
    $('.container').css('height', document.documentElement.clientHeight + 'px');
    var fixHeight = Math.abs($('.page').height() - document.documentElement.clientHeight) / 2;
    $('.logo').css('top', fixHeight + 30 + 'px');
    $("input").on("blur", function () {
        window.scroll(0, 0); //失焦后强制让页面归位
    });
    $('input[type=text]').on('focus', function () {
        $('.inputTip').hide();
        //  $('.start').hide();
    });
    $('input[type=text]').on('blur', function () {
        window.scrollTo(0, 0);
        if ($.trim($(this).val()) === '') {
            $('.inputTip').show();
            // $('.start').hide();
        } else {
            $('.inputTip').hide();
            // $('.start').show();
        }
    });
    $('.again').on('click', function () {
        $('.make,.username').show();
        $('.again,.saveTip').hide();
        $('.inputTip').show();
        $('.page').hide().filter('.page1').show();
        ctx.save();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
    });
    $('.make').on('click', function () {
        if (!inited) {
            return;
        }

        var text = $.trim($('.page:visible').find('input[type=text]').val());
        if (text === '') {
            showTip('您还没有输入名字');
            return;
        }
        if (text.gblen() > 10) {
            showTip('名字最长为5个汉字');
            return;
        }
        $('.usertips').hide();
        if (text.length === 2) {
            var last = text[1];
            text = text[0] + ' ' + last;
        }
        $('.make,.username').hide();
        $('.again,.saveTip').show();
        var img, canvas2, ctx2;
        img = loadedImages['/Public/static/image2/cover/1.jpg'];

        canvas2 = document.createElement('CANVAS'),
            ctx2 = canvas2.getContext('2d');
        ctx2.scale(2, 2);
        canvas2.height = img.height;
        canvas2.width = img.width;
        ctx2.drawImage(img, 0, 0);

        //模板1
        top = 545;
        if (browser.versions.iPhone) top = 535
        ctx2.fillStyle = '#ffffff';
        ctx2.font = 'bold 110px normal';

        ctx2.textAlign = 'left';
        ctx2.textBaseline = 'top';
        var left = ((img.width - ctx2.measureText(text).width) / 2) - 10;
        ctx2.shadowBlur = 0;
        setTimeout(function () {
            ctx2.fillText(text, left, top * 2);
            $('.page:visible').find('.showBox').show().html('<img src="' + canvas2.toDataURL('image/png') + '">');
        }, 0)
    });
    // $('input[type=text]').on('input', onInput);
});

var showTip = function (msg, delay) {
    $('#notification_area').remove();
    return my_notify(msg, delay);
}
var init = function () {
    inited = true;
    $('.imgTip').html('<canvas></canvas>');
    canvas = $('canvas').get(0);
    ctx = canvas.getContext('2d');
    ctx.scale(2, 2);
    var img = loadedImages['/Public/static/image2/cover/1.png'];
    canvas.width = img.width;
    canvas.height = img.height;
}
var drawImage = function () {
    if (uploadedImg) {
        ctx.save();
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        ctx.fillStyle = "#ffffff";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        ctx.translate(canvas.width / 2, canvas.height / 2);
        ctx.translate(imgInfo.x, imgInfo.y);
        ctx.rotate(Math.PI / 180 * imgInfo.rotation);
        ctx.scale(imgInfo.scale, imgInfo.scale);
        ctx.drawImage(uploadedImg, -uploadedImg.width / 2, -uploadedImg.height / 2);
        ctx.restore();
    }
    var img = loadedImages['/Public/static/image2/cover/4.png'];
    ctx.drawImage(img, 0, 0);
}
var showPage1 = function () {
    custom = false;
    $('.page').hide().filter('.page1').show();
    if (!firstSwiper) {
        var swiperHtml = $('<div class="swiper-container"><div class="swiper-wrapper"></div></div>');
        swiperHtml.attr('id', 'firstSwiper').css({
            width: $('.swiperBox').css('width'),
            height: $('.swiperBox').css('height')
        });
        swiperHtml.appendTo('.swiperBox');
        for (var i = 1; i < 4; i++) {
            if ((4 - i) == 4) wz = 'png'
            else wz = 'jpg'
            var img = '/Public/static/image2/cover/' + (4 - i) + '.' + wz;
            images.push(loadedImages[img]);
            var item = $('<div class="img"><img src="' + img + '" /></div>');
            item.wrap('<div class="swiper-slide"></div>').parent().prependTo($('#firstSwiper').find('.swiper-wrapper'));
        }
        $('.img').css({
            width: $('.showBox').css('width'),
            height: $('.showBox').css('height')
        });
        firstSwiper = new Swiper('#firstSwiper', {
            'allowSlideNext': true,
            // direction: 'vertical'
        });
        // firstSwiper.detachEvents()
    } else {
        $('.swiperBox,.make,.username').show();
        $('.again,.saveTip,.showBox').hide();
        $('input').val('');
        $('.inputTip').show();
    }
}
var showPage2 = function () {
    custom = true;
    uploadedImg = false;
    $('.again,.saveTip,.showBox').hide();
    $('.page').find('.imgTip,.make,.username').show();
    $('input').val('');
    $('.inputTip').show();
    $('.page').hide().filter('.page2').show();
}
var onInput = function () {
    var maxLength = 10;
    if (getLength(this.value) > maxLength)
        this.value = limitMaxLength(this.value, maxLength);
}
var getLength = function (str) {
    return str.replace(/[^ -~]/g, 'AA').length;
}
var limitMaxLength = function (str, maxLength) {
    var result = [];
    for (var i = 0; i < maxLength; i++) {
        var char = str[i]
        if (/[^ -~]/.test(char))
            maxLength--;
        result.push(char);
    }
    return result.join('');
}

String.prototype.gblen = function () {
    var len = 0;
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) > 127 || this.charCodeAt(i) == 94) {
            len += 2;
        } else {
            len++;
        }
    }
    return len;
}

var mc = new Hammer($('.imgTip').get(0));
mc.get('pan').set({
    direction: Hammer.DIRECTION_ALL
});
mc.get('pinch').set({
    enable: true
});
mc.get('rotate').set({
    enable: true
});
mc.on('panstart panmove panend', function (event) {
    if (!uploadedImg) {
        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 * 4;
        imgInfo.y += movedY * 4;
        drawImage();
    }
    //苹果手机自动调整图片 不需要旋转
    if (navigator.userAgent.indexOf('iPhone') > -1) {
        imgInfo.rotation = 0;
    }
    return false;
});
mc.on('pinchstart pinchmove pinchend', function (event) {
    if (!uploadedImg) {
        return;
    }
    if (event.type == 'pinchstart' || event.type == 'pinchend') {
        oldpoz.scale = imgInfo.scale;
    } else {
        var nowScale = event.scale * oldpoz.scale;
        //oldpoz.scale = event.scale;
        imgInfo.scale = nowScale;
        drawImage();
    }
    return false;
});
// mc.on('rotatestart rotatemove rotateend', function (event) {
//     if (!uploadedImg) {
//         return;
//     }
//     if (event.type == 'rotatestart' || event.type == 'rotateend') {
//         oldpoz.rotation = 0;
//     } else {
//         var nowRotation = (event.rotation - oldpoz.rotation);
//         oldpoz.rotation = event.rotation;
//         imgInfo.rotation += nowRotation;
//         drawImage();
//     }
//     return false;
// });