var maxConfirmLength = 13;
var useType = '';
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() {
       $(document).on("keyup", ".uPayN", function() {
           $(this).number(true);
       });
       if ($(".uPayN").length > 0) {
           $(".uPayN").number(true);
       }
        //상단 표기 상태 변경
        cordova.plugins.finPlugin.getUseType("", function(res){
                                             
            if(0 < res.length){
                if('연동형' == res){
                useType = '연동형';
                    $("#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>");
                    app.initSegmentForPeristalsis();
                    //연동형 인경우 스키마 값 체크
                    cordova.plugins.finPlugin.checkScheme("", function(isScheme){
                        //스키마 값이 있는 경우 해당 번호 기반으로 인증 정보를 가져와야 한다
                        app.getSchemeData();
                    }, function(error){
                        //스키마 값이 없는 경우 해당 앱에 정보 없음 Callback 을 한다.
                    });
                }else {
                    useType = '통합형';
                    app.initSegmentForIntegrated();
                    //통합형 인 경우 연결된 모든 사업장을 가져온다
                    app.getAllBizData();
                }
                app.onChageIssue($('#slt_issue').val());
            }
        }, null);
        
    },
    eventInit:function(){
        
    },
    otherInit:function(){
        document.addEventListener("backbutton", app.backbuttonAction, false);
        UPDATE_CHECK();
    },
    backbuttonAction:function(){
        
        var isPopupClose = false;
        if ($("#layerPopup.Popup12").is(':visible')){
            isPopupClose = true;
            app.hideWarnningPopup();
        }
        if(!isPopupClose){
            cordova.plugins.finPlugin.backButton("", null, null);
        }
        
    },
    setBattery:function(battery){
        $('#battery').html(battery);
    },
    getSchemeData:function(){
        cordova.plugins.finPlugin.getSchemeData("", function(schemeData){
            app.setSchemeData(schemeData);
        },function(error){
            if(isIphone()) cordova.plugins.finPlugin.moveStack(SET01.DATA,null, null);
        });
    },
    setSchemeData:function(schemeData){
        var dataObject = JSON.parse(schemeData);

        if(isIphone())
        {
            $("#uSum").val(dataObject['totalAmount']);
            app.setDisableAmount(true);
            
            var selectIssue = dataObject['instlmtMonth'];
            var issueDisableCheck = false;
            if (selectIssue == "0") {
                issueDisableCheck = true;
                selectIssueVal = "소비자 소득공제";
            } else if (selectIssue == "1"){
                issueDisableCheck = true;
                selectIssueVal = "사업자 지출증빙";
            } else if("99"==selectIssue){
                issueDisableCheck = true;
                selectIssueVal = "자진발급";
            }else {
                selectIssueVal = "소비자 소득공제";
            }
            
            $("#slt_issue").val(selectIssueVal).prop("selected", true);
            app.onChageIssue(selectIssueVal);
            app.setDisableIssue(issueDisableCheck);
            $("#slt_company").html('');
            var valuer = dataObject['productNumber'] + "|" + dataObject['businessNumber'] + "|" + dataObject['readerNumber'];
            var data = "<option value='" + valuer + "'>" + dataObject['businessName'] + "(" + dataObject['businessNumber'] + ")</option>";
            $("#slt_company").html(data);
            $("#slt_company").val(valuer).prop("selected", true);
            app.setDisableMerchant(true);
        }else
        {
            $("#uSum").val(dataObject.totalAmount);
            app.setDisableAmount(true);

            var selectIssue = dataObject.issuedName;
            var selectIssueVal = "";
            var issueDisableCheck = false;
            if("0"==selectIssue){
                selectIssueVal = "소비자 소득공제";
                issueDisableCheck = true;
            }else if("1"==selectIssue){
                selectIssueVal = "사업자 지출증빙";
                issueDisableCheck = true;
            } else if("99"==selectIssue){
                selectIssueVal = "자진발급";
                issueDisableCheck = true;
            } else {
                selectIssueVal = "소비자 소득공제";
            }
            $("#slt_issue").val(selectIssueVal).prop("selected", true);
            app.onChageIssue(selectIssueVal);
            app.setDisableIssue(issueDisableCheck);

            $("#slt_company").html('');
            var data = "<option value='" + dataObject.catId + "'>" + dataObject.storeName + "(" + dataObject.companyNumber + ")</option>";
            $("#slt_company").html(data);
            $("#slt_company").val(dataObject.catId).prop("selected", true);
            app.setDisableMerchant(true);
        }
        
        
        
    },
    showToastMessage:function(message){
        open_Progress(message);
        setTimeout(function(){
            close_Progress();
        }
        ,1500);
    },
    getAllBizData:function(){
        var successCallback = function(res){
            //성공 하고 나면 01_02_2.html 화면으로 이동
            //화면 이동 후 사업장 리로드
            //cordova.plugins.finPlugin.moveStack(SET02_1.DATA,null, null);
            app.setCompanyList(res);
        };
        var failureCallback = function(error){
            //실패 시 실패 팝업 발생
            open_PopupError(error);
        };
        var sendData = {
            "sepa":"cash"
        };
        cordova.plugins.finPlugin.getAllBizData(sendData, successCallback, failureCallback);
    },
    setCompanyList:function(data){
         var html = "";
         var isOneCompany = false;
         if(isIphone())
         {
             var dataArray = data['merchantsList'];
             
//             if(dataArray.length == 1) {
//                 $("#bizInfo.inputWrap").html('');
//                 var dataObject = JSON.parse(dataArray.pop());
//                 app.changeCompany(dataObject['readerNumber']);
//                 return;
//             }
             if(dataArray.length == 1) isOneCompany = true;
             
             var tmpCnt = 0;
             while (dataArray.length > 0)
             {
                 //if(0 == tmpCnt) app.changeCompany(dataObject['readerNumber']);
                 var dataObject = JSON.parse(dataArray.pop());
                 var bizName = dataObject['storeName'];
                 var bizNumber = dataObject['businessNumber'];
                 var proNumber = dataObject['productNumber'];
                 var redNumber = dataObject['readerNumber'];
                 var valuer = proNumber + "|" + bizNumber + "|" + redNumber;
                 if(0 == tmpCnt) app.changeCompany(valuer);
                 html = html + "<option value='" + valuer + "'>" + bizName + "(" + bizNumber + ")</option>";
                 tmpCnt++;
             }
         } else {
             var dataArray = JSON.parse(data);

             if(dataArray.length == 1) isOneCompany = true;
             var tmpCnt = 0;
             while (dataArray.length > 0) {
                 var dataObject = dataArray.pop();
                 if(0 == tmpCnt) app.changeCompany(dataObject.cat_id);
                 html = html + "<option value='" + dataObject.cat_id + "'>" + dataObject.biz_name + "(" + dataObject.biz_number + ")</option>";
                 tmpCnt++;
             }
         }
         $("#slt_company").html(html);
         //사업장이 하나라면 화면에 표기 하지 않는다
         if(isOneCompany) $("#bizInfo").hide();
         else $("#bizInfo").show();
    },
    changeAmount:function(_val){
        if(app.checkPayData()){
            app.goneReadCard();
        }else {
            app.showReadCard();
        }
        //가격 변동 시 계속 갱신
        cordova.plugins.finPlugin.changePrice(replaceAll(_val,",",""), null, null);
    },
    changeInst:function(_inst){

        if(maxConfirmLength < $("#uInstPlan").val().length){
            var splitData = $("#uInstPlan").val().substring(0, maxConfirmLength);
            $("#uInstPlan").val(splitData);
        }
        //할부 개월 변동 시 계속 갱신
        if(app.checkPayData()){
            app.goneReadCard();
        }else {
            app.showReadCard();
        }
        cordova.plugins.finPlugin.changeInstPlan($("#uInstPlan").val(), null, null);
    },
    changeCompany:function(_val){
        cordova.plugins.finPlugin.changeCompany(_val, null, null);
    },
    requestReadCard:function(){
        var price = $("#uSum").val(); // 판매금액 입력값
        $("#uInstPlan").attr('onkeyup','app.changeInst(this.value);');
        $("#uInstPlan").attr('maxlength','25');
        var instPlan = $("#uInstPlan").val(); // 확인번호 입력값
        var catId = $(".company").val(); // 상호 선택값
        if(price == "" || catId == ""){
            $("#layerPopup.Popup12").show();
        }else{
            //open_Progress('카드 읽기를 시작 합니다.');
            app.setCardNum('카드 읽기를 시작 합니다.');
            app.setDisableAmount(true);
            //app.setDisableInstallment(true);
            app.setDisableMerchant(true);
            var sendData = {
                "price":replaceAll(price, ",", ""),
                "instPlan":instPlan,
                "catId":catId,
                "sepa":"cash"
            };
            cordova.plugins.finPlugin.requestReadCard(sendData, function(res){
                app.setCardNum(res);
//                app.setCardNum('카드 읽기를 시작 합니다.');
            }, function(error){
                app.setCardNum('카드 읽기에 실패 하였습니다. 다시 시도해 주세요');
                close_Progress();
            });
        }
    },
    setCardNum:function(res){
        close_Progress();
        app.setChangeTextType();
        maxConfirmLength = 25;
        $("#uInstPlan").val(res);
        app.setDisableMerchant(true);
        app.setDisableInstallment(true);
        if(app.checkPayData()){
            app.goneReadCard();
        }else {
            app.showReadCard();
        }
    },
    onChageIssue:function(issue) {
        
      if(issue == '자진발급') {
        $("#dv_confirmNumber").html(" <label for='uInstPlan' class='marginT16' id='lb_confirmNumber'>확인번호</label>" +
            "<input type='number' id='uInstPlan' value=''> </input>");
    
        $("#read_card").html('');
        $("#read_card").removeClass('SaveBtnWrap100');
        $("#uInstPlan").val('0100001234');
        app.setDisableInstallment(true);
      } else if (issue == '발행안함'){
        $("#dv_confirmNumber").html('');
        $("#read_card").html('');
        $("#read_card").removeClass('SaveBtnWrap100');
        app.goneReadCard();
        return;
      } else {
        $("#dv_confirmNumber").html(" <label for='uInstPlan' class='marginT16' id='lb_confirmNumber'>확인번호</label>" +
            "<input type='number' id='uInstPlan' value='' onkeyup='app.changeInst(this.value);'/>");
        app.setDisableInstallment(false);
      }
      app.updateButton(issue);
    },
    checkPayData:function(){
        var priceResult = replaceAll($('#uSum').val(), '0', '');
        priceResult = replaceAll(priceResult, ',', '');

        var confirmNumberResult = false;
        var checkConfirmNum = $("#uInstPlan").val();
        if(($.isNumeric(checkConfirmNum) && 10 <= checkConfirmNum.length)
        || -1 != checkConfirmNum.indexOf('*')){
            confirmNumberResult = true;
        }else {
            confirmNumberResult = false;
        }
        if(0 < priceResult.length && confirmNumberResult){
            return true;
        }else return false;
    },
    updateButton:function(issue) {
      
      if($("#uInstPlan").val().length > 0) {
        app.goneReadCard();
      } else {
        app.showReadCard();
      }
      cordova.plugins.finPlugin.onChageIssue(issue,null,null);
    },
    setDisableIssue:function(_state){
        $("#slt_issue").prop("disabled", _state);
    },
    setDisableAmount:function(_state) {
        $("#uSum").prop("disabled", _state);
    },
    setDisableInstallment:function(_state) {
        $("#uInstPlan").prop("disabled", _state);
    },
    setDisableMerchant:function(_state) {
        $("#slt_company").prop("disabled", _state);
    },
    reqConfirm:function(){
        var price = $("#uSum").val(); // 판매금액 입력값
        var instPlan = $("#uInstPlan").val(); // 확인번호 입력값
        var catId = $(".company").val(); // 상호 선택값
        var sepa = $("#slt_issue option:selected").val(); // 발급구분
        if(price == "" || catId == ""){
            $("#layerPopup.Popup12").show();
        }else{
            open_Progress('결제 요청을 진행 합니다.');
            
            var sendData = {
                "price":replaceAll(price, ",", ""),
                "instPlan":instPlan,
                "catId":catId,
                "sepa":sepa
            };
            cordova.plugins.finPlugin.requestPayment(sendData, function(res){
                close_PopupError();
                if(!isIphone()) //ios는 native에서 자체 이동
                {
                    close_Progress();
                    RECEIPT_CASH.DATA.RECEIPT_ID = res;
                    cordova.plugins.finPlugin.moveStack(RECEIPT_CASH.DATA,null, null);
                }
                
            }, function(error){
                close_Progress();
                if(error) open_PopupError(error);
                else open_PopupError('결제 요청에 실패 하였습니다.');
            });
        }
        
    },
    showReadCard:function() {
      $(".SaveBtnWrap02").html("<a href='javascript:app.requestReadCard();' class=''>카드읽기</a>");
    },
    goneReadCard:function() {
      $(".SaveBtnWrap02").html("<a href='javascript:app.reqConfirm();' class=''>승인요청</a>");
    },
    setChangeTextType:function(){
          var f = document.getElementById("uInstPlan");
          f.type= "text";
    },
    showWarnningPopup:function(){
        close_Progress();
        $('#layerPopup.Popup12').show();
    },
    hideWarnningPopup:function(){
        $('#layerPopup.Popup12').hide();
    },errorOfPaymentByNetwork:function()
    {
        close_PopupError();
        open_PopupError('네트워크 문제로 인하여 결제 요청에 실패 하였습니다.');
        cordova.plugins.finPlugin.backButton("", null, null);
    },
    initSegmentForPeristalsis:function(){
        //연동형 전용 옵션
        $('#slt_issue').empty();
        $('#slt_issue').append('<option value="소비자 소득공제">소비자 소득공제</option>');
        $('#slt_issue').append('<option value="사업자 지출증빙">사업자 지출증빙</option>');
        $('#slt_issue').append('<option value="자진발급">자진발급</option>');
    },
    initSegmentForIntegrated:function(){
        //통합형 전용 옵션
        $('#slt_issue').empty();
        $('#slt_issue').append('<option value="소비자 소득공제">소비자 소득공제</option>');
        $('#slt_issue').append('<option value="사업자 지출증빙">사업자 지출증빙</option>');
        $('#slt_issue').append('<option value="자진발급">자진발급</option>');
        $('#slt_issue').append('<option value="발행안함">발행안함</option>');
        
    }
};

app.initialize();
