var ppOfflineClient = (function(){
	var windowId = 'paipai' + new Date().getTime(),
		triggerBtn = $('#menuPPLXTG'),
		layout = $('#layoutPaipaiOffline'),
		loginBtn = layout.find('.loginBtn'),
		submitBtn = layout.find('.submitBtn'),
		offlineFeeBtn = layout.find('.offlineFeeBtn'),
		offlineEndTime = layout.find('.offlineEndTime'),
		list = layout.find('.list'),
		l = function(selector){
			return layout.find(selector);
		},
		
		shopNumber = '',
		source = 'paipai'
		cookies = '';
		
	var User, App;
	
	return {
		init: function(){
			var self = this;
			offlineFeeBtn.click(function(){
				var endTime = offlineEndTime.text();
					endStr = endTime.split(/[^\d]/);
					nowStr = new Date().toJson().split(/[^\d]/)
					endTime = new Date(endStr[0], endStr[1], endStr[2]),
					nowTime = new Date(nowStr[0], nowStr[1], nowStr[2]),
					diffDay = Math.round((endTime.getTime() - nowTime.getTime())/(1000*60*60*24));

				if(diffDay > 10){
					if(confirm('淘宝离线托管还有['+diffDay+']天到期，是否确认续费？')) OfflineFee.show(source);
				}else{
					OfflineFee.show(source);
				}
			});
			
			triggerBtn.unbind('click').attr('onclick', '').click(function(){
				pur5.Pages.topMenuEvent(triggerBtn);
				self.layout();
			});
			
			loginBtn.click(function(){
				//Ds.Link(triggerBtn + '?' + windowId, windowId);
				MiniBrowser.openWindow('http://www.paipai.com');
			});
			
			
			
			submitBtn.click(function(){			
				PP.login(function(){
					PP.User.get(function(user){
						if(!user){
							Dialog.alert({
								style: {
									width: 180
								},
								title: '拍拍托管',
								content: '请先登录拍拍'
							});
							return false;
						}
						Dialog.hide();
						User = user;
						PP.Sp.init(User);
						
						PP.Api.getAccessToken(User.uin, function(app, errMsg){
							if(!app){
								Dialog.alert({
									style: {
										width: 180
									},
									title: '拍拍托管',
									content: '拍拍授权失败:' + errMsg
								});
								
								return false;
							}
							App = app;
							self.submit();
						});
					});					
				});
			});
			
			l('.whatIsOffline').click(function(){
				Dialog.alert({
					title: '什么是离线托管？',
					content: joinWithTag(['离线托管是指用户店铺对第五代平台授权后，由第五代平台在第五代服务器上帮用户自动处理订单实现发货、充值的功能。',
						'因为离线托管在第五代服务器上自动运行，所以只要托管成功（状态为“工作中”），即使用户关闭客户端软件（甚至关闭电脑），订单仍然能自动发货。',
						'当离线托管开启后，本地监控功能仍然可以正常使用，订单不会重复提交。'], '<p>', '</p>'),
					style: {
						width: 450
					}
				});
			});			
		},
		layout: function(){
			var self = this;

			if(!pur5.Cfg.pur5PassWordKey) {
				TradingPass.show(function(){
					pur5.Pages.setPur5PW2(true, function() {
						pur5.Pages.layoutTo(layout.attr('id'));
						self.getList();
					});
				});
			} else {
				pur5.Pages.layoutTo(layout.attr('id'));
				self.getList();
			}
		},
		stop: function(offlineId){
			var self = this;
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
				type: 'get',
				cache: false,
				data: {
					token: pur5.Cfg.token,
					lv: 't3',
					id: offlineId,
					source: source
				},
				success: function(Result){
					if(Result == '1') {
						list.find('td.offline_' + offlineId).parent().remove();
						self.getList();
					} else {
						alert('停止拍拍离线托管失败：' + Result);
					}
				},
				error: function(jqXhr){
					ajaxError('停止拍拍离线托管', jqXhr, textStatus);
				}
			});
		},
		getList: function(){
			this.getStatus();
			var self = this;
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
				cache: false,
				dataType: 'json',
				data: {
					token: pur5.Cfg.token,
					lv: 't2',
					source: source
				},
				success: function(OfflineList){
					list.children().remove();
					list.hide();
					var tmp = '<tr><td class="offline_Id">Number</td><td>开始：startTime<span><br />结束：endTime</span></td><td class="bluefont">states</td><td><a href="#" class="cancelOffline" value="Id" title="停止对店铺Number的离线托管">停止</a></td></tr>';
					$.each(OfflineList, function(index, offlineRow){
						
						offlineRow[1] = offlineRow[1].replace(/\b(\d)\b/g,'0$1');
						offlineRow[4] = offlineRow[4].replace(/\b(\d)\b/g,'0$1');
						list.append(
							tmp
								.replace(/Number/g, offlineRow[0])
								.replace(/startTime/g, offlineRow[1])
								.replace(/endTime/g, offlineRow[4])
								
								.replace(/states/g, offlineRow[3])
								.replace(/description/g, offlineRow[3])
								.replace(/Id/g, offlineRow[5])
						);
						
						if(!offlineRow[4]){
							list.find('tr:eq('+index+') span').hide();
						}
						if(/停止/.test(offlineRow[3])){
							list.find('tr').eq(index).find('.cancelOffline').hide();
						}
					});
					//list.find('.cancelOffline:contains("停止")').hide();
					list.show();
					
					list.find('a.cancelOffline').click(function(){
						if(!confirm($(this).attr('title') + '？')) return false;
						self.stop($(this).attr('value'));
					});

				},
				error: function(jqXhr, textStatus){
					ajaxError('读取拍拍离线托管列表', jqXhr, textStatus);
				}
			});
		},
		getStatus: function(){
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'offline/offlinePay.asp',
				dataType: 'json',
				data: {
					action: 'status',
					source: source,
					token: pur5.Cfg.token
				},
				success: function(Result){
					offlineEndTime.text(Result.values.endTime);
				},
				error: function(jqXhr, textStatus){
					ajaxError('读取拍拍离线托管缴费截止时间', jqXhr, textStatus);
				}
			});
		},
		submit: function(){
			var self = this;
			
			$.ajax({//托管
				url: Pur5.makeFullPath('offline/offline.asp'),
				type: 'post',
				cache: false,
				data: {
					version: pur5.Cfg.version,
					token: pur5.Cfg.token,
					lv: 't1',
					ww: User.uin,
					cookie: encodeURIComponent($.stringify($.extend(App, {
						uin: User.uin
					}))),
					source: source
				},
				success: function(Result){
					if(Result != '1'){
						alert('提交拍拍离线托管失败：\n' + Result);
						return false;
					};
					Dialog.tip('拍拍托管：托管成功！', 1000);
					self.getList();
				},
				error: function(jqXhr, textStatus){
					ajaxError('提交拍拍离线托管', jqXhr, textStatus);
				}
			});
		}
	}
})();

$(function(){
	$.include('scripts/', [
		'inc/function.js',
		'inc/pur5.js',
		'paipai/pp.js',
		'paipai/pp.sp.js',
		'paipai/pp.app.js'
	], function(){
		ppOfflineClient.init();
	});
});