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')
		});
	},
	alert : function(msg, timeout, callback) {
		app.loading(true);
		var wrap = $('.x-dialog');
		wrap.addClass('in').find('p').text(msg);
		setTimeout(function(){
			wrap.removeClass('in');
			callback.call();
		}, timeout);
	},
	getCookie: function(name) {
		var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
		return arr ? unescape(arr[2]) : null;
	},
	setCookie: function(name, value) {
		var exp = new Date(new Date().getTime() + 86400000);
		document.cookie = name + "="+ escape(value) + ";expires=" + exp.toGMTString();
	},
	delCookie: function(name) {
		var exp = new Date(new Date().getTime() - 1);
		var val = app.getCookie(name);
		document.cookie = name + "=" + val + ";expires=" + exp.toGMTString();
	},
	randomString: function(n) {
		var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''), res = "";
		for(var i = 0; i < n ; i ++) {
			res += chars[Math.ceil(Math.random()*35)];
		}
		return res;
	},
	toggleLoginTab: function(e) {
		var ot = $('.x-login-tab.active'), obId= ot.attr('aria-controls'), ob = $('#' + obId),
			nt = $(this), nbId = nt.attr('aria-controls'), nb = $('#' + nbId), left = nt.attr('aria-left');
		if(!nt.hasClass('active')) {
			ot.removeClass('active');
			ob.hide();
			nt.addClass('active');
			nb.show();
			$('.x-login-header .x-line').css('left', left);
			if (nbId == 'qrcode-wrap') {
				app.validByQrcode({
					clientId: app.getClientId(),
					appId: ob.find('input[name=appId]').val(),
					returnUrl: ob.find('input[name=returnUrl]').val()
				}, nb.find('img'));
			}
		}
	},
	getClientId: function() {
		var clientId = app.getCookie('sso_client_id');
		if (!clientId) {
			clientId = app.randomString(16);
			app.setCookie('sso_client_id', clientId);
		}
		return clientId;
	},
	validByQrcode: function(loginData, imageEl) {
		var now = new Date().getTime(), delay = 300000;
		if (!app.lastQRCodeImageTime || now - app.lastQRCodeImageTime > delay) {
			app.lastQRCodeImageTime = now;
			imageEl.attr('src', 'sso/qrcode?clientId=' + loginData.clientId);
		}
		$.post('sso/qrcode/login', loginData, function(data) {
			if (data && data.content) {
				if(data.content.spaces) {
					app.showSpaceSelect(data.content.spaces, function(spaceId){
						loginData.spaceId = spaceId;
						app.validByQrcode(loginData, imageEl);
					});
				} else {
					app.delCookie('sso_client_id');
					// 这里最好是到user/info
					window.location.href = data.content.returnUrl || 'http://www.ubtob.com';
				}
			} else {
				setTimeout(function(){
					app.validByQrcode(loginData, imageEl);
				}, 1000);
			}
		}, 'json');
	},

	/**
	 * 检测用户名是否被锁定
	 */
	checkUsernameIsLock: function () {
		var username = $(this).val();
		$.get('sso/checkPwd/count', {
			username: username,
		}, function (data) {
			$('.x-btn-submit').removeAttr('disabled');
			if (data.isLock) {
				$('.x-btn-submit').attr('disabled', 'disabled');
				app.error('密码错误次数已达上限，今日无法登陆', '警告');
			} else if (data.needCheckCode) {
				$('#captchaForm').show();
				app.error('当前已输错密码'+data.pwdError+'次，若达到5次今日将无法登陆', '警告');
			} else {
				$('#captchaForm').hide();
			}
			app.pwdError = data.pwdError;
		})
	},

	login : function(e, loginData) {
		var form = $('#form-wrap form');
		loginData = loginData || form.serializeObject();
		app.checkPassword();
		loginData.pwdSecLevel = $('#passstrength').val();
		$('#maxAge').is(':checked') && (loginData.sso_cookie_maxage =  30*24*60*60);
		if (!loginData.username) {
			form.find('[name=username]').focus();
			app.error('请填写账号');
		} else if (!loginData.password) {
			form.find('[name=password]').focus();
			app.error('请填写密码');
		} else if (app.pwdError >=3 && app.pwdError < 5 && !loginData.captcha) {
			form.find('[name=captcha]').focus();
			app.error('请填写验证码');
		} else {
			app.loading(true);
			$.post('sso/login', loginData, function(data) {
				app.loading(false);
				if (data) {
					if (data.error) {
						app.pwdError = data.pwdError;
						if("100" == data.errCode) {
							// redirect to set password
							app.alert('您的账户还未设置密码，正在为您跳转密码设置界面...', 4000, function () {
								window.location.href = "user/pwd?returnURL=" + encodeURIComponent(window.location.href);
							});
						} else if ("403" == data.errCode || app.pwdError >= 5) {
							app.error('密码错误次数已达上限，今日无法登陆');
							$('.x-btn-submit').attr('disabled', 'disabled');
							$('#captchaForm').hide();
						} else if (app.pwdError >= 3) {
							$('#captchaForm').show();
							app.error('当前已输错密码'+app.pwdError+'次，若达到5次今日将无法登陆', '警告');
						} else {
							app.error(data.errMsg, '警告');
						}
						app.changeCaptchaImage();
					} else if (data.content) {
						if(data.content.spaces) {
							app.showSpaceSelect(data.content.spaces, function(spaceId){
								loginData.spaceId = spaceId;
								app.login(null, loginData);
							});
						} else {
							// // 这里最好是到user/info
							// $('#body').appendTpl(data.content.loginUrl);
							$('#body').val(data.content.returnUrl || 'http://www.ubtob.com') ;
							// // 为了使众创登陆成功，加了一个延迟
							app.returnCount = 0;
							app.loading(true);
							app.noticeOther(data.content);
							// if (data.content.loginUrl) {
							// 	app.loginOther(data.content, data.content.loginUrl);
							// }
							// app.loginUuzc(data.content.uuzcData, data.content.uuzcLoginUrl);
							// app.loginMall(data.content, data.content.mallLoginUrl);
							// app.loginDiymall(data.content, data.content.diymallLoginUrl);
							setTimeout("app.returnHref()", 3000);
							// window.location.href = data.content.returnUrl || 'http://www.ubtob.com';
						}
					}
				} else {
					app.error('未知错误');
				}
			}, 'json');
		}
	},
	noticeOther: function (data) {
        for (var i=0;i<data.loginUrls.length;i++) {
			var loginUrl = data.loginUrls[i];
			$.ajax({
				type:"post",
				url:loginUrl,
				dataType:'jsonp',
				crossDomain: true,
				jsonp:'callback',
				jsonpCallback:"successCallback",
				data:data.data,
				success:function(json) {
					console.log(loginUrl);
					app.addCount(data.count);
				},
				error: function (json) {
					console.log(loginUrl);
					app.addCount(data.count);
				},
			});
        }
		var head = document.head || $('head')[0] || document.documentElement;
		var script = $('head').find('script')[0];
		script.onerror = function(evt) {
			app.addCount(a.count);
		}
	},
	addCount: function (count) {
		app.returnCount++;
		if (app.returnCount == count) {
			app.returnHref();
		}
	},
	returnHref: function () {
		var url = $('#body').val();
		window.location.href = url;
	},
	showSpaceSelect: function(spaces, callback) {
		app.loading(true);
		var wrap = $('.x-list');
		spaces.length > 8 && (wrap.addClass('x-list-' + Math.min(Math.ceil(spaces.length/8), 3) +'x'));
		wrap.addClass('in');
		wrap.find('ul').appendTpl('<li data-id="#{id}">#{name}</li>', spaces);
		// 需要考虑arrow up&down事件，不用hover来控制css
		wrap.find('ul li').mouseover(function(){
			wrap.find('ul li.active').removeClass('active');
			$(this).addClass('active');
		}).mouseleave(function(){
			$(this).removeClass('active');
		}).click(function(){
			wrap.removeClass('in');
			callback.call(null, $(this).data('id'));
		});
		$(window).keydown(function(event){
			if (wrap.is(':visible')) {
				event.stopPropagation();
				var active = wrap.find('li.active'), hasActive = active.length > 0,
					first = wrap.find('li:first'), last = wrap.find('li:last');
				if (hasActive && event.keyCode == 13) {// 回车按选中的企业登录
					callback.call(null, active.data('id'));
				} else {
					active.removeClass('active');
					if (event.keyCode == 38) {// 向上选中企业
						var prev = (hasActive ? (active.is(':first-child') ? last : active.prev()) : first);
						prev.addClass('active');
					} else if (event.keyCode == 40) {// 向下选中企业
						var next = (hasActive ? (active.is(':last-child') ? first : active.next()) : first);
						console.log(active.is(':last'));
						next.addClass('active');
					}
				}
			}
		});
	},
	slide: function() {
		var wrap = $('.x-banner'), items = wrap.find('li');
		if(window.chrome) {
			items.css('background-size', 'auto 100%');
		}
		if(items.length > 1) {
			wrap.unslider({
				speed: 1000,
				delay: 10000,
				dots: true
			});
		} else if (items.length == 1) {
			items.css('width', '100%');
		} else {
			wrap.find('ul').html('<li style="background: #efefef;width: 100%"></li>');
		}
		items.click(function(){
			var link = $(this).data("link");
			link && (window.open(link));
		});
	},
	checkPassword: function () {
		var password = $('#password').val();
		var strongRegex = new RegExp("^(?=.{8,20})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "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('Strong!');
			$('#passstrength').val(3);
		} else if (mediumRegex.test(password)) {
			$('#passstrength').className = 'alert';
			$('#passstrength').html('Medium!');
			$('#passstrength').val(2);
		} else {
			$('#passstrength').className = 'error';
			$('#passstrength').html('Weak!');
			$('#passstrength').val(1);
		}
		return true;
	},
	changeCaptchaImage: function () {
		$('#captchaImage').attr("src", "sso/checkcode/login?timestamp=" + (new Date()).valueOf());
		$('#captcha').val('');
	},
	init : function() {
		// 登录方式切换
		$('.x-login-tab').click(app.toggleLoginTab);
		$('#form-wrap .btn').click(app.login);
		// 换一张验证码
		$('#changeCode').click(app.changeCaptchaImage);
		// 用户名密码错误次数校验
		$('input[name="username"]').change(app.checkUsernameIsLock);
		$(window).keydown(function(event){
			event.stopPropagation();
			// 回车登录
			if (event.keyCode == 13) {
				app.login();
			}
		});
		// 图片轮播
		app.slide();
		app.loading(false);
		$('.softkeys').softkeys({
			target : $('.softkeys').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',
					[',','<'],
					['.','>'],
					['/','?'],
					['@']
				]
			]
		});
		$('#keyboard').on('click', function (event) {
			event.stopPropagation();
			var keyboard = $('.softkeys');
			if (keyboard.is(":hidden")) {
				keyboard.show();
			} else {
				keyboard.hide();
			}
		})
		$('.x-banner-wrap').on('click', function () {
			$('.softkeys').hide();
		})
		$('.softkeys').on('click', function (event) {
			event.stopPropagation();
		})
		$('.x-login').on('click', function (event) {
			$('.softkeys').hide();
		})
	}
};
$(document).ready(function() {
	app.init();
});