﻿
//use the following to inject js into qzone webpage.
/*
var tmp=document.createElement("script");
tmp.src="http://127.0.0.1:8000/openplat_sec.js";
document.head.appendChild(tmp);
*/

var CaptchaDialog = function(callback_funcs)
{
    this.callbacks = callback_funcs;
    this.is_showing = false;
    this.ever_touched = false;
}

CaptchaDialog.prototype = 
{
    create : function()
    {
        this.dialog_inner_html = "<html>\
            <body> \
                <style type='text/css'>\
                    #captcha_pannel{width:360px;height:270px;border:2px solid gray; background-color:#ffffff;}\
                    #captcha_title{line-height:40px; height:40px; font-size:20px; font-family:verdana; font-weight:bold; text-align:center;background-color:#d0e4fe;margin-top:0;}\
                    #captcha_content{margin:25px; background-color:#ffffff;}\
                    .captcha_prompt{height:60px;}\
                    .captcha_prompt p{font-size:12px; color:#333333;}\
                    #captcha_left_side{float:left; width=40%; height=60%;}\
                    .captcha_show_in_row{display:block;}\
                    .captcha_answer_prompt{font-size:12px; color:#666666;}\
                    #captcha_right_side{float:right; width=45%;height=60%;}\
                    #captcha_answer_input{margin:10px 0px 10px 0px; height:24px;}\
                    #captcha_submit{font-size:12px; width:90px; height:26px; position:absolute; bottom:25px; right:25px;}\
                    #captcha_time_prompt{font-size:12px; color:#666666; position:absolute; bottom:25px; left:25px;}\
                    #captcha_fail_prompt{font-size:12px; color:#cb430e;}\
                    #captcha_succ_prompt{font-size:12px; color:green;}\
                    #captcha_change_pic{font-size:12px; color:#278bcd}\
                    #captcha_left_fail{font-size:12px; color:#cb430e;}\
                </style>\
            <div id='captcha_pannel'>\
                <h1 id='captcha_title'>请输入验证码</h1>\
                <div id='captcha_content'>\
                    <div class='captcha_prompt'>\
                        <p id='captcha_prompt4single'>请您输入如下验证码，验证成功方可继续游戏。若您超时或输入错误次数超过 <span id='captcha_fail_allowed' class='captcha_max_count'>16</span> 次，将会影响您后续正常游戏。</p>\
                    </div>\
                    <div id='captcha_left_side'>\
                        <div class='captcha_show_in_row'>\
                            <img id='captcha_image' src='' border='0'/>\
                        </div>\
                        <div class='captcha_show_in_row' >\
                            <a id='captcha_change_pic' href=javascript:void(0) >看不清楚，换一张</a>\
                        </div>\
                        <div id='captcha_time_prompt'>剩余时间：<span id='captcha_time_left'>---</span>秒</div>\
                    </div>\
                    <div id='captcha_right_side'>\
                        <div class='captcha_show_in_row captcha_answer_prompt'>验证码：</div>\
                        <div class='captcha_show_in_row'>\
                            <input type='text' id='captcha_answer_input' maxlength=16 />\
                        </div>\
                        <div id='captcha_fail_prompt'>验证失败！您还有<span id='captcha_left_fail'>4</span>次机会</div>\
                        <input type='button' id='captcha_submit' onclick='SecJs.submit_code()' value=确定>\
                    </div>\
                </div>\
            </div>\
            </body>\
        </html>";


        var ctrls = {};
        var captcha_dialog_div = document.createElement('div');
        var divIdName = 'captcha_dialog_div';
        captcha_dialog_div.setAttribute('id',divIdName);
        captcha_dialog_div.style.left = "200px";
        captcha_dialog_div.style.top = "100px";
        captcha_dialog_div.style.position = "absolute";
        captcha_dialog_div.style.zIndex = 9999;
        captcha_dialog_div.style.display = "none";
        captcha_dialog_div.innerHTML = this.dialog_inner_html;
        document.body.appendChild(captcha_dialog_div);

        ctrls.dialog_div = captcha_dialog_div;
        ctrls.prompt4single = document.getElementById('captcha_prompt4single');
        ctrls.fail_allowed = document.getElementById('captcha_fail_allowed');
        ctrls.image = document.getElementById('captcha_image');
        ctrls.time_left = document.getElementById('captcha_time_left');
        ctrls.fail_prompt = document.getElementById('captcha_fail_prompt');
        ctrls.left_fail = document.getElementById('captcha_left_fail');
        ctrls.answer_input = document.getElementById('captcha_answer_input');
        ctrls.submit = document.getElementById('captcha_submit');
        ctrls.change_pic = document.getElementById('captcha_change_pic');

        this.ctrls = ctrls;
        var _self = this;

        ctrls.dialog_div.onclick = function()
        {
            _self.ever_touched = true;
        };

        ctrls.submit.onclick=function()
        {
            _self.callbacks.submit(_self.ctrls.answer_input.value);
            _self.ctrls.answer_input.value="";
        };

        ctrls.change_pic.onclick=function(){ _self.callbacks.change_image();return false;};
        ctrls.image.onload=function(){ _self.callbacks.image_ready();};

        ctrls.answer_input.onkeydown=function(evt)
        {
            var evt = (evt)?evt:window.event;
            _self.ever_touched = true;
            if (evt.keyCode == 13)
            {
                _self.ctrls.submit.onclick();
            }
        };
    },

    show : function(max_fail)
    {
        if (!this.ctrls) {
            this.create()
        }

        var ctrls = this.ctrls;

        ctrls.fail_allowed.innerHTML = max_fail.toString();
        ctrls.fail_prompt.style.display = "none";

        ctrls.answer_input.value = "";
        ctrls.dialog_div.style.display = "";

        this.is_showing = true;
        this.ever_touched = false;
        ctrls.answer_input.focus();
    },

    hide : function()
    {
        if (!this.ctrls) {
            return;
        }
        this.ctrls.dialog_div.style.display = "none";

        this.is_showing = false;
    },

    change_image : function(image_url)
    {
        this.ctrls.image.src = image_url;
    },

    set_time_remain : function(time)
    {
        this.ctrls.time_left.innerHTML = time.toString();
    },

    set_left_fail_times : function(count)
    {
        this.ctrls.fail_prompt.style.display = "";
        this.ctrls.left_fail.innerHTML = count.toString();
    }
}

var SecController = function()
{
    this.sechttpsvr = 'http://openplat.gamesafe.qq.com/cgi-bin/sec.fcgi?';//"http://10.157.40.50";//172.24.137.193

    var _self = this;
    var callbacks = {
        submit : function(answer)
        {
            _self.submit_captcha(answer);
        },

        change_image : function()
        {
            _self.change_image();
        },

        image_ready : function()
        {
            _self.image_ready();
        }
    };

    this.captcha_dialog = new CaptchaDialog(callbacks);
    this.body_check_timer = null;
};

SecController.prototype.start = function(gc)
{
    var _self = this;
    this.gc = gc;

    this.captcha_timeout = 0;//50;
    this.heart_beat_timer = null;

    this.body_check_timer = setInterval(function(){_self.on_timer();}, 1000)
};

SecController.prototype.stop = function()
{
    // if captcha dialog showing, hide it

    // stop timer
    clearInterval(this.heart_beat_timer);

    // clear game context
};

SecController.prototype.query_user_status = function()
{
    var param = (this.gc.seckey? ("&seckey="+this.gc.seckey):"") + "&appid="+this.gc.appid.toString();
    var url = this.sechttpsvr+"req=status&jsonp=SecJs.status_rsp" + param;
    SecJs.call_jsonp_server(url);
};

SecController.prototype.checkanswer = function(answer)
{
    var _self = this;
    if (answer.length < 4 || answer.length > 8)
    {
        return false;
    }
    
    for(i=0;i<answer.length;++i)
    {
        var code = answer[i];
        if ((code < 'a'|| code > 'z') && (code < 'A'|| code > 'Z') && (code < '0'|| code > '9'))
        {
            return false;
        }
    }
    return true;
};

SecController.prototype.submit_captcha = function(answer)
{
    _self = this;

    var param = "&seckey="+this.gc.seckey + "&appid="+this.gc.appid.toString()+"&code="+answer+"&sign="+this.verifysession;
    var url = this.sechttpsvr+"req=verify&jsonp=SecJs.verify_rsp" + param;
    SecJs.call_jsonp_server(url);
    this.verify_timer = setTimeout(function(){_self.rsp_timeout();}, 5000)
}

SecController.prototype.change_image = function()
{
    this.captcha_dialog.change_image("http://captcha.qq.com/getimage?uin=1234567&aid="+this.gc.appid+"&rd="+Math.random().toString());
}

SecController.prototype.image_ready = function()
{
    var url = this.sechttpsvr+"req=notify&jsonp=SecJs.verifysession_rsp";
    SecJs.call_jsonp_server(url);
}

SecController.prototype.on_timer = function()
{
    if (this.body_check_timer) {
        if (document.body) {
            var _self = this;
            this.heart_beat_timer = setInterval(function(){_self.on_timer();}, 180000);
            //this.show_captcha({succ_needed:1,error_allowed:4,timeout:300});
            
            clearInterval(this.body_check_timer);
            this.body_check_timer = null;
        }
        else {
            return;
        }
    }
    this.query_user_status();
};

SecController.prototype.rsp_timeout = function()
{
    this.hide_captcha();
}

SecController.prototype.countdown = function()
{
    this.captcha_dialog.set_time_remain(--this.captcha_timeout);
    if (this.captcha_timeout == 0) {
        this.hide_captcha();
    }
};

SecController.prototype.show_captcha = function(status)
{
    var _self = this;
    if (! this.captcha_dialog.is_showing)
    {
        /* 
          0 未设置检测全屏
          1 不在全屏
          2 未设置退出全屏
          3 退出全屏成功
          4 退出全屏失败
        */
        if (this.gc.blockapp) {
            this.gc.blockapp();
        }
        else {
            fusion.blockApp();
        }
        this.captcha_dialog.show(status.error_allowed);
        this.captcha_dialog.set_time_remain(status.timeout);

        this.change_image();
        this.captcha_timeout = status.timeout;
        this.countdown_timer = setInterval(function(){_self.countdown();}, 1000);
    }
}

SecController.prototype.hide_captcha = function()
{
    if (!this.captcha_dialog.is_showing)
    {
        return;
    }

    this.captcha_dialog.hide();
    clearInterval(this.countdown_timer);
    if (this.gc.unblockapp) {
        this.gc.unblockapp();
    }
    else{
        fusion.unblockApp();
    }
}

SecController.prototype.status_rsp = function(rsp)
{
    if (this.status_timer) {
        clearTimeout(this.status_timer);
        this.status_timer = null;
    }

    var SEC_STATUS_NORMAL_ = 0;
    var SEC_STATUS_CAPTCHA_ = 1;
    var SEC_STATUS_KICK_ = 2;

    var _self = this;
    if (rsp['seckey']) {
        this.gc.seckey = rsp['seckey'];
    }
    
    switch(rsp.status)
    {
    case SEC_STATUS_CAPTCHA_:
        this.show_captcha(rsp);
        break;
    case SEC_STATUS_KICK_:
        if (this.gc.closeapp) {
            this.gc.closeapp();
        }
        else {
            fusion.closeApp();
        }
        break;
    case SEC_STATUS_NORMAL_:
        //this.hide_captcha();
        break;
    default:
        break;
    }
};

SecController.prototype.verifysession_rsp = function(rsp)
{
    this.verifysession = rsp['verifysession'];
}

SecController.prototype.verify_rsp = function(rsp)
{
    if (this.verify_timer) {
        clearTimeout(this.verify_timer);
        this.verify_timer = null;
    }

    var captcha_dialog = this.captcha_dialog;

    if (rsp.result)
    {
        if (rsp.error_allowed <= 0)
        {
            this.hide_captcha();
        }
        else
        {
            captcha_dialog.set_left_fail_times(rsp.error_allowed);
            this.change_image();
        }
        return;
    }

    this.hide_captcha();
};

//===========================SecJs===========================
var SecJs = function() {
    this.controller = new SecController();
};

SecJs.prototype.start = function(gc)
{
    SecJs.instance_ = this;
    this.controller.start(gc);
};

SecJs.prototype.stop = function()
{
    this.controller.stop();
};

SecJs.status_rsp = function(rsp)
{
    SecJs.instance_.controller.status_rsp(rsp);
};

SecJs.verifysession_rsp = function(rsp)
{
    SecJs.instance_.controller.verifysession_rsp(rsp);
};

SecJs.verify_rsp = function(rsp)
{
    SecJs.instance_.controller.verify_rsp(rsp);
};

SecJs.call_jsonp_server = function(url)
{ // 调用JSONP服务器，url为请求服务器地址
    //console.log("call jsonp server");
    var oldscript =document.getElementById(url);
    if(oldscript){
        document.body.removeChild(oldscript);
    }

    var script =document.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("src", url+"&rn="+Math.random().toString());
    script.setAttribute("id", url);
    document.body.appendChild(script);
};

/*var secjs = new SecJs();
secjs.start(
{
    uin: 404921490,
    openid: "0000000000000000000000000B017772",
    openkey: "842170E4170F4708BB59688B524A66C0",
    appid: 12819,
});*/
