var oldBusinessNumber = "";
var oldProductNumber = "";
var app = {
    // Application Constructor
    initialize: function() {
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    },

    // deviceready Event Handler
    //
    // Bind any cordova events here. Common events are:
    // 'pause', 'resume', etc.
    onDeviceReady: function() {
        this.itemInit();
        this.eventInit();
        this.otherInit();
    },
    itemInit:function() {
        //상단 표기 상태 변경
        cordova.plugins.finPlugin.getUseType("", function(res){
            if(0 < res.length){
                if('연동형' == res){
                    if(isIphone()){
                      $("#hd_title").html("<a href='#' onclick='app.backbuttonAction();' ><h3 class='btnPre'><span class='blind'>이전</span></h3></a><h3 class='title'>모바일 인증</h3><h3 id='battery' class='battery'><span></span></h3>");
                      cordova.plugins.finPlugin.checkBattery("", function(battery){
                          updateBattery(true, battery)
                      },function(error){
                          updateBattery(false, '')
                      });
                    }else {
                      $("#hd_title").html("<h3 class='title'>모바일 인증</h3><h3 id='battery' class='battery'><span></span></h3>");
                    }
                    
                }
            }
        }, null);
        //저장된 내역 조회
        app.getPosInfoSaved();
    },
    eventInit:function(){
        //인증하기 팝업 열기
        $('#mobileAuth').on('click',function(){
            app.showAuthRequestPopup();
        });
        //인증 취소 버튼
        $('#authCancel').on('click',function(){
            app.hideAuthRequestPopup();
        });
        //인증 요청 버튼
        $('#authRequest').on('click',function(){
            var authData = {
                "businessNum":$("#businessNumber").val(),
                "productNum":$("#productNumber").val()
            };
            var successCallback = function(res){
                //성공 하고 나면 01_02_2.html 화면으로 이동
                //화면 이동 후 사업장 리로드
                //cordova.plugins.finPlugin.moveStack(SET02_1.DATA,null, null);
                app.setCompanyInfo(res.name, res.company, res.address, res.phone);
            };
            var failureCallback = function(error){
                close_Progress();
                //실패 시 실패 팝업 발생
                open_PopupError(error);
            };
            cordova.plugins.finPlugin.requestPosAuth(authData, successCallback, failureCallback);
            open_Progress('사업장 인증정보를 보내고 있습니다.');
            return false;
        });
        //저장 버튼
        $('#allSave').on('click',function(){
            var authData = {
                "businessNum":$("#businessNumber").val(),
                "productNum":$("#productNumber").val()
            };
            var successCallback = function(res){
                app.hideAuthRequestPopup();
                close_Progress();
                app.uploadCompanyInfo();
            };
            var failureCallback = function(error){
                //실패 시 실패 팝업 발생
                close_Progress();
                open_PopupError(error);
            };
            cordova.plugins.finPlugin.requestMainSave(authData, successCallback, failureCallback);
            open_Progress('모바일 인증 결과를 저장 중입니다.');
            return false;
        });
    },
    otherInit:function(){
        if(isIphone()){
            cordova.plugins.finPlugin.checkCompanyInfo('', function(res){
                app.setPosBizPrdNumForScheme(res);
            }, function(error){
                
            });
        }
        document.addEventListener("backbutton", app.backbuttonAction, false);
        UPDATE_CHECK();
    },
    backbuttonAction:function(){
        var isPopupClose = false;
        if ($("#layerPopup.Popup05").is(':visible')){
            isPopupClose = true;
            app.hideInputPinPopup();
        }
        if ($("#layerPopup.Popup08").is(':visible')){
            isPopupClose = true;
            app.hideAuthRequestPopup();
        }
        if(!isPopupClose){
            cordova.plugins.finPlugin.backButton("", null, null);
        }
    },
    getPosInfoSaved:function(){
        var successCallback = function(res){
            if(!isIphone()){
                oldBusinessNumber = res.bizNum;
                oldProductNumber = res.bizProd;
                app.setMainPosData(res.bizOwner, res.bizName, res.bizAddress, res.bizTel);
            }
        };
        var failureCallback = function(error){
            open_PopupError(error);
        };
        cordova.plugins.finPlugin.getMainBizData("",successCallback, failureCallback);
    },
    setBattery:function(battery){
        $('#battery').html(battery);
    },
    showAuthRequestPopup:function(){
        $("#businessNumber").val("");
        $("#productNumber").val("");
        $('#layerPopup.Popup08').show();
    },
    showAuthRequestPopup:function(bizNum, prdNum){
        $("#businessNumber").val(bizNum);
        $("#productNumber").val(prdNum);
        $('#layerPopup.Popup08').show();
    },
    setPosBizPrdNumForScheme:function(res)
    {
        var dataObject = JSON.parse(res);
        
        $("#businessNumber").val(dataObject['bizNum']);
        $("#productNumber").val(dataObject['prdNum']);
        $('#layerPopup.Popup08').show();
    },
    hideAuthRequestPopup:function(){
        $("#businessNumber").val("");
        $("#productNumber").val("");
        $('#layerPopup.Popup08').hide();
    },
    showInputPinPopup:function(type){
        close_Progress();
        if('SCS' == type){
            $('.pinInputContent').html('<li><span class=\'blu_divice\'></span> 디바이스를 등록하려면 </li><li>기기의 \'*\'버튼을 빠르게 3번눌러</li><li>프린트된 비밀번호 를 입력하세요.</li>');
        }else if('PRINT' == type){
            $('.pinInputContent').html('<li><span class=\'blu_divice\'></span> 디바이스를 등록하려면 </li><li>기기의 전원버튼을 빠르게 3번눌러</li><li>프린트된 비밀번호 를 입력하세요.</li>');
        }else {
            $('.pinInputContent').html('<li><span class=\'blu_divice\'></span> 디바이스를 등록하려면 </li><li>기기의 전원버튼을 빠르게 3번눌러</li><li>프린트된 비밀번호 를 입력하세요.</li>');
        }
        $('#layerPopup.Popup05').show();
    },
    hideInputPinPopup:function(){
        $('#layerPopup.Popup05').hide();
    },
    showSaveCompletedPopup:function(){
        $('#layerPopup.Popup07').show();
    },
    hideSaveCompletedPopup:function(){
        $('#layerPopup.Popup07').hide();
    },
    setCompanyInfo:function(name, company, address, phone){
        close_Progress();
        if(name != 0){
            $(".clist_name").addClass("ok");
            $(".clist_name").text(name);
        }
        if(company != 0){
            $(".clist_company").addClass("ok");
            $(".clist_company").text(company);
        }
        if(address != 0){
            $(".clist_address").addClass("ok");
            $(".clist_address").text(address);
        }
        if(phone != 0){
            $(".clist_phone").addClass("ok");
            $(".clist_phone").text(phone);
        }
        var failMessage = "";
        if(!$(".clist_name").hasClass("ok")){
            failMessage += "대표자명";
        }
        if(!$(".clist_company").hasClass("ok")){
            var comma = "";
            if(0 != failMessage.length) comma = ", "
            failMessage = failMessage + comma + "상호명";
        }
        if(!$(".clist_address").hasClass("ok")){
            var comma = "";
            if(0 != failMessage.length) comma = ", "
            failMessage = failMessage + comma + "주소지";
        }
        if(!$(".clist_phone").hasClass("ok")){
            var comma = "";
            if(0 != failMessage.length) comma = ", "
            failMessage = failMessage + comma + "연락처";
        }
        if(0 < failMessage.length){
            open_PopupError(failMessage + "항목이 없어 모바일 인증 저장을 할 수 없습니다. 고객센터로 연락하여 정보 등록 바랍니다.");
        }
    },
    setMainPosData:function(owner, bizName, bizAddress, bizCallNumber){
        var data = '';
        data = " <label for='owner' class='marginT16'>대표자명 </label>"
                + "<input type='text' class='uCardN' id='owner' value='" + owner + "'  disabled />"
                + "<label for='bizName' class='marginT16'>상호</label>"
                + "<input type='text' class='uCardN' id='bizName' value='" + bizName + "'  disabled />"
                + "<label for='bizAddress' class='marginT16'>주소</label>"
                + "<input type='text' class='uCardN' id='bizAddress' value='" + bizAddress + "'  disabled />"
                + "<label for='bizCallNumber' class='marginT16'>연락처 </label>"
                + "<input type='text' class='uCardN' id='bizCallNumber' value='" + bizCallNumber + "'  disabled />";
        $(".inputWrap03").html(data);
    },setMainPosDataIOS:function(owner, bizName, bizAddress, bizCallNumber, biznum, prdnum){
        
        oldBusinessNumber = biznum;
        oldProductNumber = prdnum;
        
        var data = '';
        data = " <label for='owner' class='marginT16'>대표자명 </label>"
                + "<input type='text' class='uCardN' id='owner' value='" + owner + "'  disabled />"
                + "<label for='bizName' class='marginT16'>상호</label>"
                + "<input type='text' class='uCardN' id='bizName' value='" + bizName + "'  disabled />"
                + "<label for='bizAddress' class='marginT16'>주소</label>"
                + "<input type='text' class='uCardN' id='bizAddress' value='" + bizAddress + "'  disabled />"
                + "<label for='bizCallNumber' class='marginT16'>연락처 </label>"
                + "<input type='text' class='uCardN' id='bizCallNumber' value='" + bizCallNumber + "'  disabled />";
        $(".inputWrap03").html(data);
    },
    mobileSetting:function(){
        var data = SET01.DATA;
        cordova.plugins.finPlugin.moveStack(data, null,null);
    },
    mobileIntegrity:function(){
        var data = SET03.DATA;
        cordova.plugins.finPlugin.moveStack(data, null,null);
    },mobileVatSet:function(){
        var data = SET04.DATA;
        cordova.plugins.finPlugin.moveStack(data, null,null);
    },mobileMultiCert:function(){
       
        var data = SET02_2.DATA;
        cordova.plugins.finPlugin.moveStack(data, null,null);
    },
    mobileUserSet:function(){
        var data = SET05.DATA;
        cordova.plugins.finPlugin.moveStack(data, null,null);
    },
    uploadCompanyInfo:function(){
        app.getPosInfoSaved();
        var sendData = {
            "del_businessNum": oldBusinessNumber,
            "del_productNum": oldProductNumber
        }
         cordova.plugins.finPlugin.setDeviceInfoChange(sendData,function(deviceInfoChange){
             var sendData = JSON.parse(deviceInfoChange);
             if(isIphone()){
                 HTTP_SEND("finpay/pos/setMainChange.json", sendData, function(res){
                         if(res){
                             if("0000" == res.header.resCd){
                                 //저장된 설정값이 업로드 되었으면 상태값을 1로 변경
                                 cordova.plugins.finPlugin.setTMSStatus(2,null,null);
                             } else {
                                 cordova.plugins.finPlugin.setTMSStatus(0,null,null);
                             }
                         }
                         location.reload();
                 });
             }else {
                 HTTP_SEND("finpay/pos/setMainChange.json", sendData, function(res){
                         if(res){
                             if("0000" == res.header.resCd){
                                 //저장된 설정값이 업로드 되었으면 상태값을 1로 변경
                                 cordova.plugins.finPlugin.setTMSStatus(2,null,null);
                             } else {
                                 cordova.plugins.finPlugin.setTMSStatus(0,null,null);
                             }
                         }
                         location.reload();
                 });
             }
             //cordova.plugins.finPlugin.moveStack(SET02_1.DATA, null, null);
         }, function(error){
             //업로드 실패 시 상태값은 0
             cordova.plugins.finPlugin.setTMSStatus(0,null,null);
             location.reload();
         });
    }
};

app.initialize();