<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가

// add_stylesheet('css 구문', 출력순서); 숫자가 작을 수록 먼저 출력됨
add_stylesheet('<link rel="stylesheet" href="'.$board_skin_url.'/style.css">', 0);
?>

<section id="bo_w">
    <form name="fwrite" id="fwrite" action="<?php echo $action_url ?>" onsubmit="return fwrite_submit(this);" method="post" enctype="multipart/form-data" autocomplete="off">
    <input type="hidden" name="w" value="<?php echo $w ?>">
    <input type="hidden" name="bo_table" value="<?php echo $bo_table ?>">
    <input type="hidden" name="wr_id" value="<?php echo $wr_id ?>">
    <input type="hidden" name="sca" value="<?php echo $sca ?>">
    <input type="hidden" name="sfl" value="<?php echo $sfl ?>">
    <input type="hidden" name="stx" value="<?php echo $stx ?>">
    <input type="hidden" name="spt" value="<?php echo $spt ?>">
    <input type="hidden" name="sst" value="<?php echo $sst ?>">
    <input type="hidden" name="sod" value="<?php echo $sod ?>">
    <input type="hidden" name="page" value="<?php echo $page ?>">
    <?php
    $option = '';
    $option_hidden = '';
    if ($is_notice || $is_html || $is_secret || $is_mail) { 
        $option = '';
        if ($is_notice) {
            $option .= PHP_EOL.'<li class="chk_box"><input type="checkbox" id="notice" name="notice"  class="selec_chk" value="1" '.$notice_checked.'>'.PHP_EOL.'<label for="notice"><span></span>공지</label></li>';
        }
        if ($is_html) {
            if ($is_dhtml_editor) {
                $option_hidden .= '<input type="hidden" value="html1" name="html">';
            } else {
                $option .= PHP_EOL.'<li class="chk_box"><input type="checkbox" id="html" name="html" onclick="html_auto_br(this);" class="selec_chk" value="'.$html_value.'" '.$html_checked.'>'.PHP_EOL.'<label for="html"><span></span>html</label></li>';
            }
        }
        if ($is_secret) {
            if ($is_admin || $is_secret==1) {
                $option .= PHP_EOL.'<li class="chk_box"><input type="checkbox" id="secret" name="secret"  class="selec_chk" value="secret" '.$secret_checked.'>'.PHP_EOL.'<label for="secret"><span></span>비밀글</label></li>';
            } else {
                $option_hidden .= '<input type="hidden" name="secret" value="secret">';
            }
        }
        if ($is_mail) {
            $option .= PHP_EOL.'<li class="chk_box"><input type="checkbox" id="mail" name="mail"  class="selec_chk" value="mail" '.$recv_email_checked.'>'.PHP_EOL.'<label for="mail"><span></span>답변메일받기</label></li>';
        }
    }
    echo $option_hidden;
    ?>
	
    <div class="form_01 write_div">
        <h2 class="sound_only"><?php echo $g5['title'] ?></h2>

        <?php if ($is_category) { ?>
        <div class="bo_w_select write_div">
            <label for="ca_name" class="sound_only">분류<strong>필수</strong></label>
            <select id="ca_name" name="ca_name" required>
                <option value="">선택하세요</option>
                <?php echo $category_option ?>
            </select>
        </div>
        <?php } ?> 
        
        <?php if ($is_name) { ?>
        <div class="write_div">
            <label for="wr_name" class="sound_only">이름<strong>필수</strong></label>
            <input type="text" name="wr_name" value="<?php echo $name ?>" id="wr_name" required class="frm_input full_input required" maxlength="20" placeholder="이름">
        </div>
        <?php } ?>

        <?php if ($is_password) { ?>
        <div class="write_div">
            <label for="wr_password" class="sound_only">비밀번호<strong>필수</strong></label>
            <input type="password" name="wr_password" id="wr_password" <?php echo $password_required ?> class="frm_input full_input <?php echo $password_required ?>" maxlength="20" placeholder="비밀번호">
        </div>
        <?php } ?>

        <?php if ($is_email) { ?>
        <div class="write_div">
            <label for="wr_email" class="sound_only">이메일</label>
            <input type="email" name="wr_email" value="<?php echo $email ?>" id="wr_email" class="frm_input full_input" email" maxlength="100" placeholder="이메일">
        </div>
        <?php } ?>

        <?php if ($is_homepage) { ?>
        <div class="write_div">
            <label for="wr_homepage" class="sound_only">홈페이지</label>
            <input type="text" name="wr_homepage" value="<?php echo $homepage ?>" id="wr_homepage" class="frm_input full_input" placeholder="홈페이지">
        </div>
        <?php } ?>

        <!--<?php if ($option) { ?>
        <div class="write_div">
            <span class="sound_only">옵션</span>
            <ul class="bo_v_option">
            <?php echo $option ?>
            </ul>
        </div>
        <?php } ?>-->

        <!--<?php for ($i=1; $is_link && $i<=G5_LINK_COUNT; $i++) { ?>
        <div class="bo_w_link write_div">
            <label for="wr_link<?php echo $i ?>"><i class="fa fa-link" aria-hidden="true"></i> <span class="sound_only">링크 #<?php echo $i ?></span></label>
            <input type="text" name="wr_link<?php echo $i ?>" value="<?php if($w=="u"){echo $write['wr_link'.$i];} ?>" id="wr_link<?php echo $i ?>" class="frm_input wr_link" placeholder="링크를 입력하세요">
        </div>
        <?php } ?>-->

<style>
.upload {
    background-color: #fcfcfc;
    border: none;
    border-radius: 8px;
    padding: 20px;
    min-width:300px;
    width:80%;
    max-width: 450px;
    margin: 0 auto;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.file_wr {
    margin-bottom: 20px;
}

.btn_file {
    background-color: #1da1f2 !important;
    color: #f9f9f9 !important;
    font-weight:520 !important;
    border:1px solid #0000 !important;
    border-radius: 13px !important;
    cursor: pointer;
}

.thumbnail-preview {
    display: flex;
    overflow: hidden;
    width: 300px;
    position: relative;
}

.thumbnail-container {
    display: flex;
    transition: transform 0.35s ease;
    border-radius:15px
}

.thumbnail-preview img {
    width: 100%;
    height: 100%;
    margin-right: 10px;
    border-radius: 5px;
}

.thumbnail-preview .arrow {
    cursor: pointer;
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 50%;
    padding: 5px;
    z-index: 10;
}

.thumbnail-preview .left-arrow {
    left: 10px;
    width:20px;
    height:20px;
}

.thumbnail-preview .right-arrow {
    right: 10px;
    width:20px;
    height:20px;
}

#nextButton {
    position: fixed; /* 고정 위치 설정 */
    right: 20px; /* 오른쪽에서 20px 떨어진 위치 */
    bottom: 80px; /* 상단에서 20px 떨어진 위치 */
    transform: translateX(0); /* X축 변환 제거 */
    background-color: #4285f4;
    color: #f9f9f9;
    padding: 10px 20px;
    border: none;
    border-radius: 15px !important;
    cursor: pointer;
    font-size: 16px;
    margin-bottom: 10px;
    z-index: 2; /* 다른 요소보다 위에 표시 */
}

textarea {
border-radius:13px !important;
padding:10px !important;
background-color:#f9f9f9 !important;
border:1px solid #f1f1f1 !important;
color:#3a3a3a !important;
}

.btn_confirm {
    display: flex; /* Flexbox를 사용하여 버튼을 나란히 배치 */
    align-items: center; /* 세로 중앙 정렬 */
    justify-content: center; /* 가로 중앙 정렬 */
    margin: 0 auto; /* 중앙 정렬을 위한 마진 */
}

#before, .public_share {
    background-color: #f2f2f2;
    padding: 10px 55px;
    border: none;
    border-radius: 10px;
    color: #3a3a3a;
    width: 50%; /* 너비를 동일하게 설정 */
    font-size: 13px;
    font-weight: 500;
    margin: 0 5px; /* 좌우 간격 설정 */
    height: 40px; /* 높이를 동일하게 설정 */
    display: flex; /* 내용 중앙 정렬을 위한 flex 설정 */
    justify-content: center; /* 가로 중앙 정렬 */
    align-items: center; /* 세로 중앙 정렬 */
    white-space: nowrap; /* 글자가 줄 바꿈되지 않도록 설정 */
}

.public_share {
    background-color: #1da1f2; /* 공개 버튼의 배경색 */
    color: #f2f2f2; /* 공개 버튼의 텍스트 색상 */
}
</style>
<div class="upload" id="uploadModal" style="display: block;">
    <button id="nextButton" style="display: none;">다음</button>
    <?php if ($is_file && $file_count > 0) { ?>
        <div class="bo_w_flie write_div">
            <div class="file_wr write_div filebox">
                <input type="text" class="fileName" readonly="readonly" placeholder="이미지 업로드" style="border-radius:13px; padding:10px; background-color:#f9f9f9; border:1px solid #f1f1f1; color:#3a3a3a">
                <label for="bf_file">
                    <span class="sound_only">업로드</span>
                    <span class="btn_file">업로드</span>
                </label>
                <input type="file" name="bf_file[]" id="bf_file" title="이미지 파일만 업로드 가능. 용량 <?php echo $upload_max_filesize ?> 이하만 업로드 가능" class="frm_file uploadBtn" accept="image/*" multiple style="display: none;">
            </div>

            <?php if($w == 'u' && isset($file[0]['file'])) { ?>
                <span class="file_del">
                    <input type="checkbox" id="bf_file_del" name="bf_file_del" value="1">
                    <label for="bf_file_del"><?php echo $file[0]['source'].'('.$file[0]['size'].')'; ?> 파일 삭제</label>
                </span>
            <?php } ?>
        </div>
        <div class="thumbnail-preview" id="thumbnailPreview">
            <div class="arrow left-arrow" onclick="prevThumbnail()"><span style="margin-bottom:5px;">❮</span></div>
            <div class="arrow right-arrow" onclick="nextThumbnail()"><span style="margin-bottom:5px;">❯</span></div>
            <div class="thumbnail-container"></div>
        </div>
    <?php } ?>
</div>
<script>
document.getElementById('bf_file').addEventListener('change', function(event) {
    const files = event.target.files;
    const previewContainer = document.querySelector('.thumbnail-container');
    previewContainer.innerHTML = '';

    if (files.length > 0) {
        Array.from(files).forEach(file => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const img = document.createElement('img');
                img.src = e.target.result;
                previewContainer.appendChild(img);
            }
            reader.readAsDataURL(file);
        });
    }
});

// 슬라이드 기능 구현
let currentIndex = 0;

function showThumbnails() {
    const thumbnails = document.querySelectorAll('.thumbnail-container img');
    const container = document.querySelector('.thumbnail-container');
    const offset = currentIndex * -110; // 각 이미지의 너비 + margin
    container.style.transform = `translateX(${offset}px)`;
}

function nextThumbnail() {
    const thumbnails = document.querySelectorAll('.thumbnail-container img');
    if (thumbnails.length > 0) {
        currentIndex = (currentIndex + 1) % thumbnails.length;
        showThumbnails();
    }
}

function prevThumbnail() {
    const thumbnails = document.querySelectorAll('.thumbnail-container img');
    if (thumbnails.length > 0) {
        currentIndex = (currentIndex - 1 + thumbnails.length) % thumbnails.length;
        showThumbnails();
    }
}

// 터치 이벤트 추가
let startX;

document.querySelector('.thumbnail-preview').addEventListener('touchstart', function(event) {
    startX = event.touches[0].clientX;
});

document.querySelector('.thumbnail-preview').addEventListener('touchmove', function(event) {
    const endX = event.touches[0].clientX;
    if (startX - endX > 50) {
        nextThumbnail();
    } else if (endX - startX > 50) {
        prevThumbnail();
    }
});

showThumbnails(); // 초기 상태 표시
</script>
<script>
document.getElementById('bf_file').addEventListener('change', function() {
    const nextButton = document.getElementById('nextButton');
    
    // 파일이 선택되었는지 확인
    if (this.files.length > 0) {
        nextButton.style.display = 'block'; // 버튼 표시
    } else {
        nextButton.style.display = 'none'; // 버튼 숨기기
    }
});
</script>

<div class="content_insert" style="display: none;">

    <div class="write_div">
        <label for="wr_content" class="sound_only">내용<strong>필수</strong></label>
        <!--<?php if($write_min || $write_max) { ?>
        <p id="char_count_desc">이 게시판은 최소 <strong><?php echo $write_min; ?></strong>글자 이상, 최대 <strong><?php echo $write_max; ?></strong>글자 이하까지 글을 쓰실 수 있습니다.</p>
        <?php } ?>-->
        <?php echo $editor_html; ?>
        <?php if($write_min || $write_max) { ?>
        <div id="char_count_wrap"><span id="char_count"></span>글자</div>
        <?php } ?>
    </div>
        <div class="bo_w_tit write_div">
        <label for="wr_subject" class="sound_only">제목<strong>필수</strong></label>
        <input type="text" name="wr_subject" value="<?php echo $subject ?>" id="wr_subject" required class="frm_input full_input required" placeholder="제목" style="border-radius:13px; padding:10px; background-color:#f9f9f9; border:1px solid #f1f1f1; color:#3a3a3a">
    </div>    
        <div class="btn_confirm">
        <span id="before">이전으로</span>
        <button type="submit" id="btn_submit" class="public_share" accesskey="s">공개</button>
    </div>
</div>

<script>
// 다음 버튼 클릭 시 새로운 모달 표시
document.getElementById('nextButton').addEventListener('click', function() {
    document.querySelector('.content_insert').style.display = 'block';
    document.getElementById('uploadModal').style.display = 'none'; // 필요시 업로드 모달 숨기기
});

// 이전 버튼 클릭 시 업로드 모달 다시 나타나게 하기
document.getElementById('before').addEventListener('click', function() {
    document.getElementById('uploadModal').style.display = 'block';
    document.querySelector('.content_insert').style.display = 'none';
});
</script>

        <?php if ($is_use_captcha) { //자동등록방지 ?>
        <div class="write_div">
            <span class="sound_only">자동등록방지</span>
            <?php echo $captcha_html ?>
        </div>
        <?php } ?>
    </div>

    </form>
</section>

<script>
<?php if($write_min || $write_max) { ?>
// 글자수 제한
var char_min = parseInt(<?php echo $write_min; ?>); // 최소
var char_max = parseInt(<?php echo $write_max; ?>); // 최대
check_byte("wr_content", "char_count");

$(function() {
    $("#wr_content").on("keyup", function() {
        check_byte("wr_content", "char_count");
    });
});

<?php } ?>
function html_auto_br(obj)
{
    if (obj.checked) {
        result = confirm("자동 줄바꿈을 하시겠습니까?\n\n자동 줄바꿈은 게시물 내용중 줄바뀐 곳을<br>태그로 변환하는 기능입니다.");
        if (result)
            obj.value = "html2";
        else
            obj.value = "html1";
    }
    else
        obj.value = "";
}

function fwrite_submit(f)
{
    <?php echo $editor_js; // 에디터 사용시 자바스크립트에서 내용을 폼필드로 넣어주며 내용이 입력되었는지 검사함   ?>

    var subject = "";
    var content = "";
    $.ajax({
        url: g5_bbs_url+"/ajax.filter.php",
        type: "POST",
        data: {
            "subject": f.wr_subject.value,
            "content": f.wr_content.value
        },
        dataType: "json",
        async: false,
        cache: false,
        success: function(data, textStatus) {
            subject = data.subject;
            content = data.content;
        }
    });

    if (subject) {
        alert("제목에 금지단어('"+subject+"')가 포함되어있습니다");
        f.wr_subject.focus();
        return false;
    }

    if (content) {
        alert("내용에 금지단어('"+content+"')가 포함되어있습니다");
        if (typeof(ed_wr_content) != "undefined")
            ed_wr_content.returnFalse();
        else
            f.wr_content.focus();
        return false;
    }

    if (document.getElementById("char_count")) {
        if (char_min > 0 || char_max > 0) {
            var cnt = parseInt(check_byte("wr_content", "char_count"));
            if (char_min > 0 && char_min > cnt) {
                alert("내용은 "+char_min+"글자 이상 쓰셔야 합니다.");
                return false;
            }
            else if (char_max > 0 && char_max < cnt) {
                alert("내용은 "+char_max+"글자 이하로 쓰셔야 합니다.");
                return false;
            }
        }
    }

    <?php echo $captcha_js; // 캡챠 사용시 자바스크립트에서 입력된 캡챠를 검사함  ?>

    document.getElementById("btn_submit").disabled = "disabled";

    return true;
}

var uploadFile = $('.filebox .uploadBtn');
uploadFile.on('change', function(){
	if(window.FileReader){
		var filename = $(this)[0].files[0].name;
	} else {
		var filename = $(this).val().split('/').pop().split('\\').pop();
	}
	$(this).siblings('.fileName').val(filename);
});
</script>
