var isProcessing = false;
var mInterval;

function isClickedButton() {
    if (isProcessing) {
        return true;
    }
    isProcessing = true;
    mInterval = setInterval(function() {
        isProcessing = false;
        clearInterval(mInterval);
    }, 1000);
    return false;
}

$(function() {
//    $("#layerPopup.Popup08 .Certinput input[type='number']").ready(function() {
//        $("#layerPopup.Popup08 .Certinput input[type='number']").keypress(function(event) {
//            if ((event.keyCode >= 48 && event.keyCode <= 57) || event.keyCode == 8) {
//                if ($("#layerPopup.Popup08 .Certinput input[type='number']").val().length == 10) {
//                    event.preventDefault();
//                }
//            } else {
//                event.preventDefault();
//            }
//        });
//    });
//    $("#layerPopup.Popup08 .Certinput input[type='text']").ready(function() {
//        $("#layerPopup.Popup08 .Certinput input[type='text']").keypress(function(event) {
//            if ($("#layerPopup.Popup08 .Certinput input[type='text']").val().length == 10) {
//                event.preventDefault();
//            }
//        });
//    });
    //UPDATE_CHECK();
});

function open_PopupError(_message) {
    //var fruits = _message.split(/\r\n|\n|\r/);
    var fruits = _message.split("<br>");

    var msg = "";
    for(var i=0; i<fruits.length; i++) {
        msg += "<li>" + fruits[i] + "</li>";
    }

    if (_message == "처리 중 입니다.<br>잠시만 기다려 주세요." || _message == "복수 사업자를 복구 합니다.<br>잠시만 기다려 주세요."
    || _message == "현재 저장된 복수사업자를 저장 합니다.") {
        document.getElementById('popup_err').innerHTML = "<div class='Dim'></div> <div class='layer-con2' id='layer_err'> <div class='hImg'> <ul>"
                                                             + msg
                                                             + "</ul> </div> </div>";
    } else {
        document.getElementById('popup_err').innerHTML = "<div class='Dim'></div> <div class='layer-con' id='layer_err'> <div class='hImg'> <ul>"
                                                             + msg
                                                             + "</ul> </div> <a href='#' onclick='close_PopupError();' class='okBtn'>OK</a> </div> </div>";
    }
    $('#popup_err.PopupError').css('position', 'absolute');
    $('#popup_err.PopupError').css('top', Math.max(0, (($(window).height() - $(this).outerHeight())/2) + $(window).scrollTop()) + 'px');
    $('#popup_err.PopupError').css('top',$(document).scrollTop() + 300).show();
    //$('#popup_err.PopupError').show();
    return;
}

function close_PopupError(){
   		$('#popup_err.PopupError').hide();
		return;
}

var isFallbackView = false;
function open_Fallback(_message) {
    //var fruits = _message.split(/\r\n|\n|\r/);
    var fruits = _message.split("<br>");

    var msg = "";
    for(var i=0; i<fruits.length; i++) {
        msg += "<li>" + fruits[i] + "</li>";
    }

    document.getElementById('popup_fb').innerHTML = " <div class='Dim'></div> <div class='layer-con'> <div class='hImg'> <ul>"
                                                             + msg
                                                             + "</ul> </div> <a href='#' onclick='ok_Fallback();' class='okBtn'>OK</a> </div> </div>";
    $('#popup_fb.PopupFB').show();
    return;
}

function ok_Fallback() {
    $('#popup_fb.PopupFB').hide();
    window.AndroidInterface.onClickFallback();
    return;
}

function close_Fallback(){
   		$('#popup_fb.PopupFB').hide();
		return;
}


function gotoDongleSetting(_isFinish) {
    window.AndroidInterface.gotoDongleSetting(_isFinish);
}

function gotoMobileAuth(_isFinish) {
    window.AndroidInterface.gotoMobileAuth(_isFinish);
}

function gotoVerify(_isFinish) {
    window.AndroidInterface.gotoVerify(_isFinish);
}

function gotoTaxSet(_isFinish) {
    window.AndroidInterface.gotoTaxSet(_isFinish);
}

function gotoUserSet(_isFinish) {
    window.AndroidInterface.gotoUserSet(_isFinish);
}

function finishActivity() {
    window.AndroidInterface.finishActivity();
}

function gotoMain() {
    window.AndroidInterface.gotoMain();
}

function gotoCardPayment() {
    window.AndroidInterface.gotoCardPayment();
}

function gotoReceiptSearch() {
    window.AndroidInterface.gotoReceiptSearch();
}

function gotoCashPayment() {
    window.AndroidInterface.gotoCashPayment();
}

function gotoSearchForToday() {
    window.AndroidInterface.gotoSearchForToday();
}

function gotoSearchForTime() {
    window.AndroidInterface.gotoSearchForTime();
}

function gotoSearchForMonth() {
    window.AndroidInterface.gotoSearchForMonth();
}

function gotoUnionPayment() {
    window.AndroidInterface.gotoUnionPayment();
}

function gotoUnionCancel() {
    window.AndroidInterface.gotoUnionCancel();
}

function gotoAliPayment() {
    window.AndroidInterface.gotoAliPayment();
}

var PageUtil = function() // 페이지 처리 함수
{
    var totalCnt; // 총 건수 3
    var pageRows; // 한 페이지에 출력될 항목 갯수 3
    var curPage; // 현재 페이지
    var disPagepCnt;// 화면출력 페이지수 5
    var totalPage;

    this.setTotalPage = function()
    {
        this.totalPage = parseInt((this.totalCnt/this.pageRows)) + (this.totalCnt%this.pageRows>0 ? 1:0);
    }

    this.getPrev = function()
    {
        var prev= 0;

        if(this.curPage > 1)
            prev= this.curPage - 1;
        else
            prev= 1;

        return prev;
    }

    this.getNext = function()
    {
        var next= 0;

        if(this.curPage < this.totalPage)
            next = this.curPage + 1;
        else
            next = this.totalPage;

        return next;
    }

    this.getPrevPage = function()
    {
        var prevPage= 0;
        var curPos= (parseInt((this.curPage/this.disPagepCnt))+(this.curPage%this.disPagepCnt>0 ? 1:0));

        if(curPos>1)
        {
            prevPage= parseInt((curPos-1))*this.disPagepCnt;
        }

        return prevPage;
    }

    this.getNextPage = function()
    {
        var nextPage= 0;
        var curPos= parseInt((parseInt((this.curPage/this.disPagepCnt))+(this.curPage%this.disPagepCnt >0 ? 1:0)));

        if((curPos*this.disPagepCnt+1) <= this.totalPage)
        {
            nextPage= curPos*this.disPagepCnt+1;
        }

        if( this.totalPage >= nextPage )
            return nextPage;
        else
            return this.totalPage;
    }

    this.Drow = function()
    {
        //var sb = "<div class='Paging_wrap marginT26'> <ul class='Paging'> ";
        sb = "";

        var start = ((parseInt((this.curPage/this.disPagepCnt))+(this.curPage%this.disPagepCnt>0 ? 1:0)) * this.disPagepCnt - (this.disPagepCnt-1));
        var end = ((parseInt((this.curPage/this.disPagepCnt))+(this.curPage%this.disPagepCnt>0 ? 1:0)) * this.disPagepCnt);
        if(end > this.totalPage)
            end = this.totalPage;

            //sb += "<a href='javascript:prev_page();' class='first on'><li><span class='blind'> << </span></li></a>";

        if(this.curPage > this.disPagepCnt)
        {
            sb += "<a href='javascript:prev_page();' class='first on'><li><span class='blind'> << </span></li></a>";
        }

        if(this.getPrev() < this.curPage)
        {
            sb += "<a href='javascript:prev();' class='two'><li><span class='blind'> < </span></li></a>";
        }

        for(var i=start; i<=end; i++)
        {
            if(i==this.curPage)
            {
                sb += "<a href='#'><li class='on'>" + i + "</li></a>" ;
            }
            else
            {
                sb += "<a href='javascript:goPage("+i+");'><li>" + i + "</li></a>";
            }
        }

        if(this.curPage < this.getNext())
        {
            sb += "<a href='javascript:next();' class='eight'><li><span class='blind'> > </span></li></a>";
        }

        if(this.totalPage >= this.getNextPage() && this.getNextPage() != 0 )
        {
            sb += "<a href='javascript:next_page();' class='last'><li><span class='blind'> >> </span></li></a>";
        }

        //sb += "</ul> </div>";
        return sb;
    }
}

function chkword(obj, maxByte) {

    var strValue = obj.value;
    var strLen = strValue.length;
    var totalByte = 0;
    var len = 0;
    var oneChar = "";
    var str2 = "";

    for (var i = 0; i < strLen; i++) {
        oneChar = strValue.charAt(i);
        if (escape(oneChar).length > 4) {
            totalByte += 2;
        } else {
            totalByte++;
        }

        // 입력한 문자 길이보다 넘치면 잘라내기 위해 저장
        if (totalByte <= maxByte) {
            len = i + 1;
        }
    }

    // 넘어가는 글자는 자른다.
    if (totalByte > maxByte) {
//        alert(maxByte + "자를 초과 입력 할 수 없습니다.");
        str2 = strValue.substr(0, len);
        obj.value = str2;
        chkword(obj, 4000);
    }
    return false;
}

function onlyNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    alert("" + evt.which + ", " + event.keyCode);
    if ((charCode >= 48 && charCode <= 57)
        || charCode == 8 || charCode == 9 || charCode == 13) {
        return false;
    } else {
        event.preventDefault();
    }
    return true;
}

function onlyNumberKey(evt, obj, length){
    var charCode = (evt.which) ? evt.which : event.keyCode;
    alert("" + evt.which + ", " + event.keyCode);
    if ((charCode >= 48 && charCode <= 57)
        || charCode == 8 || charCode == 9 || charCode == 13) {
        if (obj.value.length > length) {
            event.preventDefault();
        }
        return false;
    } else {
        event.preventDefault();
    }
    return true;
}

function onlyNumberAndAlphabetKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode;
//    alert("" + evt.which + ", " + event.keyCode);
    if ((charCode >= 48 && charCode <= 57) ||
        (charCode >= 65 && charCode <= 90) ||
        (charCode >= 97 && charCode <= 122) ||
         charCode == 8 || charCode == 9 || charCode == 13) {
        return false;
    } else {
        event.preventDefault();
    }
    return true;
}
function fillZero(sVal, iSize, option) {
  sVal += "";
  while (sVal.length < iSize) {
      if (typeof option == "undefined") {
          sVal = "0" + sVal;
      } else {
          sVal = sVal + "0";
      }

  }
  return sVal;
}
function randomRange(n1, n2) {
	  return Math.floor( (Math.random() * (n2 - n1 + 1)) + n1 );
}
var DEBUG_DEV = window.AndroidInterface.isDebugMode();
var SERVER_URL = "https://fas.firstdatacorp.co.kr/";//개발서버
if(DEBUG_DEV){
	SERVER_URL="https://testfas.firstdatacorp.co.kr/";
}else{
	SERVER_URL="https://fas.firstdatacorp.co.kr/";
}
//GetPosInfo 또는 setMultiBizNums 에 사용하는 POST 방식
function HTTP_SEND(url, json_req, callback){

    console.log(":: // ##################################################");
    console.log(":: // HTTP_SEND(url + " + url + " +)");
    console.log(":: // ##################################################");
    console.log(":: //                                                   ");
    console.log(":: //                                                   ");
    var RequestData = {};
    RequestData.body = {};//json_req;
//    RequestData.body.commonData = {};
    RequestData.body.serviceData = json_req;
    RequestData.header = {};
    RequestData.header.version = window.AndroidInterface.getAppVersion();//2.0.0
    var TO_DATE = new Date();
    var TO_MONTH = fillZero(TO_DATE.getMonth() + 1, 2);
    var TO_DAY = fillZero(TO_DATE.getDate(), 2);
    var TO_YEAR = TO_DATE.getFullYear();
    var TO_FULLYEAR = TO_YEAR + '-' + TO_MONTH + '-' + TO_DAY;
    var TO_FULLMONTH = TO_YEAR + '-' + TO_MONTH;
    var TO_YYYYMMDD = TO_YEAR + TO_MONTH + TO_DAY;
    var TO_YYYYMMDDHHMMSS = TO_YEAR + TO_MONTH + TO_DAY + fillZero(TO_DATE.getHours(), 2) + fillZero(TO_DATE.getMinutes(), 2) + fillZero(TO_DATE.getSeconds(), 2);
    RequestData.header.traceNo = TO_YYYYMMDDHHMMSS+fillZero(randomRange(1, 999), 3);

    json_req = RequestData;
    console.log(url);
    console.log(JSON.stringify(json_req, null, "    "));
    $.ajax({
        url: url,
        dataType: 'json',
        type: 'POST',
        data:JSON.stringify(json_req),
        contentType: 'application/json; charset=utf-8',
        timeout: 3000,
        success: function (res) {
            console.log(":: // ##################################################");
            console.log(":: // #####################SUCCESS######################");
            console.log(":: // ##################################################");
            console.log(JSON.stringify(res, null, "    "));
            console.log(":: //                                                   ");
            console.log(":: //                                                   ");
            // ====================================
            // 정상 로직
            if (typeof callback !== "undefined") {
                callback(res);
            }
        },
        error: function (res) {

            console.log(":: // ##################################################");
            console.log(":: // ######################FAIL########################");
            console.log(":: // ##################################################");
            console.log(JSON.stringify(res, null, "    "));
            console.log(":: //                                                   ");
            console.log(":: //                                                   ");
            try {
                if (typeof callback !== "undefined") {
                    callback(res);
                }
            } catch (e) {
                console.log(":: //      Error~~!!!                               ");
                callback(null);
            }
        }
    });
}
//기기 필터 가져올때 사용 하는 GET 방식
function HTTP_GET(url, callback){
    console.log(":: // ##################################################");
    console.log(":: // HTTP_GET(url + " + url + " +)");
    console.log(":: // ##################################################");
    console.log(":: //                                                   ");
    console.log(":: //                                                   ");
    $.ajax({
        url: url,
        dataType: 'json',
        type: 'GET',
        contentType: 'application/json; charset=utf-8',
        timeout: 3000,
        success: function (res) {

            console.log(":: // ##################################################");
            console.log(":: // ##################################################");
            console.log(JSON.stringify(res, null, "    "));
            console.log(":: //                                                   ");
            console.log(":: //                                                   ");
            // ====================================
            // 정상 로직
            if (typeof callback !== "undefined") {
                callback(res);
            }
        },
        error: function (res) {

            console.log(":: // ##################################################");
            console.log(":: // ##################################################");
            console.log(JSON.stringify(res, null, "    "));
            console.log(":: //                                                   ");
            console.log(":: //                                                   ");
            try {
                //SET_PAGE.open("ERR0101");
                if (typeof callback !== "undefined") {
                    callback(res);
                }
            } catch (e) {
                MENU.setAlert("서비스 장애");

            }
        }
    });
}
function UPDATE_CHECK(){

    console.log(":: // ##################################################");
    console.log(":: //                    UPDATE_CHECK                   ");
    console.log(":: // ##################################################");
    var productNo = JSON.parse(window.AndroidInterface.getMainProductNo());
    if(productNo){
        if(productNo.serial_no) {
            if(0 == window.AndroidInterface.getIsFirstTMSState() || 0 == window.AndroidInterface.checkVersionSame()){
                UPDATE_CHECK1();
            }else if(1 == window.AndroidInterface.getIsFirstTMSState()){
                UPDATE_CHECK2();
            } else {
                UPDATE_CHECK3();
            }
        }
    }
}
function UPDATE_CHECK1(){
    HTTP_SEND(SERVER_URL + "finpay/pos/setDeviceInfo.json", JSON.parse(window.AndroidInterface.getPosInfoData()), function(res){
        if(res){
            if("0000" == res.header.resCd){
                if(0 == window.AndroidInterface.checkVersionSame()){
                    window.AndroidInterface.saveCurrentVersion();
                    window.AndroidInterface.setIsFirstTMSState(2);
                    UPDATE_CHECK3();
                }else {
                    window.AndroidInterface.setIsFirstTMSState(1);
                    UPDATE_CHECK2();
                }
            } else {
                window.AndroidInterface.setIsFirstTMSState(0);
                UPDATE_CHECK3();
            }
        }
    });
}
function UPDATE_CHECK1_1(){
    console.log(":: // ##################################################");
    console.log(":: //                   UPDATE_CHECK1_1                   ");
    console.log(":: // ##################################################");
    var productNo = JSON.parse(window.AndroidInterface.getMainProductNo());
    if(productNo){
        HTTP_SEND(SERVER_URL + "finpay/pos/setDeviceInfo.json", JSON.parse(window.AndroidInterface.getPosInfoData()), function(res){
//            if("0000" == res.header.resCd){
//
//            }
        });
    }
}
function TestFirstMultiBizNums(){
    HTTP_SEND(SERVER_URL + "finpay/pos/setFirstMultiBizNums.json", JSON.parse(window.AndroidInterface.getMultiBizNums()), function(res){
        if(res){

        }
    });
}

function UPDATE_CHECK2(){
    console.log(":: // ##################################################");
    console.log(":: //                   UPDATE_CHECK2                   ");
    console.log(":: // ##################################################");
    if(1 == window.AndroidInterface.getIsFirstTMSState()){
        var sendData = JSON.parse(window.AndroidInterface.getMultiBizNums());
        if(!sendData.multi_registration_no){
            HTTP_SEND(SERVER_URL + "finpay/pos/setFirstMultiBizNums.json", sendData, function(res){
                if(res){
                    if("0000" == res.header.resCd){
                        window.AndroidInterface.setIsFirstTMSState(2);
                    } else {
                        window.AndroidInterface.setIsFirstTMSState(1);
                    }
                    UPDATE_CHECK3();
                }
            });
        }else {
            window.AndroidInterface.setIsFirstTMSState(2);
            UPDATE_CHECK3();
        }

    }else {
        UPDATE_CHECK3();
    }
}
function UPDATE_CHECK3(){
    console.log(":: // ##################################################");
    console.log(":: //                   UPDATE_CHECK3                   ");
    console.log(":: // ##################################################");
    if(window.AndroidInterface.isTMSLastConnectionCheck()){
        var productNo = JSON.parse(window.AndroidInterface.getMainProductNo());
        if(productNo){
            if(isTodayChecked(getCurrentPageProperties())){
                HTTP_SEND(SERVER_URL + "finpay/pos/getPosInfo.json", productNo, function(res){
                    if(res){
                        if("0000" == res.header.resCd){
                            window.AndroidInterface.updateAlertShow(JSON.stringify(res), getCurrentPageProperties());
                            window.AndroidInterface.setTMSLastConnectionTime();
                        }
                    }
                });
            }
        }
    }
}
function isTodayChecked(pageType){
    if("settings" == pageType){
        return window.AndroidInterface.isSetPageUpdateCheck();
    }else {
        return window.AndroidInterface.isPayPageUpdateCheck();
    }
}
function getCurrentPageProperties(){
    var fileName = location.pathname.split("/").slice(-1);
    if("01_01.html" == fileName || "01_02.html" == fileName || "01_03.html" == fileName
       || "01_02_2.html" == fileName || "01_02_3.html" == fileName
       || "01_04.html" == fileName || "01_05.html" == fileName){
        return "settings";
    }else if("02_01_1.html" == fileName || "02_02_1.html" == fileName || "02_03_1.html" == fileName
             || "02_04_1.html" == fileName || "04_01.html" == fileName || "04_02.html" == fileName
             || "04_03.html" == fileName || "04_04.html" == fileName){
        return "pay";
    }else {
        return "normal";
    }
}
//- pageUtil end

