document.addEventListener('deviceready', function () {
    // try {
    //     if (sessionStorage.getItem('addr_init_once') === '1') return;
    //     sessionStorage.setItem('addr_init_once', '1');
    // } catch (e) {
    //     if (window.__addr_init_once) return;
    //     window.__addr_init_once = true;
    // }

    G.checkOrganization();
    createAddress();

    /**
     * {callHistory : [{name:..,num:..,date_time:..}]}
     */
    readFile('call_history.json', (r) => {
        try {
            call_history_list = JSON.parse(r).callHistory || [];
        } catch (error) {
            call_history_list = [];
        }
    });

    //프로필 설정이 안되어있을경우..(최초 실행시 프로필 관련 설정 세팅)
    cordova.exec((r)=>{
        let json = null;
        try{
            json = JSON.parse(r);
        }catch(e){
            json = r;
        }
        console.log('getNamecardSettings', json);
        if(json.namecard_default == undefined || json.namecard_default == ''){
            let namecard_dir_path ='www/namecard';
            cordova.exec((filelist)=>{
                json = {
                    is_show : true,
                    namecard_default : `${namecard_dir_path.replace('www/','')}/${filelist.split(',')[0]}`
                }
                cordova.exec((r)=>{
                    console.log('success 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);
});

//환경설정 - 테마설정 - 프로필 미리보기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 exitCheck = false;
    document.addEventListener("backbutton", function () {
        if (exitCheck) {
            navigator.app.exitApp();
        } else {
            exitCheck = true;
            setTimeout(() => {
                exitCheck = false;
            }, 2000);
            toast("한번 더 누를 시 앱이 종료됩니다.");
        }
    }, true);

    initMainArticle();
    initMain();
    //-----------------------------게시판 목록 관련 시작

    //게시판 자동 페이징 조회
    $('.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').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');

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

    // ------------------------핀치줌 --폰트사이즈 시작
    let initialDistance = null, minTouchEventDiff = 10;

    const getDistancePointer = (touch1, touch2) => {
        const dx = touch2.clientX - touch1.clientX;
        const dy = touch2.clientY - touch1.clientY;
        return Math.sqrt(dx * dx + dy * dy);
    };

    $('#board_cont').on('touchstart', (event) => {
        if (event.touches.length === 2) {
            // 두 손가락의 초기 거리 저장
            initialDistance = getDistancePointer(event.touches[0], event.touches[1]);
        }
    });

    $('#board_cont').on('touchmove', (event) => {
        if (event.touches.length === 2 && initialDistance !== null) {
            const currentDistance = getDistancePointer(event.touches[0], event.touches[1]);

            if (Math.abs(currentDistance - initialDistance) >= minTouchEventDiff) {
                if (currentDistance > initialDistance) {
                    $('#font-setting-buttons .increase').trigger('click')
                } else if (currentDistance < initialDistance) {
                    $('#font-setting-buttons .decrease').trigger('click')
                }

                // 현재 거리를 다음 비교를 위해 저장
                initialDistance = currentDistance;
            }
        }
    });

    $('#board_cont').on('touchend', () => {
        if (initialDistance !== null) {
            initialDistance = null; // 초기화
        }
    });

    // ------------------------핀치줌 --폰트사이즈 끝

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

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

    //게시판 이동
    $('.mainSwiper a.item, .boardSwiper a.tab, .main_cont .more').on('click', async function (e) {
        e.stopPropagation();
        $('.header.main, .main_cont').addClass('none');
        $('.header.board, .sub_cont').removeClass('none');
        $('.boardSwiper a.tab.on').removeClass('on');
        $(`.boardSwiper a.tab[data-id=${$(this).data('id')}]`).addClass('on');
        await loadExternalHTML($(this).data('id'), $(this).data('file'), $('.sub_cont'));
        console.log('complete');
        $('.header.board .inp').html($(`#header_board_inp_template`).text());
        $('.header.board .inp #btn_board_search').data('pageid', $(this).data('id'));

        loadBoardData($(this).data('id'));
        $('#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, .sub_cont, .header.board, .foot_bt, .for_board_view`).removeClass('none');
                $('.main_cont, .header.main, .for_board_edit').addClass('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 == 'address') {
            await loadScriptAsync(pageid, $target);
        } else {
            await loadExternalHTML(pageid, file, $target);
        }

        // 화면 분기
        if (pageid === 'dial') {
            $('.call_cont').addClass('none');
            $('.address_cont').css('z-index', 90);
            $('.dial_cont').removeClass('none');
            $('body').addClass('dial-mode');
        } else if (pageid === 'address') {
            $('.call_cont').addClass('none');
            $('.dial_cont').addClass('none');
            $('.address_cont').css('z-index', 110);
            $('body').removeClass('dial-mode');
        } else {
            $('.dial_cont').addClass('none');
            $('.address_cont').css('z-index', 90);
            $('.call_cont').removeClass('none');
            $('body').removeClass('dial-mode');
        }

        initFooter('hide');

        $('.main_cont, .sub_cont, .view_cont').addClass('none');
        $('.address_cont').css('z-index', 90);

        // 헤더 표시 전환
        $('#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());

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


    //환경설정
    $('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').addClass('none');
        $('.header.main, .view_cont, .header.main p.header-main-title, .header.main .gohome').removeClass('none');

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

    //메인 검색
    $('#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());

        requestAstro(`isboard/v1/search`, { search_key: $('#inp_main_search').val(), board_seq: 'new' }, 'post')
            .then(r => {
                if (r.code == '0000') {
                    if ($.isEmptyObject(r.data)) {
                        $(`.sub_cont.main-search ul.board_list`).addClass('none');
                        $(`.sub_cont.main-search .empty-post`).removeClass('none');
                    } else {
                        $(`.sub_cont.main-search ul.board_list`).removeClass('none');
                        $(`.sub_cont.main-search .empty-post`).addClass('none');

                        r.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/1/${$('#inp_main_search').val()}`, JSON.parse(response.data).message);
                }

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

    $('.header.main, .main_cont').removeClass('none');
    $('.header.board, .sub_cont, .call_cont, .view_cont, foot_btn').addClass('none');


    //---------------- 메인화면 관련 끝

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

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

    // 메인 헤더의 search 영역 원본을 1회 보관
    // if (typeof window.__MAIN_HEADER_SEARCH_HTML__ === 'undefined') {
    //     window.__MAIN_HEADER_SEARCH_HTML__ = $('.header.main .search').html();
    // }

    // $('.gohome').off('click.nav').on('click.nav', function (e) {
    //     e.preventDefault();

    //     // 화면 전환: 홈만 노출
    //     $('.main_cont').removeClass('none');
    //     $('.dial_cont, .call_cont, .sub_cont, .view_cont').addClass('none');
    //     $('body').removeClass('dial-mode');
    //     $('.address_cont').css('z-index', 90);

    //     // 헤더 전환: 메인 헤더 복원, 보드 헤더 숨김/정리
    //     $('.header.main').removeClass('none');
    //     $('.header.board, .boardSwiper').addClass('none');
    //     $('#header_board_name').text('');
    //     $('.header.board .inp').empty();

    //     // 메인 헤더 search 영역을 원래대로 복원
    //     if (window.__MAIN_HEADER_SEARCH_HTML__) {
    //         $('.header.main .search').html(window.__MAIN_HEADER_SEARCH_HTML__);
    //     }

    //     // 메인 헤더 상태 정리(홈 아이콘 숨김, 타이틀 기본값)
    //     $('.header.main .gohome').addClass('none');
    //     $('.header.main .header-main-title').addClass('none');

    //     // 다이얼/검색 레이어 등 보조 UI 숨김
    //     $('#apx_preview, #search_list_layer').hide();

    //     // if (typeof initFooter === 'function') initFooter('show');
    // });



    // foor btn 공지사항 등록
    $('.foot_btn .foot_btn_reg').on('click', (e) => {
        e.stopPropagation();
        initForBoardEdit();
        $('.foot_btn .foot_btn_back_history').data('target', 'list');
        window.G.openEditNotice();
    });

    // foor btn 공지사항 수정
    $('.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'));
        window.G.openEditNotice($(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');
        }
    });

    //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();
        }

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

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

        callthrough(`${$('.call_pop').data('dialPrefix') || ''}${$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(`${$('.call_pop').data('dialPrefix') || ''}${$checked.val()}`, ($checked.data("type") || "기타"));

        $('.call_pop').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) => {
        $('.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(function (g) {
                let $li = G.renderNewGroupLi(g.code, null, false);
                if ((group_map[g.code].child_groups || []).length == 0) {
                    $($li).find('span.arrow').remove();
                }
                $tree.append($li);
            });
        } else {
            $tree.find('.arrow.expanded').trigger('click');
            $tree.find('ul').hide();
        }

        $('.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('group-code'))
                .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();
    });

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

});

let initMain = () => {

    // $('.wrap').removeClass(function(index, className) { 
    //     return className.replace(/.*(theme.{2}).*/g,'$1')
    // });
    // $('.wrap')[0].className = $('.wrap')[0].className.replace(/.*(theme.{2}).*/g,'$1')
    applySettings();

    $('.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');
    if (pageid === 'address') return $('.address_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 = (pageid, element) => {
    let df = $.Deferred();
    let scripts = [];

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

    let innerloader = scripts.map((src) => {
        let innerdf = $.Deferred();

        // 중복 로딩 방지
        if (document.querySelector(`script[src="${src}"]`)) {
            console.log(`[중복방지] 이미 로드된 스크립트: ${src}`);
            innerdf.resolve();
            return innerdf.promise();
        }

        const script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = src;
        script.onload = () => {
            console.log(`${src} loaded successfully`);
            innerdf.resolve();
        };
        script.onerror = () => {
            console.error(`Failed to load ${src}`);
            innerdf.resolve(); // 실패해도 전체 플로우 막지 않음
        };

        // ★ 안전한 부착 지점: element가 비어있으면 head로
        const mount = (element && element.length && element[0]) ? element[0] : document.head;
        mount.appendChild(script);

        return innerdf.promise();
    });

    $.when(...innerloader).done(() => df.resolve());
    return df.promise();
};


const applySettings = () => {
    let settings = localStorage.getArray('settings');
    $('.wrap')[0].className = `wrap ${settings.theme || 'theme00'} ${settings.font || 'font_basic'}`;
}

const 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;
            request_url = "notice/v1/notices/all";
            initFooter('hide');

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

            if (userData.noticeRegPermitted) {
                initFooter('notice_list');
            }
            break;
        default:
            request_url = `isboard/v1/search`;
            if (!$.isEmptyObject(options)) {
                params = {
                    ...params,
                    ...options
                }
            }
            initFooter('hide');

            break;
    };

    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) ? '' : '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(/{{creator}}/g, item.creator)
                                );
                            }
                        });
                    }
                } catch (error) {
                    console.error(board_seq, error);
                }

            } else {
                console.error(board_seq, response.data.message);
            }
            df.resolve(response);
        })
        .catch((f) => {
            console.error(f);
            df.reject(f);
        });

    return df.promise();
};

const 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');
                }

                if (callback) {
                    callback();
                }
            } else {
                console.log('ERROR isboard/v1/allseq', r);
            }

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

const initMainArticle = () => {
    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(request_url, error);
                }
            } else {
                console.error(request_url, JSON.parse(response.data).message);
            }
        })
        ;
}

const 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) {
                $('.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 && $('.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;
    }
}

const 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');
}

const 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()}`);
}

const requestToCm = (params, callback) => {
    if(typeof REQUEST_CM_THROUGH_ASTRO === 'undefined' || !REQUEST_CM_THROUGH_ASTRO){
        cordova.plugin.http.setServerTrustMode('nocheck', function() {}, function(e) {});
        cordova.plugin.http[(params.method||'post').toLowerCase()](params.url, { }, {
            Authorization: `Bearer ${params.token}`
        }, function(response) {
            let json = null;
            try {
                json = JSON.parse(response.data||'{}');
            } catch (error) {
                console.error(JSON.stringify(params), response);
                return;
            }
            callback({
                code : '0000'
                ,data : json
            });
        }, function(response) {
            console.error(JSON.stringify(response))
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });
    }else{
        requestAstro(`ipecscm/v1/rest/callrequest`, params, 'post')
        .then(response =>{
            if(callback) callback(response);
        })
        .catch(e =>{
            console.error(e);
            popAlert("오류가 발생했습니다.<br/>잠시 후 다시 시도해 주세요");
        });
    }

}

function toStr(v) { return v == null ? "" : String(v); }
function digits(s) { return toStr(s).replace(/[^0-9]/g, ""); }

function openCallPopupByNumbers(contactName, phoneNumbers, context) {

    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_" + (phoneInfo.id || 'c') + "_" + 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(digits(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');
}

// 페이지 당 렌더 개수
var address_pageinsize = 30;

function createAddressItem(contact, checked) {
    if (!contact || !Array.isArray(contact.phoneNumbers) || !contact.phoneNumbers.length) return null;

    var firstPhone = contact.phoneNumbers[0] || {};
    var displayNumber = firstPhone.number || firstPhone.normalizedNumber || '';
    var favoriteInputId = 'fav_' + contact.id;

    var tpl = $('#li_address_item_template').text() || '';
    var html = tpl
        .replace(/{{id}}/g, String(contact.id))
        .replace(/{{favInputId}}/g, favoriteInputId)
        .replace(/{{checkedAttr}}/g, checked ? ' checked' : '')
        .replace(/{{thumb}}/g, getThumbImage(contact.thumbnail))
        .replace(/{{name}}/g, contact.displayName || '')
        .replace(/{{num}}/g, displayNumber || '');

    // 문자열 → jQuery 엘리먼트로 변환한 뒤, data 저장
    var $li = $(html);
    $li.attr('data-contact', JSON.stringify(contact));
    $li.data('contactObj', contact);

    return $li;
}

// 주소록 페이지 렌더
function drawAddressList(offset = 0) {
    var allContacts = window.localStorage.getArray('contact') || [];
    var favoriteIds = window.localStorage.getArray('favorite') || [];
    var favoriteSet = {};
    for (var i = 0; i < favoriteIds.length; i++) favoriteSet[String(favoriteIds[i])] = true;

    // 범위 체크
    if (offset >= allContacts.length) return;

    // 처음 호출이면 비우기
    if (offset === 0) {
        $('#address_list_all').empty();
    }

    var contactSlice = allContacts.slice(offset, offset + address_pageinsize);
    var nodes = [];

    for (var k = 0; k < contactSlice.length; k++) {
        var contact = contactSlice[k];
        if (!contact || !contact.displayName || !Array.isArray(contact.phoneNumbers) || !contact.phoneNumbers.length) continue;

        var isFavoriteChecked = !!favoriteSet[String(contact.id || '')];
        var $item = createAddressItem(contact, isFavoriteChecked);
        if ($item) nodes.push($item[0]);
    }

    if (nodes.length) {
        $('#address_list_all').append(nodes);
    }
}

