var newContact = [];
var favoriteContact;
var historyContact;
//var searchContactByNumber;
var imsitime="";
var searchImsitime="";
function phonenumberValidation(inputtxt){
    console.log(inputtxt);
    //var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/;
    //var phoneno = /^\d{10}$/g;
    if(nullcheck(inputtxt)) {
        console.log("1");
        return false;
    }else if(inputtxt.length > 3) {
        console.log("2");
        return true;
    }else{
        console.log("3");
        return false;
    }
}

//get image
function getYear(el){
    var getYear = el.split("일");
    return getYear[0]+"일";
    // var getYear = el.substr(0,el.length-6);
    // return getYear+"시";
}
//get image
function getThumbImage(el){
    var phptoAddr = "";
    if(!nullcheck(el)){
        phptoAddr = el;
    }else{
        //console.log("makeRandom"+makeRandom(1,5));
        phptoAddr = "img/blank_gray_2.png";
    }
    return phptoAddr;
}
//set randon image
function setThumbImage(){
    var phptoNum = makeRandom(1,5);
    //console.log("makeRandom"+phptoNum);
    switch (phptoNum) {//1,2,3,4,5
        case 1:
            return "img/blank_gray_2.png";
        case 2:
            return "img/blank_gray_2.png";
        case 3:
            return "img/blank_gray_2.png";
        case 4:
            return "img/blank_gray_2.png";
        case 5:
            return "img/blank_gray_2.png";
        default:
            return "img/blank_gray_2.png";
    }
}

function makeRandom(min, max){
    var RandVal = Math.floor(Math.random()*(max-min+1)) + min;
    return RandVal;
}
//get telephone Number
/*
function getRemovePlusEightTwo(el){
    var telephoneNumber = el;
    telephoneNumber = telephoneNumber.replace( '+82', '0' );
    return telephoneNumber;
}
*/
//get telephone Number
function getTelephoneNumber(el){
    var telephoneNumber = el;
    telephoneNumber = telephoneNumber.replace( '+82', '0' );
    //var settingData = window.localStorage.getArray("settingData");
    var accCodeUsed = settingData.accCodeUsed;
    var accCode = settingData.accCode;
    var digitCount = settingData.digitCount;
    digitCount = parseInt(digitCount);
    console.log("digitCount:"+digitCount);
    console.log("accCode:"+accCode);
    console.log("accCodeUsed:"+accCodeUsed);
    if(telephoneNumber.length > digitCount){
        console.log("digitCount1:"+telephoneNumber.length);
        if(accCodeUsed == "Y"){
            telephoneNumber = accCode + telephoneNumber;
        }
    }
    console.log("telephoneNumber"+telephoneNumber);

    telephoneNumber = encodeURIComponent( telephoneNumber );
    return telephoneNumber;
}
//get user's telephone Number
function getUserNumber(){
    //var settingData = window.localStorage.getArray("settingData");
    //alert("settingData"+JSON.stringify(settingData));
    var accCodeUsed = settingData.accCodeUsed;
    var accCode = settingData.accCode;
    var digitCount = settingData.digitCount;
    var mobileNumber = settingData.mobileNumber;
    digitCount = parseInt(digitCount);
    if(!nullcheck(mobileNumber)){
        if(mobileNumber.length > digitCount){
            if(accCodeUsed == "Y"){
                mobileNumber = accCode + mobileNumber;
            }
        }

        mobileNumber = encodeURIComponent( mobileNumber );
        return mobileNumber;
    }else{
        popAlert("HP번호가 없습니다.",function() {
            goToSetting()
        });
        return "";
    }
}
//get user's prefix Number
function getPrefixNumber(){
    //var settingData = window.localStorage.getArray("settingData");
    var digitCount = settingData.digitCount;
    var prefixNumber = settingData.prefixNumber;
    console.log("prefixNumber"+prefixNumber);
    digitCount = parseInt(digitCount);
    if(!nullcheck(prefixNumber)){

        prefixNumber = encodeURIComponent( prefixNumber );
        return prefixNumber;
    }else{
        popAlert("내선번호가 없습니다.",function() {
            goToSetting()
        });
        return "";
    }
}
function goToSetting(){
    location.href = "#setting";
}
/* --------------------------------------------------
   알파벳인지 체크
  ------------------------------------------------*/
  function isAlphabet(ch) {
    var numUnicode = ch.charCodeAt(0);                                                                                    // number of the decimal Unicode
    if ( 65 <= numUnicode && numUnicode <= 90 ) return true;            // 대문자
    if ( 97 <= numUnicode && numUnicode <= 122 ) return true;            // 소문자
    return false;
}

/* --------------------------------------------------
한글인지 체크
------------------------------------------------*/
function isKorean(ch) {
    var numUnicode = ch.charCodeAt(0);
    if ( 44032 <= numUnicode && numUnicode <= 55203 ) return true;
    return false;
}

/* --------------------------------------------------
숫자인지 체크
------------------------------------------------*/
function isNumber(ch) {
    var numUnicode = ch.charCodeAt(0);
    if ( 48 <= numUnicode && numUnicode <= 57 ) return true;
    return false;
}

//초성검색
function getCho(str) {

    var rCho = ["ㄱ", "ㄲ", "ㄴ", "ㄷ", "ㄸ", "ㄹ", "ㅁ", "ㅂ", "ㅃ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅉ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"];
    //var rJung = ["ㅏ", "ㅐ", "ㅑ", "ㅒ", "ㅓ", "ㅔ", "ㅕ", "ㅖ", "ㅗ", "ㅘ", "ㅙ", "ㅚ", "ㅛ", "ㅜ", "ㅝ", "ㅞ", "ㅟ", "ㅠ", "ㅡ", "ㅢ", "ㅣ"];
    //var rJong = ["", "ㄱ", "ㄲ", "ㄳ", "ㄴ", "ㄵ", "ㄶ", "ㄷ", "ㄹ", "ㄺ", "ㄻ", "ㄼ", "ㄽ", "ㄾ", "ㄿ", "ㅀ", "ㅁ", "ㅂ", "ㅄ", "ㅅ", "ㅆ", "ㅇ", "ㅈ", "ㅊ", "ㅋ", "ㅌ", "ㅍ", "ㅎ"];

    var cho, jung, jong;

    var result = [];
    for (var i in str) {
        var char = str.substr(i, 1);

        //console.log("char"+char);

        var sTest=char;
        var nTmp=sTest.charCodeAt(0) - 0xAC00;
        jong=nTmp % 28; // 종성
        jung=( (nTmp-jong)/28 ) % 21; // 중성
        cho=( ( (nTmp-jong)/28 ) - jung ) / 21; // 종성
        /*
        console.log(
        "초성:"+rCho[cho]+"\n"
        +"중성:"+rJung[jung]+"\n"
        +"종성:"+rJong[jong]
        );
*/
        result.push(rCho[cho]);
    }
    return result.join('');
}
function getKoreanNumber(phoneNumber){
    var phone = "";

    if(phoneNumber.startsWith( '+' )){
        return phoneNumber;
    }
    if(phoneNumber.length <= 4) {
        phone = phoneNumber;
    } else if(phoneNumber.length <= 8) {
        phone = phoneNumber.replace(/([0-9]+)([0-9]{4})/,"$1-$2");
    }else {
        phone = phoneNumber.replace(/(^02.{0}|^01.{1}|[0-9]{3})([0-9]+)([0-9]{4})/,"$1-$2-$3");
    }
    return phone;
}
function createAddress(){

    navigator.contactsPhoneNumbers.list(function(contacts) {
        for (var i=0; i<contacts.length; i++) {
            if (nullcheck(contacts[i].displayName)) {
                contacts.splice(i,1);
            }else{
                var dataCho = getCho(contacts[i].displayName);
                contacts[i]["nameCho"] = dataCho;
            }

            if(nullcheck(contacts[i].thumbnail)){
                contacts[i]["thumbnail"] = setThumbImage();
                //console.log(contacts[i]["thumbnail"]);
            }

            if(!nullcheck(contacts[i].phoneNumbers)){
                for (var j = 0; j < contacts[i].phoneNumbers.length; j++) {
//                    console.log("number::"+contacts[i].phoneNumbers[j].normalizedNumber );
//                    console.log("number::"+contacts[i].phoneNumbers[j].number );
                    contacts[i].phoneNumbers[j].number = getKoreanNumber(contacts[i].phoneNumbers[j].normalizedNumber)
//                    console.log("number::"+contacts[i].phoneNumbers[j].number );
                }
            }
        }

        contacts.sort(function(a, b) {
            //console.log('contacts.sort:' + a.name.formatted + " :::: " + b.name.formatted);
            var aNameString = $.trim(a.displayName);
            var bNameString = $.trim(b.displayName);

            if(isKorean(aNameString)){
                if(isKorean(bNameString)){
                    return aNameString < bNameString ? -1 : 1;
                }else{
                    return -1;
                }
            }else if(isAlphabet(aNameString)){
                if(isKorean(bNameString)){
                    return 1;
                }else if(isAlphabet(bNameString)){
                    return aNameString < bNameString ? -1 : 1;
                }else{
                    return -1;
                }
            }else if(isNumber(aNameString)){
                if(isKorean(bNameString) || isAlphabet(bNameString)){
                    return 1;
                }else if(isNumber(bNameString)){
                    return aNameString < bNameString ? -1 : 1;
                }else{
                    return -1;
                }
            }else{
                if(!isNumber(bNameString) && !isAlphabet(bNameString) && !isKorean(bNameString)){
                    return aNameString < bNameString ? -1 : 1;
                }else{
                    return 1;
                }
            }
        })
        console.log('favoriteContact0');
        window.localStorage.setArray("contact", contacts);
        favoriteContact = window.localStorage.getArray("favorite"); //빈배열
        if(nullcheck(favoriteContact)){
            console.log('favoriteContact1');
            favoriteContact = new Array(); //빈배열
            window.localStorage.setArray("favorite", favoriteContact);
        }
        console.log('favoriteContact2');
        callAddress();
        printFavorites();
        console.log('favoriteContact3');
        //console.log(JSON.stringify(contacts));
        printAddress();
        //sortUL(".list_favorites");
        //$.mobile.loading( "hide" );

        $(".loaderWrap").addClass("hide");


     }, function(error) {
        console.error(error);
        $(".loaderWrap").addClass("hide");
     });
}

function callAddress(){
    newContact = window.localStorage.getArray("contact");
}

function sortUL(selector,callback) {
    var $ul = $(selector);
    $ul.find('li').sort(function (a, b) {
        var upA = $(a).text().toUpperCase();
        var upB = $(b).text().toUpperCase();
        return (upA < upB) ? -1 : (upA > upB) ? 1 : 0;
    }).appendTo(selector);
};
function sortULReverse(selector,callback) {
    var $ul = $(selector);
    $ul.find('li').sort(function (a, b) {
        var upA = $(a).text().toUpperCase();
        var upB = $(b).text().toUpperCase();
        return (upA > upB) ? -1 : (upA < upB) ? 1 : 0;
    }).appendTo(selector);
};
function hideLoader(){
    alert("hideLoader");
    $(".loaderWrap").addClass("hide");
}


function toggleFavorite(id){

    favoriteContact = window.localStorage.getArray("favorite"); //빈배열
    //console.log('toggleFavorite0 = ' + id);
    //console.log('toggleFavorite1 = ' + favoriteContact);

    if(favoriteContact.indexOf($.trim(id)) >=0 ) {//있으면
        favoriteContact.splice(favoriteContact.indexOf($.trim(id)), 1);

    }else{
        //favoriteContact.push(id);
        favoriteContact.push($.trim(id));
    }
    //console.log('toggleFavorite3 = ' + favoriteContact);
    window.localStorage.setArray("favorite", favoriteContact);//저장

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

    //         console.log("article_favorites"+document.querySelector(".article_favorites").offsetHeight);
    //         var offset = document.querySelector(".article_favorites").offsetHeight+24+31+61;
    //         //console.log('toggleFavorite offset = ' + offset);
    //         clusterizeAddress.setTopHeightOffset(offset);
    //     }
    // }
}
$(".input_search").focus(function(){
    window.scrollTo(0,0);
});
$(".input_search_history").focus(function(){
    window.scrollTo(0,0);
});

//즐겨찾기 불러오기
function printFavorites(){
    favoriteContact = window.localStorage.getArray("favorite"); //빈배열
    console.log('favoriteContact4:'+favoriteContact);
    if(!nullcheck(favoriteContact)){
        for (var i = 0; i < favoriteContact.length; i++) {
            var favoriteContactID = favoriteContact[i];
            console.log('favoriteContactID = ' + favoriteContact);

            var contact = newContact.find(item => $.trim(item.id) === favoriteContactID);
            if(!nullcheck(contact)){
                if(contact.phoneNumbers != null && contact.displayName != null){
                    var favoHtml = "";
                    console.log("즐찾"+JSON.stringify(contact.displayName));
                    if(favoriteContact.indexOf($.trim(contact.id)) >=0 ) {
                        //즐겨찾기 된애
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+contact.id+")' class='btn_favo'></a>"
                    }else{
                        //즐겨찾기 안된애
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+contact.id+")' class='btn_favo_no'></a>"
                    }

                    var liEl = "<li data-id='"+ contact.id +"' data-contact='"+JSON.stringify(contact) +"'>";
                    liEl += "<span class='portrait'><img src='"+getThumbImage(contact.thumbnail)+"'></span>";
                    liEl += favoHtml;
                    liEl += "<h4>"+contact.displayName+"</h4>";
                    liEl += "<button type='button' class='btn_call'></button>";
                    //liEl += phNumArrHtml;
                    liEl += "</li>";
                    console.log("즐찾"+liEl);
                    $(".list_favorites").append(liEl);
                }
            }else{
                favoriteContact.splice(i, 1);
            }

        }
        console.log('favoriteContact5:'+favoriteContact);
        window.localStorage.setArray("favorite", favoriteContact);//저장
    }

};
//주소록 불러오기
function printAddress(){
    let addressOrder = $(`.search_wrap_01>.sort_tool>button.btn_sort.on`).hasClass('sort_desc_addr');

    if(!addressOrder){
        newContact.reverse();
    }
    var data = new Array(); 
    $(".list_all").empty();
    for (var i = 0; i < newContact.length; i++) {
        if(newContact[i].phoneNumbers != null && newContact[i].displayName != null){
            var favoHtml = "";
            if(favoriteContact.indexOf($.trim(newContact[i].id)) >=0 ) {
                //즐겨찾기 된애
                favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+newContact[i].id+")' class='btn_favo'></a>"
            }else{
                //즐겨찾기 안된애
                favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+newContact[i].id+")' class='btn_favo_no'></a>"
            }

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

            if(isIOS12()){
                $(".list_all").append(liEl);
            }else{
                data.push(liEl);
            }


            //historyContact.push(contact);
            //$(".list_all").append(liEl);
        }
    }
    if(isIOS12()){
    }else{
        //article_favorites 26
        //마진 위 아래 12씩 24
        var offset = document.querySelector(".article_favorites").offsetHeight+24+31+61;


        console.log("article_favorites offset"+offset);
        //clusterizeAddress.setTopHeightOffset(offset+1000);
        //alert("Not ios12");
        if(!nullcheck(clusterizeAddress)){
            clusterizeAddress.destroy(true);
        }
        clusterizeAddress = new Clusterize({
            rows_in_block: 50,
            blocks_in_cluster: 5,
            offset:offset,
            rows: data,
            keep_parity:true,
            scrollId: 'scrollArea',
            contentId: 'contentArea'
        });

        //clusterizeAddress.offset = offset+1000;

        //clusterizeAddress.setTopHeightOffset(offset+1000);
    }
    if(!addressOrder){
        newContact.reverse();
    }
};

//전체검색
function searchPad(){
    var keyword = $(".calling_num").html();

    if(keyword.length>2){

        //alert(keyword);

         //var search = '23232';
         searchContactByNumber = newContact.filter(({phoneNumbers}) => {
            //"null check"
            if( nullcheck(phoneNumbers)){
                return
            }else{
                //return phoneNumbers.some(e => e.normalizedNumber.toLowerCase().includes(keyword.toLowerCase()))
                return phoneNumbers.some(item => new RegExp(keyword).test(item.normalizedNumber))
            }

        })

        /*
        <div class="src_result_box">
                        <span class="portrait"><img src="img/sample_portrait.jpg"></span>
                        <h4>유창현</h4>
                        <p>0101<span>234</span>5678</p>
                        <span class="num">100</span>
                        <button type="button" class="sel_other"></button>
                    </div>

                    $(".calling_num").html(callNum);
        */
        //console.log('JSON.stringify(searchContactByNumber) = ' + JSON.stringify(searchContactByNumber));

        if(searchContactByNumber.length>0){
            var firstContact =  searchContactByNumber[0];
            console.log('firstContact = ' + JSON.stringify(firstContact));

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

            var index = telephoneNumber.indexOf(keyword);
            console.log('index = ' + JSON.stringify(index));
            if (index >= 0) {
                telephoneNumber = telephoneNumber.substring(0,index) + "<span>" + telephoneNumber.substring(index,index+keyword.length) + "</span>" + telephoneNumber.substring(index + keyword.length);
                telephoneHtml = telephoneNumber;
            }

            var searchCount = "";
            if(searchContactByNumber.length != 1){
                var searchCount = searchContactByNumber.length;
                $(".sel_other").show();
            }else{
                $(".sel_other").hide();
            }
            var thumbImage = "<img src='"+getThumbImage(firstContact.thumbnail)+"'>"

            $(".src_result_box .portrait").html(thumbImage);
            $(".src_result_box").show();
            $(".src_result_box h4").html(firstContact.displayName);
            $(".src_result_box p").html(telephoneHtml);
            $(".src_result_box .num").html(searchCount);
        }else{
            $(".src_result_box").hide();
        }

    }else{
        $(".src_result_box").hide();
    }

}
//전체검색
function searchAll(){

    var keyword = $(".btn_sch_all").val();

    if(keyword.length>0){
        //var newContact = window.localStorage.getArray("contact");
        var data = new Array();

        // TODO: dhlee: IOS에서 displayName 이 (lastName + 스페이스 + middleName + 스페이스 + firstName) 형태로 되어있어 검색이 안되는 문제 수정
        //              성능문제가 있을경우 수정필요
        //var searchContactName = newContact.filter(item => new RegExp(keyword).test(item.displayName));
        // var searchContactName = newContact.filter(item => new RegExp(keyword).test(item.lastName+item.middleName+item.firstName));
        var searchContactName = newContact.filter(item => new RegExp(keyword).test((typeof item.lastName == "undefined" ? "" : item.lastName)
                                                                                                + (typeof item.middleName == "undefined" ? "" : item.middleName)
                                                                                                + (typeof item.firstName == "undefined" ? "" : item.firstName)));
        //..//

        var searchContactChoName = newContact.filter(item => new RegExp(keyword).test(item.nameCho));

        var  searchContactPlus = searchContactName.concat(searchContactChoName);

        //var search = '23232';
        var searchContactByNumber = newContact.filter(({phoneNumbers}) => {
            //"null check"
            if( nullcheck(phoneNumbers)){
                return
            }else{
                //return phoneNumbers.some(e => e.normalizedNumber.toLowerCase().includes(keyword.toLowerCase()))
                return phoneNumbers.some(item => new RegExp(keyword).test(item.normalizedNumber))
            }

        })
        //console.log('JSON.stringify(searchContact) = ' + JSON.stringify(searchContactName));
        //console.log('JSON.stringify(searchContactByNumber) = ' + JSON.stringify(searchContactByNumber));
        var  searchContact = searchContactPlus.concat(searchContactByNumber);
        favoriteContact = window.localStorage.getArray("favorite");
        console.log('JSON.stringify(searchContact) = ' + JSON.stringify(searchContact));

        console.log('searchContact.length = ' + searchContact.length);

        $(".list_sch_all").empty();
        for (var i = 0; i < searchContact.length; i++) {
            if(searchContact[i].phoneNumbers != null && searchContact[i].displayName != null){
                var favoHtml = "";
                if(favoriteContact.indexOf($.trim(searchContact[i].id)) >=0 ) {
                    //즐겨찾기 된애
                    favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+searchContact[i].id+")' class='btn_favo'></a>"
                }else{
                    //즐겨찾기 안된애
                    favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+searchContact[i].id+")' class='btn_favo_no'></a>"
                }
                var liEl = "<li data-id='"+ searchContact[i].id +"' data-contact='"+JSON.stringify(searchContact[i]) +"'>";
                liEl += "<span class='portrait'><img src='"+getThumbImage(searchContact[i].thumbnail)+"'></span>";
                liEl += favoHtml;
                liEl += "<h4>"+searchContact[i].displayName+"</h4>";
                liEl += "<button type='button' class='btn_call'></button>";
                //liEl += phNumArrHtml;
                liEl += "</li>";
                if(isIOS12()){
                    $(".list_sch_all").append(liEl);
                }else{
                    data.push(liEl);
                }
            }

        }
        if(isIOS12()){
        }else{
            var offset = 31+61;
            //alert("Not ios12");
            if(!nullcheck(clusterizeAddressSearch)){
                clusterizeAddressSearch.destroy(true);
            }
            clusterizeAddressSearch = new Clusterize({
                rows_in_block: 50,
                blocks_in_cluster: 5,
                offset: offset,
                rows: data,
                scrollId: 'scrollAreaSearch',
                contentId: 'contentAreaSearch'
            });
        }
    }else{
        $(".list_sch_all").empty();
    }
};

function printHistory() {

    listFavo = window.localStorage.getArray("favorite");
    var callHistory = window.localStorage.getArray("callHistory");
    console.log('callHistory = ' + JSON.stringify(callHistory));
    readFile("user_map.json", function (userMapData) {
        var data = new Array();
        var userMap = JSON.parse(userMapData||'{}');
        // userMap을 배열로 변환하고, 필요한 형태로 가공
        var userMapArray = [];
        for (var key in userMap) {
            if (userMap.hasOwnProperty(key)) {
                var user = userMap[key];
                var phoneNumberType = "기타"; // 기본값은 "기타"로 설정
                var phoneNumber = user.mobile_no; // 예시로 휴대폰 번호를 사용했다고 가정
                var cidNumberType = "기타";
                var cidNumber = user.cid_no;
    
                // 전화번호의 길이에 따라 타입을 지정
                if (phoneNumber.length === 11) {
                    phoneNumberType = "휴대폰";
                }
    
                // 전화번호의 길이에 따라 타입을 지정
                if (cidNumber.length === 4) {
                    cidNumberType = "사무실";
                }
    
                var userObj = {
                    id: user.uid,
                    displayName: user.name,
                    phoneNumbers: [{ number: user.cid_no, normalizedNumber: user.cid_no, type: cidNumberType }, { number: user.mobile_no, normalizedNumber: user.mobile_no, type: phoneNumberType }],
                    thumbnail: (user.photo_path_url != undefined && user.photo_path_url != '')?`${settingData.server_host}${settingData.server_port}${user.photo_path_url}`:'' // 적절한 썸네일 정보가 있다면 여기에 추가
                };
                userMapArray.push(userObj);
            }
        }
    
    
        if (nullcheck(callHistory)) {
            return;
        }
        if (!historyOrder) {
            callHistory.reverse();
        }
    
        $(".list_history").empty();
        historyContact = [];
    
        for (var i = 0; i < callHistory.length; i++) {
            var callHistoryNum = callHistory[i]["num"];
            console.log('callHistoryNum = ' + callHistoryNum);
    
            var contactArray = [];
            if (!nullcheck(newContact)) {
                contactArray = contactArray.concat(newContact);
            }
            if (!nullcheck(userMapArray)) {
                contactArray = contactArray.concat(userMapArray);
            }
    
            contactArray = contactArray.filter(contact => {
                if (nullcheck(contact.phoneNumbers)) {
                    return false;
                }
                return contact.phoneNumbers.some(item => callHistoryNum === getRemovePlusEightTwo(item.normalizedNumber));
            });
    
            if (!nullcheck(contactArray)) {
                var contact = contactArray[0];
                historyContact.push(contact);
                var callHistoryTime = callHistory[i]["time"];
                var callHistoryTimeHtml = "";
                var callHistoryTimeHtmlOthers = "";
    
                if ($.trim(callHistory[i]["id"]).startsWith("-1")) {
                    callHistory[i]["id"] = String(contact.id);
    
                    var phoneNumber = contact.phoneNumbers.find(item => $.trim(callHistory[i]["num"]) === getRemovePlusEightTwo(item.normalizedNumber));
                    var type = phoneNumber.type;
    
                    callHistory[i]["type"] = type;
                }
                console.log('callHistoryTime.length = ' + callHistoryTime.length);
                var callCount = 0;
                for (var j = 0; j < callHistoryTime.length; j++) {
                    console.log('callHistoryTime[j] = ' + callHistoryTime[j]);
                    if (j == 0) {
                        callHistoryTimeHtml += "<li>" + callHistoryTime[j] + "</li>";
                    } else {
                        callHistoryTimeHtmlOthers += "<li>" + callHistoryTime[j] + "</li>";
                    }
                    callCount++;
                }
                var callCountHtml = "";
                var historyOneHtml = "";
                if (callCount > 1) {
                    callCountHtml += " (" + callCount + ")";
                    historyOneHtml = "history_one";
                } else {
                    historyOneHtml = "history_one none";
                }
                if (contact.phoneNumbers != null && contact.displayName != null) {
                    var favoHtml = "";
                    console.log("즐찾" + contact.phoneNumbers);
    
                    var liEl = "";
                    if (listFavo.indexOf($.trim(contact.id)) >= 0) {
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite(" + contact.id + ")' class='btn_favo'></a>"
                    } else {
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite(" + contact.id + ")' class='btn_favo_no'></a>"
                    }
                    var callHistoryTimeFirst = getYear(callHistoryTime[0]);
                    console.log("callHistoryTimeFirst" + callHistoryTimeFirst);
                    console.log("imsitime" + imsitime);
                    if (imsitime != callHistoryTimeFirst) {
                        liEl += "<li class='year'>" + callHistoryTimeFirst + "</li>";
    
                        imsitime = callHistoryTimeFirst;
                        console.log("추가");
                    }
                    liEl += "<li class='history_cell_box' data-id='" + contact.id + "'data-historyid='" + callHistory[i]["historyId"] + "' data-contact='" + JSON.stringify(contact) + "'>";
                    liEl += "<span class='portrait'><img src='" + getThumbImage(contact.thumbnail) + "'></span>";
                    liEl += favoHtml;
                    liEl += "<h4 class='history_cell'>" + contact.displayName + callCountHtml + "</h4>";
                    liEl += "<p class='history_cell " + historyOneHtml + "'>" + callHistory[i]["type"] + " " + callHistory[i]["num"] + "</p><button type='button' class='btn_call'></button>";
                    liEl += "<ul class='history_call'>";
                    liEl += callHistoryTimeHtml;
                    liEl += "</ul>";
                    liEl += "<ul class='history_call others_history'>";
                    liEl += callHistoryTimeHtmlOthers;
                    liEl += "</ul>";
                    liEl += "</li>";
                    if (isIOS12()) {
                        $(".list_history").append(liEl);
                    } else {
                        data.push(liEl);
                    }
                }
            } else {
                callHistory[i]["id"] = "-1" + callHistory[i].num;
                callHistory[i]["type"] = "기타";
                var anonymousLiEl = printHistoryAnonymous(callHistory[i]);
    
                if (isIOS12()) {
                    $(".list_history").append(anonymousLiEl);
                } else {
                    data.push(anonymousLiEl);
                }
            }
        }
    
        if (isIOS12()) {
    
        } else {
    
            var offset = 31 + 61;
            if (!nullcheck(clusterizeHistory)) {
                clusterizeHistory.destroy(true);
            }
            clusterizeHistory = new Clusterize({
                rows_in_block: 50,
                blocks_in_cluster: 5,
                offset: offset,
                rows: data,
                scrollId: 'scrollAreaHistory',
                contentId: 'contentAreaHistory'
            });
        }
    
        if (!historyOrder) {
            callHistory.reverse();
        }
        console.log('callHistory 1 = ' + JSON.stringify(callHistory));
        console.log("historyContact" + JSON.stringify(historyContact));
        window.localStorage.setArray("callHistory", callHistory);
        imsitime = "";
    });

    
};


function printHistoryAnonymous(callHistoryAnonymous){
    var callHistoryTime = callHistoryAnonymous["time"];
    var callHistoryTimeHtml = "";
    var callHistoryTimeHtmlOthers = "";
    console.log('callHistoryTime.length = ' + callHistoryTime.length);
    var anonymousPhoneNumber = {
        number:callHistoryAnonymous["num"],
        normalizedNumber:callHistoryAnonymous["num"],
        type:"기타"
    };
    var anonymousPhoneNumbers = [anonymousPhoneNumber];
    var anonymousContact = {
        displayName:"알수없음",
        phoneNumbers:anonymousPhoneNumbers,
        id:"-1"+callHistoryAnonymous["num"]
    };
    historyContact.push(anonymousContact);
    var callCount = 0;
    for (var j = 0; j < callHistoryTime.length; j++) {
        console.log('callHistoryTime[j] = ' + callHistoryTime[j]);
        if(j==0){
            callHistoryTimeHtml += "<li>"+callHistoryTime[j]+"</li>";
        }else{
            callHistoryTimeHtmlOthers += "<li>"+callHistoryTime[j]+"</li>";
        }
        callCount++;
    }
    var callCountHtml = "";
    var historyOneHtml = "";
    if(callCount>1){
        callCountHtml += " ("+callCount+")";
        historyOneHtml = "history_one";
    }else{
        historyOneHtml = "history_one none";
    }
    var idHtml = "-1"+callHistoryAnonymous["num"];
    var liEl ="";

    var callHistoryTimeFirst = getYear(callHistoryTime[0]);
    console.log("callHistoryTimeFirst"+ callHistoryTimeFirst);
    console.log("imsitime"+ imsitime);
    if(imsitime!=callHistoryTimeFirst) {
        liEl += "<li class='year'>"+callHistoryTimeFirst+"</li>";

        imsitime=callHistoryTimeFirst;
        console.log("추가");
    }

    liEl += "<li class='history_cell_box' data-id='"+ anonymousContact.id + "'data-historyid='"+ callHistoryAnonymous["historyId"] + "' data-contact='"+JSON.stringify(anonymousContact) +"'>";
    //liEl += "<li data-id='"+ anonymousContact.id +"' data-contact='"+JSON.stringify(anonymousContact) +"'>";
    liEl += "<span class='portrait'><img src='img/blank_gray_2.png'></span>";
    liEl += "<h4 class='history_cell'>알수없음"+callCountHtml+"</h4>";
    liEl += "<p class='history_cell "+historyOneHtml+"'>"+callHistoryAnonymous["type"]+" "+callHistoryAnonymous["num"]+"</p><button type='button' class='btn_call'></button>";
    liEl += "<ul class='history_call'>";
    liEl += callHistoryTimeHtml;
    liEl += "</ul>";
    liEl += "<ul class='history_call others_history'>";
    liEl += callHistoryTimeHtmlOthers;
    liEl += "</ul>";
    liEl += "</li>";

    return liEl;
    //$(".list_history").append(liEl);

}
//통화목록 검색
function searchHistory(){

    var keyword = $(".btn_sch_history").val();
    var callHistory = window.localStorage.getArray("callHistory");

    if(keyword.length>0){
        var data = new Array();
        var newContact = new Array(); //빈배열
        newContact = historyContact;

        /**
         * IOS 통화목록 검색시 이름검색 이슈 있어서 주소록과 동일한 필터 반영함
         */
        // var searchContactName = newContact.filter(item => new RegExp(keyword).test(item.displayName));
        var searchContactName = newContact.filter(item => new RegExp(keyword).test((typeof item.lastName == "undefined" ? "" : item.lastName)
                                                                                                + (typeof item.middleName == "undefined" ? "" : item.middleName)
                                                                                                + (typeof item.firstName == "undefined" ? "" : item.firstName)));
                                                                                                
        var searchContactChoName = newContact.filter(item => new RegExp(keyword).test(item.nameCho));

        var searchContactPlus = searchContactName.concat(searchContactChoName);

        var searchContactByNumber = newContact.filter(({phoneNumbers}) => {
            if( nullcheck(phoneNumbers)){
                return
            }else{
                return phoneNumbers.some(item => new RegExp(keyword).test(item.normalizedNumber))
            }

        })
        var  searchContact = searchContactPlus.concat(searchContactByNumber);
        favoriteContact = window.localStorage.getArray("favorite");

        $(".list_sch_history").empty();
        for (var i = 0; i < callHistory.length; i++) {

            var callHistoryNum = callHistory[i]["num"];

            var contactArray = searchContact.filter(({phoneNumbers}) => {
                if( nullcheck(phoneNumbers)){
                    return
                }else{
                    return phoneNumbers.find(item => callHistoryNum === getRemovePlusEightTwo(item.normalizedNumber));
                }
            })
            if(!nullcheck(contactArray)){
                var contact = contactArray[0];
                var callHistoryTime = callHistory[i]["time"];
                var callHistoryTimeHtml = "";
                var callHistoryTimeHtmlOthers = "";
                console.log('callHistoryTime.length = ' + callHistoryTime.length);

                var callCount = 0;
                for (var j = 0; j < callHistoryTime.length; j++) {
                    if(j==0){
                        callHistoryTimeHtml += "<li>"+callHistoryTime[j]+"</li>";
                    }else{
                        callHistoryTimeHtmlOthers += "<li>"+callHistoryTime[j]+"</li>";
                    }
                    callCount++;
                }
                var callCountHtml = "";
                var historyOneHtml = "";
                if(callCount>1){
                    callCountHtml += " ("+callCount+")";
                    historyOneHtml = "history_one";
                }else{
                    historyOneHtml = "history_one none";
                }
                if(contact.phoneNumbers != null && contact.displayName != null){
                    var favoHtml = "";
                    var liEl = "";

                    if(listFavo.indexOf($.trim(contact.id)) >=0 ) {
                        //즐겨찾기 된애
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+contact.id+")' class='btn_favo'></a>"
                    }else{
                        //즐겨찾기 안된애
                        favoHtml = "<a href='javascript:;' onclick='toggleFavorite("+contact.id+")' class='btn_favo_no'></a>"
                    }

                    var callHistoryTimeFirst = getYear(callHistoryTime[0]);
                    console.log("callHistoryTimeFirst"+ callHistoryTimeFirst);
                    console.log("imsitime"+ imsitime);
                    if(searchImsitime!=callHistoryTimeFirst) {
                        liEl += "<li class='year'>"+callHistoryTimeFirst+"</li>";

                        searchImsitime=callHistoryTimeFirst;
                        console.log("추가");
                    }

                    liEl += "<li data-id='"+ contact.id +"' data-contact='"+JSON.stringify(contact) +"'>";
                    liEl += "<span class='portrait'><img src='"+getThumbImage(contact.thumbnail)+"'></span>";
                    liEl += favoHtml;
                    liEl += "<h4 class='history_cell'>"+contact.displayName+callCountHtml+"</h4>";
                    liEl += "<p class='history_cell "+historyOneHtml+"'>"+callHistory[i]["type"]+" "+callHistory[i]["num"]+"</p><button type='button' class='btn_call'></button>";
                    liEl += "<ul class='history_call'>";
                    liEl += callHistoryTimeHtml;
                    liEl += "</ul>";
                    liEl += "<ul class='history_call others_history'>";
                    liEl += callHistoryTimeHtmlOthers;
                    liEl += "</ul>";
                    liEl += "</li>";


                    if(isIOS12()){
                        $(".list_sch_history").append(liEl);
                    }else{
                        data.push(liEl);
                    }
                }
            }
        }
        if(isIOS12()){
        }else{

            var offset = 31+61;
            //alert("Not ios12");
            if(!nullcheck(clusterizeHistorySearch)){
                clusterizeHistorySearch.destroy(true);
            }
            clusterizeHistorySearch = new Clusterize({
                rows_in_block: 50,
                blocks_in_cluster: 5,
                offset: offset,
                rows: data,
                scrollId: 'scrollAreaSearchHistory',
                contentId: 'contentAreaSearchHistory'
            });
        }
        searchImsitime="";
    }else{
        $(".list_sch_history").empty();
    }
}
function selectDialNumber(contacts,keyword){
    console.log("selectDialNumber : "+ JSON.stringify(contacts)+"::"+keyword);


    var phNumArrHtml = "";
    console.log("selectDialNumber length: "+ contacts.length);
    for (var i = 0; i < contacts.length; i++) {
        var k = i+1;
        var telephone = contacts[i].phoneNumbers.find(item => new RegExp(keyword).test(item.normalizedNumber));
        //var type = telephone.type;
        //phNumArrHtml += "<input type='radio' name='sel_num' id='sel_num_"+k+"' value="+JSON.stringify(telephone)+"><label for='sel_num_"+k+"'>"+type+" "+telephone.normalizedNumber+"</label>";
        console.log("telephone.normalizedNumber: "+ telephone.normalizedNumber);


        var telephoneNumber = telephone.normalizedNumber
            var telephoneHtml = "";

        var index = telephoneNumber.indexOf(keyword);
        console.log('index = ' + JSON.stringify(index));
        if (index >= 0) {
            telephoneNumber = telephoneNumber.substring(0,index) + "<span>" + telephoneNumber.substring(index,index+keyword.length) + "</span>" + telephoneNumber.substring(index + keyword.length);
            telephoneHtml = telephoneNumber;
        }

        phNumArrHtml += "<li class='dial_pad_list' data-id='"+ contacts[i].id +"' data-telephonenumber='"+telephone.normalizedNumber+"'>";
        phNumArrHtml += "<span class='portrait'><img src='"+getThumbImage(contacts[i].thumbnail)+"'></span>";
        phNumArrHtml += "<h4>"+contacts[i].displayName+"</h4>";
        phNumArrHtml += "<p>"+telephone.type+" "+telephoneHtml+"</p>";
        phNumArrHtml += "</li>";
    }

    //console.log("phNumArrHtml : "+ phNumArrHtml);
    /*
    var buttonHtml = "";
    //var serverData = window.localStorage.getArray("serverData");
    if(cust_func_code == 1){
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_02'><img src='img/icon_telephone.png'>통화</button>";
    }else if(cust_func_code == 2){
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_01'><img src='img/icon_mobile.png'>통화</button>";
    }else{
        buttonHtml = "<div class='calling_btn'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_01'><img src='img/icon_mobile.png'>통화</button>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_02'><img src='img/icon_telephone.png'>통화</button>";
    }
    */
    var alertEl = "<div class='bg_calling on'>";
    alertEl += "<div class='pop_calling'>";
    alertEl += "<h3>검색결과<button type='button' class='close_calling'><img src='img/btn_close_wh.png'></button></h3>"
    alertEl += "<div class='phone_nums'>";
    alertEl += "<ul class='list'>";
    alertEl += phNumArrHtml;
    alertEl += "</ul>";
    alertEl += "</div>";
    alertEl += "</div>";
    alertEl += "</div>";
    alertEl += "</div>";
    $(".ui-mobile-viewport").append(alertEl);
    $("#sel_num_1").prop("checked", true);
}
function selectCall(contact,num,type){
    console.log("conatct : "+ JSON.stringify(contact));
    var cust_func_code = serverData.cust_func_code
    if(contact.phoneNumbers.length == 1){
        //if(cust_func_code == 1){//클릭콜
            console.log("contact_id:"+ contact.id);
            //되는거
            //clickToCall(contact.id, contact.phoneNumbers[0].normalizedNumber,contact.phoneNumbers[0].type);
           // clickToCall(id, contact.phoneNumbers[0].normalizedNumber,contact.phoneNumbers[0].type);
           // return;
        //}else if(cust_func_code == 2){//콜백
          //  callBack(id, contact.phoneNumbers[0].normalizedNumber,contact.phoneNumbers[0].type);
            //callBack(contact.id, contact.phoneNumbers[0].normalizedNumber,contact.phoneNumbers[0].type);
            //return;
        //}

    }
    //두개 다 일때
    var phNumArr = contact.phoneNumbers;
    var phNumArrHtml = "";
    if(nullcheck(num)){
        for (var j = 0; j < phNumArr.length; j++) {
            var k = j+1;
            console.log("phNumArr[j]"+JSON.stringify(phNumArr[j]));
            phNumArrHtml += "<input type='radio' name='sel_num' id='sel_num_"+k+"' value="+JSON.stringify(phNumArr[j])+"><label for='sel_num_"+k+"'>"+phNumArr[j].type+" "+phNumArr[j].number+"</label>";
        }
    }else{
        var anonymousPhoneNumber = {
            number:num,
            normalizedNumber:num,
            type:"기타"
        };

        phNumArrHtml = "<input type='radio' name='sel_num' id='sel_num_1' value="+JSON.stringify(anonymousPhoneNumber)+"><label for='sel_num_1'>"+type+" "+num+"</label>";
    }
    var buttonHtml = "";
    //var serverData = window.localStorage.getArray("serverData");
    
    if (settingData.cust_func_code  == "1") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_01'><img src='img/biz_call_btn.png'>통화(C.B)</button>";
    } else if(settingData.cust_func_code == "2") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_03'><img src='img/biz_call_btn.png'>통화(C.T)</button>";
    } else if(settingData.cust_func_code == "3") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='" + contact.id + "' class='btn_calling_03'><img src='img/icon_telephone.png'>안심통화</button>";
    } else if(settingData.cust_func_code == "4") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='" + contact.id + "' class='btn_calling_03'><img src='img/icon_telephone.png'>안심통화</button>";
        buttonHtml += "<button type='button' data-id='" + contact.id + "' class='btn_calling_02'><img src='img/icon_mobile.png'>휴대폰통화</button>";
    } else if(settingData.cust_func_code == "5") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='" + contact.id + "' class='btn_calling_03'><img src='img/icon_telephone.png'>안심통화</button>";
        buttonHtml += "<button type='button' data-id='" + contact.id + "' class='btn_calling_02'><img src='img/icon_mobile.png'>5G통화</button>";
    } else if(settingData.cust_func_code == "6") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_01'><img src='img/biz_call_btn.png'>통화(C.B)</button>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_03'><img src='img/biz_call_btn.png'>통화(C.T)</button>";
    } else if(settingData.cust_func_code == "7") {
        buttonHtml = "<div class='calling_btn'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_01'><img src='img/biz_call_btn.png'>통화(C.B)</button>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_03'><img src='img/biz_call_btn.png'>통화(C.T)</button>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_02'><img src='img/icon_mobile.png'>휴대폰통화</button>";
    } else if(settingData.cust_func_code == "8") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='" + contact.id + "' class='btn_calling_03'><img src='img/icon_telephone.png'>내선통화</button>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_02'><img src='img/icon_mobile.png'>휴대폰통화</button>";
    } else if(settingData.cust_func_code == "9") {
        buttonHtml = "<div class='calling_btn btn_01'>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_01'><img src='img/biz_call_btn.png'>통화(C.B)</button>";
        buttonHtml += "<button type='button' data-id='"+contact.id +"' class='btn_calling_02'><img src='img/icon_mobile.png'>휴대폰통화</button>";
    }

    var alertEl = "<div class='bg_calling on'>";
    alertEl += "<div class='pop_calling'>";
    alertEl += "<h3>" + contact.displayName + "<button type='button' class='close_calling'><img src='img/btn_close_wh.png'></button></h3>"
    alertEl += "<div class='phone_nums'>";
    alertEl += phNumArrHtml;
    alertEl += "</div>";
    alertEl += buttonHtml;
    alertEl += "</div>"; // end of div class='calling_btn' in buttonHtml
    alertEl += "</div>"; // end of div class='pop_calling'
    alertEl += "</div>"; // end of div class='bg_calling'
    $(".ui-mobile-viewport").append(alertEl);
    $("#sel_num_1").prop("checked", true);

    if($('.bg_calling div.calling_btn>button').length == 1 
        && $('.bg_calling div.phone_nums>input[type=radio]').length == 1
    ){
        $('.bg_calling div.calling_btn>button:eq(0)').trigger('click');
    }
}


// 전화번호 직접입력했을대 팝업
function viewCallInfo(number){

    var name = "";
    var type = "";

    // 주소록에서 찾기
    for(var key in user_map){
        var user = user_map[key];
        if ( user.mobile_no === number ) {
            type = "휴대전화";
            name = user.name
            break;
        }
        if ( user.etc_no === number ) {
            type = "기타전화";
            name = user.name
            break;
        }
        if ( user.cid_no === number ) {
            type = "내선전화";
            name = user.name
            break;
        }
    }

    // 주소록에 없으면 전화번호부에서 찾기
    if ( name == "" ) {
        var searchContactByNumber = newContact.filter(({phoneNumbers}) => {
            //"null check"
            if( nullcheck(phoneNumbers)){
                return
            }else{
                // return phoneNumbers.some(item => new RegExp(number).test(item.normalizedNumber))
                return phoneNumbers.some(item => number === item.normalizedNumber)
            }
        })

        if ( searchContactByNumber.length > 0) {
            name = searchContactByNumber[0].displayName;
            var phonenumber = searchContactByNumber[0].phoneNumbers.find(item => number === item.normalizedNumber);
            type = phonenumber.type;
        }
    }





    name = emptyToSpace(name);
    type = emptyToSpace(type);

    //두개 다 일때
    var phNumArrHtml = "";
    phNumArrHtml = "<input type='radio' name='sel_num' id='sel_num_1'><label for='sel_num_1'>"+type+" "+number+"</label>";

    var buttonHtml = "";
    buttonHtml = "<div class='calling_btn btn_01'>";
    buttonHtml += "<button type='button'>다이얼한 번호로 연결됩니다.</button>";


    var alertEl = "<div class='bg_calling bg_calling_02 on'>";
    alertEl += "<div class='pop_calling'>";
    alertEl += "<h3>" + name + "<button type='button' class='close_calling'><img src='img/btn_close_wh.png'></button></h3>"
    alertEl += "<div class='phone_nums'>";
    alertEl += phNumArrHtml;
    alertEl += "</div>";
    alertEl += buttonHtml;
    alertEl += "</div>";
    alertEl += "</div>";
    alertEl += "</div>";
    $(".ui-mobile-viewport").append(alertEl);
    $("#sel_num_1").prop("checked", true);
}


function deleteHistory(id){
    //alert('deleteHistory ::'+id);
    console.log('deleteHistory ::'+id);
    var callHistory = window.localStorage.getArray("callHistory"); //빈배열
    console.log('deleteHistory000 ::'+JSON.stringify(callHistory));


    var newCallHistory = callHistory.filter(x => {
        return x.historyId != id;
      })

    // index = callHistory.map(function(item) {
    //     return item.historyId
    // }).indexOf(id);


    // var index = callHistory.map(x => {
    //     return x.historyId;
    // }).indexOf(id);
    //console.log('deleteHistory ::'+index);
    //callHistory.splice(index, 1);
    console.log('deleteHistory ::'+JSON.stringify(newCallHistory));


    window.localStorage.setArray("callHistory",newCallHistory);

    setTimeout(() => {
        if(newCallHistory.length>0){
            $(".list_history").empty();
            printHistory();
            /*
            $(".list_history").find("[data-historyid='"+ id +"']").remove();

            if(!isIOS12()){
                clusterizeHistory.refresh(true);

                //console.log("article_favorites"+document.querySelector(".article_favorites").offsetHeight);
                //var offset = 24+31+61;
                //console.log('toggleFavorite offset = ' + offset);
                //clusterizeHistory.setTopHeightOffset(offset);
            }
            */
        }else{
            $(".list_history").empty();
        }
    }, 100);

}

function addCallHistory(id, num, type) {
    console.log('addCallHistory ::' + id + "::" + num);

    readFile("user_map.json", function (data) {
        var callHistory = window.localStorage.getArray("callHistory"); //빈배열
        
        userMap = JSON.parse(data||'{}');

        var currentdate = new Date();
        var datetime = currentdate.getFullYear() + "년 " +
            (currentdate.getMonth() + 1) + "월 " +
            currentdate.getDate() + "일 " +
            (currentdate.getHours() < 10 ? '0' : '') + currentdate.getHours() + ":" +
            (currentdate.getMinutes() < 10 ? '0' : '') + currentdate.getMinutes() + ":" +
            (currentdate.getSeconds() < 10 ? '0' : '') + currentdate.getSeconds();
    
    
        var historyId = "" + currentdate.getFullYear() + (currentdate.getMonth() + 1) + currentdate.getDate() + currentdate.getHours() + currentdate.getMinutes() + currentdate.getSeconds();
    
        var callContact = {};
        callContact["historyId"] = $.trim(historyId);
        callContact["id"] = $.trim(id);
        callContact["num"] = $.trim(num);
        callContact["type"] = $.trim(type);
        callContact["time"] = [datetime];
    
        if ($.trim(id).startsWith("-1")) {
            var searchContactByNumber = newContact.filter(({ phoneNumbers }) => {
                if (nullcheck(phoneNumbers)) {
                    return;
                } else {
                    return phoneNumbers.find(item => $.trim(num) === getRemovePlusEightTwo(item.normalizedNumber));
                }
            });
    
            // userMap의 구조를 newContact와 유사하게 변환
            var userMapArray = Object.values(userMap); // 수정: userMap을 배열로 변환
            var userMapContact = userMapArray.find(item => { // 수정: userMapArray에서 번호를 찾음
                if (!nullcheck(item.phoneNumbers)) {
                    return item.phoneNumbers.some(phone => $.trim(num) === getRemovePlusEightTwo(phone.normalizedNumber));
                }
            });
    
            if (searchContactByNumber.length === 0 && userMapContact) { // 수정: userMap에서 번호를 찾았을 경우
                searchContactByNumber = [userMapContact];
            }
    
            if (searchContactByNumber.length > 0) {
                id = searchContactByNumber[0].id;
    
                console.log('searchContactByNumber id::' + id);
                var phoneNumber = searchContactByNumber[0].phoneNumbers[0];
    
                var type = phoneNumber.type;
                console.log('searchContactByNumber ::' + phoneNumber.normalizedNumber);
                console.log('searchContactByNumber ::' + searchContactByNumber[0].displayName);
                callContact["type"] = $.trim(type);
    
                callContact["id"] = $.trim(id);
            }
        }
    
        if (nullcheck(callHistory)) {
            var callHistory = new Array(); //빈배열
    
            callHistory.unshift(callContact);
            console.log('addCallHistory1' + callHistory.length);
        } else {
    
            console.log('addCallHistory2 ::' + id + "::" + num);
            console.log('addCallHistory2' + callHistory.length);
            var firstCallHistory = callHistory[0];
            console.log('firstCallHistory = ' + firstCallHistory);
    
            var firstCallHistoryId = firstCallHistory["id"];
            var firstCallHistoryNum = firstCallHistory["num"];
            var firstCallHistoryYear = getYear(firstCallHistory["time"][0]);
    
            var firstCalHistoryTime = firstCallHistory["time"];
    
            callContactTimeDay = getYear(callContact["time"][0]);
    
            if (firstCallHistoryNum == $.trim(num) && firstCallHistoryYear == callContactTimeDay) {
                callContact["time"].push.apply(callContact["time"], firstCalHistoryTime);
    
                for (var i = 0; i < callContact["time"].length; i++) {
                    //console.log('firstCalHistoryTime3 = ' + callContact["time"][i]);
                }
    
                callHistory[0] = callContact;
            } else {
                callHistory.unshift(callContact);
                if (callHistory.length >= 500) {
                    callHistory.pop();
                }
            }
        }
    
        window.localStorage.setArray("callHistory", callHistory);
    
        if ($('.ui-page-active').attr('id') == "history") {
            setTimeout(() => {
                $(".list_history").empty();
                printHistory();
            }, 5000);
        }
    });
}

