/*!
 * jQuery-ajaxTransport-XDomainRequest - v1.0.3 - 2014-06-06
 * https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
 * Copyright (c) 2014 Jason Moon (@JSONMOON)
 * Licensed MIT (/blob/master/LICENSE.txt)
 */
(function (a) { if (typeof define === 'function' && define.amd) { define(['jquery'], a) } else if (typeof exports === 'object') { module.exports = a(require('jquery')) } else { a(jQuery) } }(function ($) { if ($.support.cors || !$.ajaxTransport || !window.XDomainRequest) { return } var n = /^https?:\/\//i; var o = /^get|post$/i; var p = new RegExp('^' + location.protocol, 'i'); $.ajaxTransport('* text html xml json', function (j, k, l) { if (!j.crossDomain || !j.async || !o.test(j.type) || !n.test(j.url) || !p.test(j.url)) { return } var m = null; return { send: function (f, g) { var h = ''; var i = (k.dataType || '').toLowerCase(); m = new XDomainRequest(); if (/^\d+$/.test(k.timeout)) { m.timeout = k.timeout } m.ontimeout = function () { g(500, 'timeout') }; m.onload = function () { var a = 'Content-Length: ' + m.responseText.length + '\r\nContent-Type: ' + m.contentType; var b = { code: 200, message: 'success' }; var c = { text: m.responseText }; try { if (i === 'html' || /text\/html/i.test(m.contentType)) { c.html = m.responseText } else if (i === 'json' || (i !== 'text' && /\/json/i.test(m.contentType))) { try { c.json = $.parseJSON(m.responseText) } catch (e) { b.code = 500; b.message = 'parseerror' } } else if (i === 'xml' || (i !== 'text' && /\/xml/i.test(m.contentType))) { var d = new ActiveXObject('Microsoft.XMLDOM'); d.async = false; try { d.loadXML(m.responseText) } catch (e) { d = undefined } if (!d || !d.documentElement || d.getElementsByTagName('parsererror').length) { b.code = 500; b.message = 'parseerror'; throw 'Invalid XML: ' + m.responseText; } c.xml = d } } catch (parseMessage) { throw parseMessage; } finally { g(b.code, b.message, c, a) } }; m.onprogress = function () { }; m.onerror = function () { g(500, 'error', { text: m.responseText }) }; if (k.data) { h = ($.type(k.data) === 'string') ? k.data : $.param(k.data) } m.open(j.type, j.url); m.send(h) }, abort: function () { if (m) { m.abort() } } } }) }));

var RemindStrategy = null;
var pageProtocol = location.protocol;

var tools = {
	getHallVersion: function () {
		var version;
		var v = navigator.userAgent.toLowerCase().match(/\s+(qgxf|qg)\/(\S+)/);
		version = v ? v[2] : '0';
		version = version.replace(/\./gm, '');
		return version;
	},
	cookie: {
		get: function (key) {
			var items = document.cookie.split('; ');
			var item = [];
			var size = items.length;
			for (var i = 0; i < size; i++) {
				item = items[i].split('=');
				if (key == item[0] && item.length == 2) {
					return decodeURIComponent(item[1]);
				}
			}
			return '';
		}
	},
	getUin: function () {
		var uin = tools.cookie.get('uin') || tools.cookie.get('p_uin');
		if (uin) return uin.replace(/^o0*/, '');
		return '';
	},
	getCSRFToken: function () {
		var skey = tools.cookie.get('skey');
		var p_skey = tools.cookie.get('p_skey');
		var str = skey ? skey : p_skey;
		str = str ? str : '';
		var hash = 5381;
		for (var i = 0, len = str.length; i < len; ++i) {
			hash += (hash << 5) + str.charAt(i).charCodeAt();
		}
		return hash & 0x7fffffff;
	},
	getUrlParam: function (key) {
		var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
		var r = window.location.search.substr(1).match(reg);
		if (r !== null) return String(unescape(r[2]));
		return '';
	},
	getAppid: function () {
		return tools.getUrlParam('appid');
	},
	parseISO8601: function (dateStringInRange) {
		// var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
		var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*(\d\d):(\d\d):(\d\d)$/,
			date = new Date(NaN), month,
			parts = isoExp.exec(dateStringInRange);
		if (parts) {
			month = +parts[2];
			date.setFullYear(parts[1], month - 1, parts[3]);
			date.setHours(parts[4], parts[5],parts[6]);
			if (month != date.getMonth() + 1) {
				date.setTime(NaN);
			}
		}
		return date;
	}
};

var queryLimit = function (data, bid, success, fail) {
	var key0 = '';
	if (data) {
		for (var i = 0; i < data.length; i += 1) {
			key0 = key0 + data[i].id + '_';
		}
	}

	$.ajax({
		url: window.location.protocol + '//seed.minigame.qq.com/querylimit',
		data: {
			key0: key0.slice(0, -1),
			bid: bid,
			g_tk: tools.getCSRFToken()
		},
		dataType: 'jsonp',
		contentType: 'application/json',
		crossOrigin: true,
		xhrFields: {
			withCredentials: true
		},
		success: function (res) {
			if (res.result === 0) {
				success(res.limit);
			} else {
				success(false);
			}
		},
		error: function () {
			fail(false);
		}
	});
};

var filterLimit = function (showFrequency, limitInfo) {
	/*var key = 'total_uin_limit_cnt';
    var usedkey = 'total_uin_used_cnt';
    switch (showFrequency) {
      case 2:
        key = 'year_uin_limit_cnt';
        usedkey = 'year_uin_used_cnt';
        break;
      case 3:
        key = 'month_uin_limit_cnt';
        usedkey = 'month_uin_used_cnt';
        break;
      case 4:
        key = 'week_uin_limit_cnt';
        usedkey = 'week_uin_used_cnt';
        break;
      case 5:
        key = 'day_uin_limit_cnt';
        usedkey = 'day_uin_used_cnt';
        break;
      default:
        break;
    }*/
    /*if (
      limitInfo[key] == 0 ||
      (limitInfo[usedkey] < limitInfo[key] &&
        (limitInfo['total_uin_used_cnt'] < limitInfo['total_uin_limit_cnt'] || limitInfo['total_uin_limit_cnt'] === 0))
    ) {*/
	if (limitInfo.limit_result == 0) {
		// 使用次数小于限制次数或者没有限制
		return true;
	} else {
		return false;
	}
};

var reportLimit = function (id) {
	$.ajax({
		url: window.location.protocol + '//seed.minigame.qq.com/checklimit',
		dataType: 'jsonp',
		contentType: 'application/json',
		data: {
			key0: id,
			bid: 'hall_enter_game_float',
			g_tk: tools.getCSRFToken()
		}
	});
}

var popupIframe = function (src, timeout) {
	var iframe = document.createElement('iframe');
	iframe.src = src;
	iframe.width = '100%';
	iframe.height = '100%';
	iframe.frameBorder = '0';
	iframe.scrolling = 'no';
	//iframe.allowTransparency = 'true';
	iframe.style['z-index'] = '9999';
	iframe.style.position = 'absolute';
	iframe.style['top'] = '0';
	iframe.style['left'] = '0';
	//iframe.style['background-color'] = 'transparent';

	document.body.appendChild(iframe);
	return iframe;
};

var checkVouchers = function (id, result) {
	$.ajax({
		url: '//go.minigame.qq.com/gift_svr/fetch',
		dataType: 'jsonp',
		data: {
			json: "{\"scene\":\"hallfloatwin\",\"id\":".concat(Number(id), "}")
		},
		success: function success(res) {
			if (res.Result === 0) {
				if (res.GiftStatus === 0) {
					result(true);
				} else {
					result(false);
				}
			}
		}
	});
}

var bindCloseEvent = function (iframe) {
	iframe;
	window.__closeAlertDialog = function () {
    window.isExpiredLimit()
		document.body.removeChild(iframe);
	};

	function onClose(e) {
		if (e.data === '__closeAlertDialog') {
			window.__closeAlertDialog();
		}
	}

	if (window.addEventListener) {
		window.addEventListener("message", onClose, false);
	} else if (window.attachEvent) {
		window.attachEvent("onmessage", onClose);
	}
}

var getEnterGameStrategy = function (cb) {
	$.ajax({
		url: window.location.protocol + '//go.minigame.qq.com/gray_strategy/gray_strategy',
		data: {
			bid: 'hall_enter_game',
			hver: tools.getHallVersion(),
			webrequest: 1,
      mainstartchannel: tools.getUrlParam('main_install_cid') || '0',
			from: Number(tools.getAppid()),
      webgamesource: window.external.callHallApi ? 1 : 2
		},
		dataType: 'jsonp',
		success: function (res) {
			if (res.RetCode === 0 && res.RuleData && res.RuleData.hall) {
				headpageList = res.RuleData.hall.enter_game;
				var availablePageList = [];
				var headpages = []; // 其他类型
				var expiredpages = []; // 过期游券
				for (var i = 0; i < headpageList.length; i += 1) {
					if (headpageList[i].template_type === 3) {
						expiredpages.push(headpageList[i]);
					} else {
						headpages.push(headpageList[i]);
					}
				}
			  window.isExpiredLimit =	function isExpiredLimit() {
					queryLimit(expiredpages, 'hall_quan_expire_float', function (expirelimit) { // 开始和结束游戏时单独查询一次过期游券限制
						if (expirelimit) {
							for (var i = 0; i < expiredpages.length; i += 1) {
								var id = expiredpages[i].id;
								if (expirelimit[id]) {
									if (filterLimit(expiredpages[i].show_frequency, expirelimit[id])) {
										RemindStrategy = expiredpages[i];
									}
								}
								else {
									// 次数限制，不曝光
									report({
										field1: 2019081901, 
										field2: 41013,
										field3: 40810045,
										field4: id,
										field16: headpages[i] ? headpages[i].template_type : -1,  // 类型
										field17: 1 // 未曝光原因（优先级=0，次数限制=1，其他=2）
									});
								}
							}
              console.timeEnd()
							//将图文放到一个队列中，优先级高的不展示后，再展示过期提醒
						if (availablePageList.length > 0) {
							availablePageList.sort(function (a, b) { return b.priority - a.priority });
							var availablePage = availablePageList[0];
							if (availablePage.template_type === 1 || availablePage.template_type === 0) {
								//图文视频直接展示
							  window.setTimeout(function () {
									var iframe = popupIframe(availablePage.url);
									reportLimit(availablePage.id);
									bindCloseEvent(iframe);
                  // 如果显示时长则定时关闭
                  if(Number(availablePage.show_duration)){
                    setTimeout(function(){
                      if(bindCloseEvent){
                        window.__closeAlertDialog(iframe)
                      }
                    },availablePage.show_duration * 1000)
                  }
                  availablePageList.splice(0,1);
                  if(!iframe){
                    isExpiredLimit();
                  }
								}, (window.parseInt(availablePage.show_time) * 1000 || 0));
								cb(true);
							} else if (availablePage.template_type === 2) {
								//游劵领取判断是否领取过
								checkVouchers(availablePage.id, function (show) {
									if (show === true) {
										window.setTimeout(function () {
											var iframe = popupIframe(availablePage.url);
											reportLimit(availablePage.id);
											bindCloseEvent(iframe);
                       // 如果显示时长则定时关闭
                      if(Number(availablePage.show_duration)){
                        setTimeout(function(){
                          if(bindCloseEvent){
                            window.__closeAlertDialog(iframe)
                          }
                        },availablePage.show_duration * 1000 )
                      }
                      availablePageList.splice(0,1);
                      if(!iframe){
                        isExpiredLimit();
                      }
										}, (window.parseInt(availablePage.show_time) * 1000 || 0));
										cb(true);
									} else {
										//已领取，查看是否有过期提醒
										cb(false);
										// 不曝光
										report({
											field1: 2019081901, 
											field2: 41013,
											field3: 40810045,
											field4: id,
											field16: headpages[i].template_type,  // 类型
											field17: 2 // 未曝光原因（优先级=0，次数限制=1，其他=2）
										});
									}
								})
							}

							// 曝光统计
							report({
								field1: 2019081901, 
								field2: 41013,
								field3: 40810044,
								field4: availablePage.id,
								field16: availablePage.template_type  // 类型
							});
							// 剩下的都不显示。未曝光打点
							for (var i = 1; i < availablePageList.length; i++) {
								report({
									field1: 2019081901, 
									field2: 41013,
									field3: 40810045,
									field4: availablePageList[i].id,
									field16: availablePageList[i].template_type,  // 类型
									field17: 0 // 未曝光原因（优先级=0，次数限制=1，其他=2）
								});                  
							}
						}
						else {
							cb(false);
						}
						}
					});
				}
				if (headpages.length === 0) {
					isExpiredLimit();
				} else {
					queryLimit(headpages, 'hall_enter_game_float', function (limit) {
						if (limit) {
							for (var i = 0; i < headpages.length; i += 1) {
								var id = headpages[i].id;
								var show_frequency = headpages[i].show_frequency;
								RemindStrategy = headpages[i];   //test code
								if (limit[id]) {
									if (filterLimit(show_frequency, limit[id])) {
										availablePageList.push(headpages[i]);
									}
								}
							}
							isExpiredLimit();
						}
					})
				}
			}
		}
	});
};

//获取背包中是否有满足条件提醒过期的游劵
var getRemindVouchers = function (id, cb) {
	var expiredQuanList = [];
	var curAppid = Number(tools.getAppid());

	$.ajax({
		url: '//go.minigame.qq.com/social/package_svr/query_quan',
		dataType: 'jsonp',
		success: function success(res) {
			if (res.Result === 0 && res.QuanList) {
				for (var i = 0; i < res.QuanList.length; i += 1) {
					var appids = res.QuanList[i].Appid;
					for (var j = 0; j < appids.length; ++j) {
						if (appids[j] === curAppid) {
							expiredQuanList.push(res.QuanList[i]);
							break;
						}
					}
				}

				if (expiredQuanList.length === 0) {
					cb(expiredQuanList);
					return;
				}

				$.ajax({
					url: '//ngo.minigame.qq.com/web_config_center_svr/get_data?objectid='+ id +'&appid=qqgame&schemaid=common_tb_hallfloatwin&appkey=0a3c07e2e734438784f2a5e451cdeff0',
					dataType: 'jsonp',
					success: function success(res) {
						if (res.Result === 0 && res.DBData) {
							var remindQuanList = [];
							var reminddays = res.DBData.effectTimeRemind;
							for (var i = 0; i < expiredQuanList.length; ++i) {
								//IE7date无法传参
								// var end= tools.parseISO8601(expiredQuanList[i].EndTime).getTime();
								var end = tools.parseISO8601(expiredQuanList[i].End).getTime();
								var now = new Date().getTime();
								if ((end - now) < (reminddays * 24 * 60 * 60 * 1000)) {
									remindQuanList.push(expiredQuanList[i]);
								}
							}
							cb(remindQuanList);
						}
						else {
							cb([]);
						}
					}
				});
			}
		}
	});
}

var getGrayStrategy = function () {
	getEnterGameStrategy(function (res) {
		if (res === false) {
			if (RemindStrategy !== null) {
				getRemindVouchers(RemindStrategy.id, function (list) {
					if (list.length > 0) {
						window.setTimeout(function () {
							var url = 'https://minigame.qq.com/voucher-dialog/index.html?id='.concat(RemindStrategy.id, '&appid=', Number(tools.getAppid()), '&subbid=gamequan_outdate');
							var iframe = popupIframe(url);
							reportLimit(RemindStrategy.id);

							bindCloseEvent(iframe);
						}, (window.parseInt(RemindStrategy.show_time) * 1000 || 0));
					}
				});
			}
		}
	});

};

  
getGrayStrategy();



//广告位生成
creatAdver('//minigame.qq.com/plat/social_hall/app_frame/page_adver/adver.css');
function creatAdver(url) {
	var link = document.createElement("link");
	link.setAttribute("rel", "stylesheet");
	link.setAttribute("type", "text/css");
	link.setAttribute("href", url);
	document.getElementsByTagName('head')[0].appendChild(link);
	var div = document.createElement('div');
	div.className = "tips";
	div.id = "tips";
	var p = document.createElement('p');
	p.className = "tips-txt";
	p.id = "tips-txt";
	var a = document.createElement('a');
	a.href = 'javascript:;';
	a.className = 'tips-close';
	a.id = 'tips-close';
	a.title = '关闭';
	var img = document.createElement('img');
	img.className = 'tips-img';
	img.id = 'tips-img';
	document.getElementsByTagName('body')[0].appendChild(div);
	div.appendChild(p);
	div.appendChild(a);
	div.appendChild(img);
}
//获取微端
function getWeiduan() {
	//https://minigame.qq.com/plat/social_hall/app_frame/index_v2.html?appid=11045&hall=5.18.56865.0&wd=1.2.1.2
	var search = location.search.slice(1);
	var searchArray = search.split('&');
	var obj = {};
	for(var i = 0; i < searchArray.length; i += 1) {
		var secArray = searchArray[i].split('=')
		obj[secArray[0]] = secArray[1]
	}
	if(obj.hall) {
		return Number(obj.hall.replace(/\./g, ""));
	}
	return 0
}

//判断win10
function win10() {
	var userAgent = navigator.userAgent.toLowerCase();
	// alert(userAgent)
	if(userAgent.indexOf("windows nt 6.2") > -1 || userAgent.indexOf("windows nt 6.3") > -1 || userAgent.indexOf("windows nt 6.4") > -1 ||userAgent.indexOf("windows nt 10") > -1) {
		return true
	}else {
		return false
	}
}

function checkLogin(callback) {
	var getcs = tools.getCSRFToken()
	var checkCgi = pageProtocol + '//dir.minigame.qq.com/cgi-bin/dir_check_login?g_tk=' + getcs + '&';
	$.ajax({
		url: checkCgi + Math.random(),
		dataType: 'jsonp',
		scriptCharset: 'gb2312',
		success: function (data) {
			// 对比微端版本
			if (data.result == 0) {
				if(getWeiduan() < 1212) {
					if(win10()) {
						callback(false);
					}else {
						callback(true);
					}
				}else{
					callback(true);
				}
			} else {
				callback(false);
			}
		}
	});
}

//广告位展示he跳转
function isLogin(isLog) {
	if (isLog) {
		//获取广告位数据
		function getAdver(callback) {
			$.ajax({
				url: '//node.minigame.qq.com/getcommondata?tbid=71&needfields=app_id|ad_url|open_url|ad_text|start_time|end_time',
				dataType: 'jsonp',
				success: function (data) {
					callback(data.data);
				}
			})
		}
		function resolveInfo(tipsinfo) {
			for (var i = 0; i < tipsinfo.length; i++) {
				if (tipsinfo[i].app_id == tools.getAppid()) {
					var starTime = tipsinfo[i].start_time.replace(/\-/g, '/');
					var endTime = tipsinfo[i].end_time.replace(/\-/g, '/');
					var DateNow = new Date();
					var now = DateNow.getTime();
					if (now > new Date(starTime).getTime() && now < new Date(endTime).getTime()) {
						$('#tips').css({ 'display': 'block' });
						setTimeout(function () {
							$('#tips').css({ 'displays': 'none' });
						}, 120000)
						break
					} else {
						continue
					}
				} else {
					$('#tips').css({ 'display': 'none' });
				}
			}
			if (tipsinfo[i]) {
				$('#tips-txt').text(tipsinfo[i].ad_text);
				$('#tips-img').attr('src', tipsinfo[i].ad_url);
			}
			$('#tips').on('click', function (e) {
				if (e.target.className == 'tips-txt' || e.target.className == 'tips-img') {
					adverReport({ field2: 41103, field3: 40810052, field11: 1 });
					window.open(tipsinfo[i].open_url);
				}
			})
		}
		getAdver(resolveInfo);
	}
}
// checkLogin(isLogin);

//数据上报
function adverReport(data) {
	var fields = (function () {
		var param = {};
		for (var i = 0; i < 26; i++) {
			param['field' + i] = -1;
			if (data['field' + i] || data['field' + i] == 0) param['field' + i] = data['field' + i];
		}
		return param;
	})();
	var loca = window.location.href;
	var qqgame = loca.match(/qqgame.qq.com/);
	if(qqgame) {
		$.ajax({
			url: '//log.minigame.qq.com/cgi-bin/dir_tlog',
			dataType: 'jsonp',
			data: $.extend(fields, {
				structname: 'webCommonReport',
				fieldcount: 26,
				field0: 40034,
				field1: 2019071001,
				field7: tools.getAppid()
			})
		});
	}else {
		$.ajax({
			url: '//log.minigame.qq.com/cgi-bin/dir_tlog',
			dataType: 'jsonp',
			data: $.extend(fields, {
				structname: 'webCommonReport',
				fieldcount: 26,
				field0: 40034,
				field1: 2019071801,
				field7: tools.getAppid()
			})
		});
	}
	
}

adverReport({field2: 41101, field3: 40810050});

function report(data) {
	var fields = (function () {
		var param = {};
		for (var i = 0; i < 26; i++) {
			param['field' + i] = -1;
			if (data['field' + i] || data['field' + i] == 0) param['field' + i] = data['field' + i];
		}
		return param;
	})();
	$.ajax({
		url: '//log.minigame.qq.com/cgi-bin/dir_tlog',
		dataType: 'jsonp',
		data: $.extend(fields, {
			structname: 'webCommonReport',
			fieldcount: 26,
			field0: 40034,
			field7: tools.getAppid()
		})
	});
}

//广告位点击关闭
$('#tips-close').on('click', function (e) {
	e.preventDefault();
	adverReport({ field2: 41103, field3: 40810052, field11: 0 });
	$('#tips').hide();
})

//兼容ie样式响应
$(window).resize(function () {
	screenRespond();
});
function screenRespond() {
	var screenWidth = $(window).width();
	if (screenWidth <= 1440) {
		$("body").attr("class", "w1440");
	}
	if (screenWidth > 1440) {
		$("body").attr("class", "");
	}
}
screenRespond();

/**右下角广告相关逻辑，iframe的显示和隐藏由ad_page页面调用*/
function initAdPage(){

	function optAdPage(e){
		if (e && e.data && typeof e.data === 'string') {
			var msg = e.data.split('|');
			if(msg[0] == 'showAdPage'){
				var width = parseInt(msg[1], 10);
				$('#ad_page').width(width>=1440 ? 260 : 208);
				$('#ad_page').height(width>=1440 ? 360 : 288);
				$('#ad_page').show();
			} else if(e.data == 'hideAdPage'){
				$('#ad_page').hide();
			}
		}
	}

	if (window.addEventListener) {
		window.addEventListener("message", optAdPage, false);
	} else if (window.attachEvent) {
		window.attachEvent("onmessage", optAdPage);
	}
	
	var from = (location.host == 'qqgame.qq.com') ? 2 : 1;
	var iframe = document.createElement('iframe');
	iframe.id = 'ad_page';
	iframe.src = '//minigame.qq.com/ad_page/index.html?appid='+tools.getAppid()+'&from='+from;
	iframe.width = '260px';
	iframe.height = '360px';
	iframe.frameBorder = '0';
	iframe.scrolling = 'no';
	iframe.style['z-index'] = '9999';
	iframe.style.position = 'absolute';
	iframe.style['bottom'] = '0';
	iframe.style['right'] = '0';
	iframe.style['display'] = 'none';
	document.body.appendChild(iframe);
}

initAdPage();


(function() {
	if (location.host === 'minigame.qq.com') return;

	function report(data) {
		var fields = (function () {
			var param = {};
			for (var i = 0; i < 26; i++) {
				param['field' + i] = -1;
				if (data['field' + i] || data['field' + i] == 0) param['field' + i] = data['field' + i];
			}
			return param;
		})();
		$.ajax({
			url: '//log.minigame.qq.com/cgi-bin/dir_tlog',
			dataType: 'jsonp',
			data: $.extend(fields, { structname: 'webCommonReport', fieldcount: 26, field0: 40034 })
		});
	}

	report({ field1: 2021092701, field2: 919, field3: 40900705, field7: tools.getAppid() });

	function fetchIsJudge(cb) {
		$.ajax({
			url: '//go.qqgame.qq.com/HealthSystem/JudgeLogin',
			dataType: 'jsonp',
			success: function(res) {
				if (res.Result === 3) {
					cb(false);
				} else {
					cb(true);
				}
			},
			error: function() {
				cb(true);
			}
		});
	}

	fetchIsJudge(function (result) {
		if (result) { return; }
		$('body').append('<div id="judge-mask" style="width: 100%; height: 100%; position: fixed; background: rgb(0, 0, 0); opacity: 0.5; z-index: 10000"></div>');
		$('body').append('<div id="judge-container" class="g-dialog g-dialog-msg" style="position: fixed; z-index: 10001; top: 50%; left: 50%; margin-top: -74px; margin-left: -191px;"><div class="dialog-header"><h3 class="dialog-title">温馨提示</h3></div><div class="dialog-body"><div class="msg-content"><i class="g-msg-icon-warn"></i><div class="msg-text">亲爱的玩家，您的账号尚未实名认证，为了您的账号和财产安全，我们根据国家政策要求，邀您进行实名认证，实名认证后即可畅玩游戏！</div></div><div class="dialog-btnbar"><a href="javascript:;" class="dialog-btn" id="goto-judge">去认证</a></div></div></div>');
		report({ field1: 2019121001, field2: 919, field3: 40900705, field16: 0 });
		$('#goto-judge').on('click', function() {
			if (!$(this).attr('data-text')) {
				report({ field1: 2019121001, field2: 919, field3: 40900705, field16: 1 });
				$(this).text('我已认证');
				$(this).attr('data-text', 'wyrz');
				window.open('https://jiazhang.qq.com/zk/index.html?source=qqgame&appid=hp3fe05ab7432579a0', '_blank');
			} else {
				fetchIsJudge(function (result1) {
					if (result1) {
						$('#judge-mask').remove();
						$('#judge-container').remove();
						report({ field1: 2019121001, field2: 919, field3: 40900704, field16: 0 });
					} else {
						report({ field1: 2019121001, field2: 919, field3: 40900704, field16: 1 });
						window.open('https://jiazhang.qq.com/zk/index.html?source=qqgame&appid=hp3fe05ab7432579a0', '_blank');
					}
				});
			}
		});
	});

	function fetchStatus(cmd, callback) {
		$.ajax({
			url: '//go.qqgame.qq.com/GameLogin/'.concat(cmd),
			dataType: 'jsonp',
			data: {
				Page: 'web',
				AppID: tools.getUrlParam('appid'),
				Duration: 300,
				AuthUserType: 11,
				Uin: tools.getUin(),
				AuthKey: tools.cookie.get("p_skey"),
				DomainID: tools.cookie.get("DomainID")
			},
			success: function(response) {
				if (response.Result === 0) {
					if (response.Instruction === 1 && response.Msg) {
						window.alert(response.Msg);
					} else if (response.SDOption === 1 && response.SDTips) {
						window.alert(response.SDTips);
					} else if (response.Instruction === 2 && response.Msg) {
						$('#iframe_app').remove();
						window.alert(response.Msg);
						window.location.href = 'https://qqgame.qq.com';
					} else if (response.SDOption === 2 && response.SDTips) {
						$('#iframe_app').remove();
						window.alert(response.SDTips);
						window.location.href = 'https://qqgame.qq.com';
					} else if (response.Instruction === 3 && response.Url) {
						$('#iframe_app').remove();
						window.open(response.Url, "__blank");
					}
					if (typeof callback === "function") {
						callback();
					}
				}
			}
		});
	}

	setTimeout(function() {
		fetchStatus('CheckStartGame', function() {
			fetchStatus('Login');
		});
	}, 2 * 1000);

	setInterval(function() {
		fetchStatus('Online');
	}, 5 * 60 * 1000);
})();