let is_device_ready = false, ready_to_dial = false, exitCheck = false;

document.addEventListener('deviceready', function () {
    is_device_ready = true;
    getSchemeData();

    try {
        window.plugins.gntel.putPreferences([
            'cm_api_url',`https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/`
            , 'cm_token', (userData.token||'')
            , 'astro_api_url', `${server_host}/astroapi/`
            , 'astro_token', (userData.astroToken||'')
            , 'cm_my_dn', (typeof custom_cm_my_dn != 'undefined' && custom_cm_my_dn != '')?eval(custom_cm_my_dn):`${userData.prefixEx.replace(serverData.svcPrefixNo,'')}`
            , 'mydn', `${userData.prefixEx}`
            , 'forward_call_mention', serverData.forward_call_mention
        ], (r) => {console.log('success put putPreferences', r);});
    } catch (error) {
        console.warn(error)
    }

    serverDataUpdate();
    G.checkOrganization();
    createAddress();

    /**
     * {callHistory : [{name:.., number:.., date_time:..}]}
     */
    if(userData.call_history_exp === undefined){
        syncUserData({
            call_history_exp : '365'
        });
    };

    readFile('call_history.json', (r) => {
        try {
            call_history_list = JSON.parse(r).callHistory || [];
            call_history_list = call_history_list.filter(item => {
                let compare = new Date(); 
                compare.setDate(new Date().getDate() - userData.call_history_exp);  
                compare.setHours(0, 0, 0, 0);  
                return new Date(item.date_time) > compare;
            });
        } catch (error) {
            call_history_list = [];
        }
    });

    cordova.exec(
        (jsonStringResult)=>{
            try {
                const result = JSON.parse(jsonStringResult);

                if (result.statusYN === "N" && (typeof USE_MCID == 'undefined' || USE_MCID != false)) {
                    switch (result.details.statusCode) {
                        case '01':
                            popAlert("전화 차단 및 발신자 확인 기능이<br/>사용자에 의해 비활성화되었습니다.<br/>(설정 > 전화 > 전화 차단 및 발신자 확인)");
                            break;
                    
                        default:
                            break;
                    }
                }

            } catch (e) {
                console.error("checkCallDirectoryStatus", e.stack, jsonStringResult);
            }
        },     

        (f) => {
            console.error("checkCallDirectoryStatus fail", f);
        },
        "GntelPlugin",
        "checkCallDirectoryStatus",
        []
    );

    //FCM푸시메세지 배너 클릭해서 들어오면 공지사항 페이지로 이동
    FirebasePlugin.onMessageReceived((msg)=>{
        // 공지사항 푸시는 messageType이 notification이고
        // 모바일 mcid 기능을 위한 통화이벤트 정보 푸시는 messageType이 data이다.
        if(msg.messageType == 'notification' && msg.body != undefined){
            $('.mainSwiper a.item[data-id="notice"]').trigger('click');
            $('body').removeClass('dial-mode');
            $('.dial_cont, .call_cont, .view_cont').addClass('none');
        }
    });
});

//환경설정 - 테마설정 - 프로필 미리보기iframe사이즈 조정
window.addEventListener('message', function (event) {
    if (event.data.iframeHeight) {
        // let iframe = $(`iframe[src="${event.data.namecard}"]`)
        // iframe.css('height',event.data.iframeHeight + 'px');

        $('#div_setting_namecards iframe').map((idx, iframe) => {
            if (`${event.data.namecard || ''}`.indexOf($(iframe).attr('src')) > -1) {
                $(iframe).css('height', event.data.iframeHeight + 'px');
                return;
            }
        })
    } else if (event.data.clickEvent) {
        let iframe = $(`iframe[src="${event.data.namecard}"]`)
        iframe.closest('.profile').find('input[type=radio][name=profile]').trigger('click');
    }
});
let fullHeight = window.innerHeight;
//키패드 감지
window.addEventListener('resize', function(e){
    const currentHeight = window.innerHeight;
    const isKeyboardOpen = currentHeight < fullHeight * 0.8;

    if (isKeyboardOpen) {
        $('.mcaller_menu, .foot_btn').addClass('none');
    } else {
        $('.mcaller_menu, .foot_btn').removeClass('none');
    }
});

$(() => {

    //하단 플로팅 메뉴 - mcaller메뉴 
    $('.mcaller_menu a.menu').off('click.menuNav').on('click.menuNav', async function () {
        const pageid = $(this).data('id');
        const file = $(this).data('file');
        const $target = getContainer(pageid);

        
        // 화면 분기
        if (pageid === 'dial') {
            $('.call_cont').addClass('none');
            $('.dial_cont').removeClass('none');
            $('body').addClass('dial-mode');
        } 
        else {
            $('.dial_cont').addClass('none');
            $('.call_cont, .header.board .search').removeClass('none');
            $('body').removeClass('dial-mode');
        }
        
        initFooter('hide');
        
        $('.main_cont, .sub_cont, .view_cont').addClass('none');
        
        // 헤더 표시 전환
        $('#header_board_name').text($(this).find('>p').text());
        $('.header.board').removeClass('none');
        $('.header.main, .boardSwiper').addClass('none');
        
        $('.header.board .inp').html($(`#${pageid}_header_inp_template`).text());

        await loadExternalHTML(pageid, file, $target);

        
        if (pageid === 'organization' && typeof G.drawOrganization === 'function') {
            G.drawOrganization();
        }
    });

    //앱스킴 받았을 경우 다이얼 페이지로 자동으로 이동시켜야함
    // 최대한 빠르게 이동시키기위해 하단 플로팅 메뉴 이벤트 바인딩 코드를 최상단에 배치함.
    ready_to_dial = true;
    getSchemeData();

    document.addEventListener("backbutton", on_backbutton_main, true);

    initMainArticle();
    initMain();

    if(typeof use_main_page == 'undefined' || use_main_page == true) {
        $('.header.main, .main_cont').removeClass('none');
    }else{
        $('.header.main, .main_cont').addClass('none');
    }
    
    $('.header.board, .sub_cont, .call_cont, .view_cont, foot_btn').addClass('none');
    
//-----------------------------게시판 목록 관련 시작

    //게시판 자동 페이징 조회
    $('.sub_cont').bind('scroll', () => {
        if ($('.sub_cont .board_list>li').length >= 50 && $('.sub_cont')[0].scrollHeight - Math.ceil($('.sub_cont').scrollTop()) <= $('.sub_cont').outerHeight()) {
            loadBoardData($('.boardSwiper a.tab.on').data('id'), true);
        }
    });

    //게시물 클릭 공통
    $('.sub_cont').on('click', '.board_list>li>a', (e) => {
        $('.view_cont>.for_board_view').removeClass('none');
        $('.view_cont>.for_board_edit, .sub_cont').addClass('none');
    });

    //게시물 클릭 - 새올 게시판 - 내용보기
    $('.sub_cont').on('click', '.board_list>li>a[data-boardseq]', (e) => {
        console.log('게시물 클릭 - 새올게시판 - 내용보기', e.currentTarget);

        //수정버튼 표시위해...
        $('.view_cont .for_board_view').data('creator', 'null');

        initFooter('common_view');
        $('#btn_prev_content,#btn_next_content').addClass('board-saeol');
        $('#btn_prev_content,#btn_next_content').removeClass('board-astro');
        let pagename = $('.boardSwiper a.tab.on').data('id');
        let a_list = $(`.sub_cont .board_list>li:not(.none)>a`);
        let thisindex = -1;
        let thisboardseq = $(e.currentTarget).data('boardseq');
        let thisdocseq = $(e.currentTarget).data('docseq');

        $('#detail_title, #detail_span_info, #detail_ul_attach, #detail_board_cont').empty();
        $('#detail_ul_attach, .comments_open').addClass('none');

        for (let idx = 0; idx < a_list.length; idx++) {
            if ($(a_list[idx]).data('boardseq') == thisboardseq && $(a_list[idx]).data('docseq') == thisdocseq) {
                thisindex = idx;
                break;
            }
        }

        let previndex = thisindex - 1;
        let nextindex = thisindex + 1;

        //이전 게시물 버튼
        if (previndex == -1) {
            $('#btn_prev_content').addClass('none');
        } else {
            $('#btn_prev_content').removeClass('none');
        }

        $('#btn_prev_content').data('boardseq', $(a_list[previndex]).data('boardseq'));
        $('#btn_prev_content').data('docseq', $(a_list[previndex]).data('docseq'));

        //다음 게시물 버튼
        if (nextindex == a_list.length) {
            $('#btn_next_content').addClass('none');
        } else {
            $('#btn_next_content').removeClass('none');
        }

        $('#btn_next_content').data('boardseq', $(a_list[nextindex]).data('boardseq'));
        $('#btn_next_content').data('docseq', $(a_list[nextindex]).data('docseq'));


        requestAstro(`isboard/v1/getContent/${thisboardseq}/${thisdocseq}`, {}, 'get')
            .then((r) => {
                console.log(`isboard/v1/getContent/${thisboardseq}/${thisdocseq} response code:: `, r.code);
                if (r.code == '0000') {
                    $('#detail_title').text(r.data.title);

                    $('#detail_span_info').text(`${r.data.userName || ''}/${r.data.dept_name || ''}/${r.data.update_date ? (r.data.update_date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')) : ''}`);

                    if (r.data.vname != undefined && r.data.vname != '') {
                        $('#detail_ul_attach').removeClass('none');

                        let vnames = r.data.vname.split('||');
                        let rnames = r.data.rname.split('||');
                        try {
                            vnames.forEach((filename, idx) => {
                                $('#detail_ul_attach').append(`<li><a href="javascript:" data-url="${file_download_url}${(r.data.file_path || '').replace(/\/ntishome\//, '\/ntis\/')}/${rnames[idx]}" download="${filename}">${filename}</a></li>`);
                            });
                        } catch (error) {
                        }
                    }

                    $('#detail_board_cont').empty();
                    $('#detail_board_cont').html(r.data.contents.replaceAll(`${img_req_org_url || 'img_req_org_url'}`, `${img_req_replaced_url || 'img_req_replaced_url'}`));

                    //폰트사이즈 시작
                    $('#font-setting-buttons').easyView({
                        container: '#detail_board_cont',
                        increaseSelector: '.increase',
                        decreaseSelector: '.decrease',
                        normalSelector: '.reset'
                    });

                    readed_contents = localStorage.getArray('readed_contents');

                    if (readed_contents[r.data.board_seq] == undefined) {
                        readed_contents[r.data.board_seq] = [];
                    }

                    if (!readed_contents[r.data.board_seq].some(seq => seq == r.data.doc_seq)) {
                        readed_contents[r.data.board_seq].push(r.data.doc_seq);
                    }

                    localStorage.setArray('readed_contents', readed_contents);
                    $(e.currentTarget).addClass('visited');

                    //메인화면 신규게시물 리스트에 신규 표시 제거 - 읽음 처리
                    $(`.main_cont .article_list li[data-boardseq=${thisboardseq}][data-docseq=${thisdocseq}] span.new`).remove();

                    //현재게시판에 visited클래스 추가
                    $(`.sub_cont .board_list a[data-boardseq=${thisboardseq}][data-docseq=${thisdocseq}]`).addClass('visited');
                }
            })
            .catch((error) => {
                console.log('게시물 클릭 - 새올게시판 - 내용보기 error occurred ::', error);
            }).finally(() => {
                $('.view_cont, .for_board_view').removeClass('none');
                $('.for_board_edit').addClass('none');
            })
            ;
    });

    //게시물 클릭 - astro 게시판(카풀,공지사항) - 내용보기
    $('.sub_cont').on('click', '.board_list>li>a[data-uid]', (e) => {
        console.log('게시물 클릭 - astro게시판 - 내용보기', e.currentTarget);

        //수정버튼 표시위해...
        $('.view_cont .for_board_view').data('creator', $(e.currentTarget).data('creator'));

        initFooter($(e.currentTarget).hasClass('type-notice') ? 'notice_view' : 'reply_view');

        $('#btn_prev_content,#btn_next_content').addClass('board-astro');
        $('#btn_prev_content,#btn_next_content').removeClass('board-saeol');
        let pagename = $('.boardSwiper a.tab.on').data('id');
        let a_list = $(`.sub_cont .board_list>li:not(.none)>a`);
        let thisindex = -1;
        let thisuid = $(e.currentTarget).data('uid');
        $('#detail_title, #detail_span_info, #detail_ul_attach, #detail_board_cont').empty();
        // $('#detail_ul_attach, .comments_open').addClass('none');

        for (let idx = 0; idx < a_list.length; idx++) {
            if ($(a_list[idx]).data('uid') == thisuid) {
                thisindex = idx;
                break;
            }
        }

        let previndex = thisindex - 1;
        let nextindex = thisindex + 1;

        //이전 게시물 버튼
        if (previndex == -1) {
            $('#btn_prev_content').addClass('none');
        } else {
            $('#btn_prev_content').removeClass('none');
        }

        $('#btn_prev_content').data('uid', $(a_list[previndex]).data('uid'));

        //다음 게시물 버튼
        if (nextindex == a_list.length) {
            $('#btn_next_content').addClass('none');
        } else {
            $('#btn_next_content').removeClass('none');
        }

        //수정버튼
        $('.foot_btn .foot_btn_modify').data('uid', thisuid);

        $('#btn_next_content').data('uid', $(a_list[nextindex]).data('uid'));

        requestAstro(`notice/v1/notice/${thisuid}`, {}, 'get')
            .then(r => {
                console.log(`notice/v1/notice/${thisuid} response code :: `, r.code);
                if (r.code == '0000') {

                    $('#iframe_comments').get(0).contentWindow.postMessage({
                        action: 'drawComments'
                        , uid: r.data.uid
                        , replies: JSON.stringify(r.data.replies || [])
                    }, '*');

                    $('#detail_title').text(r.data.title);

                    $('#detail_span_info').text(`${r.data.creator_name || ''}/${r.data.dept_name || ''}/${r.data.update_time ? (gformatter.date(new Date(r.data.update_time), 'y-M-d')) : ''}`);

                    $('#detail_board_cont').empty();
                    $('#detail_board_cont').html(r.data.contents);

                    //폰트사이즈 시작
                    $('#font-setting-buttons').easyView({
                        container: '#detail_board_cont',
                        increaseSelector: '.increase',
                        decreaseSelector: '.decrease',
                        normalSelector: '.reset'
                    });

                    readed_contents = localStorage.getArray('readed_contents');

                    if (readed_contents[r.data.category] == undefined) {
                        readed_contents[r.data.category] = [];
                    }

                    if (!readed_contents[r.data.category].some(seq => seq == r.data.uid)) {
                        readed_contents[r.data.category].push(r.data.uid);
                    }

                    localStorage.setArray('readed_contents', readed_contents);
                    $(e.currentTarget).addClass('visited');


                    //현재게시판에 visited클래스 추가
                    $(`.sub_cont .board_list a[data-uid=${thisuid}]`).addClass('visited');


                    if ($(e.currentTarget).hasClass('type-reply')) {
                        $('#detail_reply_count').text(r.data.replies?.length || 0);
                    }
                }
            })
            .catch(error => {
                console.log('게시물 클릭 - 공지사항 - 내용보기 error occurred ::', error);
            }).finally(() => {
                $('.view_cont, .for_board_view').removeClass('none');
                $('.for_board_edit').addClass('none')
            })
            ;
    });

    //검색
    $('.header.board').on('keyup', '#inp_board_search', (e) => {
        if (e.keyCode == 13) {
            $('#btn_board_search').trigger('click');
        }
    });

    $('.header.board').on('click', '#btn_board_search', (e) => {
        let pagename = $(e.currentTarget).data('pageid'),
            keyword = $('#inp_board_search').val(),
            start_date = $('#term_pop_for_search_start_date').val().replace(/[^0-9]/g, ''),
            end_date = $('#term_pop_for_search_end_date').val().replace(/[^0-9]/g, '')
            ;

        $('.header.board #inp_board_search').blur();

        if (keyword == '' && start_date == '' && end_date == '') {
            loadBoardData(pagename);
        } else {
            loadBoardData(pagename, false, { search_key: keyword, start_date: start_date, end_date: end_date })
        }

    });

    //검색 기간 팝업
    $('#term_pop_for_search_start_date,#term_pop_for_search_end_date').datepicker();
    $('.header.board').on('click', '#btn_board_search_term_pop', (e) => {
        $('.term_pop_for_search').removeClass('none');
    });
    $('#term_pop_for_search_btn_ok').on('click', () => {
        $('.term_pop_for_search').addClass('none');
    });
    $('#term_pop_for_search_btn_reset').on('click', (e) => {
        $('#term_pop_for_search_start_date,#term_pop_for_search_end_date').val('');
    });

//----------------------------게시판 목록 관련 끝

// ---------------------게시판 상세보기 페이지 관련 시작

    //목록으로
    $('.foot_btn .foot_btn_to_list').on('click', () => {
        checkReadWholeContents(function () {
            $('.view_cont').addClass('none');
            $('.sub_cont').removeClass('none');

            if ($('.boardSwiper a.tab.on').data('id') == 'notice') {
                initFooter('notice_list');
            } else {
                initFooter('common_list');
            }
        });
    });

    //댓글 팝업
    $(".comments_open").click(function (e) {
        e.preventDefault();
        $(".comments").fadeIn(100);
        $('.bottom_up').addClass('active');
    });

    $(".fade_action").click(function (e) {
        e.preventDefault();
        $('.bottom_up').removeClass('active');
        $(e.currentTarget).closest('.dim_bg').fadeOut(1000);
    });

    //이전 다음
    $('#btn_prev_content, #btn_next_content').on('click', function () {
        if ($(this).hasClass('board-saeol')) {
            $(`.sub_cont .board_list>li:not(.none)>a[data-boardseq=${$(this).data('boardseq')}][data-docseq=${$(this).data('docseq')}]`).trigger('click');
        } else {
            $(`.sub_cont .board_list>li:not(.none)>a[data-uid=${$(this).data('uid')}]`).trigger('click');
        }
    });

    //첨부파일 다운로드
    $('#detail_ul_attach').on('click', 'a', function () {
        let url = $(this).data('url'), filename = $(this).attr('download');

        if ((navigator.connection.type || '').toLowerCase() == 'none') {
            popalert('현재 네트워크에 연결되어 있지 않습니다.');
        } {
            fileDownloader.downloadAndOpenFile(`isboard/v1/downattach?request_url=${encodeURIComponent(url)}&file_name=${encodeURIComponent(filename)}`, filename);
        }
    });

    //다운로드 취소
    $('#cancel_down_attach').on('click', (e) =>{
        if(fileTransfer != undefined){
            fileTransfer.abort();
        }
    });
    
//-----------------------게시판 상세보기 페이지  관련 끝

//---------------- 메인화면 관련 시작

    //게시판 이동(메인화면, 게시판 상단 swiper)
    $('.mainSwiper a.item, .boardSwiper a.tab, .main_cont .more').on('click', function (e) {
        e.stopPropagation();

        if (/^https?:\/\//.test(($(this).data('file') || ''))) {
            cordova.InAppBrowser.open( $(this).data('file') ,'_system'  , 'location=yes');
            return;
        }

        //공지작성 권한 메뉴 진입시 반영
        requestAstro(`base/v1/user/${userData.userId}/${serverData.corp_code}`, {}, 'get')
        .then(async r => {
            syncUserData({
                noticeRegPermitted : r.data.notice_reg_permitted?'true':'false'
            });

            $('.header.main, .main_cont, .view_cont, .view_cont .for_setting').addClass('none');
            $('.header.board, .sub_cont, .header.board .search').removeClass('none');
            $('.boardSwiper a.tab.on').removeClass('on');

            const pageId = $(this).data('id');
            const file = $(this).data('file');

            if (pageId === 'attendance') { 
                $('.header.board .search .inp').addClass('none');   
            } else {
                $('.header.board .search .inp').removeClass('none');
            }

            $(`.boardSwiper a.tab[data-id=${pageId}]`).addClass('on');

            await loadExternalHTML(pageId, file, $('.sub_cont'));
            console.log('complete');

            if (pageId === 'notice') {
                $(document)
                    .off('change.noticeTab', '.tab input[name="notice_type"]') 
                    .on('change.noticeTab', '.tab input[name="notice_type"]', function () {
                        const value = this.value;  // "ALL" | "N" | "E"
                        const option = (value === 'ALL') ? { categories: ['E', 'N'] } : { category: value };
                        loadBoardData('notice', false, option);
                    });
            }

            $('.header.board .inp').html($(`#header_board_inp_template`).text());
            $('.header.board .inp #btn_board_search').data('pageid', pageId);

            loadBoardData(pageId);

            $('#term_pop_for_search_btn_reset').trigger('click');
        });
    });

    //메인화면 신규게시물 클릭
    $('.main_cont .article_list').on('click', '.main_view_detail_article', async function () {
        let pagename = 'article'
            , $element_a = $(this).find('>a')
            ;
        await loadExternalHTML('article', 'content/content-article.html', $('.sub_cont'));

        let target_boardseq = $(this).data('boardseq');
        let target_doc_seq = $(this).data('docseq');

        $.when(
            new Promise((resolve, reject) => {
                requestAstro(`isboard/v1/getContent/${target_boardseq}/${target_doc_seq}`, {}, 'get')
                    .then(r => resolve(r))
                    .catch(f => resolve(f))
            })
            , loadBoardData('article')

        )
            .then((board_data, board_list) => {
                if (board_data.code == '0000') {
                    initFooter('common_view');

                    $('#detail_title').text(board_data.data.title);

                    $('#detail_span_info').text(`${board_data.data.user_name || ''}/${board_data.data.dept_name || ''}/${board_data.data.update_date ? (board_data.data.update_date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3')) : ''}`);

                    if (board_data.data.vname != undefined && board_data.data.vname != '') {

                        let vnames = board_data.data.vname.split('||');
                        let rnames = board_data.data.rname.split('||');
                        try {
                            vnames.forEach((filename, idx) => {
                                $('#detail_ul_attach').append(
                                    `<li>
                                <a href="javascript:" data-url="${file_download_url}${(board_data.data.file_path || '').replace(/\/ntishome\//, '\/ntis\/')}/${rnames[idx]}" download="${filename}">${filename}</a>
                            </li>`
                                );
                            });
                        } catch (error) {
                        }
                    }

                    $('#detail_board_cont').empty();
                    $('#detail_board_cont').html(board_data.data.contents.replaceAll(`${img_req_org_url}`, `${img_req_replaced_url}`));


                    //폰트사이즈 시작
                    $('#font-setting-buttons').easyView({
                        container: '#detail_board_cont',
                        increaseSelector: '.increase',
                        decreaseSelector: '.decrease',
                        normalSelector: '.reset'
                    });

                    readed_contents = JSON.parse(localStorage.getItem('readed_contents') || '{}');
                    if (readed_contents[board_data.data.board_seq] == undefined) {
                        readed_contents[board_data.data.board_seq] = [];
                    }

                    readed_contents[board_data.data.board_seq].push(board_data.data.doc_seq);

                    localStorage.setItem('readed_contents', JSON.stringify(readed_contents));
                    $element_a.addClass('visited');

                    let a_list = $(`.sub_cont .board_list>li:not(.none)>a`);
                    let thisindex = -1;

                    for (let idx = 0; idx < a_list.length; idx++) {
                        if ($(a_list[idx]).data('boardseq') == board_data.data.board_seq && $(a_list[idx]).data('docseq') == board_data.data.doc_seq) {
                            thisindex = idx;
                            break;
                        }
                    }

                    let previndex = thisindex - 1;
                    let nextindex = thisindex + 1;

                    //이전 게시물 버튼
                    if (previndex == -1) {
                        $('#btn_prev_content').addClass('none');
                    } else {
                        $('#btn_prev_content').removeClass('none');
                    }

                    $('#btn_prev_content').data('boardseq', $(a_list[previndex]).data('boardseq'));
                    $('#btn_prev_content').data('docseq', $(a_list[previndex]).data('docseq'));

                    //다음 게시물 버튼
                    if (nextindex == a_list.length) {
                        $('#btn_next_content').addClass('none');
                    } else {
                        $('#btn_next_content').removeClass('none');
                    }

                    $('#btn_next_content').data('boardseq', $(a_list[nextindex]).data('boardseq'));
                    $('#btn_next_content').data('docseq', $(a_list[nextindex]).data('docseq'));

                    $('#btn_prev_content,#btn_next_content').addClass('board-saeol');
                    $('#btn_prev_content,#btn_next_content').removeClass('board-astro');

                }
            })
            .always(() => {
                $(`.view_cont, .header.board, .foot_bt, .for_board_view, .header.board .search`).removeClass('none');
                $('.main_cont, .sub_cont, .header.main, .for_board_edit').addClass('none');
            });
    });

    //환경설정
    $('a.setting').on('click', async (e) => {
        $('.header-main-title').text($(e.currentTarget).data('title'));
        $('.main_cont, .header.main p.logo, .header.main .blank, .header.board, .view_cont .for_board_view, .view_cont .for_board_edit, .call_cont, .dial_cont, .sub_cont, .search').addClass('none');
        $('.header.main, .view_cont, .header.main p.header-main-title, .header.main .gohome, .view_cont .for_setting').removeClass('none');

        await loadExternalHTML('setting', 'content/content-setting.html', $('.view_cont .for_setting'));
        $('.view_cont').scrollTop(0);
    });

    //메인 검색
    $('#inp_main_search').on('keyup', (e) => {
        e.stopPropagation();
        if (e.keyCode == 13) {
            $('#btn_main_search').trigger('click');
        }
    });

    $('#btn_main_search').on('click', async (e) => {
        e.stopPropagation();

        $('#inp_main_search').val($('#inp_main_search').val().trim());

        if ($('#inp_main_search').val() == '') {
            $(`.sub_cont.main-search ul.board_list, .sub_cont.main-search ul.person_list`).addClass('none');
            $(`.sub_cont.main-search .empty-post, .sub_cont.main-search .empty-person`).removeClass('none');
            $('#search_keyword').text('검색어없음');
            return popAlert('검색어를 입력하세요.');
        }


        $('.header-main-title').text($(e.currentTarget).data('title'));
        $('.main_cont, .header.main p.logo, .header.main .blank').addClass('none');
        $('.header.main, .sub_cont, .header.main p.header-main-title, .header.main .gohome').removeClass('none');
        $('.sub_cont').addClass('main-search');

        await loadExternalHTML('search', 'content/content-search.html', $('.sub_cont'));
        console.log('load complete');

        $('#search_keyword').text($('#inp_main_search').val());

        Promise.all(
            [
                requestAstro(`isboard/v1/search`, { search_key: $('#inp_main_search').val(), board_seq: 'new' }, 'post'),
                requestAstro(`notice/v1/notices/all`, { 
                    search_key: $('#inp_main_search').val(), 
                    board_seq: 'new',
                    corp_code : serverData.corp_code,
                    temp : false,
                    categories : ["E", "N", "C"]
                }, 'post')
            ]
        )
        .then(([saeoldata, noticedata]) =>{

            $(`.sub_cont.main-search ul.board_list`).addClass('none');
            $(`.sub_cont.main-search .empty-post`).removeClass('none');

            //새올게시판데이터
            if (saeoldata.code == '0000') {
                if (!$.isEmptyObject(saeoldata.data)) {
                    $(`.sub_cont.main-search ul.board_list`).removeClass('none');
                    $(`.sub_cont.main-search .empty-post`).addClass('none');

                    saeoldata.data.map((item, idx) => {
                        let readed_doc_list = readed_contents[item.board_seq] || [];
                        $(`.sub_cont.main-search ul.board_list`).append(
                            $('#board_item_template').text()
                                .replace(/{{title}}/g, item.title)
                                .replace(/{{doc_seq}}/g, item.doc_seq)
                                .replace(/{{board_seq}}/g, item.board_seq)
                                .replace(/{{is_new}}/g, item.is_new == 1 ? '' : 'none')
                                .replace(/{{user_name}}/g, item.user_name)
                                .replace(/{{dept_name}}/g, item.dept_name)
                                .replace(/{{update_date}}/g, item.update_date)
                                .replace(/{{is_new}}/g, item.is_new == 1 ? '' : 'none')
                                .replace(/{{visited}}/g, readed_doc_list.includes(item.doc_seq) ? 'visited' : '')
                        );
                    });
                }
            } else {
                console.error(`isboard/v1/search`, saeoldata);
            }

            //공지사항, 카풀 게시판 데이터
            if(noticedata.code == '0000'){
                if (!$.isEmptyObject(noticedata.data)) {
                    $(`.sub_cont.main-search ul.board_list`).removeClass('none');
                    $(`.sub_cont.main-search .empty-post`).addClass('none');

                    noticedata.data.map((item, idx) => {
                        let readed_doc_list = readed_contents[item.category] || [];

                        if(item.category == "C"){
                            $(`.sub_cont.main-search ul.board_list`).append(
                                $('#board_reply_template').text()
                                .replace(/{{uid}}/g, item.uid)
                                .replace(/{{category}}/g, item.category)
                                .replace(/{{title}}/g, item.title)
                                .replace(/{{name}}/g, item.creator_name)
                                .replace(/{{date}}/g, new Date(item.update_time).toLocaleString())
                                .replace(/{{show_reply}}/g, (item.reply_count || 0) > 0 ? '' : 'none')
                                .replace(/{{reply_count}}/g, (item.reply_count || 0))
                                .replace(/{{visited}}/g, readed_doc_list.includes(item.uid) ? 'visited' : '')
                                .replace(/{{my_content}}/g, (item.creator == userData.userId && userData.noticeRegPermitted == 'true') ? '' : 'none')
                                .replace(/{{creator}}/g, item.creator)
                            )
                        }else{
                            $(`.sub_cont.main-search ul.board_list`).append(
                                $('#board_notice_template').text()
                                .replace(/{{uid}}/g, item.uid)
                                .replace(/{{category}}/g, item.category)
                                .replace(/{{title}}/g, item.title)
                                .replace(/{{name}}/g, (item.creator_name || ''))
                                .replace(/{{dept_name}}/g, (item.dept_name || '') == '' ? '' : (' / ' + item.dept_name))
                                .replace(/{{date}}/g, ' / ' + new Date(item.update_time).toLocaleString())
                                .replace(/{{visited}}/g, readed_doc_list.includes(item.uid) ? 'visited' : '')
                                .replace(/{{my_content}}/g, (item.creator == userData.userId && userData.noticeRegPermitted == 'true') ? '' : 'none')
                                .replace(/{{creator}}/g, item.creator)
                            )
                        }
                    });
                }
            }else {
                console.error(`notice/v1/notices/all`, noticedata);
            }

            //사용자
            let filterd_users = Object.values(user_map).filter((user, idx) => {
                let cidno = '';
                try {
                    cidno = `${serverData.svcPrefixNo || ''}${user.cid_no}`;
                } catch (error) {
                    cidno = '';
                }
                return (user.dept_name || '').indexOf($('#inp_main_search').val()) > -1
                    || (user.name || '').indexOf($('#inp_main_search').val()) == 0
                    || (cidno != '' && cidno.indexOf($('#inp_main_search').val()) > -1)
                    || (user.mobile_no || '').indexOf($('#inp_main_search').val()) > -1
                    ;
            });

            if ($.isEmptyObject(filterd_users)) {
                $(`.sub_cont.main-search ul.person_list`).addClass('none');
                $(`.sub_cont.main-search .empty-person`).removeClass('none');
            } else {
                $(`.sub_cont.main-search ul.person_list`).empty();
                $(`.sub_cont.main-search ul.person_list`).removeClass('none');
                $(`.sub_cont.main-search .empty-person`).addClass('none');

                filterd_users.map((user, idx) => {
                    let cidno = '';
                    try {
                        cidno = `${serverData.svcPrefixNo || ''}${user.cid_no || ''}`;
                    } catch (error) {
                        cidno = '';
                    }

                    $('.sub_cont.main-search ul.person_list').append(
                        $('#search_wrap_ul_person').text()
                            .replace(/{{user_id}}/g, user.user_id)
                            .replace(/{{user_photo_path}}/g, `${server_host}${user.photo_path_url}`)
                            .replace(/{{user_name}}/g, user.name)
                            .replace(/{{user_class}}/g, user.clss)
                            .replace(/{{dept_name}}/g, user.dept_name)
                            .replace(/{{user_position}}/g, user.position == "" ? "" : (`(${user.position})`))
                            .replace(/{{cid_no}}/g, gformatter.tel(cidno))
                            .replace(/{{mobile_no}}/g, gformatter.tel(user.mobile_no))
                    )
                });
            }
        })
    });
    
    
//---------------- 메인화면 관련 끝

//-------------공통 시작

    //사용자의 즉시반영해야할 정보 반영
    requestAstro(`base/v1/user/${userData.userId}/${serverData.corp_code}`, {}, 'get')
    .then(r => {
        syncUserData({
            noticeRegPermitted : r.data.notice_reg_permitted?'true':'false'
        });
    });

    //사용자 상세정보레이어에 핀치줌 액션 바인딩
    bindPinchZoom($('.dim_bg.detail_info'));

    //홈으로
    $('.gohome').on('click', () => {
        location.href = 'main.html';
    });

    // foor btn 공지사항 or 카풀 등록 open
    $('.foot_btn .foot_btn_reg').on('click', (e) => {
        e.stopPropagation();
        initForBoardEdit();
        $('.foot_btn .foot_btn_back_history').data('target', 'list');
        let pagename = $('.boardSwiper a.tab.on').data('id');
        G.openEditNotice(pagename);
    });

    // foor btn 공지사항 수정 open
    $('.foot_btn .foot_btn_modify').on('click', (e) => {
        e.stopPropagation();
        $('.foot_btn .foot_btn_back_history').data('target', $('.view_cont').hasClass('none') ? 'list' : 'view');
        $('.foot_btn .foot_btn_back_history').data('uid', $('.view_cont').hasClass('none') ? '' : $(e.currentTarget).data('uid'));
        let pagename = $('.boardSwiper a.tab.on').data('id');
        G.openEditNotice(pagename, $(e.currentTarget).data('uid'));
    });

    // foor btn 수정 모드에서 돌아가기(공지사항에서만 사용함. ) -> 리스트 혹은 상세화면
    $('.foot_btn .foot_btn_back_history').on('click', (e) => {
        e.stopPropagation();
        if ($(e.currentTarget).data('target') == 'view') {
            $(`.sub_cont .board_list a[data-uid=${$(e.currentTarget).data('uid')}]`).trigger('click');
        } else {
            $('.foot_btn .foot_btn_to_list').trigger('click');
            $('.sub_cont').removeClass('none');
        }
    });

    //foot btn 저장
    $('.foot_btn .foot_btn_save').on('click', (e) => {

        let startDate = $("#term_pop_start_date").val(),
            endDate = $("#term_pop_end_date").val()
        startTime = '00:00',
            endTime = '23:59',
            noticeUid = $(e.currentTarget).data('notice_uid') || ''
        target_dept_codes = [],
            target_dept_names = []
            ;

        $('.for_board_edit .edit_trgt_dept span').each((idx, item) => {
            if ($(item).data('groupcode') != undefined && $(item).data('groupcode') != '' && $(item).text() != '') {
                target_dept_codes.push($(item).data('groupcode'));
                target_dept_names.push($(item).text());
            }
        });

        if ($('#edit_board_title').val() == '') {
            return popAlert("제목을 입력하세요.");
        }

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

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

            try {
                def_remains = parseInt(serverData.notice_def_remains);
            } catch (error) {
                def_remains = 0;
            }

            if (startDate == '' || endDate == '' || startDate > endDate) {
                return popAlert('공지 기간을<br/>정확히입력하세요.');
            }
        }

        if ($('#edit_board_cont').val().trim() == '') {
            return popAlert("내용을 입력하세요.");
        }

        // 데이터 객체 구성
        let params = {
            corp_code: serverData.corp_code,
            category: $('.for_board_edit input[name=edit_notice_type]:checked').val(),
            title: $('#edit_board_title').val(),
            contents: $('#edit_board_cont').val(),
            temp: 0,
            alarm_time: "",
            trgt: $('.for_board_edit input[name=edit_notice_target]:checked').val(),
            trgt_dept_codes: $("input[name='edit_notice_target']:checked").val() == 'DEPT' ? target_dept_codes.join(',') : "",
            trgt_dept_names: $("input[name='edit_notice_target']:checked").val() == 'DEPT' ? target_dept_names.join(',') : "",
        };

        if (startDate != '' && endDate != '') {
            params.start_time = new Date(`${startDate} ${startTime}`).toISOString();
            params.end_time = new Date(`${endDate} ${endTime}`).toISOString();
        }

        let pagename = $('.boardSwiper a.tab.on').data('id');
        if (noticeUid == '') {
            requestAstro(`notice/v1/notice`, params, 'post')
            .then(r => {
                if (r.code == '0000') {
                    popConfirm("등록되었습니다.<br/>알림을 발송하시겠습니까?", function () {
                        G.sendNoticeAlarm(r.data.uid, function () {
                            loadBoardData(pagename);
                            $('.view_cont').addClass('none');
                        }, true);
                    }, function () {
                        loadBoardData(pagename);
                        $('.view_cont').addClass('none');
                    });
                } else {
                    console.log(`${pagename=='notice'?'공지사항':'카풀'} 등록 실패 : `, r);
                    popAlert("오류가 발생했습니다.<br/>관리자에게 문의하세요.");
                }
            })
            .catch(error => {
                console.log(`${pagename=='notice'?'공지사항':'카풀'} 등록 실패 : `, error);
                popAlert("오류가 발생했습니다.<br/>관리자에게 문의하세요.");
            })
        } else {
            requestAstro(`notice/v1/notice/${noticeUid}`, params, 'put')
            .then(r => {
                if (r.code == '0000') {
                    popAlert("수정되었습니다.", function () {
                        loadBoardData('notice');
                        $('.view_cont').addClass('none');
                    });
                } else {
                    console.log(`${pagename=='notice'?'공지사항':'카풀'} 수정 실패 : `, r);
                    popAlert("오류가 발생했습니다.<br/>관리자에게 문의하세요.");
                }
            })
            .catch(error => {
                console.log(`${pagename=='notice'?'공지사항':'카풀'} 수정 실패 : `, error);
                popAlert("오류가 발생했습니다.<br/>관리자에게 문의하세요.");
            })
        }
    });

    //call_pop

    if($.isEmptyObject(userData.dn)){
        $('#call_pop_btn_clicktocall').removeClass('none');
    }else{
        switch (serverData.cust_func_code) {
            case '1':
                $('#call_pop_btn_callback').removeClass('none');
                break;
            case '2':
            case '3':
                $('#call_pop_btn_callthrough').removeClass('none');
                break;
            case '4':
            case '5':
            case '8':
                $('#call_pop_btn_callthrough, #call_pop_btn_clicktocall').removeClass('none');
                break;
            case '6':
                $('#call_pop_btn_callback, #call_pop_btn_callthrough').removeClass('none');
                break;
            case '7':
                $('#call_pop_btn_callback, #call_pop_btn_callthrough, #call_pop_btn_clicktocall').removeClass('none');
                break;
            case '9':
                $('#call_pop_btn_callback, #call_pop_btn_clicktocall').removeClass('none');
                break;
            default:
                break;
        }
    }


    $('#call_pop_btn_callback').on('click', function(e){
        e.preventDefault();
        let $checked = $('.call_pop input[name="num"]:checked');
        if ($checked.length == 0) return;

        callBack(`${$checked.val()}`, ($checked.data("type") || "기타"));

        $('.call_pop').addClass('none');
    });

    $("#call_pop_btn_callthrough").on("click", function (e) {
        e.preventDefault();
        let $checked = $('.call_pop input[name="num"]:checked');
        if ($checked.length == 0) return;

        callthrough(`${$checked.val()}`, ($checked.data("type") || "기타"));

        $('.call_pop').addClass('none');
    });

    $("#call_pop_btn_clicktocall").on("click", function (e) {
        e.preventDefault();
        let $checked = $('.call_pop input[name="num"]:checked');
        if ($checked.length == 0) return;

        clickToCall(`${$checked.val()}`, ($checked.data("type") || "기타"));

        $('.call_pop').addClass('none');
    });

    //비밀번호 변경 pop
    $('.password_pop .btn_ok').on('click', () => {
        let checkLength = (password) =>{
            return (password.length >= 4 && password.length <= 10)?true:false;
        }

        if($.trim($('#pop_password_inp_org_password').val()) == ''){
            return popAlert('기존 비밀번호를 입력하세요.');
        }

        if($.trim($('#pop_password_inp_new_password').val()) == ''){
            return popAlert('변경할 비밀번호를 입력하세요.');
        }

        if(!checkLength($.trim($('#pop_password_inp_new_password').val()))){
            return popAlert('비밀번호는 4 ~ 10자로 입력해주세요.');
        }

        if($.trim($('#pop_password_inp_new_password').val()) != $.trim($('#pop_password_inp_confirm_password').val())){
            return popAlert('동일한 비밀번호를 재입력해주세요.');
        }

        let params = {
            user_id : userData.userId,
            corp_code: serverData.corp_code,
            org_pwd: $('#pop_password_inp_org_password').val(),
            new_pwd: $('#pop_password_inp_new_password').val()
        }

        requestAstro(`base/v1/user/password`, params, 'PUT')
        .then(r =>{
            switch (r.code) {
                case '0000':
                    $('.password_pop').addClass('none');
                    popAlert("비밀번호가 변경 되었습니다.");
                    break;
                default:
                    throw new Error('비밀번호 변경 응답 비정상');
            }
            $('.password_pop').addClass('none');
        })
        .catch(e =>{
            popAlert("비밀번호 변경에 실패했습니다.");
        });
        ;
    });


    // $('#pop_detail_p_user_name').data('userid')
    $('#pop_detail_add_contact').on('click', () => {
        addContactWithImage($('#pop_detail_p_user_name').data('userid'));
    });

    //내선번호 없는 사용자용처리
    if($.isEmptyObject(userData?.dn)){
        $('.only-cid').addClass('none');
    }

//------------------공통 끝

//------------------공지 작성 관련 시작
    //공지사항 알림 대상
    $('.for_board_edit input[type=radio][name=edit_notice_target]').on('change', (e) => {
        if ($(e.currentTarget).val() == 'DEPT') {
            $('#btn_edit_open_dept, .edit_trgt_dept').removeClass('none');
        } else {
            $('#btn_edit_open_dept, .edit_trgt_dept').addClass('none');
        }
    });

    //공지기간
    $('#term_pop_start_date,#term_pop_end_date').datepicker();
    $('#term_pop_start_date,#term_pop_end_date').on('change', (e) => {
        if ($(e.currentTarget).val() != '' && $('#term_pop_limitless').is(':checked')) {
            $('#term_pop_limitless').prop('checked', false);
        }
    });

    //기간제한없음
    $("#term_pop_limitless").on('change', (e) => {
        if ($(e.currentTarget).is(':checked')) {
            $('#term_pop_start_date,#term_pop_end_date').val('');
            $('#edit_board_term').text(`~`);
        } else if ($('#term_pop_start_date').val() == '' && $('#term_pop_end_date').val() == '') {
            setNoticeTermDefault();
        }
    });

    $('#btn_edit_term_open').on('click', () => $('.term_pop').removeClass('none'));

    $('#term_pop_btn_ok').on('click', (e) => {
        $('#edit_board_term').text(`${$('#term_pop_start_date').val()} ~ ${$('#term_pop_end_date').val()}`);
        $('.term_pop').addClass('none');
    });

    // 부서선택 팝업 시작
    // G.bindNewTreeEvents($('.organ_pop ul.tree'));
    $('.organ_pop ul.tree').on('click.selectdept', 'label.group-label', (e) => {
        $('.organ_pop ul.tree li.selected').removeClass('selected');
        $(e.currentTarget).closest('li').addClass('selected');
    });

    $('#btn_edit_open_dept').on('click', (e) => {
        let $tree = $('.organ_pop ul.tree')
            , dept1_group = localStorage.getArray('dept1_group', 'list')
            , group_map = localStorage.getArray('group_map', 'list')
            ;
        ;
        if ($tree.find('>li').length == 0) {
            (dept1_group||[]).forEach((dept)=>{
                G.drawOrgTreeDept($tree, dept, false);
            });
        } else {
            $tree.find('.arrow.expanded').trigger('click');
        }

        $('.organ_pop .group-checkbox').remove();
        $('.organ_pop').removeClass('none');
    });

    $('#organ_pop_btn_ok').on('click', (e) => {
        let $li = $('.organ_pop .tree li.selected');

        $('.for_board_edit .edit_trgt_dept').append(
            $('#selected_notice_dept_template').text()
            .replace(/{{group-code}}/g, $li.data('deptcode'))
            .replace(/{{name}}/g, $li.find('>label>span').text())
        );
        $('.organ_pop').addClass('none');
    });

    // 부서선택 팝업 끝

    //선택된 부서 제거
    $('.for_board_edit').on('click', 'span.part>a:has(.bi-x)', (e) => {
        $(e.currentTarget).closest('span').remove();
    });

//------------------공지 작성 관련 끝

//------------------사용자 상세 팝업 관련 시작
    $('#pop_detail_btn_sms').on('click', function(e){
        e.preventDefault();
        if ($(this).hasClass('disabled')) return;

        let number = $(this).data('to');
        var num = gformatter.number(number);
        if (!num) return;
        var uri = 'sms:' + num;
        if (window.cordova && cordova.InAppBrowser) cordova.InAppBrowser.open(uri, '_system');
        else window.location.href = uri;
    });

    $('#pop_detail_btn_email').on('click', function(e){
        e.preventDefault();
        if ($(this).hasClass('disabled')) return;
        if(isIOS()){
            cordova.InAppBrowser.open(`mailto:${$(this).data('to')}`, '_system');
        }else{
            window.location.href = `mailto:${$(this).data('to')}`;
        }
    });

    $('#pop_detail_btn_cell, #pop_detail_btn_tell').on('click', function(e){
        e.preventDefault();
        if ($(this).hasClass('disabled')) return;

        var number = gformatter.number($(this).data('to') || "");
        if (!number) return;

        openCallPopupByNumbers($('#pop_detail_p_user_name').text(), [{
            number: number,
            display: gformatter.tel(number)
        }]);
    });

//------------------사용자 상세 팝업 관련 끝
});

let initMain = () => {
    G.openEditNotice = openEditNotice;

    $('.mainSwiper>.swiper-wrapper,.boardSwiper>.swiper-wrapper').empty();

    menu_info.forEach((item, index) => {
        // mainSwiper
        $('.mainSwiper>.swiper-wrapper').append(
            substituteVariables($('#template_main_swiper').text(), item)
            .replace(/{{none}}/g, '')
            .replace(/{{count}}/g, '0')
            .replace(/{{boardseq}}/g, board_seqs[item.id] || '')
        )

        //boardswiper
        $('.boardSwiper>.swiper-wrapper').append(
            substituteVariables($('#template_board_swiper').text(), item)
        )
    });

    //반드시 6배수이여야함 모자르는 수는 <div class="swiper-slide"></div> <!-- 메뉴가 없어도 빈레이어 유지 필수 -->
    // <!-- 
    // 	[중요] <div class="swiper-slide"></div>는 6의 배수 만큼 존재해야 함. (6개 이하인 경우 6개, 7~12개 경우 12개...)
    // -->
    if (menu_info.length % 6 != 0) {
        let count = menu_info.length % 6;
        for (let idx = 0; idx < (6 - count); idx++) {
            $('.mainSwiper>.swiper-wrapper').append(
                '<div class="swiper-slide"></div>'
            )
        }
    }

    new Swiper(".mainSwiper", {
        slidesPerView: 3,
        slidesPerGroup: 3,
        grid: {
            rows: 2,
            fill: "row",
        },
        spaceBetween: 8,
        pagination: {
            el: ".swiper-pagination",
            clickable: true,
        },
    });

    checkReadWholeContents();

    new Swiper(".boardSwiper", {
        slidesPerView: "auto",
        spaceBetween: 20,
        freeMode: true
    });

}

let loadHTML = (filepath, element) => {
    let df = $.Deferred();
    let xhr = new XMLHttpRequest();
    xhr.open('GET', filepath, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            // attachHTML(xhr.responseText ,element);
            element.html(xhr.responseText);
            df.resolve(true);
        }
    };
    xhr.send();
    return df.promise();
}

let loadNativeHTML = (filepath, element) => {
    let df = $.Deferred();

    window.resolveLocalFileSystemURL(`${cordova.file.documentsDirectory}www/${filepath}`, function (fileEntry) {
        fileEntry.file(function (file) {
            let reader = new FileReader();

            reader.onloadend = function () {
                //attachHTML(this.result, element);
                element.html(this.result);
                console.log(`${filepath} attached`);
                df.resolve(true);
            };

            reader.onerror = function (error) {
                console.error(`Failed to read file: ${error}`);
                df.reject(`Failed to read file: ${error}`);
            };

            reader.readAsText(file);
        }, function (error) {
            console.error(`Failed to get file: ${error}`);
            df.reject(`Failed to get file: ${error}`);
        });
    }, function (error) {
        console.error(`Failed to resolve file system URL: ${error}`);
        df.reject(`Failed to resolve file system URL: ${error}`);
    });

    return df.promise();
}

function getContainer(pageid) {
    if (pageid === 'dial') return $('.dial_cont');
    return $('.call_cont');
}

function showSection(section) {
    $('.sub_cont, .call_cont, .dial_cont, .view_cont').addClass('none');

    if (section === 'dial') {
        $('.dial_cont').removeClass('none');
    } else if (section === 'call') {
        $('.call_cont').removeClass('none');
    } else if (section === 'board') {
        $('.sub_cont').removeClass('none');
    }
}

let loadExternalHTML = async (pageid, url, element) => {
    const $target = element || getContainer(pageid);
    if (typeof device == 'undefined') {
        const response = await fetch(url);
        const htmlContent = await response.text();
        $target.html(htmlContent);
        console.log(`${url} loaded`);
    } else {
        if (device.platform === 'iOS') {
            await loadNativeHTML(url, $target);
        } else {
            await loadHTML(url, $target);
        }
    }
    await loadScriptAsync(pageid, $target);
};

let loadScriptAsync = async (pageid, element) => {
    let scripts = [];

    switch (pageid) {
        case "notice":
        case "carfull":
            scripts = [
                'summernote/summernote-lite.js',
                `content/js/content-${pageid}.js`
            ];
            break;
        default:
            // case "address":
            // case "history":
            // case "setting":
            // case "dial":
            scripts = [`content/js/content-${pageid}.js`];
            break;
    }

    for (const script of scripts) {
        await loadScript(script, element);
    }

    if(G.init && G.init[pageid]){
        G.init[pageid]();
    }
};

let loadScript = async (src) => {
    return new Promise((resolve, reject) => {
        if (document.querySelector(`script[src="${src}"]`)) {
            console.log(`[중복방지] 이미 로드된 스크립트: ${src}`);
            return resolve();
        }
        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = src;
        script.onload = () => {
            console.log(`${src} loaded successfully`);
            resolve();
        };
        script.onerror = () => {
            console.error(`Failed to load ${src}`);
            resolve();
        };
        document.head.appendChild(script);
    });
}

let loadBoardData = (boardname, append = false, options = {}) => {
    let df = $.Deferred();
    console.log('loadBoardData append ::', append);
    let boardlabel = "";
    try {
        boardlabel = menu_info.filter(item => item.id == boardname)[0].name;
    } catch (error) {
        boardlabel = "";
    }

    $('#header_board_name').text(boardlabel);
    let request_url = "", readed_contents = JSON.parse(localStorage.getItem('readed_contents') || '{}');

    let params = {
        board_seq: (board_seqs[boardname] || '')
        , offset: append ? $('.sub_cont ul.board_list>li').length : 0
    };


    switch (boardname) {
        case 'carfull':
            params.category = "C";
            params.temp = false;
            params.corp_code = serverData.corp_code;
            request_url = "notice/v1/notices/all";
            initFooter('notice_list');

            break;
        case 'notice':
            if (options.category) {
                params.category = options.category;
            } else {
                params.categories = options.categories || ["E", "N"];
            }
            params.temp = false;
            params.corp_code = serverData.corp_code;
            request_url = "notice/v1/notices/all";

            if (userData.noticeRegPermitted == 'true') {
                initFooter('notice_list');
            }
            break;
        default:
            request_url = `isboard/v1/search`;

            initFooter('hide');

            break;
    };

    if (!$.isEmptyObject(options)) {
        params = {
            ...params,
            ...options
        }
    }

    requestAstro(request_url, params, 'post')
    .then((response) => {
        let board_item_template = $('#board_item_template').text()
            , board_type = 'normal';
        ;

        if (boardname == 'carfull') {
            board_type = 'reply';
            board_item_template = $('#board_reply_template').text();
        } else if (boardname == 'notice') {
            board_type = 'notice';
            board_item_template = $('#board_notice_template').text();
        }

        if (response.code == '0000') {
            if (append == false) {
                $('.sub_cont ul.board_list').empty();
            }
            try {
                if ($.isEmptyObject(response.data)) {
                    if (append) return;
                    $('.sub_cont .empty').removeClass('none');
                    $('.sub_cont ul.board_list').addClass('none');
                } else {
                    $('.sub_cont .empty').addClass('none');
                    $('.sub_cont ul.board_list').removeClass('none');

                    response.data.map((item, idx) => {
                        let readed_doc_list = [];
                        if (board_type == 'normal') {
                            readed_doc_list = readed_contents[item.board_seq] || [];
                            $(`.sub_cont ul.board_list`).append(
                                board_item_template
                                .replace(/{{title}}/g, item.title)
                                .replace(/{{doc_seq}}/g, item.doc_seq)
                                .replace(/{{board_seq}}/g, item.board_seq)
                                .replace(/{{is_new}}/g, item.is_new == 1 ? '' : 'none')
                                .replace(/{{user_name}}/g, item.user_name)
                                .replace(/{{dept_name}}/g, item.dept_name)
                                .replace(/{{update_date}}/g, item.update_date)
                                .replace(/{{is_new}}/g, item.is_new == 1 ? '' : 'none')
                                .replace(/{{visited}}/g, readed_doc_list.includes(item.doc_seq) ? 'visited' : '')

                            );
                        } else if (board_type == 'notice') {
                            readed_doc_list = readed_contents[item.category] || [];
                            $(`.sub_cont ul.board_list`).append(
                                board_item_template
                                .replace(/{{uid}}/g, item.uid)
                                .replace(/{{category}}/g, item.category)
                                .replace(/{{title}}/g, item.title)
                                .replace(/{{name}}/g, (item.creator_name || ''))
                                .replace(/{{dept_name}}/g, (item.dept_name || '') == '' ? '' : (' / ' + item.dept_name))
                                .replace(/{{date}}/g, ' / ' + new Date(item.update_time).toLocaleString())
                                .replace(/{{visited}}/g, readed_doc_list.includes(item.uid) ? 'visited' : '')
                                .replace(/{{my_content}}/g, (item.creator == userData.userId && userData.noticeRegPermitted == 'true') ? '' : 'none')
                                .replace(/{{creator}}/g, item.creator)
                            );
                        } else {
                            readed_doc_list = readed_contents[item.category] || [];
                            $(`.sub_cont ul.board_list`).append(
                                board_item_template
                                .replace(/{{uid}}/g, item.uid)
                                .replace(/{{category}}/g, item.category)
                                .replace(/{{title}}/g, item.title)
                                .replace(/{{name}}/g, item.creator_name)
                                .replace(/{{date}}/g, new Date(item.update_time).toLocaleString())
                                .replace(/{{show_reply}}/g, (item.reply_count || 0) > 0 ? '' : 'none')
                                .replace(/{{reply_count}}/g, (item.reply_count || 0))
                                .replace(/{{visited}}/g, readed_doc_list.includes(item.uid) ? 'visited' : '')
                                .replace(/{{my_content}}/g, (item.creator == userData.userId && userData.noticeRegPermitted == 'true') ? '' : 'none')
                                .replace(/{{creator}}/g, item.creator)
                            );
                        }
                    });
                }
            } catch (error) {
                console.error('loadBoardData', boardname, error.stack);
            }

        } else {
            console.error('loadBoardData', boardname, response.message||'');
        }
        df.resolve(response);
    })
    .catch((f) => {
        console.error(f);
        df.reject(f);
    });

    return df.promise();
};

let checkReadWholeContents = (callback) => {
    $(`.main_cont .swiper-slide a.item span.num`).addClass('none');

    let board_infos = {
        '-1': 'article',
        'carfull': 1
    }

    $.when(
        new Promise((resolve, reject) => {
            requestAstro('isboard/v1/allseq', {}, 'get')
                .then((r) => resolve(r))
                .catch(f => resolve(f))
        })
        , new Promise((resolve, reject) => {
            requestAstro('notice/v1/notices/alluid', { categories: ['C', 'N', 'E'] }, 'post')
                .then((r) => resolve(r))
                .catch((f) => resolve(f))
        })
    )
    .done((boardresponse, noticeresponse) => {
        readed_contents = localStorage.getArray('readed_contents');

        if (boardresponse.code == '0000') {
            //안하는게 나을지도..
            // $('.main_cont .swiper-slide>a.item>span.num').addClass('none');


            for (let board_seq in boardresponse.data) {
                if (board_seq == -1) {
                    continue;
                }

                let r_content_list = boardresponse.data[board_seq];

                //로컬에 저장된 읽은 게시물아이디(readed_contents)중에 새로 조회해온 게시물아이디에서 제외된 아이디는 제거함
                readed_contents[board_seq] = (readed_contents[board_seq] || []).filter(docseq => r_content_list.includes(docseq));

                let readed_list = readed_contents[board_seq] || [];

                let new_content_cnt = 0;
                try {
                    new_content_cnt = r_content_list.length - readed_list.length;
                    if (new_content_cnt < 0) {
                        new_content_cnt = 0
                    }
                } catch (error) {
                    new_content_cnt = 0;
                }

                $(`.main_cont .mainSwiper a[data-boardseq=${board_seq}] span.num`).text(`${new_content_cnt}`);
                if (new_content_cnt > 0) {
                    $(`.main_cont .mainSwiper a[data-boardseq=${board_seq}] span.num`).removeClass('none');
                } else {
                    $(`.main_cont .mainSwiper a[data-boardseq=${board_seq}] span.num`).addClass('none');
                }
            }

            // 신규 게시물 카운트는 마지막에..신규게시물은 별도로 readed_contents를 관리하지않음 모든 게시판의 readed_contents를 체크함
            let r_content_list = boardresponse.data[-1];
            for (let board_seq in readed_contents) {
                let readed_list = readed_contents[board_seq] || [];
                r_content_list = r_content_list.filter(x => !readed_list.includes(x));
            }

            let new_content_cnt = 0;
            try {
                new_content_cnt = r_content_list.length;
            } catch (error) {
                new_content_cnt = 0;
            }

            $(`.main_cont .mainSwiper a[data-boardseq=new] span.num`).text(`${new_content_cnt}`);
            if (new_content_cnt > 0) {
                $(`.main_cont .mainSwiper a[data-boardseq=new] span.num`).removeClass('none');
            } else {
                $(`.main_cont .mainSwiper a[data-boardseq=new] span.num`).addClass('none');
            }
        } else {
            console.log('ERROR isboard/v1/allseq', boardresponse, 'notice/v1/notices/alluid', noticeresponse);
        }

        if (noticeresponse.code == '0000') {
            let notice_new_content_cnt = 0,
                carfull_new_content_cnt = 0
                ;

            for (let notice_category in noticeresponse.data) {

                let r_content_list = noticeresponse.data[notice_category];

                //로컬에 저장된 읽은 게시물아이디(readed_contents)중에 새로 조회해온 게시물아이디에서 제외된 아이디는 제거함
                readed_contents[notice_category] = (readed_contents[notice_category] || []).filter(x => r_content_list.includes(x));

                let readed_list = readed_contents[notice_category] || [];

                switch (notice_category) {
                    case 'E':
                    case 'N':
                        try {
                            notice_new_content_cnt += r_content_list.length - readed_list.length;
                            if (notice_new_content_cnt < 0) {
                                notice_new_content_cnt = 0
                            }
                        } catch (error) {
                            notice_new_content_cnt = 0;
                        }

                        break;
                    case 'C':
                        try {
                            carfull_new_content_cnt = r_content_list.length - readed_list.length;
                            if (carfull_new_content_cnt < 0) {
                                carfull_new_content_cnt = 0
                            }
                        } catch (error) {
                            carfull_new_content_cnt = 0;
                        }

                        break;
                    default:
                        break;
                }

                $(`.main_cont .swiper-slide a[data-id=${notice_category == 'C' ? 'carfull' : 'notice'}] span.num`).text(`${notice_category == 'C' ? carfull_new_content_cnt : notice_new_content_cnt}`);
                if ((notice_category == 'C' ? carfull_new_content_cnt : notice_new_content_cnt) > 0) {
                    $(`.main_cont .swiper-slide a[data-id=${notice_category == 'C' ? 'carfull' : 'notice'}] span.num`).removeClass('none');
                } else {
                    $(`.main_cont .swiper-slide a[data-id=${notice_category == 'C' ? 'carfull' : 'notice'}] span.num`).addClass('none');
                }
            }
        }

        if (callback) {
            callback();
        }
    });
}

let initMainArticle = () => {
    if(typeof use_main_page != 'undefined' && use_main_page == false){
        console.log('use_main_page is false do not initMainArticle');
        return;
    }
    readed_contents = localStorage.getArray('readed_contents');
    requestAstro(`isboard/v1/newboardcontent`, {}, 'get')
    .then(r => {
        if (r.code == '0000') {
            $(`.main_cont .article_list ul`).empty();
            try {
                r.data.map((item, idx) => {
                    if (idx >= 5) return;
                    let readed_doc_list = readed_contents[item.board_seq] || [];
                    $(`.main_cont .article_list ul`).append(
                        $('#main_article_list_template').text()
                        .replace(/{{title}}/g, item.title)
                        .replace(/{{doc_seq}}/g, item.doc_seq)
                        .replace(/{{board_seq}}/g, item.board_seq)
                        .replace(/{{update_date}}/g, item.update_date)
                        .replace(/{{visited}}/g, readed_doc_list.includes(item.doc_seq) ? '' : '<span class="new"></span>')
                        .replace(/{{prev_board_seq}}/g, idx == 0 ? 'not' : r.data[idx - 1].board_seq)
                        .replace(/{{prev_doc_seq}}/g, idx == 0 ? 'not' : (r.data[idx - 1].doc_seq))
                        .replace(/{{next_board_seq}}/g, idx >= (r.datalength - 1) ? 'not' : r.data[idx + 1].board_seq)
                        .replace(/{{next_doc_seq}}/g, idx >= (r.datalength - 1) ? 'not' : r.data[idx + 1].doc_seq)
                    )
                });
            } catch (error) {
                console.error(`isboard/v1/newboardcontent error`, error);
            }
        } else {
            console.error(`isboard/v1/newboardcontent error`, r);
        }
    })
    ;
}

let initFooter = (type = 'hide') => {
    console.log('init footer type :: ', type);
    /**
     * foot_btn
     * foot_div_first
     *      comments_open
     * foot_div_second
     *      foot_btn_modify
     */

    //모든 버튼을 안보이게 한후 각 타입별로 필요한것만 보이게함. 아 이거 어렵네.
    $('.foot_div_first>a, .foot_div_second>a').addClass('none');

    switch (type) {
        case 'hide':
            $('div.foot_btn').addClass('none');
            break;
        case 'notice_list':
            $('.foot_btn, .foot_div_first, .foot_div_second').removeClass('none');
            if (userData.noticeRegPermitted == 'true') {
                $('.foot_btn_reg').removeClass('none')
            }
            break;
        case 'common_view':
            // btn_prev_content, btn_next_content 는 게시물 클릭시 별도로 제어함
            $('.foot_btn, .foot_div_first, .foot_div_second').removeClass('none');
            $('.foot_btn_to_list').removeClass('none');
            break;
        case 'reply_view':
            // btn_prev_content, btn_next_content 는 게시물 클릭시 별도로 제어함
            $('.foot_btn, .foot_div_first, .foot_div_second').removeClass('none');
            $('.comments_open, .foot_btn_to_list').removeClass('none');
            break;
        case 'notice_view':
            // btn_prev_content, btn_next_content 는 게시물 클릭시 별도로 제어함
            $('.foot_btn, .foot_div_first, .foot_div_second').removeClass('none');
            $('.foot_btn_to_list').removeClass('none');
            if (userData.noticeRegPermitted == 'true' && $('.view_cont .for_board_view').data('creator') == userData.userId) {
                $('.foot_btn_modify').removeClass('none')
            }
            break;
        case 'notice_edit':
            $('.foot_btn, .foot_div_first, .foot_div_second').removeClass('none');
            $('.foot_btn_back_history, .foot_btn_save').removeClass('none');
            break;
        
        default:
            break;
    }
}

let initForBoardEdit = () => {
    $('.for_board_edit input[type=text]').val('');
    $('#edit_board_term').text('');
    $('#term_pop_limitless').prop('checked', false).trigger('change');
    $('.for_board_edit input[type=radio][name=edit_notice_type]:eq(0), .for_board_edit input[type=radio][name=edit_notice_target]:eq(0)').trigger('click');
    $('.for_board_edit .edit_trgt_dept').empty().addClass('none');
    $('#edit_board_cont').summernote('reset');
}

let setNoticeTermDefault = () => {
    //공지사항 기본 유지일수 설정
    let def_remains = 0;

    try {
        def_remains = parseInt(serverData.notice_def_remains);
    } catch (error) {
        def_remains = 0;
    }

    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; }

    $('#term_pop_start_date').val(y + '.' + M + '.' + d);

    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; }

    $('#term_pop_end_date').val(y + '.' + M + '.' + d);

    $('#edit_board_term').text(`${$('#term_pop_start_date').val()} ~ ${$('#term_pop_end_date').val()}`);
}

let openEditNotice = (pagename = 'notice', notice_id) => {

    function drawEditNotice(data){

        $('.view_cont .for_board_edit').removeClass('none');
        $('.view_cont .for_board_view, .sub_cont').addClass('none');
        $('.foot_btn .foot_btn_save').data("notice_uid", notice_id||'');
        $('.for_board_edit .edit_trgt_dept').empty();

        $('#edit_board_title').val(data?.title||'');

        if(data){
            let start_time = data.start_time?gformatter.date(new Date(data.start_time),'y.M.d'):'',
                end_time = data.end_time?gformatter.date(new Date(data.end_time),'y.M.d'):''
            ;
            $('#edit_board_term').text(`${start_time} ~ ${end_time}`);
            $('#term_pop_start_date').val(`${start_time} `)
            $('#term_pop_end_date').val(`${end_time} `)
            
            if((data.start_time == undefined || data.start_time == '') && (data.end_time == undefined || data.  end_time == '')){
                $('#term_pop_limitless').prop('checked', true).trigger('change');
            }
        }else{
            setNoticeTermDefault()
        }

        
        if( pagename == 'carfull'){
            $(`div.board_edit input[type=radio][name=edit_notice_type][value=${data?.category||'C'}]`).prop('checked', true);
            $('#dl_board_edit_category').addClass('none');

            $('#dl_board_edit_trgt').addClass('none');
            $(`div.board_edit input[type=radio][name=edit_notice_target][value=ALL]`).prop('checked', true).trigger('change');
        }else{
            $(`div.board_edit input[type=radio][name=edit_notice_type][value=${data?.category||'N'}]`).prop('checked', true);
            $('#dl_board_edit_category').removeClass('none');

            $('#dl_board_edit_trgt').removeClass('none');
            $(`div.board_edit input[type=radio][name=edit_notice_target][value=${data?.trgt||'ALL'}]`).prop('checked', true).trigger('change');
    
            if(data?.trgt == 'DEPT'){
                let group_codes = (data.trgt_dept_codes||'').split(','), names = (data.trgt_dept_names||'').split(',');
                group_codes.forEach((groupcode, idx) => {
                    $('.for_board_edit .edit_trgt_dept').append(
                        $('#selected_notice_dept_template').text()
                        .replace(/{{group-code}}/g, groupcode)   
                        .replace(/{{name}}/g, names[idx]||'알수없음')   
                    );
                });
            }
        }
        
        $('#edit_board_cont').empty();
        $("#edit_board_cont").summernote({minHeight: 200}).summernote('code', data?.contents||'');

        initFooter('notice_edit');
        $('.view_cont').removeClass('none');
    }

    if(notice_id){
        requestAstro(`notice/v1/notice/${notice_id}`, {}, 'get')
        .then(r => {
            console.log(`notice/v1/notice/${notice_id} response code :: `, r.code);
            
            if(r.code == '0000'){
                drawEditNotice(r.data);
            }
        });
    }else{
        drawEditNotice(pagename);
    }
}

let openCallPopupByNumbers = (contactName, phoneNumbers) => {

    var $callPop = $('.call_pop');

    var $numberList = $callPop.find("#call_num_list").empty();

    $callPop.find(".call_title").text(contactName || "");
    $callPop.removeClass("none");

    if (!Array.isArray(phoneNumbers) || phoneNumbers.length === 0) {
        $numberList.append('<li><span>번호 없음</span></li>');
        $callPop.find("#btn_callthrough, #btn_clicktocall").prop("disabled", true);
    } else {
        $callPop.find("#btn_callthrough, #btn_clicktocall").prop("disabled", false);
        phoneNumbers.forEach(function (phoneInfo, index) {
            var radioId = "num_radio_call_pop_" + index;
            var displayNumber = phoneInfo.display || phoneInfo.number || "";
            // var numberType = phoneInfo.type || "기타";
            var numberType = '';

            var $li = $(`
                <li>
                    <input type="radio" name="num" id="${radioId}">
                    <label for="${radioId}"></label>
                </li>
            `);

            $li.find("input")
                .val(gformatter.number(phoneInfo.number || ""))
                .attr("data-type", numberType)
                .attr("data-id", phoneInfo.id || "");

            if (index === 0) $li.find("input").prop("checked", true);
            $li.find("label").text(displayNumber + (numberType ? " (" + numberType + ")" : ""));
            $numberList.append($li);
        });
    }
    // $callPop.data("callId", context.callId);
    // $callPop.data("dialPrefix", context.dialPrefix);
    $callPop.removeClass('none');
}

let openUserDetail = (user) => {

    if(typeof user != 'object'){
        user = user_map[user];
    }

    $('#pop_detail_p_user_position, #pop_detail_p_user_name, #pop_detail_dd_user_dept, #pop_detail_dd_user_class, #pop_detail_dd_user_position, #pop_detail_span_user_tel, #pop_detail_span_user_email, #pop_detail_span_user_mobile, #pop_detail_dd_user_desc').empty();

    $('#pop_detail_div_user_photo').css('background-image',`url('${server_host}${user.photo_path_url}'),url('images/thumb.png')`);
    $('#pop_detail_p_user_position').text(user.position);
    $('#pop_detail_p_user_name').data('userid', user.user_id);
    $('#pop_detail_p_user_name').text(user.name);
    $('#pop_detail_p_user_type').text(user.type);
    let group_name_arr = user.full_group_names?.split("@@") ?? [];
    let group_name_html = "";
    group_name_arr.map( group_name => group_name_html+=`<span class="part">${group_name}</span>`);
    $('#pop_detail_dd_user_dept').html(group_name_html);
    $('#pop_detail_dd_user_class').text(user.clss);
    $('#pop_detail_dd_user_position').text(user.position);

    let cidno = `${user.cid_no||''}`;

    $('#pop_detail_span_user_tel').text(gformatter.tel(cidno));
    if(cidno != undefined && cidno != ''){
        $('#pop_detail_btn_tell').data('to', `${cidno}`).removeClass('disabled');
    }else{
        $('#pop_detail_btn_tell').addClass('disabled');
    }

    $('#pop_detail_span_user_email').text(user.email);
    if(user.email != undefined && user.email != ''){
        $('#pop_detail_btn_email').data('to', `${user.email}`).removeClass('disabled');
    }else{
        $('#pop_detail_btn_email').addClass('disabled');
    }

    $('#pop_detail_span_user_mobile').text(gformatter.tel(user.mobile_no));
    if(user.mobile_no != undefined && user.mobile_no != ''){
        $('#pop_detail_btn_cell, #pop_detail_btn_sms').data('to', `${user.mobile_no.replace(/[^\d]/g,'')}`).removeClass('disabled');
    }else{
        $('#pop_detail_btn_cell, #pop_detail_btn_sms').addClass('disabled');
    }

    let desc = user.description||'-';
    var lines = desc.split(/\r?\n|;|•/);
    for (var i = 0; i < lines.length; i++) {
        var t = gformatter.string(lines[i]).trim();
        if (t) $('<p>').text(t.charAt(0) === '-' ? t : '- ' + t).appendTo($('#pop_detail_dd_user_desc'));
    }

    $('#pop_detail_dd_user_extra1').text(user.extra1);

    if (typeof applySettings === 'function') {
        applySettings();
    }

    $('.dim_bg.detail_info').removeClass('none');
}

let createAddress = () => {
    // 로컬 읽기
    try { newContact = window.localStorage.getArray("contact") || []; } catch (e) { newContact = []; }
    try { favoriteContact = window.localStorage.getArray("contact_favorite") || []; } catch (e) { favoriteContact = []; }

    if (window.device != undefined) {
        navigator.contactsPhoneNumbers.list(function (contacts) {
            // 전처리
            for (var i = 0; i < contacts.length; i++) {
                var c = contacts[i];

                // 이름 없으면 제거
                if (!c || !c.displayName) { contacts.splice(i, 1); i--; continue; }

                // iOS 이름 합치기
                try {
                    if ((device.platform || '').toLowerCase() === 'ios') {
                        c.displayName = (c.lastName || '') + (c.firstName || '') || c.displayName;
                    }
                } catch (e) { }

                // 초성
                c.nameCho = getCho(c.displayName);

                // 썸네일 기본
                if (!c.thumbnail) c.thumbnail = setThumbImage();

                // 번호 정리
                if (Array.isArray(c.phoneNumbers)) {
                    for (var j = 0; j < c.phoneNumbers.length; j++) {
                        var p = c.phoneNumbers[j] || {};
                        var raw = p.normalizedNumber || p.number || "";
                        var clean = cleanPhoneNumber(raw);
                        c.phoneNumbers[j].normalizedNumber = clean;
                        c.phoneNumbers[j].number = getKoreanNumber(clean);
                        if (!c.phoneNumbers[j].type) c.phoneNumbers[j].type = "기타";
                    }
                } else {
                    c.phoneNumbers = [];
                }
            }

            // 정렬
            contacts.sort(function (a, b) {
                var A = $.trim(a.displayName), B = $.trim(b.displayName);
                if (isKorean(A)) return isKorean(B) ? (A < B ? -1 : 1) : -1;
                if (isAlphabet(A)) return isKorean(B) ? 1 : (isAlphabet(B) ? (A < B ? -1 : 1) : -1);
                if (isNumber(A)) return (isKorean(B) || isAlphabet(B)) ? 1 : (isNumber(B) ? (A < B ? -1 : 1) : -1);
                return (!isNumber(B) && !isAlphabet(B) && !isKorean(B)) ? (A < B ? -1 : 1) : 1;
            });

            // 저장
            newContact = contacts;
            window.localStorage.setArray("contact", newContact);

            if (!Array.isArray(favoriteContact)) {
                favoriteContact = [];
                window.localStorage.setArray("contact_favorite", favoriteContact);
            }

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

let addCallHistory = (number, type) => {
    console.log('addCallHistory ::', number, '::', type);

    call_history_list.unshift({
        number: nomalizeNumber($.trim(number)),
        date_time: gformatter.date(new Date(), 'y-M-d h:m:s')
    });
    writeFile('call_history.json', JSON.stringify({ "callHistory": call_history_list }), (r) => {
        console.log('success write call_history.json');
    });
}

// 콜쓰루
let callthrough = (phoneNumber, type) => {
    const toNumber = getTelephoneNumber(phoneNumber);
    const params = {
        url: `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/callthrough?from=${serverData.call_thru_prefix}${userData.mobileNumber}&to=${toNumber}`,
        token: window.localStorage.getArray("userData").token
    };
    console.log('callthrough :: ', params);

    requestAstro(`ipecscm/v1/rest/callrequest`, params, 'post')
    .then(response => {
        if (response.data.error.message === "OK") {
            addCallHistory(phoneNumber, type);
            if ((window.device?.platform || '').toLowerCase() === 'android') {
                window.plugins.gntel.setCallToNumber(phoneNumber);
                cordova.plugins.phonedialer.call(
                    userData.prefixEx,
                    function (success) {
                        console.log('callthrough', 'Dialing succee  ded');
                    },
                    function (err) {
                        if (err === "empty") console.log("Unknown phone number");
                        else console.error("Dialer Error: " + err);
                    }
                );
            } else {
                cordova.InAppBrowser.open(`tel:${userData.prefixEx}`, "_system");
            }
        } else {
            console.error("Callthrough Error: " + response.data.error.message);
            popAlert(response.data.error.message);
        }
    })
}

// 클릭투콜
let clickToCall = (phoneNumber, type) => {
    console.log('clicktoCall :: ', clickToCall);
    //기타 번호가 세팅되어있을 경우에는 기타번호에 저장된 번호로 전화함.. 이거 언제까지할거지.;; 서비스팀 요청사항임.
    if (phoneNumber.length == serverData.cidLength) {
        let etcNo = null;
        if (serverData.pbxType === 'CM') {
            for (var key in user_map) {
                var u = user_map[key];
                if (u.cid_no === phoneNumber) {
                    if (u.etc_no) etcNo = u.etc_no;
                    break;
                }
            }
        }
        phoneNumber = etcNo ? etcNo : serverData.svcPrefixNo + phoneNumber;
    }

    if ((window.device?.platform || '').toLowerCase() === 'android') {
        cordova.plugins.phonedialer.call(
            phoneNumber,
            function () { addCallHistory(phoneNumber, type); },
            function (err) {
                if (err === "empty") console.log("Unknown phone number");
                else console.error("Dialer Error: " + err);
            }
        );
    } else {
        cordova.InAppBrowser.open(`tel:${phoneNumber}`, "_system");
        try { addCallHistory(phoneNumber, type); } catch (e) { console.warn(e); }
    }
}

// 콜백
let callBack = (phoneNumber, type) => {
    const toNumber = getTelephoneNumber(phoneNumber);
    const fromNumber = getFromNumberForCallBack();//userData.mobileNumber;
    if ($.isEmptyObject(fromNumber)) return;

    const params = {
        url: `https://${serverData.cust_con_pbx_ip}:${serverData.cust_con_port}/ipxapi/v1/users/${userData.id}/callback?from=${fromNumber}&to=${toNumber}`,
        token: window.localStorage.getArray("userData").token
    };

    requestAstro(`ipecscm/v1/rest/callrequest`, params, 'post')
    .then(response => {
        if (response.data.error.message === "OK") {
            console.log("내 휴대폰으로 발신 요청 중입니다. 잠시만 기다려주세요");
            addCallHistory(phoneNumber, type);
        } else {
            console.error("Callback Error: " + response.data.error.message);
            popAlert(response.data.error.message);
        }     
    })
}

//callback api호출할때는 호출코드 사용여부 판단해서 호출코드 붙일지 여부를 판단해야함.callthrough는 callthough prefix만 고려하면됨
let getFromNumberForCallBack = (telno) => {
    var accCodeUsed = serverData.accCodeUsed;
    var accCode = serverData.accCode;
    var digitCount = serverData.digitCount;
    var mobileNumber = userData.mobileNumber;
    digitCount = parseInt(digitCount);
    if(!$.isEmptyObject(mobileNumber)){
        if(mobileNumber.length > digitCount){
            if(accCodeUsed == "Y"){
                mobileNumber = accCode + mobileNumber;
            }
        }

        mobileNumber = encodeURIComponent( mobileNumber );
        return mobileNumber;
    }else{
        return popAlert("사용자의 휴대폰번호 정보가 없습니다.");
    }
}

let getTelephoneNumber = (telephoneNumber) => {
    telephoneNumber = telephoneNumber.replace('+82', '0');
    var accCodeUsed = serverData.accCodeUsed;
    var accCode = serverData.accCode;
    var digitCount = serverData.digitCount;
    digitCount = parseInt(digitCount);
    if (telephoneNumber.length > digitCount) {
        if (accCodeUsed == "Y") {
            telephoneNumber = accCode + telephoneNumber;
        }
    }

    telephoneNumber = encodeURIComponent(telephoneNumber);
    return telephoneNumber;
}

// native에서  setSchemeData를 호출하면 getSchemeData를 실행해서 localStorage에 저장함.
let setSchemeData = () => {
    getSchemeData();
}

let getSchemeData = () =>{
    if(ready_to_dial == false || is_device_ready == false) return;
    try{
        cordova.exec(
            (result) => {
                console.log('getSchemeData plugin called', result);
                if(result != null && result != ''){
                    localStorage.setItem('schemeData', result);
                    $('.mcaller_menu a.menu[data-id=dial]').trigger('click.menuNav');
                }
            }, null, "GntelPlugin", "getSchemeData", []);
    }catch{

    }
}

//저장된로그내용을 서버로전송
let sendGLog = () => {
    window.plugins.gntel.getGLog(function(log) {
        let data = {
            "title": `log_${userData.userId}_${gformatter.date(new Date(),'y-M-d h:m:s')}`
            ,"log":  log
        };

        requestAstro(`launcher/v1/clientlog/client/send`, data, 'post')
        .then(r =>{
            popAlert("전송성공");
        })
        .catch(f => {
            popAlert("전송실패", f.message||'');
        })
    }, function(error) {
        console.error(error);
    })
}

let on_backbutton_main = function () {
    if (exitCheck) {
        navigator.app.exitApp();
    } else {
        if(typeof use_main_page == 'undefined' || use_main_page == true){
            if($('.dim_bg').is(':visible')) {
                $('.popup_close:not(.fade_action), .pop_btn_close').trigger('click');
            }else if($('.dial_cont, .call_cont').is(':visible')){
                $('.gohome').trigger('click');
            }else if($('.sub_cont').is(':visible')){
                if($('.foot_btn_to_list').is(':visible')){
                    $('.foot_btn_to_list').trigger('click');
                }else if($('.foot_btn_back_history').is(':visible')){
                    $('.foot_btn_back_history').trigger('click');
                }else{
                    $('.gohome').trigger('click');
                }
            }else{
                exitCheck = true;
                setTimeout(() => {
                    exitCheck = false;
                }, 2000);
                toast("한번 더 누를 시 앱이 종료됩니다.");
            }
        }else{
            if($('.dim_bg').is(':visible')) {
                $('.popup_close:not(.fade_action), .pop_btn_close').trigger('click');
            }else if(!$('.dial_cont').is(':visible')){
                $('.mcaller_menu a.menu[data-id="dial"]').trigger('click');
            }else{
                exitCheck = true;
                setTimeout(() => {
                    exitCheck = false;
                }, 2000);
                toast("한번 더 누를 시 앱이 종료됩니다.");
            }
        }
    }
};

const serverDataUpdate = () => {
    requestAstro(`mdial/v1/corp/${serverData.corp_code}`,{},'get')
    .then(response => {
        if(response.code == '0000'){

            profileSetting(response.data);

            syncServerData({
                ...response.data,
                companyId: `${serverData.companyId}`,
                companyPw: `${serverData.companyPw}`
            })
            try {
                window.plugins.gntel.putPreferences([
                    'forward_call_mention', response.data.forward_call_mention,
                ], (r) => {console.log('success put putPreferences forward_call_mention', r);});
            } catch (error) {
                console.warn(error);
            }


        } else {
            console.log('requestAstro fail')
        }
    })
    .catch(error => {
        console.error(error);
    })
}

let profileSetting = (data) => {
    cordova.exec((r)=>{
        let isDefaultNameCard = localStorage.getItem("isDefaultNameCard");
        let default_profile = data.default_profile.replace("www/", "");

        if(isDefaultNameCard == null) {
            localStorage.setItem("isDefaultNameCard", "Y");
            isDefaultNameCard = "Y";
        }

        let json = null;
        try{
            json = JSON.parse(r);
        }catch(e){
            json = r;
        }
        console.log('profileSetting - getNamecardSettings', json);

        if(json.namecard_default == undefined || json.namecard_default == '' || json.namecard_default == 'www/'){
            let namecard_dir_path ='www/namecard';
            localStorage.setItem("isDefaultNameCard", "Y");
            cordova.exec((filelist)=>{

                let list = filelist.split(',');
                let nameCard = list.find(x => x === default_profile) || list[0]

                json = {
                    is_show : true,
                    namecard_default : `${namecard_dir_path.replace('www/','')}/${nameCard}`
                }
                cordova.exec((r)=>{
                    console.log('success profileSetting undefined setNamecardSettings', JSON.stringify(json));
                }, (error) => {
                    console.error(error);
                }, "GntelPlugin", "setNamecardSettings", ['www/', JSON.stringify(json)]);

            }, (f) =>{
                console.error('can not exec getNameCardsList', f );
            }, "GntelPlugin", "getNameCardsList", [namecard_dir_path]);
        }else if(data.profile_used != true && json.is_show == true){
            localStorage.setItem("isDefaultNameCard", "Y");
            json = {
                is_show : false,
                namecard_default : ""
            }
            cordova.exec((r)=>{
                console.log('success profileSetting profile_used setNamecardSettings', JSON.stringify(json));
            }, (error) => {
                console.error(error);
            }, "GntelPlugin", "setNamecardSettings", ['www/', JSON.stringify(json)]);
        } else if(isDefaultNameCard == "Y") {
            let namecard_dir_path ='www/namecard';
            cordova.exec((filelist)=>{

                let list = filelist.split(',');
                let nameCard = list.find(x => x === default_profile) || list[0]

                json = {
                    is_show: json.is_show,
                    namecard_default : `${namecard_dir_path.replace('www/','')}/${nameCard}`
                }

                cordova.exec((r)=>{
                    console.log('success profileSetting isDefaultNameCard setNamecardSettings', JSON.stringify(json));
                }, (error) => {
                    console.error(error);
                }, "GntelPlugin", "setNamecardSettings", ['www/', JSON.stringify(json)]);

            }, (f) =>{
                console.error('can not exec getNameCardsList', f );
            }, "GntelPlugin", "getNameCardsList", [namecard_dir_path]);
        }
    }, (f)=>{
        console.error('can not exec getNamecardSettings', f )
    }, "GntelPlugin", "getNamecardSettings", null);
}

//앱 사진 탐색
function takePhoto() {
    const options = {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: Camera.PictureSourceType.PHOTOLIBRARY, // CAMERA
        encodingType: Camera.EncodingType.JPEG,
        mediaType: Camera.MediaType.PICTURE,
        correctOrientation: true
    };

    navigator.camera.getPicture(onSuccessTakePhoto, onFailTakePhoto, options);
}

function onSuccessTakePhoto(imageURI) {
    console.log("onSuccessTakePhoto :: 사진 경로: " + imageURI);
    // 여기서 업로드 함수 호출
    // uploadPhoto(imageURI);
}

function onFailTakePhoto(message) {
    alert('onFailTakePhoto :: 실패: ' + message);
}

//파일 탐색기 열기
function openFilePicker() {
    let roomId = $('.chat_room.selected').data('roomid') ?? (typeof chatRoom !== 'undefined' ? chatRoom.roomId : null);
    if (!roomId) return console.error("roomId를 찾을 수 없습니다.");

    chooser.getFile().then(file => {
        if (!file || !file.data) return;

        //데이터를 Blob으로 변환
        let blob;
        if (typeof file.data === 'string') {
            let base64 = file.data.includes(',') ? file.data.split(',')[1] : file.data;
            base64 = base64.replace(/\s/g, ''); 
            const byteCharacters = atob(base64);
            const byteNumbers = new Uint8Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            blob = new Blob([byteNumbers], { type: file.mediaType });
        } else {
            blob = new Blob([file.data], { type: file.mediaType });
        }
        uploadAndRenderChatFile(blob, file.name, file.mediaType, roomId, file.size);

    }).catch(error => console.error("Chooser 에러:", error));
}

//파일,이미지 업로드
async function uploadAndRenderChatFile(blob, fileName, mediaType, roomId, fileSizeRaw) {
    const formData = new FormData();
    formData.append("file", blob, fileName);
    formData.append("senderId", userData.chat_profile_id);
    formData.append("message", ""); 

    try {
        const r = await requestMDM(encodeURI(`https://chat.astro.lgntel.com/api/chats/${roomId}/upload`), formData, "post");
        
        
        if (mediaType.startsWith('image/')) {
            if (typeof window.chatImages === 'function') {
                window.chatImages([r.data]); 
            }
        } else {
            if (typeof window.drawFileChat === 'function') {
                window.drawFileChat(r.data);
            }
        }

        // 스크롤 하단으로
        $('.chat-context .chat').scrollTop($('.chat-context .chat')[0].scrollHeight);

    } catch (err) {
        console.error("파일 전송 실패:", err);
        popAlert("파일 전송 중 오류가 발생했습니다.");
    }
}

// 이미지 선택 (여러 개 선택 가능)
function selectMultiplePhoto() {    
    var options = {
        maximumImagesCount: 10, // 최대 선택 장수
        width: 1024,            // 리사이징 가로 (0이면 원본)
        height: 1024,           // 리사이징 세로
        quality: 80             // 이미지 품질 (1-100)
    };

    let roomId = $('.chat_room.selected').data('roomid');
    
    window.plugins.imagePicker.getPictures(
        async function(results) {
            await uploadChatImg(results);
        }, function (error) {
            console.error('Error: ' + error);
        }, options
    );
}

async function uploadChatImg(results){
    var imageList = results;
    try {
        if (typeof results === 'string') {
            imageList = JSON.parse(results);
        }
    } catch (e) {
        console.error("결과 파싱 에러:", e);
        return;
    }

    // 결과가 유효한지 확인
    if (!imageList || imageList.length === 0 || imageList === "OK" || imageList === "RESULT_CANCELED") {
        console.log("선택된 이미지가 없거나 취소되었습니다.");
        return;
    }
    console.log(imageList.length + "장의 이미지가 선택되었습니다.");

    let imgCnt = 0, gridStyle = "";

    if (imgCnt === 1) {
        gridStyle = "grid-template-columns: 1fr;";
    } else if (imgCnt === 2) {
        gridStyle = "grid-template-columns: repeat(2, 1fr);";
    } else {
        gridStyle = "grid-template-columns: repeat(3, 1fr);";
    }
    let gid = `live_g_${gformatter.date(new Date(), 'h:m:s').replace(/:/g, '')}`;

    $('.chat-context .chat').append(`                            
        <div class="chat-response user">
            <span class="name">${userData.userName}</span>
            <p class="gallery" style="${gridStyle}" id="${gid}">
                <a href="#" class="download">이미지 다운로드 <i class="bi bi-caret-down-fill"></i></a>
                <span class="time">${gformatter.date(new Date(), 'h:m')}</span>
                <!-- 반복문 추가 (이미지가 여러 개일 경우) -->

            </p>
        </div>`
    );

    for (const [index, fileURI] of imageList.entries()) {
        console.log("image :: " + (index + 1) + "번째 파일 : " + fileURI);
        // await uploadFileViaTransfer(fileURI);
        let { blob, name } = await getFileFromURI(fileURI);
        let roomId = $('.chat_room.selected').data('roomid');

        let formData = new FormData();
        formData.append("file", blob, name);
        formData.append("senderId", userData.chat_profile_id);
        formData.append("message", "");

        await requestMDM(encodeURI("https://chat.astro.lgntel.com/api/chats/" + roomId + "/upload"), formData, "post")
        .then(r =>{
            $(`#${gid}`).append(`<img src="${r.data.fileUrl}" class="popup-img " alt="gallery image">`);
        });
    }
}

function uploadChatImgBinary(file){
    $('.chat-context .chat').append(`                            
        <div class="chat-response user">
            <span class="name">${userData.userName}</span>
            <p class="gallery" style="${gridStyle}" id="${gid}">
                <a href="#" class="download">이미지 다운로드 <i class="bi bi-caret-down-fill"></i></a>
                <span class="time">${gformatter.date(new Date(), 'h:m')}</span>
                <!-- 반복문 추가 (이미지가 여러 개일 경우) -->
                <img src=${file.dataURI}>
            </p>
        </div>`
    );
}

async function getFileFromURI(uri) {
    return new Promise((resolve, reject) => {
        window.resolveLocalFileSystemURL(
            uri,
            function(fileEntry) {
                fileEntry.file(
                    function(file) {
                        const reader = new FileReader();

                        reader.onloadend = function() {
                            const blob = new Blob(
                                [this.result],
                                { type: file.type || "image/jpeg" }
                            );

                            resolve({
                                blob: blob,
                                name: file.name || "upload.jpg"
                            });
                        };

                        reader.onerror = function(err) {
                            reject(err);
                        };

                        reader.readAsArrayBuffer(file);
                    },
                    function(err) {
                        reject(err);
                    }
                );
            },
            function(err) {
                reject(err);
            }
        );
    });
}

async function uploadFileViaTransfer(fileURI) {
    let roomId = $('.chat_room.selected').data('roomid');
    let serverUrl = encodeURI("https://chat.astro.lgntel.com/api/chats/" + roomId + "/upload");

    let rawFileName = fileURI.split('/').pop();
    let cleanFileName = decodeURIComponent(rawFileName).trim();
    let finalFileName = cleanFileName.replace("file:///data/user/0/com.gntel.app.common.mcaller/cache/", "https://chat.astro.lgntel.com/uploads/")

    // var options = new FileUploadOptions();
    // options.fileKey = "files"; // 서버에서 받는 파라미터명
    // options.fileName = finalFileName; // 파일명 추출
    // options.mimeType = "image/jpeg";

    // // 서버에 전달할 추가 파라미터
    // var params = {};
    // params.roomId = roomId;
    // params.senderId = userData.chat_profile_id;
    // options.params = params;
    // options.headers = {
    //     "accept": "*/*",
    //     "Authorization": `Bearer ${userData.astroToken}`
    // };

    // console.log("업로드 시작 파일명: " + finalFileName);

    // var ft = new FileTransfer();
    
    // // 실제 전송 실행
    // ft.upload(fileURI, serverUrl, function(result) {
    //     console.log("전송 성공! 서버 응답: " + result.response);
    //     // 성공 시 로직 (예: 채팅방에 이미지 표시 등)
    // }, function(error) {
    //     console.error("전송 실패 에러 코드: " + error.code);
    //     alert("사진 전송 중 오류가 발생했습니다.");
    // }, options);
    let file = await getFileFromURI(fileURI);

    let formData = new FormData();
    formData.append("file", file, file.name);
    formData.append("senderId", userData.chat_profile_id);
    formData.append("message", "");

    requestMDM(serverUrl, formData, "post");
}

//이미지 추가 테스트함수
let addContactWithImage =  (userid) => {
    let user = user_map[userid] ?? {};

    if($.isEmptyObject(user)) {
        return popAlert("주소록 등록실패<br/>사용자를 찾을수 없습니다");
    }

    popConfirm(user.name + " 님을 폰주소록에 등록합니다", function() {
        var myContact = navigator.contacts.create({
            "displayName": user.name,
            "nickname": user.name
        });

        var img = $('#pop_detail_div_user_photo')[0];
        var canvas = $('<canvas>')[0];
        var ctx = canvas.getContext('2d');
        // 캔버스 크기 설정
        var imgWidth = img.width;
        var imgHeight = img.height;

        // 캔버스 크기를 이미지 크기에 맞게 설정
        canvas.width = imgWidth;
        canvas.height = imgHeight;

        // 캔버스에 이미지 그리기
        try {
            ctx.drawImage(img, 0, 0, imgWidth, imgHeight);  // 원본 이미지 크기로 그리기
            const bg = $('#pop_detail_div_user_photo').css('background-image');
    
            const img_suffix = [...bg.matchAll(/url\(["']?([^"')]+)["']?\)/g)]
            .map(m => m[1])                              
            .filter(url => !url.endsWith('thumb.png'))  // thumb.png 제외
            .map(url => url.split('?')[0].split('.').pop().toLowerCase())
            [0] ?? null;
    
            if(img_suffix != null){
                // Base64로 변환 (PNG 형식)
                var base64Image = canvas.toDataURL(`image/${img_suffix}`);
                var photo = new ContactField('photo', base64Image);
                myContact.photos = [photo];  // photos 배열에 추가
            }
            
        } catch (error) {
            console.warn('사용자 사진파일 등록 실패', error);
        }

        var varUA = navigator.userAgent.toLowerCase(); // userAgent 값 얻기

        if (varUA.indexOf("iphone") > -1 || varUA.indexOf("ipad") > -1 || varUA.indexOf("ipod") > -1) {
            var name = new ContactName();
            name.givenName = user.name;
            myContact.name = name;
        }

        var phoneNumbers = [];
        var emails = [];
        var organizations = [];
        var class_nm = '';
        var dept_nm = '';

        $.each($('.popup_container dd, .popup_container dd>span'), function(idx, item) {
            if ($(item).text().trim() != '') {
                switch ($(item).attr("id")) {
                    case 'pop_detail_span_user_tel':    //내선번호
                        let cn = $(item).text().trim().replace(/\D/g,'').startsWith(serverData.svcPrefixNo)?$(item).text().trim().replace(/\D/g,''):`${serverData.svcPrefixNo}${$(item).text().trim().replace(/\D/g,'')}`;
                        phoneNumbers.push(new ContactField('work', cn, false));
                        break;
                    // case '일반전화':
                    // case '주의번호':
                    //     phoneNumbers.push(new ContactField('work', $(item).find('span.value').text(), false));
                    //     break;
                    case 'pop_detail_span_user_mobile':     //휴대폰번호
                        phoneNumbers.push(new ContactField('mobile', $(item).text().trim().replace(/\D/g,''), false));
                        break;
                    case 'pop_detail_span_user_email':      //이메일
                        emails.push(new ContactField('work', $(item).text().trim(), false));
                        break;
                    case 'pop_detail_dd_user_class':        //직급
                        class_nm = $(item).find('span.value').text();
                        break;
                    case 'pop_detail_dd_user_dept':        //부서
                        let spans = $(item).find('span.part');
                        dept_nm = $(spans[spans.length -1]).text().trim();
                        break;
                    case 'pop_detail_dd_user_desc':         //담당업무
                        myContact.note = $(item).text().trim();
                        break;
                    default:
                        break;
                }
            }
        });


        if (dept_nm != '' || class_nm != '') {
            organizations.push(new ContactOrganization(true, 'work', dept_nm, '', class_nm));
            myContact.organizations = organizations;
        }

        if (!$.isEmptyObject(phoneNumbers)) {
            myContact.phoneNumbers = phoneNumbers;
        }
        if (!$.isEmptyObject(emails)) {
            myContact.emails = emails;
        }

        // 연락처 저장
        myContact.save(() => { popAlert("저장되었습니다."); }, (err) => { 
            let err_msg = "";
            switch (err.code) {
                case 1:
                    err_msg = "전달인자 오류"
                    break;
                case 2:
                    err_msg = "타임아웃 오류"
                    break;
                case 3:
                    err_msg = "PENDING OPERATION 오류"
                    break;
                case 4:
                    err_msg = "입출력 오류"
                    break;
                case 5:
                    err_msg = "주소록 미지원 오류"
                    break;
                case 5:
                    err_msg = "주소록 미지원 오류"
                    break;
                case 6:
                    err_msg = "작동 강제종료 오류"
                    break;
                case 20:
                    err_msg = "주소록 접근 권한 오류"
                    break;
            
                default:
                    err_msg = "알수없는 오류";
                    break;
            }
            popAlert(`저장실패하였습니다.<br/>${err_msg}`); 
        });
    });
}