var approvalNum;
var tradeDate;
var instPlan;
var catId;
var companyName;
var businessNumber;
var productNumber;
var referenceNo;
var kakaoPayType;
var kakaoDiscount;
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>");
                    //연동형 인경우 스키마 값 체크
                    cordova.plugins.finPlugin.checkScheme("", function(isScheme){
                        //스키마 값이 있는 경우 해당 번호 기반으로 인증 정보를 가져와야 한다
                        app.getSchemeData();
                    }, function(error){
                        //스키마 값이 없는 경우 해당 앱에 정보 없음 Callback 을 한다.
                    });
                }else {
                    useType = '통합형';
                    app.getCancelData();
                }
            }
        }, null);
        if(isIphone()){
          cordova.plugins.finPlugin.getAliCost("", function(res){
              $("#uSum").val(res);
          }, function(error){
              alert(error);
          });
        }else {
          app.setAliManualData();
        }
    },
    eventInit:function(){
       
    },
    otherInit:function(){
        document.addEventListener("backbutton", app.backbuttonAction, false);
    },
    backbuttonAction:function(){
        var isPopupClose = false;
        if ($("#layerPopup.Popup12").is(':visible')){
            isPopupClose = true;
            app.hideWarnningPopup();
        }
        if(!isPopupClose){
            cordova.plugins.finPlugin.backButton("", null, null);
        }
    },
    setAliManualData:function(){
        cordova.plugins.finPlugin.getAliManualAmount("", function(manualData){
            var dataObject = JSON.parse(manualData);
            $("#uSum").val(dataObject.price);
            catId = dataObject.catId;
        }, function(error){
            showToastMessage(error);
        });
    },
    changeKakaoPayNum:function(uniqNum){
        cordova.plugins.finPlugin.changeKakaoPayNum(uniqNum, null, null);
    },
    hideWarnningPopup:function(){
        $('#layerPopup.Popup12').hide();
    },
    getCancelData:function(){
         var successCallback = function(res){
             app.setCancelData(res);
         };
         var failureCallback = function(error){
             open_PopupError(error);
         };
         //취소 데이터 가져오기
         if(isIphone())
         {
             var dt = {"TYPE":"COMMON_CARD"};
             cordova.plugins.finPlugin.getCancelData(dt, successCallback, failureCallback);
         }else
         {
             cordova.plugins.finPlugin.getCancelData("", successCallback, failureCallback);
         }
     },
     setCancelData:function(data){
         //취소 데이터 화면에 셋팅 하기
         var cancelData = JSON.parse(data);
         if(isIphone())
         {
            approvalNum = cancelData['approvalNumber'];
            tradeDate = cancelData['dateOfApproval'];
            instPlan = cancelData['installment'];
            businessNumber = cancelData['businessName'];
            catId = cancelData['readerNumber'];
             $('#uSum').val(cancelData['totalAmount']);
             businessNumber = cancelData['businessNumber'];
             productNumber = cancelData['productNumber'];
             kakaoPayType = cancelData['kakaoPayType'];
         }else {
             approvalNum = cancelData.approvalNumber;
             tradeDate = cancelData.tradeDate;
             instPlan = cancelData.instPlan;
             companyName = cancelData.companyName;
             catId = cancelData.catId;
             kakaoPayType = cancelData.kakaoPayType;
             kakaoDiscount = cancelData.kakaoDiscount;
             referenceNo = cancelData.referenceNo;
             $('#uSum').val(cancelData.totalAmount);
             $('#uDiscount').val(kakaoDiscount);
             $("#uDiscount").prop("disabled", true);
             $("#slt_company").html('');
             var data = "<option value='" + catId + "'>" + companyName + "</option>";
             $("#slt_company").html(data);
             $("#slt_company").val(catId).prop("selected", true);
             app.setDisableMerchant(true);
         }
     },
    requestPayment:function(){
        if (isClickedButton()) {
            return;
        }
        var price = replaceAll($("#uSum").val(),",",""); // 판매금액 입력값
        
        if(isIphone()){
            if(price == ""){
                $("#layerPopup.Popup12").show();
            }else{
                var data = {
                    "PRICE":$("#uSum").val(),
                    "ALINUM":$("#uniqueNumber").val()
                };
                cordova.plugins.finPlugin.reqConfirmAliSelfInput(data, function(res){
                    alert(res);
                }, function(error){
                    alert(error);
                });
            }
        }else {
            if(price == "" || catId == ""){
                $("#layerPopup.Popup12").show();
            }else{
                var sendData = {
                    "price":price,
                    "catId":catId,
                    "sepa":"cancel_kakaoInquiry",
                    "kakaoUniqNum":$("#uniqueNumber").val()
                };
                cordova.plugins.finPlugin.requestKakaoInquiry(sendData,
                function(res){
                    close_PopupError();
                    if("C" == res){
                        KAKAO_CAN.DATA.SUBTITLE = "카카오페이 신용 취소결제";
                    }else {
                        KAKAO_CAN.DATA.SUBTITLE = "카카오페이 머니 취소결제";
                    }
                    cordova.plugins.finPlugin.moveStack(KAKAO_CAN.DATA,null, null);
               },
               function(error){
                    if(error) open_PopupError(error);
                    else open_PopupError('결제 요청에 실패 하였습니다.');
                    if('통합형' == useType){
                         cordova.plugins.finPlugin.backButton("", null, null);
                    }
               });
            }
        }
        
    }
};

app.initialize();

