/**
 * 设置交易全局配置项
 */
$.extend(pur5.Cfg, {
	TBcookies: '',                                     //登录taobao后监控的cookie
	GBTAOBAOLOG: false,                                //taobao登录状态，登录后为true
	taobaoUid: '',                                     //登录taobao后的uid
	GBstopTaobao: true,                                //是否暂停taobao监控，系统一开始未登录taobao前是true
	ReadTBOrdersInterval: null,                        //"淘宝监控"筛选符合发货条件的订单定时器
	ReadTBOrdersIntervalTime: 25000,                   //"淘宝监控"筛选符合发货条件的订单定时器时长
	TBOrders: [],                                      //"淘宝监控"等待发货的列表
	TBBlkOrders: [],                                   //"淘宝监控"黑名单列表
	TBComments: [],                                    //"淘宝监控"自动评价列表
	TBPreBlkFinish: true,                              //"淘宝监控"关闭上一个黑名单操作是否完成标记
	TBPreSendFinish: true,                             //"淘宝监控"发货时上一个商品是否发送完毕标记
	TBPreComFinish: true,                              //"淘宝监控"上一个评价操作是否完成标记
	TBSendOrdersInterval: null,                        //"淘宝监控"发货和关闭交易定时器
	TBSendOrdersIntervalTime: 4000,                    //"淘宝监控"发货和关闭交易定时器时长
	TBOrdersPage: 1,                                   //监控"淘宝"订单页的当前页码数
	TBBlkOrdersPage: 1,                                //监控"淘宝"待发货页的当前页码数
	TBCommentsPage: 1,                                 //监控"淘宝"待评价页的当前页码数
	TBMaxPages: 15,                                    //"淘宝监控"的最大页码数
	TBReDeliverInterval: null,                         //"淘宝监控"重新检查遗漏的未发货商品定时器
	TBReDeliverIntervalTime: 240000,                   //"淘宝监控"重新检查遗漏的未发货商品定时器时长
	TBRecordMax: 4000,                                 //"淘宝监控"记录文字最大长度
	TBOfflineMax: 1,                                   //taobao离线托管最大用户数
	TBJKWinId: '',                                     //taobao控件获取cookie前弹出窗口的id
	TBBlkListNameFile: 'controls/TBBlkN.pur5',         //taobao买家姓名黑名单本地FSO存储文件
	TBBlkListProFile: 'controls/TBBlkP.pur5',          //taobao商品名称黑名单本地FSO存储文件
	TBCommentsFile: 'controls/TBComm.pur5'             //taobao自动评价文字内容本地FSO存储文件
});

var TbNoOrderWarn = {//淘宝无单报警
	lastTimeGetDeal: 0,
	init: function(){
		$('#noOrderCheck').unbind('click').click(function(){
			if(this.checked) pur5.Cfg.lastTimeGetDeal = new Date().getTime();
			$('#noOrderWarnTime').attr('disabled', !this.checked);
		});
		$('#noOrderWarnTime').unbind('click').keyup(function(){
			if(this.value == '' || isNaN(this.value)){
				this.value = '30';
			}else{
				if(this.value < 1){
					this.value = 1;
				}
			}
		}).unbind('blur').blur(function(){
			$(this).trigger('keyup');
		})	
	},
	check: function(){
		if($('#noOrderCheck').attr('checked') && new Date()-this.lastTimeGetDeal >= $('#noOrderWarnTime').val()*60*1000){
			UI.pop('淘宝无单警告：在设置的时间'+$('#noOrderWarnTime').val()+'分钟内没有订单发生！');
			UI.play('media/error.wav');
		}
	}
};


/**
 * 设置"淘宝监控"的实时记录显示
 * @param {String} sMsg 登录日志信息
 */
pur5.Pages.setTBRecord = function(sMsg) {
	var layoutTBJKRecord = $('#layoutTBJKRecord')[0],
		p = document.createElement('p');
	try { p.innerHTML = sMsg; layoutTBJKRecord.insertBefore(p, layoutTBJKRecord.firstChild); } catch(e) {}
}


/**
 * 清除"淘宝监控"的实时记录显示
 */
pur5.Pages.clearTBRecord = function() {
	var layoutTBJKRecord = $('#layoutTBJKRecord');
	layoutTBJKRecord.html('');
}


/**
 * 淘宝监控时session超时重新设置交易密码
 */
pur5.Pages.tbInputAgainPur5PW2 = function() {
	if($('#inputTradingPass')[0].style.display != 'none') return;

	alert('session超时，请重新输入交易密码！');
	clearInterval(pur5.Cfg.ReadTBOrdersInterval);
	clearInterval(pur5.Cfg.TBSendOrdersInterval);
	pur5.Cfg.GBstopTaobao = true;
	
	TradingPass.show(function(){
		pur5.Pages.setPur5PW2(false, function() {
			pur5.Cfg.GBstopTaobao = false;
			pur5.Pages.runTBOrdersInterval();
			pur5.Pages.runTBSendOrdersInterval();
		});
	});
}


/**
 * 切换到"淘宝监控"事件
 */
pur5.Pages.switchToTBJK = function() {
	$('#layoutTBJKUserNo').html(pur5.Cfg.pur5Uid);
	if(!pur5.Cfg.pur5PassWordKey) {
		TradingPass.show(function(){
			pur5.Pages.setPur5PW2(true, function() {
				pur5.Pages.layoutTo('layoutTbJk');
			});
		});
	} else {
		pur5.Pages.layoutTo('layoutTbJk');
	}
}


/**
 * 切换到"离线托管"事件
 */
pur5.Pages.switchToLXTG = function() {
	var offlineTBUser = $('#offlineTBUser'),
		offlineTBLastTime = $('#offlineTBLastTime'),
		offlineTBResult = $('#offlineTBResult'),
		tds = offlineTBResult.find('td'),
		startText = '正在监控',
		stopText = '停止监控',
		fnInit = function() {
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
				type: 'get',
				cache: false,
				data: {
					token: pur5.Cfg.token,
					lv: 't2',
					source: 'taobao'
				},
				success: function(data){
					try {
						var arr = $.parseJSON(data), html = '';
						if(arr.length == 0) { alert('离线托管未开启，或已关闭，请重新启用'); return; }
						for(var i = 0, l = arr.length; i < l; i++) {
							html += '<tr><td>' + pur5.Cfg.pur5Uid + '</td><td>' + decodeURIComponent(arr[i][0]) + '</td><td>' + arr[i][1].replace(/\s+/g, '<br />') + '</td><td>' + arr[i][3] + '</td></tr>';
						}
						offlineTBResult.html(html);
						offlineTBUser.html(decodeURI(arr[0][0]));//20100530 xz
						offlineTBLastTime.html(arr[0][1]);
						
						var state = arr[0][2];
						if(state == 1)
							state = 0;
						else
							state = 1;
						$('input[name="offlineTBIsStart"]').eq(state).attr('checked', false).siblings().attr('checked', true);
					} catch(e) {
						alert('返回数据格式不对！');
					}
				},
				error: function(jqXhr, textStatus){
					alert('托管状态获取失败');
				}
			});
		};

	if(!pur5.Cfg.pur5PassWordKey) {//修改 增加交易密码输入 20110530 xz
		TradingPass.show(function(){
			pur5.Pages.setPur5PW2(true, function() {
				pur5.Pages.layoutTo('layoutTbTg');
				fnInit();
			});
		});
	} else {
		pur5.Pages.layoutTo('layoutTbTg');
		fnInit();
	}
}


/**
 * 设置"淘宝"启用买家黑名单的关联控制
 * @param {String} target 目标字符串
 * @param {Boolean} bConditions 判断条件
 */
pur5.Pages.getTaobaoBlacklist = function(sTarget, bConditions) {
	var arrResult = [];
	if(bConditions) {
		arrResult = sTarget.formatComma().split(',');
	}
	return arrResult;
}


/**
 * 分析淘宝"发货列表页"order_list_new.htm的HTML代码
 * @param {String} sHtml httpCookiePost请求淘宝order_list_new.htm返回回来的html代码
 */
pur5.Pages.readTBDeliveryOrders = function(sHtml) {
	if(sHtml == '') { pur5.Cfg.TBPreSendFinish = true; return; }

 	var a = sHtml.split('<tr class="order-title">'),
		sn, tborderid, tborder,
 		str = '',
 		str1 = '',
 		neworder = false,
		//订单编号
		orderId = 0,
		//买家帐号名
		buyerName = '',
		//商品名称
		goodsName = '',
		//购买某商品数量
		howMany = 0,
		isInBlack = false,
		blackListID = $('#tbBlackListID')[0],
		blackListIDON = $('#tbBlackListIDON')[0],
		autoCloseOrderTitle = $('#tbAutoCloseOrderTitle')[0],
		autoCloseOrder = $('#tbAutoCloseOrder')[0],
		autoCloseAll = $('#tbAutoCloseAll')[0],
		tbBkUsersList = pur5.Pages.getTaobaoBlacklist(blackListID.value, blackListIDON.checked && blackListID.value != ''),
		tbBkGoodsList = pur5.Pages.getTaobaoBlacklist(autoCloseOrderTitle.value, autoCloseOrder.checked && autoCloseOrderTitle.value != '' && !autoCloseAll.checked);
 	for(var i = 1, l = a.length; i < l; i++) {
		isInBlack = false;
		sn = a[i].between('<li class="desc" title="', '">').trim()
		
		if(sn == '') {
		 	sn = a[i].between('hidden', 'total');
		 	sn = a[i].between('商家编码：', '\r\n').trim();
		}
		
		if(sn.left(8).toUpperCase() == 'PUR5.COM') {
		//if((!isNaN(sn) && sn != '') || sn.left(8).toUpperCase() == 'PUR5.COM') {
			if(!isNaN(sn)){
				if(sn >= 10 && sn <= 20){
				} else {
					continue;
				}
			}
			
			orderId = a[i].between('<span class="order-number">订单编号：', '</span>'),
			buyerName = a[i].between('<span class="ww ww:token" ww:params="nick=', '&amp;tnick='),
			goodsName = a[i].between('<a target="_blank" title="名称：', ' §数量：'),
			howMany = a[i].between(' §数量：', '件"');
			
			//淘宝买家姓名黑名单过滤
			if(blackListIDON.checked && tbBkUsersList.length > 0) {
				for(var j = 0, jL = tbBkUsersList.length; j < jL; j++) {
					if(buyerName == tbBkUsersList[j]) {
						isInBlack = true;
						break;
					}
				}
				
				if(isInBlack) continue;
			}
			
			//商品数量与商品关键字黑名单过滤
			if(autoCloseOrder.checked && howMany > 1) {
				if(autoCloseAll.checked) {
					continue;
				} else {
					if(tbBkGoodsList.length > 0) {
						for(j = 0, jL = tbBkGoodsList.length; j < jL; j++) {
							if(goodsName.indexOf(tbBkGoodsList[j]) > 0) {
								isInBlack = true;
								break;
							}
						}
						
						if(isInBlack) continue;
					}
				}
			}
			
			//pur5.Pages.setTBRecord('编码:' + sn);
			str = '';
			str1 = a[i].between('order_id=', '">').replace('order_id=', '');
			tborderid = str1.replace('">', '').split('&cdtoken=')[0];
		
			
			str1 = a[i];
			tborder = str1.between('<span class="order-number">订单编号：', '</span>');

			str += '平台账号' + String.fromCharCode(11) + pur5.Cfg.pur5Uid + String.fromCharCode(12)
							+ '商家编码' + String.fromCharCode(11) + sn + String.fromCharCode(12)
							+ '淘宝订单号' + String.fromCharCode(11) + tborder + String.fromCharCode(12)
							+ '淘宝序号' + String.fromCharCode(11) + tborderid + String.fromCharCode(12)
							+ '淘宝状态' + String.fromCharCode(11) + '买家已付款' + String.fromCharCode(12);
		
			neworder = true;
			
			//将符合发货条件的订单统一放到pur5.Cfg.TBOrders里
			if(pur5.Cfg.TBOrders.length > 50) pur5.Cfg.TBOrders = pur5.Cfg.TBOrders.slice(0, 50);
			pur5.Cfg.TBOrders.$push([tborderid, tborder, str, sn], 0);
		}
	}
	if(!pur5.Cfg.TBOrders.length) pur5.Pages.setTBRecord('当前没有符合发货条件的宝贝 ' + pur5.Pages.getTime('2'));
}


/**
 * "淘宝"发货定时器、关闭黑名单交易定时器、自动评价定时器运行函数
 */
pur5.Pages.runTBSendOrdersInterval = function() {
	clearInterval(pur5.Cfg.TBSendOrdersInterval);
	TbNoOrderWarn.lastTimeGetDeal = new Date().getTime();
	pur5.Cfg.TBSendOrdersInterval = setInterval(function() {
		TbNoOrderWarn.check();
		var arr = pur5.Cfg.TBOrders.shift(),
			arrBlk = pur5.Cfg.TBBlkOrders.shift(),
			arrCom = pur5.Cfg.TBComments.shift();
		if(arr && pur5.Cfg.TBPreSendFinish) pur5.Pages.prepareForTBDeliver(arr[0], arr[1], arr[2], arr[3]);
		if(arrBlk && pur5.Cfg.TBPreBlkFinish) pur5.Pages.closeTBTransaction(arrBlk[0], arrBlk[1]);
		if(arrCom && pur5.Cfg.TBPreComFinish) pur5.Pages.todoTBComments(arrCom[0]);
	}, pur5.Cfg.TBSendOrdersIntervalTime);
}


/**
 * 淘宝"发货列表页"order_list_new.htm自动发货前的检查准备
 * @param {Number} nTborderid 淘宝序号
 * @param {Number} nTborder 淘宝订单号
 * @param {String} sStr 当前用户信息字符串值
 * @param {Number} nSn 商家编码
 */
pur5.Pages.prepareForTBDeliver = function(nTborderid, nTborder, sStr, nSn) {
	var spt1 = String.fromCharCode(11), spt2 = String.fromCharCode(12),
		step2 = function(a) {
			if(a == '' || a == 'ErrorKey') { pur5.Cfg.TBPreSendFinish = true; return; }
			if(a == 'SessionLost') { pur5.Pages.tbInputAgainPur5PW2(); return; }
			
			tborderid = sStr.between('淘宝序号' + spt1, spt2).split('&cdtoken=')[0],
			tborder = sStr.between('淘宝订单号' + spt1, spt2);
			if(a == tborder) {
				pur5.Cfg.err.mark1 = false;
			} else {
				pur5.Pages.setTBRecord('未保存成功');
				pur5.Cfg.TBPreSendFinish = true;
				
				///临时增加的，将出现"未保存成功"文字时存trading表的str和ajax返回的数据a存起来，方便将来从用户那拿过来分析
				if(!pur5.Cfg.err.mark1) {
					$.ajax({
						url: pur5.Cfg.GBHOSTSOFT + 'softerror/softerror.asp',
						type: 'POST',
						cache: false,
						data: {lv: 't1', page: 'hta'.$$$(), message: '[' + pur5.Cfg.GBHOST + ']' + '出现"未保存成功"文字时存trading表的str和ajax返回的数据a'.$$$(), content: 'str:\n' + sStr.replace(new RegExp(spt1, 'g'), '\r').replace(new RegExp(spt2, 'g'), '\n').$$$() + '\na:\n' + a, q: (new Date()).getTime() + Math.random()},
						success: function(a) {
							pur5.Pages.setTBRecord("提交失败信息成功！");
						},
						error: function() {
							pur5.Pages.setTBRecord("提交失败信息未成功！");
						}
					});
					pur5.Cfg.err.mark1 = true;
				}
				return;
			}
			
			pur5.Pages.setTBRecord('保存成功');
			
			if(!pur5.Pages.getProDetail(sStr)) {
				pur5.Pages.setTBRecord('分析订单' + tborderid + '详情页内容不满足发货条件!!');
				pur5.Cfg.TBPreSendFinish = true;
				return;
			}
			
			var ds1 = pur5.Cfg.Ds,
				ret0 = ds1.httpCookiePost('http://wuliu.taobao.com/user/consign_dummy.htm?order_id=' + tborderid, pur5.Cfg.TBcookies, 1, '', '.taobao.com', '');
			pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");
			if(ret0 == '') { pur5.Pages.setTBRecord('检查物流'); };
			if(ret0.search('这笔订单不是无需物流的订单')	>	0) {
				ret0 = ds1.httpCookiePost('http://wuliu.taobao.com/user/consign.htm?order_id=' + tborderid, pur5.Cfg.TBcookies, 1, '', '.taobao.com', '');
				pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");
				pur5.Pages.setTBRecord("不是非物流");
				pur5.Pages.tbDeliver(ret0, sStr, true);
				ret0 = null;
				return;
			}
			pur5.Pages.tbDeliver(ret0, sStr, false);
			ret0 = null;
		};

	pur5.Cfg.TBPreSendFinish = false;
	
	pur5.Pages.setTBRecord('编码:' + nSn);
	pur5.Pages.setTBRecord('正在保存' + nTborder);
	TbNoOrderWarn.lastTimeGetDeal = new Date().getTime();
	//先将该条记录存到服务器trading表中，再开始发货
	$.ajax({
		url: pur5.Cfg.GBHOSTSOFT + 'taobao.asp',
		type: 'POST',
		cache: false,
		data: {tborderid: nTborder, token: pur5.Cfg.token, str: sStr.replace(new RegExp(spt1, 'g'), '\r').replace(new RegExp(spt2, 'g'), '\n').$$$(), lv: 't1', ls: pur5.Cfg.pur5PassWordKey, q: (new Date()).getTime() + Math.random()},
		success: step2,
		error: function() {
			pur5.Cfg.TBPreSendFinish = true;
			///pur5.Pages.setTBRecord('请求服务器trading表失败！');
		}
	});
}


/**
 * 获取某订单的详情信息
 * @param {String} sStr 之前拼接起来的用户表单键值对信息字符串
 */
pur5.Pages.getProDetail = function(sStr) {
	var ds1 = pur5.Cfg.Ds,
		str = sStr,
		spt1 = String.fromCharCode(11),
		spt2 = String.fromCharCode(12),
		sOrderId = str.between('淘宝订单号' + spt1, spt2),
		a = ds1.httpCookiePost('http://trade.taobao.com/trade/detail/trade_item_detail.htm?bizOrderId=' + sOrderId, pur5.Cfg.TBcookies, 1, '', '.taobao.com', '');
	pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");

	a = a.replace(/[\r\n]/gm, '').replace(/>\s*(.*?)\s*</g, '>$1<');

	var _orderNum = a.between('order-num">', '</'),
		_alilayNum = a.between('<span class="alilay-num">', '</'),
		_waitStatus = a.between('class="wait">', '</'),
		_price = a.between('<td class="price">', '</'),
		_count = a.between('<td class="num">', '</td><td class="discount">'),
		_totalPrice = a.between('<td class="order-price" rowspan="1">', '<').trim(),//xz 0718 促销信息bug
		_postFee = a.between('<td class="post-fee" rowspan="1"><span>', '</'),
		_getMoney = a.between('实收款：<strong>', '</'),
		_tradeTime = a.between('<span class="trade-time">', '</'),
		_payTime = a.between('<span class="pay-time">', '</'),
		_status = a.between('<td class="status">', '</');

	if(
		a == ''
		|| a.indexOf('class="nickname">') == -1
		|| (_orderNum == -1 || isNaN(_orderNum))
		|| (_price == -1 || isNaN(_price))
		|| (_count == -1 || isNaN(_count))
		|| (_totalPrice == -1 || isNaN(_totalPrice))
		|| (_postFee == -1 || isNaN(_postFee))
		|| (_getMoney == -1 || isNaN(_getMoney))
		|| (_alilayNum == -1 || isNaN(_alilayNum))
		|| (_waitStatus == -1)
		|| (_totalPrice == -1 || isNaN(_totalPrice))
		|| !/\d{4}-\d{1,2}-\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2}/.test(_tradeTime)
		|| !/\d{4}-\d{1,2}-\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2}/.test(_payTime)
	) {		
		///临时增加的，将订单详情页html代码不合法的情况下，对应的html代码先存起来，方便将来从用户那拿过来分析
		if(!pur5.Cfg.err.mark6) {
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'softerror/softerror.asp',
				type: 'POST',
				cache: false,
				data: {lv: 't1', page: 'hta'.$$$(), message: '[' + pur5.Cfg.GBHOST + ']' + '订单详情页html代码不合法'.$$$(), content: (pur5.Cfg.token + '\n' + a).$$$(), q: (new Date()).getTime() + Math.random()},
				success: function(a) {
					pur5.Pages.setTBRecord("提交失败信息成功！");
				},
				error: function() {
					pur5.Pages.setTBRecord("提交失败信息未成功！");
				}
			});
			pur5.Cfg.err.mark6 = true;
		}
		
		ds1 = a = null;
		return '';
	}

	str += [
		"旺旺" , spt1 , pur5.Cfg.taobaoUid , spt2,
		"昵称" , spt1 , a.between('class="nickname">', '</') , spt2,
		"姓名" , spt1 , a.between('真实姓名：<span class="name">', '</') , spt2,
		"地区" , spt1 , a.between('class="city">', '</') , spt2,
		"电话" , spt1 , a.between('class="tel" >', '</') , spt2,
		"宝贝名称" , spt1 , a.between('<span class="name"><a', '</a').split('>')[1] , spt2
	].join('');

	if(a.between('<td class="sku">', '</td>') != '-') {
		str += ["宝贝属性" , spt1 , a.between('<td class="sku">', '</td>') , spt2].join('');
	}
	
	///临时增加的，将数量夸张和没有收货地址的单的html代码先存起来，方便将来从用户那拿过来分析
	if(a.indexOf('<th>收货地址：</th>') != -1) {
		pur5.Cfg.err.mark2 = false;
	} else {
		if(!pur5.Cfg.err.mark2) {
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'softerror/softerror.asp',
				type: 'POST',
				cache: false,
				data: {lv: 't1', page: 'hta'.$$$(), message: '[' + pur5.Cfg.GBHOST + ']' + '没有收货地址或收货地址有问号等乱码'.$$$(), content: a.$$$(), q: (new Date()).getTime() + Math.random()},
				success: function(a) {
					pur5.Pages.setTBRecord("提交失败信息成功！");
				},
				error: function() {
					pur5.Pages.setTBRecord("提交失败信息未成功！");
				}
			});
			pur5.Cfg.err.mark2 = true;
		}
	}

	str += [
		"单价" , spt1 , _price , spt2,
		"数量" , spt1 , _count , spt2,
		"优惠" , spt1 , a.between('<td class="discount">', '</td>').replace(/<.*?>/g, '') , spt2,
		"商品总价" , spt1 , _totalPrice , spt2,
		"运费" , spt1 , _postFee , spt2,
		"实收款" , spt1 , _getMoney , spt2,
		"支付宝单号" , spt1 , _alilayNum , spt2,
		"成交时间" , spt1 , _tradeTime , spt2,
		"付款时间" , spt1 , _payTime , spt2
	].join('');
	
	//if(a.indexOf('<table class="simple-list logistics-info">') != -1) {
		if(a.indexOf('<th>收货地址：</th>') != -1) str += "收货地址" + spt1 + a.between('<th>收货地址：</th><td>', '</').replace(/[\s\u3000]+/g, ' ') + spt2;
		if(a.indexOf('<th>运送方式：</th>') != -1) str += "收货方式" + spt1 + a.between('<th>运送方式：</th><td>', '</').replace(/[\s\u3000]+/g, ' ') + spt2;
		if(a.indexOf('<th>买家留言：</th>') != -1) str += "留言" + spt1 + a.between('<th>买家留言：</th><td>', '</').replace(/[\s\u3000]+/g, ' ') + spt2;
		if(a.indexOf('<th>附加信息：</th>') != -1) str += "附加信息" + spt1 + a.between('<th>附加信息：</th><td>', '</').replace(/[\s\u3000]+/g, ' ') + spt2;
	//}
	str = str.replace(new RegExp('淘宝状态' + spt1 + '买家已付款' + spt2, 'gi'), '淘宝状态' + spt1 + _status + spt2).replace(new RegExp('&nbsp;|&nbsp', 'gi'), '');
	ds1 = a = null;
	return str;
}


/**
 * 淘宝发货
 * @param {String} sRet httpCookiePost到淘宝的consign_dummy.htm页面后返回的内容
 * @param {String} sStr 当前用户信息字符串值
 * @param {Boolean} bLogistics 物流类型，false或空为原版本的"Deliver3",即无需物流；true为原版本的"Deliver35",即需要物流
 */
pur5.Pages.tbDeliver = function(sRet, sStr, bLogistics) {
	if(sRet == '' || sRet.indexOf('>首页<') != -1) {
		///临时增加的，将出现"保存成功"后就没下文的情况下抓到的html代码，post到服务器先存起来，方便将来从用户那拿过来分析
		if(!pur5.Cfg.err.mark7) {
			$.ajax({
				url: pur5.Cfg.GBHOSTSOFT + 'softerror/softerror.asp',
				type: 'POST',
				cache: false,
				data: {lv: 't1', page: 'hta'.$$$(), message: '[' + pur5.Cfg.GBHOST + ']' + '出现"保存成功"后就没下文的情况下抓到的html（http://wuliu.taobao.com/user/consign_dummy.htm?order_id=）代码'.$$$(), content: (pur5.Cfg.token + '\n' + sRet).$$$(), q: (new Date()).getTime() + Math.random()},
				success: function(a) {
					pur5.Pages.setTBRecord("提交信息成功！");
				},
				error: function() {
					pur5.Pages.setTBRecord("提交信息未成功！");
				}
			});
			pur5.Cfg.err.mark7 = true;
		}
			
		pur5.Cfg.TBPreSendFinish = true;
		return;
	}
	
	var ds1 = pur5.Cfg.Ds,
		tborderid = sStr.between('淘宝序号' + String.fromCharCode(11), String.fromCharCode(12));
	sRet = sRet.between('<form id="orderForm"', '</form>');
	if(sRet == '') {
		if(!bLogistics) {
			pur5.Pages.setTBRecord('noform');
		}
		pur5.Cfg.TBPreSendFinish = true;
		return;
	}	

	var x = '', xObj = sRet.getUrlHash();
	for(var p in xObj) {
		switch(p) {
			case 'event_submit_do_dummy':
				x += p + '=' + 'anything' + '&';
				break;
			case '_fmw.n._0.g':
				x += p + '=' + 'new' + (!bLogistics ? '' : '2') + '&';
				break;
			case 'action':
				x += p + '=' + (!bLogistics ? 'user%2Fconsign_action' : xObj[p]) + '&';
				break;
			default:
				x += p + '=' + xObj[p] + '&';
		}
	}
	x = x.substr(0, x.length - 1);
	
	pur5.Pages.setTBRecord('准备发货');
	
	if(!pur5.Pages.getProDetail(sStr)) {
		var tborderid2 = sStr.between('淘宝订单号' + String.fromCharCode(11), String.fromCharCode(12));
		pur5.Pages.setTBRecord('分析订单' + tborderid2 + '详情页内容不满足发货条件!');
		pur5.Cfg.TBPreSendFinish = true;
		return;
	}	
	
	//真正发货请求，调试时请记得注释掉或者在之前return掉
	var ret0 = ds1.httpCookiePost(
		'http://wuliu.taobao.com/user/'
		+ (!bLogistics ? 'consign_dummy.htm' : 'consign.htm')
		+ '?order_id=' + tborderid, pur5.Cfg.TBcookies, 1, x, '', '');
	pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");
	if(ret0.indexOf('恭喜您，操作成功') == -1) {
		if(ret0.indexOf('交易订单详情') == -1) {
			pur5.Pages.setTBRecord('发货未成功');
		} else {
			pur5.Pages.setTBRecord('订单' + tborderid + '在别处已发货');
		}
		pur5.Cfg.TBPreSendFinish = true;
		ret0 = null;
		return;
	}
	pur5.Pages.setTBRecord('发货方式' + (!bLogistics ? '1' : '2'));

	pur5.Pages.tbDeliverOK(ret0, sStr);
	ret0 = null;
}


/**
 * 淘宝"发货列表页"order_list_new.htm自动发货完成后收尾与把记录提交到pur5服务器
 * @param {String} sRet httpCookiePost到淘宝的consign_dummy.htm页面后返回的内容
 * @param {String} sStr 拼接起来的用户表单键值对信息字符串
 */
pur5.Pages.tbDeliverOK = function(sRet, sStr) {
	var tborder = sStr.between('淘宝订单号' + String.fromCharCode(11), String.fromCharCode(12));
	pur5.Pages.setTBRecord("发货成功，发货已返回信息");
	if(sRet.search('恭喜您，操作成功') >= 0) {
		pur5.Pages.tbProDetail(sRet, sStr, tborder);
	} else {
		pur5.Cfg.TBPreSendFinish = true;
		//发货失败
	}
}


/**
 * 淘宝自动发货完成后获取订单信息
 * @param {String} sRet httpCookiePost到淘宝的consign_dummy.htm页面后返回的内容
 * @param {String} sStr 拼接起来的用户表单键值对信息字符串
 * @param {String} sOrderId 订单编号
 * @param {Boolean} bIsFromTrad 是否从复查trading表那边过来的，缺省时为否
 */
pur5.Pages.tbProDetail = function(sRet, sStr, sOrderId, bIsFromTrad) {
	var _key = !bIsFromTrad ? '恭喜您，操作成功' : '订单编号';
	if(sRet == '' || sRet.indexOf(_key) == -1) { if(!bIsFromTrad) { pur5.Cfg.TBPreSendFinish = true; } return; }
	pur5.Pages.setTBRecord('准备提交订单');
	
	var str = pur5.Pages.getProDetail(sStr);
	if(!str) {
		pur5.Pages.setTBRecord('分析订单' + sOrderId + '详情页内容不满足发货条件!!!');
		if(!bIsFromTrad) pur5.Cfg.TBPreSendFinish = true;
		return;
	}
	
	pur5.Pages.setTBRecord("已经获取订单信息");	
	pur5.Pages.tbSendToServer(str, bIsFromTrad ? true : false);
}


/**
 * 淘宝自动发货完成后获取订单信息发送到pur5服务器保存
 * @param {String} sStr 上一步拼接起来的用户成交订单信息
 * @param {Boolean} bIsFromTrad 是否从复查trading表那边过来的，缺省时为否
 */
pur5.Pages.tbSendToServer = function(sStr, bIsFromTrad) {
	var spt1 = String.fromCharCode(11),
		spt2 = String.fromCharCode(12),
		statusHash = {
			st1: ['未确认收货', '卖家已发货'],
			st2: ['已确认收货', '交易成功'] 
		},
		status = sStr.between('淘宝状态' + spt1, spt2);
	if(sStr.between('平台账号' + spt1, spt2) != pur5.Cfg.pur5Uid) { pur5.Pages.setTBRecord("平台账号不匹配"); if(!bIsFromTrad) { pur5.Cfg.TBPreSendFinish = true; } return; }
	if(sStr.between('旺旺' + spt1, spt2) != pur5.Cfg.taobaoUid) { pur5.Pages.setTBRecord("旺旺不匹配"); if(!bIsFromTrad) { pur5.Cfg.TBPreSendFinish = true; } return; }
	if(status == statusHash.st1[0]) {
		sStr = sStr.replace(new RegExp('淘宝状态' + spt1 + statusHash.st1[0] + spt2, 'gi'), '淘宝状态' + spt1 + statusHash.st1[1] + spt2);
	} else if(status == statusHash.st2[0]) {
		sStr = sStr.replace(new RegExp('淘宝状态' + spt1 + statusHash.st2[0] + spt2, 'gi'), '淘宝状态' + spt1 + statusHash.st2[1] + spt2);
	} else {
		//pur5.Pages.setTBRecord("订单状态不匹配：" + status);
		if(!bIsFromTrad) { pur5.Cfg.TBPreSendFinish = true; } return;
	}
	
	pur5.Pages.setTBRecord("准备发送");

	$.ajax({
		url: pur5.Cfg.GBHOSTSOFT + 'taobao.asp',
		type: 'POST',
		cache: false,
		data: {token: pur5.Cfg.token, Text: sStr.replace(new RegExp(spt1, 'g'), '\r').replace(new RegExp(spt2, 'g'), '\n').$$$(), lv: 't2', ls: pur5.Cfg.pur5PassWordKey, q: (new Date()).getTime() + Math.random()},
		success: function(a) {
			pur5.Pages.setTBRecord("检查网络");
			if(a == '' || a == 'ErrorKey') { pur5.Cfg.TBPreSendFinish = true; return; }
			if(a == 'SessionLost') { pur5.Pages.tbInputAgainPur5PW2(); pur5.Cfg.TBPreSendFinish = true; return; }
			if(!bIsFromTrad) { pur5.Cfg.TBPreSendFinish = true; }
			pur5.Pages.setTBRecord("提交完毕！");
			
			pur5.Cfg.err.mark3 = false;
		},
		error: function() {
			if(!bIsFromTrad) { pur5.Cfg.TBPreSendFinish = true; }
			pur5.Pages.setTBRecord('网络错误。正在重试！');
			
			///临时增加的，将taobao已发了货但结果里没有该条记录的情况下，post到服务器的参数先存起来，方便将来从用户那拿过来分析
			if(!pur5.Cfg.err.mark3) {
				$.ajax({
					url: pur5.Cfg.GBHOSTSOFT + 'softerror/softerror.asp',
					type: 'POST',
					cache: false,
					data: {lv: 't1', page: 'hta'.$$$(), message: '[' + pur5.Cfg.GBHOST + ']' + 'taobao已发了货但结果里没有该条记录'.$$$(), content: (pur5.Cfg.token + '\n' + sStr.replace(new RegExp(spt1, 'g'), '\r').replace(new RegExp(spt2, 'g'), '\n')).$$$(), q: (new Date()).getTime() + Math.random()},
					success: function(a) {
						pur5.Pages.setTBRecord("提交失败信息成功！");
					},
					error: function() {
						pur5.Pages.setTBRecord("提交失败信息未成功！");
					}
				});
				pur5.Cfg.err.mark3 = true;
			}
		}
	});
	
	return;
}


/**
 * 分析淘宝"等待买家付款列表"页面属性，实现按照黑名单关闭交易
 * @param {String} a ajax请求回来的html代码
 */
pur5.Pages.readTBTransaction = function(sHtml) {
	if(sHtml == '') { pur5.Cfg.TBPreBlkFinish = true; return; }

 	var a = sHtml.split('<tr class="order-hd">'),
		//订单编号
		orderId = 0,
		//买家帐号名
		buyerName = '',
		//交易类型，为200时是关闭交易
		bizType = 0,
		//商品名称
		goodsName = '',
		//购买某商品数量
		howMany = 0,
		blackListID = $('#tbBlackListID')[0],
		blackListIDON = $('#tbBlackListIDON')[0],
		autoCloseOrderTitle = $('#tbAutoCloseOrderTitle')[0],
		autoCloseOrder = $('#tbAutoCloseOrder')[0],
		autoCloseAll = $('#tbAutoCloseAll')[0],
		tbBkUsersList = pur5.Pages.getTaobaoBlacklist(blackListID.value, blackListIDON.checked && blackListID.value),
		tbBkGoodsList = pur5.Pages.getTaobaoBlacklist(autoCloseOrderTitle.value, autoCloseOrder.checked && autoCloseOrderTitle.value && !autoCloseAll.checked);
	
	if(a.length < 2) { pur5.Cfg.TBPreBlkFinish = true; return; }

 	for(var i = 1, l = a.length; i < l; i++) {
			
		orderId = a[i].between('<span class="order-num"><label for="cb', '">订单编号：'),
		buyerName = a[i].between('<span class="J_WangWang" data-nick="', '" data-display="inline"'),
		//bizType = a[i].between('&bizType=', '"'),
		bizType = a[i].between('&amp;biz_type=', '"'),
		goodsName = a[i].between('title="查看宝贝详情" target="_blank">', '</a>'),
		howMany = a[i].between('<td class="num" title="', '">');
		
		//淘宝买家姓名黑名单过滤
		if(blackListIDON.checked && tbBkUsersList.length) {
			for(var j = 0, jL = tbBkUsersList.length; j < jL; j++) {
				if(buyerName == tbBkUsersList[j]) {
					//alert(orderId + ' ' + buyerName + ' ' + bizType + ' ' + goodsName + ' ' +howMany)
					if(pur5.Cfg.TBBlkOrders.length > 50) pur5.Cfg.TBBlkOrders = pur5.Cfg.TBBlkOrders.slice(0, 50);
					pur5.Cfg.TBBlkOrders.$push([orderId, bizType], 0);
					break;
				}
			}
		}
		
		
		//商品数量与商品关键字黑名单过滤
		if(autoCloseOrder.checked && howMany > 1) {
			if(autoCloseAll.checked) {
				if(pur5.Cfg.TBBlkOrders.length > 50) pur5.Cfg.TBBlkOrders = pur5.Cfg.TBBlkOrders.slice(0, 50);
				pur5.Cfg.TBBlkOrders.$push([orderId, bizType], 0);
			} else {
				if(tbBkGoodsList.length) {
					for(var k = 0, kL = tbBkGoodsList.length; k < kL; k++) {
						if(goodsName.indexOf(tbBkGoodsList[k]) > 0) {
							if(pur5.Cfg.TBBlkOrders.length > 50) pur5.Cfg.TBBlkOrders = pur5.Cfg.TBBlkOrders.slice(0, 50);
							pur5.Cfg.TBBlkOrders.$push([orderId, bizType], 0);
							break;
						}
					}
				}
			}
		}

	}
}


/**
 * 关闭淘宝"等待买家付款列表"页中黑名单里存在的交易
 * @param {String} sOrderId 该条交易的orderId
 * @param {Number} nBizType 该条交易的bizType
 */
pur5.Pages.closeTBTransaction = function(sOrderId, nBizType) {
	var ds1 = pur5.Cfg.Ds,
		a = ds1.httpCookiePost('http://trade.taobao.com/trade/cancel_order.htm?biz_order_id=' + sOrderId + '&biz_type=' + nBizType, pur5.Cfg.TBcookies, 1, '', '.taobao.com', '');
	pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");

	if(a == '') { pur5.Cfg.TBPreBlkFinish = true; a = null; return; }
	pur5.Cfg.TBPreBlkFinish = false;
	var token = a.between("<input name='_tb_token_' type='hidden' value='", "'>"),
		bizType = a.between('<input type="hidden" name="bizType" value="', '" />'),
		bizOrderId = a.between('<input type="hidden" name="bizOrderId"  value="', '" />');
	pur5.Pages.setTBRecord('正在关闭订单：' + sOrderId);
	var x = '_tb_token_=' + token + '&'
		+ 'bizType=' + bizType + '&'
		+ 'bizOrderId=' + bizOrderId + '&'
		+ 'action=' + 'cancelOrderAction.htm' + '&'
		+ 'event_submit_do_cancel=' + '1' + '&'
		+ 'J_CloseReason=' + '%C6%E4%CB%FB%D4%AD%D2%F2';
	var b = ds1.httpCookiePost('http://trade.taobao.com/trade/cancel_order.htm?biz_order_id=' + sOrderId + '&biz_type=' + nBizType, pur5.Cfg.TBcookies, 1, x, '.taobao.com', '');
	pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");
	pur5.Cfg.TBPreBlkFinish = true;
	if(b == '') { a = b = null; return; }
	if(b.indexOf('SYSTEM_ERROR') != -1){
		pur5.Pages.setTBRecord('关闭订单：' + sOrderId + '失败！');
	}else{
		pur5.Pages.setTBRecord('关闭订单：' + sOrderId + '成功！');
	}
	a = b = null;
}


/**
 * 分析淘宝"等待评价列表"页面属性，实现自动评价
 * @param {String} a ajax请求回来的html代码
 */
pur5.Pages.readTBComments = function(sHtml) {
	if(sHtml == '') { pur5.Cfg.TBPreComFinish = true; return; }

 	var a = sHtml.split('<tr class="order-hd">'),
		tbAutoComments = $('#tbAutoComments'),
		//订单编号
		orderId = 0;
	
	if(a.length < 2) { pur5.Cfg.TBPreComFinish = true; return; }

 	for(var i = 1, l = a.length; i < l; i++) {
		orderId = a[i].between('<span class="order-num"><label for="cb', '">订单编号：');
		pur5.Cfg.TBComments.$push([orderId]);
	}
}


/**
 * “淘宝”自动评价
 * @param {String} sOrderId 该条交易的orderId
 */
pur5.Pages.todoTBComments = function(sOrderId) {
	var ds1 = pur5.Cfg.Ds,
		a = ds1.httpCookiePost('http://rate.taobao.com/remark_buyer.jhtml?tradeID=' + sOrderId, pur5.Cfg.TBcookies, 1, '', '.taobao.com', ''),
		tbAutoCommentsSel = $('#tbAutoCommentsSel'),
		tbAutoCommentsText = $('#tbAutoCommentsText');
	pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");

	if(a == '') { pur5.Cfg.TBPreComFinish = true; a = null; return; }
	pur5.Cfg.TBPreComFinish = false;
	
	try{
		var formStr = a.match(/(<form id="rateListForm"[^>]+>[\s\S]+?<\/form>)/)[1],
			vForm = $(formStr),
			args = {},
			tmp;
			
		vForm.find('input:hidden, textarea, input:text').each(function(){
			tmp = $(this);
			args[tmp.attr('name')] = tmp.val();
		});
		
		args['rateContents' + sOrderId] = tbAutoCommentsText.val().replace(/&/g, '+');
		args['rate-good-' + sOrderId] = 1;
		args['rates' + sOrderId] = 1;
		args['good-all'] = 'on';
		
		var tmp = [];
		$.each(args, function(key, value){
			tmp.push(key + '=' + value)
		});
		args = tmp.join('&');
	
		var b = ds1.httpCookiePost('http://rate.taobao.com/remarkBuyer.htm', pur5.Cfg.TBcookies, 1, args, '.taobao.com', '');
		pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");
		pur5.Cfg.TBPreComFinish = true;
		if(b == '') { a = b = null; return; }
		if(b.indexOf('<dl class="ok naked">信用评价成功') != -1) {
			pur5.Pages.setTBRecord('自动评价：' + sOrderId + '成功！');
		} else {
			pur5.Pages.setTBRecord('自动评价：' + sOrderId + '失败！');
		}
		a = b = null;
	}catch(e){}
}


/**
 * "淘宝监控"定时器调用函数
 */
pur5.Pages.doingReadTBOrders = function() {
	//document.title = Math.random();
	if(!pur5.Cfg.GBPUR5LOG || !pur5.Cfg.GBTAOBAOLOG || pur5.Cfg.GBstopTaobao) return;
	
	//定时清空监控记录
	var layoutTBJKRecord = $('#layoutTBJKRecord');
	if(layoutTBJKRecord[0].innerHTML.length >= pur5.Cfg.TBRecordMax) {
		layoutTBJKRecord[0].innerHTML = '';
	}
	
	//更新cookie
	/*var ds0 = pur5.Cfg.Ds,
		ret00 = ds0.httpCookiePost("http://member1.taobao.com/message/add_private_msg.htm", pur5.Cfg.TBcookies, 1, '', '', ''),
		ret0 = ds0.GetCookie(".taobao.com");
		//ret0 = ds0.httpCookiePost("http://member1.taobao.com/message/add_private_msg.htm", pur5.Cfg.TBcookies, 0, '', '', '');
	if(ret0.search("token") > 0) {
		pur5.Cfg.TBcookies = ret0;
		pur5.Pages.setTBRecord('保存旺旺');
	} else {
		pur5.Pages.setTBRecord('更新cookie失败！');
		ret00 = ret0 = null;
		return;
	}*/
	////不再需要单独更新cookie了
		
	var	tbAutoCloseOrder  = $('#tbAutoCloseOrder'),
		tbAutoCloseAll = $('#tbAutoCloseAll'),
		tbBlackListIDON = $('#tbBlackListIDON'),
		tbBlackListID = $('#tbBlackListID'),
		tbAutoCloseOrder = $('#tbAutoCloseOrder'),
		tbAutoCloseOrderTitle = $('#tbAutoCloseOrderTitle'),
		tbAutoComments = $('#tbAutoComments'),
		tbAutoCommentsSel = $('#tbAutoCommentsSel'),
		tbAutoCommentsText = $('#tbAutoCommentsText'),
		stepLen = Math.ceil(pur5.Cfg.ReadTBOrdersIntervalTime / pur5.Cfg.TBSendOrdersIntervalTime);
	
	var i = 0;		//发货递归次数
	if(!pur5.Cfg.TBOrders.length) pur5.Cfg.TBOrdersPage = 1;
	(function() {
		if(pur5.Cfg.GBstopTaobao) return;
		var ds1 = pur5.Cfg.Ds,
			ret = ds1.httpCookiePost('http://wuliu.taobao.com/user/order_list_new.htm?currentPage='
									+ pur5.Cfg.TBOrdersPage
									+ '&orderStatusShow=send',
									pur5.Cfg.TBcookies,
									1,
									'',
									'.taobao.com',
									'');
		pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");
		
		if(!ret) { pur5.Pages.setTBRecord('网络中途掉线，请检查网络!'); ret = null; return; }
		if(ret == '网络异常') { pur5.Pages.setTBRecord('网络异常'); ret = null; return; }
		//如果频率过快taobao网主动跳转到网站首页或进不到待发货列表页
		//if(ret.indexOf('>首页<') != -1) { pur5.Pages.setTBRecord('频率过高跳转到淘宝首页！'); ret = null; return; }
		if(ret.indexOf('<span>首页</span>') != -1) { pur5.Pages.setTBRecord('频率过高跳转到淘宝首页！'); ret = null; return; }
		
		if(ret.indexOf('<form id="J_DynamicForm" action="https://login.taobao.com/member/login.jhtml" method="post">') != -1){//抓到登录超时: 20110530 xz
			pur5.Pages.setTBRecord('淘宝登录超时，需要重新登录');
			pur5.Pages.reportErrorToServer({
				lv: 't1',
				page: 'hta'.$$$(),
				message: '[' + pur5.Cfg.GBHOST + ']' + '登录超时http://wuliu.taobao.com/user/order_list_new.htm'.$$$(),
				content: ret.$$$(), 
				q: (new Date()).getTime() + Math.random()
			});
			ret = null; return;
		}
		
		//mark5 抓到广告
		pur5.Cfg.err.mark5 = false;
		if(/^<script/.test(ret)){//抓到广告：20110530 xz
			pur5.Pages.setTBRecord('抓取到广告，放弃本次操作!');
			pur5.Pages.setTBRecord('如多次抓取到广告，请联系宽带提供商!');
			pur5.Cfg.err.mark5 = true;
			
			pur5.Pages.reportErrorToServer({
				lv: 't1',
				page: 'hta'.$$$(),
				message: '[' + pur5.Cfg.GBHOST + ']' + '抓到广告http://wuliu.taobao.com/user/order_list_new.htm'.$$$(),
				content: ret.$$$(), 
				q: (new Date()).getTime() + Math.random()
			});
			ret = null; return;
		}//广告处理结束
		
		
		if(ret.indexOf('等待发货的订单') != -1) {
			pur5.Cfg.err.mark4 = false;
		} else {
			pur5.Pages.setTBRecord('待发货列表页为空！');
			
			///临时增加的，将抓取待发货列表页html先存起来，方便将来从用户那拿过来分析
			if(!pur5.Cfg.err.mark4) {
				pur5.Pages.reportErrorToServer({
					lv: 't1',
					page: 'hta'.$$$(),
					message: '[' + pur5.Cfg.GBHOST + ']' + '待发货列表页为空http://wuliu.taobao.com/user/order_list_new.htm'.$$$(),
					content: ret.$$$(),
					q: (new Date()).getTime() + Math.random()
				});
				pur5.Cfg.err.mark4 = true;
			}
			ret = null; return;
		}
		
		if(ret.indexOf('<span class="order-number">订单编号') == -1) {
			if(!pur5.Cfg.TBOrders.length) pur5.Pages.setTBRecord('当前没有需要发货的宝贝 ' + pur5.Pages.getTime('2'));
			ret = null;
			return;
		}
		//如果找不到当前页码说明不存在分页器，此时只有一页
		if(ret.indexOf('<span class="page-cur">') == -1) {
			pur5.Pages.readTBDeliveryOrders(ret);
			ret = null;
			return;
		} else {
			if(ret.between('<span class="page-cur">', '</') == pur5.Cfg.TBOrdersPage
				&& pur5.Cfg.TBOrdersPage <= pur5.Cfg.TBMaxPages
				&& pur5.Cfg.TBOrders.length < stepLen
				&& i < stepLen
			) {
				pur5.Pages.readTBDeliveryOrders(ret);
				pur5.Cfg.TBOrdersPage++;
				i++;
				arguments.callee();
			} else {
				ret = null;
				return;
			}
		}
	})();
	
	var j = 0;		//关闭交易递归次数
	if(!pur5.Cfg.TBBlkOrders.length) pur5.Cfg.TBBlkOrdersPage = 1;
	(function() {
		if(pur5.Cfg.GBstopTaobao) return;
		//只有启用"姓名黑名单"、"最大数量产品关键字限制黑名单"、"最大数量全部限制黑名单"功能中的一个，才检查
		if((tbBlackListIDON[0].checked && tbBlackListID.val() != '') || (tbAutoCloseOrder[0].checked && (tbAutoCloseOrderTitle.val() != '' || tbAutoCloseAll[0].checked))) {
			var ds2 = pur5.Cfg.Ds,
				ret2 = ds2.httpCookiePost('http://trade.taobao.com/trade/itemlist/list_sold_items.htm?event_submit_do_query=1&user_type=1&_fmt.q._0.au=NOT_PAID&action=itemlist/QueryAction&pageNum=' + pur5.Cfg.TBBlkOrdersPage, pur5.Cfg.TBcookies, 1, '', '.taobao.com', '');
			pur5.Cfg.TBcookies = ds2.GetCookie(".taobao.com");
			
			//如果频率过快taobao网主动跳转到网站首页
			if(ret2.indexOf('<span>首页</span>') != -1) {ret2 = null; return; }
			//if(ret2.indexOf('>首页<') != -1) {document.body.innerText = ret2; ret2 = null; return; }
			if(ret2.indexOf('curr-page') == -1) {
				//if(!pur5.Cfg.TBBlkOrders.length) pur5.Pages.setTBRecord('当前没有需要关闭交易的宝贝 ' + pur5.Pages.getTime('2'));
				ret2 = null;
				return;
			}
			var curNum = ret2.between('<li class="curr-page"><a href="#" class="selected" onclick="return changePage', '</a></li>').split('>')[1];
			if(curNum == pur5.Cfg.TBBlkOrdersPage
				&& pur5.Cfg.TBBlkOrdersPage <= pur5.Cfg.TBMaxPages
				&& pur5.Cfg.TBBlkOrders < stepLen
				&& j < stepLen
			) {
				pur5.Pages.readTBTransaction(ret2);
				pur5.Cfg.TBBlkOrdersPage++;
				j++;
				arguments.callee();
			} else {
				ret2 = null;
				return;
			}
		}
	})();
	
	var k = 0;		//评价递归次数
	if(!pur5.Cfg.TBComments.length) pur5.Cfg.TBCommentsPage = 1;
	(function() {
		if(pur5.Cfg.GBstopTaobao) return;
		//只有启用"自动评价"功能，才检查
		if(tbAutoComments[0].checked) {
			var ds3 = pur5.Cfg.Ds,
				ret3 = ds3.httpCookiePost('http://trade.taobao.com/trade/itemlist/list_sold_items.htm?event_submit_do_query=1&user_type=1&isArchive=false&order=desc&order_type=orderList&isArchiveDefault=0&isQueryMore=false&select_shop_name=&isOwnOfficialShop=false&sellerNumID=54785369&_fmt.q._0.a=&_fmt.q._0.bi=&_fmt.q._0.biz=00&_fmt.q._0.bizo=00&_fmt.q._0.bizor=&_fmt.q._0.bizord=00&_fmt.q._0.bizorde=00&_fmt.q._0.b=&_fmt.q._0.au=ALL&_fmt.q._0.c=I_HAS_NOT_COMMENT&_fmt.q._0.bizorder=&_fmt.q._0.l=ALL&_fmt.q._0.t=ALL&queryTag=0&_fmt.q._0.sh=All&action=itemlist/QueryAction&fromTag=true&pageNum=' + pur5.Cfg.TBCommentsPage, pur5.Cfg.TBcookies, 1, '', '.taobao.com', '');
			pur5.Cfg.TBcookies = ds3.GetCookie(".taobao.com");
			
			//如果频率过快taobao网主动跳转到网站首页
			if(ret3.indexOf('<span>首页</span>') != -1) {ret3 = null; return; }
			if(ret3.indexOf('curr-page') == -1) {
				//if(!pur5.Cfg.TBComments.length) pur5.Pages.setTBRecord('当前没有需要评价的宝贝 ' + pur5.Pages.getTime('2'));
				ret3 = null;
				return;
			}
			var curNum = ret3.between('<li class="curr-page"><a href="#" class="selected" onclick="return changePage', '</a></li>').split('>')[1];
			if(curNum == pur5.Cfg.TBCommentsPage
				&& pur5.Cfg.TBCommentsPage <= pur5.Cfg.TBMaxPages
				&& pur5.Cfg.TBComments < stepLen
				&& k < stepLen
			) {
				pur5.Pages.readTBComments(ret3);
				pur5.Cfg.TBCommentsPage++;
				k++;
				arguments.callee();
			} else {
				ret3 = null;
				return;
			}
		}
	})();
	
	////不再需要单独更新cookie了
	////ret00 = ret0 = null;
	return;
}

/**
 * 定时检查淘宝之前已存服务器的trading表，将表里存在的"已成功发货，但因网络问题或软件退出导致发货记录还没来得及提交到pur5服务器"的订单，重新提交到pur5服务器
 */
pur5.Pages.tbReDeliverInterval = function() {
	if(!pur5.Cfg.GBPUR5LOG || !pur5.Cfg.GBTAOBAOLOG) return;

	$.ajax({
		url: pur5.Cfg.GBHOSTSOFT + 'taobao.asp',
		type: 'get',
		cache: false,
		data: {
			token: pur5.Cfg.token,
			lv: 't3',
			ls: pur5.Cfg.pur5PassWordKey
		},
		success: function(a){
			if(a == '' || a == 'ErrorKey') return;
			if(a == 'SessionLost') { pur5.Pages.tbInputAgainPur5PW2(); return; }
			
			var aa = [], str = '', tborder = '', spt1 = String.fromCharCode(11), spt2 = String.fromCharCode(12);
			a = a.replace(/\r/g, spt1).replace(/\n/g, spt2);
			aa = a.split("|||").slice(0, Math.floor(pur5.Cfg.TBReDeliverIntervalTime / pur5.Cfg.TBSendOrdersIntervalTime / 2));
			
			if(aa.length == 1) return;
			pur5.Pages.setTBRecord('正在复查是否有漏单......');
			//重新走流程提交发货和把记录返回pur5服务器并清除trading表中该条记录
			for(var i = 0, l = aa.length; i < l; i++) {
				(function(j) {
					setTimeout(function() {
						str = aa[j];
						if(str) {
							tborder = str.between('淘宝订单号' + spt1, spt2);
							if(!tborder) return;
							
							var ds1 = pur5.Cfg.Ds,
								ret0 = ds1.httpCookiePost('http://trade.taobao.com/trade/detail/trade_item_detail.htm?biz_order_id=' + tborder + '&his=false', pur5.Cfg.TBcookies, 1, '', '.taobao.com', '');
							pur5.Cfg.TBcookies = ds1.GetCookie(".taobao.com");
	
							pur5.Pages.tbProDetail(ret0, str, tborder, true);
							ret0 = null;
						}
					}, j * pur5.Cfg.TBSendOrdersIntervalTime / 2);
				})(i);
			}
		},
		error: function(jqXhr, textStatus){
			pur5.Pages.setTBRecord('t3失败：' + $('#loginHost').text());
		}
	});
}


/**
 * "淘宝"筛选符合发货条件的订单定时器运行函数
 */
pur5.Pages.runTBOrdersInterval = function() {
	clearInterval(pur5.Cfg.ReadTBOrdersInterval);
	clearInterval(pur5.Cfg.TBReDeliverInterval);
	pur5.Cfg.ReadTBOrdersInterval = setInterval(pur5.Pages.doingReadTBOrders, pur5.Cfg.ReadTBOrdersIntervalTime);
	pur5.Cfg.TBReDeliverInterval = setInterval(pur5.Pages.tbReDeliverInterval, pur5.Cfg.TBReDeliverIntervalTime);
	return;
}


/**
 * 主显示区"淘宝监控"的初始化设置
 */
$(function() {
	var layoutTBJKButton = $('#layoutTBJKButton'),
		//layoutTBJKInputUser = $('#layoutTBJKInputUser'),
		//layoutTBJKInputPass = $('#layoutTBJKInputPass'),
		layoutTBJKInfoText = $('#layoutTBJKInfoText'),
		layoutTBJKInputStart = $('#layoutTBJKInputStart'),
		layoutTBJKInputTime = $('#layoutTBJKInputTime'),
		layoutTBJKInputSuspend = $('#layoutTBJKInputSuspend'),
		layoutTBJKInputStop = $('#layoutTBJKInputStop'),
		layoutTBJKRecord = $('#layoutTBJKRecord'),
		layoutTBJKLoginBefore = $('#layoutTBJKLoginBefore'),
		layoutTBJKLoginAfter = $('#layoutTBJKLoginAfter'),
		layoutTBJKTextUser = $('#layoutTBJKTextUser'),
		statusBarMonitorTB = $('#statusBarMonitorTB'),
		layoutTBJKRecordClear = $('#layoutTBJKRecordClear'),
		tbAutoCloseOrder = $('#tbAutoCloseOrder'),
		tbBlackListIDON = $('#tbBlackListIDON'),
		tbBlackListID = $('#tbBlackListID'),
		tbAutoCloseAll = $('#tbAutoCloseAll'),
		tbAutoCloseOrderTitle = $('#tbAutoCloseOrderTitle'),
		tbAutoComments = $('#tbAutoComments'),
		tbAutoCommentsSel = $('#tbAutoCommentsSel'),
		tbAutoCommentsText = $('#tbAutoCommentsText'),
		startClick = function() {
			var cookies = '';
			if(pur5.Cfg.TBJKWinId) {
				pur5.Cfg.Ds.CloseWindow(pur5.Cfg.TBJKWinId);
				cookies = pur5.Cfg.Ds.GetCookie(pur5.Cfg.TBJKWinId);
				if(cookies) cookies = cookies.replace(/[\n\r]+/gm, '');
			}

			if(cookies.search("token") <= 0 || !pur5.Cfg.TBJKWinId) { alert('请先点击"登录淘宝"按钮登录后再启动监控！'); return; }
			var user = '';
			if(cookies.indexOf('_nk_=') != -1) {
				user = unescape(cookies.split('_nk_=')[1].split(';')[0].replace(/%5C/g, '%'));
			} else if(cookies.indexOf('nick=') != -1) {
				user = unescape(cookies.split('nick=')[1].split(';')[0].replace(/%5C/g, '%'));
			}
			if(user == '') pur5.Pages.setTBRecord('获取旺旺号为空');
			pur5.Pages.setTBRecord('正在登录淘宝...');
			layoutTBJKInputSuspend[0].disabled = false;
			if(cookies.search('cookie1') >= 0 && cookies.search('cookie2') >= 0 && cookies.search('uc1=lltime') >= 0) {
				pur5.Cfg.TBcookies = cookies;
				pur5.Cfg.GBTAOBAOLOG = true;
				pur5.Cfg.GBstopTaobao = false;
				TbNoOrderWarn.init();
				layoutTBJKRecord.html('');
				pur5.Pages.setTBRecord('登录淘宝成功,' + user);
				layoutTBJKLoginBefore.hide();
				layoutTBJKLoginAfter.show();
				layoutTBJKInputStart.hide();
				layoutTBJKInputStop.show();
				layoutTBJKTextUser.html(user);
				layoutTBJKInfoText.html('正在监控');
				statusBarMonitorTB.html('正在监控');
				pur5.Cfg.taobaoUid = user;
				pur5.Pages.doingReadTBOrders();
				pur5.Cfg.ReadTBOrdersIntervalTime = layoutTBJKInputTime.val() * 1000;
				pur5.Pages.tbReDeliverInterval();					//登录完毕后也先查一下trading表
				pur5.Pages.runTBOrdersInterval();
				pur5.Pages.runTBSendOrdersInterval();
			} else {
				//pur5.Pages.setTBRecord('登录失败！！如果多次登录失败，先在淘宝网站输入旺旺密码登录淘宝以后再试！注意：不能设置淘宝的登录保护以及手机验证。');
				pur5.Cfg.GBTAOBAOLOG = false;
			}
		},
		setComForm = function() {
			tbAutoCommentsSel[0].disabled = tbAutoCommentsText[0].disabled = tbAutoComments[0].checked ? false : true;
		};
		
	try{	
		pur5.Cfg.Ds.AddFilter(".taobao.com");
	}catch(e){}

	layoutTBJKButton.click(function() {
		if(pur5.Cfg.TBJKWinId) pur5.Cfg.Ds.CloseWindow(pur5.Cfg.TBJKWinId);
		pur5.Cfg.TBJKWinId = (new Date()).getTime() + Math.random() + '';
		pur5.Cfg.Ds.Link('https://login.taobao.com/member/login.jhtml?' + (new Date()).getTime() + Math.random(), pur5.Cfg.TBJKWinId);
	});
	
	layoutTBJKInputStart.click(startClick);
	
	

	
	layoutTBJKRecordClear.click(pur5.Pages.clearTBRecord);
	
	if(tbAutoCloseOrder[0].checked) tbAutoCloseAll[0].disabled = false;
	
	tbBlackListIDON.click(function() {
		tbBlackListID[0].disabled = this.checked ? false : true;
	});
	
	tbAutoCloseOrder.click(function() {
		tbAutoCloseAll[0].disabled = tbAutoCloseOrderTitle[0].disabled = this.checked ? false : true;
	});
	
	layoutTBJKInputTime.blur(function() {
		var val = this.value;
		if(isNaN(val)) val = 25;
		if(val < 15) {
			val = 15;
		} else if(val > 120) {
			val = 120;
		}
		this.value = val;
		pur5.Cfg.ReadTBOrdersIntervalTime = val * 1000;
		pur5.Pages.runTBOrdersInterval();
		pur5.Pages.runTBSendOrdersInterval();
	});
	layoutTBJKInputSuspend.click(function() {
		if(this.checked && pur5.Cfg.ReadTBOrdersInterval && pur5.Cfg.GBTAOBAOLOG && !pur5.Cfg.GBstopTaobao) {
			if(confirm('注意：淘宝已发货的订单将无法暂停！是否继续？')) {
				clearInterval(pur5.Cfg.ReadTBOrdersInterval);
				clearInterval(pur5.Cfg.TBSendOrdersInterval);
				pur5.Cfg.GBstopTaobao = true;
				layoutTBJKInfoText.html('暂停监控');
				statusBarMonitorTB.html('暂停监控');
			} else {
				this.checked = false;
			}
		} else {
			pur5.Cfg.GBstopTaobao = false;
			pur5.Pages.runTBOrdersInterval();
			pur5.Pages.runTBSendOrdersInterval();
			layoutTBJKInfoText.html('正在监控');
			statusBarMonitorTB.html('正在监控');
		}
	});
	layoutTBJKInputStop.click(function() {
		if(confirm('是否退出淘宝？')) {
			var ds1 = pur5.Cfg.Ds;
			layoutTBJKTextUser.html('未登录');
			ds1.httpCookiePost('http://login.taobao.com/member/logout.jhtml?', pur5.Cfg.TBcookies, 1, '', '', '');
			ds1.SetCookie('.taobao.com');
			pur5.Cfg.TBcookies = '';
			pur5.Cfg.TBJKWinId = '';
			pur5.Cfg.GBTAOBAOLOG = false;
			pur5.Cfg.GBstopTaobao = true;
			pur5.Pages.setTBRecord('退出淘宝');
			layoutTBJKInfoText.html('未监控');
			statusBarMonitorTB.html('未监控');
			layoutTBJKInputSuspend[0].checked = false;
			layoutTBJKInputSuspend[0].disabled = true;
			pur5.Cfg.taobaoUid = '';
			//layoutTBJKInputPass.val('');
			layoutTBJKLoginBefore.show();
			layoutTBJKLoginAfter.hide();
			layoutTBJKInputStart.show();
			clearInterval(pur5.Cfg.ReadTBOrdersInterval);
			clearInterval(pur5.Cfg.TBSendOrdersInterval);
			clearInterval(pur5.Cfg.TBReDeliverInterval);
			$(this).hide();
		}
	});
	
	tbAutoComments[0].checked = false;
	tbAutoCommentsSel.val(1);
	setComForm();
	tbAutoComments.click(setComForm);
	
	try {
		tbBlackListID.val(pur5.Pages.getFso(pur5.Cfg.TBBlkListNameFile));
		tbAutoCloseOrderTitle.val(pur5.Pages.getFso(pur5.Cfg.TBBlkListProFile));
		tbAutoCommentsText.val(pur5.Pages.getFso(pur5.Cfg.TBCommentsFile));
	} catch(e) {}
});


/**
 * taobao离线托管的初始化设置
 */
$(function() {
	var offlineTBLastTime = $('#offlineTBLastTime'),
		offlineTBJKButton = $('#offlineTBJKButton'),
		//offlineTBWW = $('#offlineTBWW'),
		//offlineTBWWP = $('#offlineTBWWP'),
		offlineTBStop = $('#offlineTBStop'),
		offlineTBSubmit = $('#offlineTBSubmit'),
		offlineTBResult = $('#offlineTBResult'),
		tds = offlineTBResult.find('td'),
		startText = '正在监控',
		stopText = '停止监控',
		successText = '登录成功';
	
	offlineTBJKButton.click(function() {
		if(pur5.Cfg.TBJKWinId) pur5.Cfg.Ds.CloseWindow(pur5.Cfg.TBJKWinId);
		pur5.Cfg.TBJKWinId = (new Date()).getTime() + Math.random() + '';
		pur5.Cfg.Ds.Link('https://login.taobao.com/member/login.jhtml?' + (new Date()).getTime() + Math.random(), pur5.Cfg.TBJKWinId);
	});
	
	offlineTBSubmit.click(function() {
		//var user = offlineTBWW.val().toLocaleLowerCase(),
		var user = '',
			//pass = offlineTBWWP.val().left(16),
			trs = offlineTBResult.find('tr'),
			needStop = false,
			inTable = false,
			ds1 = pur5.Cfg.Ds,
			//poststr = "from=tb&TPL_username=" + user.$$() + "&TPL_password=" + pass.$$() + "&isww=1&actionForStable=enable_post_user_action&action=Authenticator&TPL_redirect_url=&event_submit_do_login=anything",
			cookies = '';
		if(pur5.Cfg.TBJKWinId) ds1.CloseWindow(pur5.Cfg.TBJKWinId);
		cookies = ds1.GetCookie(pur5.Cfg.TBJKWinId);
		
		if(cookies) cookies = cookies.replace(/[\n\r]+/gm, '');
		if(!cookies || cookies.search("token") <= 0) { alert('请先点击"登录淘宝"按钮登录后再点确定按钮！'); return; }
		
		if(cookies.indexOf('_nk_=') != -1) {
			user = unescape(cookies.split('_nk_=')[1].split(';')[0].replace(/%5C/g, '%'));
		} else if(cookies.indexOf('nick=') != -1) {
			user = unescape(cookies.split('nick=')[1].split(';')[0].replace(/%5C/g, '%'));
		}
		if(user == '') alert('获取旺旺号为空');
			
		if(offlineTBStop[0].checked) {
			//if(user == '') { alert('请输入旺旺账号'); return; }
			//if(pass == '') { alert('请输入旺旺密码'); return; }
			//cookies = ds1.httpCookiePost("http://login.taobao.com/member/login.jhtml", "", 0, poststr, '', '');
			//将cookie清除
			//ds1.httpCookiePost('http://login.taobao.com/member/logout.jhtml?', cookies, 1, '', '', '');
			//ds1.SetCookie('.taobao.com');
			
			for(var i = 0, l = trs.length; i < l; i++) {
				var tds = trs[i].getElementsByTagName('td');
				if(tds[3].innerHTML == startText) {
					needStop = true;
					break;
				}				
			}
			if(needStop) {
				if(cookies.search('cookie1') >= 0 && cookies.search('cookie2') >= 0 && cookies.search('uc1=lltime') >= 0) {
					$.ajax({
						url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
						type: 'get',
						cache: false,
						data: {
							token: pur5.Cfg.token,
							lv: 't3', ww: user,
							source: 'taobao'
						},
						success: function(data){
							if(data == '1') {
								//offlineTBWWP.val('');
								tds[3].innerHTML = stopText;
								tds[3].className = 'redfont';
								tds[4].innerHTML = successText;
							} else {
								tds[4].innerHTML = data;
							}
						}
					});
				} else {
					alert('请先点击"登录淘宝"按钮登录后再点确定按钮！')
				}
			} else { alert('该旺旺账号未起用离线托管'); }
			needStop = false;
		} else {
			//if(user == '') { alert('请输入旺旺账号'); return; }
			//if(pass == '') { alert('请输入旺旺密码'); return; }
			//cookies = ds1.httpCookiePost("http://login.taobao.com/member/login.jhtml", "", 0, poststr, '', '');
			
			var loginTime = pur5.Pages.getTime(), trIndex = 0;
			if(cookies.search('cookie1') >= 0 && cookies.search('cookie2') >= 0 && cookies.search('uc1=lltime') >= 0) {
				for(var i = 0, l = trs.length; i < l; i++) {
					var tds = trs[i].getElementsByTagName('td');
					if(tds[1].innerHTML == user) {
						inTable = true;
						trIndex = i;
						break;
					}
				}
				
				$.ajax({
					url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
					type: 'post',
					cache: false,
					data: {
						token: pur5.Cfg.token,
						lv: 't1',
						ww: user.$$$(),
						cookie: cookies.$$$(),
						source: 'taobao'
					},
					success: function(data){
						if(data != '1') { alert(data); return; }
						var tds = trs[trIndex].getElementsByTagName('td');
						if(inTable) {
							if(tds[3].innerHTML == stopText) {
								tds[2].innerHTML = loginTime.replace(/\s+/g, '<br />');
								tds[3].innerHTML = startText;
								tds[3].className = 'bluefont';
								tds[4].innerHTML = successText;
							} else {
								alert('该旺旺已经在离线托管中！');
							}
						} else {
							if(pur5.Cfg.TBOfflineMax == 1) {
								tds[0].innerHTML = pur5.Cfg.pur5Uid;
								tds[1].innerHTML = user;
								tds[2].innerHTML = loginTime.replace(/\s+/g, '<br />');
								tds[3].innerHTML = startText;
								tds[3].className = 'bluefont';
								tds[4].innerHTML = successText;
															
								$('#offlineTBUser').html(user);//20100530 xz
								$('#offlineTBLastTime').html(loginTime);
	
								return;
							}
							
							if(trs.length >= pur5.Cfg.TBOfflineMax) {
								offlineTBResult[0].deleteRow(pur5.Cfg.TBOfflineMax - 1);
							}
							
							if(tds[0].innerHTML == '') {
								tds[0].innerHTML = pur5.Cfg.pur5Uid;
								tds[1].innerHTML = user;
								tds[2].innerHTML = loginTime.replace(/\s+/g, '<br />');
								tds[3].innerHTML = startText, tds[3].className = 'bluefont';
								tds[4].innerHTML = successText;
							} else {
								var trNew = offlineTBResult[0].insertRow(0), trNewCells = trNew.cells;
								trNew.insertCell(0), trNewCells[0].innerHTML = pur5.Cfg.pur5Uid;
								trNew.insertCell(1), trNewCells[1].innerHTML = user;
								trNew.insertCell(2), trNewCells[2].innerHTML = loginTime.replace(/\s+/g, '<br />');
								trNew.insertCell(3), trNewCells[3].innerHTML = startText, trNew.cells[3].className = 'bluefont';
								trNew.insertCell(4), trNewCells[4].innerHTML = successText;
							}
						}
						
						offlineTBLastTime.html(loginTime);
						//offlineTBWWP.val('');
						inTable = false;
					},
					error: function(jqXhr, textStatus){
						alert('托管失败:' + textStatus);
					}
				});
			}else{
				alert('登录失败！！');
			}
		}
	});
})