gift.page.js 2.99 KB
/**
 * 个人中心页-兑换礼品卡
 * @author: wsl<shuiling.wang@yoho.cn>
 * @date: 2016/02/22
 */
var $ = require('yoho-jquery'),
    Captcha = require('../plugins/captcha');

var dialog = require('../common/dialog');

var Alert = dialog.Alert;

var $giftError = $('.giftCardCode').find('.gift-error'),
    reg = /^[0-9a-zA-Z]{4,4}$/,
    i = 1;

var active;

var captcha;

var Gift = {
    suc: [
        false,
        false,
        false,
        false
    ],
    checkCard: function(num) {

        if (!reg.test($('#giftCardCode' + num).val())) {
            $giftError.html('您输入的兑换码有误,兑换码必须为数字或字母,每个文本框里只能输入四个兑换码!');
            Gift.suc[num - 1] = false;
        } else {
            for (i = 1; i <= 3; i++) {
                if (!reg.test($('#giftCardCode' + i).val())) {
                    $giftError.html('您输入的兑换码有误,兑换码必须为数字或字母,每个文本框里只能输入四个兑换码!');
                    Gift.suc[i] = false;
                } else {
                    $giftError.html('');
                    Gift.suc[i] = true;
                }
            }

            if (num !== 3) {
                $('#giftCardCode' + (num + 1)).focus();
            }
        }
    },
    bindGiftCardForm: function() {
        $('#giftCardCode1').bind('blur keyup', function() {
            Gift.checkCard(1);
        });

        $('#giftCardCode2').bind('blur keyup', function() {
            Gift.checkCard(2);
        });

        $('#giftCardCode3').bind('blur keyup', function() {
            Gift.checkCard(3);
        });
    },

    checkForm: function() {
        if (!reg.test($('#giftCardCode1').val()) || !reg.test($('#giftCardCode2').val()) ||
            !reg.test($('#giftCardCode3').val())) {
            $giftError.html('您输入的兑换码有误,兑换码必须为数字或字母,每个文本框里只能输入四个兑换码!');
            return $.Deferred().reject().promise(); // eslint-disable-line
        }

        return captcha.check();
    }
};

captcha = new Captcha('.captcha-img').init();

captcha.refresh();

require('../common');

// 更换验证码
function refreshCaptcha() {
    var dt = new Date();

    $('#imgcode').attr('src', '/passport/imagesNode?t=' + dt.getTime());
    return false;
}

$('#sub-gift').on('click', function() {

    Gift.checkForm().then(function() {
        $.post('/home/gift/exchange', $('#giftCardForm').serialize(), function(data) {
            if (data.code === 200) {
                window.location.href = '/home/gift?type=1';
            } else if (data.code === 400) {
                active = new Alert(data.message);
                active.show();
                refreshCaptcha();
            } else {
                window.location.href = '/home/gift?type=2';
            }
        }, 'json');
    });
});

$(document).on('click', '#imgcode,.check-img', function() {
    refreshCaptcha();
});

$(function() {
    refreshCaptcha();
    Gift.bindGiftCardForm();
});