Tb = (window.Tb || {});
Tb.User = (function() {
	var me,
		loginStatusCheckUrl = 'http://mai.taobao.com/json/home/seller_menu_data.htm',

		loginUrl = 'https://login.taobao.com/member/login.jhtml?' + $.param({
			sub: 'true',
			style: 'mini_top',
			from: 'mini_top',
			from_encoding: 'utf-8'
		}),

		loginCanceled = false,//是否取消过登录淘宝对话框

		token,
		shopId,
		isSub,//是否是子账号
		Logined = {};

	return {
		/*appRoot: '',
		nick: '',
		session: '',*/
		LoginTip: (function() {
			var callback,
				$loginTip = $('<div>本功能需要获取您的店铺信息 点击<a class="login-btn" href="#">登录店铺</a></div>')
					.css({
						'white-space': 'nowrap',
						position: 'absolute',
						top: 0,
						left: 0,
						padding: '4px 8px',
						color: '#fff',
						"line-height": "17px",
						'z-index': 999,
						'background-color': '#333',
						display: 'none'
					})
					.appendTo(document.body)
					.find('a').css({
						'color': '#fff',
						'text-decoration': 'underline'
					}).end();

			return {
				show: function(Login) {
					var	Pos = Menu.getIframePosition(),
						windowWidth = $(window).width(),
						animateHeight = 20;

					$loginTip.css({
						left: windowWidth - $loginTip.outerWidth() - 5,
						top: Pos.top + animateHeight,
						opacity: 0
					}).off().show().animate({
						opacity: 0.85,
						top: Pos.top
					})
						.on('click', '.login-btn', function() {
							Login.manually = true;
							me.login(Login);
						});
				},
				firstShow: function(Login) {
					var Pos = Menu.getIframePosition(),
						windowWidth = $(window).width(),
						windowHeight = $(window).height(),
						animateHeight = 20;

					$loginTip.css({
						left: windowWidth - $loginTip.outerWidth() - 5,
						top: Pos.top,
						opacity: 0.85,
						display: 'block'
					})

					var DialogSize = arguments.callee.DialogSize,
						myPos = {
							left: $loginTip.position().left,
							top: Pos.top,
							width: $loginTip.width(),
							height: $loginTip.height()
						};

					$loginTip.css({
						left: (windowWidth - DialogSize.width) / 2,
						top: (windowHeight - DialogSize.height) / 2,
						width: DialogSize.width - 16,
						height: DialogSize.height - 8,
						opacity: 0.85
					}).off().stop().animate({
						left: myPos.left,
						top: myPos.top,
						width: myPos.width,
						height: myPos.height
					}, 500)
						.on('click', '.author-btn, .login-btn', function() {
							Login.manually = true;
							me.login(Login);
						});
				},
				hide: function() {
					$loginTip.hide();
				}
			}
		})(),
		init: function() {
			me = this;

			Dwd.loginSuccess(function() {
				Menu.change(function() {
					me.LoginTip.hide();
				});
			});

			setInterval(function() { //刷用户session，保持连接
				$.post(loginStatusCheckUrl);
			}, 1000 * 60 * 10);

			return this;
		},
		logout: function(cb) { //登出
			$.ajax({
				url: 'http://login.taobao.com/member/logout.jhtml',
				type: 'get',
				complete: cb
			});
		},
		cancelAuthorise: function(CancelAuthorise) {
			$.ajax({
				url: 'http://container.api.taobao.com/container/authManager',
				cache: false,
				data: {
					action: 'cancel',
					appId: CancelAuthorise.appId,
					_tb_token_: token
				},
				success: function(Result) {
					var state = false;
					try {
						state = Result.Result.state == 1;
					} catch (e) {}

					CancelAuthorise.callback({
						state: state
					});
				},
				complete: function() {
					CancelAuthorise.callback({
						state: false
					});
				}
			});
		},
		loginBox: function(Login){
			var Size ={
				width: 310,
				height: 298
			};

			Dialog.normalAlert('淘宝登录', '数据读取中……');
			MiniBrowser.navigate({
				title: '淘宝登录',
				url: loginUrl,
				top: true,
				width: Size.width,
				height: Size.height,
				callback: function(obj, eventName) {
					if (eventName == 'close') {
						loginCanceled = true;
						Dialog.hide();
					}

					if (eventName == 'beforeNavigate' && /(https?:\/\/(i|login)\.taobao\.com|quicklogin=true)/.test(obj.url)) {
						MiniBrowser.hide();
					}
					if (eventName != 'documentComplete') {
						return;
					}

					var Field = getFields({
						subNumber: /sn=([^;$]+)/,
						nk: /_nk_=([^;$]+)/,
						token: /_tb_token_=([^;$]+)/
					}, obj.cookie);

					if(Field.subNumber){
						Field.subNumber = decodeURIComponent(Field.subNumber);
					}

					if(Field.nk || Field.subNumber){//已经登录用户
						me.getLoginedNick(function(userNick){
							MiniBrowser.hide({
								blank: true//清空页面
							});

							setTimeout(function(){
								Login.callback && Login.callback(userNick);
							}, 400);
						});
						return;
					}

					(function() { //异常登录，直接显示异常页面给用户自行处理
						if (~obj.url.indexOf('login_unusual.htm')) {
							MiniBrowser.show(true, 320, 270);
						}
					})();

					(function() {//登录窗口样式整理
						if (!~obj.url.indexOf('login.taobao.com')) {
							return;
						}

						var $body = $(obj.Win.document.body);

						$body.find('#J_LoginBox').css({
							width: 250,
							padding: 10
						});

						$body.find('.bd').css({
							padding: 0
						});

						$body = null;
						MiniBrowser.show(true);
					})();

					(function() { //登录成功
						return;
						if (!/(http:\/\/i\.taobao\.com|quicklogin=true)/.test(obj.url)) {
							return;
						}

						me.getLoginedNick(function(userNick){
							MiniBrowser.hide({
								blank: true//清空页面
							});

							setTimeout(function(){
								Login.callback && Login.callback(userNick);
							}, 400);
						});
					})();
				}
			});
		},
		login: function(callback, nick, add) { //登录
			var Login = arguments2object(arguments, true);

			//被取消过登录对话框或不是手动登录，显示非阻塞登录对话框
			if(loginCanceled && !Login.manually){
				Login.manually = true;
				me.LoginTip.show(Login);
				return;				
			}else{
				me.LoginTip.hide();
			}
			
			me.getLoginedNick(function(userNick) {
				if(!userNick){
					shopId = token = null;
					me.loginBox(Login);
					return;
				}

				var realClose = true;
				Dialog.alert({
					title: '请确认',
					content: '<div style="padding:5px;">当前登录旺旺是：[<strong style="color:#f00;">' + userNick + '</strong>]，继续？</div>',
					style: {
						width: 250
					},
					closeCallback: function(){
						if(!realClose) return;
						
						loginCanceled = true;
						me.LoginTip.firstShow.DialogSize = Dialog.getSize();
						me.LoginTip.firstShow(Login);
					},
					button: {
						'确 定': function() {
							realClose = false;

							Login.callback(userNick);
						},
						'切 换': function() {
							realClose = false;
							me.logout(function() {
								me.loginBox(Login);
							});
						},
						'取 消': function() {}
					}
				});
			});
		},
		isLogin: function(cb) { //是否登录了淘宝
			me.getLoginedNick(function(userNick){
				cb(userNick);
			});
		},
		getShopId: function(cb) {
			if (shopId) {
				cb(shopId);
				return;
			}

			$.ajax({
				url: 'http://siteadmin.taobao.com/design.htm',
				success: function(text) {
					try {
						shopId = text.match(/shopId=(\d+)/)[1];
					} catch (e) {}

					if (shopId) {
						cb(shopId);
					}
				}
			});
		},
		getLoginedNick: function(cb) { //取登录用户的昵称
			$.ajax({
				url: 'http://mai.taobao.com/seller_admin.htm',
				cache: false,
				success: function(html){
					var Field = getFields({
						userNick: /class="user-nick">(.+?)<\/a>/,//子账号
						token: /&_tb_token_=(.+?)">/,//子账号
						userId: /&userid=(\d+)/
					}, html);

					if(Field.userNick && Field.token && Field.userId){
						Logined[Field.userId] = Field.userNick;
						token = Field.token;
						cb(Field.userNick);
						return;
					}

					if(!Field.userId){
						cb(false);
						return;
					}

					$.ajax({
						url: 'http://i.taobao.com/user/baseInfoSet.htm',
						cache: false,
						success: function(html){
							var Field = getFields({
								userNick: />亲爱的<b>(.+?)<\/b>/,
								token: /<input name='_tb_token_' type='hidden' value='(.+?)'>/,
								userId: /&userid=(\d+)/
							}, html);

							if(Field.userNick && Field.token && Field.userId){
								Logined[Field.userId] = Field.userNick;
								token = Field.token;
								cb(Field.userNick);
							}else{
								cb(false);
							}
						}
					});
				},
				error: function(){
					cb(false);
				}
			});
		},
		getToken: function(cb) {
			cb && cb(token);
		}
	}
})().init();