var fMarkingCardNum = "";
var payType = "";
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>");
                }else {
                    useType = '통합형';
                }
                app.setSubTitle();
            }
        }, null);
        app.getKakaoPayData();
    },
    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 ($("#layerPopup.Popup13").is(':visible')){
            isPopupClose = true;
            app.hideWarnningPopup2();
        }
        if ($("#popup_fb.PopupFB").is(':visible')){
            isPopupClose = true;
            close_Fallback();
        }
        if(!isPopupClose){
            cordova.plugins.finPlugin.backButton("", null, null);
        }
    },
    setBattery:function(battery){
        $('#battery').html(battery);
    },
    setSubTitle:function(){
        var data = {"sepa":"common_kakao"};
        cordova.plugins.finPlugin.getSignTitle(data,function(title){
            $('.title').html(title);
        },function(error){

        });
    },
    numberWithCommas:function(x) {
        return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    },
    changeAmount:function(_val){
        //가격 변동 시 계속 갱신
        if(!isIphone()) cordova.plugins.finPlugin.changePrice(replaceAll(_val,",",""), null, null);
    },
    changeInst:function(_val){
        //할부 개월 변동 시 계속 갱신
        if(!isIphone()) cordova.plugins.finPlugin.changeInstPlan(replaceAll(_val,",",""), null, null);
    },
    changeCompany:function(_val){
        if(!isIphone()) cordova.plugins.finPlugin.changeCompany(_val, null, null);
    },
    getKakaoPayData:function(){
        cordova.plugins.finPlugin.getKakaoPayData("",
        function(res){
            app.setKakaoPayData(res);
        },
        function(error){
        });
    },
    setCardInfo:function(_val){
        close_Progress();
        $("#uCardN").val(_val);
        app.setSignButton("C" == payType);
    },
    setCardNum:function(res){
        app.setCardInfo(res);
    },
    setKakaoPayData:function(kakaoData){

        var dataObject;
        if(isIphone()) {
            dataObject = JSON.parse(kakaoData);
        } else {
            dataObject = kakaoData;
        }
        $("#uSum").val(dataObject.price);
        app.setDisableAmount(true);
        $("#slt_company").html('');
        var data = "<option value='" + dataObject.catId + "'>" + dataObject.companyName + "(" + dataObject.companyNumber + ")</option>";
        $("#slt_company").html(data);
        $("#slt_company").val(dataObject.catId).prop("selected", true);
        $("#uDiscount").val(dataObject.discount);
        $("#uInstPlan").val(dataObject.month);
        
        payType = dataObject.payType;
        app.setDisableMerchant(true);
        app.setCardInfo(dataObject.referenceNo);
        
        if("C" == payType){
            app.setDisableInstallment(false);
        }else if("D" == dataObject.payType){
            $("#uInstPlan_label").hide();
            $("#uInstPlan").hide();
        }
    },
    requestSign:function(){
        var price = $("#uSum").val(); // 판매금액 입력값
        var month = $("#uInstPlan").val(); // 할부개월 입력값
        var catId = $(".company").val(); // 상호 선택값
        var cardnum = $("#uCardN").val(); // 카드번호 입력값

        if(price == "" || catId == "" || cardnum == ""){
            app.showWarnningPopup();
        }else{
                
            var sendData = {
                "catId":$(".company").val(),
                "price":replaceAll($("#uSum").val(), ",", ""),
                "month":$("#uInstPlan").val(),
                "referenceNo":$("#uCardN").val(),
                "sepa":"common_kakaopay"
            };
            if("C" == payType){
                open_PopupError('결제 승인 요청 중 입니다.');
                cordova.plugins.finPlugin.checkNoCVMValue(sendData, function(res){
                    if(1 > res){
                        app.requestPayment("");
                    }else {
                        SIGN.DATA.SUBTITLE = $('.title').html();
                        SIGN.DATA.CARDINFO = cardnum;
                        SIGN.DATA.merchant    = $(".company").val();
                        SIGN.DATA.price       = $("#uSum").val();
                        SIGN.DATA.installment = $("#uInstPlan").val();
                        SIGN.DATA.SEPA = "common_kakaopay";
                        cordova.plugins.finPlugin.requestSignData(SIGN.DATA,function(signData){
                            app.requestPayment(signData);
                        }, function(error){
                            showToastMessage(error);
                        });
                    }
                }, function(error){
                    showToastMessage(error);
                });
            }else {
                open_PopupError('결제 승인 요청 중 입니다.');
                app.requestPayment("");
            }
        }
    },
    requestPayment:function(signData){
//        open_PopupError('결제 승인 요청 중 입니다.');
        setTimeout(function(){
            var sendData = {
                "catId":$(".company").val(),
                "price":replaceAll($("#uSum").val(), ",", ""),
                "month":$("#uInstPlan").val(),
                "sign":signData,
                "referenceNo":$("#uCardN").val(),
                "sepa":"common_kakaopay"
            };
            cordova.plugins.finPlugin.requestPayment(sendData, function(dbId){
                close_PopupError();
                if(!isIphone()) //ios는 native에서 자체 이동
                 {
                     open_PopupError('결제가 완료 되었습니다.');
                     var receiptStack;
                     if("C" == payType){
                        RECEIPT_KAKAO_PAY.DATA.RECEIPT_ID = dbId;
                        receiptStack = RECEIPT_KAKAO_PAY.DATA;
                     }else {
                        RECEIPT_KAKAO_MONEY.DATA.RECEIPT_ID = dbId;
                        receiptStack = RECEIPT_KAKAO_MONEY.DATA;
                     }
                     cordova.plugins.finPlugin.moveStack(receiptStack,null, null);
                 }

            }, function(error){
                if(error) open_PopupError(error);
                else open_PopupError('결제 요청에 실패 하였습니다.');
                if('통합형' == useType){
                    cordova.plugins.finPlugin.backButton("", null, null);
                }
            });
        },100);
    },
    setDisableAmount:function(_state) {
        $("#uSum").prop("disabled", _state);
    },
    setDisableInstallment:function(_state) {
        $("#uInstPlan").prop("disabled", _state);
    },
    setDisableMerchant:function(_state) {
        $("#slt_company").prop("disabled", _state);
    },
    setSignButton:function(isSign){
        if(isSign == true) {
            app.setDisableAmount(true);
            //app.setDisableInstallment(true);
            app.setDisableMerchant(true);
            var sendData = {
                "catId":$(".company").val(),
                "price":replaceAll($("#uSum").val(), ",", ""),
                "sepa":"common_kakaopay"
            };
            cordova.plugins.finPlugin.checkNoCVMValue(sendData, function(res){
                if(1 > res){
                    $(".SaveBtnWrap02").html( "<a href='#' onclick='app.requestSign();' class=''>승인요청(무서명)</a>");
                }else {
                    $(".SaveBtnWrap02").html( "<a href='#' onclick='app.requestSign();' class=''>서명요청</a>");
                }
            }, function(error){
                showToastMessage(error);
            });
        }else {
            app.setDisableAmount(true);
            //app.setDisableInstallment(true);
            app.setDisableMerchant(true);
            $(".SaveBtnWrap02").html( "<a href='javascript:app.requestSign();' class=''>승인요청(무서명)</a>");
        }
    },
    showWarnningPopup:function(){
        close_Progress();
        $('#layerPopup.Popup12').show();
    },
    hideWarnningPopup:function(){
        $('#layerPopup.Popup12').hide();
    },
    hideWarnningPopup2:function(){
        $('#layerPopup.Popup13').hide();
    }
    ,makeEnableInputText:function()
    {
        app.setDisableAmount(false);
        app.setDisableInstallment(false);
        app.setDisableMerchant(false);
        $("#uCardN").val('');
    },errorOfPaymentByNetwork:function()
    {
        close_PopupError();
        open_PopupError('네트워크 문제로 인하여 결제 요청에 실패 하였습니다.');
        cordova.plugins.finPlugin.backButton("", null, null);
    }
    
};

app.initialize();