//input number maxLength
var INTRO = {"URL":"../html/loadintro.html","DATA":{"STACK_ID":"INTRO","STACK_URL":"loadintro.html"}};

var INDEX = {"URL":"../html/index.html","DATA":{"STACK_ID":"INDEX","STACK_URL":"index.html"}};

var MAIN = {"URL":"../html/main.html","DATA":{"STACK_ID":"MAIN","STACK_URL":"main.html"}};
var SET01 = {"URL":"../html/01_01.html","DATA":{"STACK_ID":"SET01","STACK_URL":"01_01.html"}};
var SET02 = {"URL":"../html/01_02.html","DATA":{"STACK_ID":"SET02","STACK_URL":"01_02.html"}};
var SET02_1 = {"URL":"../html/01_02_2.html","DATA":{"STACK_ID":"SET02_1","STACK_URL":"01_02_2.html"}};
var SET02_2 = {"URL":"../html/01_02_3.html","DATA":{"STACK_ID":"SET02_2","STACK_URL":"01_02_3.html"}};
var SET03 = {"URL":"../html/01_03.html","DATA":{"STACK_ID":"SET03","STACK_URL":"01_03.html"}};
var SET03_1 = {"URL":"../html/01_03_2.html","DATA":{"STACK_ID":"SET03_1","STACK_URL":"01_03_2.html"}};
var SET03_2 = {"URL":"../html/01_03_3.html","DATA":{"STACK_ID":"SET03_2","STACK_URL":"01_03_3.html"}};
var SET04 = {"URL":"../html/01_04.html","DATA":{"STACK_ID":"SET04","STACK_URL":"01_04.html"}};
var SET05 = {"URL":"../html/01_05.html","DATA":{"STACK_ID":"SET05","STACK_URL":"01_05.html"}};
var PRIVACY_POLICY = {"URL":"","DATA":{"STACK_ID":"PRIVACY_POLICY","STACK_URL":"","RECEIPT_ID":""}};
var RECEIPT = {"URL":"../html/03_01.html","DATA":{"STACK_ID":"RECEIPT","STACK_URL":"03_01.html"}};
var RECEIPT_CARD = {"URL":"../html/03_02.html","DATA":{"STACK_ID":"RECEIPT_CARD","STACK_URL":"03_02.html","RECEIPT_ID":""}};
var RECEIPT_UNION = {"URL":"../html/03_02.html","DATA":{"STACK_ID":"RECEIPT_UNION","STACK_URL":"03_03.html","RECEIPT_ID":""}};
var RECEIPT_CASH = {"URL":"../html/03_04.html","DATA":{"STACK_ID":"RECEIPT_CASH","STACK_URL":"03_04.html","RECEIPT_ID":""}};
var RECEIPT_ALI = {"URL":"../html/03_05.html","DATA":{"STACK_ID":"RECEIPT_ALI","STACK_URL":"03_05.html","RECEIPT_ID":""}};
var RECEIPT_CASH_CAN = {"URL":"../html/03_04_3.html","DATA":{"STACK_ID":"RECEIPT_CASH_CAN","STACK_URL":"03_04_3.html","RECEIPT_ID":""}};
var RECEIPT_ALI_CAN = {"URL":"../html/03_05_3.html","DATA":{"STACK_ID":"RECEIPT_ALI_CAN","STACK_URL":"03_05_3.html","RECEIPT_ID":""}};
var RECEIPT_CARD_CAN = {"URL":"../html/03_02_3.html","DATA":{"STACK_ID":"RECEIPT_CARD_CAN","STACK_URL":"03_02_3.html","RECEIPT_ID":""}};
var RECEIPT_UNION_CAN = {"URL":"../html/03_03_3.html","DATA":{"STACK_ID":"RECEIPT_UNION_CAN","STACK_URL":"03_03_3.html","RECEIPT_ID":""}};

var RECEIPT_WECHAT = {"URL":"../html/03_07.html","DATA":{"STACK_ID":"RECEIPT_WECHAT","STACK_URL":"03_07.html","RECEIPT_ID":""}};
var RECEIPT_WECHAT_CAN = {"URL":"../html/03_05_3.html","DATA":{"STACK_ID":"RECEIPT_WECHAT_CAN","STACK_URL":"03_05_3.html","RECEIPT_ID":""}};

var RECEIPT_ZERO = {"URL":"../html/03_08.html","DATA":{"STACK_ID":"RECEIPT_ZERO","STACK_URL":"03_08.html","RECEIPT_ID":""}};
var RECEIPT_ZERO_CAN = {"URL":"../html/03_08_2.html","DATA":{"STACK_ID":"RECEIPT_ZERO_CAN","STACK_URL":"03_08_2.html","RECEIPT_ID":""}};


var SIGN = {"URL":"../html/02_01_2.html","DATA":{"STACK_ID":"SIGN","STACK_URL":"02_01_2.html","SUBTITLE":"","CARDINFO":""}};
var CARD_PAY = {"URL":"../html/02_01_1.html","DATA":{"STACK_ID":"CARD_PAY","STACK_URL":"02_01_1.html"}};
var CARD_SIGN = {"URL":"../html/02_01_2.html","DATA":{"STACK_ID":"SIGN","STACK_URL":"02_01_2.html"}};
var CARD_CAN = {"URL":"../html/04_01.html","DATA":{"STACK_ID":"CARD_CAN","STACK_URL":"04_01.html"}};

var CASH_PAY = {"URL":"../html/02_02_1.html","DATA":{"STACK_ID":"CASH_PAY","STACK_URL":"02_02_1.html"}};
var CASH_CAN = {"URL":"../html/04_02.html","DATA":{"STACK_ID":"CASH_CAN","STACK_URL":"04_02.html"}};

var UNION_PAY = {"URL":"../html/02_03_1.html","DATA":{"STACK_ID":"UNION_PAY","STACK_URL":"02_03_1.html"}};
var UNION_CAN = {"URL":"../html/04_03.html","DATA":{"STACK_ID":"UNION_CAN","STACK_URL":"04_03.html"}};

var ALI_PAY = {"URL":"../html/02_04_1.html","DATA":{"STACK_ID":"ALI_PAY","STACK_URL":"02_04_1.html"}};
var ALI_BAR = {"URL":"../html/02_04_2.html","DATA":{"STACK_ID":"ALI_BAR","STACK_URL":"02_04_2.html"}};
var ALI_INPUT = {"URL":"../html/02_04_3.html","DATA":{"STACK_ID":"ALI_INPUT","STACK_URL":"02_04_3.html"}};

var ALI_CAN = {"URL":"../html/04_04.html","DATA":{"STACK_ID":"ALI_CAN","STACK_URL":"04_04.html"}};
var ALI_CAN_BAR = {"URL":"../html/04_04_2.html","DATA":{"STACK_ID":"ALI_CAN_BAR","STACK_URL":"04_04_2.html"}};
var ALI_CAN_INPUT = {"URL":"../html/04_04_3.html","DATA":{"STACK_ID":"ALI_CAN_INPUT","STACK_URL":"04_04_3.html"}};

var WECHAT_PAY = {"URL":"../html/02_06_1.html","DATA":{"STACK_ID":"WECHAT_PAY","STACK_URL":"02_06_1.html"}};
var WECHAT_BAR = {"URL":"../html/02_06_2.html","DATA":{"STACK_ID":"WECHAT_BAR","STACK_URL":"02_06_2.html"}};
var WECHAT_INPUT = {"URL":"../html/02_06_3.html","DATA":{"STACK_ID":"WECHAT_INPUT","STACK_URL":"02_06_3.html"}};

var WECHAT_CAN_PAY = {"URL":"../html/04_06.html","DATA":{"STACK_ID":"WECHAT_CAN_PAY","STACK_URL":"04_06.html"}};
var WECHAT_CAN_BAR = {"URL":"../html/02_06_2.html","DATA":{"STACK_ID":"WECHAT_CAN_BAR","STACK_URL":"02_06_2.html"}};
var WECHAT_CAN_INPUT = {"URL":"../html/04_06_3.html","DATA":{"STACK_ID":"WECHAT_CAN_INPUT","STACK_URL":"04_06_3.html"}};

var ZERO_PAY   = {"URL":"../html/02_07_1.html","DATA":{"STACK_ID":"ZERO_PAY","STACK_URL":"02_07_1.html"}};
var ZERO_BAR   = {"URL":"../html/02_07_2.html","DATA":{"STACK_ID":"ZERO_BAR","STACK_URL":"02_07_2.html"}};
var ZERO_INPUT = {"URL":"../html/02_07_3.html","DATA":{"STACK_ID":"ZERO_INPUT","STACK_URL":"02_07_3.html"}};

var ZERO_CAN_PAY = {"URL":"../html/04_07.html","DATA":{"STACK_ID":"ZERO_CAN_PAY","STACK_URL":"04_07.html"}};
var ZERO_CAN_BAR = {"URL":"../html/02_07_2.html","DATA":{"STACK_ID":"ZERO_CAN_BAR","STACK_URL":"02_07_2.html"}};
var ZERO_CAN_INPUT = {"URL":"../html/04_07_3.html","DATA":{"STACK_ID":"ZERO_CAN_INPUT","STACK_URL":"04_07_3.html"}};

var KAKAO_SEARCH = {"URL":"../html/02_05_1.html","DATA":{"STACK_ID":"KAKAO_SEARCH","STACK_URL":"02_05_1.html"}};
var KAKAO_SEARCH_INPUT = {"URL":"../html/02_05_3.html","DATA":{"STACK_ID":"KAKAO_SEARCH_INPUT","STACK_URL":"02_05_3.html"}};
var KAKAO_PAY = {"URL":"../html/02_05_2.html","DATA":{"STACK_ID":"KAKAO_PAY","STACK_URL": "02_05_2.html"}};
var KAKAO_SEARCH_CAN = {"URL":"../html/04_05.html","DATA":{"STACK_ID":"KAKAO_SEARCH_CAN","STACK_URL":"04_05.html","RECEIPT_ID":""}};
var KAKAO_SEARCH_CAN_INPUT = {"URL":"../html/04_05_3.html","DATA":{"STACK_ID":"KAKAO_SEARCH_CAN_INPUT","STACK_URL":"04_05_3.html"}};
var KAKAO_CAN = {"URL":"../html/04_05_1.html","DATA":{"STACK_ID":"KAKAO_CAN","STACK_URL":"04_05_1.html"}};
var RECEIPT_KAKAO_PAY = {"URL":"../html/03_06_1.html","DATA":{"STACK_ID":"RECEIPT_KAKAO_PAY","STACK_URL":"03_06_1.html","RECEIPT_ID":""}};
var RECEIPT_KAKAO_MONEY = {"URL":"../html/03_06_2.html","DATA":{"STACK_ID":"RECEIPT_KAKAO_MONEY","STACK_URL":"03_06_2.html","RECEIPT_ID":""}};

var HIPASS_PAY = {"URL":"../html/02_08_1.html","DATA":{"STACK_ID":"HIPASS_PAY","STACK_URL":"02_08_1.html"}};
var HIPASS_CAN = {"URL":"../html/04_08.html","DATA":{"STACK_ID":"HIPASS_CAN","STACK_URL":"04_08.html"}};

var TODAY_CON = {"URL":"../html/05_01.html","DATA":{"STACK_ID":"TODAY_CON","STACK_URL":"05_01.html"}};
var TIME_CON = {"URL":"../html/05_02.html","DATA":{"STACK_ID":"TIME_CON","STACK_URL":"05_02.html"}};
var MONTH_CON = {"URL":"../html/05_03.html","DATA":{"STACK_ID":"MONTH_CON","STACK_URL":"05_03.html"}};

var isProcessing = false;
var mInterval;
function isClickedButton() {
    if (isProcessing) {
        return true;
    }
    isProcessing = true;
    mInterval = setInterval(function() {
        isProcessing = false;
        clearInterval(mInterval);
    }, 1000);
    return false;
}
function replaceAll(str, searchStr, replaceStr) {
  return str.split(searchStr).join(replaceStr);
}
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function isIphone(){
    var varUA = navigator.userAgent.toLowerCase(); //userAgent 값 얻기
    if (varUA.indexOf("iphone")>-1||varUA.indexOf("ipad")>-1||varUA.indexOf("ipod")>-1||varUA.indexOf("macintosh")>-1) {
        return true;
    }else if(varUA.match('android') != null){
        return false;
    }
    return false;
}
function maskCatId(_catId){
    return _catId.substring(0,3) + "****" + _catId.substring(7,_catId.length);
}
function maskAsterisk(_cardNum){
    var result = "";
    if(_cardNum.length == 12){
        result = _cardNum.substring(0,4) + "****";
    } else if(_cardNum.length == 13){
        result = _cardNum.substring(0,5) + "****";
    } else if(_cardNum.length == 14){
        result = _cardNum.substring(0,6) + "****";
    } else if(_cardNum.length == 15){
        result = _cardNum.substring(0,6) + "******";
    } else if(_cardNum.length == 16){
        result = _cardNum.substring(0,6) + "******";
    } else if(_cardNum.length == 17){
        result = _cardNum.substring(0,6) + "*******";
    } else if(_cardNum.length == 18){
        result = _cardNum.substring(0,6) + "********";
    } else if(_cardNum.length == 19){
        result = _cardNum.substring(0,6) + "*********";
    } else{
        result = _cardNum;
    }
    result = result + _cardNum.substring(result.length,_cardNum.length);
    return result.replace(/(....)(?=.)/g, "$1-");
}
function maxLengthCheck(object){
	if (object.value.length > object.maxLength){
		object.value = object.value.slice(0, object.maxLength);
	}
}
function showToastMessage(message){
    open_Progress(message);
    setTimeout(function(){
       close_Progress();
    }
    ,1500);
}
function showToastMessage(message, delay){
    open_Progress(message);
    setTimeout(function(){
       close_Progress();
    }
    ,delay);
}
function open_Progress(_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_err').innerHTML = "<div class='Dim'></div> <div class='layer-con2' id='layer_err'> <div class='hImg'> <ul>"
                                                         + msg
                                                         + "</ul> </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();
    return;
}
function close_Progress(){
    
   if($("#popup_err.PopupError").css("display") != "none")
   {
      $('#popup_err.PopupError').hide();
   }
    return;
}
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;
}
function open_saveCompleted(isSuccess) {
    if (isSuccess) {
        document.getElementById('popup_err').innerHTML = "<div class='Dim'></div> <div class='layer-con' id='layer_err'> <div class='hImg'> <ul>"
                                                                     + '저장에 성공 하였습니다.'
                                                                     + "</ul> </div> <a href='#' onclick='successVerifyConfirm();' class='okBtn'>OK</a> </div> </div>";
    } else {
        document.getElementById('popup_err').innerHTML = "<div class='Dim'></div> <div class='layer-con' id='layer_err'> <div class='hImg'> <ul>"
                                                             + '저장에 실패 하였습니다.'
                                                             + "</ul> </div> <a href='#' onclick='failVerifyConfirm();' 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();
}
function close_saveCompleted(){
    
}
function open_verifyPopup(isSuccess) {

    if (isSuccess) {
        document.getElementById('popup_err').innerHTML = "<div class='Dim'></div> <div class='layer-con' id='layer_err'> <div class='hImg'> <ul>"
                                                                     + '무결성 검사가 완료 되었습니다'
                                                                     + "</ul> </div> <a href='#' onclick='successVerifyConfirm();' class='okBtn'>OK</a> </div> </div>";
    } else {
        document.getElementById('popup_err').innerHTML = "<div class='Dim'></div> <div class='layer-con' id='layer_err'> <div class='hImg'> <ul>"
                                                             + '보안리더기 보안 침해 발생<br>[관리자 문의 요망]'
                                                             + "</ul> </div> <a href='#' onclick='failVerifyConfirm();' 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 successVerifyConfirm(){
    cordova.plugins.finPlugin.moveStack(SET03_1.DATA, null, null);
}
function failVerifyConfirm(){
    close_PopupError();
}
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();
    return;
}

function close_Fallback(){
    if($("#popup_fb.PopupFB").css("display") != "none")
   {
      $('#popup_fb.PopupFB').hide();
   }
    return;
}
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 );
}
function getAmount(amount) {
    amount = replaceAll(amount,"-","");
    amount = replaceAll(amount,"원","");
    amount = replaceAll(amount,",","");
    return amount;
}
function updateBattery(isVisible, _value) {
   if (isVisible) {
//       if ($('#homeBtn').hasClass('blind')) {
           if (document.getElementById('battery')) {
               if (!$('#battery').hasClass('blind')) {
                   $('#battery span:nth-child(1)').text(_value);
                   var pos = _value.indexOf('%');
                   var val = _value.substring(0, pos);
                   if (val > 10) {
                       $('#battery span:nth-child(1)').css('color', '#0f4765');
                   } else {
                       $('#battery span:nth-child(1)').css('color', '#bb0000');
                   }
               }
           }
//       }
   } else {
       if (document.getElementById('battery')) {
           if (!$('#battery').hasClass('blind')) {
               $('#battery span:nth-child(1)').text('');
           }
       }
   }
}
var DEBUG_DEV = false;
var SERVER_URL = "https://fas.kpn.co.kr/";//"https://fas.firstdatacorp.co.kr/";//개발서버
if(DEBUG_DEV){
	SERVER_URL="https://testfas.kpn.co.kr/";//"https://testfas.firstdatacorp.co.kr/";
}else{
	SERVER_URL="https://fas.kpn.co.kr/";//"https://fas.firstdatacorp.co.kr/";
}
//GetPosInfo 또는 setMultiBizNums 에 사용하는 POST 방식
function HTTP_SEND(url, json_req, callback){
    cordova.plugins.finPlugin.isDebugCheck("",function(isDebug){
        if("true" == isDebug){
            SERVER_URL = "https://testfas.kpn.co.kr/";//"https://testfas.firstdatacorp.co.kr/";//테스트 서버
        }else {
            SERVER_URL="https://fas.kpn.co.kr/";//"https://fas.firstdatacorp.co.kr/";//운영 서버
        }
        var sendUrl = SERVER_URL + url;
        console.log(":: // ##################################################");
        console.log(":: // HTTP_SEND(url : " + sendUrl + " )");
        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 = json_req.native_version;
        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(sendUrl);
        console.log(JSON.stringify(RequestData, null, "    "));
        $.ajax({
            url: sendUrl,
            dataType: 'json',
            type: 'POST',
            data:JSON.stringify(RequestData),
            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);
                }
            }
        });
    },null);
//    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 = json_req.native_version;
//    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(RequestData, null, "    "));
//    $.ajax({
//        url: url,
//        dataType: 'json',
//        type: 'POST',
//        data:JSON.stringify(RequestData),
//        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);
//            }
//        }
//    });
}
function UPDATE_CHECK(){

    console.log(":: // ##################################################");
    console.log(":: //                    UPDATE_CHECK                   ");
    console.log(":: // ##################################################");
    //인증 데이터 있음
    var successCallback = function(productNo){
        //최초 업로드 여부 확인
        cordova.plugins.finPlugin.getTMSStatus("",function(status){
            if(0 >= status){
                UPDATE_CHECK1();
            }else if(1 == status){
                UPDATE_CHECK2();
            }else {
                UPDATE_CHECK3();
            }
        }, null);
    };
    //인증여부 확인
    cordova.plugins.finPlugin.getMainProductNo("",successCallback, null);
}
//저장된 설정 값을 업로드 한다
function UPDATE_CHECK1(){
    console.log(":: // ##################################################");
    console.log(":: //                   UPDATE_CHECK1                   ");
    console.log(":: // ##################################################");
    cordova.plugins.finPlugin.setDeviceInfo("",function(deviceInfo){
        var sendData = JSON.parse(deviceInfo);
        if(isIphone()){
            HTTP_SEND("finpay/pos/setDeviceInfo.json", sendData, function(res){
                    if(res){
                        if("0000" == res.header.resCd){
                            //저장된 설정값이 업로드 되었으면 상태값을 1로 변경
                            cordova.plugins.finPlugin.setTMSStatus(1,null,null);
                            UPDATE_CHECK2();
                        } else {
                            cordova.plugins.finPlugin.setTMSStatus(0,null,null);
                        }
                    }
            });
        }else {
            HTTP_SEND("finpay/pos/setDeviceInfo.json", sendData, function(res){
                    if(res){
                        if("0000" == res.header.resCd){
                            //저장된 설정값이 업로드 되었으면 상태값을 1로 변경
                            cordova.plugins.finPlugin.setTMSStatus(1,null,null);
                            UPDATE_CHECK2();
                        } else {
                            cordova.plugins.finPlugin.setTMSStatus(0,null,null);
                        }
                    }
            });
        }
    }, function(error){
        //업로드 실패 시 상태값은 0
        cordova.plugins.finPlugin.setTMSStatus(0,null,null);
    });
}
//저장된 복수 사업장을 업로드 한다
function UPDATE_CHECK2(){
    console.log(":: // ##################################################");
    console.log(":: //                   UPDATE_CHECK2                   ");
    console.log(":: // ##################################################");
    //복수사업자 업로드 못한 내역이 있다면 복수사업자 한번에 업로드 하는 기능
    cordova.plugins.finPlugin.getUploadBizData("",
        function(bizData){
            if(isIphone())
            {
                var sendData = JSON.parse(bizData);
                if(sendData.serial_no && sendData.registration_no)
                {
                    HTTP_SEND("finpay/pos/setMultiBizNums.json", sendData, function(res){
                        close_Progress();
                        if(res){
                            if("0000" == res.header.resCd){
                                //업로드 성공
                                cordova.plugins.finPlugin.setTMSStatus(2,null,null);
                            } else {
                                //업로드 실패
                                cordova.plugins.finPlugin.setTMSStatus(1,null,null);
                            }
                        }else {
                                //업로드 실패
                            cordova.plugins.finPlugin.setTMSStatus(1,null,null);
                        }
                        //복수사업자 상태 상관 없이 업데이트 체크 진행
                        setTimeout(function(){UPDATE_CHECK3();},1000);
                    });
                }else {
                    //메인 사업장 정보 가져오기 실패
                }
            }else{
                var sendData = JSON.parse(bizData);
                if(sendData.serial_no && sendData.registration_no)
                {
                    HTTP_SEND("finpay/pos/setMultiBizNums.json", sendData, function(res){
                        close_Progress();
                        if(res){
                            if("0000" == res.header.resCd){
                                //업로드 성공
                                cordova.plugins.finPlugin.setTMSStatus(2,null,null);
                            } else {
                                //업로드 실패
                                cordova.plugins.finPlugin.setTMSStatus(1,null,null);
                            }
                        }else {
                                //업로드 실패
                            cordova.plugins.finPlugin.setTMSStatus(1,null,null);
                        }
                        //복수사업자 상태 상관 없이 업데이트 체크 진행
                        setTimeout(function(){UPDATE_CHECK3();},1000);
                    });
                }else {
                    //메인 사업장 정보 가져오기 실패
                }
            }
        },function(error){
            //사업장 정보 불러오는 중 에러 발생
            cordova.plugins.finPlugin.setTMSStatus(1,null,null);
        }
    );
}
//업데이트 체크를 한다
function UPDATE_CHECK3(){
    console.log(":: // ##################################################");
    console.log(":: //                   UPDATE_CHECK3                   ");
    console.log(":: // ##################################################");

    cordova.plugins.finPlugin.checkTodayTMS("",function(result){
        cordova.plugins.finPlugin.setDeviceInfo("",function(deviceInfo){
            var sendData = JSON.parse(deviceInfo);
            if(isIphone()){
                HTTP_SEND("finpay/pos/setDeviceInfo.json", sendData, function(res){
                    if(res){
                        if("0000" == res.header.resCd){
                            //저장된 설정값이 업로드 되었으면 상태값을 1로 변경
                            cordova.plugins.finPlugin.setTMSStatus(2,null,null);
                            res.pageType = getCurrentPageProperties();
                            cordova.plugins.finPlugin.checkUpdatePopup(res,null, null);
                        } else {
                            cordova.plugins.finPlugin.setTMSStatus(0,null,null);
                        }
                    }
                });
            }else {
                HTTP_SEND("finpay/pos/setDeviceInfo.json", sendData, function(res){
                    if(res){
                        if("0000" == res.header.resCd){
                            //저장된 설정값이 업로드 되었으면 상태값을 1로 변경
                            cordova.plugins.finPlugin.setTMSStatus(2,null,null);
                            res.pageType = getCurrentPageProperties();
                            cordova.plugins.finPlugin.checkUpdatePopup(res,null, null);
                        } else {
                            cordova.plugins.finPlugin.setTMSStatus(0,null,null);
                        }
                    }
                });
            }
        }, null);
    }, null);
    //오늘 체크 여부 확인
//    cordova.plugins.finPlugin.checkTodayTMS("",function(result){
//        //메인 제품번호 가져오기
//        cordova.plugins.finPlugin.getMainProductNo("",function(productNo){
//              HTTP_SEND(SERVER_URL + "finpay/pos/getPosInfo.json", productNo, function(response){
//                  if(response){
//                      console.log(":: // ##################################################");
//                      console.log(":: //                   UPDATE_CHECK3                   ");
//                      console.log(":: // ##################################################");
//                      console.log("res : " + JSON.stringify(response));
//                      response.pageType = getCurrentPageProperties();
//                      //업데이트 체크 로직 필요
//                      cordova.plugins.finPlugin.checkUpdatePopup(response,null, null);
//                  }
//              });
//        }, null);
//    }, null);
}
function setOptions(settingsValue) {
    var sendData = JSON.parse(settingsValue);
    HTTP_SEND("finpay/pos/setOptions.json", sendData, function(res){
        if(res){
//            var successMessage = "";
//            if("0000" == res.header.resCd){
//                successMessage = "저장이 모두 완료 되었습니다.";
//            }else {
//                successMessage = "저장이 완료 되었습니다.";
//            }
//            showToastMessage(successMessage);
        }
    });
}
//function setOptions(req_type, useVat, vatIncluded, vatRate, useType, useMultiStore, payInfoLst){
//    console.log(":: // ##################################################");
//    console.log(":: //                     setOptions                    ");
//    console.log(":: // ##################################################");
//    var sendData = {};
//    sendData.req_type = req_type;
//    if("all" == req_type){
//        sendData.useVat = useVat;
//        sendData.vatIncluded = vatIncluded;
//        sendData.vatRate = vatRate;
//        sendData.useType = useType;
//        sendData.useMultiStore = useMultiStore;
//        sendData.payInfoLst = payInfoLst;
//    }else if("vat" == req_type){
//        sendData.useVat = useVat;
//        sendData.vatIncluded = vatIncluded;
//        sendData.vatRate = vatRate;
//    }else if("opt" == req_type){
//        sendData.useType = useType;
//        sendData.useMultiStore = useMultiStore;
//        sendData.payInfoLst = payInfoLst;
//    }
//    HTTP_SEND(SERVER_URL + "finpay/pos/setOptions.json", sendData, function(res){
//        if(res){
//            var successMessage = "";
//            if("0000" == res.header.resCd){
//                successMessage = "저장이 모두 완료 되었습니다.";
//            }else {
//                successMessage = "저장이 완료 되었습니다.";
//            }
//            showToastMessage(successMessage);
//        }
//    });
//}
function getCurrentPageProperties(){
    var fileName = location.pathname.split("/").slice(-1);
    if("01_01.html" == fileName || "01_02.html" == fileName || "01_03.html" == fileName
        ||"01_03_2.html" == fileName||"01_03_3.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";
    }
}
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:app.prev_page();' class='first on'><li><span class='blind'> << </span></li></a>";
        }

        if(this.getPrev() < this.curPage)
        {
            sb += "<a href='javascript:app.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:app.goPage("+i+");'><li>" + i + "</li></a>";
            }
        }

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

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

        //sb += "</ul> </div>";
        return sb;
    }
}
$(function(){

	var openPopup = false;

	//레이어 팝업 열기
	function openLayer(id){
		$('#'+id).show();
		$('.dim').show();
		openPopup = true;
	}

	//레이어 팝업 닫기
	function closeLayer(){
		$('.layer').hide();
		$('.dim').hide().css('z-index','200');
		openPopup = false;
	}
	$(document).ready(function(){
		//뒤로가기 버튼
		$('.btnBack').click(function(){window.history.back()});
		$('.searchSection .btnBack').click(function(){
			$('.searchSection').hide();
			return false;
		});

		//my coupon road
		$('.btnMy').click(function(){
			if (openPopup ==false){
				$('.mycouponSection').show();
				$('.dim').show();
				openPopup = true;
			}else{
				$('.mycouponSection').hide();
				$('.dim').hide();
				openPopup = false;
			}
		});

		//검색
		$('.btnSearch').click(function(){
			$('.searchSection').toggle();
			$('#keyword').val('');
		});

		//매장 상세 더보기
		var moreOpen = false;
		$('.linkGroup > button.more').click(function(){
			$(this).toggleClass('open');
			if(moreOpen == true){
				moreOpen =  false;
				$('.linkGroup a').hide();
				$('.dim').hide();
			}else{
				moreOpen =  true ;
				$('.linkGroup a').css('display','block');
				$('.dim').show();
			}
		});

		//레이어팝업 닫기
		$('.btnClose, .dim').click(function(){
			closeLayer();
			if ($('.dim').parent().hasClass('mainBody')){
				$('.mycouponSection').hide();
			}
			return false;
		});

		$('.btnClose2').click(function(){
			$('.shareLayerWrap').hide();
			$('.infoLayerWrap').hide();
			$('.dim').css('z-index','200');
			return false;
		});

		//가맹점 상세 쿠폰 레이어 열기
		$('.btnCoupon').click(function(){
			openLayer('coupon');
			return false;
		});

		//쿠폰 선물하기
		$('.btnGiveCoupon').click(function(){
			openLayer('share');
			return false;
		});


		//가맹점 상세 스탬프 레이어 열기
		$('.btnStamp').click(function(){
			openLayer('stampInfo');
			return false;
		});

		//포인트 사용 안내
		$('.infoPoint').click(function(){
			openLayer('point');
			return false;
		});

		//스탬프 사용 안내
		$('.infoStamp').click(function(){
			openLayer('stamp');
			$('.dim').css('z-index','400');
			return false;
		});

		//리뷰작성하기
		$('.reviewWriteSection .btnStar button').click(function(){
			$(this).toggleClass('on');
			return false;
		});

		//결제수단 선택
		$('.selectSection a').click(function(){
			$('.selectSection a').removeClass('selected');
			$(this).addClass('selected');
			return false;
		});

		//FAQ
		$('.list .q a').click(function(){
			$(this).parent().toggleClass('open');
			$(this).parent().next().slideToggle('fast');
			return false;
		});

		//매장소식
		$('.newsList .img').click(function(){
			openLayer('image');
			imageSliderShow.reloadSlider();
			return false;
		});

		//쿠폰 받기
		$('.couponLayerWrap button').click(function(){
			if ($(this).hasClass('btnGet')){
				$(this).removeClass('btnGet').addClass('btnUse').text('쿠폰사용');
			}else if ($(this).hasClass('btnUse')){
				$(this).parent().addClass('open');
				$(this).parent().next('.couponWrap').slideDown('fast');
				$(this).removeClass('btnUse').addClass('btnCancel').text('사용취소');
			}else{
				$(this).parent().removeClass('open');
				$(this).parent().next('.couponWrap').slideUp('fast');
				$(this).removeClass('btnCancel').addClass('btnUse').text('쿠폰사용');
			}
		});

		//지역선택하기 팝업 열기
		$('.roadSection a').click(function(){
			openLayer('area');
		});

		//지역선택하기
		$target = $('.areaListWrap>.list>li>a');
		$targetIn = $('.listIn>li>a');
		$('.open').next().slideDown();
		$target.click(function(){
			$(this).toggleClass('open').next().slideToggle();
			return false;
		});
		$targetIn.click(function(){
			$(this).toggleClass('on');
			return false;
		});

        if('settings' == getCurrentPageProperties()){
            $('#titleBackBtn').on('click',function(){
                app.backbuttonAction();
            });
            $('#titleHomeBtn').on('click',function(){
                app.backbuttonAction();
            });
            $('.tabLast').click(function(){
                $('.tabSubMenu').show();
                $('#tabLast1').hide();
                $('#tabLast2').show();
                return false;
            });
            $('#tabLast2').click(function(){
                $('.tabSubMenu').hide();
                $('#tabLast1').show();
                $('#tabLast2').hide();
                return false;
            });
        }
	});

});
