var app = {
	loading : function(is, position) {
		$('#loading').css('display', is ? 'block' : 'none');
		is && position && ($('#loading').addClass(position));
	},
	info : function(message, title, position) {
		toastr.info(message, title, {
			positionClass : 'toast-' + (position || 'top-center'),
			timeOut : 1000
		});
	},
	error : function(message, title, position) {
		toastr.error(message, title, {
			positionClass : 'toast-' + (position || 'top-center')
		});
	},
	getUrlParam: function(param) {
		var reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)");
		var r = window.location.search.substr(1).match(reg);
		return r ? decodeURI(r[2]) : null;
	},
	showDelayTime: function(el, step) {
		el.attr('disabled', 'disabled');
		setTimeout(function(){
			el.text(step-- + ' S');
			if(step > 0) {
				app.showDelayTime(el, step);
			} else {
				el.attr('disabled', null);
				el.text('获取验证码');
			}
		}, 1000);
	},
	checkTel: function (el, tel) {
		if(tel==null){
      toggleError(el, false, data.errMsg);
		}
		$.get('api/user/checkTel', {
			tel: tel
		}, function (data) {
			if (data.error) {
				el.addClass('x-error');
				toggleError(el, false, data.errMsg);
				$('.x-btn-code').attr('disabled', 'disabled');
			} else {
				$('.x-btn-code').remove('disabled');
			}
		})
	},
	checkEmail: function(el, email) {
		$.get('api/user/checkEmail', {
			email: email
		},function (data) {
			if (data.error) {
				el.addClass('x-error');
				toggleError(el, false, data.errMsg);
				$('.x-btn-emailCode').attr('disabled', 'disabled');
			} else {
				$('.x-btn-emailCode').remove('disabled');
			}
		})
	},
	enableCheckcode: function () {
		var telInput = $('input[name=tel]'), emailInput = $('[name=email]'),
			telCheckBtn = $('.x-btn-code'), emailCheckBtn = $('.x-btn-emailCode');
		function updateTelEnable() {
			if (telInput.val() && checkPattern(telInput)) {
				telCheckBtn.removeAttr('disabled');
			} else {
				telCheckBtn.attr('disabled', 'disabled');
			}
		}
		function updateEmailEnable() {
			if (emailInput.val() && checkPattern(emailInput)) {
				emailCheckBtn.removeAttr('disabled');
			} else {
				emailCheckBtn.attr('disabled', 'disabled');
			}
		}
		telInput.bind('change', function (event) {
			updateTelEnable();
		});
		emailInput.bind('change', function (event) {
			updateEmailEnable();
		});
	},
	sendValidCode: function() {
		var btn = $(this), f_tel = $('input[name=tel]'), tel = f_tel.val(),
			now = new Date().getTime(), delay = 60;
		if (!tel) {
			app.error('请填写手机号');
			f_tel.focus();
			return;
		}
		if (app.lastGetCodeTime && now - app.lastGetCodeTime < delay * 1000) {
			app.error('请稍后再获取');
			return;
		}
		app.lastGetCodeTime = now;
		app.loading(true);
		$.get('api/user/vcode', {
			source: 'resetPwd',
			username: tel
		}, function(data){
			app.loading(false);
			// 这里无论是否error都应设置success
			app.validCodeSendSuccess = true;
			if (data.errMsg) {
				if('403' != data.errCode) {
					app.lastGetCodeTime = null;
				}
				app.error(data.errMsg);
			} else {
				app.showDelayTime(btn, delay);
			}
		}).error(function (respose) {
			app.loading(false);
		});
	},
	checkValidCode: function() {
		var tel = $('input[name="tel"]').val();
		var validCode = $('input[name="validCode"]').val();
		$.post('api/user/vcode', {
			source: 'resetPwd',
			username: tel,
			validCode: validCode
		}, function(data){
			if (data.errMsg) {
				app.error(data.errMsg);
				$('input[name="validCode"]').addClass('x-error');
				toggleError($('input[name="validCode"]') , false, data.errMsg);
				// $('#validCode_err').show();
			} else {
				$('#validCode_err').hide();
				$('input[name="validCode"]').removeClass('x-error');
			}
		});
	},
	submitValidCheck: function(form, data) {
		app.loading(true);
		$.post('api/user/vcode', {
			source: 'submitValidCheck',
			username: data.tel,
			validCode: data.validCode
		}, function(data){
			app.loading(false);
			if (data.errMsg) {
				app.error(data.errMsg);
				form.find('input#validCode').addClass('x-error');
				toggleError(form.find('input#validCode') , false, data.errMsg);
				// $('#validCode_err').show();
			} else {
				// 验证成功后token
				app.pageToken = data.content;
				$('#validCode_err').hide();
				// $('.x-step li').eq(0).removeClass('active');
				$('.x-step li').eq(1).addClass('active');
				$('form[name=checkForm]').hide();
				$('#assistCheck').show();
			}
		});
	},
	sendValidMailCode: function() {
		var btn = $(this), f_email = $('input[name=email]'), email = f_email.val(),
			now = new Date().getTime(), delay = 60;
		if (!email) {
			app.error('请填写邮箱地址');
			f_email.focus();
			return;
		}
		if (app.lastMailCodeTime && now - app.lastMailCodeTime < delay * 1000) {
			app.error('请稍后再获取');
			return;
		}
		app.lastMailCodeTime = now;
		app.loading(true);
		$.get('api/user/vcode', {
			source: 'resetPwd',
			username: email
		}, function(data){
			app.loading(false);
			// 这里无论是否error都应设置success
			app.validMailCodeSendSuccess = true;
			if (data.errMsg) {
				if('403' != data.errCode) {
					app.lastMailCodeTime = null;
				}
				app.error(data.errMsg);
			} else {
				app.showDelayTime(btn, delay);
			}
		}).error(function (respose) {
			app.loading(false);
		});
	},
	checkValidMailCode: function() {
		var email = $('input[name="email"]').val();
		var validEmailCode = $('input[name="validEmailCode"]').val();
		$.post('api/user/vcode', {
			source: 'resetPwd',
			username: email,
			validCode: validEmailCode
		}, function(data){
			if (data.errMsg) {
				app.error(data.errMsg);
				$('input[name="validEmailCode"]').addClass('x-error');
				toggleError($('input[name="validEmailCode"]') , false, data.errMsg);
			} else {
				// 验证成功后token
				app.pageToken = data.content;
				$('#emailCode_err').hide();
				$('input[name="validEmailCode"]').removeClass('x-error');
			}
		});
	},
	submitTelCode: function (form, data) {
		app.loading(true);
		$.post('api/user/vcode', {
			source: 'submitValidCheck',
			username: data.tel,
			validCode: data.validCode
		}, function(data){
			app.loading(false);
			if (data.errMsg) {
				app.error(data.errMsg);
			} else {
				// 验证成功后token
				app.pageToken = data.content;
				app.getEncrypted();
				// $('.x-step li').eq(0).removeClass('active');
				$('.x-step li').eq(1).addClass('active');
				$('#firstStep').hide();
				$('#secondStep').show();
			}
		});
	},
	submitMailCode: function (form, data) {
		app.loading(true);
		$.post('api/user/vcode', {
			source: 'submitValidCheck',
			username: data.email,
			validCode: data.validEmailCode
		}, function(data){
			app.loading(false);
			if (data.errMsg) {
				app.error(data.errMsg);
			} else {
				// 验证成功后token
				app.pageToken = data.content;
				app.getEncrypted();
				// $('.x-step li').eq(0).removeClass('active');
				$('.x-step li').eq(1).addClass('active');
				$('#firstStep').hide();
				$('#secondStep').show();
			}
		});
	},
	resetPwd: function(form, data) {
		app.loading(true);
		var pwdInput = $('input[name=password]');
		var repwdInput = $('input[name=passwordConfirm]');
		if (pwdInput.val() != repwdInput.val()) {
            app.error("两次输入的密码不一致");
			toggleError(repwdInput, '两次输入的密码不一致');
            return;
		}
		$.post('api/user/resetPwd', {
			pageToken: app.pageToken,
			password: data.password
		}, function(data){
			app.loading(false);
			if (data.errMsg) {
				app.error(data.errMsg);
			} else {
				// 重置成功，跳转
				$('.x-step li').eq(3).addClass('active');
				$('#thirdStep').hide();
				$('#fourthStep').show();
				var redirectUrl = 'sso/login?appId=' + (app.getUrlParam('appId') || 'sso'), retUrl = app.getUrlParam('returnURL');
				retUrl && (redirectUrl += '&returnURL=' + retUrl);
				$('#toLogin').attr('href', redirectUrl);
				// window.location.href = redirectUrl;
			}
		});
	},
	choiseCheckType: function () {
		var type = $('input[name="checkType"]:checked').val();
		if (type == 'emailCheck') {
			$('#emailCheckForm').show();
			$('#checkForm').hide();
			$('#emailCheck').attr('checked', true);
			$('#telCheck').attr('checked', false);
		} else {
			// app.getEncrypted();
			$('#emailCheckForm').hide();
			$('#checkForm').show();
			$('#emailCheck').attr('checked', false);
			$('#telCheck').attr('checked', true);
		}
	},
	getEncrypted: function () {
		var tel = $('input[name="tel"]').val();
		$.get('api/user/encrypted/question', {
			'tel': tel
		}, function (data) {
			if (data.error) {
				app.error(data.errMsg);
				$('form[name="encryptedCheckForm"]').hide();
				$('form[name="noEncryptedForm"]').show();
			} else {
				app.questions = data.content;
				// var f_encrpCheck = $('#encryptedCheckForm');
				$.each(app.questions,function(i,item){
					// document.createElement();
					if (i == 0) {
						$('.question-first').html(item.question);
						$('.answer-first').attr('id', 'answer'+item.id);
					}
					if (i == 1) {
						$('.question-second').html(item.question);
						$('.answer-second').attr('id', 'answer'+item.id);
					}
				});
			}
		})
	},
	checkEncrypted: function (item) {
		var answer = $('#answer'+item.id).val();
		$('#answer'+item.id).addClass('x-error');
		$.post('api/user/check/question', {
			id: item.id,
			answer: answer
		}, function (data) {
			app.isOk = data.isOk;
			if (data.code == 404) {
				$('#answer'+item.id).addClass('x-error');
				// app.error(data.errMsg);
				toggleError($('#answer'+item.id), false, data.errMsg)
			}

			if (data.error) {
				// TODO 错误信息显示在输入框之后
				$('#answer'+item.id).addClass('x-error');
				// app.error(data.errMsg);
				toggleError($('#answer'+item.id), false, data.errMsg)
			} else {
				// TODO 答案正确
				$('#answer'+item.id).removeClass('x-error');
				// $('#assistCheck').hide();
				// $('form[name="resetForm"]').show();
			}
		})
	},
	checkFirst: function () {
		app.checkEncrypted(app.questions[0]);
	},
	checkSecond: function () {
		app.checkEncrypted(app.questions[1]);
	},
	submitAnswer: function() {
		if (!$('.answer-first').val() || !$('.answer-second').val()){
			return;
		}
		if (!app.isOk) {
			app.error('请填写正确的答案');
		} else {
			$('#secondStep').hide();
			$('#thirdStep').show();
			$('.x-step li').eq(2).addClass('active');
		}
	},
	checkPassword: function () {
		var password = $('#password').val();
		var strongRegex = new RegExp("^(?=.*[0-9].*)(?=.*[A-Z].*)(?=.*[a-z].*).{8,20}$", "g");
		var mediumRegex = new RegExp("^(?=.{8,20})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
		if (strongRegex.test(password)) {
			$('#passstrength').className = 'ok';
			$('#passstrength').html('强');
			$('#passstrength').val('3');
		} else if (mediumRegex.test(password)) {
			$('#passstrength').className = 'alert';
			$('#passstrength').html('中');
			$('#passstrength').val('2');
		} else {
			$('#passstrength').className = 'error';
			$('#passstrength').html('弱');
			$('#passstrength').val('1');
		}
		return true;
	},
	init : function() {
		app.loading(false);
		// 初始化单选按钮
		app.choiseCheckType();
		// 获取验证码按钮监听
		app.enableCheckcode();
		// 获取验证码
		$('.x-btn-code').click(app.sendValidCode);
		// 手机验证
		$('form[name=checkForm]').validation({
			disable: true,
			success: app.submitTelCode,
			error: function(form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'tel': app.checkTel,
				'validCode': app.checkValidCode
			}
		});
		// 获取验证码
		$('.x-btn-emailCode').click(app.sendValidMailCode);
		$('input[name="checkType"]').click(app.choiseCheckType);
		// 邮箱验证
		$('form[name=emailCheckForm]').validation({
			disable: true,
			success: app.submitMailCode,
			error: function (form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'email': app.checkEmail,
				'validEmailCode': app.checkValidMailCode
			}
		});
		// 密保验证
		$('form[name=encryptedCheckForm]').validation({
			disable: true,
			success: app.submitAnswer,
			error: function (form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'answer-first': app.checkFirst,
				'answer-second': app.checkSecond
			}
		});
		// 重置密码
		$("#password").keyup(function(){
          app.checkPassword();
		});
		$('form[name=resetForm]').validation({
			disable: true,
			success: app.resetPwd,
			error: function(form, errEl, errMsg) {
				app.error(errMsg);
			},
			listeners: {
				'password': {
					'change': function(el, val) {
						var oth = $('input[name=passwordConfirm]');
						if ($('#passstrength').val() == '1') {
							app.error('密码强度过低，请重新输入密码');
							toggleError($('#password'), false, '密码为8-20位字母、数字组合密码');
						} else if (oth.val() && val != oth.val()) {
							app.error('两次输入密码不一致');
							toggleError($('#passwordConfirm'), false, '两次输入密码不一致');
						}
					},
					'propertychange': function(el, val){
						var oth = $('input[name=password]');

						if (val && val == oth.val()) {
							$('form[name=resetForm] .x-btn-submit').attr('disabled', null);
						} else {
							$('form[name=resetForm] .x-btn-submit').attr('disabled', 'disabled');
						}
					}
				},
				'passwordConfirm': {
					'change': function(el, val){
						var oth = $('input[name=password]');
						if (val != oth.val()) {
							el.addClass('x-error');
							app.error('密码不一致');
							toggleError($('#passwordConfirm'),false,'两次输入密码不一致');
						}
					},
					'propertychange': function(el, val){
						var oth = $('input[name=password]');
						if (val && val == oth.val()) {
							$('form[name=resetForm] .x-btn-submit').attr('disabled', null);
						} else {
							$('form[name=resetForm] .x-btn-submit').attr('disabled', 'disabled');
						}
					}
				}
			}
		});
		initKeyboard('.softkeys1');
		initKeyboard('.softkeys2');
		$('#keyboard1').on('click', function (event) {
			event.stopPropagation();
			var keyboard = $('.softkeys1');
			if (keyboard.is(":hidden")) {
				keyboard.show();
			} else {
				keyboard.hide();
                app.checkPassword();
                $('#password').focus();
                $('#password').blur();
			}
		});
		$('#keyboard2').on('click', function (event) {
			event.stopPropagation();
			var keyboard = $('.softkeys2');
			if (keyboard.is(":hidden")) {
				keyboard.show();
			} else {
				keyboard.hide();
			}
		});
		$('.x-content').on('click', function () {
            if (!$('.softkeys1').is(":hidden")) {
                app.checkPassword();
                $('#password').focus();
                $('#password').blur();
            } else if (!$('.softkeys2').is(":hidden")) {
                $('#passwordConfirm').focus();
                $('#passwordConfirm').blur();
            }
			$('.softkeys').hide();
		})
		$('.softkeys').on('click', function (event) {
			event.stopPropagation();
		})
	}
};
function initKeyboard(str) {
	$(str).softkeys({
		target : $(str).data('target'),
		layout : [
			[
				['`','~'],
				['1','!'],
				['2','@'],
				['3','#'],
				['4','$'],
				['5','%'],
				['6','^'],
				['7','&'],
				['8','*'],
				['9','('],
				['0',')'],
				['-', '_'],
				['=','+'],
				'delete'
			],
			[
				'q','w','e','r','t','y','u','i','o','p',
				['[','{'],
				[']','}']
			],
			[
				'capslock',
				'a','s','d','f','g','h','j','k','l',
				[';',':'],
				["'",'"'],
				['\\','|']
			],
			[
				'shift',
				'z','x','c','v','b','n','m',
				[',','<'],
				['.','>'],
				['/','?'],
				['@']
			]
		]
	});
}
$(document).ready(function() {
	app.init();
});