var PP = (function(){
	return {
		init: function(){
		},
		logout: function(cb){
			$.ajax({
				url: 'http://member.paipai.com/cgi-bin/c2cUser_LoginOut',
				complete: cb
			});
		},
		login: function(cb){
			var self = this,
				loginAction = function(){
					MiniBrowser.navigate({
						url: 'https://ssl.ui.ptlogin2.paipai.com/cgi-bin/login?' + $.param({
							appid: 17000101,
							pt_safe: 1,
							style: 13,
							target: 'self',
							link_target: 'blank',
							hide_title_bar: 1,
							hide_close_icon: 1,
							tmp: 201105241407,
							s_url: encodeURI('http://member.paipai.com/cgi-bin/ptlogin?loginfrom=18')
						}),	
						callback: function(obj){
							var uinReg = /; uin=(o0+)?(\d+)/,
								loginedUin = '';
							try{
								loginedUin = obj.cookie.match(uinReg)[2];
							}catch(e){}
							
							if(loginedUin){
								cb(loginedUin);
							}
						}
					});				
				};
			
			this.User.getUserInfo(function(User){
				if(User){
					Dialog.alert({
						title: '请确认',
						content: '当前登录拍拍是：[<strong style="color:#f00;">' + User.uin + '</strong>]，继续？',
						style: {
							width: 250,
							height: 30
						},
						button: {
							'确 定': function() {
								cb(User.uin);
							},
							'切 换': function() {
								self.logout(loginAction);
								//loginAction();
							},
							'取 消': function() {}
						}
					});					
				}else{
					loginAction();
				}
			});
		}
	}
})();

PP.User = (function(){
	var User,
		userKeepOnlineTimer;
	
	return {
		get: function(callback){
			this.getUserInfo(function(user){
				callback(user);
			});
		},
		getUserInfo: function(callback){
			var url = 'http://my.paipai.com/cgi-bin/c2cUser_view_userInfo';
			var cookie = MiniBrowser.getCookie();
			
			$.ajax({
				url: url,
				cache: false,
				success: function(data){
					User = getFields({
						isLogined: /个人资料设置/,
						isSeller: /var bIsSeller="1";/,
						uin: /<input type="hidden" id="userid" value="(\d+)" \/>/,
						email: /DoAlertEmail\('(.+?)',0,0\)/,
						name: /<input type="hidden"id="sName" name="sName" value="(.*?)"\/>/,
						nickName: /<th>昵称：<\/th>\s*<td>(\S+)/,
						address: /<input id="sAddress" name="sAddress" type="text" value="(.*?)"/,
						phone: /<input type="text" id="sPhone" name="sPhone" .+? value="(.*?)" >/,
						mobile: /DoAlertMobile\(1,'(.*?)', 0\)/
					}, data);
					
					if(!userKeepOnlineTimer){
						userKeepOnlineTimer = setInterval(function(){
							$.get('http://my.paipai.com/myppindex/buyer');
						}, 1000 * 60 * 10);
					}
					
					if(!User.isLogined) User = false;
					callback && callback(User);
				},
				error: function(){
					callback && callback(false);
				}
			});
		}
	}
})();