/****************
****************localStorage 값****************
serverData=>최초 회사 로그인시 받아옴****************
{
    "cust_digit_cnt":"5",
    "errcode":"0",
    "cust_func_code":"0", 기능제한코드
    "cust_con_ip":"211.220.138.26",
    "cust_mnt_date":"99991231",
    "cust_con_pbx_ip":"192.168.1.50",
    "cust_name":"지엔텔",
    "cust_con_port":"443",
    "cust_acc_code_used":"Y", 중계선호출코드사용여부
    "cust_ci_path":"http:\/\/touchsquare.co.kr\/wp\/wp-content\/uploads\/2019\/03\/touch-1.png",
    "cust_acc_code":"9" 중계선 호출코드 적용 자릿수
}

userData=>최초 로그인시 받아옴****************
{
    "method":"token.GET",
    "data":{
        "id":"user1",
        "node":"1",
        "systemType":"ipecs-ucm",
        "token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhcGlVc2VyIjoidHJ1ZSIsInRpbWVTdGFtcCI6MTU4OTE2NzA2M30.BlblCCjKj0uPzWiXpObK4vITFim9reYyrybvv6kn5hc",
        "mdn":"000010"
    },
    "apiVersion":"1"
}
settingData=>최초 회사 로그인시 설정함****************
 {
    accCodeUsed: jsonData.cust_acc_code_used,
    accCode: jsonData.cust_acc_code,
    digitCount: jsonData.cust_digit_cnt,
    companyId:companyId,
    companyPw:companyPw,
    autoLogin:"",
    checkIdSave:"",
    savedId:"",
    savedPw:"",
    mobileNumber:"",
    prefixNumber:""
};
*****************/
var settingData;
var serverData;
var userData;
var historyOrder = true;
var addressOrder = true;
var exitCheck = false;
var devicePlatform;
var deviceVersion;
var clusterizeAddress;
var clusterizeAddressSearch;
var clusterizeHistory;
var clusterizeHistorySearch;
var app_ver_string;
var from_top = false;

var app = {
    initialize: function() {     
        document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
        document.addEventListener('pause', this.onDevicePause.bind(this), false);
        document.addEventListener('resume', this.onDeviceResume.bind(this), false);
    },
    onDevicePause: function() {
        FirebasePlugin.clearAllNotifications();
        FirebasePlugin.setBadgeNumber(0);  
    },
    onDeviceResume: function() {
        FirebasePlugin.clearAllNotifications();
        FirebasePlugin.setBadgeNumber(0);
        // 다이얼 입력 팝업은 화면 복귀시 무조건 닫는다
        $(".bg_calling_02").removeClass("on");
        setTimeout(() => {
            $(".bg_calling_02").remove();
        }, 100);
    },
    onDeviceReady: function() {
        FirebasePlugin.clearAllNotifications();
        FirebasePlugin.setBadgeNumber(0);

        document.addEventListener("backbutton", onBackKeyDown, true);
        try {
            cordova.plugins.Keyboard.shrinkView(true);
        } catch(e)  {}
        cordova.getAppVersion.getVersionNumber().then(function (version) {
            $('.info_app_version').val(version);
            $('.info_contents_version').val(contents_version);
            $('.info_domain').val(server_debug_description);
        });

        //FCM푸시메세지 배너 클릭해서 들어오면 공지사항 페이지로 이동
        FirebasePlugin.onMessageReceived((msg)=>{
            // 공지사항 푸시는 messageType이 notification이고
            // 모바일 mcid 기능을 위한 통화이벤트 정보 푸시는 messageType이 data이다.
            if(msg.messageType == 'notification'){
                $('#loadNoticesBtn').trigger('click');
            }
        });

        //앱실행시 조직도데이터 조회 - 앱시작시 or 조직도 메뉴 진입시에 조직도데이터 갱신 필요여부를 체크함
        var groupSaveDate = window.localStorage.getItem("setGroupLastDate");
        var lastGroupDateTime = "";
        settingData = window.localStorage.getArray("settingData");
        serverData = window.localStorage.getArray("serverData");   

        if((settingData.noticeManageGroups).includes(settingData.deptCode)){
            getNotices();
            $(".notice_pop").stop().show();
        }

        cordova.plugin.http.get(settingData.server_host +settingData.server_port+ '/astroapi/base/v1/corp/updatetime/' + serverData.corp_code, {}, {
            Authorization: 'Bearer '+window.localStorage.getArray("userData").astroToken
        }, function(response) {

            let data = JSON.parse(response.data).data;
            lastGroupDateTime = data.update_time;

            console.log('onDeviceReady lastGroupDateTime' + lastGroupDateTime);

            if(groupSaveDate == lastGroupDateTime){
                console.log('onDeviceReady 같다');
                if($.isEmptyObject(user_map)){
                    readFile('user_map.json',(data)=>{
                        try {
                            user_map = JSON.parse(data);
                        } catch (error) {
                            user_map = {};
                        }

                        //한번 readFile했는데 user_map이 구성되어있지않으면 getOrganization을 호출해서 writeFile한후 진행한다.
                        if($.isEmptyObject(user_map)){
                            getOrganization((userMap)=>{
                                $('.gnb_01').trigger('click');
                                drawOrganization();
                                if(devicePlatform == "iOS"){
                                    genegateCallExtension(userMap);
                                }
                                window.localStorage.setItem("setGroupLastDate", lastGroupDateTime);
                            });
                        }else{
                            $('.gnb_01').trigger('click');
                            drawOrganization();
                        }
                    });
                }else{
                    $('.gnb_01').trigger('click');
                    drawOrganization();
                }

            }else{
                console.log('onDeviceReady 다르다');

                getOrganization((userMap)=>{
                    $('.gnb_01').trigger('click');
                    drawOrganization();
                    if(devicePlatform == "iOS"){
                        genegateCallExtension(userMap);
                    }
                    window.localStorage.setItem("setGroupLastDate", lastGroupDateTime);
                });
            }

        }, function(response) {
          console.error('onDeviceReady',response.error);
        });

        $(document).ready(function(){

            let settingData = window.localStorage.getArray("settingData");

            if(settingData.notice_used == 'Y'){
                $('#loadNoticesBtn').show();
            } else {
                $('#loadNoticesBtn').hide();
            }

            getNoticesUids();

            $(".btn_notice").click(function(e){
                e.preventDefault();
                var noticeRegPermitted = window.localStorage.getItem("noticeRegPermitted");
                getNotices();
                if (noticeRegPermitted === "false") {
                    $(".btn_notice_edit").stop().hide();
                    $("#alarmSelect").stop().hide();
                    
                } else {
                    $(".btn_notice_edit").stop().show();
                    $("#alarmSelect").stop().show();
                }
                getNotices("#tab01");
                $(".notice_pop").stop().show();
            });

            $("#tab_notice a").click(function(e){
                e.preventDefault();
                var tabId = $(this).attr("href");
                getNotices(tabId); // 각 탭에 해당하는 데이터를 요청
            });
        
            $(".popup_close").click(function(e){
                e.preventDefault();
                getNoticesUids();
                $(".notice_pop").stop().hide();
            });
        });

        $(document).ready(function(){
            // 확인 버튼 클릭 시
            $(".btn_submit.sendNotice").click(function(e){
                e.preventDefault();
                // var selectedNoticeUid = $(this).closest("li").find(".btn_notice_view").attr("id"); // 선택된 공지사항 ID 가져오기
                var storedNoticeId = $(".btn_submit.sendNotice").data("notice-id");
                sendNoticeAlert(storedNoticeId); // 공지사항 알림 발송 함수 호출
                $(".confirm_pop").stop().hide(); // 확인 팝업 닫기
            });
            
            // 취소 버튼 클릭 시
            $(".confirm_pop_close").click(function (e) {
                e.preventDefault();
                $(".confirm_pop").stop().hide(); // 확인 팝업 닫기
            });
        });
        
        $(document).ready(function(){
            var selectedNoticeUid;
            // 이벤트 위임을 사용하여 .btn_notice_view 요소 클릭 이벤트 처리
            $('ul.notice_list').on("click", "li", function(e){
                e.preventDefault();
                selectedNoticeUid = $(this).find('.btn_notice_view').attr("id");
                getSelectedNotice(selectedNoticeUid);
                $(".notice_view").stop().show();
            });
            // 버튼 클릭 시 이벤트 전파 중단
            $('ul.notice_list').on("click", ".func button", function(e){
                e.preventDefault();
                e.stopPropagation();
            });

            // 전달 버튼으로 알림 발송
            $(document).on("click", ".notice_forward", function(e){
                e.preventDefault();
                // alert(selectedNoticeUid);
                sendNoticeAlert(selectedNoticeUid);
            });

            // 이벤트 위임을 사용하여 .notice_view_close 요소 클릭 이벤트 처리
            $(document).on("click", ".notice_view_close", function(e){
                e.preventDefault();
                $(".notice_view").stop().hide();
                $(".notice_view").empty();
                $('.notice_pop_close').show();
                selectedNoticeUid = "";

                // 이전에 보고 있던 탭을 다시 그림
                redrawLastVisitedTab();
            });
        });

        $(document).ready(function(){
            $(".btn_notice_edit").click(function(e){
                e.preventDefault();
                
                // 입력사항 초기화
                selectedNoticeUid = "";
                $("#notice_edit_submit").text("등록");
                $("#notice_title").val("");
                $("#editor_main").summernote('reset');
                $("input[name='category'][value='E']").prop('checked', true).trigger("change");
                $("#notice_start_date").val("");
                $("#notice_start_time").val("");
                $("#notice_end_date").val("");
                $("#notice_end_time").val("");
                $("#selected_period").text("");
                $("input[name='target'][value='ALL']").prop('checked', true).trigger("change");
                $("#unlimited").prop("checked", true).trigger("change")
                target_dept_codes = [];
			    target_dept_names = [];
                $("#selected_depts").empty();

                $(".notice_edit").stop().show();
                $(".notice_view").stop().hide();
            });
            $(".notice_edit_close").click(function(e){
                e.preventDefault();
                $(".notice_edit").stop().hide();
                selectedNoticeUid = "";
            });
        });

        $(document).ready(function () {
            $(".btn_organ_pop").click(function (e) {
                e.preventDefault();
                getTreeData();
                $(".organ_pop").stop().show();
            });
            $(".organ_pop_close").click(function (e) {
                e.preventDefault();
                $(".organ_pop").stop().hide();
            });
        });


        // var target_dept_codes = [];
        // var target_dept_names = [];

        $(document).ready(function(){
            // 부서 선택 클릭 시 
            $(".btn_submit.choose_dept").click(function(e){
                e.preventDefault();
                if (selected_dept_code !== undefined) { 
                    target_dept_codes.push(selected_dept_code);
                    console.log('.btn_submit.choose_dept onclick',"target_dept_codes : " + target_dept_codes);
                }
                if (selected_dept_name !== undefined) { 
                    target_dept_names.push(selected_dept_name);
                    console.log('.btn_submit.choose_dept onclick',"target_dept_names : " + target_dept_names);
        
                    var newListItem = $("<div class='swiper-slide'>" + selected_dept_name + " <a href='#' class='del'></a></div>");
                    $(".picks.swiper-wrapper").append(newListItem);
                }
                $(".organ_pop").stop().hide();
            });

            // 선택한 부서 취소
            $("#selected_depts").on("click", "a.del", function(e) {
                e.preventDefault();

                var deptItem = $(this).parent();
                var deptName = deptItem.text().trim();

                var index = target_dept_names.indexOf(deptName);
                if (index !== -1) {
                    target_dept_names.splice(index, 1);
                    target_dept_codes.splice(index, 1);
                }

                deptItem.remove();
            });
        });
        

        $(document).ready(function () {       
            // 공지 기간 설정 팝업 열기
            $(".btn_term_pop").click(function(e){
                e.preventDefault();
                $(".term_pop").stop().show();
            });

            $(".btn_close.term_pop_close").click(function(e){
                e.preventDefault();
                $(".term_pop").stop().hide();
            });
        
            // 기간 설정 팝업에서 확인 버튼 클릭 시
            $(".btn_submit.setTime").click(function (e) {
                e.preventDefault();

                var selectedTime; // 변수 선언

                if ($("#unlimited").prop("checked")) {
                    selectedTime = null; // 체크박스가 체크되었을 때 null 할당
                    $("#selected_period").text("");
                } else {
                    // 시작일과 종료일을 가져와서 기간에 넣기
                    var startDate = $("#notice_start_date").val();
                    var startTime = $("#notice_start_time").val();
                    var endDate = $("#notice_end_date").val();
                    var endTime = $("#notice_end_time").val();

                    // 선택한 시간을 기간에 삽입
                    selectedTime = startDate + " " + startTime + " ~ " + endDate + " " + endTime;
                }

                console.log('btn_submit.setTime on click',selectedTime);

                // 선택한 시간을 #selected_period 레이블에 표시
                selectedTime == null || selectedTime == "  ~  " ? "" : $("#selected_period").text(selectedTime);

                // 팝업 닫기
                $(".term_pop").stop().hide();
            });
        });

        $(document).ready(function () {       
            // 공지사항 등록 버튼 클릭 시
            $(".notice_edit_submit").click(function(e){
                e.preventDefault();
                addNotice();
            });
        });

        $(document).on("click", ".pd_btn", function() {
            // 클릭된 pd_btn의 부모 요소(li)에서 id 값을 가져옴
            var selectedNoticeUid = $(this).closest("li").find(".btn_notice_view").attr("id");
            readNotice(selectedNoticeUid); // readNotice 함수 호출
        });

        $(document).ready(function () {
            // Listen for changes in the checkbox for unlimited period
            $("#unlimited").on("change", function () {
                if ($(this).is(":checked")) {
                    // Disable date/time inputs
                    $("#notice_start_date").prop('disabled', true);
                    $("#notice_start_time").prop('disabled', true);
                    $("#notice_end_date").prop('disabled', true);
                    $("#notice_end_time").prop('disabled', true);
                } else {
                    // Enable date/time inputs
                    $("#notice_start_date").prop('disabled', false);
                    $("#notice_start_time").prop('disabled', false);
                    $("#notice_end_date").prop('disabled', false);
                    $("#notice_end_time").prop('disabled', false);
                }
            });
        });
        
        $(".title").text(title);
        // TODO: dhlee: 로고는 하드코딩으로 변경함
        //$('.top_logo').attr("src",window.localStorage.getItem("logo"));
        //var serverData = window.localStorage.getArray("serverData");
        if (nullcheck(serverData) == false) {
            if (nullcheck(serverData.cust_logo3) == false) {
                $(".company_logo3").attr("src", server_host + server_port + serverData.cust_logo3);
            } else {
                $(".company_logo3").attr("src", "img/logo.png");
            };
        };



        // if (keyboard.isVisible) {
        //     // do something
        //     alert("forwarding");
        //     //$('.forwarding').scrollTop(300);
        // }

        window.addEventListener('keyboardDidShow', function () {
            // Describe your logic which will be run each time keyboard is shown.


            if($('.ui-page-active').attr('id') == "forwarding"){
                console.log('keyboardDidShow',"forwarding");

                //document.getElementsByClassName('forwarding').scrollTop = 200;

                $(window).scrollTop(500);
                //$('.forwarding').scrollTop(300);

                //$("html, body").animate({ scrollTop: $(document).height()-400 }, 0);
            }
        });

        window.addEventListener('statusTap', function() {
            // scroll-up with document.body.scrollTop = 0; or do whatever you want

            console.log('statusTap',"statusTap");


            if(isIOS12()){
                $(window).scrollTop(0);
            }else{
                if($('.ui-page-active').attr('id') == "address"){
                    document.getElementById('scrollArea').style.overflow = 'hidden';
                    document.getElementById('scrollArea').scrollTop = 0;
                    setTimeout(function() {
                        document.getElementById('scrollArea').style.overflow = '';
                    }, 10);
                }else if($('.ui-page-active').attr('id') == "addr_search"){
                    document.getElementById('scrollAreaSearch').style.overflow = 'hidden';
                    document.getElementById('scrollAreaSearch').scrollTop = 0;
                    setTimeout(function() {
                        document.getElementById('scrollAreaSearch').style.overflow = '';
                    }, 10);
                }else if($('.ui-page-active').attr('id') == "history"){
                    document.getElementById('scrollAreaHistory').style.overflow = 'hidden';
                    document.getElementById('scrollAreaHistory').scrollTop = 0;
                    setTimeout(function() {
                        document.getElementById('scrollAreaHistory').style.overflow = '';
                    }, 10);
                }else if($('.ui-page-active').attr('id') == "history_search"){
                    document.getElementById('scrollAreaSearchHistory').style.overflow = 'hidden';
                    document.getElementById('scrollAreaSearchHistory').scrollTop = 0;
                    setTimeout(function() {
                        document.getElementById('scrollAreaSearchHistory').style.overflow = '';
                    }, 10);
                }
            }
        });

        cordova.getAppVersion.getVersionNumber().then(function (version) {
            app_ver_string = version;
            console.log('getVersionNumber callback',"app_ver_string11111:"+app_ver_string);
        });
        devicePlatform = device.platform;
        deviceVersion = device.version;

        if(devicePlatform == "Android"){
            $(".myMobileNumber").prop("readonly",true);
        }

        if(devicePlatform == "iOS" && (parseInt(deviceVersion) < 13)){
            $(".calling_num").prop("contenteditable",false);
        }else{
            $('#scrollArea').addClass("clusterize-scroll");
            $('#scrollAreaSearch').addClass("clusterize-scroll");
            $('#scrollAreaHistory').addClass("clusterize-scroll");
            $('#scrollAreaSearchHistory').addClass("clusterize-scroll");
            var addressHeight = $('#address').height() ;
            console.log("addressHeight"+addressHeight+"::"+$(window).height()+"::"+$(document).height()+"::"+window.screen.height);
            $('.clusterize-scroll').css({'max-height':addressHeight+'px'});
        }

        // $('#scrollArea').addClass("clusterize-scroll");
        // $('#scrollAreaSearch').addClass("clusterize-scroll");
        // $('#scrollAreaHistory').addClass("clusterize-scroll");
        // $('#scrollAreaSearchHistory').addClass("clusterize-scroll");
        // var addressHeight = $('#address').height() ;
        // console.log("addressHeight"+addressHeight+"::"+$(window).height()+"::"+$(document).height()+"::"+window.screen.height);
        // $('.clusterize-scroll').css({'max-height':addressHeight+'px'});
        createAddress();

        getForward(true);
    }
    
};

app.initialize();

//조직도 화면구성
function drawOrganization(){
    console.log('drawOrganization start');
    let manageGroups = (settingData.noticeManageGroups||'').split(',');

    $("ul.list_org_favo,ul.favo_tree,ul.all_tree_root").empty();

    //즐겨찾기 구성
    var fav_infos = window.localStorage.getArray('fav_infos');
    for(var idx in fav_infos){
        var favorate_code = fav_infos[idx].favorate_code;
        if(fav_infos[idx].type == "user"){
            favo_map.favo_user[fav_infos[idx].favorate_code] = fav_infos[idx];
            var user = user_map[favorate_code];
            var group_info = group_map[user.dept_code].info
            var photo_uri = user.photo_uri;
            if(photo_uri != undefined && photo_uri != ''){
                photo_uri = settingData.server_host+":8100/xmladmin/userphoto/"+photo_uri;
            }

            $(".list_org_favo").append(
                person_template
                .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
                .replace(/{{comment}}/g, formatDisplayGroup(user.group_names, '@@'))
                .replace(/{{user_class}}/g, user.clss)
                .replace(/{{phone_number}}/g, user.cid_no)
                .replace(/{{cell_phone_number}}/g, user.mobile_no)
                .replace(/{{email}}/g, user.email)
                .replace(/{{user_position}}/g, user.position)
                .replace(/{{group_name}}/g, user.group_name)
                .replace(/{{user_id}}/g, user.user_id)
                .replace(/{{fav_flag}}/g, "btn_favo_org")
                .replace(/{{user_id_type}}/g, "favo_"+user.user_id)
                .replace(/{{user_photo_uri}}/g, photo_uri==''?setThumbImage():photo_uri)
                .replace(/{{view_type}}/g, "")
            )
        }else{
            favo_map.favo_group[fav_infos[idx].favorate_code] = fav_infos[idx];
            var group = group_map[favorate_code].info;
            if(manageGroups.includes(group.code)){
                continue;
            }

            $(".favo_tree").append(
                favo_template
                .replace(/{{group_name}}/g, group.name)
                .replace(/{{group_code}}/g, group.code)
            )
        }
    };
    //------즐겨찾기 구성 끝

    //let dept1_group = localStorage.getArray('dept1_group')||[];
    dept1_group.forEach((group)=>{
        
        if(favo_map.favo_group.hasOwnProperty(group.code)){
            favo_flag = "";
        }else{
            favo_flag = "off";
        }

        if(manageGroups.includes(group.code)){
            return ;
        }

        $(".all_tree_root").append(
            group_template
            .replace(/{{group_name}}/g, group.name+ " ("+group.user_cnt +")")
            .replace(/{{group_code}}/g, group.code)
            .replace(/{{haschild}}/g, group.haschild)
            .replace(/{{dept_class}}/g, "01")
            .replace(/{{fav_flag}}/g, favo_flag)
        )

        var parent_code = group.code;
        var child_user_list = group_map[parent_code].user_id_list;
        var favo_flag = "btn_favo_no_org";
        if(child_user_list.length >0){

            $("#"+parent_code).append(
                "<ul class='list_org ul_person_"+parent_code+"'></ul>"
            );

            for(var idx in child_user_list){
                var user_code = child_user_list[idx];
                var user = user_map[user_code];

                if ( user === undefined ) {
                    continue ;
                }

                if(favo_map.favo_user.hasOwnProperty(user_code)){
                    favo_flag = "btn_favo_org";
                }else{
                    favo_flag = "btn_favo_no_org";
                }

                var photo_uri = '';
//                var photo_uri = user.photo_uri;
//                if(photo_uri != undefined && photo_uri != ''){
//                    photo_uri = settingData.server_host+":8100/xmladmin/userphoto/"+photo_uri;
//                }

                $(".ul_person_"+parent_code).append(
                    person_template
                    .replace(/{{user_name}}/g, "["+user.clss+"] "+user.name)
                    .replace(/{{comment}}/g, "")
                    .replace(/{{user_class}}/g, user.clss)
                    .replace(/{{phone_number}}/g, user.cid_no)
                    .replace(/{{cell_phone_number}}/g, user.mobile_no)
                    .replace(/{{email}}/g, user.email)
                    .replace(/{{user_position}}/g, user.position)
                    .replace(/{{group_name}}/g, user.group_name)
                    .replace(/{{user_id}}/g, user.user_id)
                    .replace(/{{fav_flag}}/g, favo_flag)
                    .replace(/{{user_id_type}}/g, user.user_id)
                    .replace(/{{user_photo_uri}}/g, photo_uri==''?setThumbImage():photo_uri)
                    .replace(/{{view_type}}/g, "")
                )
            }
        }


        var child_group_list = group_map[parent_code].child_groups;

        $("#"+parent_code).append(
            "<ul class='tree ul_"+parent_code+"'></ul>"
        );

        for(var idx in child_group_list){
            var group_code = child_group_list[idx];
            var child_user = group_map[group_code].info;
            var depth = parseInt(child_user.relation_depth)+1;

            if(favo_map.favo_group.hasOwnProperty(group_code)){
                favo_flag = "";
            }else{
                favo_flag = "off";
            }

            if(manageGroups.includes(child_user.code)){
                continue;
            }

            $(".ul_"+parent_code).append(
                group_template
                .replace(/{{group_name}}/g, child_user.name+ " ("+child_user.user_cnt +")")
                .replace(/{{group_code}}/g, child_user.code)
                .replace(/{{dept_class}}/g, "0"+depth)
                .replace(/{{fav_flag}}/g, favo_flag)
            )
        }
    });

    $(".dpt_01:last").trigger('click');

    console.log('drawOrganization end');
    
}

//저장된로그내용을 서버로전송
function sendGLog(){
    window.plugins.gntel.getGLog(function(log) {
        console.log('sendGLog','log.length ::', log.length);
        var data = {
            "title": formatDate(new Date()).replace(/[^\d]/g,'')
            ,"log":  log
        };

        var dataSerializer = cordova.plugin.http.getDataSerializer();
        cordova.plugin.http.setDataSerializer('utf8');

        var tempUrl = server_host+server_port+'/astroapi/launcher/v1/clientlog/client/send';
        cordova.plugin.http.post(tempUrl, JSON.stringify(data), {
            'Content-Type': 'application/json'
        }, function(response) {
            popAlert("전송성공");
            console.log('sendGLog','send success');
        }, function(response) {
            popAlert("전송실패");
            console.log('sendGLog',"response status:"+response.status);
            console.log('sendGLog',response.error);
        });

        cordova.plugin.http.setDataSerializer(dataSerializer);

    }, function(error) {
        console.error(error);
    })
}

function writeFile(filename, data, callback) {

    // 파일 삭제
    var type = window.PERSISTENT;
    var size = 5 * 1024 * 1024;
    window.requestFileSystem(type, size, deleteSuccessCallback, deleteErrorCallback);
    function deleteSuccessCallback(fs) {
        fs.root.getFile(filename, { create: false}, function (fileEntry) {
            fileEntry.remove(function (file) {
                // 삭제가 완료되어도
                write();
            }, function (error) {
                // 에러가 발생했어도
                write();
            }, function () {
                // 원래 파일이 없어도
                write();
            });
        }, function errorCallback(error) {
            console.log(arguments.callee.name,error);
            write();
        });
    }
    function deleteErrorCallback(error) {
        console.log(error);
        write();
    }

    // 파일 작성
    function write() {
        window.requestFileSystem(type, size, writeSuccessCallback, writeErrorCallback);
        function writeSuccessCallback(fs) {
            fs.root.getFile(filename, { create: true, exclusive: false }, function (fileEntry) {
                fileEntry.createWriter(function (fileWriter) {
                    fileWriter.onwriteend = function (e) {
                        callback();
                    };
    
                    fileWriter.onerror = function (e) {
                        callback();
                    };
                    fileWriter.write(data);
                },  function errorCallback(error) {
                    console.log(arguments.callee.name,error);
                });
            },  function errorCallback(error) {
                console.log(arguments.callee.name,error);
            });
        }
        function writeErrorCallback(error) {
            console.log(error);
        }
    }
}
function writeFileX(filename, data, callback) {
    var type = window.PERSISTENT;
    var size = 10 * 1024 * 1024;
    //  o12nolja
    console.log('writeFileX','########### writeFile', filename, "size=", data.length);
    alert(" size="+ data.length);
    
    window.requestFileSystem(type, size, successCallback, errorCallback);
    function successCallback(fs) {
        fs.root.getFile(filename, { create: true, exclusive: false }, function (fileEntry) {

            /**
            // ������ �̹� �����ϸ� ����
            fileEntry.remove(function () {
                console.log('���� ���� ������.');
            }, errorCallback);
            /**/
            fileEntry.createWriter(function (fileWriter) {
                fileWriter.onwriteend = function (e) {
                    callback();
                };
                fileWriter.onerror = function (e) {
                    callback();
                };
                fileWriter.write(data);
            }, errorCallback);
        }, errorCallback);
    }
    function errorCallback(error) {
        console.log('writeFileX',"EEEEEEEEEEEEEEEE", error);
        alert("ERROR: " + error.code);
    }
}

function readFile(filename, callback) {
    var type = window.PERSISTENT;
    var size = 50 * 1024 * 1024;
    window.requestFileSystem(type, size, successCallback, errorCallback);
    function successCallback(fs) {
        fs.root.getFile(filename, {create: true, exclusive: false}, function (fileEntry) {
            fileEntry.file(function (file) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    var arrayBuffer = new Uint8Array(e.target.result);
                    var enc = new TextDecoder("utf-8");
                    callback(enc.decode(arrayBuffer));
                };
                reader.readAsArrayBuffer(file);
            }, errorCallback);
        }, errorCallback);
    }
    function errorCallback(error) {
        callback("{}");
        // alert("ERROR: " + error.code);
    }
}	

function isIOS12(){
    if(devicePlatform == "iOS" && (parseInt(deviceVersion) < 13)){
        return true;
        //return false;
    }else{
        return false;
    }
}
//서비스 탈퇴
function serviceSecession(){
    $(".loaderWrap").removeClass("hide");
    var data = {
        cust_pw: settingData.companyPw, //test1234
        device_id: device.uuid, // 1234567890
        device_number: settingData.mobileNumber,
        cust_name: settingData.companyId
    };

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('serviceSecession','success!');
    }, function() {
        console.log('serviceSecession','error :(');
    });
    cordova.plugin.http.post(server_host +server_port+ '/astroapi/mdial/v1/unregdevice', data, {
        Authorization: 'Bearer '+window.localStorage.getArray("userData").astroToken
     }, function(response) {
        var jsonData = JSON.parse(response.data);
        var chkJsonData = jsonData["errcode"];
        console.log('serviceSecession',"jsonData:"+JSON.stringify(jsonData));
        $(".loaderWrap").addClass("hide");
        switch (chkJsonData) {
            case "0":
                var androidPhoneNumber = window.localStorage.getItem("androidPhoneNumber");//저장
                //var permissionChecked = window.localStorage.getItem("permissionChecked");//저장
                window.localStorage.clear();
                //window.localStorage.setItem("permissionChecked", permissionChecked);//저장
                window.localStorage.setItem("androidPhoneNumber", androidPhoneNumber);//저장

                //permissionChecked
                location.href = "server.html";
                break;
            case "100":
                popAlert("비밀번호를 확인해 주세요");
                break;
            default:
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }
    }, function(response) {
        $(".loaderWrap").addClass("hide");
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function logOut(){
    window.localStorage.setArray("userData", []);//저장
    window.localStorage.setItem("autoLoginSave", "");//저장
    location.href = "login.html";
}
function serverUpdate(){
    $(".loaderWrap").removeClass("hide");

    console.log('serverUpdate',"app_ver_string:"+app_ver_string);
    var data = {
        cust_name: settingData.companyId, //지엔텔
        cust_pw: settingData.companyPw, //test1234
        device_id: device.uuid, // 1EBB6196-7830-46D5-83CC-93359F57CFDA
        device_number: settingData.mobileNumber, // 1234567890
        device_model: device.model, // iPhone7,1
        device_os: device.version, // 12.4.6
        device_platform: device.platform, // iOS
        device_app: app_ver_string // 1.0.0.1
    };


    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('serverUpdate','success!');
    }, function() {
        console.log('serverUpdate','error :(');
    });

    console.log('serverUpdate',"data:"+JSON.stringify(data));

    cordova.plugin.http.post(server_host +server_port+ '/astroapi/mdial/v1/searchcust', data, { 
        Authorization: 'Bearer '+window.localStorage.getArray("userData").astroToken
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        var chkJsonData = jsonData["errcode"];
        console.log('serverUpdate',"jsonData:"+JSON.stringify(jsonData));
        $(".loaderWrap").addClass("hide");

        switch (chkJsonData) {
            case "0":
                //alert("로그인 성공");
                window.localStorage.setArray("serverData", jsonData);
                //cust_acc_code_used : 중계선호출코드사용여부
                //Y : 사용함
                //N : 사용안함
                //cust_acc_code : 중계선 호출코드
                //cust_digit_cnt : 중계선 호출코드 적용 자릿수
                settingData.pbxType = jsonData.cust_pbx_type;
                settingData.svcPrefixNo = jsonData.cust_svc_prefix_no;
                settingData.cidLength = jsonData.cust_cid_length;
                settingData.fsSvcNo = jsonData.cust_fs_svc_no;
                settingData.accCodeUsed = jsonData.cust_acc_code_used;
                settingData.accCode = jsonData.cust_acc_code;
                settingData.digitCount = jsonData.cust_digit_cnt;
                settingData.cust_func_code = jsonData.cust_func_code;

                var prefixEx = "";
                if(!nullcheck(settingData.prefixNumber)){
                     var dn = settingData.prefixNumber;
                     dn = dn.substring(dn.length-Number(settingData.cidLength),dn.length);
                     var prefixEx;
                     if (settingData.pbxType == "FS") {
                        // FS 일경우
                        prefixEx = settingData.svcPrefixNo + settingData.fsSvcNo;
                     } else if((settingData.etcNo !== "" && settingData.etcNo !== undefined && settingData.etcNo !== null) && settingData.pbxType == "CM") {
                        prefixEx = settingData.etcNo;
                     } else {
                        // CM일경우
                        prefixEx = settingData.svcPrefixNo + dn;
                     };

                     window.localStorage.setItem("prefixEx",prefixEx);
                     settingData.prefixEx = prefixEx
                }

                window.localStorage.setArray("settingData", settingData);
                settingRefresh();
                refreshButtuons();
                popAlert("시스템 동기화가 완료 되었습니다.");
                break;
            case "100":
                popAlert("비밀번호를 확인해 주세요");
                break;
            default:
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
                break;
        }

    }, function(response) {
        $(".loaderWrap").addClass("hide");
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}
function settingRefresh(){
    var autoLogin = settingData.autoLogin;
    var method_callback = settingData.method_callback
    var method_callthrough = settingData.method_callthrough
    var method_click_to_call = settingData.method_click_to_call

    if(method_callback == true){
        $("#method_callback").prop("checked", true).checkboxradio("refresh");
    }
    if(method_callthrough == true){
        $("#method_callthrough").prop("checked", true).checkboxradio("refresh");
    }
    if(method_click_to_call == true){
        $("#method_click_to_call").prop("checked", true).checkboxradio("refresh");
    }

    if(!nullcheck(autoLogin) && autoLogin == 'true'){
        $("#set_auto").prop("checked", true).checkboxradio("refresh");
    }else{
        $("#set_auto").prop("checked", false).checkboxradio("refresh");
    }
    //중계선호출코드 사용여부
    var accCodeUsed = settingData.accCodeUsed;
    if(!nullcheck(accCodeUsed) && accCodeUsed == 'Y'){
        $("#set_relay").prop("checked", true).checkboxradio("refresh");
        $(".set_code").prop("readonly",true);
        $(".set_digit").prop("readonly",true);
    }else{
        //alert("2");
        $("#set_relay").prop("checked", false).checkboxradio("refresh");
        $(".set_code").prop("readonly",true);
        $(".set_digit").prop("readonly",true);
    }


    console.log('settingRefresh',"settingData:"+JSON.stringify(settingData));
    //중계선호출코드
    var accCode = settingData.accCode;
    // if(!nullcheck(accCode)){
        $(".set_code").val(accCode);
    // }
    //중계선호출코드 적용 자리수
    var digitCount = settingData.digitCount;
    if(!nullcheck(digitCount)){
        $(".set_digit").val(digitCount);
    }

    //HP번호
    var mobileNumber = settingData.mobileNumber;
    if(!nullcheck(mobileNumber)){
        $(".myMobileNumber").val(mobileNumber);
    }

    //내선번호
    var prefixNumber = settingData.prefixNumber;
    if(!nullcheck(prefixNumber)){
        $(".myPrefixNumber").val(prefixNumber);
    }

    //내선지역번호
    var prefixEx = settingData.prefixEx;
    if(!nullcheck(prefixEx)){
        $(".prefixEx").val(prefixEx);
    }

    var userData = window.localStorage.getArray("userData");
    // 아이디
    var user_id = userData.userId;
    if(!nullcheck(user_id)){
        $(".setting_userId").val(user_id);
    }

    // 이름
    var name = userData.userName;
    if(!nullcheck(name)){
        $(".setting_userName").val(name);
    }

    //푸시서비스 수신허용
    var allow_push = settingData.allow_push;
    if(!nullcheck(allow_push) && allow_push == 'Y'){
    // if(allow_push == 'Y'){
        $('#set_allow_push').prop('checked', true);
    }else{
        $('#set_allow_push').prop('checked', false);
    }
    $('#set_allow_push').checkboxradio('refresh');

    //푸시서비스 수신 시간설정

    if(!nullcheck(settingData.push_start_time) && !nullcheck(settingData.push_end_time)){
        $('[name=set_push_duration][value=spec]').prop('checked', true);
        $('#set_push_start_time').val(settingData.push_start_time);
        $('#set_push_end_time').val(settingData.push_end_time);
    }else{
        $('[name=set_push_duration][value=allday]').prop('checked', true);
        $('#set_push_start_time').val('');
        $('#set_push_end_time').val('');
    }
}
function getForward(first){
    console.log('getForward',"getForward:");
    //alert("getForward");

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('getForward','success!');
    }, function() {
        console.log('getForward','error :(');
    });
    //var serverData = window.localStorage.getArray("serverData");
    var userData = window.localStorage.getArray("userData");
    var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/cfwd';

    cordova.plugin.http.get(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        console.log('getForward',"jsonData : "+JSON.stringify(jsonData));
        console.log('getForward',"jsonData.data : "+JSON.stringify(jsonData.data));
        console.log('getForward',"jsonData.data : "+nullcheck(jsonData.data));
        if(!nullcheck(jsonData.data)){
            window.localStorage.setArray("forwardData", jsonData.data);//저장
            printForward(first);
            return;
        }else if(!nullcheck(jsonData.error)){
            popAlert(jsonData.error.message);
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }
        return;
    }, function(response) {
        // prints 403
        console.log('getForward',"response status:"+response.status);
        //prints Permission denied
        console.log('getForward',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}
function printForward(first){

    //alert(first);
    var forwardData = window.localStorage.getArray("forwardData");
    //등록/해제 여부
    if(forwardData.type == 0){
        $(".msg_box").addClass('off');

    }else{
        if(forwardData.to == "8888"){
            $(".con_value").text('VMS 착신 중입니다.');
            $(".msg_box").css("background-color","#ef6964");
        }
        $(".msg_box").removeClass('off');
        $(".con_num").html(forwardData.to);
    }
    //동작시간
    switch (forwardData.time_type) {//1,2,3,4
        case "0":
            if(first){
                $("#all").prop("checked", true);
                $("#spcf").prop("checked", false);
            }else{
                $("#all").prop("checked", true).checkboxradio("refresh");
                $("#spcf").prop("checked", false).checkboxradio("refresh");
            }

            break;
        default:
            if(first){
                $("#all").prop("checked", false);
                $("#spcf").prop("checked", true);
            }else{
                $("#all").prop("checked", false).checkboxradio("refresh");
                $("#spcf").prop("checked", true).checkboxradio("refresh");
            }
    }
    $("#forward_start_time").val(forwardData.start_time);
    $("#forward_end_time").val(forwardData.stop_time);
    //동작 조건
    //$("input[name=condition]").prop("checked", false);

    //alert("forwardData.type"+forwardData.type);
    if(first){
        $("input[name=condition]").prop("checked", false);
        $("input:radio[name='condition']:radio[value='"+forwardData.type+"']").prop("checked",true);
    }else{
        $("input[name=condition]").prop("checked", false).checkboxradio("refresh");
        $("input:radio[name='condition']:radio[value='"+forwardData.type+"']").prop("checked",true).checkboxradio("refresh");
    }
    //전화번호
    $(".forw_num").val(forwardData.to);
}
function callBack(id, phoneNumber, type){

    var toNumber = getTelephoneNumber(phoneNumber);
    var fromNumber = getUserNumber();
    if(nullcheck(fromNumber)){
        return;
    }

    var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/callback?from='+fromNumber+'&to='+toNumber;

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callBack','success!');
    }, function() {
        console.log('callBack','error :(');
    });
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        console.log('callBack',"jsonData:"+JSON.stringify(jsonData));
        if(!nullcheck(jsonData.error)){
            if(jsonData.error.message == 'OK'){
                popCallAction("내 휴대폰으로 발신 요청 중입니다.<br>잠시만 기다려주세요", function() {
                    callDisconnect(fromNumber,toNumber);
                });
                setTimeout(() => {
                    closePopAlert();
                }, 5000);
                addCallHistory(id, phoneNumber,type);
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }

    }, function(response) {
        // prints 403
        console.log('callBack',"response status:"+response.status);
        //prints Permission denied
        console.log('callBack',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}
function clickToCall(id, phoneNumber,type){

    // 내신번호 이면 prefix를 붙여줌
    if ( phoneNumber.length == settingData.cidLength ) {

        var etcNo = null;

        if(settingData.pbxType == 'CM'){
            for(var key in user_map){
                var user = user_map[key];
                try {
                    if ( user.cid_no == phoneNumber ) {
                        if ( user.etc_no !== 'undefined' && user.etc_no !== null && user.etc_no !== '' ) {
                            etcNo = user.etc_no;
                        }
                        break;
                    }
                } catch (e) {}
            }
        } 

        if(etcNo == null){
            phoneNumber = settingData.svcPrefixNo + phoneNumber;
        } else {
            phoneNumber = etcNo;
        }
    }

    cordova.plugins.phonedialer.call(
        '' + phoneNumber + '',
        function (success) { 
            addCallHistory(id, phoneNumber,type);
            console.log('clickToCall','Dialing succee  ded'); },
        function (err) {
            if (err == "empty") console.log('clickToCall',"Unknown phone number");
            else alert("Dialer Error:" + err);
        }
    );
    return;
}

function callthrough(id, phoneNumber,type){
    console.log('callthrough',"callthrough 클릭")

    console.log('callthrough',"phoneNumber:"+phoneNumber);
    var toNumber = getTelephoneNumber(phoneNumber);
    var fromNumber = getUserNumber();
    if(nullcheck(fromNumber)){
        return;
    }

    var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/callthrough?from='+settingData.mobileNumber+'&to='+toNumber;
    console.log("callthrough tempUrl 0 tempUrl"+tempUrl);
    //tempUrl = encodeURIComponent( tempUrl );
    console.log("callthrough tempUrl 0 "+userData.token+":::"+tempUrl);

    if(window.localStorage.getItem("prefixEx") == ""){
        console.log('callthrough',"내선 값이 없음");
    }else{
        console.log('callthrough',"내선 값이 있음");
    }

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callthrough','success!');
        //console.log("serverdata",window.localStorage.getItem("prefixEx"));
    }, function() {
        console.log('callthrough','error :(');
    });
    console.log('callthrough',"실행");
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        console.log('callthrough',response)
        var jsonData = JSON.parse(response.data);
        if(!nullcheck(jsonData.error)){
            console.log('callthrough',"error메시지",JSON.stringify(jsonData))
            if(jsonData.error.message == 'OK'){

                console.log('callthrough',window.localStorage.getItem("prefixEx"));
                if(window.localStorage.getItem("prefixEx") == ""){
                    alert("설정에서 내선지역번호를 저장 후 다시 시도해주세요")
                }else{

                    addCallHistory(id, phoneNumber,type);
                    cordova.plugins.phonedialer.call(
                      '' + window.localStorage.getItem("prefixEx") + '',
                      function(success) { console.log('callthrough','Dialing succee  ded'); },
                      function(err) {
                        if (err == "empty") console.log('callthrough',"Unknown phone number");
                        else alert("Dialer Error:" + err);
                      }
                     );

                }
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }

    }, function(response) {
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

// TODO: dhlee: 임의로 언스크린드 작성
function callunscreened(id, phoneNumber,type){
    
    console.log('callunscreened',"phoneNumber:"+phoneNumber);
    var toNumber = getTelephoneNumber(phoneNumber);
    var fromNumber = getUserNumber();
    if(nullcheck(fromNumber)){
        return;
    }

    var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/callthrough2?from='+settingData.mobileNumber+'&to='+toNumber;
    console.log('callunscreened',"tempUrl 0 "+userData.token+":::"+tempUrl);


    if(window.localStorage.getItem("prefixEx") == ""){
        console.log('callunscreened',"내선 값이 없음");
    }else{
        console.log('callunscreened',"내선 값이 있음");
    }

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callunscreened','success!');
        //console.log("serverdata",window.localStorage.getItem("prefixEx"));
    }, function() {
        console.log('callunscreened','error :(');
    });
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        console.log('callunscreened',response)
        var jsonData = JSON.parse(response.data);
        if(!nullcheck(jsonData.error)){
            console.log('callunscreened',"error메시지",JSON.stringify(jsonData))
            if(jsonData.error.message == 'OK'){

                console.log('callunscreened',window.localStorage.getItem("prefixEx"));
                if(window.localStorage.getItem("prefixEx") == ""){
                    alert("설정에서 내선지역번호를 저장 후 다시 시도해주세요")
                }else{

                    addCallHistory(id, phoneNumber,type);
                    cordova.plugins.phonedialer.call(
                      '' + window.localStorage.getItem("prefixEx") + '',
                      function(success) { console.log('callunscreened','Dialing succee  ded'); },
                      function(err) {
                        if (err == "empty") console.log('callunscreened',"Unknown phone number");
                        else alert("Dialer Error:" + err);
                      }
                     );

                }
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }

    }, function(response) {
        //popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function callDisconnect(fromNumber,toNumber){
    var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/disconnect?from='+fromNumber+'&to='+toNumber;
    console.log('callDisconnect',"clickToCall tempUrl"+tempUrl);
    //tempUrl = encodeURIComponent( tempUrl );
    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('callDisconnect','success!');
    }, function() {
        console.log('callDisconnect','error :(');
    });
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        console.log('callDisconnect',"jsonData:"+JSON.stringify(jsonData));

        if(!nullcheck(jsonData.error)){
            if(jsonData.error.message == 'OK'){
                popAlert("취소되었습니다.");
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }
    }, function(response) {
        // prints 403
        console.log('callDisconnect',"response status:"+response.status);
        //prints Permission denied
        console.log('callDisconnect',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}
function passwordCheck(el){
    //alert(el.length);
    if( el.length > 3 && el.length <11){
        //alert("1"+el.length);
        return true;
    } else {
        //alert("2"+el.length);
        return false;
    }
}
function changePassword(){
    var new_password = $(".new_password").val();
    var re_password = $(".re_password").val();
    //alert("current_password:"+current_password+"new_password"+new_password+"re_password"+re_password);
    if(!passwordCheck(new_password)){
        popAlert("새로운 비밀번호는 4~10자 입니다.");
        return;
    }else if(!passwordCheck(re_password)){
        popAlert("비밀번호 확인은 4~10자 입니다.");
        return;
    }else if(re_password != new_password){
        popAlert("비밀번호 확인이 일치하지 않습니다.");
        return;
    }

    var data = {
        "password" : new_password
    };

    cordova.plugin.http.setServerTrustMode('nocheck', function() {
        console.log('changePassword','success!');
    }, function() {
        console.log('changePassword','error :(');
    });


    var dataSerializer = cordova.plugin.http.getDataSerializer();

    cordova.plugin.http.setDataSerializer('utf8');

    var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/password';
    cordova.plugin.http.post(tempUrl, JSON.stringify(data), {
        Authorization: 'Bearer '+userData.token,
        'Content-Type': 'application/json'
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        console.log('changePassword',"jsonData:"+JSON.stringify(jsonData));
        if(!nullcheck(jsonData.data)){

            window.localStorage.setArray("userData", jsonData.data);//저장
            userData = window.localStorage.getArray("userData");
            $(".bg_rev_pw").removeClass("on");
            setTimeout(() => {
                $(".bg_rev_pw").hide();
            }, 200);


            $(".new_password").val("");
            $(".re_password").val("");

            popAlert("비밀번호가 변경 되었습니다.");
        }else if(!nullcheck(jsonData.error)){
            popAlert(jsonData.error.message);
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }
        return;
    }, function(response) {
        // prints 403
        console.log('changePassword',"response status:"+response.status);
        //prints Permission denied
        console.log('changePassword',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });

    cordova.plugin.http.setDataSerializer(dataSerializer);
}

function closeCalling(){
    $(".bg_calling").removeClass("on");
    setTimeout(() => {
        $(".bg_calling").remove();
    }, 200);
}
function onBackKeyDown() {
    if($('.ui-page-active').attr('id') == front_pageId){
        if(exitCheck){
            navigator.app.exitApp();
        }else{
            exitCheck = true;
            setTimeout(() => {
                exitCheck = false;
            }, 2000);
            toast("한번 더 누를 시 앱이 종료됩니다.");
        }
    }else{
        window.history.back();
    }
}
var callNum = "";
var selection = "";
var range = "";
var callNumStart = "";
var callNumEnd = "";
var frontNum = "";
var backNum = "";

function resetCaret(){
    selection = "";
    range = "";
    callNumStart = "";
    callNumEnd = "";
    frontNum = "";
    backNum = "";
}

function setCaret(){
    selection = document.getSelection();
    range = selection.getRangeAt(0);
    callNumStart = range.startOffset;
    callNumEnd = range.endOffset;

    frontNum = callNum.substring(0, callNumStart);
    backNum = callNum.substring(callNumEnd, callNum.length);
    console.log('setCaret',"frontNum::"+frontNum+"::backNum::"+backNum);
}
$( document ).one( "pagecreate", ".body_wrap", function() {
    // Handler for navigating to the next page
    function navnext( next ) {
        //location.href = "#" + next;

        $( ":mobile-pagecontainer" ).pagecontainer( "change", "#" + next , {
            transition: "slidefade"
        });
    }

    // Handler for navigating to the previous page
    function navprev( prev ) {
        //location.href = "#" + prev;

        $( ":mobile-pagecontainer" ).pagecontainer( "change", "#" + prev , {
            transition: "slidefade",
            reverse: true
        });
    }

    $( document ).on( "swipeleft", ".ui-page", function( event ) {
        var next = $( this ).jqmData( "next" );
        if ( next ) {
            navnext( next );
        }
    });

    $( document ).on( "swiperight", ".ui-page", function( event ) {
        var prev = $( this ).jqmData( "prev" );
        if ( prev ) {
            navprev( prev );
        }
    });

});


let user_map = {};

let group_map = window.localStorage.getArray("group_map")||{};
let dept1_group = window.localStorage.getArray("dept1_group")||[];
var favo_map = {
    favo_user : {}
    , favo_group : {}
};
let favo_template = '';
let group_template = '';
let person_template = '';

$(document).on("ready", function(){

    favo_template = $('#tree_favo_template').text();
    group_template = $('#tree_group_template').text();
    person_template = $('#tree_group_person_template').text();
    
    settingData = window.localStorage.getArray("settingData");
//조직도 구성


//리스트 구성

/*
    console.log("make tree start");

    for(var idx in dept1_group){
        var group = dept1_group[idx];

        if(favo_map.favo_group.hasOwnProperty(group.code)){
            favo_flag = ""
        }else{
            favo_flag = "off"
        }


        console.log("make tree do 1");
        console.log(group);

        $(".all_tree_root").append(
            group_template
            .replace(/{{group_name}}/g, group.name+ " ("+group.user_cnt +")")
            .replace(/{{group_code}}/g, group.code)
            .replace(/{{haschild}}/g, group.haschild)
            .replace(/{{dept_class}}/g, "01")
            .replace(/{{fav_flag}}/g, favo_flag)
        )



        var parent_code = group.code;
        var child_user_list = group_map[parent_code].user_id_list;
        var favo_flag = "btn_favo_no_org";
        if(child_user_list.length >0){


            console.log("make tree do 2");

            $("#"+parent_code).append(
                "<ul class='list_org ul_person_"+parent_code+"'></ul>"
            );

            for(var idx in child_user_list){
                var user_code = child_user_list[idx];
                var user = user_map[user_code];

                if ( user === undefined ) {
                    // alert(user_code);
                    // continue;
                    user = user_map["jsjung.gpc"];
                    alert(user);
                    continue ;
                }

                if(favo_map.favo_user.hasOwnProperty(user_code)){
                    favo_flag = "btn_favo_org"
                }else{
                    favo_flag = "btn_favo_no_org"
                }

//                var photo_uri = user.photo_uri;
//                if(photo_uri != undefined && photo_uri != ''){
//                    photo_uri = settingData.server_host+":8100/xmladmin/userphoto/"+photo_uri;
//                }

                $(".ul_person_"+parent_code).append(
                    person_template
                    .replace(/{{user_name}}/g, "["+user.clss+"] "+user.name)
                    .replace(/{{comment}}/g, user.description||'　')

                    .replace(/{{user_class}}/g, user.clss)
                    .replace(/{{phone_number}}/g, user.cid_no)
                    .replace(/{{cell_phone_number}}/g, user.mobile_no)
                    .replace(/{{email}}/g, user.email)
                    .replace(/{{user_position}}/g, user.position)
                    .replace(/{{group_name}}/g, user.group_name)
                    .replace(/{{user_id}}/g, user.user_id)
                    .replace(/{{fav_flag}}/g, favo_flag)
                    .replace(/{{user_id_type}}/g, user.user_id)
                    .replace(/{{user_photo_uri}}/g, photo_uri==''?setThumbImage():photo_uri)
                    .replace(/{{view_type}}/g, "")
                )
            }
        }


        var child_group_list = group_map[parent_code].child_groups;

        $("#"+parent_code).append(
            "<ul class='tree ul_"+parent_code+"'></ul>"
        );

        for(var idx in child_group_list){
            var group_code = child_group_list[idx];
            var child_user = group_map[group_code].info;
            var depth = parseInt(child_user.relation_depth)+1;

            if(favo_map.favo_group.hasOwnProperty(group_code)){
                favo_flag = ""
            }else{
                favo_flag = "off"
            }

            $(".ul_"+parent_code).append(
                group_template
                .replace(/{{group_name}}/g, child_user.name+ " ("+child_user.user_cnt +")")
                .replace(/{{group_code}}/g, child_user.code)
                .replace(/{{dept_class}}/g, "0"+depth)
                .replace(/{{fav_flag}}/g, favo_flag)
            )
        }
    }

    $(".dpt_01:last").trigger('click');

    console.log("make tree end");
    */

//------리스트구성 끝
//-------------------조직도 구성 끝

//조직도 관련 이벤트

    /* 검색창 클릭 시 */
    $(".search_wrap_05 .input_search").focus(function(){
        $(".search_wrap_05 .article_srch").css("display","");
        $(".search_wrap_05 .article_favorites").css("display","none");
        $(".search_wrap_05 .article_all").css("display","none");
        $(".search_wrap_05").css("padding-left","102px");

    });

    /* 검색 취소 */
    $(".search_wrap_05 .cancel_search").on("click", function(){
        $(".search_wrap_05 .article_srch").css("display","none");
        $(".search_wrap_05 .article_favorites").css("display","");
        $(".search_wrap_05 .article_all").css("display","");
        $(".search_wrap_05").css("padding-left","16px");

        $(".search_wrap_05 .list_org_srch").empty();
        $(".search_wrap_05 .input_search").val("");
    });

   /* 그룹 click */
    $("#organization .wt_src").on("click", ".all_view_tree", function(event){
        
        event.stopPropagation();
        var $clickedElement = $(this);
        var isExpanded = $clickedElement.hasClass("on");
        let manageGroups = (settingData.noticeManageGroups||'').split(',');
        
        if (!isExpanded) {
            if ($clickedElement.parent().find(".tree").length == 0) {
                var parent_code = $clickedElement.attr("groupcode");
                var child_user_list = group_map[parent_code].user_id_list;
                var favo_flag = "btn_favo_no_org";

                if (child_user_list.length > 0) {
                    $("#" + parent_code).append(
                        "<ul class='list_org ul_person_" + parent_code + "'></ul>"
                    );
                    for (var idx in child_user_list) {
                        var user_code = child_user_list[idx];
                        var user = user_map[user_code];

                        favo_flag = favo_map.favo_user.hasOwnProperty(user_code) ? "btn_favo_org" : "btn_favo_no_org";

                        var photo_uri = user.photo_uri;
                        if (photo_uri != undefined && photo_uri != '') {
                            photo_uri = settingData.server_host + ":8100/xmladmin/userphoto/" + photo_uri;
                        }

                        $(".ul_person_" + parent_code).append(
                            person_template
                            .replace(/{{user_name}}/g, "[" + user.position + "] " + user.name)
                            .replace(/{{comment}}/g, "")
                            .replace(/{{user_class}}/g, user.clss)
                            .replace(/{{phone_number}}/g, user.cid_no)
                            .replace(/{{cell_phone_number}}/g, user.mobile_no)
                            .replace(/{{email}}/g, user.email)
                            .replace(/{{user_position}}/g, user.position)
                            .replace(/{{group_name}}/g, user.group_name)
                            .replace(/{{user_id}}/g, user.user_id)
                            .replace(/{{fav_flag}}/g, favo_flag)
                            .replace(/{{user_id_type}}/g, user.user_id)
                            .replace(/{{user_photo_uri}}/g, photo_uri == '' ? setThumbImage() : photo_uri)
                            .replace(/{{view_type}}/g, "")
                        );
                    }
                }

                var child_group_list = group_map[parent_code].child_groups;

                $("#" + parent_code).append(
                    "<ul class='tree ul_" + parent_code + "'></ul>"
                );

                for (var idx in child_group_list) {
                    var group_code = child_group_list[idx];
                    var child_user = group_map[group_code].info;
                    var depth = parseInt(child_user.relation_depth) + 1;

                    favo_flag = favo_map.favo_group.hasOwnProperty(group_code) ? "" : "off";

                    if(manageGroups.includes(child_user.code)){
                        continue;
                    }

                    $(".ul_" + parent_code).append(
                        group_template
                        .replace(/{{group_name}}/g, child_user.name + " (" + child_user.user_cnt + ")")
                        .replace(/{{group_code}}/g, child_user.code)
                        .replace(/{{dept_class}}/g, "0" + depth)
                        .replace(/{{fav_flag}}/g, favo_flag)
                    );
                }
            }
        }

        // Toggle 'on' class and slideToggle
        $clickedElement.toggleClass("on", !isExpanded);
        $clickedElement.siblings("ul").slideToggle('fast', function() {
            // Scroll to the clicked element if it has class 'on'
            var scrollTo = $clickedElement.offset().top - 110;
            if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
                scrollTo -= 55; // Adjust as needed
            }
            $('html, body').animate({
                scrollTop: scrollTo
            }, 'fast');
        });
    });

    /* 즐겨찾기 그룹 click */
    $("#organization .wt_src").on("click", ".favo_group", function(event){
        event.stopPropagation();
        if(!$(this).hasClass("on")) {
            if($(this).parent().find(".list_org").length == 0 ){

                var parent_code = $(this).attr("groupcode");
                var child_user_list = group_map[parent_code].user_id_list;
                var favo_flag = "btn_favo_org";

                if(child_user_list.length >0){
                    $("#favo_"+parent_code).append(
                        "<ul class='list_org ul_person_favo_"+parent_code+"'></ul>"
                    );
                    for(var idx in child_user_list){
                        var user_code = child_user_list[idx];
                        var user = user_map[user_code];
                        var photo_uri = user.photo_uri;
                        if(photo_uri != undefined && photo_uri != ''){
                            photo_uri = settingData.server_host+":8100/xmladmin/userphoto/"+photo_uri;
                        }
                        $(".ul_person_favo_"+parent_code).append(
                            person_template
                            .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
                            .replace(/{{comment}}/g, "")
                            .replace(/{{user_class}}/g, user.clss)
                            .replace(/{{phone_number}}/g, user.cid_no)
                            .replace(/{{cell_phone_number}}/g, user.mobile_no)
                            .replace(/{{email}}/g, user.email)
                            .replace(/{{user_position}}/g, user.position)
                            .replace(/{{group_name}}/g, user.group_name)
                            .replace(/{{user_id}}/g, user.user_id)
                            .replace(/{{fav_flag}}/g, favo_flag)
                            .replace(/{{user_id_type}}/g, "favo_"+user.user_id)
                            .replace(/{{user_photo_uri}}/g, photo_uri==''?setThumbImage():photo_uri)
                            .replace(/{{view_type}}/g, "favo")
                        )
                    }
                }
            }
        }

        $(this).toggleClass("on");
        $(this).siblings("ul").slideToggle("fast");

    });

    /* 즐겨찾기 메뉴 보기 */
    $("#organization .wt_src").on("click", ".fav_view_tree", function(event){
        event.stopPropagation();
        $(this).toggleClass("on");
        $(this).siblings("ul").slideToggle("fast");
    });

    /* 즐겨찾기 아이콘(유저) click */
    $("#organization .wt_src").on("click", ".favo", function(event){
        event.stopPropagation();
        var fav_info = $(this).attr("user_id");
        if($(this).hasClass("btn_favo_org")) {
            if($(this).attr("view_type") == "favo" ){
                openAlert("그룹 내 사용자는 삭제할 수 없습니다.");
            }else{
                $(this).removeClass("btn_favo_org");
                $(this).addClass("btn_favo_no_org");
                deleteFavorate(fav_info, "user", this)
            }
        } else {
            $(this).removeClass("btn_favo_no_org");
            $(this).addClass("btn_favo_org");
            insertFavorate(fav_info, "user", this)
        }
    });

    /* 즐겨찾기 아이콘(그룹) click */
    $("#organization .wt_src").on("click", ".btn_favo_tree:not(.none)", function(event){
        event.stopPropagation();
        var fav_info = $(this).attr("groupcode");
        var user_cnt = group_map[$(this).attr("groupcode")].user_cnt
        if($(this).hasClass("off")) {
            if(user_cnt > 0){
                insertFavorate(fav_info, "group", this);
            }
        } else {
            deleteFavorate(fav_info, "group", this)
        }
    });

    let default_setting = {
        region_number : ""
    }

    /* 사용자 상세 */
    $("#organization .wt_src").on("click", ".view_detail,.portrait", function(e){
        e.stopPropagation();
        if($(this).hasClass("view_detail")){
            var user = user_map[$(this).attr("user_id")];
        }else{
            var user = user_map[$(this).siblings('div').find('.view_detail').attr("user_id")];
        }

        var group = group_map[user.dept_code].info;
        var  img_src = $(this).closest('li').find('img').attr('src').replace('.png','_big.png');
        var user_info ={"name":user.name, "photo_url":user.photo_uri==''?img_src:user.photo_uri};
        var infos =[
            {"key":"소속", "value": formatDisplayGroup(user.group_names, '@@')} 
            ,  {"key":"직책", "value": emptyToSpace(user.position)}
            ,  {"key":"내선번호", "value":format_phone_number(default_setting.region_number + user.cid_no), buttons : (user.cid_no == "" ? [] : ["call"])}
            ,  {"key":"휴대폰", "value":(user.cell_phone_number == "" ? '-' : format_phone_number(user.mobile_no)), buttons : (user.mobile_no == "" ? [] : ["sms", "call"] ) }
//            ,  {"key":"일반전화", "value":format_phone_number(user.etc_phone_number), buttons : ["call"]}
//            ,  {"key":"이메일", "value":user.email}
            ,  {"key":"담당업무", "value":emptyToSpace(user.description)}

            ];
        openDetail(user_info,infos,null,'organization');
    });

    //전화걸기 팝업
    $("#organization .wt_src").on("click", ".btn_org_call", function(e){
        console.log('organization .wt_src on click',"calling");
        e.stopPropagation();
        var user_info = user_map[$(this).data('user_id')];
        var numbers = [];
        if(user_info.cid_no != undefined && user_info.cid_no != '') numbers.push({"number":(default_setting.region_number + user_info.cid_no), "type":"내선전화"});
        if(user_info.mobile_no != undefined && user_info.mobile_no != '') numbers.push({"number":user_info.mobile_no, "type":"휴대전화"});
        if(user_info.etc_no != undefined && user_info.etc_no != '') numbers.push({"number":user_info.etc_no, "type":"기타전화"});
        console.log('organization .wt_src on click',numbers);
        console.log('organization .wt_src on click',user_info.user_name);

        for(var idx =0;idx<numbers.length;idx++){
            var item = numbers[idx];
            item.normalizedNumber = item.number.replace(/[^0-9]/gi,'');
        }

        var contact = {
            id : "contant_fake_id"
            ,phoneNumbers : numbers
            ,displayName : user_info.name
        }

        console.log('organization .wt_src on click',"selectCall"+JSON.stringify(contact));

        selectCall(contact,'','');
        //console.log("selectCall"+contact.id+"::"+thisNum+"::"+type);
    });

    /* 조직도 검색창 클릭 시 */
    $(".search_wrap_05 .input_search").focus(function(){
        $("#organization .article_srch").css("display","");
        $("#organization .article_favorites").css("display","none");
        $("#organization .article_all").css("display","none");
        $("#organization .search_wrap").css("padding-left","102px");
    });

    /* 검색 취소 */
    $("#btn_cancel_org_search").on("click", function(){
        $("#organization .article_srch").css("display","none");
        $("#organization .article_favorites").css("display","");
        $("#organization .article_all").css("display","");
        $("#organization .search_wrap").css("padding-left","16px");

        $("#organization .list_org_srch").empty();
        $("#inp_org_srch_name").val("");
    });

    $("#btn_delete_org_search").on("click", function(){
        $("#inp_org_srch_name").val("");
        $("#organization .list_org_srch").empty();
    });

    var itcdelay = (function () {
        // Function
        var itcTimer = 0;
        return function (callback, ms) {
            clearTimeout(itcTimer);
            itcTimer = setTimeout(callback, ms);
        };
    })();

    // 문자열 Bytes로 몇자인지 확인
    const getByteLengthOfString = function (s, b, i, c) {
        for (b = i = 0; (c = s.charCodeAt(i++)); b += c >> 11 ? 3 : c >> 7 ? 2 : 1);
        return b;
      };

    /* 연락처, 이름 검색 */
    $('.search_wrap_05 .input_search').on('keyup', function(e){
        itcdelay(function () {
            // 비어있거나 bytes로 계산했을때 1글자이면 검색하지 않음
            if($("#inp_org_srch_name").val() != "" && getByteLengthOfString($("#inp_org_srch_name").val().trim()) > 1 ){
                var sch_key = $('#inp_org_srch_name').val();
                $("#organization .list_org_srch").empty();
                for(var key in user_map){
                    var user = user_map[key];
                    try {
                        if(user.name.indexOf(sch_key)>-1 || user.mobile_no.indexOf(sch_key)>-1 || user.etc_no.indexOf(sch_key)>-1 || user.cid_no.indexOf(sch_key)>-1 ||user.cho_name.indexOf(sch_key)>-1){
                            drawUser(user);
                        }
                    } catch (e) {}
                }
            }else{
                $(".list_org_srch").empty();
            }
        }, 500);
    });

    // 공지 검색 기능 구현
    $('#notice_srch_keyword').on('keyup', function() {
        var searchKeyword = $(this).val().toLowerCase().trim(); // 검색어를 소문자로 변환하여 가져옵니다.
        searchNotices(searchKeyword); // 검색어를 이용하여 공지사항을 검색합니다.
    });

    // 공지 검색 함수
    function searchNotices(keyword) {
        // 각 공지사항을 순회하면서 검색어와 제목을 비교하여 일치하는 것만 보여줍니다.
        $('.notice_list li').each(function() {
            var noticeTitle = $(this).find('.btn_notice_view').text().toLowerCase(); // 공지 제목을 소문자로 가져옵니다.
            if (noticeTitle.indexOf(keyword) !== -1) {
                $(this).show(); // 검색어가 제목에 포함되어 있는 경우 해당 공지사항을 표시합니다.
            } else {
                $(this).hide(); // 검색어가 제목에 포함되어 있지 않은 경우 해당 공지사항을 숨깁니다.
            }
        });
    }

    

    //상세레이어 통화 버튼
    $('.detail_layer').on('click','a.btn_call', function(){
        if(isNaN($(this).data('info')) && $(this).data('info').replace(/\s/g,'') =='' ) return;
        var numbers = [];

        if($(this).data('info')!=undefined && $(this).data('info') != ''){
            numbers.push({"number": ($(this).data('info')+''), "type":($(this).closest('li').find('span.item').text())});
        }
        for(var idx =0;idx<numbers.length;idx++){
            var item = numbers[idx];
            item.normalizedNumber = item.number.replace(/[^0-9]/gi,'');
        }

        var contact = {
            id : "contant_fake_id"
            ,phoneNumbers : numbers
            ,displayName : $('#detail_layer_name').text()
        }

        console.log('detail_layer on click',"selectCall"+JSON.stringify(contact));

        selectCall(contact,'','');
    });

    //상세레이어 문자(SMS) 버튼
    $('.detail_layer').on('click','a.btn_sms', function(){
        if(isNaN($(this).data('info')) && $(this).data('info').replace(/\s/g,'') =='' ) return;
        var numbers = [];

        if($(this).data('info')!=undefined && $(this).data('info') != ''){
            numbers.push({"number": ($(this).data('info')+''), "type":($(this).closest('li').find('span.item').text())});
        }
        for(var idx =0;idx<numbers.length;idx++){
            var item = numbers[idx];
            item.normalizedNumber = item.number.replace(/[^0-9]/gi,'');
        }
        
        if (numbers.length > 0) {
            document.location.href = "sms:" + numbers[0].normalizedNumber;
        }
    });


//--------조직도 관련 이벤트 끝


    $(".sort_desc_addr").addClass("on");
    //alert("sort_desc_addr");
    $(".sort_desc_history").addClass("on");

    $(".search_wrap_01").show();
    // 밑에 $(".gnb_03").trigger('click'); 이거 없애야 함 조직도 추가 작업시 밑에 줄 없애고 조직도 관련 추가작업 주석 풀기
    //$(".gnb_03").trigger('click');

//  조직도 관련 추가 작업
    var updateGroup = window.localStorage.getItem("groupok");

    if(updateGroup == 1){
        $(".search_wrap_01").hide();
        $(".gnb_02").trigger('click');
    }else{
        $(front_page).trigger('click');
    }

    window.localStorage.removeItem("groupok");



    // TODO: dhlee: 로고 클릭해도 어드레스로 안가되됨
    // TODO: dhlee: !!!!!! 스크롤 관련 문제는 확인해 봐야함
    // $(".top_logo").on("click",function(){
    //     if($('.ui-page-active').attr('id') == "address"){
    //         if(isIOS12()){
    //             $(window).scrollTop(0);
    //         }else{
    //             //document.getElementById('scrollArea').scrollTop = 0;

    //             document.getElementById('scrollArea').style.overflow = 'hidden';
    //             document.getElementById('scrollArea').scrollTop = 0;

    //             setTimeout(function() {
    //                 document.getElementById('scrollArea').style.overflow = '';
    //             }, 10);
    //         }
    //     }else{
    //         from_top = true;
    //         window.location.href = "#address";
    //     }
    // });

    $(".privacy").on("click",function(){
        // var ref = cordova.InAppBrowser.open(href="./privacy.html", '_blank', 'location=yes');
        var ref = cordova.InAppBrowser.open(privacy_url, '_blank', 'location=yes,x=0,y=200,width=437,height=650');
    });
    
    $("#goTop").on("click",function(){
        if(isIOS12()){
            $(window).scrollTop(0);
        }else{
            if($('.ui-page-active').attr('id') == "address"){
                document.getElementById('scrollArea').style.overflow = 'hidden';
                document.getElementById('scrollArea').scrollTop = 0;
                setTimeout(function() {
                    document.getElementById('scrollArea').style.overflow = '';
                }, 10);
            }else if($('.ui-page-active').attr('id') == "addr_search"){
                document.getElementById('scrollAreaSearch').style.overflow = 'hidden';
                document.getElementById('scrollAreaSearch').scrollTop = 0;
                setTimeout(function() {
                    document.getElementById('scrollAreaSearch').style.overflow = '';
                }, 10);
            }else if($('.ui-page-active').attr('id') == "history"){
                document.getElementById('scrollAreaHistory').style.overflow = 'hidden';
                document.getElementById('scrollAreaHistory').scrollTop = 0;
                setTimeout(function() {
                    document.getElementById('scrollAreaHistory').style.overflow = '';
                }, 10);
            }else if($('.ui-page-active').attr('id') == "history_search"){
                document.getElementById('scrollAreaSearchHistory').style.overflow = 'hidden';
                document.getElementById('scrollAreaSearchHistory').scrollTop = 0;
                setTimeout(function() {
                    document.getElementById('scrollAreaSearchHistory').style.overflow = '';
                }, 10);
            }
        }
    });

    var whitelist = '*#';
    //set_code,set_digit,myMobileNumber,myPrefixNumber
    $('.maxLength11').alphanum({
        maxLength:11
    });
    //set_code,set_digit,myMobileNumber,myPrefixNumber
    $('.maxLength16').alphanum({
        allow : whitelist,  // Specify characters to disallow
        maxLength:16
    });
    var blacklist = '!@$%^&()+=[]\\\';,/{}|":<>?~`.- _';
    //set_code,set_digit,myMobileNumber,myPrefixNumber
    $('.maxLength1').alphanum({
        maxLength:1
    });
    $('.maxLength4').alphanum({
        maxLength:4
    });

    $('.maxLength6').alphanum({
        maxLength:6
    });

    $('.maxLength8').alphanum({

        allow : whitelist,  // Specify characters to disallow
        //disallow : blacklist,  // Specify characters to disallow
        maxLength:8
    });
    //alert("document ready");
    var pgNum = 0;
    settingData = window.localStorage.getArray("settingData");
    serverData = window.localStorage.getArray("serverData");
    userData = window.localStorage.getArray("userData");
    ////////////////////////////////////////////
    /////////////////다이얼 페이지/////////////////
    ////////////////////////////////////////////
    //숫자 패드

    callNum = $(".calling_num").html();

    $(".calling_num").on("click", function(){
        event.stopPropagation();
        setCaret();
    });

    var dialCheck = false;

    $(".dial_box button").on("touchstart", function(e){

        $(this).addClass("selected");
        // setTimeout(() => {
        //     $(this).removeClass("selected");
        // }, 100);
        if(callNum.length > 15){
            if(dialCheck){
            }else{
                dialCheck = true;
                setTimeout(() => {
                    dialCheck = false;
                }, 2000);
                toast("16자리 까지 입력 됩니다");
            }
            resetCaret();
            return;
        }

        console.log('dial_box button on click',"oscillator1.start",oscillator1);
        e.preventDefault();

        freqs = $(this).data("freq").split(",");
        dialTone(parseInt(freqs[0]), parseInt(freqs[1]));

        setTimeout(() => {
            stop();
        }, 2000);

        event.stopPropagation();
        if(frontNum.length == 0 && backNum.length == 0){
            callNum = callNum + $(this).data("val");
            callNum = callNum.substring(0,16);
            $(".calling_num").html(callNum);
        } else {

            callNum = frontNum + $(this).data("val") + backNum;
            callNum = callNum.substring(0,16);
            $(".calling_num").html(callNum);


            let newrange = new Range();
            newrange.setStart(Num.firstChild, frontNum.length+1);
            console.log('dial_box button on click',"frontNum"+frontNum.length);
            newrange.setEnd(Num.firstChild, frontNum.length+1);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(newrange);
            setCaret();
        }
    });

    $(".dial_box button").on("touchend", function(e){
        e.preventDefault();
        //stop();
        setTimeout(() => {
            stop();
        }, 100);
        $(this).removeClass("selected");
        searchPad();
    });

    $(".del_digit").on("click", function(){
        event.stopPropagation();
        if(frontNum.length == 0 && backNum.length == 0){
            callNum = callNum.slice(0, -1);
            $(".calling_num").html(callNum);
            searchPad();
        } else {
            callNum = frontNum.slice(0, -1) + backNum;
            $(".calling_num").html(callNum);
            searchPad();
            let newrange = new Range();
            newrange.setStart(Num.firstChild, frontNum.length-1);
            newrange.setEnd(Num.firstChild, frontNum.length-1);
            console.log('del_digit on click',frontNum.length);
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(newrange);
            setCaret();
            if(frontNum.length < 2){
                resetCaret();
            }
        }

    });
    $(".del_digit").on("taphold", function(){
        $(".calling_num").html("");
        resetCaret();
        callNum ="";
        searchPad();
    });
    //sel_other
    $(".sel_other").on("click", function(){
        //alert("sel_other");
        event.stopPropagation();
        console.log('sel_other on click','telephone = ' + JSON.stringify(searchContactByNumber));
        selectDialNumber(searchContactByNumber,callNum);
    });

    $(".src_result_box").on("click", function(){
        //alert("src_result_box");
        var firstContact =  searchContactByNumber[0];
        console.log('src_result_box on click','firstContact = ' + JSON.stringify(firstContact));

        //var telephone = searchContactByNumber[0].phoneNumbers.find(item => $.trim(keyword) === getRemovePlusEightTwo(item.normalizedNumber));
        var telephone = searchContactByNumber[0].phoneNumbers.find(item => new RegExp(callNum).test(item.normalizedNumber))
        console.log('src_result_box on click','telephone = ' + JSON.stringify(telephone));
        var telephoneNumber = telephone.normalizedNumber

        $(".calling_num").html(telephoneNumber);
        callNum = telephoneNumber;

        searchPad();
    });
    $(document).on("click", ".dial_pad_list", function(){

        var telephoneNumber = $(this).data("telephonenumber");

        console.log('dial_pad_list on click',telephoneNumber);
        $(".calling_num").html(telephoneNumber);
        callNum = telephoneNumber;

        searchPad();

        setTimeout(() => {
            $(".bg_calling").remove();
        }, 200);
    });
    //call_back
    $(".call_back").on("click", function(){
        var oriToNumber = $(".calling_num").html();
        $(".calling_num").html("");
        callNum = "";
        $(".src_result_box").hide();
        if(nullcheck(oriToNumber)){
            var callHistory = window.localStorage.getArray("callHistory");


            console.log('call_back on click',"callHistory1111"+JSON.stringify(callHistory));
            if( nullcheck(callHistory)){
                popAlert("전화 번호를 확인해 주세요");
                return
            }

            $(".calling_num").html(callHistory[0].num);
            callNum = callHistory[0].num;
            return;
        }

        // TODO: dhlee: 공통처리로 변경
        callBack("-1"+oriToNumber, oriToNumber, "기타");

    });
    //클릭콜 버튼
    $(".click_to_call").on("click", function(){

    // TODO: dhlee: 임의로 언스크린드로 변경

        var oriToNumber = $(".calling_num").html();
        $(".calling_num").html("");
        callNum = "";
        $(".src_result_box").hide();
        if(nullcheck(oriToNumber)){
            var callHistory = window.localStorage.getArray("callHistory");

            if( nullcheck(callHistory)){
                popAlert("전화 번호를 확인해 주세요");
                return
            }

            $(".calling_num").html(callHistory[0].num);
            callNum = callHistory[0].num;
            return;
        }


        clickToCall("-1"+oriToNumber, oriToNumber, "기타");

    });

    //클릭콜 버튼
    $(".call_through").on("click", function(){

        var oriToNumber = $(".calling_num").html();
        $(".calling_num").html("");
        callNum = "";
        $(".src_result_box").hide();
        if(nullcheck(oriToNumber)){
            var callHistory = window.localStorage.getArray("callHistory");

            if( nullcheck(callHistory)){
                popAlert("전화 번호를 확인해 주세요");
                return
            }

            $(".calling_num").html(callHistory[0].num);
            callNum = callHistory[0].num;
            return;
        }


        viewCallInfo(oriToNumber);

        var timeout = devicePlatform == "iOS" ? 0 : 3000;

        setTimeout(() => {
            // if (settingData.cust_func_code == "10" || settingData.cust_func_code == "11" || settingData.cust_func_code == "12") {
            //     callunscreened("-1"+oriToNumber, oriToNumber, "기타");
            // } else {
                callthrough("-1"+oriToNumber, oriToNumber, "기타");
            // }
        }, timeout);
    });


    // 키패드 버튼 배치
    refreshButtuons();


    ////////////////////////////////////////////
    /////////////////주소록 페이지/////////////////
    ////////////////////////////////////////////
    //즐겨찾기 추가
    $(document).on("click", "#address .btn_favo_no,#contentAreaHistory .btn_favo_no, #contentAreaSearch .btn_favo_no,#contentAreaSearchHistory .btn_favo_no", function(){
        var tgID = $(this).parent("li").data("id");
        console.log('btn_favo_no on click',"tgID"+tgID);
        $(".list_all").find("[data-id='"+ tgID +"']").children(".btn_favo_no").removeClass().addClass("btn_favo");
        $(".list_history").find("[data-id='"+ tgID +"']").children(".btn_favo_no").removeClass().addClass("btn_favo");
        $(".list_sch_all").find("[data-id='"+ tgID +"']").children(".btn_favo_no").removeClass().addClass("btn_favo");
        $(".list_sch_history").find("[data-id='"+ tgID +"']").children(".btn_favo_no").removeClass().addClass("btn_favo");

        var contact = $(this).parents("li").data("contact");
        var favoHtml = "";
        favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+contact.id+")' class='btn_favo'></a>"

        var liEl = "<li data-id='"+ contact.id +"' data-contact='"+JSON.stringify(contact) +"'>";
        liEl += "<span class='portrait'><img src='"+getThumbImage(contact.thumbnail)+"'></span>";
        liEl += favoHtml;
        liEl += "<h4>"+contact.displayName+"</h4>";
        liEl += "<button type='button' class='btn_call'></button>";
        liEl += "</li>";
        $(".list_favorites").append(liEl);

        if($('.ui-page-active').attr('id') == "address"){
            if(!isIOS12()){
                clusterizeAddress.refresh(true);

                //console.log("article_favorites"+document.querySelector(".article_favorites").offsetHeight);
                var offset = document.querySelector(".article_favorites").offsetHeight+24+31+61;
                console.log('btn_favo_no on click','toggleFavorite offset = ' + offset);
                clusterizeAddress.setTopHeightOffset(offset);
            }
        }
    });
    //즐겨찾기 삭제
    $(document).on("click", "#address .btn_favo,#contentAreaHistory .btn_favo, #contentAreaSearch .btn_favo, #contentAreaSearchHistory .btn_favo", function(){
        var tgID = $(this).parent("li").data("id");
        console.log('btn_favo on click',"tgID"+tgID);
        $(".list_favorites").find("[data-id='"+ tgID +"']").remove();
        $(".list_all").find("[data-id='"+ tgID +"']").children(".btn_favo").removeClass().addClass("btn_favo_no");
        $(".list_history").find("[data-id='"+ tgID +"']").children(".btn_favo").removeClass().addClass("btn_favo_no");
        $(".list_sch_all").find("[data-id='"+ tgID +"']").children(".btn_favo").removeClass().addClass("btn_favo_no");
        $(".list_sch_history").find("[data-id='"+ tgID +"']").children(".btn_favo").removeClass().addClass("btn_favo_no");

        if($('.ui-page-active').attr('id') == "address"){
            if(!isIOS12()){
                clusterizeAddress.refresh(true);

                //console.log('btn_favo on click',"article_favorites"+document.querySelector(".article_favorites").offsetHeight);
                var offset = document.querySelector(".article_favorites").offsetHeight+24+31+61;
                console.log('btn_favo on click','toggleFavorite offset = ' + offset);
                clusterizeAddress.setTopHeightOffset(offset);
            }
        }
    });

    //주소록 오른쪽 전화 버튼
    $(document).on("click", "#address .btn_call,#contentAreaSearch .btn_call,#contentAreaHistory .btn_call, #contentAreaSearchHistory .btn_call", function(){

        var contact = $(this).parents("li").data("contact");

        console.log('btn_call on click',"selectCall"+JSON.stringify(contact));
        var thisNum = $(this).prev("p").text();
        var number = "";
        var type = "";
        if(!nullcheck(thisNum)){
            number=thisNum.replace(/[^0-9]/g,'');
            type=thisNum.replace(/[0-9]/g,'');
        }

        console.log('btn_call on click',"selectCall"+contact.id);

        selectCall(contact,number,type);
        //console.log("selectCall"+contact.id+"::"+thisNum+"::"+type);
    });

    //통화목록 이름 및 전화 클릭시
    $(document).on("click", "#address .history_cell, #history .history_cell, #history_search .history_cell", function(){
        var telHistory = $(this).parents("li").children(".others_history");

        var historyOne = $(this).parents("li").children(".history_one");

        if(telHistory.find("li").length == 0){
            return;
        }
        telHistory.slideToggle("fast");
        historyOne.toggleClass("on");
    });



    //전화 팝업 콜백 버튼
    $(document).on("click", ".pop_calling .btn_calling_01", function(){
        var thisID = $(this).data("id");
        var numberOrder = $('input[name="sel_num"]:checked').val();
        var numberObj = JSON.parse(numberOrder);
        console.log('pop_calling .btn_calling_01 on click',"numberOrder:"+JSON.stringify(numberObj));
        var telephoneNumber = numberObj.normalizedNumber;
        var type = numberObj.type
        console.log('pop_calling .btn_calling_01 on click',"btn_calling_01:"+thisID +"::::" +telephoneNumber+"::::" +type);
        closeCalling();

        callBack(thisID, telephoneNumber, type);
    });

    //전화 팝업 클릭콜 버튼
    $(document).on("click", ".pop_calling .btn_calling_02", function(){
        var thisID = $(this).data("id");
        var numberOrder = $('input[name="sel_num"]:checked').val();
        var numberObj = JSON.parse(numberOrder);
        console.log('pop_calling .btn_calling_02 on click',"numberOrder:"+JSON.stringify(numberObj));
        var telephoneNumber = numberObj.normalizedNumber;
        var type = numberObj.type;
        console.log('pop_calling .btn_calling_02 on click',"btn_calling_01:"+thisID +"::::" +telephoneNumber+"::::" +type);
        closeCalling();

        clickToCall(thisID, telephoneNumber, type);
    });

    //전화 팝업 클릭콜 버튼
    $(document).on("click", ".pop_calling .btn_calling_03", function(){
        var thisID = $(this).data("id");
        var numberOrder = $('input[name="sel_num"]:checked').val();
        var numberObj = JSON.parse(numberOrder);
        console.log('pop_calling .btn_calling_03 on click',"numberOrder:"+JSON.stringify(numberObj));
        var telephoneNumber = numberObj.normalizedNumber;
        var type = numberObj.type
        console.log('pop_calling .btn_calling_03 on click',"btn_calling_01:"+thisID +"::::" +telephoneNumber+"::::" +type);
        closeCalling();

        // if (settingData.cust_func_code == "10" || settingData.cust_func_code == "11" || settingData.cust_func_code == "12") {
        //     callunscreened(thisID, telephoneNumber, type);
        // } else {
            callthrough(thisID, telephoneNumber, type);
        // }
    });

    //주소록 소트 내림 차순
    $(".sort_desc_addr").on("click", function(){
        $(".loaderWrap").removeClass("hide");
        setTimeout(function(){
            try {
                if($(".sort_desc_addr").hasClass("on")){
                    return false;
                } else {
                    $(".sort_desc_addr").addClass("on");
                    $(".sort_asce_addr").removeClass("on");
                    addressOrder = true;
                    $(".list_all").empty();

                    printAddress();
                }
            }
            finally {
                $(".loaderWrap").addClass("hide");
            }
        },0)
    });

    $("#button2").on('click', function () {
        $('#ulIn').append(function() {
          return $(this).children().get().reverse()
        });
    });

    $(".gnb_02").on('click', function(){

        //조직도 추가 작업 - 업데이트 시간에 따른 조직도 다시 select 작업임
        try {
            console.log('gnb_02 click',"updatetime");

            var groupSaveDate = window.localStorage.getItem("setGroupLastDate");
            var lastGroupDateTime = "";

            cordova.plugin.http.get(server_host +server_port+ '/astroapi/base/v1/corp/updatetime/' + serverData.corp_code, {}, {
                Authorization: 'Bearer '+window.localStorage.getArray("userData").astroToken
            }, function(response) {

                let data = JSON.parse(response.data).data;
                lastGroupDateTime = data.update_time;

                console.log('gnb_02 click',"lastGroupDateTime " + lastGroupDateTime);

                if(groupSaveDate == lastGroupDateTime){
                    console.log('gnb_02 click',"같다");
                }else{
                    console.log('gnb_02 click',"다르다");
                    window.localStorage.setItem("setGroupLastDate", lastGroupDateTime);
                    getOrganization((userMap)=>{
                        drawOrganization();
                        
                        if(devicePlatform == "iOS"){
                            genegateCallExtension(userMap);
                        }
                    });
                }

            }, function(response) {
                console.error('gnb_02 click',response.error);
            });    
        } catch (error) {
            
        }

        // $(".view_tree").removeClass("on");
        // $(".list_org").css("display","");
        // $(".tree").css("display","");
    });

    //주소록 소트 오름 차순
    $(".sort_asce_addr").on("click", function(){
        $(".loaderWrap").removeClass("hide");
        setTimeout(function(){
            try {
                if($(".sort_asce_addr").hasClass("on")){
                    return false;
                } else {
                    $(".sort_asce_addr").addClass("on");
                    $(".sort_desc_addr").removeClass("on");
                    //newContact = newContact.reverse();

                    addressOrder = false;
                    $(".list_all").empty();

                    printAddress();
                }
            }
            finally {
                $(".loaderWrap").addClass("hide");
            }
        },0)
    });

    $(".sort_desc_history").on("click", function(){
        $(".loaderWrap").removeClass("hide");
        setTimeout(function(){
            try {
                if($(".sort_desc_history").hasClass("on")){
                    return false;
                } else {
                    $(".sort_desc_history").addClass("on");
                    $(".sort_asce_history").removeClass("on");
                    $(".list_history").empty();
                    historyOrder = true;
                    printHistory();
                }
            }
            finally {
                $(".loaderWrap").addClass("hide");
            }
        },0)
    });

    $(".sort_asce_history").on("click", function(){
        $(".loaderWrap").removeClass("hide");
        setTimeout(function(){
            try {
                if($(".sort_asce_history").hasClass("on")){
                    return false;
                } else {
                    $(".sort_asce_history").addClass("on");
                    $(".sort_desc_history").removeClass("on");
                    $(".list_history").empty();
                    historyOrder = false;
                    printHistory();
                }
            }
            finally {
                $(".loaderWrap").addClass("hide");
            }
        },0)
    });

    ////////////////////////////////////////////
    /////////////////통화 목록/////////////////
    ////////////////////////////////////////////
    $(document).on("taphold", ".history_cell_box", function(){

        var thisID = $(this).data("historyid");
        //alert(thisID);
        popConfirmAction("해당 통화목록을 삭제 하시겠습니까?", function() {
            deleteHistory(thisID);
        });
    })
    ////////////////////////////////////////////
    /////////////////설정 페이지/////////////////
    ////////////////////////////////////////////



    $(".btn_basic_setting").on("click", function(){
        $(this).addClass("selected");
        $(".btn_rev_info").removeClass("selected");
        $(".panel_basic_setting").show();
        $(".panel_rev_info").hide();
        $(".save_setting").show();
    });
    $(".btn_rev_info").on("click", function(){
        $(this).addClass("selected");
        $(".btn_basic_setting").removeClass("selected");
        $(".panel_rev_info").show();
        $(".panel_basic_setting").hide();
        $(".save_setting").hide();
    });
    //로그아웃 버튼
    $(".btn_logout").click(function(){
        popConfirmAction("로그아웃 하시겠습니까?", function() {
            logOut()
        });
    });
    //설정 서버 업데이트 버튼
    $(".update_setting").click(function(){
        popConfirmAction("설정 값을 서버로부터\n새로 업데이트합니다.", function() {
            serverUpdate()
        });
    })
    //설정 서비스 탈퇴 버튼
    $(".ser_sc").click(function(){
        popConfirmAction("서비스 이용을 종료합니다.<br>다시 이용하실 경우는 처음부터 재 설치 절차를 수행하셔야 합니다.", function() {
            serviceSecession()
        });
    })
    //설정 중계선 호출코드 스위치 버튼
    $("#set_relay").on("change", function(){
        if($("#set_relay").is(':checked')){
            $(".set_code").prop("readonly",true);
            $(".set_digit").prop("readonly",true);
        }else{
            $(".set_code").prop("readonly",true);
            $(".set_digit").prop("readonly",true);
        }
    });
    //설정 저장 버튼
    $(".save_setting").click(function(){


        var dataSerializer = cordova.plugin.http.getDataSerializer();

        cordova.plugin.http.setDataSerializer('utf8');
    
        var params = {
            allow_push : $('#set_allow_push').is(':checked')?'Y':'N'
        };

        if($('[name=set_push_duration]:checked').val() == 'spec' ){
            if($('#set_push_start_time').val() == '' || $('#set_push_end_time').val() == ''){
                return popAlert('푸시 수신시간을 정확히 입력하세요.');
            }else{
                params.push_start_time = $('#set_push_start_time').val();
                params.push_end_time = $('#set_push_end_time').val();
            }
        } 

        var tempUrl = `${server_host}${server_port}/astroapi/mdial/v1/device/${serverData.corp_code}/${settingData.mobileNumber}/${device.uuid}`;
        console.log(tempUrl);
        cordova.plugin.http.put(tempUrl, JSON.stringify(params), {
            Authorization: 'Bearer '+ window.localStorage.getArray("userData").astroToken,
            'Content-Type': 'application/json'
        }, function(response) {
            var jsonData = JSON.parse(response.data);
            console.log('changePassword',"jsonData:"+JSON.stringify(jsonData));
            if(!nullcheck(jsonData.data)){
                //자동로그인
                if($("#set_auto").is(':checked')){
                    settingData.autoLogin = "true";
                }else{
                    settingData.autoLogin = "";
                }
                //중계선호출코드
                if($("#set_relay").is(':checked')){
                    settingData.accCodeUsed = "Y";
                }else{
                    settingData.accCodeUsed = "N";
                }

                settingData.accCode = $(".set_code").val();
                settingData.digitCount = $(".set_digit").val();
                settingData.mobileNumber = $(".myMobileNumber").val();
                settingData.prefixNumber = $(".myPrefixNumber").val();
                settingData.prefixEx = $(".prefixEx").val();
                settingData.method_callback = $('#method_callback').prop("checked");
                settingData.method_callthrough = $('#method_callthrough').prop("checked");
                settingData.method_click_to_call = $('#method_click_to_call').prop("checked");
                settingData.allow_push = params.allow_push;
                settingData.push_start_time = params.push_start_time;
                settingData.push_end_time = params.push_end_time;
                window.localStorage.setItem("prefixEx",$(".prefixEx").val());
                window.localStorage.setArray("settingData", settingData);
                popAlert("설정이 저장 되었습니다.");
            }else if(!nullcheck(jsonData.error)){
                popAlert(jsonData.error.message);
            }else{
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
            }
            return;
        }, function(response) {
            // prints 403
            console.log('changePassword',"response status:"+response.status);
            //prints Permission denied
            console.log('changePassword',response.error);
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });
    
        cordova.plugin.http.setDataSerializer(dataSerializer);
    });

    //비밀번호 변경 띄우기
    $(".rev_pw").on("click", function(){
        $(".bg_rev_pw").show();
        setTimeout(() => {
            $(".bg_rev_pw").addClass("on");
        }, 50);

    });
    //닫기
    $(".close_rev_pw").on("click", function(){
        $(".new_password").val('');
        $(".re_password").val('');
        $(".bg_rev_pw").removeClass("on");
        setTimeout(() => {
            $(".bg_rev_pw").hide();
        }, 200);
    });
    //비밀번호 변경 확인
    $(".confirm_rev_pw").on("click", function(){
        changePassword();
    });

    //전화걸기 팝업 닫기 버튼
    $(document).on("click", ".close_calling", function(){
        $(".bg_calling").removeClass("on");

        // 키패드에서 팝업 닫기
        $(".bg_calling_02").removeClass("on");
        setTimeout(() => {
            $(".bg_calling").remove();

            // 키패드에서 팝업 닫기
            $(".bg_calling_02").remove();
        }, 200);
    });
    //착신전화 등록 버튼
    $(".reg_forw").on("click", function(){
        var time_type = $('input[name="time"]:checked').val();
        var start_time = $("#forward_start_time").val();
        var stop_time = $("#forward_end_time").val();
        var type = $('input[name="condition"]:checked').val();
        var to = $(".forw_num").val();
        if(type == "0"){
            popAlert("착신전환 동작 조건 설정을\n선택해 주세요.");
            return;
        }
        // 매일이면 시간 강제입력 (어자피 사용하지 않음)
        if ( time_type == 0 ) {
            if (start_time == "" || stop_time == "" ) {
                start_time = "09:00";
                stop_time = "18:00";
            }
        } else if ( time_type == 4 && (start_time == "" || stop_time == "" ) ) {
            popAlert("착신전환 동작시간을 입력해주세요.");
            return;
        }
        console.log('reg_forw','착신전화!' + time_type + "::" + start_time + "::" + stop_time + "::" + type + "::" + to);
        if(!phonenumberValidation(to)){
            popAlert("착신전환 등록전화번호를 확인해 주세요.");
            return;
        }
        cordova.plugin.http.setServerTrustMode('nocheck', function() {
            console.log('reg_forw','success!');
        }, function() {
            console.log('reg_forw','error :(');
        });
        var param = '?to='+to+'&start_time='+start_time+'&type='+type+'&time_type='+time_type+'&stop_time='+stop_time;
        var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/cfwd'+param;
        cordova.plugin.http.post(tempUrl, { }, {
            Authorization: 'Bearer '+userData.token
        }, function(response) {
            var jsonData = JSON.parse(response.data);
            console.log('reg_forw',"jsonData:"+JSON.stringify(jsonData));
            if(!nullcheck(jsonData.error)){
                if(jsonData.error.message == 'OK'){
                    popAlert("착신전환이 등록 되었습니다.");
                    getForward(false);
                }else{
                    popAlert(jsonData.error.message);
                }
            }else{
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
            }

        }, function(response) {
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });

    });


    //착신전화 해제 버튼
    $(".cancel_forw").on("click", function(){
        var time_type = $('input[name="time"]:checked').val();
        var start_time = $("#forward_start_time").val();
        var stop_time = $("#forward_end_time").val();
        var type = "0";
        var to = $(".forw_num").val();
        cordova.plugin.http.setServerTrustMode('nocheck', function() {
            console.log('cancel_forw','success!');
        }, function() {
            console.log('cancel_forw','error :(');
        });
        var param = '?to='+to+'&start_time='+start_time+'&type='+type+'&time_type='+time_type+'&stop_time='+stop_time;
        var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/cfwd'+param;
        cordova.plugin.http.post(tempUrl, { }, {
            Authorization: 'Bearer '+userData.token
        }, function(response) {
            var jsonData = JSON.parse(response.data);
            console.log('cancel_forw',"jsonData:"+JSON.stringify(jsonData));
            if(!nullcheck(jsonData.error)){
                if(jsonData.error.message == 'OK'){
                    popAlert("착신전환이 해제 되었습니다.");
                    //$(".msg_box").css("background-color", "#5d5d5d");
                    getForward(false);
                }else{
                    popAlert(jsonData.error.message);
                }
            }else{
                popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
            }

        }, function(response) {
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });

    });

});

$(".vms_btn").on("click",function(){
   var time_type = "0";
   var type = "1";
   var start_time = $("#forward_start_time").val();
   var stop_time = $("#forward_end_time").val();
   var to = "8888";
   //alert('착신전화!' + time_type + "::" + start_time + "::" + stop_time + "::" + type + "::" + to);

    var param = '?to='+to+'&start_time='+start_time+'&type='+type+'&time_type='+time_type+'&stop_time='+stop_time;
    var tempUrl = 'https://' + serverData.cust_con_pbx_ip + ':' + serverData.cust_con_port + '/ipxapi/v1/users/' + userData.id + '/cfwd'+param;
    cordova.plugin.http.post(tempUrl, { }, {
        Authorization: 'Bearer '+userData.token
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        console.log('vms_btn',"jsonData:"+JSON.stringify(jsonData));
        if(!nullcheck(jsonData.error)){
            if(jsonData.error.message == 'OK'){
                popAlert("착신전환이 등록 되었습니다.");
                getForward(false);
            }else{
                popAlert(jsonData.error.message);
            }
        }else{
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        }

    }, function(response) {
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });


});

//페이지 이동시 보여질때
$(document).on('pagecontainershow', (event,ui)=>{

    if (ui.toPage.prop('id') === 'organization') {
        if( $('.search_wrap_05 .input_search').val() != ''){
            $(".search_wrap_05").css("padding-left",'102px');
        }else{
            $(".search_wrap_05").css("padding-left",'16px');
        }
        $(".search_wrap_05").show();

        $(".gnb_02").addClass("selected");
    }

    if (ui.toPage.prop('id') === 'dial') {
        // var method_callback = settingData.method_callback
        // var method_callthrough = settingData.method_callthrough
        // var method_click_to_call = settingData.method_click_to_call
    }
    if (ui.toPage.prop('id') === 'address') {
        $("#goTop").show();
        console.log('pagecontainershow','pagecontainershow address');
        if(!isIOS12() && !nullcheck(clusterizeAddress)){

            console.log('pagecontainershow','pagecontainershow address 2');
            clusterizeAddress.refresh(true);
            var offset = document.querySelector(".article_favorites").offsetHeight+24+31+61;
            console.log('pagecontainershow','pagecontainershow offset = ' + offset);
            clusterizeAddress.setTopHeightOffset(offset);
        }


        console.log('pagecontainershow',"from_top"+from_top);

        if(from_top){
            console.log('pagecontainershow',"from_top");
            if(isIOS12()){
                $(window).scrollTop(0);
            }else{
                document.getElementById('scrollArea').scrollTop = 0;
            }
        }

        //$(window).scrollTop(0);
        from_top = false;

    }
    if (ui.toPage.prop('id') === 'history') {
        $("#goTop").show();
        printHistory();
    }
    if (ui.toPage.prop('id') === 'addr_search') {
        //$("#goTop").show();
        $(".btn_sch_all").focus();
        $(".btn_sch_all").on("keyup", function(){
            searchAll();
        });
    }
    if (ui.toPage.prop('id') === 'history_search') {
        //$("#goTop").show();
        $(".btn_sch_history").focus();
        $(".btn_sch_history").on("keyup", function(){
            searchHistory();
        });
    }
    if (ui.toPage.prop('id') === 'forwarding') {
        printForward(false);
    }
    if (ui.toPage.prop('id') === 'setting') {
        settingRefresh();
    }
});

//페이지 이동시 사라질때
$(document).on('pagebeforehide', (event, ui)=>{
    $("#goTop").hide();
    $(".gnb li a").removeClass("selected");
    $(".search_wrap").hide();
    if (ui.prevPage.prop('id') === 'organization') {
        if( $('.search_wrap_05 .input_search').val() == ''){
            $('#btn_cancel_org_search').trigger('click');
        }
    }
    if (ui.prevPage.prop('id') === 'dial') {
        $(".calling_num").html("");
        callNum = "";
        resetCaret();
        $(".src_result_box").hide();
    }
    if (ui.prevPage.prop('id') === 'address') {
        localStorage.setItem("addrTop",$(window).scrollTop());
    }

    ///보여지는 페이지가
    if (ui.toPage.prop('id') === 'dial') {

        $(".gnb_01").addClass("selected");
    }
    if (ui.toPage.prop('id') === 'address') {
        $(".search_wrap_01").show();
        $(".gnb_03").addClass("selected");

        if(isIOS12()){
            $.mobile.defaultHomeScroll = localStorage.getItem("addrTop");
        }
    }
    if (ui.toPage.prop('id') === 'addr_search') {
        $(".search_wrap_02").show();
        $(".list_sch_all").empty();
        $(".btn_sch_all").val("");

        $(".gnb_03").addClass("selected");
    }
    if (ui.toPage.prop('id') === 'history') {
        $(".search_wrap_03").show();
        $(".gnb_05").addClass("selected");
        // $.mobile.defaultHomeScroll = 0;
    }
    if (ui.toPage.prop('id') === 'history_search') {
        $(".search_wrap_04").show();
        $(".list_sch_history").empty();
        $(".btn_sch_history").val("");

        $(".gnb_05").addClass("selected");
    }
    if (ui.toPage.prop('id') === 'forwarding') {
        $(".gnb_06").addClass("selected");
    }
    if (ui.toPage.prop('id') === 'setting') {
    }


});


$(document).ready(function(){
    
    //이름 클릭, 상세팝업
    $(document).on("click", ".view_detail", function(){
        $(".detail_layer").show();
        $(".detail_layer").addClass("on");
        setTimeout(() => {
            $(".detail_header").addClass("fixed");
        },200);
    });
    $(document).on("click", ".btn_close_detail", function(){
        $(".detail_layer").removeClass("on");
        $(".detail_header").removeClass("fixed");
    });

    //전화걸기 팝업
    $(".btn_org_call").on("click", function(){
        $(".bg_calling_01").show();
        setTimeout(() => {
            $(".bg_calling_01").addClass("on");
        }, 10);
    });
    $(".close_calling").on("click", function(){
        $(".bg_calling_01").removeClass("on");
        setTimeout(() => {
            $(".bg_calling_01").hide();
        }, 100);
    })

    // 그룹 메뉴 보기
    $(document).on("click", ".view_tree", function(){
        $(this).toggleClass("on");
        $(this).siblings("ul").slideToggle("fast");
    });
})

    // 조직도 관련 기능

    /* 즐겨찾기 추가 */
    function insertFavorate(fav_info, type, obj){

        var info = window.localStorage.getArray('fav_infos')||[];

        info.push({
            favorate_code : fav_info
            ,type : type
        });

        window.localStorage.setArray('fav_infos',info);
        $(obj).removeClass('off');
        refreshFavoList(type, fav_info);
    }

    function refreshFavoList(type, fav_info){
        if(type == "user"){
            favo_map.favo_user[fav_info] = {"favorate_code" :fav_info, "type":type}
            var user = user_map[fav_info];
            var group_info = group_map[user.dept_code].info
            var photo_uri = user.photo_uri;
            if(photo_uri != undefined && photo_uri != ''){
                photo_uri = settingData.server_host+":8100/xmladmin/userphoto/"+photo_uri;
            }
            $(".list_org_favo").append(
                person_template
                .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
                .replace(/{{comment}}/g, formatDisplayGroup(user.group_names, '@@'))
                .replace(/{{user_class}}/g, user.clss)
                .replace(/{{phone_number}}/g, user.cid_no)
                .replace(/{{cell_phone_number}}/g, user.mobile_no)
                .replace(/{{email}}/g, user.email)
                .replace(/{{user_position}}/g, user.position)
                .replace(/{{group_name}}/g, user.group_name)
                .replace(/{{user_id}}/g, user.user_id)
                .replace(/{{fav_flag}}/g, "btn_favo_org")
                .replace(/{{user_id_type}}/g, "favo_"+user.user_id)
                .replace(/{{user_photo_uri}}/g, photo_uri==''?setThumbImage():photo_uri)
                .replace(/{{view_type}}/g, "")
            )
        }else{
            favo_map.favo_group[fav_info] = { "favorate_code" :fav_info, "type":type}
            var group = group_map[fav_info].info;
            $(".favo_tree").append(
                favo_template
                .replace(/{{group_name}}/g, group.name)
                .replace(/{{group_code}}/g, group.code)
            )
        }
    }


    /* 즐겨찾기삭제 */
    function deleteFavorate(fav_info, type, obj){
        var info = window.localStorage.getArray('fav_infos')||[];

        var sinfo = info.filter(item => (item.favorate_code != fav_info && item.type != type));

        window.localStorage.setArray('fav_infos',sinfo);

        if($(obj).parents().find(".fav_tree_root").length > 0){
            if(type == "user"){
                $("#"+fav_info).find(".favo").removeClass("btn_favo_org")
                $("#"+fav_info).find(".favo").addClass("btn_favo_no_org");
            }else{
                var obj_root = $("#"+fav_info).find(".btn_favo_tree")[0];
                $(obj_root).addClass("off");
            }
        }

        if(type == "user"){
            delete favo_map.favo_user[fav_info];
        }else{
            delete favo_map.favo_group[fav_info];
        }

        $(obj).addClass("off");
        $("#favo_"+fav_info).remove();

        console.log('deleteFavorate',favo_map);
    }

    /**
     * 사용자 상세 정보 팝업
     * user_info : {
     *                     name : ''
     *                     ,number : ''
     *                     ,photo_url : ''
     *                  }
     * infos : [
     *      {'key' : 'asd', 'value':'vas', buttons : [call,mail,chat]}
     * ...
     * ]
     * history : [
     *      {'type': 'coming/send/miss', 'time' : 'asdklasd'}
     * ]
     * @returns
     */
    function openDetail(user_info, infos, history, type){
        $('#img_user_detail_photo').attr('src',setThumbImage());
        $('#detail_layer_edit_caution').css("display", type=='caution'?'inline':'none');
        $('#detail_layer_add_address').css("display", type=='address'?'none':'inline');
        $('#detail_layer_add_attention').css("display", type=='caution'?'none':'inline');
        $('#detail_layer_name').text(user_info.name||'');
        $('#detail_layer_number').text(user_info.number||'');
        $('.detail_layer ul.detail_conts_list').empty();
        var html = '';
        for(var idx =0;idx<infos.length;idx++){
            var item = infos[idx];
            if(item.buttons){
                var buttons = item.buttons;
                html += '<li><span class="item">'+item.key+'</span><span class="value">'+item.value+'</span><div class="detail_conts_tool">';
                for(var bidx = 0; bidx<buttons.length; bidx++){
                    switch (buttons[bidx]) {
                    case 'call':
                        // TODO: dhlee: 이미지 맞는사이즈가 없어서 다른걸로 바꿈
                        // html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/biz-call_btn_1.png"></a>'
                        html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/icon_call.png"></a>'
                        break;
                    case 'chat':
                    case 'mail':
                        html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/icon_'+buttons[bidx]+'_cc.png"></a>'
                        break;
                    // TODO: dhlee: 문자 넣어달라고해서 임의로 넣음
                    case 'sms':
                        html += '<a class="btn_'+buttons[bidx]+'" data-info="'+item.value+'"><img src="img/icon_chat_cc.png"></a>'
                        break;
                    }
                }
                html += '</div></li>';
            }else{
                html += '<li><span class="item">'+item.key+'</span><span class="value">'+item.value+'</span></li>'
            }
        }
        if(!$.isEmptyObject(history)){
            for(idx =0; idx< history.length;idx++){
                html += '<li class="'+history[idx].type+'">'+history[idx].time+'</li>';
            }
        }
        $('.detail_layer ul.detail_conts_list').html(html);

        $(".detail_layer").show();
        $(".detail_layer").addClass("on");
        $(".detail_header").addClass("fixed");
    }

    function formatDisplayGroup(group_names, parser){

        console.log('formatDisplayGroup',"group_names : " + group_names);



        if(group_names == undefined || group_names == null) return "";
        try{
            var disp_exp = '${g-2}/${g-1}';
        }catch(e){
            disp_exp = undefined;
        }
        var $opener = opener;
        var group_arr = group_names.split(parser);
        // TODO: dhlee: 회사 이름을 제거했었나?.... 일단 뺌
//        group_arr.splice(0,1);
        if($.isEmptyObject(group_arr)) return "";

        var to_convert_str = "";
        var group_name = "";
        var head_index,end_index;
        while((head_index = disp_exp.indexOf("${"))>=0 && (end_index = disp_exp.indexOf("}"))>head_index ){
            to_convert_str = disp_exp.substring(head_index, end_index+1);
            try{
                var group_depth = parseInt(to_convert_str.replace(/[$ { } g]/g,''));
                if(group_depth >0){
                    group_name = group_arr[group_depth]?group_arr[group_depth]:"";
                }else if(group_depth < 0){
                    group_name = group_arr[group_arr.length + group_depth]?group_arr[group_arr.length + group_depth]:"";
                }else{
                    group_name = "";
                }

                console.log('formatDisplayGroup',"group_name : " + group_name);
                disp_exp = disp_exp.replace(to_convert_str, group_name);
            }catch(e){
                return openAlert("그룹표시 형식이 잘못되었습니다.");
            }
        }
        if(disp_exp.startsWith("/"))disp_exp = disp_exp.substring(1);
        return disp_exp;
    }

    /**
     * 전화번호 포맷 (하이픈 추가).
     */
    var format_phone_number = function(number){
        if(number == undefined ||  (number+'').trim() == '') return '　';
        number = number +'';

        if(/[*#]/.test(number)) return number;
        number = number.replace(/[^0-9]/g, "");
        if(number.length == 12){
            return number.replace(/([0-9]{4})([0-9]+)?([0-9]{4})$/,"$1-$2-$3").replace("--", "-")
        }else{
            return number.replace(/(^02|^0505|^1[0-9]{3}|^0[0-9]{2})([0-9]+)?([0-9]{4})$/,"$1-$2-$3").replace("--", "-")
        }
    }

    // 
    var emptyToSpace = function(value){
        if(value == undefined ||  (value+'').trim() == '') return '　';
        return value;
    }

    function drawUser(user){
        var favo_flag = "btn_favo_no_org";
        if(favo_map.favo_user.hasOwnProperty(user.user_id)){
            favo_flag = "btn_favo_org"
        }else{
            favo_flag = "btn_favo_no_org"
        }
        var group_info = group_map[user.dept_code].info
        var photo_uri = user.photo_uri;
        if(photo_uri != undefined && photo_uri != ''){
            photo_uri = settingData.server_host+":8100/xmladmin/userphoto/"+photo_uri;
        }
        $(".list_org_srch").append(
            person_template
            .replace(/{{user_name}}/g, "["+user.position+"] "+user.name)
            .replace(/{{comment}}/g, formatDisplayGroup(user.group_names, '@@'))
            .replace(/{{user_class}}/g, user.clss)
            .replace(/{{phone_number}}/g, user.cid_no)
            .replace(/{{cell_phone_number}}/g, user.mobile_no)
            .replace(/{{email}}/g, user.email)
            .replace(/{{user_position}}/g, user.position)
            .replace(/{{group_name}}/g, user.group_name)
            .replace(/{{user_id}}/g, user.user_id)
            .replace(/{{fav_flag}}/g, favo_flag)
            .replace(/{{user_id_type}}/g, user.user_id)
            .replace(/{{user_photo_uri}}/g, photo_uri==''?setThumbImage():photo_uri)
            .replace(/{{view_type}}/g, "")
        )
    }
 //--------------------------------조직도 관련 기능 끝



//조직도 구성에 필요한 데이터 가져오기
function getOrganization(callback){
    console.log('getOrganization start');
    //alert("다시 호출");
    if(settingData.rootGroupcode == undefined || settingData.rootGroupcode == ''){
        return popAlert("조직최상위 코드 설정이 필요합니다 관리자에게 문의하세요.");
    }

    var groups =[];
    var users = [];
    cordova.plugin.http.get(server_host + server_port + '/astroapi/base/v1/users/'+ settingData.rootGroupcode, {}, {
        Authorization: 'Bearer '+window.localStorage.getArray("userData").astroToken
     }
    ,function(result){
        
        try{
            users = JSON.parse(result.data).data;
        }catch(e){
            users= [];
        }

        // console.log("userfilter");
        // console.log(users);
        cordova.plugin.http.get(server_host +server_port+ '/astroapi/base/v1/corps/withdept/'+ settingData.rootGroupcode, {}, {
            Authorization: 'Bearer '+window.localStorage.getArray("userData").astroToken
        }
        ,function(gresult){
            try{
               // alert(gresult);
                groups = JSON.parse(gresult.data).data;
            }catch(e){
               // alert('여기3');
                groups = [];
            }

            group_map = {};
            user_map ={};
            var mindepth = 999;
            for(var idx = 0; idx<groups.length; idx++){
                var group = groups[idx];
                group_map[group['code']] = {};
                group_map[group['code']].info =group;
                group_map[group['code']].child_groups =[];
                group_map[group['code']].user_id_list = [];
                group_map[group['code']].user_cnt = 0;
                if(group.relation_depth < mindepth){
                    mindepth = group.relation_depth;
                }
            }

            for(var idx=0; idx<users.length;idx++){
                var user = users[idx];
                var group = group_map[user.dept_code];
                if(group == undefined) continue;
                group['user_id_list'].push(user.user_id);
                group['user_cnt'] =group['user_cnt']+1;
                //모바일mcid용필드 추가
                try {
                    if(mcid_tel_no_format != undefined){
                        user.mcid_tel_no = (user.cid_no != '')?eval(mcid_tel_no_format):'';
                    }
                    if(mcid_tel_name_format != undefined){
                        user.mcid_tel_name = eval(mcid_tel_name_format);
                    }
                    if(mcid_mobile_no_format != undefined){
                        user.mcid_mobile_no = eval(mcid_mobile_no_format);
                    }
                } catch (error) {}
                user_map[user.user_id] =  user;
            }
            
            for(var idx =0;idx<groups.length;idx++){
                var group = groups[idx];
                var sg = groups.filter(function(item){
                    return item.relation_code.startsWith(group.relation_code);
                });

                var sg_codes = [];
                for(var sidx =0;sidx<sg.length;sidx++){
                    sg_codes.push(sg[sidx].code);
                }

                var su = users.filter(function(item){
                    return  sg_codes.includes(item.dept_code);
                });
                var user_cnt = $.isEmptyObject(su)?0:su.length;
                group['user_cnt'] = user_cnt;
            }
            //각그룹별 하위그룹 유저 총합
            for(var oidx = 0; oidx<groups.length; oidx++){
                var group = groups[oidx];
                var user_cnt = 0;
                var relationed_groups = groups.filter(function(item){
                    return item.relation_code && (item.relation_code+'.').startsWith(group.relation_code+'.');
                });
                if(relationed_groups != undefined){
                    for(var idx=0;idx<relationed_groups.length; idx++){
                        user_cnt+= group_map[relationed_groups[idx].code].user_cnt;
                    }
                }
                group.user_cnt = user_cnt;
                if(group.prnt_code && group.prnt_code != '' && group_map[group.prnt_code] != undefined){
                    group_map[group.prnt_code].child_groups.push(group.code);
                }

                group['haschild'] = ($.isEmptyObject(relationed_groups) && group.user_cnt<=0 )?'0':'1';
            }
            //alert(JSON.stringify(groups));
            dept1_group = groups.filter(function(item){
               // alert(JSON.stringify(item.relation_depth));
                return item.relation_depth==mindepth;
            });

            writeFile("user_map.json", JSON.stringify(user_map), function () {
                window.localStorage.setArray("group_map", group_map);
                window.localStorage.setArray("dept1_group", dept1_group);
                window.localStorage.setItem("groupok", "1");
                console.log('getOrganization end');
                if(callback){
                    callback(user_map);
                }
            });

            
        }
        ,function(fresult){
            console.log('getOrganization fail withdept',fresult);
            if(callback){
                callback(fresult);
            }
        });

    }
    ,function(fresult){
        //fail
        console.log('getOrganization fail users',fresult);
        if(callback){
            callback(fresult);
        }
    });
}

//ios의 경우 calldirectoryxtension데이터를 이용하여 통화상대의 정보를 보여준다
function genegateCallExtension(userMapJson){
    //window.plugins.gntel.getGLog(function(log))
    let groupSaveDate = window.localStorage.getItem("setGroupLastDate");
    window.plugins.gntel.checkMIddleDBFileExist((iExists)=>{
        console.log('checkMIddleDBFileExist success', iExists);

        if(!iExists){
            window.plugins.gntel.middleDBGenerator((r)=>{
                console.log('middleDBGenerator success', r);
            },(r)=>{
                console.log('middleDBGenerator fail', r);
            },'user_map.json');
        }else{
            //[{number,name,status}]
            let params = [];
            let list = Object.values(userMapJson).filter(item => item.create_time > groupSaveDate);
            list.forEach(item =>{
                params.push({
                    'name' : (item.mcid_tel_name||'')
                    ,'number' : (item.mcid_mobile_no||'')
                    ,'status' : 'c'
                });
            });
    
            list = Object.values(userMapJson).filter(item => item.update_time > groupSaveDate);
            list.forEach(item =>{
                params.push({
                    'name' : (item.mcid_tel_name||'')
                    ,'number' : (item.mcid_mobile_no||'')
                    ,'status' : 'u'
                });
            });
            
            console.log('updateMiddleDB params', params)
            window.plugins.gntel.updateMiddleDB((r)=>{
                console.log('updateMiddleDB success', r);
            },(r)=>{
                console.log('updateMiddleDB fail', r);
            },params);
        }
        
    },(r)=>{
        console.log('checkMIddleDBFileExist fail', r);
    })

}

var selectedNoticeUid;
var readNoticeList = JSON.parse(localStorage.getItem('readNoticeList')) || [];
var selfDeletedNoticeList = JSON.parse(localStorage.getItem('selfDeletedNoticeList')) || []; 

$(document).ready(function() {
    // 페이지가 로드될 때 읽은 공지사항 표시
    markReadNotices(readNoticeList);

    // 알람 셀렉트 박스 변경 이벤트 핸들러
    $("#alarmSelect").change(function() {
        // 현재 활성화된 탭의 링크를 선택
        var currentTabLink = $(".tabnav li a.active");
        
        // 해당 링크의 href 값을 가져와서 클릭 이벤트를 트리거
        var currentTabHref = currentTabLink.attr("href");
        $('a[href="' + currentTabHref + '"]').trigger("click");
    });

    // 탭 변경 이벤트 핸들러
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var selectedTabId = $(e.target).attr('href'); // 선택된 탭의 ID 가져오기
        getNotices(selectedTabId); // 해당 탭에 대한 공지사항 조회
    });
});

var noticeUids = [];

function getNoticesUids(){
    var tempUrl = server_host + server_port + '/astroapi/notice/v1/notices/all';

    cordova.plugin.http.get(tempUrl, {}, {
        Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
    }, function (response) {
        var jsonData = JSON.parse(response.data);

        noticeUids = jsonData.data.map(function(notice) {
            return notice.uid;
        });

        updateNewNoticeIndicator();

    }, function (response) {
        // prints 403
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function updateNewNoticeIndicator() {
    var unreadNoticeCount = 0;
    for (var i = 0; i < noticeUids.length; i++) {
        if (!readNoticeList.includes(noticeUids[i])) { 
            unreadNoticeCount++;
        }
    }

    if (unreadNoticeCount > 0) {
        // 읽지 않은 공지사항이 있는 경우
        $(".new").show(); 
    } else {
        $(".new").hide(); 
    }
}

    // 공지사항 불러오기 함수
function getNotices(tabId) {
    // 선택된 탭의 ID에 따라 필터링할 카테고리 설정
    var categoryFilter = "";
    if (tabId === "#tab02") {
        categoryFilter = "E"; // "E" 카테고리 필터
    } else if (tabId === "#tab03") {
        categoryFilter = "N"; // "N" 카테고리 필터
    }

    // 알람 여부 셀렉트 박스 값 가져오기
    var alarmValue = $("#alarmSelect").val();

    // 셀렉트 박스 값에 따라 필터 설정
    var alarmFilter = "";
    if (alarmValue === "Y") {
        alarmFilter = "Y"; // 알람 여부가 Y인 경우
    } else if (alarmValue === "N") {
        alarmFilter = "N"; // 알람 여부가 N인 경우
    }

    var tempUrl = server_host + server_port + '/astroapi/notice/v1/notices/all';
    // var tempUrl = server_host + server_port + '/astroapi/notice/v1/notices/user';

    cordova.plugin.http.get(tempUrl, {}, {
        Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
    }, function (response) {
        var jsonData = JSON.parse(response.data);
        console.log('getNotices',"jsonData.data : " + JSON.stringify(jsonData.data));

        // jsonData.data.uid 내림차순으로 정렬
        jsonData.data.sort(function(a, b) {
            return b.uid - a.uid;
        });

        // 필터링된 공지사항 데이터를 가져오기
        var filteredNotices = filterNoticesByAlarm(jsonData.data, alarmFilter);

        // 필터링된 공지사항 데이터를 받아와서 HTML에 추가하는 함수 호출
        addFilteredNoticesToHTML(filteredNotices, categoryFilter);

        if($('#notice_srch_keyword').val() != ''){
            $('#notice_srch_keyword').trigger('keyup');
        }
        $(".notice_pop").stop().show(); // 공지사항을 불러온 후 팝업 열기

        // 공지사항 알림 발송 버튼 클릭 이벤트 핸들러 추가
        $(".btn_confirm_pop").click(function(){
        selectedNoticeUid = $(this).closest("li").find(".btn_notice_view").attr("id");
        $(".btn_submit.sendNotice").data("notice-id", selectedNoticeUid); // 발송 버튼에 선택된 공지사항 ID 저장
        $(".confirm_pop").show(); // 확인 팝업 열기
    });

    $(".btn_edit_notice").click(function(){
            selectedNoticeUid = $(this).closest("li").find(".btn_notice_view").attr("id");
            editSelectedNotice(selectedNoticeUid);
        });

    // 공지사항 삭제 버튼 클릭 이벤트 핸들러 추가
    $(".btn_delete_notice").click(function(){
        selectedNoticeUid = $(this).closest("li").find(".btn_notice_view").attr("id");

        popConfirmAction('삭제하시겠습니까?\n삭제한 데이터는 복구 할 수 없습니다.', function(){
            deleteNotice(selectedNoticeUid); // 선택된 공지사항 삭제 함수 호출
        })
    });

    // 읽은 공지사항 처리
    markReadNotices(filteredNotices);

    // jsonData에서 공지사항의 uid 추출
    var jsonDataUids = jsonData.data.map(function(notice) {
        return notice.uid;
    });

    // readNoticeList에는 있지만 jsonData에는 없는 uid 삭제
    readNoticeList = readNoticeList.filter(function(uid) {
        return jsonDataUids.includes(uid);
    });

    localStorage.setItem('readNoticeList', JSON.stringify(readNoticeList));

    // 모두읽음 버튼 클릭 이벤트 핸들러
    $("#readAll").on("click", function(e){
        e.preventDefault();
        e.stopPropagation();
        readAllNotices();
    });

    // 모두삭제 버튼 클릭 이벤트 핸들러
    $("#deleteAll").on("click", function(e){
        e.preventDefault();
        e.stopPropagation();
        popConfirmAction("공지 사항을\n모두 삭제하시겠습니까?", function(){
            deleteAllNotices();
        });
    });

    // 모든 공지를 읽은 것으로 표시하는 함수
    function readAllNotices() {
        // 모든 공지 읽은 것으로 처리
        $(".new").removeClass("new");
        readNoticeList = [];

        jsonData.data.forEach(item => {
            readNoticeList.push(item.uid);
        });

        localStorage.setItem('readNoticeList', JSON.stringify(readNoticeList));

        // 리스트 갱신
        getNotices("#tab01");
        $(".new").remove(); // 새로고침 후 모든 새로운 표시 제거
    }

    // deleteAll 버튼 클릭 시 실행되는 함수
    function deleteAllNotices() {
        // 모든 공지를 읽은 것으로 처리
        $(".new").removeClass("new");

        // selfDeletedNoticeList에 모든 공지를 추가하여 해당 공지를 삭제했음을 표시
        jsonData.data.forEach(item => {
            var uid = item.uid;
            if (!selfDeletedNoticeList.includes(uid)) {
                selfDeletedNoticeList.push(uid);
            }
            // 이미 읽은 공지는 readNoticeList에 유지하도록 수정
            if (!readNoticeList.includes(uid)) {
                readNoticeList.push(uid); // 읽은 것으로 처리
            }
        });

        localStorage.setItem('readNoticeList', JSON.stringify(readNoticeList));
        localStorage.setItem('selfDeletedNoticeList', JSON.stringify(selfDeletedNoticeList));

        // 리스트 갱신
        getNotices("#tab01");
    }


    }, function (response) {
        // prints 403
        console.log('readAllNotices',"공지사항 불러오기 실패 response status:" + JSON.stringify(response));
        console.log('readAllNotices',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
};



// 알람 여부에 따라 공지사항 필터링하는 함수
function filterNoticesByAlarm(notices, alarmFilter) {
    if (alarmFilter === "Y") {
        return notices.filter(function(notice) {
            return notice.alarm_result !== null && notice.alarm_result !== '' && notice.alarm_result !== undefined;
        });
    } else if (alarmFilter === "N") {
        return notices.filter(function(notice) {
            return notice.alarm_result === null || notice.alarm_result === undefined || notice.alarm_result === '';
        });
    } else {
        return notices; // 알람 필터링이 없는 경우 모든 공지사항 반환
    }
}

// 필터링된 공지사항 데이터를 HTML에 추가하는 함수
// 본인이 작성한 공지사항만 버튼이 보이도록
// pulldelete로 삭제버튼을 눌렀을 때 실행되는 함수
function addFilteredNoticesToHTML(notices, categoryFilter) {
    var noticeList = $(".notice_list");
    noticeList.empty(); // 기존의 공지사항을 모두 지우고 시작

    // 입력된 공지 데이터의 uid 순서대로 리스트를 구성합니다.
    notices.forEach(function(notice) {
        // selfDeletedNoticeList에 있는 uid는 건너뜁니다.
        if (selfDeletedNoticeList.includes(notice.uid)) {
            return;
        }

        // 카테고리 필터 적용
        if (!categoryFilter || notice.category == categoryFilter) {
            // alarm_time을 formatDate 함수를 사용하여 원하는 형식으로 변환
            var formattedDate = notice.create_time == null ? "-" : formatDate(new Date(notice.create_time));

            // 이미 읽은 공지사항인 경우, 새로운 표시를 없앱니다.
            var isNewClass = readNoticeList.includes(notice.uid) ? '' : `<span class="new">N</span>`;

            var creatorName = notice.creator_name !== undefined ? notice.creator_name : "알 수 없음";
            var noticeItem = `
                <li class="pull_delete" data-uid="${notice.uid}">
                    <div>
                        <h4 class="btn_notice_view" id="${notice.uid}">${isNewClass} [공지] ${notice.title}</h4>
                        <p>
                            ${formattedDate} / ${creatorName} <!-- 변환된 날짜 표시 -->
                            <span class="func">
                                ${notice.creator === window.localStorage.getItem("verifyUser") ? `
                                    <button class="btn btn_confirm_pop" type="button" name="" id="${notice.uid}"><i class="ri-send-plane-2-line"></i></button>
                                    <button class="btn btn_edit_notice" type="button" name="" id="${notice.uid}"><i class="ri-edit-2-line"></i></button>
                                    <button class="btn btn_delete_notice" type="button" name="" id="${notice.uid}"><i class="ri-delete-bin-line"></i></button>
                                ` : ''}
                            </span>
                        </p>
                    </div>
                </li>
            `;
            noticeList.append(noticeItem); // 생성한 공지사항 HTML을 리스트에 추가
        }
    });

    // pulldelete 이벤트 핸들러 추가
    $('.pull_delete').pulldelete(function($dom){
        var uid = $dom.data('uid');
        // 선택된 공지를 selfDeletedNoticeList에 추가하여 해당 공지를 삭제했음을 표시
        selfDeletedNoticeList.push(uid);
        readNoticeList.push(uid); 
        localStorage.setItem('selfDeletedNoticeList', JSON.stringify(selfDeletedNoticeList));
        localStorage.setItem('readNoticeList', JSON.stringify(readNoticeList));
        $dom.remove();
        updateNewNoticeIndicator();
    });
}

// 읽은 공지사항 처리하는 함수
function markReadNotices(notices) {
    $(".btn_notice_view").each(function() {
        var noticeUid = $(this).attr("id");
        if (notices.includes(noticeUid)) {
            // 읽은 공지사항이면서 새로운 표시가 있는 경우에만 제거하도록 수정
            if ($(this).find('.new').length > 0) {
                $(this).find('.new').remove();
            }
        }
    });
}

// 이전에 보고 있던 탭을 다시 그리는 함수
function redrawLastVisitedTab() {
    var lastVisitedTabId = localStorage.getItem('lastVisitedTabId');
    if (lastVisitedTabId) {
        getNotices("#" + lastVisitedTabId);
    }
}

// localStorage에서 readNoticeList 불러오기
var readNoticeList = JSON.parse(localStorage.getItem('readNoticeList')) || [];

// 선택한 공지사항 불러오기 함수
function getSelectedNotice(selectedNoticeUid){
    var tempUrl = server_host + server_port + '/astroapi/notice/v1/notice/' + selectedNoticeUid;

    cordova.plugin.http.get(tempUrl, {}, {
        Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
    }, function (response) {
        var jsonData = JSON.parse(response.data);
        console.log('getSelectedNotice',"jsonData.data : " + JSON.stringify(jsonData.data));
        
        var creatorName = jsonData.data.creator_name !== undefined ? jsonData.data.creator_name : "알 수 없음";
        var deptName = jsonData.data.dept_name !== "" ? jsonData.data.dept_name : "알 수 없음";

        // JSON 데이터를 활용하여 HTML 수정
        var noticeHtml = `
            <div class="head" style="-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none">
                <h4>[공지] ${jsonData.data.title}</h4>
                <p>작성자 : ${deptName} / ${creatorName}</p>
                <p>작성일 : ${formatDate(jsonData.data.create_time)}</p>
            </div>
            <div class="cont">
                ${jsonData.data.contents}
            </div>
            <div class="btn_box" style="-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none">
            ${jsonData.data.creator === window.localStorage.getItem("verifyUser") ? '<a href="#" class="notice_forward">재전송</a>' : ''}
                <a href="#" class="notice_view_close">닫기</a>
            </div>
        `;
        $('.notice_pop_close').hide();
        // HTML을 공지사항 컨테이너에 추가
        $("#notice_container").html(noticeHtml);

        // 현재 탭의 ID 저장
        var currentTabId = $(".tab-content .tab-pane.active").attr("id");
        localStorage.setItem('lastVisitedTabId', currentTabId);

        if (!readNoticeList.includes(jsonData.data.uid)) {
            readNoticeList.push(jsonData.data.uid);
            // localStorage에 업데이트된 readNoticeList 저장
            localStorage.setItem('readNoticeList', JSON.stringify(readNoticeList));
        }
        
    }, function (response) {
        console.log('getSelectedNotice',"공지사항 불러오기 실패 response status:" + JSON.stringify(response));
        console.log('getSelectedNotice',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
}

function editSelectedNotice(selectedNoticeUid){
    var tempUrl = server_host + server_port + '/astroapi/notice/v1/notice/' + selectedNoticeUid;

    cordova.plugin.http.get(tempUrl, {}, {
        Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
    }, function (response) {
        var jsonData = JSON.parse(response.data);
        console.log('editSelectedNotice',"jsonData.data : " + JSON.stringify(jsonData.data));
        console.log('editSelectedNotice',selectedNoticeUid);

        $("#notice_edit_submit").text("수정");

        var deptCodes = jsonData.data.trgt_dept_codes.split(',');
        var deptNames = jsonData.data.trgt_dept_names.split(',');

        // 입력사항 초기화
        $("#notice_title").val(jsonData.data.title);
        $("#editor_main").summernote('code', jsonData.data.contents);
        $("input[name='category'][value='" + jsonData.data.category + "']").prop('checked', true);
        jsonData.data.start_time == null ? $("#selected_period").text("") : $("#selected_period").text(formatDate(jsonData.data.start_time) + " ~ " + formatDate(jsonData.data.end_time));
        $("input[name='target'][value='" + jsonData.data.trgt + "']").prop('checked', true).trigger('change');
        jsonData.data.start_time == null ? $("#unlimited").prop("checked", true).trigger("change") : $("#unlimited").prop("checked", false).trigger("change");
        target_dept_codes = jsonData.data.trgt == 'DEPT' ? deptCodes : [];
        target_dept_names = jsonData.data.trgt == 'DEPT' ? deptNames : [];

        if (jsonData.data.trgt == 'DEPT') {
            $("#selected_depts").empty(); // 선택한 부서 항목을 초기화합니다.
            deptNames.forEach(function(deptName) {
                var newListItem = $("<div class='swiper-slide'>" + deptName.trim() + " <a href='#' class='del'></a></div>");
                $(".picks.swiper-wrapper").append(newListItem);
            });
        } else {
            // DEPT가 아닌 경우에는 선택한 부서 항목을 숨깁니다.
            $("#selected_depts").empty(); // 선택한 부서 항목을 초기화합니다.
        }

        $(".notice_edit").stop().show();
        $(".notice_view").stop().hide();
        
    }, function (response) {
        console.log('editSelectedNotice',"공지사항 불러오기 실패 response status:" + JSON.stringify(response));
        console.log('editSelectedNotice',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
};

// ISO 8601 형식의 날짜를 다른 형태로 변환하는 함수
function formatDate(isoDateTime) {
    var date = new Date(isoDateTime);
    var year = date.getFullYear();
    var month = ('0' + (date.getMonth() + 1)).slice(-2);
    var day = ('0' + date.getDate()).slice(-2);
    var hours = ('0' + date.getHours()).slice(-2);
    var minutes = ('0' + date.getMinutes()).slice(-2);
    var formattedDate = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
    return formattedDate;
}

// 날짜 + 시간 변환 함수
// 날짜와 시간을 받아서 지역 시간대를 고려한 ISO 형식의 문자열로 반환하는 함수
function formatDateTime(date, time) {
    date = date.replace(/\./g,'-');
    var combinedDateTime = new Date(date + "T" + time);
    var timezoneOffset = new Date().getTimezoneOffset();
    combinedDateTime.setMinutes(combinedDateTime.getMinutes() - timezoneOffset);
    var isoDateTime = combinedDateTime.toISOString().replace('Z', '');
    var localTimezoneOffset = (timezoneOffset < 0 ? '+' : '-') + pad(Math.abs(timezoneOffset / 60), 2) + ':00';
    return isoDateTime + localTimezoneOffset;
}

// 지역 시간대 오프셋을 두 자리 숫자로 패딩하는 함수
function pad(number, length) {
    var str = '' + number;
    while (str.length < length) {
        str = '0' + str;
    }
    return str;
}

// 시작 시간과 종료 시간을 설정하는 함수
function setDateTimeInputs(datetime, startDateInput, startTimeInput) {
    if (!datetime) return;
    var date = new Date(datetime);
    $(startDateInput).val(date.toISOString().substring(0, 10));
    $(startTimeInput).val(formatUTCtoLocalTime(datetime.substring(11, 16)));
}

// UTC 시간을 로컬 시간으로 변환하여 "HH:mm" 형식으로 반환하는 함수
function formatUTCtoLocalTime(timeStr) {
    if (!timeStr || timeStr.length !== 5) return timeStr; // 잘못된 입력이거나 시간 정보가 없는 경우

    var date = new Date("2023-12-14T" + timeStr + ":00.000+09:00");
    
    // 시간대를 설정해줍니다.
    var localTime = new Date(date.toLocaleString('en-US', {timeZone: 'Asia/Seoul'}));

    var hours = localTime.getHours();
    var minutes = localTime.getMinutes();

    // "HH:mm" 형식으로 반환
    return ('0' + hours).slice(-2) + ':' + ('0' + minutes).slice(-2);
}

// 공지사항 등록
function addNotice() {

    var dataSerializer = cordova.plugin.http.getDataSerializer();

    cordova.plugin.http.setDataSerializer('json');

    // 필요한 데이터를 HTML에서 가져오기
    var title = document.getElementById("notice_title").value;
    var contents = $("#editor_main").val();
    var startDate = $("#notice_start_date").val();
    var startTime = $("#notice_start_time").val();
    var endDate = $("#notice_end_date").val();
    var endTime = $("#notice_end_time").val();
    var category = $("input[name='category']:checked").val();
    var target = $("input[name='target']:checked").val();

    if(!$("#unlimited").is(":checked")){

        //공지사항 기본 유지일수 설정
        let def_remains = 0;

        try {
            let settingData = JSON.parse(localStorage.getItem("settingData")||{});
            def_remains = parseInt(settingData.notice_def_remains);
        } catch (error) {
            def_remains = 0;
        }
        
        if(startDate == '' && startTime == '' && endDate == '' && endTime == ''){
            let today = new Date(), sday = new Date(), eday = new Date(today.setDate(today.getDate() + def_remains)),y,M,d;

            y = sday.getFullYear().toString();
            M = (sday.getMonth()+1).toString();
            if(M.length == 1){ M = '0'+M; }
            d = sday.getDate().toString();
            if(d.length == 1){ d = '0'+d; }
            
            startDate = y+'.'+M+'.'+d;
            startTime = '00:00';

            y = eday.getFullYear().toString();
            M = (eday.getMonth()+1).toString();
            if(M.length == 1){ M = '0'+M; }
            d = eday.getDate().toString();
            if(d.length == 1){ d = '0'+d; }

            endDate = y+'.'+M+'.'+d;
            endTime = '23:59'

        }else if((startDate == '' && startTime != '') || (endDate == '' && endTime != '')){
            return popAlert('공지 기간을 정확히\n입력해주세요.');
        }else{
            if(startDate != '' && startTime == ''){
                startTime = '00:00';
            }

            if(endDate != '' && endTime == ''){
                endTime = '23:59';
            }
        }
    }

     // 시작일과 종료일이 유효한 값인지 확인하고 ISO 형식의 문자열로 변환
     var formattedStartTime = startDate && startTime ? formatDateTime(startDate, startTime) : null;
     var formattedEndTime = endDate && endTime ? formatDateTime(endDate, endTime) : null;

    // 데이터 객체 구성
    var data = {
        corp_code: window.localStorage.getArray("serverData").corp_code,
        category: category,
        title: title,
        contents: contents,
        start_time: formattedStartTime,
        end_time: formattedEndTime,
        temp: 0,
        alarm_time: "",
        trgt: target,
        trgt_dept_codes: $("input[name='target']:checked").val() == 'DEPT' ? target_dept_codes.join(',') : "",
        trgt_dept_names: $("input[name='target']:checked").val() == 'DEPT' ? target_dept_names.join(',') : "",
    };

    if((title == "") || (contents == "")){
        return popAlert("입력사항을\n정확히 입력해주세요.");
    };

    if ((((startDate == "") || (startTime == "") || (endDate == "") || (endTime == "")) || ((startDate == undefined) || (startTime == undefined) || (endDate == undefined) || (endTime == undefined))) && ($("#unlimited").is(":checked") == false)){
        return popAlert("기간을\n정확히 입력해주세요.");
    };
    
    if (selectedNoticeUid == "") {
        var tempUrl = server_host + server_port + '/astroapi/notice/v1/notice';

        cordova.plugin.http.post(tempUrl, data, {
            Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
        }, function(response) {
            var jsonData = JSON.parse(response.data);

            // 성공 시 작업
            getNotices("#tab01");
            $("#span_new_notice").addClass("new");
            $(".notice_edit").stop().hide();
            popConfirmAction("등록되었습니다.\n알림을 발송하시겠습니까?", function(){
                var storedNoticeId = jsonData.data.uid;
                sendNoticeAlert(storedNoticeId);
            });
        }, function(response) {
            console.log('addNotice',"등록 실패 : " + response);
            popAlert(response.error);
        });
    } else {
        var tempUrl = server_host + server_port + '/astroapi/notice/v1/notice/' + selectedNoticeUid;

        console.log('addNotice',"파라미터 잘 들어가는지 확인용 : " + JSON.stringify(data));
        cordova.plugin.http.put(tempUrl, data, {
            Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
        }, function(response) {
            console.log('addNotice',"post 되긴하고 있는거임??" + response.data);
            // 성공 시 작업
            getNotices("#tab01");
            $(".notice_edit").stop().hide();
            popAlert("수정되었습니다.");
            target_dept_codes = [];
            target_dept_names = [];
        }, function(response) {
            console.log('addNotice',"수정 실패 : " + JSON.stringify(response.data));
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });
    }
    cordova.plugin.http.setDataSerializer(dataSerializer);
};

function deleteNotice(selectedNoticeUid){
    var dataSerializer = cordova.plugin.http.getDataSerializer();

    cordova.plugin.http.setDataSerializer('utf8');

    var tempUrl = server_host + server_port + '/astroapi/notice/v1/notice/' + selectedNoticeUid;

    cordova.plugin.http.delete(tempUrl, {}, {
        Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
    }, function (response) {

        popAlert("삭제되었습니다.");
        
        getNotices();
        getNotices("#tab01");

    }, function (response) {
        console.log('deleteNotice',"공지사항 삭제 실패 response status:" + JSON.stringify(response));
        console.log('deleteNotice',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });
    cordova.plugin.http.setDataSerializer(dataSerializer);
};

function readNotice(selectedNoticeUid) {
    var dataSerializer = cordova.plugin.http.getDataSerializer();

    cordova.plugin.http.setDataSerializer('json');

    var tempUrl = server_host + server_port + '/astroapi/notice/v1/notice/read';

    var data = {
        notice_uid: selectedNoticeUid
    };

    cordova.plugin.http.put(tempUrl, data, {
        Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        console.log('readNotice',"jsonData.data : " + JSON.stringify(jsonData.data));
        popAlert("읽음 처리 되었습니다.");

    }, function(response) {
        console.log('readNotice',"공지사항 불러오기 실패 response status:" + JSON.stringify(response));
        console.log('readNotice',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });

    cordova.plugin.http.setDataSerializer(dataSerializer);
}

// 공지사항 알림 발송
function sendNoticeAlert(storedNoticeId){
    var dataSerializer = cordova.plugin.http.getDataSerializer();

    cordova.plugin.http.setDataSerializer('json');

    var tempUrl = server_host + server_port + '/astroapi/mdial/v1/notice/alarm/send';

    console.log('sendNoticeAlert',"sendNotice : " + storedNoticeId);
    
    var data = {
        notice_id : storedNoticeId
    }

    console.log('sendNoticeAlert',data);

    cordova.plugin.http.post(tempUrl, data, {
        Authorization: 'Bearer ' + window.localStorage.getArray("userData").astroToken
    }, function (response) {
        var jsonData = JSON.parse(response.data);
        console.log('sendNoticeAlert',"jsonData.data : " + JSON.stringify(jsonData));
        popAlert("발송되었습니다.")
    }, function (response) {
        console.log('sendNoticeAlert',"공지사항 발송 실패 response status:" + JSON.stringify(response));
        console.log('sendNoticeAlert',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });

    cordova.plugin.http.setDataSerializer(dataSerializer);
};

var upinsert = "U";
    
function getTreeData(){
    //조직도
    var tree;
    
    var tempUrl = server_host + server_port + '/astroapi/base/v1/corps/withdept/tree/' + serverData.corp_code;

    cordova.plugin.http.get(tempUrl, { }, {
        Authorization: 'Bearer '+ window.localStorage.getArray("userData").astroToken
    }, function(response) {
        var jsonData = JSON.parse(response.data);
        try {
            var transformedData = transformData(jsonData.data);
            console.log('getTreeData',jsonData);
            tree = new DinampTreeEditor('.organization').setData(transformedData).set({
                extended: false,
                editable: true
            });
        } catch (e) {
            console.error('getTreeData',e);
        }
    }, function(response) {
        // prints 403
        console.log('getTreeData',"response status:"+response.status);
        //prints Permission denied
        console.log('getTreeData',response.error);
        popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
    });

    var transformData = function (data) {
        var transformedData = [];

        for (var i = 0; i < data.length; i++) {

            var item = data[i];
            var transformedItem = {
                title: item.name,
                code: item.code,
                corp_code: item.corp_code,
                prnt_code: item.prnt_code,
                group_type: item.group_type,
                children: [],
            };

            if (item.childs && (item.childs).length > 0) {
                transformedItem.children = transformData(item.childs);
            }

            transformedData.push(transformedItem);
        }

        return transformedData;
    };
};

var selected_dept_code;
var selected_dept_name;

//클릭시 조직정보 조회
$(document).on('click', '.jsTree p', function (e) {
    var orgName = $(this).text();
    var grouptype = $(this).attr('group-type');

    console.log('jsTree p',grouptype);

    upinsert = "U";

    if ($(this).data('code') != null && grouptype !== "C") {
        var dept_code = $(this).attr("data-code");
        var corp_code = $(this).attr("corp-code");

        $('.jsTree').find('.itemParent').removeClass('selected');
        $(this).closest('.itemParent').addClass('selected');

        var tempUrl = server_host + server_port + '/astroapi/base/v1/dept/detail/' + dept_code + '/' + corp_code;

        cordova.plugin.http.get(tempUrl, {},{
            Authorization: 'Bearer '+ window.localStorage.getArray("userData").astroToken
        }, function(response) {
            var jsonData = JSON.parse(response.data);

            selected_dept_code = jsonData.data.code;
            selected_dept_name = jsonData.data.name;

        }, function(response) {
            // prints 403
            console.log('jsTree p',"response status:"+response.status);
            //prints Permission denied
            console.log('jsTree p',response.error);
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });
    }
});


function refreshButtuons() {

    var cust_func_code = settingData.cust_func_code;

    $(".call_back").hide();
    $(".call_through").hide();
    $(".click_to_call").hide();

    if (cust_func_code == "1") {
        $(".call_back_div").empty();
        $(".call_back_div").append("<i class='bi bi-telephone'></i>통화(C.B)");
        $(".call_back").show();
    } else if(cust_func_code == "2") {
        $(".call_through_div").empty();
        $(".call_through_div").append("<i class='bi bi-telephone'></i>통화(C.T)");
        $(".call_through").show();
    } else if(cust_func_code == "3") {
        $(".call_through_div").empty();
        $(".call_through_div").append("<i class='bi bi-telephone'></i>안심통화");
        $(".call_through").show();
    } else if(cust_func_code == "4") {
        $(".call_through_div").empty();
        $(".call_through_div").append("<i class='bi bi-telephone'></i>안심통화");
        $(".click_to_call_div").empty();
        $(".click_to_call_div").append("<i class='bi bi-phone'></i>휴대폰통화");
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "5") {
        $(".call_through_div").empty();
        $(".call_through_div").append("<i class='bi bi-telephone'></i>안심통화");
        $(".click_to_call_div").empty();
        $(".click_to_call_div").append("<i class='bi bi-phone'></i>5G통화");
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "6") {
        $(".call_back_div").empty();
        $(".call_back_div").append("<i class='bi bi-telephone'></i>통화(C.B)");
        $(".call_through_div").empty();
        $(".call_through_div").append("<i class='bi bi-telephone'></i>통화(C.T)");
        $(".call_back").show();
        $(".call_through").show();
    } else if(cust_func_code == "7") {
        $(".call_back_div").empty();
        $(".call_back_div").append("<i class='bi bi-telephone'></i>통화(C.B)");
        $(".call_through_div").empty();
        $(".call_through_div").append("<i class='bi bi-telephone'></i>통화(C.T)");
        $(".click_to_call_div").empty();
        $(".click_to_call_div").append("<i class='bi bi-phone'></i>휴대폰통화");
        $(".call_back").show();
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "8") {
        $(".call_through_div").empty();
        $(".call_through_div").append("<i class='bi bi-telephone'></i>내선통화");
        $(".click_to_call_div").empty();
        $(".click_to_call_div").append("<i class='bi bi-phone'></i>휴대폰통화");
        $(".call_through").show();
        $(".click_to_call").show();
    } else if(cust_func_code == "9") {
        $(".call_back_div").empty();
        $(".call_back_div").append("<img src='img/gnb_01_on.png'>통화(C.B)");
        $(".click_to_call_div").empty();
        $(".click_to_call_div").append("<img src='img/icon_mobile_blue.png'>휴대폰통화");
        $(".call_back").show();
        $(".click_to_call").show();
    }
}