/* /webgame/home/js/init/PageWebSdk.js */
var PageWebApiSdk = {
    data: {
        fcmDialog: '',
        mainTitle: '',
        closeBtn: '',
        submitBtn: '',
        tId: '',
        fcmTimeoutTId:'',
        fcmTid: '',
        fcmIframe: '',
        timeRemaining:'',
        closePop:'',
        times: 0,
        isFirstCount:0,
        fcmBoxPosition:{}
    },
    init: function (obj,callback) {
         if(PageWebApiSdk.data.fcmDialog =='' ){ 
             PageWebApiSdk.createFcmIframe();
             PageWebApiSdk.createFcmDialog();
             PageWebApiSdk.closeDialog();
         }
         return PageWebApiSdk.sendFcmData(obj,callback);

    },
    sendFcmData :function(obj,afterInit){
        var isPlayLimit = 0;
        $.ajax({
            type: "get",
            url: config._homeApi + "realName-ajaxFcmHeartbeat?_AJAX_=1&" + Math.random(),
            data: obj,
            dataType : "json",
            contentType:'utf-8',
            async: false,
            success: function (rs) {
              var data  = rs.result;
                if(rs.code == 203){
                    window.console &&console.log('用户需要防沉迷限制，弹窗提醒用户相关信息（如：需用户完善身份信息或者用户游戏时长超限、当前为禁止游戏时段等），禁止游戏；');
                    var popWindow  = data.pop_config[0];
                    if (typeof(popWindow) != "undefined") {
                        PageWebApiSdk.reRenderFcmDialog(popWindow, 203);
                    }
                    PageWebApiSdk.doSetTimeoutClose();
                    isPlayLimit = 1;
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            }

        });
        return isPlayLimit;
    },
    createFcmDialog: function () {
        var dialogElement = PageWebApiSdk.data;
        dialogElement.fcmDialog = document.createElement("div");
        dialogElement.fcmDialog.className = "sdkDialog ";
        document.body.appendChild(dialogElement.fcmDialog);
    },
    createMaxIframe: function() {
        var $fcmIframe = document.getElementById("fcmIframe");
        var swith,sheight;
        if(typeof(config)!=="undefined" && config._module =="wd" ){
            swith = document.documentElement.clientWidth *3;
            sheight = document.documentElement.clientHeight*3;
        }else{
            swith = document.documentElement.clientWidth *0.8;
            sheight = document.documentElement.clientHeight*1;
        }
        $fcmIframe.style.cssText += ";z-index:100;width:" + swith + "px;height:" + sheight + "px; margin-top:-220px;margin-left:-" + Math.floor(swith / 2) + "px; background:none; background-color:#f00; opacity: 0;  filter:alpha(opacity=0); display:block;";
        $fcmIframe.onclick = function() {
             return false;
         };
    },
    createMinIframe: function() {
        var $fcmIframe = document.getElementById("fcmIframe");
        $fcmIframe.style.cssText += ";width:618px;height:354px;background:none";

    },
    reRenderFcmDialog: function(obj, code,isMy) {
        PageWebApiSdk.data.fcmIframe.style.cssText += ";display:none";
        PageWebApiSdk.data.fcmDialog.style.cssText += ";display:none";
        PageWebApiSdk.data.fcmIframe.style.cssText += ";display:block";
        PageWebApiSdk.data.fcmDialog.style.cssText += ";display:block";
        var html = PageWebApiSdk.renderDialogTmp(obj, code);
        PageWebApiSdk.data.fcmDialog.innerHTML = html;
        if(code == 203 || typeof (isMy) !== "undefined" &&  isMy == 1){
            PageWebApiSdk.createMaxIframe();
        }else {
            PageWebApiSdk.createMinIframe();
        }
        if(typeof(config)!=="undefined" && config._module =="wd" ){

            PageWebApiSdk.data.fcmBoxPosition = PageWebApiSdk.getWdPositon();
            $('.sdkDialog').css({"left":PageWebApiSdk.data.fcmBoxPosition.left, "top":PageWebApiSdk.data.fcmBoxPosition.top});
            $('.fcmIframe').css({"left":PageWebApiSdk.data.fcmBoxPosition.left, "top":PageWebApiSdk.data.fcmBoxPosition.top});
        }
    },
    getWdPositon:function() {
        $wdBox = $('.wd_box .wd_cont');
        var fcmWidth  = 618;
        var fcmHeight = 354;
        var width     = $wdBox.width();
        var height    = $wdBox.height();
        var top       = $wdBox.offset().top;
        var left      = $wdBox.offset().left;
        if( width > fcmWidth ){
            left += (width-fcmWidth)/2;
        }
        if( height > fcmHeight ){
            top += (height-fcmHeight)/2;
        }
        return {"left":left, "top":top};

    },
    closeDialog: function () {
        PageWebApiSdk.data.fcmDialog.style.cssText += ';display:none';
        PageWebApiSdk.data.fcmIframe.style.cssText += ';display:none';
    },
    /* 创建底层iframe */
    createFcmIframe: function () {
        PageWebApiSdk.data.fcmIframe = document.createElement("iframe");
        PageWebApiSdk.data.fcmIframe.src = "/webgame/home/ifs-web_sdk?getConf=1";
        PageWebApiSdk.data.fcmIframe.frameborder = '0';
        PageWebApiSdk.data.fcmIframe.className = 'fcmIframe';
        PageWebApiSdk.data.fcmIframe.id="fcmIframe";
        document.body.appendChild(PageWebApiSdk.data.fcmIframe);

    },
    /* 定时关闭 */
    doSetTimeoutClose : function(){
        // clearTimeout(PageWebApiSdk.data.closePop);
        // PageWebApiSdk.data.closePop = setTimeout(function () {
        //     PageWebApiSdk.closeDialog();
        // },10*1000);
    },
    showPopupCertify: function(){
        PageWebApiSdk.closeDialog();
        if(typeof (UniLogin)!=="undefined"){
             switch (config._appKey) {
                 case 'ltzg':
                     loginRegLevel = "4";
                     break;
                 case 'zzsg':
                     loginRegLevel = "100";
                     break;
                 case 'lssg2':
                     loginRegLevel = "101";
                     break;
                 case 'smcs':
                     loginRegLevel = "102";
                     break;
             }

            UniLogin.showPopupCertify();

            if(typeof(config)!=="undefined" && config._module =="wd" ){
                $('.certify_dialog').css({"left":PageWebApiSdk.data.fcmBoxPosition.left, "margin-top":-(PageWebApiSdk.data.fcmBoxPosition.top*2),"margin-left":0});
            }

        }
        if(typeof ( $('#loginCertifyBg')) !=='undefined'){
            $('#loginCertifyBg').css({"height": 0,"display": "none" });
        }
        PageWebApiSdk.createMaxIframe();

    },
    /* 渲染弹窗模板 */
    renderDialogTmp: function (obj,code) {
        var modTip ='',tipLi='',modBtn='',btns='',closeBtn='';
        if(typeof(obj.tips)!="undefined"){
            var tips  = obj.tips;
            var len  =  tips.length;
            for( var  i= 1; i<=len; i++){
                tipLi +=' <li>'+ tips[i-1] +'</li>';
            }
            modTip = '<div class="mod-tip">' +
                '           <h3 class="tip-title">温馨提示：</h3>' +
                '            <ul class="tip-info">'+ tipLi +'</ul>' +
                '        </div>' ;
        }
        if(typeof(obj.buttons)!="undefined"){
            var buttons = obj.buttons;
            var len  =  buttons.length;
            for( var  i= 0; i<len; i++){
                if(typeof(buttons[i].url_info)!="undefined"){
                    if(code!=203){
                        btns +=' <a href="'+ buttons[i].url_info.url +'" target="'+ buttons[i].url_info.target  +'" class="btn-fcmprimary" onclick="PageWebApiSdk.closeDialog()">'+ buttons[i].name +'</a>';
                    }else{
                        btns +=' <a href="'+ buttons[i].url_info.url +'" target="'+ buttons[i].url_info.target  +'" class="btn-fcmprimary" >'+ buttons[i].name +'</a>';
                    }

                }else if(buttons[i].func == "change_account"){
                    btns +='<span  onclick="PageWebApiSdk.closeDialog();UniLogin.logout();UniLogin.showPopupLogin(\'\',\'\',true);"  class="btn-fcmprimary">'+ buttons[i].name +'</span>';
                }else if(buttons[i].func == "realname") {
                    btns += '<span  onclick="PageWebApiSdk.showPopupCertify();"  class="btn-fcmprimary">' + buttons[i].name + '</span>';
                }else{

                    btns +='<span  onclick="PageWebApiSdk.closeDialog()"  class="btn-fcmprimary">'+ buttons[i].name +'</span>';
                }
            }
            modBtn =' <div class="mod-btn">'+ btns +'</div>';
        }
        if(typeof(obj.close_button)!="undefined"){
            var close  = obj.close_button;
            var  urlInfo = close.url_info;

            if(close.show){
                if(typeof (urlInfo)!='undefined'){
                    closeBtn ='<a href="'+ urlInfo.url +'" target="'+  urlInfo.target +'" class="close-btn">关闭</a>';
                }else{
                    closeBtn ='<span onclick="PageWebApiSdk.closeDialog()"  class="close-btn">关闭</span>';
                }
            }
        }
        var tmpStile ='';
        if(typeof (obj.content )!='undefined'){
            tmpStile =  '<div class="stitle">'+ obj.content +'</div>';
        }

        var b = ' <div class="fcmdialog">' + closeBtn +
            '        <h2 class="title">'+ obj.title +'</h2>' +
            tmpStile + modTip + modBtn +
            '    </div>';

        return b;
    }
};
PageWebApiSdk.checkFcm = function(){
    if(PageWebApiSdk.data.fcmDialog =='' ){
        PageWebApiSdk.createFcmIframe();
        PageWebApiSdk.createFcmDialog();
        PageWebApiSdk.closeDialog();
    }
    try {
        PageWebGame._getUinfo().then(function () {

            if(config._uInfo){
                PageWebApiSdkConf.uid = config._uInfo.uid;
                PageWebApiSdkConf.is_adult = config._uInfo.sdk;
                PageWebApiSdkConf.version= 2;
            }
            $.ajax({
                type: "get",
                url: "https://apps.4399.com/online/heartbeat?_AJAX_=1&" + Math.random(),
                data: PageWebApiSdkConf,
                dataType : "jsonp",
                contentType:'utf-8',
                async: false,
                success: function (rs) {
                    var data  = rs.result;
                    window.console &&console.log('用户需要防沉迷限制，弹窗提醒用户相关信息（如：需用户完善身份信息或者用户游戏时长超限、当前为禁止游戏时段等），禁止游戏；');
                    if(typeof data.pop_config!=='undefined'){
                        var popWindow  = data.pop_config[0];
                        PageWebApiSdkConf.code = rs.code;
                        if (typeof(popWindow) != "undefined") {
                            if(popWindow.type == 3 && typeof PageWebApiSdk.showPopupCertify =='function'  ){
                                PageWebApiSdk.showPopupCertify();
                            }
                            if(popWindow.cancel_func !== "undefined"){
                                PageWebApiSdkConf.touristMode = popWindow.cancel_func;
                            }
                            if(popWindow.other_popups !== "undefined"){
                                PageWebApiSdkConf.other_popups = data.other_popups;
                            }
                        }
                    }


                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {

                }

            });
        });
    }catch (e) {

    }
};
PageWebApiSdk.touristMode = function(){
    if(PageWebApiSdkConf.touristMode !== "undefined"){
             var  func =   PageWebApiSdkConf.touristMode.func,
              popup_id =   PageWebApiSdkConf.touristMode.popup_id,
            otherPopups =  PageWebApiSdkConf.other_popups,
            code = PageWebApiSdkConf.code;
        if(func && popup_id && otherPopups &&code ){
            PageWebApiSdk.reRenderFcmDialog(otherPopups[popup_id],code,1);
        }
    }
};
PageWebApiSdk._JSONP = (function () {
    var counter = 0, head, window = this, config = {};

    function load(url, pfnError) {
        var script = document.createElement('script'), done = false;
        script.src = url;
        script.async = false;
        var errorHandler = pfnError || config.error;
        if (typeof errorHandler === 'function') {
            script.onerror = function (ex) {
                errorHandler({url: url, event: ex})
            }
        }
        script.onload = script.onreadystatechange = function () {
            if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                done = true;
                script.onload = script.onreadystatechange = null;
                if (script && script.parentNode) {
                    script.parentNode.removeChild(script)
                }
            }
        };
        if (!head) {
            head = document.getElementsByTagName('head')[0]
        }
        head.appendChild(script);
    };
    function encode(str) {
        return encodeURIComponent(str)
    };
    function jsonp(url, params, callback, callbackName) {
        var query = (url || '').indexOf('?') === -1 ? '?' : '&', key;
        callbackName = (callbackName || config['callbackName'] || 'callback');
        var uniqueName ='callback_' + new Date().getTime();
        params = params || {};
        for (key in params) {
            if (params.hasOwnProperty(key)) {
                query += encode(key) + "=" + encode(params[key]) + "&"
            }
        }
        window[uniqueName] = function (data) {
            callback(data);
            try {
                delete window[uniqueName]
            } catch (e) {
            }
            window[uniqueName] = null
        };
        load(url + query + callbackName + '=' + uniqueName);
        return uniqueName
    };
    function setDefaults(obj) {
        config = obj
    };
    return {get: jsonp, init: setDefaults}
}());



