if (typeof(Tb) == 'undefined') {
	Tb = {};
};
Tb.User = (function() {
	var loginStatusCheckUrl = 'http://sample.home.taobao.com/loginCheck.htm',
		loginedReg = /\s*null\(\d+\)\s*/,
		token = '';

	return {
		appRoot: '',
		nick: '',
		session: '',
		init: function() {
			setInterval(function() { //刷用户session，保持连接
				$.post(loginStatusCheckUrl);
			},
			1000 * 60 * 10);
		},
		getToken: function() {
			return token;
		},
		logout: function(cb) { //登出
			$.ajax({
				url: 'http://login.taobao.com/member/logout.jhtml',
				type: 'get',
				complete: cb
			});
		},
		cancelAuthorise: function(CancelAuthoriseObject) {
			$.ajax({
				url: 'http://container.api.taobao.com/container/authManager',
				cache: false,
				data: {
					action: 'cancel',
					appId: CancelAuthoriseObject.appId,
					_tb_token_: token
				},
				success: function(Result) {
					var state = false;
					try {
						state = Result.Result.state == 1;
					} catch (e) {}

					CancelAuthoriseObject.callback({
						state: state
					});
				},
				complete: function() {
					CancelAuthoriseObject.callback({
						state: false
					});
				}
			});
		},
		login: function(cb, nick, add) { //登录
			var self = this,
				loginUrl = 'https://login.taobao.com/member/login.jhtml?' + $.param($.extend({}, {
					'style': 'mini',
					'TPL_redirect_url': decodeURI(loginStatusCheckUrl)
				})),
				loginAction = function() {

					MiniBrowser.navigate({
						url: loginUrl,
						callback: function(obj) {
							if (obj.url == loginStatusCheckUrl) {
								var loginedNick = '';
								try {
									loginedNick = ('' + obj.cookie).match(/_nk_=([^;]+);/)[1];
								} catch (e) {}

								$.ajax({
									url: 'http://container.api.taobao.com/container/authManager?t=' + Number(new Date()),
									success: function(html) {
										token = getFields({
											token: /<input name="_tb_token_" type="hidden" value="(\w+)"/
										}, html).token;
									},
									complete: function() {
										MiniBrowser.hide();
										cb && cb(unescape(decodeURI(loginedNick).replace(/\\/g, '%')));
									}
								});
							}
						}
					});
					return false;

					var loginFilePath = '../log/logintemp.html',
						showForm = function(url) {
							Dialog.superIframe({
								title: '登录淘宝',
								src: url,
								style: {
									width: 300,
									height: 260
								},
								action: function($doc, Win, $content, layout) {
									Fso.del(loginFilePath);

									var url = Win.location.href,
										$body = $doc.find('body'),
										html = $doc.find('body').html(),
										winP = Win;

									try {
										Win.KISSY.io.setupConfig({
											crossDomain: false
										});
									} catch (e) {}

									var userName = $body.find('#TPL_username_1').val(nick || '').focus();
									$body.find('#J_StaticLink, #J_Quick2Static').click(function() {
										$body.find('#J_Dynamic, #J_QuickLogin').hide();
										$body.find('#J_Static').show();
									});

									$body.find('#J_DynamicLink').click(function() {
										$body.find('#J_Dynamic').show();
										$body.find('#J_Static, #J_QuickLogin').hide();
									});

									(function() {
										if (url.indexOf('logintemp.html') == -1) return;

										var loginBlank = 'http://login.taobao.com/static/img/blank.gif';

										try {
											$('<iframe style="display:none;" src="about:blank" application="yes"></iframe>')
												.appendTo(Win.document.body)
												.load(function() {
												var Win2 = this.contentWindow,
													Doc = Win2.document,
													body = Doc.body,
													url = Win2.location;

												if (url != loginBlank && url != 'about:blank') {
													Win.location = url;
													return;
												} else if (url != loginBlank) {
													return;
												}

												var filePath = '../log/quick-login.js',
													template = 'window.onerror=function(){return true;};var Login = (function(){\
															var ctrl = new ActiveXObject("AliIMSSOLogin.SSOLoginCtrl.1"),\
															UserList = ctrl.GetUserList(1, 0);\
															\
															return {\
																getSize: function(){\
																	return UserList.GetSize();\
																},\
																getList: function(){\
																	var arr = [];\
																	for(var i=this.getSize(); i--;){\
																		var Data = UserList.GetItemData(i);\
																		arr.push({\
																			index: i,\
																			nick: Data.GetDataStr("strKey_ShortUserID"),\
																			fullNick: Data.GetDataStr("strKey_FullUserID")\
																		});\
																	}\
																	return arr;\
																},\
																login: function(index, cb){\
																	try{\
																		var H = UserList.GetItemData(index);\
																		H.SetDataStr("strKey_SrcURL", "' + loginStatusCheckUrl + '");\
																		var K = ctrl.Go(0, H);\
																		cb(K.GetDataStr("strKey_GOResult") == "1");\
																	}catch(e){\
																		cb(false);\
																	}\
																}\
															}\
														})();';

												try {
													Fso.write(filePath, template);
													var script = Doc.createElement('script');
													script.type = 'text/javascript';
													script.src = self.appRoot + filePath;
													Doc.body.appendChild(script);
													Fso.del(filePath);

													var userSize = Win2.Login.getSize();
													if (userSize > 0) {
														var userListHTML = parseData2Template(
															'<li class="item-user item-wwuser $cls">\
														<input data-index="$index" id="ra-$index" class="r-user r-wwuser" name="user" value="$fullNick" type="radio" $checked />\
														<label for="ra-$index">$nick</label>\
													</li>',
														Win2.Login.getList(), {
															cls: '',
															checked: ''
														});

														$body.find('#J_QuickLogin').submit(function() {
															Win2.Login.login(parseInt($body.find('#J_QuickLogin ul.userlist2 :checked').attr('data-index')), function(success) {
																if (!success) {
																	$body.find('#J_QuickLogin').hide();
																	$body.find('#J_Static').show();
																}
															});
															$body.find('#J_SubmitQuick').html('\u6B63\u5728\u767B\u5F55\u2026');
															return false;
														});

														setTimeout(function() {
															$body.find('#J_QuickLogin').show().find('ul.userlist').hide().after('<ul class="userlist2 userlist"></ul>');

															$body.find('#J_QuickLogin ul.userlist2').html(userListHTML).find(':radio').click(function() {
																$(this).parent().addClass('current').siblings().removeClass('current');
															}).show().eq(0).click();
															$body.find('#J_Static').hide();

															var $radio = $body.find('#J_QuickLogin ul.userlist2 :radio');
															if ($radio.length === 1) {
																$radio.hide();
															}
														}, 0);
													}
												} catch (e) {}
											})
												.attr('src', loginBlank);
										} catch (e) {}
									})();

									if (url.indexOf('http://login.taobao.com/member/login_unusual.htm') === 0) {
										$doc.find('body').find('iframe').attr('application', 'yes').load(function() {
											var Win = this.contentWindow,
												$doc = $(Win.document);
											var html = $(this.contentWindow.document).find('body').html();
											if (html.indexOf('var isSuccess = window.location.search.indexOf') > -1) {
												winP.AQPop.success();
											} else {
												$doc.find('body').find('.J_Close').click(function() {
													loginCancelBtnTriggered = true;
												});
											}
										});
									}

									if (loginedReg.test(html)) {
										var loginedNick = '';
										try {
											loginedNick = ('' + Win.document.cookie).match(/_nk_=([^;]+);/)[1];
										} catch (e) {}

										Dialog.hide();
										cb && cb(unescape(decodeURI(loginedNick).replace(/\\/g, '%')));
									}
								},
								button: {
									'确 定': false
								}
							});
						};

					if (RealyIEVersion.get() >= 9) {
						top.Dialog.alert({
							title: '提示',
							content: '正在启动淘宝登录窗口…',
							style: {
								width: 250,
								height: 30
							},
							button: {
								'确 定': false
							}
						});

						top.$.ajax({
							url: loginUrl,
							dataType: 'text',
							success: function(html) {
								var content = Fso.asynWrite(
								loginFilePath,
								html.replace('content="IE=edge"', 'content="IE=8"')
									.replace(/(um.init\(\{\s*debug: false,\s*enabled: )true/, '$1false')
									.replace('<head>', '<head><script>window.onerror=function(a,b,c,d){return true;}</script>'),

								function() {
									showForm(loginFilePath);
								});
							}
						});
					} else {
						showForm(loginUrl);
					}
				},
				checker = function() {
					self.getLoginedNick(function(loginedNick) {
						if ((nick && nick == loginedNick) || loginedNick) {
							Dialog.alert({
								title: '请确认',
								content: '当前登录旺旺是：[<strong style="color:#f00;">' + loginedNick + '</strong>]，继续？',
								style: {
									width: 250,
									height: 30
								},
								button: {
									'确 定': function() {
										cb(loginedNick);
									},
									'切 换': function() {
										loginAction();
									},
									'取 消': function() {}
								}
							});
						} else {
							loginAction();
						}
					});
				};

			if (add) {
				loginAction();
			} else {
				checker();
			}
		},
		isLogin: function(cb) { //是否登录了淘宝
			var self = this;
			$.ajax({
				url: loginStatusCheckUrl,
				success: function(html) {
					if (loginedReg.test(html)) {
						self.getLoginedNick(cb);
					} else {
						cb(false);
					}
				},
				error: function() {
					cb(false);
				}
			});
		},
		getLoginedNick: function(cb) { //取登录用户的昵称
			$.ajax({
				url: 'http://i.taobao.com/my_taobao.htm',
				cache: false,
				dataType: 'text',
				success: function(data) {
					try {
						var userId = data.match(/userid=(\d+)/)[1];
						$.ajax({
							url: 'http://rate.taobao.com/rate.htm?userId=' + userId,
							dataType: 'text',
							cache: false,
							success: function(data) {
								try {
									var ww = decodeURI(data.match(/data\-nick="([^"]+)"/)[1]);
									cb(ww);
								} catch (e) {
									cb(false);
								}
							},
							error: function() {
								cb(false);
							}
						});
					} catch (e) {
						cb(false);
					}
				},
				error: function(jqXhr, textStatus) {
					cb(false);
				}
			});
		}
	}
})();
$(function() {
	Tb.User.init();
});