var PP = {
	Config: {//静态配置
		Ds: false,
		loginWindowId: '',
		debug: false,//调试模式
		userId: '',//用户的PP UID
		userCookies: '',//用户的cookie
		pageSize: 30,//单次定单数量
		Interval: {//间隔时间 毫秒
			normal: 25,
			min: 15,//最小时间间隔
			max: 100,
			closeTransaction: 10
		},
		recordMaxLength: 100//记录长度
	},
	Timer: {
		closeTransaction: false//关闭交易定时器
	},
	Data: {//动态数据
		Log: [pur5.Pages.getTime('0', new Date())],
		isPauseMonitor: false,
		isStopMonitor: true,
		isGettingDealList: false,
		isSavingTrade: false,
		isGettingTradding: false,
		isCheckOrderOnPP: false,
		listErrorCount: 0,//"获取订单错误"的次数
		DealList: {
			Delivered: [],//发货成功的列表
			Tradding: [],//从pur5取到的订单号列表
			Good: [],//正常的订单
			Bad: []//错误(未通过验证)的订单
		}
	},	
	init: function(){//初始化
		$('#layoutPPJKButton').click(function(){
			PP.login();
		});
		
		this.appendRecord('初始化', 1);
		$('#layoutPPJKInputTime').val(PP.Config.Interval.normal);
		
		$('#layoutPPJKInputUser')
			.unbind('blur')
			.blur(function(){
				PP.refreshValidateCode();
			});
		
		$('#layoutPPJKRefreshCode')
			.unbind('click')
			.click(function(){
				PP.refreshValidateCode();
			});
			
		$('#layoutPPJKRecordClear')
			.click(function(){
				PP.clearRecord();
			});
			
		$('#layoutPPJKInputStart')
			.unbind('click')
			.click(function(){
				PP.beforeStartMonitor();
			});
		
		$('#layoutPPJKInputStop')
			.unbind('click')
			.click(function(){
				PP.stopMonitor();
			});
		
		$('#layoutPPJKCode')
			.unbind('keypress')
			.unbind('focus');
			
		$('#layoutPPJKInputSuspend')
			.unbind('click')
			.click(function(){
				PP.pauseMonitor(this.checked);
			});

		$('#layoutPPJKInputTime')
			//.attr('disabled', true)
			.unbind('keyup')
			.blur(function(){
				if(!/^\d+$/.test(this.value)){
					this.value = PP.Config.Interval.normal;
				}else{
					if(this.value < PP.Config.Interval.min){
						this.value = PP.Config.Interval.min;
					}
					if(this.value > PP.Config.Interval.max){
						this.value = PP.Config.Interval.max;
					}				
				}
				PP.Config.Interval.normal = this.value;
			});
			
		$('#ppBuiedItemCountLimitCheckbox').click(function(){
			$('#ppXzGoodsNames,#ppXzAllGoods,#ppXzSomeGoods').attr('disabled', !this.checked);
			$(this).blur();
		}).triggerHandler('click');
		
		$('#ppBlackBlistCheckbox').click(function(){
			$('#ppBlackBlist').attr('disabled', !this.checked);
			$(this).blur();
		}).triggerHandler('click');
	},
	appendRecord: function(sMsg, must){//追加日志记录
		PP.Data.Log.push(sMsg);
		if(PP.Data.Log.length == 25){
			try{
				pur5.Pages.saveLog(
					'paipai',
					PP.Config.userId,
					'\r\n'
					+ PP.Data.Log.join('\r\n')
				);
			}catch(e){}
			PP.Data.Log = [pur5.Pages.getTime('0', new Date())];
		}
	
		if(!PP.Config.debug && !must){
			return false;
		}
		$('#layoutPPJKRecord').append('<p>'+sMsg+'</p>');
		$('#layoutPPJKRecord').scrollTop($('#layoutPPJKRecord p').length * 50);
		
		if($('#layoutPPJKRecord p').length > PP.Config.recordMaxLength){
			this.clearRecord();
		}
	},
	clearRecord: function(){//清空日志记录
		$('#layoutPPJKRecord').html('');
	},
	beforeStartMonitor: function(){
		var cookies = '';
			
		if(PP.Config.loginWindowId) {
			//pur5.Cfg.Ds.CloseWindow(PP.Config.loginWindowId);
			//cookies = pur5.Cfg.Ds.GetCookie(PP.Config.loginWindowId);
			cookies = MiniBrowser.getCookie();
			//alert(cookies);
			delete PP.Config.loginWindowId;
			if(cookies) cookies = cookies.replace(/[\n\r]+/gm, '');
			var uinReg = /; uin=(o0+)?(\d+)/;
			
			//alert(cookies.match(uinReg).join('\n------------\n'));
			if(!uinReg.test(cookies)){
				alert('请先点击"登录拍拍"按钮成功登录后,再启动监控！');
				return;
			}
			
			PP.Config.userCookies = cookies;
			PP.Config.userId = cookies.match(uinReg)[2];
			if(!PP.Config.userId){
				alert(cookies);
			}
			//pur5.Pages.alert($('#inputTradingPassPP')[0]);
			PP.startMonitor();
			
		}else{
			alert('请先点击"登录拍拍"按钮成功登录后,再启动监控！');
		}
	},
	login: function(){
		var Ds = PP.Config.Ds;
		try {
			if(!Ds) Ds = PP.Config.Ds = new ActiveXObject('dsCookieGetter.ds');
			Ds.AddFilter(".paipai.com");
		} catch(e) { PP.appendRecord('离线组件注册失败，请重新注册！', 1); return false;}

		if(PP.Config.loginWindowId) pur5.Cfg.Ds.CloseWindow(PP.Config.loginWindowId);
		PP.Config.loginWindowId = (new Date()).getTime() + Math.random() + 'paipai';
		//Ds.Link('http://member.paipai.com/cgi-bin/login_entry', PP.Config.loginWindowId);
		MiniBrowser.openWindow('http://www.paipai.com');
	},
	get: function(url){
		var content = PP.Config.Ds.httpCookiePost(url, PP.Config.userCookies, 1, '', '.paipai.com', '');
		PP.Config.userCookies = PP.Config.Ds.GetCookie(".paipai.com");
		return content;
	},
	post: function(url, data){
		var content = PP.Config.Ds.httpCookiePost(url, PP.Config.userCookies, 1, data, '.paipai.com', '');
		PP.Config.userCookies = PP.Config.Ds.GetCookie(".paipai.com");
		return content;
	},
	closeTransaction: function(){//关闭交易执行函数
		if(PP.Data.isPauseMonitor) return false;
		PP.appendRecord('关闭订单');
		if(!$('#ppBuiedItemCountLimitCheckbox').is(':checked') && !$('#ppBlackBlistCheckbox').is(':checked')){
			return false;
		}
		
		var sDealList = PP.get(('http://my.paipai.com/cgi-bin/trade_deal_list/sold'
								+'?deal_state=1'
								+'&start_page=1'
								+'&serial_no=33661'
								+'&page_size=PAGE_SIZE'
								+'&t=TIME')
									.replace('PAGE_SIZE', PP.Config.pageSize)
									.replace('TIME', Math.random()));
		var DealObj,DealArr;
		try{
			DealObj = $.xml2json(sDealList);
			DealArr = DealObj.DealList.Deal
			if(!DealArr){
				PP.appendRecord('没有需要关闭的订单');
				return false;
			}
		}catch(e){
			PP.appendRecord(e.description);
			return false;
		}
		
		if(DealArr.constructor != Array) DealArr = [DealArr];
		
		var closeResult = '';//关闭结果
		PP.appendRecord('遍历未付款订单');
		$.each(DealArr, function(i, Item){//便利未付款订单并关闭交易
			if(Item.CanClose != 1 || !PP.isLimitedOrder(Item)){
				PP.appendRecord(['不能关闭或不被限制', Item.ID, Item.CanClose]);
				return true;
			}
			
			PP.appendRecord('关闭订单:' + Item.ID, 1);
			closeResult = PP.post('http://pay.paipai.com/cgi-bin/close_deal/submit', 'close_reason=16&selected_index=0&deal_id='+Item.ID + '&trade_id_0=' + Item.ID.match(/\d+$/)[0]);
			PP.appendRecord('关闭' + ((closeResult.indexOf('订单关闭成功！') != -1)?'成功':'失败'), 1);
		});
	},
	isLimitedOrder: function(Order){//被限制的订单
		var limited = false, splitReg = /[\s\|,，　]/;
		
		PP.appendRecord('Order.Buyer.Uin' + Order.Buyer.Uin);
		PP.appendRecord(['BlackList', $('#ppBlackBlist').val().split(splitReg).join('|')]);
		if($('#ppBlackBlistCheckbox').is(':checked') && $.inArray(Order.Buyer.Uin, $('#ppBlackBlist').val().split(splitReg)) != -1){
			PP.appendRecord(['BlackList Got']);
			limited = true;
		}
		if($('#ppBuiedItemCountLimitCheckbox').is(':checked') && Order.TradeList.Trade.ItemCount > 1){
			if($('#ppXzAllGoods').is(':checked')){//全部商品
				PP.appendRecord('全部商品倍拍限制');
				limited = true;
			}else{//关键词商品
				$.each($('#ppXzGoodsNames').val().split(splitReg), function(index, goodsKeyWord){
					if(Order.TradeList.Trade.Item.Name.indexOf(goodsKeyWord) != -1){
						PP.appendRecord(['关键字商品倍拍限制', Order.TradeList.Trade.Item.Name, goodsKeyWord]);
						limited = true;
						return false;
					}
				});
			}
		}
		return limited;
	},
	getDealList: function(){//读取待发货列表
		if(PP.Data.isGettingDealList || PP.Data.isStopMonitor){
			return false;
		}
		
		if(PP.Data.isPauseMonitor){
			setTimeout(arguments.callee, 500);
			return false;
		}

		PP.Data.isGettingDealList = true;
		PP.appendRecord('下载发货列表');
		var sDealList = PP.get(('http://my.paipai.com/cgi-bin/trade_deal_list/sold'
								+'?deal_state=2'
								+'&start_page=1'
								+'&serial_no=33661'
								+'&page_size=PAGE_SIZE'
								+'&t=TIME')
									.replace('PAGE_SIZE', PP.Config.pageSize)
									.replace('TIME', Math.random()));
									
		PP.analysisDealList(sDealList);
	},
	analysisDealList: function(sDealList, silence){//分析发货列表
		if(!silence)PP.appendRecord('分析发货列表');
		var oDealData, aDeal, nInterval;
		try{
			oDealData = $.xml2json(sDealList);//转为Json格式
			aDeal = oDealData.DealList.Deal;
		}catch(e){
			if(oDealData && oDealData.Result && oDealData.Result.code == 13){//超时
				//alert(sDealList);
				PP.stopMonitor();
				alert('拍拍超时, 请重新登录拍拍！');
				//pur5.Pages.ppInputAgainPur5PW2();
				return false;
			}
			
			if(oDealData && oDealData.Result && oDealData.Result.code == 219){//0616
				PP.stopMonitor();
				PpTradingPass.show(function(tradeCode){
					setTimeout(function(){
						var	loginWithTradeCodeResult
								= PP.post('http://member.paipai.com/cgi-bin/c2clogin?g_tk=G_TK&g_ty=fr'.replace(/G_TK/, PP.getToken()),
											'fill_p=FILL_P'.replace('FILL_P', md5(tradeCode)));
						if(/<title>交易密码管理<\/title>/.test(loginWithTradeCodeResult)){
							alert('拍拍交易密码输入错误，请重新输入！\n-----------------------\n提示: 拍拍交易密码是指拍拍网的交易密码\n　　　不是pur5平台交易密码！\n　　　不是财富通支付密码！\n设置方式：登录拍拍网->我的拍拍->账户管理->交易密码管理');
						}else{
							PpTradingPass.hide();
							PP.startMonitor();
						}
					}, 1)
				});
				
				return false;				
			}
		}
		
		if(!aDeal){
			aDeal = [];
		}else{
			if(aDeal.constructor != Array) aDeal = [aDeal];
		}
		
		var Deals = sDealList.match(/(<Deal>[\s\S]+?<\/Deal>)/g);
		for(var i=aDeal.length; i--;){
			aDeal[i]._str = Deals[i];//sDealList;
			if(PP.isGoodDeal(aDeal[i], oDealData, sDealList, silence)){
				PP.Data.DealList.Bad.$pop(aDeal[i].ID, 'ID');//从错误订单中弹出
				PP.Data.DealList.Good.$push(aDeal[i], 'ID');//压到正确订单
				//PP.Data.DealList.Good.sort(function(dealA, dealB){//根据日期重新整理数组,以便查询充值列表
				//	return (dealA.DealTime>dealB.DealTime)?1: -1;
				//});
			}else{
				PP.Data.DealList.Good.$pop(aDeal[i].ID, 'ID');//从正确订单中弹出
				PP.Data.DealList.Bad.$push(aDeal[i], 'ID');//压到错误订单
			}
		}
		
		PP.Data.isGettingDealList = false;
		if(!silence)setTimeout(PP.getDealList, PP.Config.Interval.normal*1000);
	},
	isGoodDeal: function(oDeal, oDealData, sDealList, silence){//验证订单有效性
		if(PP.isLimitedOrder(oDeal)) return false;
		if(!/\[\*\d*\]/.test(oDeal.TradeList.Trade.Item.Name)) return false;//不是第五代货物
		//return true;//不需要验证
		var info = [];
					
//		!/\[\*\d*\]/.test(oDeal.TradeList.Trade.Item.Name)
//			&& (info.push('商品名称不符合规范:' + oDeal.TradeList.Trade.Item.Name));
//
//		!/^\d{4}\-\d\d\-\d\d \d+\:\d+\:\d+$/.test(oDeal.DealTime)
//			&& (info.push('日期格式(yyyy-mm-dd hh:mm:ss)错误:' + oDeal.DealTime));	
//			
//		!/^\d+$/.test(oDeal.State)
//			&& (info.push('订单状态数据有错误:' + oDeal.State));
//			
//		!/^\d+\-\d+\-\d+$/.test(oDeal.ID)
//			&& (info.push('订单ID数据格式错误:' + oDeal.ID));
			
		if(/^$/.test(oDeal.Consignee.Mobile.trim()) && /^$/.test(oDeal.Postscript.trim())){ 
			info.push('被充值号码为空');
		}
			
		if(info.length){			
			if(!silence)PP.appendRecord('订单错误:' + oDeal.ID + ':<br />' + info.join('<br />'), 1);
			return false;
		}else{
			return true;
		}
	},
	saveTrade: function(){
		if(PP.Data.isSavingTrade || PP.Data.isStopMonitor){
			return false;
		}

		if(PP.Data.isPauseMonitor){
			setTimeout(arguments.callee, 500);
			return false;
		}
		
		var Deal = PP.Data.DealList.Good[0];
		if(!Deal){
			PP.appendRecord(pur5.Pages.getTime('2') + ' 没有需要发货的宝贝', 1);
			setTimeout(arguments.callee, PP.Config.Interval.normal*1000);
			return false;
		}
		
		PP.Data.isSavingTrade = true;	
		PP.appendRecord('提交订单:' + Deal.ID + ' 开始', 1);	
		
		$.ajax({
			url: pur5.Cfg.GBHOSTSOFT + 'paipainew.asp?er=true',
			type: 'post',
			dataType: 'text',
			cache: false,
			data: {
				lv: 't1',
				token: pur5.Cfg.token,
				str: Deal._str.$$$(),
				orderid: Deal.ID,
				uid: pur5.Cfg.pur5Uid,
				status: Deal.State,
				ls: pur5.Cfg.pur5PassWordKey
			},
			success: function(data, textStatus, jqXhr){
				if(data == Deal.ID){
					PP.appendRecord('提交订单:' + Deal.ID + ' 成功', 1);
					PP.deliver(Deal);
					//PP.1(Deal);
				}else{
					PP.appendRecord('提交订单:' + Deal.ID + ' 失败', 1);
					PP.appendRecord(data, 1);
					
					if(data == '订单已存在'){
						PP.deliver(Deal);
					}else{
						PP.Data.DealList.Good.$pop(Deal.ID, 'ID');	
						PP.Data.DealList.Tradding.$pop(Deal.ID);				
						PP.Data.isSavingTrade = false;
						setTimeout(PP.saveTrade, PP.Config.Interval.normal*1000);
					}
				}
			},
			error: function(jqXhr, textStatus){
				PP.appendRecord('提交订单:' + Deal.ID + ' 错误' + textStatus, 1);
				PP.appendRecord(jqXhr.responseText);
				PP.Data.isSavingTrade = false;
				setTimeout(PP.saveTrade, PP.Config.Interval.normal*1000*2);
			}
		});
	},
	deliver: function(Deal){//发货
		PP.appendRecord('拍拍发货:' + Deal.ID + ' 开始', 1);

		var deliverResult
			= PP.post(('http://wuliu.paipai.com/cgi-bin/wuliu/marknowuliu'
				+'?g_tk=$g_tk'
				+'&g_ty=j132')
					.replace('$g_tk', PP.getToken()),
					'biz_deal=$biz_deal'.replace('$biz_deal', Deal.ID + '##' + Deal.Buyer.Uin));
								
		if(/{errCode: 0,/.test(deliverResult)){
			PP.appendRecord('拍拍发货:' + Deal.ID + ' 成功', 1);
			PP.pur5Deliver(Deal);
		}else{
			if(/errCode: 100002,/.test(deliverResult)){//todo:重复订单（重复发货）
				PP.pur5Deliver(Deal);
			}else{
				PP.appendRecord('拍拍发货:' + Deal.ID + ' 失败', 1);
				PP.Data.DealList.Good.$pop(Deal.ID, 'ID');
				PP.Data.DealList.Bad.$push(Deal, 'ID');
				PP.Data.isSavingTrade = false;
				setTimeout(PP.saveTrade, PP.Config.Interval.normal*1000*2);
			}
		}
	},
	pur5Deliver: function(Deal){//平台发货
		PP.appendRecord('平台下单:' + Deal.ID + ' 开始', 1);

		$.ajax({
			url: pur5.Cfg.GBHOSTSOFT + 'paipainew.asp',
			type: 'post',
			dataType: 'text',
			cache: false,
			data: {
				token: pur5.Cfg.token,
				uid: pur5.Cfg.pur5Uid,
				lv: 't2',
				str: Deal._str.$$$(),
				orderid: Deal.ID,
				status: Deal.State,
				ls: pur5.Cfg.pur5PassWordKey
			},
			success: function(data){
				if(data == 'SessionLost' || data == 'ErrorKey'){
					PP.stopMonitor();
					pur5.Pages.ppInputAgainPur5PW2();
					return false;
				}
				if(data == Deal.ID+':0'){
					PP.appendRecord('平台下单:' + Deal.ID + ' 成功', 1);
					
					//充值成功后从Good中弹出
					//alert(Deal.ID);
					PP.Data.DealList.Delivered.$push(Deal.ID, 'ID');
					PP.Data.DealList.Good.$pop(Deal.ID, 'ID');
				}else{
					PP.appendRecord('平台下单:' + Deal.ID + ' 失败:失败号(' + data.split(':')[1] + ')', 1);
					PP.appendRecord(data);
					PP.Data.isGettingTradding = false;
					setTimeout(PP.getTradding, 1000*60);
				}
				
				PP.Data.isSavingTrade = false;
				setTimeout(PP.saveTrade, PP.Config.Interval.normal*1000);
			},
			error: function(jqXhr, textStatus){
				PP.appendRecord('平台下单:' + Deal.ID + ' 错误:<br />' + jqXhr.responseText, 1);
				PP.appendRecord(jqXhr.responseText);
				PP.Data.isSavingTrade = false;
				setTimeout(PP.saveTrade, PP.Config.Interval.normal*1000*2);
			}
		});
	},
	getTradding: function(){//from my Server
		if(PP.Data.isStopMonitor || PP.Data.isGettingTradding) return false;
		
		if(PP.Data.isPauseMonitor){
			setTimeout(arguments.callee, 500);
			return false;
		}
		
		PP.Data.isGettingTradding = true;
		
		$.ajax({
			url: pur5.Cfg.GBHOSTSOFT + 'paipainew.asp',
			type: 'post',
			dataType: 'text',
			cache: false,
			data: {
				uid: pur5.Cfg.pur5Uid,
				token: pur5.Cfg.token,
				lv: 't3',
				ls: pur5.Cfg.pur5PassWordKey
			},
			success: function(data){
				if(data == 'SessionLost' || data == 'ErrorKey'){
					PP.stopMonitor();
					pur5.Pages.ppInputAgainPur5PW2();
					return false;
				}
				
				data = data.replace(/[\[\]]/g,'');
				if(data != ''){
					var dealIds = data.match(/\d+\-\d+\-\d+/g);
					if(dealIds){
						for(var i=dealIds.length; i--;){
							PP.Data.DealList.Tradding.$push(dealIds[i]);
						}
					}
				}
				
				setTimeout(PP.getTradding, PP.Config.Interval.normal*1000*6*4);
			},
			error: function(jqXhr, textStatus){
				PP.appendRecord('t3失败:' + jqXhr.responseText);
				setTimeout(PP.getTradding, PP.Config.Interval.normal*1000*6*4*2);
			}
		});		
	},
	checkOrderOnPP: function(){//from Paipai
		var deal_id = PP.Data.DealList.Tradding[0];
		if(PP.Data.isCheckOrderOnPP || PP.Data.isStopMonitor) return false;
		
		if(PP.Data.isPauseMonitor || !deal_id){
			setTimeout(arguments.callee, 500);
			return false;
		}
		
		PP.Data.isCheckOrderOnPP = true;
		
		var Deal//检查此deal_id的订单
			= PP.get(('http://my.paipai.com/cgi-bin/trade_deal_list/sold'
						+'?start_page=1'
						+'&serial_no=236632'
						+'&g_tk=763425149'
						+'&g_ty=j132'
						+'&deal_id=DEAL_ID'
						+'&page_size=PAGESIZE'
						+'&t=TIME')
							.replace('DEAL_ID', deal_id)
							.replace('PAGESIZE', PP.Config.pageSize)	
							.replace('TIME', Math.random()));

		PP.Data.DealList.Tradding.$pop(deal_id);					
		PP.analysisDealList(Deal, true);
		PP.Data.isCheckOrderOnPP = false;
		setTimeout(arguments.callee, PP.Config.Interval.normal*1000);
	},
	pauseMonitor: function(checked){
		if(!checked){
			PP.Config.Interval.normal = $('#layoutPPJKInputTime').val();
		}
		PP.Data.isPauseMonitor = checked;
		
		$('#layoutPPJKInputSuspend').attr('checked', checked);
		$('#layoutPPJKInputTime').attr('disabled', !checked);
		
		var monitorText = checked?'暂停监控':'正在监控';	
		$('#layoutPPJKInfoText').html(monitorText);
		$('#statusBarMonitorPP').html(monitorText);		
		PP.appendRecord(monitorText, 1);		
	},
	startMonitor: function(){
		PP.Data.DealList.Good = [];
		PP.Data.DealList.Bad = [];
		PP.Data.DealList.Tradding = [];
		
		PP.Data.isPauseMonitor = false;
		PP.Data.isGettingDealList = false;
		PP.Data.isSavingTrade = false;
		PP.Data.isGettingTradding = false;
		PP.Data.isCheckOrderOnPP = false;
		PP.Data.isStopMonitor = false;

		PP.Data.listErrorCount = 0;
		
		var monitorText = '正在监控';
		PP.appendRecord(monitorText, 1);
		
		$('#layoutPPJKInputSuspend').attr('checked', false);
		$('#layoutPPJKInputSuspend').attr('disabled', false);
		$('#layoutPPJKInputTime').attr('disabled', true);
		
		$('#layoutPPJKInputUser').val(PP.Config.userId);
		$('#layoutPPJKTextUser').text(PP.Config.userId);
		$('#layoutPPJKUserNo').text(pur5.Cfg.pur5Uid);
		
		$('#layoutPPJKLoginAfter').show();
		$('#layoutPPJKLoginBefore').hide();
		$('#layoutPPJKInputStart').hide();
		$('#layoutPPJKInputStop').show();
		$('#layoutPPJKInfoText').html(monitorText);
		$('#statusBarMonitorPP').html(monitorText);
		$('#layoutPPJKUserNo').text(pur5.Cfg.pur5Uid);
		$('#layoutPPJKCode').val('');
		$('#PPLoginLine1').css('height', 80);
		
		PP.getDealList();
		setTimeout(function(){
			PP.saveTrade();
			PP.getTradding();
			PP.checkOrderOnPP();
		}, 1000);
		

		if($('#ppBuiedItemCountLimitCheckbox').is(':checked') || $('#ppBlackBlistCheckbox').is(':checked')){//选中了关闭才启用关闭定时器
			PP.Timer.closeTransaction = window.setInterval(function(){
				PP.closeTransaction();
			}, PP.Config.Interval.closeTransaction*1000);
		}
	},
	stopMonitor: function(){
		var monitorText = '停止监控';
		window.clearInterval(PP.Timer.closeTransaction);
		
		PP.Data.isStopMonitor = true;
		PP.Data.isPauseMonitor = true;
		PP.Data.isGettingDealList = true;
		PP.Data.isSavingTrade = true;
		PP.Data.isGettingTradding = true;
		PP.Data.isCheckOrderOnPP = true;
		
		PP.Config.userId = '';
		PP.appendRecord(monitorText, 1);
		
		$('#layoutPPJKInputSuspend').attr('checked', false);
		$('#layoutPPJKInputSuspend').attr('disabled', true);
		$('#layoutPPJKInputTime').attr('disabled', false);
		
		$('#layoutPPJKTextUser').val('');
		$('#layoutPPJKUserNo').text('');
		
		$('#layoutPPJKLoginAfter').hide();
		$('#layoutPPJKLoginBefore').show();
		$('#layoutPPJKInputStart').show();
		$('#layoutPPJKInputStop').hide();
		$('#layoutPPJKInfoText').html(monitorText);
		$('#statusBarMonitorPP').html(monitorText);
		$('#PPLoginLine1').css('height', 54);
	},
	time33: function(str){
		for(var i=0, len = str.length, hash = 5381; i < len; ++i) {
			hash += (hash << 5) + str.charAt(i).charCodeAt();
		}
		return hash&0x7fffffff;
	},
	getToken: function(){
		var skey = PP.Config.userCookies.between('skey=', ';'),
			token = skey == null ? '' : PP.time33(skey);
		return token;
	}
};

var PPOffline = {
	cookies: '',
	qq: '',
	Ds: new ActiveXObject('dsCookieGetter.ds'),
	windowId: (+new Date()) + 'paipai',
	init: function(){
		var self = this;
		
		$('#offlinePPJKButton').click(function(){
			self.loginPP();
		});
		$('#offlinePPSubmit').click(function(){
			self.startTG();
		});
	},
	loginPP: function(){
		this.Ds.CloseWindow(this.windowId);
		this.Ds.AddFilter(".paipai.com");
		//this.Ds.Link('http://member.paipai.com/cgi-bin/login_entry', this.windowId);
		MiniBrowser.openWindow('http://member.paipai.com/cgi-bin/login_entry');
	},
	tradePwd: function(){//输入拍拍交易密码
		var self = this;

		PpTradingPass.show(function(tradeCode){
			var result = self.Ds.httpCookiePost(
					'http://member.paipai.com/cgi-bin/c2clogin?g_tk=G_TK&g_ty=fr'.replace(/G_TK/, self.getToken()),
						self.cookies, 1, 'fill_p=' +  md5(tradeCode), '', '');
									
				if(/<title>交易密码管理<\/title>/.test(result)){
					alert('拍拍交易密码错误，请重新输入！');
					//self.tradePwd();
				}else{
					PpTradingPass.hide();
					self.testGetDealList();
				}
		});		
	},
	testGetDealList: function(){//测试是否能成功取得订单
		var result = this.Ds.httpCookiePost(
			'http://my.paipai.com/cgi-bin/trade_deal_list/sold?deal_state=2&start_page=1&serial_no=33661&page_size=1&t='+ Math.random(),
				this.cookies, 1, '', '', '');
				
		var DealData, code;
		try{
			DealData = $.xml2json(result);
		}catch(e){}
		if(DealData && DealData.Result){
			code = DealData.Result.code;
			if(code == 219){
				this.tradePwd();
			}else if(code == 13){
				alert('拍拍超时,请重新登录拍拍');
			}else if(code == 0){
				this.post();
				//this.getOfflineList();
			}
		}else{
			
		}
	},
	startTG: function(){
		this.Ds.CloseWindow(this.windowId);
		
		//var cookies = this.Ds.GetCookie(this.windowId);
		var cookies = MiniBrowser.getCookie();
		var uinReg = /; uin=(o0+)?(\d+)/;
		
		if(cookies) cookies = cookies.replace(/[\n\r]+/gm, '');
		if(!uinReg.test(cookies)){
			alert('请重新登录拍拍，拍拍登录成功后，再开启离线托管！');
			//this.loginPP();
			return;
		}
		var qq = cookies.match(uinReg)[2];
		
		if($('#offlinePPResult td.qq'+qq).length){
			alert('当前拍拍号已经在离线托管中！');
			return false;
		}
		
		this.cookies = cookies;
		this.qq = qq;
		this.testGetDealList();
	},
	stopTG: function(qq){
		$.ajax({
			url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
			type: 'get',
			cache: false,
			data: {
				token: pur5.Cfg.token,
				lv: 't3',
				ww: qq,
				source: 'paipai'
			},
			success: function(data){
				if(data == '1') {
					$('#offlinePPResult td.qq' + qq).parent().remove();
				} else {
					alert('取消托管失败：' + data);
				}
			},
			error: function(jqXhr){
				alert('取消托管错误：' + jqXhr.responseText);
			}
		});
	},
	getOfflineList: function(){
		var self = this;
		$('#offlinePPResult').children().remove();
		$.ajax({//取已经托管列表
			url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
			type: 'get',
			dataType: 'json',
			cache: false,
			data: {
				token: pur5.Cfg.token,
				lv: 't2',
				source: 'paipai'
			},
			success: function(OfflineList){
				if(!OfflineList.length){
					UI.pop('拍拍托管:未托管！');
					return false;
				}
				var tmp = '<tr><td class="qqqqNumber">qqNumber</td><td>time</td><td class="bluefont">states</td><td><a href="#" class="cancelPPTG" value="qqNumber" title="取消对拍拍qqNumber的离线托管">取消</a></td></tr>';
				$.each(OfflineList, function(i, offlineRow){
					$('#offlinePPResult').append(
						tmp
							//.replace(/pur5Uid/, pur5.Cfg.pur5Uid)
							.replace(/qqNumber/g, offlineRow[0])
							.replace(/time/g, offlineRow[1])
							.replace(/states/g, (offlineRow[2] == 0)?'正常':'关闭')
							.replace(/description/g, offlineRow[3])
					);
					UI.pop('拍拍托管:[' + offlineRow[0] + ']托管中');
				});
				
				$('#offlinePPResult a.cancelPPTG').click(function(){
					if(!confirm('确实要取消拍拍'+$(this).attr('value')+'的离线托管？')) return false;
					self.stopTG($(this).attr('value'));
				});
			},
			error: function(jqXhr, textStatus){
				alert(jqXhr.responseText);
			}
		});
	},
	post: function(){
		var self = this;
		
		$.ajax({//托管
			url: pur5.Cfg.GBHOSTSOFT + 'offline/offline.asp',
			type: 'post',
			cache: false,
			data: {
				token: pur5.Cfg.token,
				lv: 't1',
				ww: this.qq.$$$(),
				cookie: this.cookies.$$$(),
				source: 'paipai'
			},
			success: function(data){
				if(data != '1'){
					alert('托管失败：\n' + data);
					return false;
				}
				self.getOfflineList();
			},
			error: function(jqXhr, textStatus){
				alert('托管错误：\n' + jqXhr.responseText);
			}
		});
		
	},
	time33: function(str){
		for(var i=0, len = str.length, hash = 5381; i < len; ++i) {
			hash += (hash << 5) + str.charAt(i).charCodeAt();
		}
		return hash&0x7fffffff;
	},
	getToken: function(){
		var skey = this.cookies.between('skey=', ';'),
			token = skey == null ? '' : PP.time33(skey);
		return token;
	}

};

$(function(){
	PP.init();
	PPOffline.init();
});


Array.prototype.$pop = function(value, index){
	var Arr = this;
	for(var i=Arr.length; i--;){
		if(index){
			if(Arr[i][index] === value){
				Arr.splice(i, 1);
			}
		}else{
			if(Arr[i] === value){
				Arr.splice(i, 1);
			}
		}
	}
	return Arr;
};

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

pur5.Pages.switchToPPLXTG = function(){//拍拍离线托管
	if(!pur5.Cfg.pur5PassWordKey) {
		TradingPass.show(function(){
			pur5.Pages.setPur5PW2(true, function() {
				pur5.Pages.layoutTo('layoutPpTg');
				PPOffline.getOfflineList();
			});
		});
	} else {
		pur5.Pages.layoutTo('layoutPpTg');
		PPOffline.getOfflineList();
	}
}

pur5.Pages.ppInputAgainPur5PW2 = function() {
	PP.Data.isPauseMonitor = true;
	if($('#inputTradingPass').is(':visible')){
		return false;
	}	
	alert('session超时，请重新输入交易密码！');
	
	TradingPass.show(function(){
		pur5.Pages.setPur5PW2(false, function() {
			PP.Data.isPauseMonitor = false
		});
	});
};