var currentSec = 0;
var pushCallCnt = 0;
var pollCnt = 0;
var callCnt = 0;
var initSec = 2;
var waitLimit = 600;

var ajaxForceStop = false;
var token_push_value = getObjValue("token_push");
function selfcloseWindow() {
    try {
        location.replace("https://www.naver.com");
    } catch (exception) {}
}

function addPushTokenValue() {
    var delEl = $("token_push");
    if (delEl != null) {
    } else {
        var formEl = $("frmNIDLogin");
        tmpInput = document.createElement('input');
        tmpInput.type = "hidden";
        tmpInput.name = "token_push";
        tmpInput.id = "token_push";
        tmpInput.value = token_push_value;
        formEl.appendChild(tmpInput);
    }
}

function makeTimer() {
    currentSec++;
    if (currentSec <= waitLimit) {
        setTimeout(function () {
            makeTimer();
        }, 1000);
    } else {
        viewLayer(2);
    }
}

var callgcnt = 0;

function callBackground(repush) {
    if (repush) {
        viewLayer(1);
    }
    urls = "https://nid.naver.com/app/api/push/getStatus?token_push=" + $("token_push").value + "&cnt=" + callgcnt;
    try {
        var xmlhttp = getXmlHttp();
        xmlhttp.open("GET", urls);
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4) {
                pollCnt++;
                callgcnt++;
                try {
                    var obj = JSON.parse(xmlhttp.responseText);
                    if (repush) {
                        if (obj.auth_result == "success") {
                            addPushTokenValue();
                            $('frmNIDLogin').submit();
                            ajaxForceStop = true;
                        } else {
                            rePush();
                        }
                    } else {
                        if (obj.auth_result == "success") {
                            addPushTokenValue();
                            $('frmNIDLogin').submit();
                            ajaxForceStop = true;
                        } else if (obj.auth_result == "cancel") {
                            checkFail('cancel');
                            waitLimit = currentSec;
                        } else if (obj.auth_result == "unmatch") {
                            checkFail('unmatch');
                            waitLimit = currentSec;
                        } else if (obj.auth_result == "init" || obj.auth_result == "view") {
                            setTimeout(function () {
                                askServerStatus();
                            }, 2000);
                        } else {
                            checkFail('fail');
                        }
                    }
                } catch (e) {
                    setTimeout(function () {
                        askServerStatus();
                    }, 2000);
                }
            }
        }
        xmlhttp.send(null);
    } catch (e) {
        if (window.bridgeGotTime) {
            throw e;
        } else {
            // page reload?
        }
    }
}

function checkFail(alertFlg) {

    if (alertFlg == 'fail') {
        alert($("ajax_alert_fail").value);
    } else if (alertFlg == 'unmatch') {
        alert($("ajax_alert_unmatch").value);
    } else { //'cancel' case
        alert($("ajax_alert_deny").value);
    }
    ajaxForceStop = true;
    viewLayer(2);
}

function rePush() {
    if (pushCallCnt >= 3) {
        alert($("push_count_over").value);
        viewLayer(2);
        ajaxForceStop = true;
    } else {
        pushCallCnt++;
        ajaxForceStop = false;
        pushUrl = "https://nid.naver.com/app/api/push/repush?token_push=" + $("token_push").value;
        try {
            var xmlhttp = getXmlHttp();
            xmlhttp.open("GET", pushUrl);
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.readyState == 4) {
                    try {
                        var obj = JSON.parse(xmlhttp.responseText);
                        if (obj.rtn_msg == "SUCCESS") {
                        } else {
                            checkFail('fail');
                        }
                    } catch (e) {
                    }
                }
            }
            xmlhttp.send(null);
        } catch (e) {
            if (window.bridgeGotTime) {
                throw e;
            } else {
                // page reload?
            }
        }
    }
}

function askServerStatus() {
    if (ajaxForceStop) {
    } else {
        if (currentSec > (waitLimit - initSec)) {
            checkFail('fail');
        } else {
            callBackground(false);
        }
    }
    callCnt++;
}

var Polling = function (option) {
    "use strict";
    var nativeEventSource = window.EventSource !== undefined;

    function loggingPanel(msg) {
        console.log(msg);
    }

    return {
        init: function () {
            loggingPanel("init");
            loggingPanel('event source is ' + (nativeEventSource ? "enable" : 'disable'));
            var session = getObjValue("otpsession");
            loggingPanel(session + " init");
            var receiver = new EventReceiver('/push/otp?session=' + session);
            loggingPanel('enable session ' + session);
            receiver.then(function (data) {
                if (isObjExist("isPollingDisabled")) {
					console.log("polling disabled")
					return;
				}

                loggingPanel('data(' + new Date().toString() + '): ' + JSON.stringify(data));
                receiver.close();
                try {
                    if (data.msgType == "CANCEL") {
                        checkFail('cancel');
                        ajaxForceStop = true;
                    } else {
                        addPushTokenValue();
                        $('frmNIDLogin').submit();
                        ajaxForceStop = true;
                    }
                } catch (e) {
                }
            }).ping(function (ping) {
                loggingPanel('ping: ' + ping.time);
            }).error(function (error) {
                loggingPanel('error:' + JSON.stringify(error));
            });
        }
    };
};

window.Polling = Polling;


function callPollingBackground(repush) {
    if (repush) {
        viewLayer(1);
        try {
            var xmlhttp = getXmlHttp();
            if ($("token_push").value) {
                xmlhttp.open("GET", "https://nid.naver.com/app/api/push/getStatus?token_push=" + $("token_push").value + "&cnt=again");
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4) {
                        try {
                            var obj = JSON.parse(xmlhttp.responseText);
                            if (obj.auth_result == "success") {
                                addPushTokenValue();
                                $('frmNIDLogin').submit();
                                ajaxForceStop = true;
                            } else if (obj.auth_result == "cancel") {
                                checkFail('cancel');
                                ajaxForceStop = true;
                            } else {
                                rePush();
                            }
                        } catch (e) {
                        }
                    }
                }
                xmlhttp.send(null);
            }
        } catch (e) {
            if (window.bridgeGotTime) {
                throw e;
            } else {
                // page reload?
            }
        }
    } else {
        var app = new Polling();
        app.init();
    }
}

var cntbg = 0;

function callBGAuto() {
    try {
        cntbg++;
        if (cntbg > 20 || ajaxForceStop) {
        } else {
            var xmlhttp = getXmlHttp();
            if ($("token_push").value) {
                xmlhttp.open("GET", "https://nid.naver.com/app/api/push/getStatus?token_push=" + $("token_push").value + "&cntbg=" + cntbg);
                xmlhttp.onreadystatechange = function () {
                    if (xmlhttp.readyState == 4) {
                        try {
                            var obj = JSON.parse(xmlhttp.responseText);
                            if (obj.auth_result == "success") {
                                addPushTokenValue();
                                $('frmNIDLogin').submit();
                                ajaxForceStop = true;
                            } else if (obj.auth_result == "cancel") {
                                checkFail('cancel');
                                ajaxForceStop = true;
                            } else {
                                if (cntbg < 6) { //15s -> 2.5s 간격
                                    setTimeout(function () {
                                        callBGAuto();
                                    }, 2500);
                                } else {
                                    setTimeout(function () {
                                        callBGAuto();
                                    }, 5000);
                                }
                            }
                        } catch (e) {
                        }
                    }
                }
                xmlhttp.send(null);
            }
        }
    } catch (e) {
        if (window.bridgeGotTime) {
            throw e;
        } else {
            // page reload?
        }
    }
}

function askServerStatusWithPolling() {
    if (ajaxForceStop) {
    } else {
        if (currentSec > (waitLimit - initSec)) {
            checkFail('fail');
        } else {
            callPollingBackground(false);
            setTimeout(function () {
                callBGAuto();
            }, 5000);
        }
    }
    callCnt++;
}

function confirmPushOTPSubmit() {
    var otp = $('otp');
    if (otp.value == '' || !isOtpValidate(otp.value)) {
        if (!isOtpValidate(otp.value)) {
            otp.value = "";
        }
        $("error_message").innerHTML=viewObjMap.get("id_error_message_txt");
        show("login_error_msg");
        return false;
    }
    return true;
}

function isOtpValidate(val) {
    var regExpStr = /^[0-9]*$/
    return regExpStr.test(val);
}

function viewLayer(viewNo) {
    if (viewNo == 0) {
        show("push_case");
        show("call_success_div");
        hide("call_fail_div1");
        hide("call_fail_div2");
        hide("direct_case");
        hide("direct_case2");
    } else if (viewNo == 1) {
        show("push_case");
        hide("call_success_div");
        show("call_fail_div1");
        show("call_fail_div2");
        hide("direct_case");
        hide("direct_case2");
    } else {
        if (getObjValue("grp_member")=="true"){
            selfcloseWindow()
        } else {
            hide("push_case");
            hide("call_fail_div1");
            hide("call_fail_div2");
            hide("call_success_div");
            show("direct_case");
            show("direct_case2");
            var formEl = $("frmNIDLogin");
            var delEl = $("token_push");
            if (formEl != null && delEl != null) {
                try {
                    formEl.removeChild(delEl);
                } catch (e) {
                }
            }
        }
    }
}

var formElement = $('frmNIDLogin');
if (formElement.addEventListener) {
    formElement.addEventListener("submit", function (e) {
        if (confirmPushOTPSubmit()) {
        } else {
            e.preventDefault();
        }
    }, false);
} else {
    formElement.attachEvent("onsubmit", function (e) {
        if (confirmPushOTPSubmit()) {
        } else {
            e.preventDefault();
        }
    });
}

function notAskAgain(init_val) {
    var e = $('wait');
    var f = $('auto');
    if (init_val == "init") {
        e.checked = true;
    } else {
        e.checked = false;
    }
    f.value = init_val;
}

function release2nd() {
    location.href = "https://nid.naver.com/app/ext/extsecondAuth?type=second&key=" + $("key").value + "&locale=" + $("locale").value;
}


addNormalEvent("resendBtn", function () {
    rePush();
    if (!ajaxForceStop) {
        viewLayer(1);
    }
});
addNormalEvent("useotpBtn", function () {
    viewLayer(2);
});
addNormalEvent("wait", function () {
    notAskAgain($("wait").checked==true?"init":"");
});
addNormalEvent("release2nd", function () {
    release2nd();
});

if (isMobile()) {
    notAskAgain("init");
}
if (getObjValue("push_result") == "true") {
    viewLayer(0);
    setTimeout(function () {
        askServerStatusWithPolling();
    }, 1000);
    makeTimer();
} else if (getObjValue("push_result") == "push_fault" || getObjValue("push_result") == "push_error_410") {
    viewLayer(1);
    makeTimer();
} else {
    viewLayer(2);
}

var contentsArray = new Array();
contentsArray["ko_KR"] = [
    ["langCode_txt", "한국어"],
    ["push_title_txt", "2단계 인증 알림 발송 완료"],
    ["push_desc_txt", "설정한 기기에서 인증 알림을 확인하세요."],
    ["fail_title_txt", "알림을 받지 못하셨나요?"],
    ["fail_guide_title_txt", "아래 사항을 확인하고 알림을 다시 요청 해주세요."],
    ["fail_guide_desc1_txt", "네이버앱에 로그인 되어 있나요?"],
    ["fail_guide_desc2_txt", "기기 설정에서 네이버 앱의 알림 수신을 허용 했나요?"],
    ["fail_guide_desc3_txt", "네이버 앱 설정에서 알림 수신을 허용 했나요?"],
    ["not_ask_again_txt", "이 브라우저는 “2단계 인증” 없이 로그인 합니다."],
    ["resend_txt", "알림 다시 보내기"],
    ["useotp_txt", "OTP 인증번호를 입력하여 로그인 하기"],
    ["otp_title_txt", "OTP 인증번호를 입력해 주세요."],
    ["otp_desc_txt", "2단계 인증 알림이 오지 않는다면 OTP 인증번호로 로그인해보세요."],
    ["otp_attr_placeholder", "OTP 인증번호를 입력하세요."],
    ["confirm_txt", "확인"],
    ["direct_guide_title_txt", "OTP 인증번호 확인 방법"],
    ["direct_guide_desc1_txt", "삼선버튼"],
    ["direct_guide_desc2_txt", "앱설정"],
    ["direct_guide_desc3_txt", "네이버 OTP"],
    ["direct_guide_desc4_txt", "인증번호 확인"],
    ["id_error_message_txt", "OTP 번호를 입력하세요."],
    ["release2nd_txt", "2단계 인증 해제"],
    ["help_txt", "회원정보 고객센터"]
];
contentsArray["en_US"] = [
    ["langCode_txt", "English"],
    ["push_title_txt", "2-Step Verification notification sent"],
    ["push_desc_txt", "Check the verification notification on the registered device."],
    ["not_ask_again_txt", "This browser will sign in without 2-Step Verification."],
    ["fail_title_txt", "Not getting the notification?"],
    ["fail_guide_title_txt", "Check the following and request the notification again."],
    ["fail_guide_desc1_txt", "Are you signed into the NAVER app?"],
    ["fail_guide_desc2_txt", "Did you allow the NAVER app's notifications in your device settings?"],
    ["fail_guide_desc3_txt", "Did you allow notifications in the NAVER app settings?"],
    ["resend_txt", "Resend notification"],
    ["useotp_txt", "Sign in using the OTP verification code"],
    ["otp_title_txt", "Enter the OTP verification code."],
    ["otp_desc_txt", "If you cannot receive the 2-Step Verification notification, sign in using the OTP verification code."],
    ["otp_attr_placeholder", "Enter the verification code."],
    ["confirm_txt", "Confirm"],
    ["direct_guide_title_txt", "How to check the OTP verification code"],
    ["direct_guide_desc1_txt", "Button"],
    ["direct_guide_desc2_txt", "NAVER app<br>settings"],
    ["direct_guide_desc3_txt", "NAVER OTP"],
    ["direct_guide_desc4_txt", "Check verificationn<br>code"],
    ["id_error_message_txt", "Please enter the OTP Number."],
    ["release2nd_txt", "2-Step Verification will be disabled."],
    ["help_txt", "Help"]
];
contentsArray["zh-Hans_CN"] = [
    ["langCode_txt", "中文(简体)"],
    ["push_title_txt", "两步验证通知已发送"],
    ["push_desc_txt", "请在设置的设备确认验证通知。"],
    ["not_ask_again_txt", "此浏览器无需“两步验证”即可登录。"],
    ["fail_title_txt", "没有收到通知吗？"],
    ["fail_guide_title_txt", "请确认下列事项并再次申请通知。"],
    ["fail_guide_desc1_txt", "已登录NAVER APP吗?"],
    ["fail_guide_desc2_txt", "在设备设置允许接收NAVER APP通知吗?"],
    ["fail_guide_desc3_txt", "在NAVER APP设置允许接收通知吗?"],
    ["resend_txt", "重新发送通知"],
    ["useotp_txt", "请输入OTP验证码进行登录"],
    ["otp_title_txt", "请输入OTP验证码。"],
    ["otp_desc_txt", "若未收到两步验证通知,可输入OTP验证码进行登录。"],
    ["otp_attr_placeholder", "请输入OTP验证码。"],
    ["confirm_txt", "确认"],
    ["direct_guide_title_txt", "确认OTP验证码方法"],
    ["direct_guide_desc1_txt", "按钮"],
    ["direct_guide_desc2_txt", "NAVER APP设置"],
    ["direct_guide_desc3_txt", "NAVER OTP"],
    ["direct_guide_desc4_txt", "确认验证码"],
    ["id_error_message_txt", "请输入OTP号码。"],
    ["release2nd_txt", "已解除两步验证。"],
    ["help_txt", "Help"]
];
contentsArray["zh-Hant_TW"] = [
    ["langCode_txt", "中文(台灣)"],
    ["push_title_txt", "兩步驟驗證通知已發送"],
    ["push_desc_txt", "請於設定的裝置確認驗證通知。"],
    ["not_ask_again_txt", "本瀏覽器無需「兩步驟驗證」即可登入。"],
    ["fail_title_txt", "沒有收到通知嗎？"],
    ["fail_guide_title_txt", "請確認下列事項並再次申請通知。"],
    ["fail_guide_desc1_txt", "已登入NAVER APP嗎?"],
    ["fail_guide_desc2_txt", "於裝置設定允許接收NAVER APP通知嗎?"],
    ["fail_guide_desc3_txt", "於NAVER APP設定允許接收通知嗎?"],
    ["resend_txt", "再次發送通知"],
    ["useotp_txt", "輸入OTP驗證碼進行登入"],
    ["otp_title_txt", "请输入OTP验证码。"],
    ["otp_desc_txt", "若沒有收到兩步驟驗證通知,可輸入OTP驗證碼進行登入。"],
    ["otp_attr_placeholder", "请输入OTP验证码。"],
    ["confirm_txt", "確認"],
    ["direct_guide_title_txt", "確認OTP驗證碼方法"],
    ["direct_guide_desc1_txt", "按鍵"],
    ["direct_guide_desc2_txt", "NAVER APP設定"],
    ["direct_guide_desc3_txt", "NAVER OTP"],
    ["direct_guide_desc4_txt", "確認驗證碼"],
    ["id_error_message_txt", "請輸入OTP號碼。"],
    ["release2nd_txt", "已解除兩步驟驗證。"],
    ["help_txt", "Help"]
];
function initPage(langCode) {
    viewObjMap = new mapObj(contentsArray[langCode]);
    for (var key in viewObjMap.getMap()) {
        doActionByKeyName(key);
    }
    setAriaExpanded("locale_switch", "false");
    if (isObjExist("locale")) {
        $("locale").value = langCode;
    }
    hide("lang_list");
    if (langCode=="ko_KR") {
        $("guide_image").src = "https://ssl.pstatic.net/static/nid/app/img-2step-mockup-01.png";
    } else {
        $("guide_image").src = "https://ssl.pstatic.net/static/nid/app/img-2step-mockup-01-en.png";
    }
}
var viewObjMap = new mapObj(contentsArray[getObjValue("locale")]);
initPage(getObjValue("locale"));

function isMobile() {
    if (navigator.userAgentData) {
        return navigator.userAgentData.mobile;
    }

    // https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent#os
    return navigator.userAgent.indexOf('Mobi') !== -1;
}