var gIsSnsAdsExists = 0;

function getCurEnv() {
    var pathName = location.pathname;

    if (pathName.indexOf('/app_frame/index_v4.html') !== -1) {
        return 'hall';
    } else if (pathName.indexOf('/webappframe/') !== -1) {
        return 'pc';
    } else if (pathName.indexOf('/app_frame/index_mobile.html') !== -1) {
        return 'mobile';
    } else {
        return '';
    }
}

function getSdkHost(isTest) {
    var env = getCurEnv();

    if (env === 'pc') {
        return '//sdk.qqgame.qq.com';
    } else {
        return isTest ? '//testsdk.minigame.qq.com:80' : '//sdk.minigame.qq.com';
    }
}

function handleResponse(response) {
    if (typeof response.result === 'number') {
        response.ret = response.result;
        response.msg = response.resultstr;
        delete response.result;
        delete response.resultstr;
    }

    return response;
}

function handleError(e) {
    return {
        ret: -1,
        msg: e.message || e.statusText || 'request error'
    }
}

// qqgame js api, need jquery
function QQGameAPI()
{
    var _api = this;
    var _version = '';
	//这里的this==window,下面定义的函数和对象全部等同于全局函数和对象
    this.report_stat = function(rid, rint)
    {
        $.getJSON(window.location.protocol + "//log.minigame.qq.com/cgi-bin/qqgame_web_report?callback=?&", 
        {"rid": rid, "rint":rint.join('_')}, 
        function()
        {
        });
    } 
    
    this.Aux =
    {
        get_cookie: function(name)
        {
            var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
            if(arr != null)
            {
                    return unescape(arr[2]);
            }
            
            return "";
        },
        
        set_cookie: function(name, value, domain)
        {
            domain = domain || "qq.com";
            document.cookie = name + "=" + value + "; path=/; domain=" + domain;
        },

        set_cookie_max_age: function(name, value, maxAge, domain)
        {
            domain = domain || "qq.com";
            document.cookie = name + "=" + value + "; path=/; domain=" + domain + '; max-age=' + maxAge ;
        },
        
        delete_cookie: function(name, domain)
        {
            set_cookie(name, "", domain);
        },
        
        get_url_param: function(search)
        {
            var args = {};
            var search = search || location.search;
            if (search.length > 1)
            {
                var query=search.substring(1);
                var pairs=query.split("&");
                for(var i=0; i < pairs.length; i++ )
                {
                    var pos=pairs[i].indexOf('=');
                    if(pos==-1)   continue;
                    var argname=pairs[i].substring(0,pos);
                    var value=pairs[i].substring(pos+1);
                    args[argname]=decodeURIComponent(value);
                }
            }
            return args;
        }, 
        
        get_hash_param: function(hash)
        {
            var args = {};
            var hash = hash || location.hash;
            if (hash.length > 1)
            {
                var query=hash.substring(1);
                var pairs=query.split("&");
                for(var i=0; i < pairs.length; i++ )
                {
                    var pos=pairs[i].indexOf('=');
                    if(pos==-1)   continue;
                    var argname=pairs[i].substring(0,pos);
                    var value=pairs[i].substring(pos+1);
                    args[argname]=decodeURIComponent(value);
                }
            }
            
            return args;
        },
        
        make_string: function(param)
        {
            var str = '';
            for (var i in param)
            {
                str += i + '=' + param[i] + '&';
            }
            
            if (str.length > 0)
            {
                str = str.substr(0, str.length - 1);
            }
            
            return str;
        }, 
        
        str2int: function(str)
        {
            var i = 0;
            try{i=parseInt(str);}catch(e){}
            return isNaN(i)? 0 : i;
        },
        json_stringify: function (obj)
        {
            if (typeof JSON !== 'undefined') {
                return JSON.stringify(obj);
            }
            var t = typeof (obj);
            if (t == 'undefined') {
                return;
            }
            if (t != "object" || obj === null) {

                // simple data type
                if (t == "string") obj = '\"'+obj+'\"';
                return String(obj);
            }
            else 
            {
                // recurse array or object
                var n, v, json = [], arr = (obj && obj.constructor == Array);

                for (n in obj) {
                    v = obj[n]; t = typeof(v);
                    n = n.replace(/\"/g, '\\"');
                    if (t == "string") {
                        v = '\"'+v.replace(/\"/g, '\\"')+'\"';
                    } else if (t == "object" && v !== null) {
                        v = this.json_stringify(v);
                        if (v == 'undefined') {
                            continue;
                        }
                    } else if (t == 'undefined') {
                        continue;
                    }
                    
                    json.push((arr ? "" : '\"' + n + '\":') + String(v));
                }

                return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
            }
        },
        get_csrf_token: function() {
            var skey = _api.Aux.get_cookie("skey");
            var p_skey= _api.Aux.get_cookie("p_skey");
            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;
        },

        post_cross_domain: function(url, data, success, error, dataType, option) {
            data = data || {};
            data.g_tk = _api.Aux.get_csrf_token();
            (function() {
                var str = 'ajax_post_obj_'+parseInt(Math.random()*10000000000);
                var $iframe = null;
                document[str] = $.extend({
                    url: url,
                    data: data,
                    type: 'POST',
                    success: function(data) {
                        document[str] = null;
                        try {
                            $iframe && $iframe.remove();
                            $iframe = null;
                        } catch(_) {}
                        success(data);
                    },
                    error: function(e) {
                        try {
                            $iframe && $iframe.remove();
                            $iframe = null;
                        } catch(_) {}
                        error && error(e);
                    },
                    dataType: dataType || null
                }, option || {});
                var host = '';
                var prefix = '', suffix = '';
                if(url.indexOf('seed') == 7) {
                    prefix = 'seed';
                    suffix = 'CommonProxyCrossDomain';
                } else if(url.indexOf('nseed') == 7) {
                    prefix = 'nseed';
                    suffix = 'CommonProxyCrossDomain';
                } else if(url.indexOf('dir') == 7) {
                    prefix = 'dir';
                    suffix = 'jqproxy.html';
                } else if (url.indexOf('actp') == 7) {
                    prefix = 'actp';
                    suffix = 'business/Proxy/CommonProxyCrossDomain';
                } else if (url.indexOf('actp') == 12) {
                    prefix = 'test.actp';
                    suffix = 'business/Proxy/CommonProxyCrossDomain';
                } else if (url.indexOf('node') == 7) {
                    prefix = 'node';
                    suffix = 'proxypage';
                }
                if (prefix != '') {
                    host = prefix + '.minigame.qq.com';
                } else {
                    host = 'minigame.qq.com';
                }

                var $iframe = $('<iframe style="display:none" src=window.location.protocol + "//'+host+'/'+suffix+'?'+str+'"></iframe>');
                $(document.body).append($iframe);
            })();
        },

        exec_protocol :function(url) {
            var body = document.getElementsByTagName('BODY').item(0);
            var _iframe = document.getElementById('__qqgame_protocol_iframe__');
            if (_iframe) {
                body.removeChild(_iframe);
            }
            _iframe = document.createElement('IFRAME');
            _iframe.id = '__qqgame_protocol_iframe__';
            _iframe.style.display = 'none';
            body.appendChild(_iframe);
            _iframe.src = url;
        }

    }
    
    this.CallAPI = function(api, m, p, s, f)
    {
        var baseURL = (function() {
            if (window.location.hostname === 'qqgame.qq.com') {
                return 'https://lobby.qqgame.qq.com';
            }
            return 'https://lobby.minigame.qq.com';
        })();
        var emptyfunc = function(){};
        s = s || emptyfunc;
        f = f || emptyfunc;
        var opt = 
        {
            cache: false, 
            data: p, 
            dataType: "jsonp", 
            error: f, 
            success: s, 
            type: m, 
            url: baseURL + "/cgi-bin/"+api+"?callback=?"
        };
        $.ajax(opt);
    }
    
    this.CreateDlg = function(id, html, width, height)
    {
        var doc_obj = $(document);
        //var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2;
        //var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
		
		var p = [0, 0];
		var psw = doc_obj.scrollLeft(), ww = doc_obj.width(), psh = doc_obj.scrollTop(), wh = doc_obj.height();
		p[0] = psw + (ww - width)/2;
		p[1] = psh + (wh - height)/2;
		
		//超出右侧
		(p[0] + width) > (psw + ww) ? (p[0] = psw + ww - width) : "";
		//超出底部
		(p[1] + height) > (psh + wh) ? (p[1] = psh + wh - height) : "";
		//超出顶部
		p[1] < psh ? p[1] = psh + 20 : "";
		//超出左侧
		p[0] < psw ? p[0] = psw + 8 : "";
		var top = p[1];
        var left = p[0];
		
        var dlg_html = '<div id="'+id+'" style="display:none;overflow:hidden;border:solid #00D2FF 1px;z-index:9999;position:absolute;width:'+width+'px;height:'+height+'px;top:'+top+'px;left:'+left+'px;margin:0px;padding:0px;">'+html+'</div>';
        var dlg_obj = $(dlg_html);
        $('body').append(dlg_obj);
        return dlg_obj;
    }
    
    this.CreateMask = function(id, opacity, zidx)
    {
        var dlg_obj = $("#"+id)[0];
        if(typeof dlg_obj !="undefined"){
            dlg_obj.style.display="block";
        }else{
            var doc_obj = $(document);
            // var dlg_html = '<div id="'+id+'" style="display:block;z-index:'+zidx+';position:absolute;width:'+doc_obj.width()+'px;height:'+doc_obj.height()+'px;top:0px;left:0px;margin:0px;padding:0px;filter:alpha(opacity='+opacity+');opacity:'+opacity/100+';background-color:#000000"></div>';
            
			
			var appid = 0;
			var url_params = _api.Aux.get_url_param();
			for (i in url_params)
			{
				if (i != 'appid')
					continue;
				appid = url_params[i];
			}
			
			if(appid != 0 && window.g_loginBackImg && window.g_loginBackImg[appid]){
				dlg_html = '<div id="'+id+'" style="display:block;z-index:'+zidx+';position:absolute;width:'+doc_obj.width()+'px;height:'+doc_obj.height()+'px;top:0px;left:0px;margin:0px;padding:0px;background-color:#000000">\
								<img src='+window.g_loginBackImg[appid]+' style="display: block; position: absolute; top: 0; left: 50%; min-width: 1100px; z-index: 9; width:1920px; margin-left: -960px;">\
								<span style="display: block; width: 100%; height: 100%; background: #000; position: absolute; top: 0; left: 0; z-index: 10; filter:alpha(opacity=40); opacity: .4;"></span>\
							</div>';
			}else {
				dlg_html = '<div id="'+id+'" style="display:block;z-index:'+zidx+';position:absolute;width:'+doc_obj.width()+'px;height:'+doc_obj.height()+'px;top:0px;left:0px;margin:0px;padding:0px;filter:alpha(opacity='+opacity+');opacity:'+opacity/100+';background-color:#000000"></div>';
			}
			
			
			dlg_obj = $(dlg_html);
            $('body').append(dlg_obj);
        }
        return dlg_obj;
    }

    this.ShowLoginDlg = function(jumpurl, proxyurl)
    {
		jumpurl = jumpurl || location.href;
		function str2JSON(str){
            eval('var __pt_json='+str);
            return __pt_json;
        }
        //此处为message监听事件，放入此方法体如已登录则不需要执行监听
        if(typeof  window.postMessage!=="undefined"){
            window.onmessage=function(event){
                var msg = event || window.event; // 兼容IE8
                var data;
                if(typeof  JSON!=="undefined"){
                    data=JSON.parse(msg.data);
                }else{
                    data = str2JSON(msg.data);
                }
                switch(data.action){
                    case "close":
                        ptlogin2_onClose();
                        break;
                    case "resize":
                        ptlogin2_onResize(data.width,data.height);
                        break;
                    default :
                        break;
                }
            }
        }
		
		if(typeof window.postMessage !== 'undefined')
		{
			function handle(event) {
				var msg = event || window.event; // 兼容IE8
				if(msg.origin.indexOf('qq.com') < 0) return;
				var data = null;
				try{
					if (typeof  JSON !== 'undefined')
					data = JSON.parse(msg.data);
				else
					data = str2JSON(msg.data);
				}catch(_){}
				if(data.op == 'refresh')
				{
					location.href = jumpurl;
				}
			}
			if(typeof window.addEventListener == 'function')
			{
				window.addEventListener('message',handle);
			}
			else
			{
				window.attachEvent('onmessage',handle);
			}
		} else {
			navigator.__refreshLoginCallback = function(msg) {
				var data = str2JSON(msg);
				if(data.op == 'refresh')
				{
					location.href = jumpurl;
				}
			}
		}
		
		var purl = window.location.protocol + '//minigame.qq.com/other/loginproxy.html?refresh=1';
		
        //此处有bug 应该是location.href
        
        //设置同域IE6，7通讯代理页面
        //proxyurl = proxyurl || "//"+ window.location.host+ "/social_hall/app_frame/proxy.html";
		proxyurl = proxyurl || window.location.protocol + "//" + (window.location.host=="minigame.qq.com" ? "minigame.qq.com/plat" : "qqgameplatcdn.qq.com") + "/social_hall/app_frame/ptlogin_proxy.html";
        // create mask
        var mask_obj = _api.CreateMask("ptlogin_mask", 40, 1000);

        //create login_div
        if(typeof $("#login_div")[0]=="undefined"){
          var str='<div id="login_div" style="position:absolute; z-index: 1001; width: 400px; height: 382px;" class="login_div"><iframe id="login_frame" style="padding:0; margin:0px; width: 100%; height: 100%;" frameborder="0" scrolling="no"></iframe></div>';
          //登录成功隐藏背景
          var getUrlParam = function(key) {
            var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) return r[2] || '';
            return '';
          };
          if(window.location.host === 'qqgame.qq.com' && getUrlParam('ipids')){
            
            var ajaxObj = $.ajax({
              url: '//ngo.minigame.qq.com/web_config_center_svr/get_data?appid=qqgame&schemaid=game_configuration&apitype=normal&objectid='+getUrlParam('ipids'),
              dataType: 'jsonp',
              timeout: 1000*1, 
              success: function(response) {
                if(response.Result === 0 && response.DBData){
                  var DBData = response.DBData;
                  if(DBData.loginBg){
                    str = '<div id="login-contains" style="position:absolute;left:0;right:0;top:0;bottom:0;margin:auto;width:890px;height:560px;z-index:99999;background:url(' + DBData.loginBg + ') no-repeat;background-size:cover;background-position:top center" ><div id="login_div" style="position:absolute; z-index: 1001; width: 400px; height: 382px;" class="login_div"><iframe id="login_frame" style="padding:0; margin:0px; width: 100%; height: 100%;" frameborder="0" scrolling="no"></iframe></div></div>';
                    $('body').append(str);
                    $("#login_frame").onreadystatechange = function() {
                    if (document.readyState == 'complete') {
                        $("#login_frame").onreadystatechange = null;
                        $("#login_div").style.display = 'block';
                      }
                    }
                    $("#login_frame").onload = function() {
                        $("#login_div").style.display = 'block';
                    }
                    //现以设appid,s_url,proxy_url参数
                    var url= window.location.protocol + '//xui.ptlogin2.qq.com/cgi-bin/xlogin?daid=207&target=self&appid=7000201&s_url='+escape(purl)+'&style=22&proxy_url='+escape(proxyurl);
                    $("#login_frame").attr("src",url);
                 } else {
                  $('body').append(str);
                  $("#login_frame").onreadystatechange = function() {
                    if (document.readyState == 'complete') {
                        $("#login_frame").onreadystatechange = null;
                        $("#login_div").style.display = 'block';
                    }
                  };

                  $("#login_frame").onload = function() {
                      $("#login_div").style.display = 'block';
                  };
                  //现以设appid,s_url,proxy_url参数
                  var url= window.location.protocol + '//xui.ptlogin2.qq.com/cgi-bin/xlogin?daid=207&target=self&appid=7000201&s_url='+escape(purl)+'&style=22&proxy_url='+escape(proxyurl);
                  $("#login_frame").attr("src",url);
                }
                }
              }
            });
          }else{
            $('body').append(str);
          }
        }

        $("#login_frame").onreadystatechange = function() {
            if (document.readyState == 'complete') {
                $("#login_frame").onreadystatechange = null;
                $("#login_div").style.display = 'block';
            }
        };
        $("#login_frame").onload = function() {
            $("#login_div").style.display = 'block';
        };
        //现以设appid,s_url,proxy_url参数
        var url= window.location.protocol + '//xui.ptlogin2.qq.com/cgi-bin/xlogin?daid=207&target=self&appid=7000201&s_url='+escape(purl)+'&style=22&proxy_url='+escape(proxyurl);
    
        if (window.location.hostname === 'qqgame.qq.com') {
            url = window.location.protocol + '//xui.ptlogin2.qq.com/cgi-bin/xlogin?daid=181&target=self&appid=21001601&s_url='+escape(purl)+'&style=22&proxy_url='+escape(proxyurl);
        }

        $("#login_frame").attr("src",url);
    }
    this.TokenManger = new function(){
        var _this = this;
        var _appid = -1;
        var _succ_callback = null;
        var _fail_callback = null;
        this.get_token = function()
        {
            return _api.Aux.get_cookie("gameapi_access_token");
        }
        
        this.verify_token = function()
        {
            _api.CallAPI("qqgame_assign_token", "GET", "appid="+_appid, _succ_callback, _fail_callback);
        }
        
        this.init_refresh_token = function(interval, appid, s, f)
        {
            _succ_callback = s;
            _fail_callback = f;
            _appid = appid;
            setInterval(_this.verify_token, interval);
        }
    }
    
    this.createQQGameDlg = function(opt)
    {
        var def_opt = {'width':300, 'height':120, 'top':0, 'left':0, 'zidx':10, 'url': '', 'title':'notitle', 'id':'qqgame_popup_dlg','scrolling':'no'};
        for (var i in def_opt) opt[i] = opt[i] || def_opt[i];
        var html = '<div id="'+opt['id']+'"><div class="qgui_popup" style="border-bottom:1px solid #0077a8;position:absolute; width:'+(opt['width']+30)+'px;top:'
            +opt['top']+'px;left:'+opt['left']+'px;z-index:'+opt['zidx']+'"><div class="qgui_popup_title"><div class="qgui_popup_title_tl"></div>'
            + '<div class="qgui_popup_title_tm"><h3>'+opt['title']+'</h3></div>'
            + '<div class="qgui_popup_title_tr"><button type="button" class="close"><span>╳</span></button></div></div>'
            + '<div class="qgui_popup_cont"><div class="qgui_popup_main">'
            + '<iframe name="mainiframe" width="'+opt['width']+'" height="'+opt['height']+'" frameborder="0" scrolling="'+opt['scrolling']+'" allowTransparency="true" src="'+opt['url']+'"></iframe>'
            + '</div></div><!--<div class="qgui_popup_op"><div class="qgui_popup_title_bl"></div><div class="qgui_popup_title_bm">';
        if (opt['box_type'] == 'confirm')
        {
            html += '<button type="button" class="btn btn_confirm">确认</button><button type="button" class="btn btn_cancel">取消</button>';
        }
        
        html += '</div><div class="qgui_popup_title_br"></div></div>--></div><iframe style="position:absolute;width:'+(opt['width']+30)+'px;height:'+ (opt['height']+60) +'px;top:'+opt['top']+'px;left:'+opt['left']+'px;" frameborder="0" scrolling="no"></iframe></div>';
        return html;
    }
    
    this.InviteCloseCallback = null;
    this.InviteCallback = null;
    this.InviteClose = function()
    {
        if (typeof(_api.InviteCloseCallback) == 'function')
        {
            _api.InviteCloseCallback();
        }
        
        $('#qqgame_invite_dlg').remove();
    }
    
    this.InviteCloseDlg = function()
    {        
        $('#qqgame_invite_dlg').remove();
    }
    
    this.Invite = function(appid, callback, closecallback, opt)
    {
        // open a dlg, create window
        if (typeof(opt) == 'undefined') opt = {};
        _api.InviteCallback = callback;
        _api.InviteCloseCallback = closecallback;
        
        var url_param = '';
        if(typeof(opt['filter_type']) != 'undefined')
        {
            url_param += '&filter_type='+opt['filter_type'];
        }
        
        if(typeof(opt['intro']) != 'undefined')
        {
            url_param += '&intro='+encodeURIComponent(opt['intro']);
        }          
        
        var doc_obj = $(document);
        var width = 535;
        var height = 470;
        var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
        var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
        var def_opt = {'width':width, 'height':height, 'top':top, 'left':left, 'zidx':10, 
            'url': window.location.protocol + '//minigame.qq.com/plat/social_hall/invite_v2.html?appid='+appid+url_param, 
            'id': 'qqgame_invite_dlg', 
            'title':'邀请好友'};

        for (var i in def_opt) opt[i] = opt[i] || def_opt[i];
        var dlg_html = _api.createQQGameDlg(opt);
        $('body').append(dlg_html);
        $('#qqgame_invite_dlg button.close').click(_api.InviteClose);
    }
    
    this.ConfirmFeedCallback = null;
    this.ConfirmFeedOk = function(preview_data)
    {
        $('#qqgame_feed_preview_dlg').remove();
        if (_api.ConfirmFeedCallback)
        {
            _api.ConfirmFeedCallback(true, preview_data);
        }
    }
    
    this.ConfirmFeedCancel = function()
    {
        $('#qqgame_feed_preview_dlg').remove();
        if (_api.ConfirmFeedCallback)
        {
            _api.ConfirmFeedCallback(false);
        }
    }

    this.ConfirmFeed = function(appid, callback, opt)
    {
        if (typeof(opt) != 'object') opt = {};
        _api.ConfirmFeedCallback = callback;
            
        var paramstr = '&app_param=' + escape(JsonToStr(opt));

        
        var doc_obj = $(document);
        var width = 600;
        var height = 420;
        if( (typeof(opt['show_post'])!='undefined') && (opt['show_post']) )
        {
            height = 500;
        }

        var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
        var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
        var def_opt = {'width':width, 'height':height, 'top':top, 'left':left, 'zidx':10, 
            'url': window.location.protocol + '//minigame.qq.com/plat/social_hall/preview.html?appid='+appid+paramstr, 
            'id': 'qqgame_feed_preview_dlg', 
            'title': typeof(opt['title']) == 'undefined'? '游戏事件预览': opt['title']};
        var dlg_html = _api.createQQGameDlg(def_opt);
        $('body').append(dlg_html);

        $('#qqgame_feed_preview_dlg button.close').click(_api.ConfirmFeedCancel);
    }
	
	this.modifyTitle = function(obj)
	{
		if (!obj || 'undefined' == typeof(obj.title))
		{
			return;
		}
		$('#qqgame_pay_dlg').find('.qgui_popup_title_tm').find('h3').text(obj.title);
	};
	
	///////////////////////
	// 
	this.AgentBuyCloseCallback = null;
	this.AgentBuyCallback = null;
	this.AgentBuyClose = function()
	{
		if (typeof(_api.AgentBuyCloseCallback) == 'function')
		{
			_api.AgentBuyCloseCallback();
		}
		_api.AgentBuyCloseDlg();
	}
	this.AgentBuyCloseDlg = function()
	{
		$('#qqgame_agent_buy_dlg').remove();
	}
	this.AgentBuy = function(appid, title, item_info, close_cb, agent_buy_cb)
	{
		_api.AgentBuyCloseCallback = close_cb;
		_api.AgentBuyCallback = agent_buy_cb;
	
		if (typeof(item_info["id"]) != 'string' || typeof(item_info["name"]) != 'string'
			|| typeof(item_info["img_url"]) != 'string' || typeof(item_info["pricex"]) != 'number' || typeof(item_info["pricey"]) != 'number'
			|| typeof(item_info["num"]) != 'number' || item_info["name"].length <= 0 || item_info["name"].length > 4
			|| (item_info["num"] % item_info["pricey"]) != 0)
		{		
			if (typeof(agent_buy_cb) == 'function')
			{
				var resultinfo = {"order_no":"", "item_id":item_info["id"], "item_num":item_info["num"]};
				agent_buy_cb(-1, "invalid param", resultinfo);
			}
				
			return;
		}
				
		var url = window.location.protocol + "//minigame.qq.com/plat/social_hall/agent_buy.html?appid=" + appid 
				+ "&item_id=" + encodeURIComponent(item_info["id"]) 
		        + "&item_name=" + encodeURIComponent(item_info["name"])
				+ "&item_img_url=" + encodeURIComponent(item_info["img_url"])
				+ "&item_pricex=" + encodeURIComponent(item_info["pricex"])
				+ "&item_pricey=" + encodeURIComponent(item_info["pricey"])
				+ "&item_num=" + encodeURIComponent(item_info["num"]);
				
		var width = 490;
		var height = 360;
		var doc_obj = $(document);
		var top = doc_obj.scrollTop() + (doc_obj.height() - height) / 2 - 30;
		var left = doc_obj.scrollLeft() + (doc_obj.width() - width) / 2;
		
		var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
			'url': url,
			'id': 'qqgame_agent_buy_dlg',
			'title': title,
			'box_type': 'none'
		};
		
		var dlg_html = _api.createQQGameDlg(def_opt);
		$('body').append(dlg_html);	
		
		$('#qqgame_agent_buy_dlg button.close').click(_api.AgentBuyClose);
	}	
	
	///////////////////////
	this.PayCloseCallback = null;
	this.PayClose = function()
	{
		if (typeof(_api.PayCloseCallback) == 'function')
		{
			_api.PayCloseCallback();
		}
		$('#qqgame_pay_dlg').remove();
	};

    this.BuyGame = function(appid, zoneid, sandbox, close_cb) {
        window.midas.minipay.buyGame({
            methods: { 
                onClose: close_cb,
            }
        }, {
            appid: appid,
            openid: window.openid,
            openkey: window.openkey,
            session_id: "openid",
            session_type: "openkey",
            zoneid: zoneid,
            sandbox: sandbox,
            pf: get_pf(),
            buy_quantity: 100,
            step: 1,
            disable_channels: 'wechat'
        });
    };
	this.Pay = function(appid, zoneid, sandbox, close_cb)
	{
        this.BuyGame(appid, zoneid, sandbox, close_cb);
        return false;
		
		_api.PayCloseCallback = close_cb;
		var width = 490;
		var height = 320;

		var doc_obj = $(document);
		var top = doc_obj.scrollTop() + (doc_obj.height() - height) / 2 - 30;
		var left = doc_obj.scrollLeft() + (doc_obj.width() - width) / 2;
		
		var sSandBox = '';
		
		if (!('undefined' == typeof(sandbox) || 0 == sandbox))
		{
			sSandBox = 'sandbox.';
		}
		
		var now = new Date();
		
		var sUrl = window.location.protocol + '//' + sSandBox + 'api.unipay.qq.com/v1/r/' + appid + '/qz_buy_page?platform=30005&timestamp=' +
			parseInt(now.getTime() / 1000) + '&zoneid=' + zoneid + '&version=v2';

		var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
			'url': sUrl,
			'id': 'qqgame_pay_dlg',
			'title': '游戏币购买',
			'box_type': 'none'
		};
		
		var dlg_html = _api.createQQGameDlg(def_opt);
		$('body').append(dlg_html);
		$('#qqgame_pay_dlg button.close').click(_api.PayClose);
		window.closePay = function()
		{
			$('#qqgame_pay_dlg button.close').click();
		}
		return false;
	};
	///////////////////////
	
	this.RechargeGameCoinCloseCallback = null;
	this.RechargeGameCoinClose = function()
	{
		if (typeof(_api.RechargeGameCoinCloseCallback) == 'function')
		{
			_api.RechargeGameCoinCloseCallback();
		}
		$('#qqgame_pay_dlg').remove();
	};
	this.RechargeGameCoin = function(appid, zoneid, sandbox, close_cb)
	{
        this.BuyGame(appid, zoneid, sandbox, close_cb);
        return false;
		_api.RechargeGameCoinCloseCallback = close_cb;
		width = 490;
		height = 320;

		var doc_obj = $(document);
		var top = doc_obj.scrollTop() + (doc_obj.height() - height) / 2 - 30;
		var left = doc_obj.scrollLeft() + (doc_obj.width() - width) / 2;
		
		var sSandBox = '';
		
		if (!('undefined' == typeof(sandbox) || 0 == sandbox))
		{
			sSandBox = 'sandbox.';
		}
		
		var now = new Date();
		
		var sUrl = window.location.protocol + '//' + sSandBox + 'api.unipay.qq.com/v1/r/' + appid + '/qz_buy_page?platform=30005&timestamp=' +
			parseInt(now.getTime() / 1000) + '&zoneid=' + zoneid + '&version=v2';

		var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
			'url': sUrl,
			'id': 'qqgame_pay_dlg',
			'title': '游戏币购买',
			'box_type': 'none'
		};
		
		var dlg_html = _api.createQQGameDlg(def_opt);
		$('body').append(dlg_html);
		$('#qqgame_pay_dlg button.close').click(_api.RechargeGameCoinClose);
		window.closeRechargeGameCoin = function()
		{
			$('#qqgame_pay_dlg button.close').click();
		}
		return false;
	};
	
	this.GameVIPActionCloseCallback = null;
	this.GameVIPActionClose = function()
	{
		if (typeof(_api.GameVIPActionCloseCallback) == 'function')
		{
			_api.GameVIPActionCloseCallback();
		}
		$('#qqgame_gamevipaction_dlg').remove();
	}
	this.GameVIPAction = function(appid, mp_id, token, zoneid, openid, version, close_cb, service_type, duration, open_gamevip_mode)
	{
		_api.GameVIPActionCloseCallback = close_cb;
		var width = 650;
		var height = 400;
		var doc_obj = $(document);
		var top = doc_obj.scrollTop() + (doc_obj.height() - height) / 2 - 30;
		var left = doc_obj.scrollLeft() + (doc_obj.width() - width) / 2;
		var sPayTime = '';
		var sDefaultMonth = '';
		if ('undefined' != typeof(duration))
		{
			sPayTime = '&paytime=month';
			sDefaultMonth = '&defaultmonth=' + duration;
		}
        var sOpenGamevipMode = '';
		if (('undefined' != typeof(open_gamevip_mode) ) && (open_gamevip_mode == 2) )
        {
            sOpenGamevipMode = '&ch=send';
        }
        else
        {
            sOpenGamevipMode = '&ch=self';
        }
        var sAid = '&aid=VIP.APP' + appid + '.PLATqqgameact';
        if (duration >= 12)
        {
            sAid += 'year';
        }
        var sAdtag = '&adtag=VIP.APP' + appid + '.PLATqqgameact';
        if (duration >= 12)
        {
            sAdtag += 'year;'
        }        
		var sLuxury = '&service=xxqgame|xxzxgp';
        if (typeof(service_type) != 'undefined') 
        {
            switch (service_type)
            {
                case 1:
                {
                    sLuxury = '&service=xxqgame';
                    break;
                }
                case 2:
                {
                    sLuxury = '&service=xxzxgp';
                    break;
                }
                case 3:
                default:
                {
                    break;
                }
            }
        }
		var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
			'url': window.location.protocol + '//pay.qq.com/minipay/service/?mm=service&platform=30005' + '&appid=' + appid +
				'&mp_id=' + mp_id + '&token=' + token + '&zoneid=' + zoneid + '&openid=' + openid +
				'&version=' + version + sPayTime + sLuxury + sDefaultMonth + sOpenGamevipMode + sAid + sAdtag,
			'id': 'qqgame_gamevipaction_dlg',
			'title': '蓝钻开通活动',
			'box_type': 'none'};
		var dlg_html = _api.createQQGameDlg(def_opt);
		$('body').append(dlg_html);
		$('#qqgame_gamevipaction_dlg button.close').click(_api.GameVIPActionClose);

		return false;
	}

	this.OpenGameVIPCloseCallback = null;
	this.OpenGameVIPClose = function()
	{
		if (typeof(_api.OpenGameVIPCloseCallback) == 'function')
		{
			_api.OpenGameVIPCloseCallback();
		}
		$('#qqgame_opengamevip_dlg').remove();
	}
	
	this.OpenGameVIP = function(appid, close_cb, aid, adtag, service_type, duration)
	{
		_api.OpenGameVIPCloseCallback = close_cb;
		
		var width = 650;
		var height = 400;
		var doc_obj = $(document);
		var top = doc_obj.scrollTop() + (doc_obj.height() - height) / 2 - 30;
		var left = doc_obj.scrollLeft() + (doc_obj.width() - width) / 2;
        var url = window.location.protocol + '//pay.qq.com/minipay/service/?mm=service&platform=30005';
        if (typeof(service_type) != 'undefined') 
        {
            switch (service_type)
            {
                case 1:
                {
                    url += '&service=xxqgame';
                    break;
                }
                case 2:
                {
                    url += '&service=xxzxgp';
                    break;
                }
                case 3:
                default:
                {
                    url += '&service=xxqgame|xxzxgp';
                    break;
                }
            }
        }
        else
        {
            url += '&service=xxqgame|xxzxgp';
        }
        
        if (typeof(duration) != 'undefined') 
        {
		url += '&paytime=month';
		url += '&defaultmonth=' + duration;
        }
        
        + '&appid=' + appid + '&aid=' + aid + '&adtag=' + adtag;
		var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
			'url': url + '&appid=' + appid + '&aid=' + aid + '&adtag=' + adtag,
			'id': 'qqgame_opengamevip_dlg',
			'title': '蓝钻开通',
			'box_type': 'none'};
		var dlg_html = _api.createQQGameDlg(def_opt);
		$('body').append(dlg_html);
		$('#qqgame_opengamevip_dlg button.close').click(_api.OpenGameVIPClose);
		
		return false;
	}
    
	this.NewGameVIPAction = function(appid, mp_id, token, zoneid, openid, version, close_cb, service_type, duration, open_gamevip_mode, preventDragging)
	{
        if (typeof(window.cashier) == 'undefined') 
        {
            return false;
        }
		preventDragging = preventDragging || false;
		var sDefaultMonth = '';
		var amountType = '';
		if ('undefined' != typeof(duration))
		{
			amountType = '!month';
			sDefaultMonth = '!'+duration;
		}
        var sOpenGamevipMode = '';
		if (('undefined' != typeof(open_gamevip_mode) ) && (open_gamevip_mode == 2) )
        {
            sOpenGamevipMode = 'send';
        }
        else
        {
            sOpenGamevipMode = 'self';
        }
        var sAid = 'VIP.APP' + appid + '.PLATqqgameact';
        if (duration >= 12)
        {
            sAid += 'year';
        }      
		var sLuxury = 'xxzxgp,xxqgame';
        if (typeof(service_type) != 'undefined') 
        {
            switch (service_type)
            {
                case 1:
                {
                    sLuxury = 'xxqgame';
                    break;
                }
                case 2:
                {
                    sLuxury = 'xxzxgp';
                    break;
                }
                case 3:
                default:
                {
                    break;
                }
            }
        }
        
        var openParams = {'codes':sLuxury,'scene':'minipay','type':'service','source':152003,'aid':sAid,'actid':mp_id,'appid':appid,'token':token,'zoneid':zoneid,'openid':openid,'version':version,'amount':sDefaultMonth,'target':sOpenGamevipMode,'context':'','amountType':amountType,
            'onSuccess':function (opt) {},
            'onError':function (opt) {},
            'onClose':function (opt) {close_cb();},
			'preventDragging' : preventDragging
        };
        cashier.dialog.buy(openParams);

		return false;
	}
    
    this.NewGameVIPActionEx = function(appid, mp_id, token, zoneid, openid, version, close_cb, service_type, duration, open_gamevip_mode,preventDragging)
	{
        if (typeof(window.cashier) == 'undefined') 
        {
            return false;
        }
		preventDragging = preventDragging || false;
		var sDefaultMonth = '';
		var amountType = '';
		if ('undefined' != typeof(duration))
		{
			amountType = '!month';
			sDefaultMonth = '!'+duration;
		}
        var sOpenGamevipMode = '';
		if (('undefined' != typeof(open_gamevip_mode) ) && (open_gamevip_mode == 2) )
        {
            sOpenGamevipMode = 'send';
        }
        else
        {
            sOpenGamevipMode = 'self';
        }
        var sAid = 'VIP.APP' + appid + '.PLATqqgameact';
        if (duration >= 12)
        {
            sAid += 'year';
        }      
		var sLuxury = 'lzhda,lzhdb,lzhdc';
        if (typeof(service_type) != 'undefined') 
        {
            switch (service_type)
            {
                case 1:
                {
                    sLuxury = 'lzhda';
                    break;
                }
                case 2:
                {
                    sLuxury = 'lzhdb';
                    break;
                }
                case 3:
                default:
                {
                    break;
                }
            }
        }
        
        var openParams = {'codes':sLuxury,'scene':'minipay','type':'service','source':152003,'aid':sAid,'actid':mp_id,'appid':appid,'token':token,'zoneid':zoneid,'openid':openid,'version':version,'amount':sDefaultMonth,'target':sOpenGamevipMode,'context':'','amountType':amountType,
            'onSuccess':function (opt) {},
            'onError':function (opt) {},
            'onClose':function (opt) {close_cb();},
			'preventDragging' : preventDragging
        };
        cashier.dialog.buy(openParams);

		return false;
	}

	this.NewOpenGameVIP = function(appid, close_cb, aid, service_type, duration, preventDragging)
	{
        if (!_api.Aux.get_cookie("p_skey") && _api.Aux.get_cookie("account_type") && window.midas) {
            var param = {
                appid: '1450011625,1450011626',
                pf: 'qqgame',
                coupon_id: '1',
                aid: aid || "",
                buy_quantity: duration || ""
            };
        
            if (_api.Aux.get_cookie("account_type") === "wx") {
                param.wxAppid = "wxc2ef8950176f5f07";
                param.appid = "1450261371,1450275438";
                param.session_id = "hy_gameid";
                param.session_type = "wc_actoken";
                param.openid = _api.Aux.get_cookie("wopenid");
                param.openkey = _api.Aux.get_cookie("waccess_token");
                param.disable_channels = "qbqd";
            }
            if (_api.Aux.get_cookie("account_type") === "qq") {
                param.qqAppid = "1000001183";
                param.session_id = "openid";
                param.session_type = "kp_accesstoken";
                param.openid = _api.Aux.get_cookie("qopenid");
                param.openkey = _api.Aux.get_cookie("qaccess_token");
            }

            if (localStorage.getItem("midas_sandbox")) {
                param.sandbox = "1";
            }
        
            var baseParam = {
                title: "开通包月",
                methods: {
                    onClose: function() {
                        if (typeof close_cb === "function") close_cb();
                        if (console) console.log("onClose");
                    },
                    onSuccess: function() {
                        if (console) console.log("onSuccess");
                    },
                    onError: function() {
                        if (console) console.log("onError");
                    }
                }
            };
            window.midas.minipay.service(baseParam, param);
            return false;
        }

		if (typeof(window.cashier) == 'undefined') 
        {
            return false;
        }

		preventDragging = preventDragging || false;
        //var sLuxury = 'xxqgame,xxzxgp';
		var sLuxury = '!xxzxgj,xxqgame';
        if (typeof(service_type) != 'undefined') 
        {
            switch (service_type)
            {
                case 1:
                {
                    sLuxury = 'xxqgame';
                    break;
                }
                case 2:
                {
                    sLuxury = 'xxzxgj';
                    break;
                }
                case 3:
                default:
                {
                    break;
                }
            }
        }
        
        var sDefaultMonth = '';
		if ('undefined' != typeof(duration))
		{
			sDefaultMonth = duration;
		}
		
        var openParams = {'codes':sLuxury,'scene':'minipay','type':'service','source':152003,'aid':aid,'appid':appid,'amount':sDefaultMonth,'context':'',
            'onSuccess':function (opt) {},
            'onError':function (opt) {},
            'onClose':function (opt) {close_cb();},
			'preventDragging' : preventDragging
        };
        cashier.dialog.buy(openParams);
        
		return false;
	}

    this.GetCouponCloseCallback = null;
	this.GetCouponClose = function()
	{
		if (typeof(_api.GetCouponCloseCallback) == 'function')
		{
			_api.GetCouponCloseCallback();
		}
		$('#qqgame_get_coupon_dlg').remove();
	}
    
    this.GetCoupon = function(appid, sandbox, title, close_cb)
    {
        _api.GetCouponCloseCallback = close_cb;
		
		var width = 500;
		var height = 305;
		var doc_obj = $(document);
		var top = doc_obj.scrollTop() + (doc_obj.height() - height) / 2 - 30;
		var left = doc_obj.scrollLeft() + (doc_obj.width() - width) / 2;
		var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
			'url': window.location.protocol + '//qzs.qq.com/open/coupon/api/index.html?pf=' + (get_pf() || 'qqgame'),
			'id': 'qqgame_get_coupon_dlg',
			'title': '每日金券抽奖',
			'box_type': 'none'};
		var dlg_html = _api.createQQGameDlg(def_opt);
		$('body').append(dlg_html);
		$('#qqgame_get_coupon_dlg button.close').click(_api.GetCouponClose);
		
		return false;
	}
	
	this.RegAntiaddiction = function(callback)
	{
		if (typeof(callback) != 'function') 
			return;
		
		if (typeof(CAntiaddiction) != 'undefined' 
			&& typeof(CAntiaddiction.Register) == 'function')
		{
			CAntiaddiction.Register(callback);
		}
	}
    
    this.BuyCloseCallback = null;
    this.BuyClose = function()
    {
        if (typeof(_api.BuyCloseCallback) == 'function')
        {
            _api.BuyCloseCallback();
        }
		$('#qqgame_buy_dlg').remove();
    }
	
	this.ShowBuyDlg = function()
	{
		$('#qqgame_buy_dlg').show();
	}

    $.getScript('https://qqgame.qq.com/midaspay/appgrayconfig.js');
   
    this.Buy = function(appid, url, sandbox, title, close_cb, buy_cb, disturb)
    {
		if (url.indexOf('new_cpay=1') >= 0 ) {
            var activeTab = -1;
            var resultMark = true;
            var getIsDisableWechat = function() {
                if (sandbox === 1 || sandbox === "1") {
                    return false;
                }
                var blackList = ["100698537","1109844048","1109686504","1111032579","21641","1101082222","27036","1110265884","1105673153","1110592651","1110655553","1104216374","102382491"];
                return blackList.indexOf(String(appid)) === -1;
            };
            var isQQ = !_api.Aux.get_cookie("p_skey") && _api.Aux.get_cookie("account_type") === "qq";
            var isWX = !_api.Aux.get_cookie("p_skey") && _api.Aux.get_cookie("account_type") === "wx";
            
            var buyGoods = function(goodstokenurl, tabs, disable_channels) {
                midas.minipay.buyGoods({
                    title: title,
                    methods: {
                        "onError": function() {
                            if (buy_cb) {
                                buy_cb();
                            }
                            if (window.report) {
                                resultMark = false;
                                window.report({ field1: 2023081501, field2: 410069, field3: 45000125, field16: url, field17: activeTab });
                            }
                            if (window.gAegis) {
                                window.gAegis.error({ event: "pay error",  appid: appid, url: url });
                            }
                        },
                        "onSuccess": function() {
                            if (buy_cb) {
                                buy_cb();
                            }
                            if (window.report) {
                                resultMark = false;
                                window.report({ field1: 2023081501, field2: 410069, field3: 45000124, field16: url, field17: activeTab });
                            }
                            if (tabs && $(tabs)) {
                                $(tabs).remove();
                            }
                        },
                        "onClose": function() {
                            if (close_cb) {
                                close_cb();
                            }
                            if (window.report && resultMark) {
                                window.report({ field1: 2023081501, field2: 410069, field3: 45000126, field16: url, field17: activeTab });
                            }
                        },
                        "onBackButton": function() {
                            if (tabs && $('.midas_minipay_dialog_wrap_no_border')) {
                                $('.midas_minipay_dialog_wrap_no_border').prepend(tabs);
                            }
                        }
                    }
                },{
                    appid : appid,
                    session_id : (function() {
                        if (isQQ) return "openid";
                        if (isWX) return "hy_gameid";
                        if (appid == '24599') {
                            return 'openid';
                        }
                        return 'uin';
                    })(),
                    session_type : (function() {
                        if (isQQ) return "openkey";
                        if (isWX) return "wc_actoken";
                        if (appid == '24599') {
                            return 'openkey';
                        }
                        if (window.location.hostname === "qqgame.qq.com") {
                            return "pskey_181"
                        }
                        return 'skey';
                    })(),
                    openid: (function() {
                        if (isQQ) return window.openid;
                        if (isWX) return _api.Aux.get_cookie("wopenid");
                        if (appid == '24599') {
                            return window.openid;
                        }
                        if (window.location.hostname === "qqgame.qq.com") {
                            return _api.Aux.get_cookie("p_uin").replace(/^o0*/,'');
                        }
                        return _api.Aux.get_cookie("uin").replace(/^o0*/,'');
                    })(),
                    openkey: (function() {
                        if (isQQ) return window.openkey;
                        if (isWX) return _api.Aux.get_cookie("waccess_token");
                        if (appid == '24599') {
                            return window.openkey;
                        }
                        if (window.location.hostname === "qqgame.qq.com") {
                            return _api.Aux.get_cookie("p_skey");
                        }
                        return _api.Aux.get_cookie("skey");
                    })(),
                    sandbox : sandbox,
                    pf : get_pf(),
                    goodstokenurl : goodstokenurl,
                    coupon_id: '1',
                    disable_channels: (function() {
                        if (isWX) {
                            return (disable_channels || "").concat("qbqd");
                        }
                        return disable_channels;
                    })(),
                    showCount: activeTab === 1 ? false : true
                });
                if (window.report) {
                    window.report({ field1: 2023081501, field2: 410069, field3: 45000123, field16: url, field17: activeTab });
                }
            };

            var fetchTabs = function(onSuccess) {
                if (!(window.QQGAME_MIDAS_GRAY instanceof Array)) {
                    onSuccess();
                    return false;
                }
                var pass = false;

                for (var i = 0; i < window.QQGAME_MIDAS_GRAY.length; i += 1) {
                    var item = window.QQGAME_MIDAS_GRAY[i];
                    if ((item.gaid == appid || item.offerid == appid) && item.qb_switch === 1) {
                        pass = true;
                    }
                }

                if(pass === false){
                    onSuccess();
                    return false;
                }

                var getParameterByName = function(name, url) {
                    name = name.replace(/[\[\]]/g, '\\$&');
                    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)');
                    var results = regex.exec(url);
                    if (!results) return '';
                    if (!results[2]) return '';
                    return decodeURIComponent(results[2].replace(/\+/g, ' '));
                };
    
                var tabs = document.createElement('div');
                tabs.style.height = '44px';
                tabs.style.position = 'relative';
                tabs.style.color = '#333';
                
                var wechatTab = document.createElement('div');
                wechatTab.innerText = '微信支付';
                wechatTab.style.position = 'relative';
                wechatTab.style.fontSize = '16px';
                wechatTab.style.float = 'left';
                wechatTab.style.display = 'inline-block';
                wechatTab.style.lineHeight = '41px';
                wechatTab.style.borderBottom = '3px solid #ff6c58';
                wechatTab.style.padding = '0 20px';
                wechatTab.style.cursor = 'pointer';

                var otherTab = document.createElement('div');
                otherTab.innerText = '其他支付';
                otherTab.style.position = 'relative';
                otherTab.style.fontSize = '16px';
                otherTab.style.float = 'left';
                otherTab.style.display = 'inline-block';
                otherTab.style.lineHeight = '41px';
                otherTab.style.padding = '0 20px';
                otherTab.style.cursor = 'pointer';
                
                tabs.appendChild(wechatTab);
                tabs.appendChild(otherTab);
    
                $.ajax({
                    url: 'https://ngo.minigame.qq.com/openapi_pay/buy_goods_token_open',
                    data: {
                        gaid: appid,
                        token: getParameterByName('token_id', url),
                        openid: window.openid || '',
                        openkey: window.openkey || ''
                    },
                    dataType: 'json',
                    xhrFields: {
                        withCredentials: true
                    },
                    timeout: 2000,
                    success: function(response) {
                        if (response.data && response.data.goodstokenurl2) {
                            if (isWX || response.is_hide_other_pay) {
                                onSuccess({ tabs: null, goodstokenurl2: response.data.goodstokenurl2 });
                                return;
                            }
                            activeTab = 1;
                            wechatTab.addEventListener('click', function() {
                                if (activeTab !== 1) {
                                    activeTab = 1;
                                    wechatTab.style.borderBottom = '3px solid #ff6c58';
                                    otherTab.style.borderBottom = 'initial';
                                    buyGoods(response.data.goodstokenurl2, tabs);
                                    if (window.report) {
                                        window.report({ field1: 2023081501, field2: 410069, field3: 45000127, field16: 1 });
                                    }
                                }
                            });
                            otherTab.addEventListener('click', function() {
                                if (activeTab !== 2) {
                                    activeTab = 2;
                                    wechatTab.style.borderBottom = '';
                                    otherTab.style.borderBottom = '3px solid #ff6c58';
                                    buyGoods(response.data.goodstokenurl, tabs, 'wechat');
                                    if (window.report) {
                                        window.report({ field1: 2023081501, field2: 410069, field3: 45000127, field16: 2 });
                                    }
                                }
                            });
                            onSuccess({ tabs: tabs, goodstokenurl2: response.data.goodstokenurl2 });
                        } else {
                            buyGoods(url, null, getIsDisableWechat() ? 'wechat' : '');
                        }
                    },
                    error: function() {
                        if (isWX) {
                            window.alert("网络异常，请稍后重试。");
                            return;
                        }
                        buyGoods(url, null, 'wechat');
                    }
                });
            };

            fetchTabs(function(response) {
                if (response) {
                    buyGoods(response.goodstokenurl2, response.tabs);
                } else {
                    if (getIsDisableWechat()) {
                        buyGoods(url, null, 'wechat');
                    } else {
                        buyGoods(url);
                    }
                }
            });
		} else {
			_api.BuyCloseCallback = close_cb;
        
			var width = 490;
			var height = 320;
			var doc_obj = $(document);
			var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
			var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
			
			var is_tj = false;
			if(url.indexOf('?') != -1)
			{
				var buy_param = url.substring(url.indexOf('?') + 1, url.length);
				
				var url_params = _api.Aux.get_url_param(buy_param);
				for (i in url_params)
				{
					if ( (i == 'sub_domain') & (url_params[i] == 'tj') )
					{
						is_tj = true;
						break;
					}
				}
			}

			if(is_tj)
			{
				var unipay_url_prefix = sandbox? window.location.protocol + '//tj.sandbox.api.unipay.qq.com/': window.location.protocol +  '//tj.api.unipay.qq.com/';
			}
			else
			{
				var unipay_url_prefix = sandbox? window.location.protocol + '//sandbox.api.unipay.qq.com/': window.location.protocol + '//api.unipay.qq.com/';
			}

			if ('/' == unipay_url_prefix.charAt(unipay_url_prefix.length - 1) && '/' == url.charAt(0))
			{
				unipay_url_prefix = unipay_url_prefix.substr(0, unipay_url_prefix.length - 1);
			}
			var def_opt = {'width':width, 'height':height, 'top':top, 'left':left, 'zidx':11, 
				'url': unipay_url_prefix + url + '&platform=30005' + '&version=v2', 
				'id': 'qqgame_buy_dlg', 
				'title': title, 
				'box_type': 'none'};
			var dlg_html = _api.createQQGameDlg(def_opt);
			
			$('#qqgame_buy_dlg').remove();
			$('body').append(dlg_html);
			
			$('#qqgame_buy_dlg button.close').click(_api.BuyClose);
			
			if (typeof(disturb) != 'undefined' && disturb == 0)
			{
				$('#qqgame_buy_dlg').hide();
			}
			
			window.closeBuy = function()
			{
				$('#qqgame_buy_dlg button.close').click();
			}
            window.callbackBuy = function()
            {
                buy_cb();
            }
            
            window.ShowBuyDlg = function()
            {
                _api.ShowBuyDlg();
            }

            if (window.gAegis) {
                window.gAegis.infoAll({
                    event: "midas_cpay",
                    appid: appid,
                    url: window.location.href
                });
            }
        }
        
        return false;
    }
    this.open_gamebuy_from_voucher = null;
    this.voucher_close_cb = function() {
        $('#qqgame_gamevoucher_dlg').remove();
    };
    this.Voucher = function(actid, open_gamebuy_cb) {
        if (!_api.open_gamebuy_from_voucher) {
            _api.open_gamebuy_from_voucher = open_gamebuy_cb;
        }
        var width = 912;
        var height = 595;
        var doc_obj = $(document);
        var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
        var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
        var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
            'url': '//minigame.qq.com/voucher/index.html?id='+actid,
            'id': 'qqgame_gamevoucher_dlg',
            'title': '【QQ游戏】充值返利活动',
            'box_type': 'none'};
        var dlg_html = _api.createQQGameDlg(def_opt);
        $('body').append(dlg_html);
        $('#qqgame_gamevoucher_dlg button.close').click(_api.voucher_close_cb);
    }

    var fetchAMS = function() {
        return new Promise(function(resolve) {
            if (window.QQGAME_AMS) {
                resolve(window.QQGAME_AMS);
            } else {
                $.getScript('https://minigame.qq.com/ams/ams.js', function() {
                    resolve(window.QQGAME_AMS);
                });
            }
        });
    };

    this.openVideoAD = function(options) {
        fetchAMS().then(function() {
            window.QQGAME_AMS.openVideoAD(options);
        });
    }

    this.CheckUserId = function(param, callback) {
        var url_params = _api.Aux.get_url_param();
        $.ajax({
            url: '//go.minigame.qq.com/GameLogin/UserCheck',
            dataType: 'jsonp',
            data: {
                AppID: url_params['appid'] || '',
                Page: 'web',
                Name: param.name,
                ID: param.id
            },
            success: function(response) {
                if (response.Result  === 0) {
                    if (response.IsCert === 1 && response.IsMatch === 1) {
                        callback({ result: 1 });
                    } else {
                        callback({ result: -1 });
                    }
                } else {
                    callback({ result: -1 });
                }
            },
            error: function() {
                callback({ result: -2 });
            }
        });
    }
    
    this.RechargeClose = function()
    {
        $('#qqgame_recharge_dlg').remove();
    }
   
    this.Recharge = function()
    {       
        var appid = 0;
        var url_params = _api.Aux.get_url_param();
        for (i in url_params)
        {
            if (i != 'appid')
                continue;
            appid = url_params[i];
        }
		
		var width = 595,height =456;
		
        var doc_obj = $(document);
        var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
        var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
		var def_opt = null;
		
		var def_opt = {'width':width, 'height':height, 'top':top, 'left':left, 'zidx':11, 
            'url': window.location.protocol + '//pay.qq.com/ipay/mini.shtml?s=minipay&c=qqacct_save&hcb=1&mm=paycenter&appid=' + appid + '&platform=30005&ADTAG=APP.BUY.MINIPAY.QQGAME', 
            'id': 'qqgame_recharge_dlg', 
            'title': 'Q币Q点充值', 
            'box_type': 'none',
			'scrolling':'auto'};
		
        var dlg_html = _api.createQQGameDlg(def_opt);
        $('body').append(dlg_html);
        $('#qqgame_recharge_dlg button.close').click(_api.RechargeClose);
                
        return false;
    }
    
    this.InviteEx = function(appid, opt, close_cb, invite_cb)
    {
        _api.report_stat(4, [2, 20001, appid]);
        return _api.Invite(appid,
            function(uins)
            {
                if (uins.length <= 0)
                {
                   if(typeof close_cb=="function"){
                       var cb_result={'result':0, 'resultstr':'cancelled!', 'invnum':0};
                       close_cb(cb_result);
                   }
                    return false;
                }

                var iDstUinNum = 0;
                var invite_uins = [];
                for (var i = 0; i < uins.length; ++i)
                {
                    invite_uins[i] = uins[i]['uin'];
                    ++iDstUinNum;
                }

                _api.report_stat(5, [2, 20002, appid, iDstUinNum]);

                var gamepara = "";
                var istpo = 0;
                var tips_id = 0;
				var tips_id_3366 = 0;
                if (typeof(opt) != 'undefined')
                {
                    if (typeof(opt['gamepara']) != 'undefined')
                        gamepara = opt['gamepara'];
                    if (typeof(opt['is_tpo']) != 'undefined')
                        istpo = opt['is_tpo'];
                    if (typeof(opt['tips_id']) != 'undefined')
                        tips_id = opt['tips_id'];
					if(typeof(opt['tips_id_3366']) != 'undefined')
						tips_id_3366 = opt['tips_id_3366'];
                }

                var inviteURL = (function() {
                    if (window.location.hostname === 'qqgame.qq.com') {
                        return window.location.protocol + "//lobby.qqgame.qq.com/cgi-bin/qqgame_invite?callback=?"
                    }
                    return window.location.protocol + "//lobby.minigame.qq.com/cgi-bin/qqgame_invite?callback=?"
                })();

                $.getJSON(
                    inviteURL,
                    {"gaid":appid, "invuins": invite_uins.join('_'), "gamepara":gamepara, "istpo":istpo, "tips_id":tips_id, "tips_id_3366":tips_id_3366},
                    function(data)
                    {
                        var cb_result={'result':0, 'resultstr':'success!', 'invnum':iDstUinNum};
                        if (data['result'] != 0)
                        {
                            cb_result['result']=data['result'];
                            cb_result['resultstr']='internal error!';
                            cb_result['invnum']=0;
                        }
                        if (typeof(invite_cb)=="function")
                            invite_cb(cb_result);

                        return true;
                    });

                return false;
            },
            function()
            {
                var cb_result={'result':0, 'resultstr':'cancelled!', 'invnum':0};
                if (typeof(close_cb) == "function")
                    close_cb(cb_result);
                return true;
            }, opt);
    }
    
    this.ShowCouponActivityClose = function()
    {
		$('#qqgame_show_coupon_activity_dlg').remove();
    }
    
    this.ShowCouponActivity = function(appid, suc_cb)
    {        
        var width = 700;
        var height = 450;
        var doc_obj = $(document);
        var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
        var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
        
        var show_coupon_url = window.location.protocol + '//qzs.qzone.qq.com/open/dialog/coupon_activity_v2/index.html';
        var def_opt = {'width':width, 'height':height, 'top':top, 'left':left, 'zidx':11, 
            'url': show_coupon_url + '?pf=' + (get_pf() || 'qqgame') + '&appid=' + appid, 
            'id': 'qqgame_show_coupon_activity_dlg', 
            'title': '活动中心'};
        var dlg_html = _api.createQQGameDlg(def_opt);
        
		$('#qqgame_show_coupon_activity_dlg').remove();
		$('body').append(dlg_html);
        
		$('#qqgame_show_coupon_activity_dlg button.close').click(_api.ShowCouponActivityClose);
        
        window.CloseShowCouponActivity = function()
        {
            $('#qqgame_show_coupon_activity_dlg button.close').click();
        }
        
        window.CallbackSucShowCouponActivity = function(action_id)
        {
            suc_cb(action_id);
        }
        
        return false;
    }
	
	this.ShareLiveAction = function(sharetype,live_id,room_name,nickname,emcee_avatar,live_pic,stream_name,succ_cb,close_cb)
	{
		var appid = 0;
        var url_params = window.GameAPI.Aux.get_url_param();
        for (i in url_params)
        {
            if (i != 'appid')
                continue;
            appid = url_params[i];
        }
		if(!appid){return false;}
		
		if('feeds' != sharetype){
			//百度分享
			var shareurl = getBdShareUrl({
				url: window.location.protocol + '//minigame.qq.com/cooperation/feed/feed_jump.html?appid='+appid+'&itemid='+live_id,
				title : '我正在看'+nickname+'的直播，快一起来看吧！',
				pic : live_pic,
				sharetype : sharetype
			});
			window.open(shareurl);
			return false;
		}
		//好友动态分享
		if (typeof(window.UniversalFeedShare) == 'undefined') 
        {
            $.getScript(window.location.protocol + '//minigame.qq.com/js2.0/tempestfeeds/sendfeeds.js',function(){
				openShareDialog();
			});
        }else{
			openShareDialog();
		}
		
		function openShareDialog(){
			var infojson = '{"GameID":'+appid+',"LiveID":"'+live_id+'","RoomName":"'+room_name+'","NickName":"'+nickname+'","EmceeAvatar":"'+emcee_avatar+'","LivePic":"'+live_pic+'","StreamURL":"'+stream_name+'"}';
			infojson = encodeURIComponent(infojson);
			var sharepageurl=window.location.protocol + '//minigame.qq.com/tempestfeeds/sharepage.shtml?type=ShareLive&infojson='+infojson;
			
			var width = 498;
			var height = 246;
			var doc_obj = $(document);
			var top = doc_obj.scrollTop() + (doc_obj.height() - height) / 2 - 30;
			var left = doc_obj.scrollLeft() + (doc_obj.width() - width) / 2;
			var def_opt = {'width': width, 'height': height, 'top': top, 'left': left, 'zidx': 11,
				'url': sharepageurl,
				'id': 'qqgame_sendfeeds_dlg',
				'title': '分享到QQ游戏动态圈',
				'box_type': 'none'};
			var dlg_html = _api.createQQGameDlg(def_opt);
			$('body').append(dlg_html);
			$('#qqgame_sendfeeds_dlg button.close').click(function(e){
				$('#qqgame_sendfeeds_dlg').remove();
				if(typeof close_cb ==='function'){
					close_cb();
				}
			});
			UniversalFeedShare.registerSharePageCallback(sharefeedsSuccCallback);
			
		}
		
		function sharefeedsSuccCallback(data){
			if(data.extramsg == 'success'){
				$('#qqgame_sendfeeds_dlg').remove();
				if(typeof succ_cb ==='function'){
					succ_cb();
				}
			}
		}
		
		function getBdShareUrl(option){
			option = $.extend({
				sharetype : 'qzone',
				url : window.location.href,
				title : document.title
			},option);
			var url = encodeURIComponent(option.url);
			var title = encodeURIComponent(option.title);
			var shareurl =window.location.protocol + '//connect.qq.com/widget/shareqq/index.html?';
			if(sharetype == 'qzone'){
				shareurl = window.location.protocol + '//sns.qzone.qq.com/cgi-bin/qzshare/cgi_qzshare_onekey?';
			}
			shareurl += 'url='+ url +'&title='+ title;
			if(option.pic){
				shareurl += '&pics='+encodeURIComponent(option.pic);
			}
			return shareurl;
		}
		
		return false;
	}

	this.SNSBrowserCallWeb = function(cmd, param)
	{
		switch (cmd)
		{
		case "OpenRaiders":
			try{
				var p=eval("(" + param + ")");				
				var url = window.location.protocol + "//wan.qq.com/box/microGameBox/appFrame/side.shtml?appid=" + $('#iframe_side').attr('appid') + "&iTime=" + p["LastTime"];				
				switch_iframe_side(url);
			}catch(e){
				/*alert("error: json:" + param + ", message:" + e.message);*/
			}
		break;
		default:;
		}
	}
    
    this.SNSBrowser = 
    {
        IsQQGame: function()
        {
			return true; 
        },
        
        SetTitle: function(icon, title)
        {
            if(typeof(window.external) != null)
            {
                window.external.WebCallSetData2 && window.external.WebCallSetData2(2, icon, title);
            }
        },
        
        SetSize: function(height,width)
        {
            if(typeof(window.external) != null)
            {
				height = height + gIsSnsAdsExists * 30; 
                height = parseInt(height);
                window.external.WebCallSetData2 && window.external.WebCallSetData2(7, height, width);    
            }
			if(location.host == 'qqgame.qq.com')
			{
				margin = ($(window).width() - width)/2;
				$('#iframe_app').attr('width',width);
				$('#iframe_app').css({'width':width,'margin-left':margin,'margin-right':margin});
			}
        },
		
		SetSize_New: function(seq, height, width)
		{
			if (typeof(window.external) != null)
			{
				if (0 > seq || 15 < seq)
				{
					seq = 0;
				}
				height = height + gIsSnsAdsExists * 30; 
                height = parseInt(height);
				window.external.WebCallSetData2 && window.external.WebCallSetData2(seq + 7, height, width);
			}
			if(location.host == 'qqgame.qq.com')
			{
				margin = ($(window).width() - width)/2;
				$('#iframe_app').attr('width',width);
				$('#iframe_app').css({'width':width,'margin-left':margin,'margin-right':margin});
			}
		},
        
        SetTab: function(tab_seq, url, title, icon)
        {
            if(typeof(window.external) != null)
            {
                window.external.WebCallSetData3 && window.external.WebCallSetData3(tab_seq, url, title, icon);
            }
        },

        SetTab1: function(url, title, icon)
        {
            _api.SNSBrowser.SetTab(3, url, title, icon);
        },
        
        SetTab2: function(url, title, icon)
        {
            _api.SNSBrowser.SetTab(4, url, title, icon);
        },
        
        SetTab3: function(url, title, icon)
        {
            _api.SNSBrowser.SetTab(5, url, title, icon);
        },
        
        SetTab4: function(url, title, icon)
        {
            _api.SNSBrowser.SetTab(6, url, title, icon);
        },
		
        SetOK: function()
        {
            if(typeof(window.external) != null)
            {
                window.external.WebCallIsReadyToShow && window.external.WebCallIsReadyToShow();
            }
        },
        
        SetFlashWindow: function()
        {
            if(typeof(window.external) != null)
            {
                window.external.WebCallFlashWindow && window.external.WebCallFlashWindow();
            }
        },
        
        SetTips: function()
        {
            if(typeof(window.external) != null)
            {
                window.external.WebCallSetNoticeValid && window.external.WebCallSetNoticeValid();
            }
        },
        
        Close: function()
        {
            if(typeof(window.external) != null)
            {
                window.external.WebCallQuitGame && window.external.WebCallQuitGame();
            }
        },             
        
		AlertClose: function(bWarn, sWarnTxt)
		{
			if (typeof(window.external) != null)
			{
				window.external.WebCallSetExitWarning && window.external.WebCallSetExitWarning(bWarn, sWarnTxt);
			}
		},
		
		ChangeTab: function(appid, tabid)
		{
			var jumpurl = "qqgame://jumpsnstab:gameid=" + appid + ",tabid=" + (tabid + 1);
			window.location.href(jumpurl);
		},
		
		WebCallSNSBrowser: function(cmd, param)// common function for appframe page to make snsbrowser do something
		{
			try{window.external.WebCallSNSBrowser(cmd, param);}
			catch(e){/*alert("error:" + e.message);*/}				
		}		
    }; 
    
    this.ModSDK = {
        // 缓存排序数据
        sortModsCache: {},
        // 排序类型集合
        orderTypeMap: {
            1: 'mixValue', //综合排名
            2: 'favoriteCount', //最多收藏
            3: 'subscribeCount', //最多订阅
            4: 'goodCount', //最多点赞
            5: 'edit_time' //最新更新
        },
        // 缓存mod详情
        modInfoCache: {},
        // 拉取mod数据
        GetModData: function(cmd, msgbody, callback) {
            var req = {
                "Cmd": cmd,
                "MsgBody": msgbody
            }
            $.ajax({
                url: window.location.protocol + '//node.minigame.qq.com/getmoddata?param='+encodeURIComponent(_api.Aux.json_stringify(req)),
                dataType: 'jsonp',
                scriptCharset: 'utf-8',
                success: callback,
                error: callback
            });
        },
        // mod状态修改
        OPMod: function(gameid, modid, op, optype, callback) {
            $.ajax({
                url: window.location.protocol + '//dir.minigame.qq.com/cgi-bin/QQGameOpen/qqgame_comm_count_opr',
                data: {
                    'prefix': 'mod',
                    'fieldname': optype,
                    'id': modid,
                    'gameid': gameid,
                    'opr': op,
                    'g_tk': _api.Aux.get_csrf_token()
                },
                dataType: 'jsonp',
                scriptChatset : 'utf-8',
                success: function(data) {
                    callback(data);
                },
                error: function() {
                    callback({"result": 500, "resultstr": "server error", "uin": 0});
                }
            });
        },
        GetQQNick: function(uins, callback) {
            var m = Math.ceil(uins.length / 20);
            var qqnicks = {};
            for(var j = 0; j < m; j++) {
                (function(index) {
                    var u = uins.slice(index * 20, (index + 1) * 20);
                    $.ajax({
                        url: window.location.protocol + '//dir.minigame.qq.com/cgi-bin/GetQQNick?uins=' + u.join('-'),
                        dataType: 'jsonp',
                        scriptCharset: 'UTF-8',
                        success: function(data) {
                            if(data.result == 0) {
                                for(var i = 0, len = data.user_data_list.length; i < len; i++) {
                                    qqnicks[data.user_data_list[i].uin] = data.user_data_list[i].nick;
                                }
                            }
                            if (index + 1 == m) {
                                callback(qqnicks);
                            }
                        }
                    });
                })(j);
            }
        },
        GetHeadUrl: function(uins, callback) {
            var m = Math.ceil(uin.length / 20);
            var headurls = {};
            for(var j = 0; j < m; j++) {
                (function(index) {
                    var u = uin.slice(index * 20, (index + 1) * 20);
                    $.ajax({
                        url : window.location.protocol + '//dir.minigame.qq.com/cgi-bin/dir_fetch_qqhead?dstuins=' + u.join('_'),
                        dataType: 'jsonp',
                        scriptCharset: 'UTF-8',
                        success: function(data) {
                            if(data.result == 0) {
                                for(var i = 0, len = data.qqhead.length; i < len; i++) {
                                    headurls[data.qqhead[i].uin] = data.qqhead[i].headurl;
                                }
                            }
                            if (index + 1 == m) {
                                callback(headurls);
                            }
                        }
                    });
                })(j);
            }
        },
        GetSubscribeModList: function(gameid, offset, count, callback) {
            $.ajax({
                url: window.location.protocol + '//dir.minigame.qq.com/cgi-bin/QQGameOpen/qqgame_comm_count_opr',
                data: {
                    'prefix': 'mod',
                    'fieldname': 'subscribe',
                    'gameid': gameid,
                    'offset': offset,
                    'count': count,
                    'opr': 0,
                    'g_tk': _api.Aux.get_csrf_token()
                },
                dataType: 'jsonp',
                scriptChatset : 'utf-8',
                success: function(data) {
                    callback(data);
                },
                error: function() {
                    callback({'result': 500, 'resultstr': 'server error', 'totalcount': 0, 'list': []});
                }
            })
        },
        GetModRankList: function(gameid, count, ordertype, callback) {
            var ordertypestr = _api.ModSDK.orderTypeMap[ordertype];
            var sortkey = gameid + '_' + ordertypestr + '_' + count;
            if (!_api.ModSDK.sortModsCache[sortkey]) {
                _api.ModSDK.GetModData('GetModOrderList2', {
                    "GameID": gameid,
                    "needfield": ["game_id","mod_type","mod_name","mod_tags","mod_desc","icon_url","author","subscribeCount","favoriteCount","goodCount","badCount","mixValue","downloadCount"],
                    "Start": 0,
                    "Count": count,
                    "order": ordertypestr
                }, function(data) {
                    if(data.result == 0) {
                        var datas = data.data;
                        for(var i = 0, len = datas.length; i < len; i++) {
                            datas[i].mod_desc = datas[i].mod_desc.replace(/\r/g, '').replace(/\n/g, '<br/>');
                        }
                        _api.ModSDK.sortModsCache[sortkey] = datas;
                        callback(datas);
                    } else {
                        callback([]);
                    }
                }, function() {
                    callback([]);
                });
            } else {
                callback(_api.ModSDK.sortModsCache[sortkey]);
            }
        },
        GetModDetail: function(gameid, modids, callback) {
            var miss = [], detailary = [];
            for (var i = 0, len = modids.length; i < len; i++) {
                if (!_api.ModSDK.modInfoCache[modids[i]]) {
                    miss.push(modids[i]);
                } else {
                    detailary.push(_api.ModSDK.modInfoCache[modids[i]]);
                }
            }
            if (miss.length > 0) {
                _api.ModSDK.GetModData('GetModInfos2', {
                    "GameID": gameid,
                    "GameVerID": 0,
                    "GetType": 2,
                    "NeedFilterTag": 0,
                    "ModIDs": miss,
                    "Start": 0,
                    "Count": miss.length
                }, function(data) {
                    if(data.result == 0 && data.data.length) {
                        var infos = data.data;
                        for(var i = 0, len = infos.length; i < len; i++) {
                            infos[i].mod_tags = eval(infos[i].mod_tags);
                            infos[i].screenshot_imgs = eval(infos[i].screenshot_imgs);
                            infos[i].summary = infos[i].summary.replace(/\r/g, '').replace(/\n/g, '<br/>');
                            infos[i].mod_desc = infos[i].mod_desc.replace(/\r/g, '').replace(/\n/g, '<br/>');
                            _api.ModSDK.modInfoCache[infos[i].id] = infos[i];
                        }
                        detailary = detailary.concat(infos);
                    }
                    callback(detailary);
                }, function() {
                    callback(detailary);
                });
            } else {
                callback(detailary);
            }
        },
        ModSubScribe: function(gameid, modid, op, optype, callback) {
            _api.ModSDK.OPMod(gameid, modid, op, optype, function(data) {
                callback(data);
            });
        },
        GetCommentList: function(gameid, modid, orderType, start, count, callback) {
            var appId = 'mod_' + gameid + '_' + modid;
            var timer = null;
            $.ajax({
                url: window.location.protocol + '//dir.minigame.qq.com/cgi-bin/newhall_detail_comment_no_skey',
                data: {
                    cmd: 101,
                    orderType: orderType,
                    appId: appId,
                    start: start,
                    num: count,
                    neednickheadurl: 1,
                    g_tk: _api.Aux.get_csrf_token()
                },
                dataType: 'jsonp',
                scriptCharset: 'utf-8',
                success: function(data) {
                    for (var i = 0, len = data.batchInfo.length; i < len; i++) {
                        if (data.batchInfo[i]['from']) {
                            delete data.batchInfo[i]['from'];
                        }
                    }
                    callback(data);
                },
                error: function() {
                    callback({'result': 500, 'resultstr': 'server error'});
                }
            });    
        },
        SubmitComment: function(gameid, modid, content, callback) {
            if (typeof content === 'string' && content.length <= 1000) {
                var commentdata = {
                    content: content
                };
                _api.Aux.post_cross_domain(window.location.protocol + '//dir.minigame.qq.com/cgi-bin/comment_auto_check', commentdata, function(data) {
                    if (data.result == 0) {
                        if (data.BonResult == 1) {
                            // 自动审核不通过
                            callback({'result': 1, 'resultstr': 'auto check failed'});
                        } else {
                            commentdata.cmd = 102;
                            commentdata.appId = 'mod_' + gameid + '_' + modid;
                            _api.Aux.post_cross_domain(window.location.protocol + '//dir.minigame.qq.com/cgi-bin/newhall_detail_comment', commentdata, function(data) {
                                callback(data);
                            }, function() {
                                callback({'result': 500, 'resultstr': 'server error'});            
                            },'json');
                        }
                    } else {
                        callback(data);
                    }
                }, function() {
                    callback({'result': 500, 'resultstr': 'server error'});
                }, 'json');
            } else {
                callback({'result': 2, 'resultstr': 'content too long, limit 1000'});
            }
        },
        GetAllocateModID: function(gameid, modid, callback) {
            if (modid > 0) {
                callback(modid);
            } else {
                $.ajax({
                    url: window.location.protocol + '//node.minigame.qq.com/allocatemodid?gameid='+gameid+'&g_tk='+_api.Aux.get_csrf_token(),
                    dataType: 'jsonp',
                    scriptCharset: 'utf-8',
                    success: function(data) {
                        if (data.result == 0) {
                            callback(data.modid);
                        } else {
                            callback(-1);    
                        }
                    },
                    error: function() {
                        callback(-1);
                    }
                });
            }
        },
        UploadFile: function(obj, callback) {
            if (obj['icon_url'] == '' && obj['screenshot_imgs'] == '') {
                var res = {
                    'result': 0,
                    'resultstr': 'Success',
                    'data': obj
                }
                callback(res);
            } else {
                _api.Aux.post_cross_domain(window.location.protocol + '//actp.minigame.qq.com/business/ModSDK/FileUpload', obj, function(data) {
                    callback(data);
                }, function() {
                    callback({'result': 500, 'resultstr': 'server error', 'data': {}});
                }, 'json');
            }
        },
        FilterFormData: function(formdata) {
            var keys = ['id', 'game_id', 'mod_name', 'mod_desc', 'icon_url', 'screenshot_imgs', 'mod_tags', 'mod_type','update_way', 'share_level', 'summary'];
            for (var key in formdata) {
                if (formdata.hasOwnProperty(key)) {
                    if ($.inArray(key, keys) == -1) {
                        delete formdata[key];
                    }
                }
            }
            return formdata;
        },
        UploadModInfo: function(gameid, modid, formdata, callback) {
            _api.ModSDK.GetAllocateModID(gameid, modid, function(allocate_modid) {
                if (allocate_modid > 0) {
                    var obj = {
                        'gameid': gameid,
                        'modid': allocate_modid,
                        'icon_url': formdata['icon_url'],
                        'screenshot_imgs': formdata['screenshot_imgs']
                    }
                    _api.ModSDK.UploadFile(obj, function(res) {
                        if (res.result == 0) {
                            var resdata = res.data;
                            formdata['game_id'] = obj.gameid;
                            formdata['id'] = obj.modid;
                            formdata['icon_url'] = resdata['icon_url'];
                            formdata['screenshot_imgs'] = _api.Aux.json_stringify(resdata['screenshot_imgs'].split('|'));
                            
                            var filterformdata = _api.ModSDK.FilterFormData(formdata);
                             _api.Aux.post_cross_domain(window.location.protocol + '//node.minigame.qq.com/uploadmodinfo', _api.Aux.json_stringify(filterformdata), function(data) {
                                if (data.result == 0) {
                                    callback({'result': 0, 'resultstr': 'success', 'modid': allocate_modid});
                                } else {
                                    callback(data);
                                }
                            }, function() {
                                callback({'result': 500, 'resultstr': 'server error', 'modid': -1});
                            }, 'json', {contentType: 'application/json; charset=utf-8'});
                        } else {
                            callback(res);
                        }
                    });
                } else {
                    callback({'result': 500, 'resultstr': 'server error', 'modid': -1});
                }
            });
        }
    }

    // 米大师支付或开通蓝钻上报到经分
    this.ReportTLog = function(param){
        if(typeof gReportTLog === 'undefined'){
            return;
        }
        if(typeof param !== 'object'){
            return;
        }

        if(typeof param.data === 'undefined'){
            return;
        }

        if(typeof param.data.event === 'undefined'){
            return;
        }

        var event = param.data.event;
        switch(event){
            case 'midas-pay-param':
                gReportTLog({ field16: 1, field17: 0}, 'pay');
                break;
            case 'open-vip-param':
                gReportTLog({ field16: 2, field17: 0}, 'pay');
                break;
        }

    }
    // 错误监控上报
    this.ReportMonitor = function(param) {

        _api.ReportTLog(param);

        if(typeof gAegis !== 'undefined') {
            var str = param.data;
            if( typeof str === 'object'){

                // 上报自定义事件
                if(typeof str.event !== 'undefined' && typeof gAegis.reportEvent !== 'undefined'){
                    gAegis.reportEvent(str.event);
                }

                var urlP = _api.Aux.get_url_param() || {};
                str.appid = urlP.appid || '';
                str.from = 'business';
                str = JSON.stringify(str);
            }
            if(typeof gAegis[param.type] !== 'undefined'){
                gAegis[param.type](str);
            } else {
                gAegis.infoAll(str);
            }
        }
    }

    this.GameSDK = {
        sdkActive: false,

        timer: null,

        _setSdkCookie: function(appid) {
            _api.Aux.set_cookie_max_age("openid", window.openid, 1, window.location.hostname);
            _api.Aux.set_cookie_max_age("access_token", window.openkey, 1, window.location.hostname);
            _api.Aux.set_cookie_max_age("appid", parseInt(appid), 1, window.location.hostname);
        },

        _hideSdkCookie: function() {
            _api.Aux.set_cookie_max_age("openid", '', 0, window.location.hostname);
            _api.Aux.set_cookie_max_age("access_token", '', 0, window.location.hostname);
            _api.Aux.set_cookie_max_age("appid", '', 0, window.location.hostname);
        },

        _canUse: function() {
            return _api.GameSDK.sdkActive;
        },

        _resizeHander: function() {
            var doc_obj = $(document);
            var width = 1080;
            var height = 630;
            var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
            var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
            $('.qgui_popup').css({top: top > 50 ? top : 50, left: left});
        },

        setActive: function(callback) {
            if (!_api.GameSDK.sdkActive) {
                _api.GameSDK.sdkActive = true;

                try {
                    var src = $('#iframe_app').attr('src');

                    if (!src || src.indexOf('?') === -1) {
                        return;
                    }

                    var tmp = src.split('?');

                    var game = _api.Aux.get_url_param(tmp[1]);
                    var pfkey = game.pfkey;

                    if (!pfkey) {
                        return;
                    }

                    callback({ ret: 0, msg: "", openid: window.openid, openkey: window.openkey, refreshToken: "" });

                    if (_api.GameSDK.timer) {
                        clearInterval(_api.GameSDK.timer);
                    }

                    _api.GameSDK.timer = setInterval(function() {
                        _api.GameSDK.reNewRefresh(pfkey, function(data) {
                            if (data.ret === 0) {
                                // if (window.openid !== data.openid) {
                                //     window.openid = data.openid
                                // }

                                if (window.openkey !== data.openkey) {
                                    window.openkey = data.openkey;
                                    callback(data);
                                }
                            }
                        });
                    },60 * 60 * 1000);
                } catch(e) {
                    console.error(e);
                }
            }
        },

        closeActive: function() {
            if (_api.GameSDK.sdkActive) {
                _api.GameSDK.sdkActive = false;

                if (_api.GameSDK.timer) {
                    clearInterval(_api.GameSDK.timer);
                }
            }
        },

        // 展示特权页
        openPrivilegePage: function(param) {
           var isIe = navigator.userAgent.toLowerCase().indexOf('trident')>-1?true:false;

            var openid = param.openid || window.openid;

            var env = getCurEnv();

            if (!_api.GameSDK._canUse() || !openid || !env || isIe) {
                return;
            }

            // var isCharge = param.isCharge || 0;
            var isCharge = 0;

            var query = 'appid=' + param.shortId + '&serverId=' + param.serverId + '&serverName=' + param.serverName +
                '&roleId=' + param.roleId + '&roleName=' + param.roleName + '&openid=' + openid + '&gaid=' +
                param.gaid + '&isCharge=' + isCharge;

            if (env === 'pc') {
                var doc_obj = $(document);
                var width = 1080;
                var height = 630;
                var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 30;
                var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
                var opt = {
                    'width':width,
                    'height':height,
                    'top':top > 50 ? top : 50,
                    'left':left,
                    'zidx':10,
                    'url': 'https://qqgame.qq.com/privilege_page/#/privilege?' + query + '&from=pc',
                    'id': 'qqgame_privilege_dlg',
                    'title': 'QQ游戏大厅特权',
                    'ignoreHandleWidth': true,
                    'ignoreHandleBorder': true
                };

                var dlg_html = _api.createQQGameDlg(opt);
                $('body').append(dlg_html);
                $('.qgui_popup').css('width', '1080px');
                $('.qgui_popup_main').css({padding: 0, height: '630px'});
                $('.qgui_popup_cont').css('padding', 0);

                $('#qqgame_privilege_dlg button.close').click(function() {
                    $('#qqgame_privilege_dlg').remove();
                    $(window).off('resize', _api.GameSDK._resizeHander);
                });

                $(window).on('resize', _api.GameSDK._resizeHander);
            } else if (env === 'hall') {
                var url = 'https://minigame.qq.com/privilege_page/#/privilege?' + query;
                var schema = 'qqgameprotocol:///openembedwebdialog:Caption=QQ%E6%B8%B8%E6%88%8F%E5%A4%A7%E5%8E%85%E7%89%B9%E6%9D%83,Height=630,Width=1080,GroupId=privilege,URL=' + url;
                window.open(schema);
            } else if (env === 'mobile') {
                var doc_obj = $(document);
                var width = window.innerWidth > 380 ? 600 : 550;
                var height = window.innerWidth > 380 ? 350 : 320;
                var top = doc_obj.scrollTop() + (doc_obj.height() - height)/2 - 15;
                var left = doc_obj.scrollLeft() + (doc_obj.width() - width)/2;
                var opt = {
                    'width':width,
                    'height':height,
                    'top':top,
                    'left':left,
                    'zidx':10,
                    'url': 'https://minigame.qq.com/privilege_page/#/privilege?' + query + '&from=mobile',
                    'id': 'qqgame_privilege_dlg',
                    'title': 'QQ游戏大厅特权',
                    'ignoreHandleWidth': true,
                    'ignoreHandleBorder': true
                };

                var dlg_html = _api.createQQGameDlg(opt);
                $('body').append(dlg_html);
                $('.qgui_popup').css({width: width + 'px', transform: 'rotate(90deg)'});
                $('.qgui_popup_main').css({padding: 0, height: height + 'px'});
                $('.qgui_popup_cont').css('padding', 0);

                var ele = document.getElementsByClassName('qgui_popup_title_tr')[0];
                ele.addEventListener('touchend', function(e) {
                    e.preventDefault();
                    $('#qqgame_privilege_dlg').remove();
                });
            }
        },

        // 登陆接口(短appid)
        launchApp: function(appid, callback) {
            if (!_api.GameSDK._canUse()) {
                return;
            }

            var env = getCurEnv();

            var pf = env === 'pc' ? 'qqgame-web' : 'qqgame';

            var url = 'https://app.lobby.minigame.qq.com/cgi-bin/qqgame_launchapp?type=json&callback=?&appid=' + appid + '&pf=' + pf;

            $.getJSON(url, null, function(data) {
                callback(handleResponse(data));
            });
        },

        // token续期接口(短appid)
        reNewRefresh: function(pfkey, callback) {
            var page = _api.Aux.get_url_param();

            if (!_api.GameSDK._canUse() || !page.appid) {
                return;
            }

            var appid = parseInt(page.appid);

            var env = getCurEnv();

            var host = env === 'pc' ? '//go.qqgame.qq.com' : '//go.minigame.qq.com';

            $.ajax({
                url: host + '/open_launch/renew_refresh',
                dataType: 'jsonp',
                data: {
                    Appid: appid,
                    Openid: window.openid,
                    Openkey: window.openkey,
                    RefreshToken: '',
                    Pf: '',
                    Pfkey: pfkey
                },
                success: function(data) {
                    callback(handleResponse(data));
                },
                error: function(e) {
                    callback(handleError(e));
                }
            });
        },

        // 获取用户个人信息
        getInfo: function(appid, isTest, callback) {
            if (!_api.GameSDK._canUse()) {
                return;
            }

            _api.GameSDK._setSdkCookie(appid);

            var host = getSdkHost(isTest);

            $.ajax({
                url: host + '/sdkapi/get_info',
                headers: {
                    "Content-Type": "application/json"
                },
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    _api.GameSDK._hideSdkCookie();
                    callback(data);
                },
                error: function(e) {
                    _api.GameSDK._hideSdkCookie();
                    callback(handleError(e));
                }
            });
        },

        // 获取用户个人蓝钻信息
        getBlueVipInfo: function(appid, isTest, callback) {
            if (!_api.GameSDK._canUse()) {
                return;
            }

            _api.GameSDK._setSdkCookie(appid);

            var host = getSdkHost(isTest);

            $.ajax({
                url: host + '/sdkapi/blue_vip_info',
                headers: {
                    "Content-Type": "application/json"
                },
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    _api.GameSDK._hideSdkCookie();
                    callback(data);
                },
                error: function(e) {
                    _api.GameSDK._hideSdkCookie();
                    callback(handleError(e));
                }
            });
        },

        // 过滤敏感词
        filterUic: function(appid, textList, isTest, callback) {
            if (!_api.GameSDK._canUse()) {
                return;
            }

            _api.GameSDK._setSdkCookie(appid);

            var host = getSdkHost(isTest);

            $.ajax({
                url: host + '/sdkapi/uic_filter',
                type: 'POST',
                data: JSON.stringify({'text_list_': textList}),
                headers: {
                    "Content-Type": "application/json"
                },
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    _api.GameSDK._hideSdkCookie();
                    callback(data);
                },
                error: function(e) {
                    _api.GameSDK._hideSdkCookie();
                    callback(handleError(e));
                }
            });
        },

        // 获取大玩咖信息
        getDaWanKaInfo: function(appid, version, isTest, callback) {
            if (!_api.GameSDK._canUse()) {
                return;
            }

            _api.GameSDK._setSdkCookie(appid);

            var host = getSdkHost(isTest);

            var url = '/sdkapi/get_dawanka_info';


            if (version && version === '2') {
                url = url + '?version=2';
            }

            $.ajax({
                url: host + url,
                headers: {
                    "Content-Type": "application/json"
                },
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    _api.GameSDK._hideSdkCookie();
                    callback(data);
                },
                error: function(e) {
                    _api.GameSDK._hideSdkCookie();
                    callback(handleError(e));
                }
            });
        },

        // 游戏行为上报
        gameBehaviorReport: function(appid, config, isTest) {
            if (!_api.GameSDK._canUse()) {
                return;
            }

            _api.GameSDK._setSdkCookie(appid);

            var host = getSdkHost(isTest);

            $.ajax({
                url: host + '/sdkapi/report',
                data: config,
                headers: {
                    "Content-Type": "application/json"
                },
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    _api.GameSDK._hideSdkCookie();
                },
                error: function(e) {
                    _api.GameSDK._hideSdkCookie();
                }
            });
        },

        // 获取特权红点
        getPrivilegeRedPoints: function(appid, serverId, roleId, isTest, callback) {
            if (!_api.GameSDK._canUse()) {
                return;
            }

            _api.GameSDK._setSdkCookie(appid);

            var host = getSdkHost(isTest);

            $.ajax({
                url: host + '/sdkapi/get_privilege_red_points?server_id=' + serverId + '&role_id=' + roleId,
                headers: {
                    "Content-Type": "application/json"
                },
                xhrFields: {
                    withCredentials: true
                },
                success: function(data) {
                    _api.GameSDK._hideSdkCookie();
                    callback(data);
                },
                error: function(e) {
                    _api.GameSDK._hideSdkCookie();
                    callback(handleError(e));
                }
            });
                   },

        // 拉起客服反馈页
        openFeedback: function(config) {
            if (!config) {
                config = {};
            }
            var url_params = _api.Aux.get_url_param();
            var appid = url_params.appid || "";
            var serverid = config.serverid || "";
            var roleid = config.roleid || "";

            window.open("qqgameprotocol:///openfeedbackdialog url=https://minigame.qq.com/customer_service/?from=2&tab=2&module=2&appid=" + appid + "&serverid=" + serverid + "&roleid=" + roleid);
        }
    };

    this.getNewGameApi = function(callback) {
        var urlParam = _api.Aux.get_url_param() || {};
        var appid = urlParam.appid || '';
        var timer = null;

        $.getScript('https://minigame.qq.com/ngo_cache_data/js_sdk_version.js', function() {
            if (typeof window.JS_SDK_VERSION_DATA === 'object') {
                var list = window.JS_SDK_VERSION_DATA.list || [];

                var allList = list
                       .filter(function(item) {
                            if (typeof item.black_list === 'string' && item.black_list.length > 0) {
                                return item.publish + '' === '1' && item.black_list.indexOf(appid) === -1;
                            }
                            return item.publish + '' === '1';
                       })
                       .map(function(item) {
                            return parseFloat(item.version);
                       })
                       .sort(function(a, b) {
                          return b - a;
                       });

                var allVersion = allList.length > 0 ? allList[0] : '';

                var grayList = list
                   .filter(function(item) {
                       if (typeof item.appid === 'string' && item.appid.length > 0) {
                          return item.publish + '' === '2' && item.appid.indexOf(appid) !== -1;
                       }
                       return item.publish + '' === '2';
                   })
                   .map(function(item) {
                        return parseFloat(item.version);
                    })
                    .sort(function(a, b) {
                        return b - a;
                    });    


                var grayVersion = grayList.length > 0 ? grayList[0] : '';

                var version = grayVersion ? grayVersion : allVersion;

                if (version) {
                    _version = version;
                    var jsUrl = 'https://minigame.qq.com/new_game_api/js_sdk.' + version + '.js';
                    $.getScript(jsUrl, function() {
                        if (typeof window.NewGameAPI === 'object') {
                            timer && clearTimeout(timer);
                            callback({cmdList: window.NewGameAPI.exportCmd});
                        } else {
                            timer && clearTimeout(timer);
                            callback({cmdList: []});
                        }
                    });
                } else {
                    timer && clearTimeout(timer);
                    callback({cmdList: []});
                }
            } else {
                timer && clearTimeout(timer);
                callback({cmdList: []});
            }
        });

        // 异常保护
        timer = setTimeout(function() {
            callback({cmdList: []});
        }, 1500);
    };
}

function registerAPI()
{
    if (typeof(window.GameAPI) == 'undefined')
    {
        window.GameAPI = new QQGameAPI();
    }
}

//json convert function
function JsonToStr(o) 
{      
    var arr = [];      
    var fmt = function(s) {      
    if (typeof s == 'object' && s != null) return JsonToStr(s);      
    return /^(string|number)$/.test(typeof s) ? "'" + s + "'" : s;      
    }      
    for (var i in o) arr.push("'" + i + "':" + fmt(o[i]));      
    return '{' + arr.join(',') + '}';      
}   

//实现有登录框相对应接口方法
function ptlogin2_onResize(widthval,heightval){
    var width = widthval > 400 ? widthval : 400;
    var height = heightval > 382 ? heightval : 382;
    var login_wnd=$("#login_div");
    if(typeof  login_wnd[0]!="undefined"){
        login_wnd.find("#login_frame").css({width:width+'px',height:height+'px'});
        var doc_obj = $(document);
        var p = [0, 0];
        var psw = doc_obj.scrollLeft(), ww = doc_obj.width(), psh = doc_obj.scrollTop(), wh = doc_obj.height();
        p[0] = psw + (ww - width)/2;

        p[1] = psh + (wh - height)/2;

        //超出右侧
        //(p[0] + width) > (psw + ww) ? (p[0] = psw + ww - width) : "";
        //超出底部
       // (p[1] + height) > (psh + wh) ? (p[1] = psh + wh - height) : "";
        //超出顶部
        p[1] < psh ? p[1] = psh + 20 : "";
        //超出左侧
        p[0] < psw ? p[0] = psw + 8 : "";
        var top = p[1];
        var left = p[0];
        login_wnd.css({width:width+'px',height:height+'px',top:top+'px',left:left+'px',visibility:"hidden"}).show();
        login_wnd.css({visibility:"visible"});
    }
}
function ptlogin2_onClose(){
    $("#login_div").hide();
    $("#ptlogin_mask").hide();
    $("#login_frame").attr("src","");
}

registerAPI();

$(function()
{
    if (typeof(window.ptlogin2_onResize) != 'function')
    {
        window.ptlogin2_onResize = function(width, heigth)
        {
            $('#ptlogin_dlg').width(width).height(heigth);
            return true;
        }
    }
    
    if (typeof(window.ptlogin2_onLogin) != 'function')
    {
        window.ptlogin2_onLogin = function()
        {
            return true;
        }
    }
    
    if (typeof(window.ptlogin2_onClose) != 'function')
    {
        window.ptlogin2_onClose = function()
        {
            $("#ptlogin_dlg").remove();
            $("#ptlogin_mask").remove();
        }
    }

	// 获取当前游戏的sns运营位配置信息
	$.getScript(window.location.protocol + "//minigame.qq.com/plat/social_hall/app_frame/SnsAdsGameList.js", function() 
	{ 
        var appid = 0;
        var url_params = window.GameAPI.Aux.get_url_param();
        for (i in url_params)
        {
            if (i != 'appid')
                continue;
            appid = url_params[i];
        }
		
		if (typeof(gSnsAdsGameList) != 'undefined')
		{
			for (var i=0; i<gSnsAdsGameList.length; i++)
			{
				if (gSnsAdsGameList[i] == appid)
				{
					gIsSnsAdsExists  = 1;
					break;
				}
			}
		}		
	}); 
});
