var dummyEl;
var getDummyEl = function () {
    if (!dummyEl) {
        dummyEl = document.createElement("div");
    }
    return dummyEl;
};

/**
 * Random templating util extracted from the piskel codebase.
 */
var replace = function (template, dict) {
    for (var key in dict) {
        if (dict.hasOwnProperty(key)) {
            var value = sanitize(dict[key]);
            template = template.replace(new RegExp('\\{\\{' + key + '\\}\\}', 'g'), value);
        }
    }
    return template;
};
/**
 * String sanitizer for the template values.
 */
var sanitize = function (string) {
    var dummyEl = getDummyEl();

    // Apply the unsafe string as text content and
    dummyEl.textContent = string;
    var sanitizedString = dummyEl.innerHTML;
    dummyEl.innerHTML = '';

    return sanitizedString;
};
//댓글 UI
var getReplyCard = function (data, session, imgUrl, session_nick, key) {

    if(typeof data.imgkey === 'string'){

        var year = data.imgkey_created_at.substring(2,4);
        var month = data.imgkey_created_at.substring(5,7);
        var day = data.imgkey_created_at.substring(8,10);

        // ai 이미지경로
        if(data.type == 1){
            imgUrl = `/outputs/txt2img/20${year}-${month}-${day}/${data.imgkey}.png`;
        }else{
            imgUrl = `/upload/${year}/${month}/${day}/${data.imgkey}.png`;
        }
        IMEAGE_URL ='class="img-follow rounded-circle" src="'+imgUrl+'"';

    }else{
        IMEAGE_URL = 'class="img-follow-null rounded-circle" src="/img/pixelog-profile.png" ';
    }

    //로그인 유저
    if(session !== 'null'){

        //글작성자도 삭제가능하도록
        //댓글 작성자
        if(data.uid == session){
            var template = '<div id="media{{id}}" class="media align-items-center">\
                <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                  <span class="card-follow-container d-inline-block align-middle position-relative">\
                    <img '+IMEAGE_URL+'/>\
                    <div class="pixelog-img-profile-follow rounded-circle text-center align-middle"></div>\
                    </span>\
                  </a>\
                  <div class="ms-2 media-body">\
                    <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                        <span class="card-follow-body d-inline-block font-weight-bold">\
                          <span class="text-truncate text-dark mobile-title">{{nick}}</span>\
                        </span>\
                      </a>\
                    <span id="reply{{id}}">'+data.reply+'</span>\
                  </div>\
              </div>\
                <div id="media_bottom{{id}}" class="mb-3" style="margin-left:45px">\
                <span id="reply_time{{id}}"class="text-secondary" style="font-size:10px">'+timeBefore(data.updated_at)+'</span>\
                <svg id="stepIcon{{id}}" onclick="btnAdd_step({{id}},\''+session+'\',\''+imgUrl+'\',\''+session_nick+'\',\''+key+'\');" width="1em" height="1em" viewBox="0 0 16 16" class="ms-2 stepIcon bi bi-chat-square-text cursor-pointer" fill="currentColor" xmlns="http://www.w3.org/2000/svg">\
                  <path fill-rule="evenodd" d="M14 1H2a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h2.5a2 2 0 0 1 1.6.8L8 14.333 9.9 11.8a2 2 0 0 1 1.6-.8H14a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1zM2 0a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2.5a1 1 0 0 1 .8.4l1.9 2.533a1 1 0 0 0 1.6 0l1.9-2.533a1 1 0 0 1 .8-.4H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z"/>\
                  <path fill-rule="evenodd" d="M3 3.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 6a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9A.5.5 0 0 1 3 6zm0 2.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z"/>\
                </svg>\
                <span aria-haspopup="true" aria-expanded="false" data-bs-toggle="dropdown">\
                  <svg width="1em" height="1em" viewBox="0 0 16 16" class="ms-2 bi bi-three-dots position-relative dropdown-toggle cursor-pointer" fill="currentColor" xmlns="http://www.w3.org/2000/svg">\
                    <path fill-rule="evenodd" d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/>\
                  </svg>\
                </span>\
                <div class="dropdown-menu text-center">\
                  <a class="dropdown-item cursor-pointer" onclick="action_reply(\'edit\', {{id}})">수정</a>\
                  <a class="dropdown-item cursor-pointer" onclick="action_reply(\'delete\', {{id}})">삭제</a>\
                </div>\
                </div>\
              ';
            //로그인유저-권한없음
        }else{
            var template = '<div class="media align-items-center">\
                <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                  <span class="card-follow-container d-inline-block align-middle position-relative">\
                    <img '+IMEAGE_URL+'/>\
                    <div class="pixelog-img-profile-follow rounded-circle text-center align-middle"></div>\
                    </span>\
                  </a>\
                  <div class="ms-2 media-body">\
                    <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                        <span class="card-follow-body d-inline-block font-weight-bold">\
                          <span class="text-truncate text-dark mobile-title">{{nick}}</span>\
                        </span>\
                      </a>\
                    <span id="reply{{id}}">'+data.reply+'</span>\
                  </div>\
              </div>\
                <div id="media_bottom{{id}}" class="mb-3" style="margin-left:45px">\
                  <span class="text-secondary" style="font-size:10px">'+timeBefore(data.updated_at)+'</span>\
                <svg id="stepIcon{{id}}" onclick="btnAdd_step({{id}},\''+session+'\',\''+session_profileKey+'\',\''+session_nick+'\',\''+key+'\');" width="1em" height="1em" viewBox="0 0 16 16" class="ms-2 stepIcon bi bi-chat-square-text cursor-pointer" fill="currentColor" xmlns="http://www.w3.org/2000/svg">\
                  <path fill-rule="evenodd" d="M14 1H2a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h2.5a2 2 0 0 1 1.6.8L8 14.333 9.9 11.8a2 2 0 0 1 1.6-.8H14a1 1 0 0 0 1-1V2a1 1 0 0 0-1-1zM2 0a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h2.5a1 1 0 0 1 .8.4l1.9 2.533a1 1 0 0 0 1.6 0l1.9-2.533a1 1 0 0 1 .8-.4H14a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z"/>\
                  <path fill-rule="evenodd" d="M3 3.5a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9a.5.5 0 0 1-.5-.5zM3 6a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 0 1h-9A.5.5 0 0 1 3 6zm0 2.5a.5.5 0 0 1 .5-.5h5a.5.5 0 0 1 0 1h-5a.5.5 0 0 1-.5-.5z"/>\
                </svg>\
                </div>\
              ';
        }

        //비로그인
    }else{
        var template = '<div class="media align-items-center">\
              <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                <span class="card-follow-container d-inline-block align-middle position-relative">\
                  <img '+IMEAGE_URL+'/>\
                  <div class="pixelog-img-profile-follow rounded-circle text-center align-middle"></div>\
                  </span>\
                </a>\
                <div class="ms-2 media-body">\
                  <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                      <span class="card-follow-body d-inline-block font-weight-bold">\
                        <span class="text-truncate text-dark mobile-title">{{nick}}</span>\
                      </span>\
                    </a>\
                  <span >'+data.reply+'</span>\
                </div>\
            </div>\
            <div id="media_bottom{{id}}" class="mb-3" style="margin-left:45px">\
              <span class="text-secondary" style="font-size:10px">'+timeBefore(data.updated_at)+'</span>\
            </div>\
            ';
    }

    return replace(template, {
        imgkey: data.imgkey,
        nick: data.nick,
        reply: data.reply,
        step: data.step,
        uid: data.uid,
        date: data.updated_at,
        id: data.id
    });

};

//대댓글 UI
var getReplyCard_step = function (data, session) {

    if(typeof data.imgkey === 'string'){
        var year = data.imgkey_created_at.substring(2,4);
        var month = data.imgkey_created_at.substring(5,7);
        var day = data.imgkey_created_at.substring(8,10);

        // ai 이미지경로
        if(data.type == 1){
            IMEAGE_URL = `/outputs/txt2img/20${year}-${month}-${day}/${data.imgkey}.png`;
        }else{
            IMEAGE_URL = `/upload/${year}/${month}/${day}/${data.imgkey}.png`;
        }
        IMEAGE_URL ='class="img-follow rounded-circle" src="'+IMEAGE_URL+'"';

    }else{
        IMEAGE_URL = 'class="img-follow-null rounded-circle" src="/img/pixelog-profile.png" ';
    }

    //로그인 유저
    if(session !== 'null'){

        //글작성자도 삭제가능하도록
        //댓글 작성자
        if(data.uid == session){

            var template = '<div id="media{{id}}" class="media align-items-center mt-3">\
                <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                  <span class="card-follow-container d-inline-block align-middle position-relative">\
                    <img '+IMEAGE_URL+'/>\
                    <div class="pixelog-img-profile-follow rounded-circle text-center align-middle"></div>\
                    </span>\
                  </a>\
                  <div class="ms-2 media-body">\
                    <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                        <span class="card-follow-body d-inline-block font-weight-bold">\
                          <span class="text-truncate text-dark mobile-title">{{nick}}</span>\
                        </span>\
                      </a>\
                    <span id="reply{{id}}">'+data.reply+'</span>\
                  </div>\
              </div>\
                <div id="media_bottom{{id}}" class="mb-3" style="margin-left: 45px;">\
                  <span class="text-secondary" style="font-size:10px">'+timeBefore(data.updated_at)+'</span>\
                  <span aria-haspopup="true" aria-expanded="false" data-bs-toggle="dropdown">\
                    <svg width="1em" height="1em" viewBox="0 0 16 16" class="ms-2 bi bi-three-dots position-relative dropdown-toggle cursor-pointer" fill="currentColor" xmlns="http://www.w3.org/2000/svg">\
                      <path fill-rule="evenodd" d="M3 9.5a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3zm5 0a1.5 1.5 0 1 1 0-3 1.5 1.5 0 0 1 0 3z"/>\
                    </svg>\
                  </span>\
                  <div class="dropdown-menu text-center">\
                    <a class="dropdown-item cursor-pointer" onclick="action_reply(\'edit\', {{id}})">수정</a>\
                    <a class="dropdown-item cursor-pointer" onclick="action_reply(\'delete\', {{id}})">삭제</a>\
                  </div>\
                </div>\
              ';
            //로그인유저
        }else{

            var template = '<div id="media{{id}}" class="media align-items-center mt-3">\
                <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                  <span class="card-follow-container d-inline-block align-middle position-relative">\
                    <img '+IMEAGE_URL+'/>\
                    <div class="pixelog-img-profile-follow rounded-circle text-center align-middle"></div>\
                    </span>\
                  </a>\
                  <div class="ms-2 media-body">\
                    <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                        <span class="card-follow-body d-inline-block font-weight-bold">\
                          <span class="text-truncate text-dark mobile-title">{{nick}}</span>\
                        </span>\
                      </a>\
                    <span id="reply{{id}}">'+data.reply+'</span>\
                  </div>\
              </div>\
              <div class="mb-3" style="margin-left:45px">\
                <span class="text-secondary" style="font-size:10px">'+timeBefore(data.updated_at)+'</span>\
              </div>\
              ';
        }
        //비로그인
    }else{

        var template = '<div class="media align-items-center mt-3">\
              <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                <span class="card-follow-container d-inline-block align-middle position-relative">\
                  <img '+IMEAGE_URL+'/>\
                  <div class="pixelog-img-profile-follow rounded-circle text-center align-middle"></div>\
                  </span>\
                </a>\
                <div class="ms-2 media-body">\
                  <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
                      <span class="card-follow-body d-inline-block font-weight-bold">\
                        <span class="text-truncate text-dark mobile-title">{{nick}}</span>\
                      </span>\
                    </a>\
                  <span>'+data.reply+'</span>\
                </div>\
            </div>\
            <div class="mb-3" style="margin-left:45px">\
              <span class="text-secondary" style="font-size:10px">'+timeBefore(data.updated_at)+'</span>\
            </div>\
            ';

    }

    return replace(template, {
        imgkey: data.imgkey,
        nick: data.nick,
        step: data.step,
        uid: data.uid,
        reply: data.reply,
        id: data.id
    });

}

//대댓글 INPUT
var getReplyCard_step_input = function (data) {

    var template = '<div id="media_clone_{{id}}" class="media align-items-center mt-3">\
            <a class="text-decoration-none card-preview-link" href="/user/{{uid}}">\
              <span class="card-follow-container d-inline-block align-middle position-relative">\
                <img '+IMEAGE_URL+' />\
                <div class="pixelog-img-profile-follow rounded-circle text-center align-middle"></div>\
                </span>\
                  <span class="ms-2 card-follow-body d-inline-block align-middle">\
                    <div class="text-truncate text-dark mobile-title">{{nick}}</div>\
                  </span>\
              </a>\
              <div class="ms-2 media-body pe-3">\
              <input id="reply_input_step" type="text" class="form-control" placeholder="댓글 추가">\
              </div>\
          </div>\
            <div id="reply_input_button_step" class="clearfix text-end d-none mt-2 pe-3">\
              <button id="reply_cancel_step" onclick="btnAdd_step({{id}}, \'null\', \'null\', \'null\')" class="btn btn-sm btn-primary">취소</button>\
              <button id="reply_submit_step" onclick="btnAdd(\'{{key}}\',\'{{uid}}\',2,{{id}})" class="btn btn-sm btn-primary disabled cursor-default">완료</button>\
            </div>\
          ';
    return replace(template, {
        nick: data.nick,
        step: data.step,
        uid: data.uid,
        id: data.id,
        key: data.key,
    });

}


function btnLike(key, uid){

    $('#sp'+key).removeClass('d-none');
    $('#id'+key).addClass('d-none');

    $.ajax({
        type:"POST",
        url: "/user/likes",
        data:{key:key,uid:uid},
        success : function(data) {
            $('#sp'+key).addClass('d-none');
            $('#id'+key).removeClass('d-none');

            if(data == 'N'){
                $('#loginModal').modal('show');
            }else if(data == 'C'){
                // $('#id'+key).removeClass('likes-icon');
                // $('#id'+key).addClass('likes-no-icon');
            }else if(data == 'Y'){
                // $('#id'+key).removeClass('likes-no-icon');
                // $('#id'+key).addClass('likes-icon');
            }

        },
        complete: function(data) {
            if(data.responseText == 'Y'){
                //푸시알림 발송
                $.ajax({
                    type:"POST",
                    url: "/push/likes",
                    data:{key:key,uid:uid},
                    success : function(data) {
                    }
                });
            }
        }
    });
}

function ViewbtnLike(key, uid){

    $('#sp'+key).removeClass('d-none');
    $('#id'+key).addClass('d-none');

    $.ajax({
        type:"POST",
        url: "/user/likes",
        data:{key:key,uid:uid},
        success : function(data) {

            $('#sp'+key).addClass('d-none');
            $('#id'+key).removeClass('d-none');

            if(data == 'N'){
                $('#loginModal').modal('show');
            }else if(data == 'C'){
                // $('#id'+key).removeClass('view-likes-icon1');
                // $('#id'+key).addClass('view-likes-no-icon1');
            }else if(data == 'Y'){
                // $('#id'+key).removeClass('view-likes-no-icon1');
                // $('#id'+key).addClass('view-likes-icon1');
            }

        },
        complete: function(data) {
            if(data.responseText == 'Y'){
                //푸시알림 발송
                $.ajax({
                    type:"POST",
                    url: "/push/likes",
                    data:{key:key,uid:uid},
                    success : function(data) {
                    }
                });
            }
        }
    });
}


function btnFollow(uid, fuid){
    $('#btnFollowSpin').removeClass('d-none');
    $('#btnFollowText').addClass('d-none');
    $.ajax({
        type:"POST",
        url: "/user/follow",
        data:{uid:uid,fuid:fuid},
        success : function(data) {
            $('#btnFollowSpin').addClass('d-none');
            $('#btnFollowText').removeClass('d-none');
            if(data == 'N'){
                $('#loginModal').modal('show');
            }else if(data == 'C'){
                $('#btnFollow').removeClass('btn-outline-primary');
                $('#btnFollow').addClass('btn-primary');
                $('#btnFollowText').text('팔로우');
            }else if(data == 'Y'){
                $('#btnFollow').removeClass('btn-primary');
                $('#btnFollow').addClass('btn-outline-primary');
                $('#btnFollowText').text('팔로잉');
            }
        },
        complete: function(data) {
            if(data.responseText == 'Y'){
                //푸시알림 발송
                $.ajax({
                    type:"POST",
                    url: "/push/follower",
                    data:{uid:uid,fuid:fuid},
                    success : function(data) {
                    }
                });
            }
        }
    });
}

//대댓글  btn
function btnAdd_step(id, uid, imgUrl, nick, key){
    //exist
    if($("#media_bottom"+id).find("#media_clone_"+id).length){
        $(".stepIcon").removeClass("d-none");
        $("#media_clone_"+id).remove();
        $("#reply_input_button_step").remove();
    //new
    }else{
        $(".stepIcon").addClass("d-none");
        $("#stepIcon"+id).removeClass("d-none");
        if(typeof imgUrl === 'string'){
            //image
            if(imgUrl){
                IMEAGE_URL ='class="img-follow rounded-circle" src="'+imgUrl+'"';
            }else{
                IMEAGE_URL = 'class="img-follow-null rounded-circle" src="/img/pixelog-profile.png" ';
            }
        }else{
            IMEAGE_URL = 'class="img-follow-null rounded-circle" src="/img/pixelog-profile.png" ';
        }
        var data = new Object();
        data.id = id;
        data.uid = uid;
        data.imgUrl = imgUrl;
        data.nick = nick;
        data.key = key;
        var template = getReplyCard_step_input(data);
        $("#media_bottom"+id).append(template);
        $("#reply_input_step").focus();
    }
}
//댓글 등록 버튼
function btnAdd(key, session, step, parent, session_profileKey, session_nick){
    if(step == 1){
        var reply = $("#reply_input").val();
    }else if(step == 2){
        var reply = $("#reply_input_step").val();
    }
    var loadcontainer = '<div id="loadcontainer" class="spin-container pb-3 mb-3">'
        +'<div class="spinner-border" style="width: 2rem; height: 2rem;" role="status"></div>'
        +'</div>';
    var container = document.querySelector('#reply_area');
    if(reply == ''){
        return;
    }
    $.ajax({
        type:"POST",
        url: "/reply/insert_reply",
        data:{key:key,uid:session,reply:reply,step:step,parent:parent},
        success : function(data) {
            if(data == 'N'){
                $('#loginModal').modal('show');
            }else{
                var response = JSON.parse(data);
                $("#reply_cnt").text(response.cnt);
                if(response.cnt == 1){
                    $("#empty_area").remove();
                }
                if(step == 1){
                    document.getElementById('reply_input').value = '';
                }else if(step == 2){
                    document.getElementById('reply_input_step').value = '';
                }
                addReply(response.data, session, step, parent, session_profileKey, session_nick, key);
            }
        },
        error: function (e){
            console.error("btnAdd failed");
            return;
        },
        beforeSend: function() {
            if(step == 1){
                $("#reply_area").after(loadcontainer);
            }else{
                $("#media_bottom"+parent).after(loadcontainer);
            }
        },
        complete: function() {
            $("#loadcontainer").addClass("d-none");
            $("#loadcontainer").remove();
            $("#reply_submit").addClass('disabled');
            if(step == 1){
                $("#reply_area").scrollTop($("#reply_area")[0].scrollHeight);
            }
            if(session !== 'null'){
                //푸시알림 발송
                $.ajax({
                    type:"POST",
                    url: "/push/reply",
                    data:{key:key,uid:session,reply:reply},
                    success : function(data) {
                    }
                });
            }
        }
    });
}
//댓글 등록 버튼 PROC
function addReply(data, session, step, parent, session_profileKey, session_nick, key) {
    if (!data) {
        return;
    }
    var container = document.querySelector('#reply_area');
    var container_step = document.querySelector("#media_bottom"+parent);
    var dummyEl = getDummyEl();
    if(step == 1){
        dummyEl.innerHTML = data.reduce(function (markup, data) {
            return markup + getReplyCard(data, session, session_profileKey, session_nick, key);
        }, '');
        while (dummyEl.firstChild) {
            container.appendChild(dummyEl.firstChild);
        }
    }else if(step == 2){
        dummyEl.innerHTML = data.reduce(function (markup, data) {
            return markup + getReplyCard_step(data, session, session_profileKey, session_nick, key);
        }, '');
        while (dummyEl.firstChild) {
            container_step.appendChild(dummyEl.firstChild);
            $("#media_clone_"+parent).remove();
            $("#reply_input_button_step").remove();
            $(".stepIcon").removeClass("d-none");
        }
    }
}
//뷰페이지 정보 수정 버튼 액션
function action_piskel(key, ispublic, isdiary){
    var name = $("#name"+key).text();
    var description = $("#description"+key).text();
    $('#edit_info_name').val(htmlspecialchars_decode(name, 'ENT_HTML_QUOTE_SINGLE'));
    $('#edit_info_description').val(htmlspecialchars_decode(description, 'ENT_HTML_QUOTE_SINGLE'));
    $("#edit_info_submit").attr("onclick", "action_piskel_proc(\'"+key+"\',\'"+ispublic+"\',\'"+isdiary+"\')");

    if(ispublic === '1'){
        $("input:checkbox[id='edit_info_public']").prop("checked", true);
    }else{
        $("input:checkbox[id='edit_info_public']").prop("checked", false);
    }

    if(isdiary === '1'){
        $("input:checkbox[id='edit_info_diary']").prop("checked", true);
    }else{
        $("input:checkbox[id='edit_info_diary']").prop("checked", false);
    }
    $('#edit_info').modal('show');
}
//뷰페이지 정보 수정 버튼 PROC
function action_piskel_proc(key, ispublic, isdiary){
    var name = $("#edit_info_name").val();
    var description = $("#edit_info_description").val();
    let changePublic, changeDiary;
    if($("input:checkbox[id=edit_info_public]").is(":checked") == true) {
        changePublic = 1;
    }else{
        changePublic = 0;
    }
    if($("input:checkbox[id=edit_info_diary]").is(":checked") == true) {
        changeDiary = 1;
    }else{
        changeDiary = 0;
    }
    var stringByteLength = (function(s,b,i,c){
        for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
        return b
    })(gf_Convert2ByteChar(description));
    if(stringByteLength > 500){
        alert("내용은 500바이트를 넘을 수 없습니다. 현재:"+stringByteLength + " Bytes");
        return false;
    }else{
        //엔터 2개이상일때 1개로
        description = description.replace(/\n$/gm, '');
        $.ajax({
            type:"POST",
            url: "/pixelog/updateInfoAjax/"+key,
            data:{description:gf_Convert2ByteChar2(description), name:name, ispublic:changePublic, isdiary:changeDiary},
            success : function(data) {
                if(data == 'Y'){
                    $('#edit_info').modal('hide');
                    if(Number(ispublic) !== changePublic || Number(isdiary) !== changeDiary ){
                        location.reload();
                    }
                    if(description !== null){
                        $("#description"+key).text(description);
                    }
                    if(name !== null){
                        $("#name"+key).text(name);
                    }
                }else if(data == 'YD'){
                    $('#edit_info').modal('hide');
                    if(Number(ispublic) !== changePublic || Number(isdiary) !== changeDiary ){
                        location.reload();
                    }
                    if(description !== null){
                        $("#description"+key).text(gf_Convert2ByteChar(description));
                    }
                    if(name !== null){
                        $("#name"+key).text(name);
                    }
                }else if(data == 'N'){
                    $('#loginModal').modal('show');
                }else{
                    location.href = '/';
                }
            }
        });
    }
}
function getByteLength(s,b,i,c){
    for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
    return b;
}
//반각->전각
function gf_Convert2ByteChar(x_char) {
    var x_2byteChar = ""; //컨버트된 문자
    //var c = x_char.charCodeAt(0);
    for(var i=0, l=x_char.length; i<l; i++) {
        var c = x_char[i].charCodeAt(0);
        // make sure we only convert half-full width char
        if(32 <= c && c <= 126) {
            //전각으로 변환될수 있는 문자의 범위
            if(c == 32) { //스페이스인경우 ascii 코드 32
                // x_2byteChar += unescape("%uFFFC");
                // x_2byteChar += "ㅤ";
                x_2byteChar += "　";
                // x_2byteChar += " ";
            } else {
                x_2byteChar += unescape("%u"+(c+65248).toString(16));
            }
        }else{
            x_2byteChar += x_char[i];
        }
    }
    return  x_2byteChar;
}

//전각->반각
function gf_Convert2ByteChar2(x_char) {
    var x_2byteChar = new String;
    var len = x_char.length;
    for (var i = 0; i < len; i++) {
        var c = x_char.charCodeAt(i);
        if (c >= 65281 && c <= 65374 && c != 65340) {
            x_2byteChar += String.fromCharCode(c - 65248);
        } else if (c == 8217) {
            x_2byteChar += String.fromCharCode(39);
        } else if (c == 8221) {
            x_2byteChar += String.fromCharCode(34);
        } else if (c == 12288) {
            x_2byteChar += String.fromCharCode(32);
        } else if (c == 65507) {
            x_2byteChar += String.fromCharCode(126);
        } else if (c == 65509) {
            x_2byteChar += String.fromCharCode(92);
        } else {
            x_2byteChar += x_char.charAt(i);
        }
    }
    return x_2byteChar;
}
//댓글영역 버튼 액션(수정,삭제)
function action_reply(method, key){
    if(method == 'edit'){
        var description = $("#reply"+key).text();
        $('#edit_reply_description').val(htmlspecialchars_decode(description, 'ENT_HTML_QUOTE_SINGLE'));
        $('#edit_reply').modal('show');
        $("#edit_submit").addClass('disabled');
        document.getElementById('edit_submit').setAttribute('key',key);
    }else if(method == 'delete'){
        $('#delete_reply').modal('show');
        document.getElementById('delete_submit').setAttribute('key',key);
    }else{
        return;
    }
}
//댓글 수정,삭제 PROC(모달에 있음)
function proc_reply(method){
    if(method == 'edit'){
        var description = $("#edit_reply_description").val();
        var key = $("#edit_submit").attr('key');
        var disabled = $("#edit_submit").hasClass('disabled');

        if(description == '' || disabled == true){
            return false;
        }else{
            $.ajax({
                type:"POST",
                url: "/reply/update/"+key,
                data:{description:description},
                success : function(data) {
                    if(data == 'Y'){
                        $('#edit_reply').modal('hide');
                        $("#reply_time"+key).val("지금");
                        $("#reply"+key).text(description);
                    }else if(data == 'N'){
                        $('#loginModal').modal('show');
                    }else{
                        location.href = '/';
                    }
                }
            });
        }
    }else if(method == 'delete'){
        var key = $("#delete_submit").attr('key');
        var cnt = parseInt($("#reply_cnt").text());
        $.ajax({
            type:"POST",
            url: "/reply/delete/"+key,
            data:{description:description},
            success : function(data) {
                if(data == 'Y'){
                    $('#delete_reply').modal('hide');
                    $("#reply_cnt").text(cnt-1);
                    $("#media"+key).remove();
                    $("#media_bottom"+key).remove();
                }else if(data == 'N'){
                    $('#loginModal').modal('show');
                }else{
                    location.href = '/';
                }
            }
        });
    }else{
        return false;
    }
}
//시간계산
function timeBefore(date){
    date = date.replace("-", "/"); // '2019/09/09 17:22'
    //현재시간
    var now = new Date();
    //글쓴 시간
    var writeDay = new Date(date);
    //또는 파라미터로 시간을 넘겨받아서 계산할 수도 있음..
    var minus;
    //현재 년도랑 글쓴시간의 년도 비교
    if(now.getFullYear() > writeDay.getFullYear()){
        minus= now.getFullYear()-writeDay.getFullYear();
        //두개의 차이를 구해서 표시
        res = minus+"년 전";
        return res;
    }else if(now.getMonth() > writeDay.getMonth()){
        //년도가 같을 경우 달을 비교해서 출력
        minus= now.getMonth()-writeDay.getMonth();
        res = minus+"달 전";
        return res;
    }else if(now.getDate() > writeDay.getDate()){
        //같은 달일 경우 일을 계산
        minus= now.getDate()-writeDay.getDate();
        res = minus+"일 전";
        return res;
    }else if(now.getDate() == writeDay.getDate()){
        //당일인 경우에는
        var nowTime = now.getTime();
        var writeTime = writeDay.getTime();
        if(nowTime>writeTime){
            //시간을 비교
            sec = parseInt(nowTime - writeTime) / 1000;
            day = parseInt(sec/60/60/24);
            sec = (sec - (day * 60 * 60 * 24));
            hour = parseInt(sec/60/60);
            sec = (sec - (hour*60*60)); min = parseInt(sec/60);
            sec = parseInt(sec-(min*60));
            if(hour>0){
                //몇시간전인지
                res = hour+"시간 전";
                return res;
            }else if(min>0){
                //몇분전인지
                res = min+"분 전";
                return res;
            }else if(sec>0){
                //몇초전인지 계산
                res = sec+"초 전";
                return res;
            }else{
                res = "지금";
                return res;
            }
        }else{
            res = "지금";
            return res;
        }
    }
}