var TaobaoOffline = (function(){
	var windowId = '' + new Date().getTime(),
		//Ds = new ActiveXObject('dsCookieGetter.ds'),
		loginUrl = 'https://login.taobao.com/member/login.jhtml',
		triggerBtn = $('#menuLXTG'),
		layout = $('#layoutTbApiOffline'),
		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 = '',
		wwId = '',
		source = 'taobao'
		cookies = '';
	
	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(loginUrl + '?' + windowId, windowId);
				Tb.Api.authorise(function(){
					if(!self.getCookies()) return false;
					self.submit();
				}, '开始托管[{1}]？');
			});
			
			submitBtn.click(function(){
				if(!self.getCookies()) return false;
				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, textStatus){
					ajaxError('停止淘宝离线托管', jqXhr, textStatus);
				}
			});
		},
		getList: function(){
			this.getStatus();
			var self = this;
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
				cache: false,
				dataType: 'json',
				timeout: 15000,
				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[4] = '';
						
						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, decodeURIComponent(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.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);
				}
			});
		},
		getCookies: function(){
			var callbackArg = Tb.Api.getArg();
			if(!callbackArg || !callbackArg.session){
				alert('授权失败，授权成功才能托管！');
				return false;
			}
			cookies = $.stringify({
				session: callbackArg.session,
				refresh_token: callbackArg.session,
				refresh_time: new Date().getTime()
			});
			shopNumber = callbackArg.userNickName;
			wwId = callbackArg.wwId;
			return true;
		},
		submit: function(){
			var self = this;

			$.ajax({//托管
				url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
				type: 'post',
				cache: false,
				data: {
					token: pur5.Cfg.token,
					lv: 't1',
					ww: encodeURIComponent(shopNumber),
					wwId: wwId,
					cookie: encodeURIComponent(cookies),
					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/', [
		'taobao/taobao.api.js'
	], function(){
		TaobaoOffline.init();
	});
});