OLDBOY/skin/board/daemon_trading_upbit/write.skin.php
<?php
if (!defined('_GNUBOARD_')) exit; // 개별 페이지 접근 불가
error_reporting(0);
ini_set('display_errors', '0');
include_once("{$board_skin_path}/db_update.php"); // db 업데이트

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

<style>
/* 토글 스위치 스타일 추가 */
.toggle-switch { position: relative; display: inline-block; width: 50px; height: 24px; vertical-align: middle; margin-left: 5px; }
.toggle-switch input { opacity: 0; width: 0; height: 0; }
.slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 24px; }
.slider:before { position: absolute; content: ""; height: 18px; width: 18px; left: 3px; bottom: 3px; background-color: white; transition: .4s; border-radius: 50%; }
input:checked + .slider { background-color: #2196F3; }
input:checked + .slider.x2_ai { background-color: #7d59ea; } /* AI 기능 전용 컬러 */
input:checked + .slider.sell_stop { background-color: #ff4d4d; } /* 매도 정지 전용 컬러 */
input:focus + .slider { box-shadow: 0 0 1px #2196F3; }
input:checked + .slider:before { transform: translateX(26px); }
.toggle-label { font-size: 12px; margin-left: 5px; font-weight: bold; }
</style>

<article id="Write">
    <!-- 게시물 작성/수정 시작 { -->
    <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="uid" value="<?php echo get_uniqid(); ?>">
        <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;
        ?>
       <!-- 설정 시작 -->
        <section class="Block">
            <div class="List">
                <!-- 
                기본 카테고리 사용 안함
                자체 컬럼 사용
                -->
                <ul>
                   <!-- 코인 분로 -->
                    <li>
                        <span>분류</span>
                    </li>
                   <!-- 매매 기준 선택 -->
                    <li>
                        기준 :
                    </li>
                    <li>
                        <select name="coin_criteria" id="coin_criteria" required>
                            <option value="">기준 선택</option>
                            <option value="start_price" <?php echo (isset($write['coin_criteria']) && $write['coin_criteria'] == 'start_price') ? 'selected' : ''; ?>>시작가 기준</option>
                            <option value="avg_price" <?php echo (isset($write['coin_criteria']) && $write['coin_criteria'] == 'avg_price') ? 'selected' : ''; ?>>평균가 기준</option>
                            <option value="specific_price" <?php echo (isset($write['coin_criteria']) && $write['coin_criteria'] == 'specific_price') ? 'selected' : ''; ?>>특정금액 기준</option>
                        </select>
                    </li>
                   <!-- 특정 금액에 한하여 사용 -->
                    <li class="price-criteria-item" style="display:none;">
                        특정금액 기준 :
                    </li>
                    <li class="price-criteria-item" style="display:none;">
                        <input type="text" name="price_criteria" id="price_criteria" value="<?php echo isset($write['price_criteria']) ? htmlspecialchars($write['price_criteria'], ENT_QUOTES, 'UTF-8') : ''; ?>" placeholder="금액을 입력하세요" pattern="[0-9,]+" title="숫자만 입력 가능합니다">
                    </li>
                   <!-- 중요 도움말 : 기본값은 분류.1 -->
                    <li>
                        형태 :
                    </li>
                    <li>
                        <select name="coin_kind" id="coin_kind" required>
                            <option value="">형태 선택</option>
                            <option value="main" <?php echo (isset($write['coin_kind']) && $write['coin_kind'] == 'main') ? 'selected' : ''; ?>>비트코인</option>
                            <option value="sub1" <?php echo (isset($write['coin_kind']) && $write['coin_kind'] == 'sub1') ? 'selected' : ''; ?>>메이저 코인</option>
                            <option value="sub2" <?php echo (isset($write['coin_kind']) && $write['coin_kind'] == 'sub2') ? 'selected' : ''; ?>>메이저 알트 코인</option>
                            <option value="sub3" <?php echo (isset($write['coin_kind']) && $write['coin_kind'] == 'sub3') ? 'selected' : ''; ?>>잡 알트 코인</option>
                            <option value="sub4" <?php echo (isset($write['coin_kind']) && $write['coin_kind'] == 'sub4') ? 'selected' : ''; ?>>두더지 코인</option>
                            <option value="sub5" <?php echo (isset($write['coin_kind']) && $write['coin_kind'] == 'sub5') ? 'selected' : ''; ?>>대멸종 코인</option>
                            <option value="sub6" <?php echo (isset($write['coin_kind']) && $write['coin_kind'] == 'sub6') ? 'selected' : ''; ?>>광마 코인</option>
                        </select>
                    </li>
                    <li class="Help">
                        <label>* 기준 : 매매 기준 / 형태 : 종류 및 프로젝트</label>
                    </li>
                   <!-- 기본 옵션 -->
                    <?php if ($option) { ?>
                        <ul class="Line-HY"><?=$option;?></ul>
                    <?php } ?>
                   <!-- 임시 저장 버튼 -->
                    <?php
                     if ($is_member) {
                        echo "<li>";
                        echo "<script src='".G5_JS_URL."/autosave.js'></script>";
                        if($editor_content_js) echo $editor_content_js;
                        if ($autosave_count>6) echo "<div><button type='button' id='btn_autosave'>임시 (<span id='autosave_count'>{$autosave_count}</span>)</button></div>";
                        echo "</li>";
                     }
                    ?>
                </ul>
               <!-- 코인 종목 -->
                <ul>
                    <li>
                        <span>코인</span>
                    </li>
                    <li>
                        종목 :
                    </li>
                    <li>
                        <input type="text" value="<?php echo $write['coin_code']; ?>" name="coin_code" id="coin_code" required>
                    </li>
                    <li>
                        한글명 :
                    </li>
                    <li>
                        <input type="text" value="<?php echo $subject ?>" name="wr_subject" id="wr_subject" placeholder="제목" required><!-- 제목 : 코인 한글명칭 -->
                    </li>
                    <li>
                        실행/중지 :
                    </li>
                    <li>
                        <select name="daemon_file" id="daemon_file" required>
                            <option value="">가동 선택</option>
                            <option value="yes" <?php echo (isset($write['daemon_file']) && $write['daemon_file'] == 'yes') ? 'selected' : ''; ?>>실행</option>
                            <option value="no" <?php echo (isset($write['daemon_file']) && $write['daemon_file'] == 'no') ? 'selected' : ''; ?>>중단</option>
                        </select>
                    </li>
                    <!-- 토글 기능들 -->
                    <li>
                        AI 기능 :
                    </li>
                    <li>
                        <label class="toggle-switch">
                            <input type="checkbox" name="x2_ai" value="1" <?php echo (isset($write['x2_ai']) && $write['x2_ai'] == '1') ? 'checked' : ''; ?>>
                            <span class="slider round x2_ai"></span>
                        </label>
                        <span class="toggle-label" id="label_x2_ai"><?php echo (isset($write['x2_ai']) && $write['x2_ai'] == '1') ? '사용' : '비사용'; ?></span>
                    </li>
                    <li>
                        매도 동일 :
                    </li>
                    <li>
                        <label class="toggle-switch">
                            <input type="checkbox" name="x2_force" value="1" <?php echo (!isset($write['x2_force']) || $write['x2_force'] == '1') ? 'checked' : ''; ?>>
                            <span class="slider round"></span>
                        </label>
                        <span class="toggle-label" id="label_x2_force"><?php echo (!isset($write['x2_force']) || $write['x2_force'] == '1') ? '동일' : '각'; ?></span>
                    </li>
                    <li>
                        매도 정지 :
                    </li>
                    <li>
                        <label class="toggle-switch">
                            <input type="checkbox" name="sell_stop" value="1" <?php echo (isset($write['sell_stop']) && $write['sell_stop'] == '1') ? 'checked' : ''; ?>>
                            <span class="slider round sell_stop"></span>
                        </label>
                        <span class="toggle-label" id="label_sell_stop"><?php echo (isset($write['sell_stop']) && $write['sell_stop'] == '1') ? '정지' : '유지'; ?></span>
                    </li>
                    <li class="Help">
                        <label>* AI 자동 옵션 / 일괄 평단가 매도 동일 / 강제 매도 정지</label>
                    </li>
                </ul>
            </div>
            <div class="Coin-Options">
               <!-- 왼쪽 매수/매도 옵션 -->
                <div class="Left">
                    <ul>
                        <li>매수</li>
                    </ul>
                    <?php 
                    for ($i=1; $i<=10; $i++) { 
                        // 6번째 이상은 기본적으로 숨김, 하지만 해당 항목에 값이 있으면 보이기
                        $is_hidden = false;
                        if ($i > 5) {
                            // 해당 항목에 값이 있는지 확인
                            $has_value = (!empty($write['buy_percent_'.$i]) || !empty($write['buy_amount_'.$i]));
                            // 값이 있으면 보이기, 없으면 숨기기
                            $is_hidden = !$has_value;
                        }
                    ?>
                        <ul class="buy-option-item <?php echo $is_hidden ? 'hidden-option' : ''; ?>">
                            <li>
                                <span>매수 . <?php echo $i;?></span>
                            </li>
                            <li>
                                <input type="text" value="<?php echo $write['buy_percent_'.$i]; ?>" name="buy_percent_<?php echo $i; ?>" id="buy_percent_<?php echo $i; ?>"> %
                            </li>
                            <li>
                                금액
                            </li>
                            <li>
                                <input type="text" value="<?php echo $write['buy_amount_'.$i]; ?>" name="buy_amount_<?php echo $i; ?>" id="buy_amount_<?php echo $i; ?>"> KRW
                            </li>
                        </ul>
                    <?php } ?>
                    <div class="add-more-btn-wrapper">
                        <button type="button" class="add-more-btn" id="addMoreBuyBtn">+ 매수 옵션 추가 (5개)</button>
                    </div>
                </div>
               <!-- 오른쪽 매도/매도 옵션 -->
                <div class="Left">
                    <ul>
                        <li>매도</li>
                    </ul>
                    <?php 
                    for ($i=1; $i<=10; $i++) { 
                        // 6번째 이상은 기본적으로 숨김, 하지만 해당 항목에 값이 있으면 보이기
                        $is_hidden = false;
                        if ($i > 5) {
                            // 해당 항목에 값이 있는지 확인
                            $has_value = (!empty($write['sell_percent_'.$i]) || !empty($write['sell_amount_'.$i]));
                            // 값이 있으면 보이기, 없으면 숨기기
                            $is_hidden = !$has_value;
                        }
                    ?>
                    <ul class="sell-option-item <?php echo $is_hidden ? 'hidden-option' : ''; ?>">
                        <li>
                            <span>매도 . <?php echo $i;?></span>
                        </li>
                        <li>
                            <input type="text" value="<?php echo $write['sell_percent_'.$i]; ?>" name="sell_percent_<?php echo $i; ?>" id="sell_percent_<?php echo $i; ?>"> %
                        </li>
                        <li>
                            금액
                        </li>
                        <li>
                            <input type="text" value="<?php echo $write['sell_amount_'.$i]; ?>" name="sell_amount_<?php echo $i; ?>" id="sell_amount_<?php echo $i; ?>"> KRW
                        </li>
                    </ul>
                    <?php } ?>
                    <div class="add-more-btn-wrapper">
                        <button type="button" class="add-more-btn" id="addMoreSellBtn">+ 매도 옵션 추가 (5개)</button>
                    </div>
                </div>
               <!-- 메세지 -->
                <div class="Left Message-Box">
                    <div class="message-header">
                        <h4>거래 정보</h4>
                    </div>
                    <div class="message-content">
                        <!-- 기본 정보 -->
                        <div class="message-section">
                            <div class="message-section-title">기본 정보</div>
                            <div id="basicInfoList" class="message-basic-list">
                                <!-- 동적으로 생성됨 -->
                            </div>
                        </div>                
                        <div class="message-alert" id="messageAlert" style="display:none;"></div>
                    </div>
                </div>
                <div class="Left Message-Box">
                    <div class="message-header">
                        <h4>거래 정보</h4>
                    </div>
                    <div class="message-content">
                        <!-- 매수 상세 정보 -->
                        <div class="message-section">
                            <div class="message-section-title">매수 정보</div>
                            <div id="buyDetailsList" class="message-details-list">
                                <!-- 동적으로 생성됨 -->
                            </div>
                            <div class="message-item message-total">
                                <span class="message-label">매수 총 퍼센트:</span>
                                <span class="message-value" id="totalBuyPercent">0%</span>
                            </div>
                            <div class="message-item message-total">
                                <span class="message-label">매수 총 금액:</span>
                                <span class="message-value" id="totalBuyAmount">0 KRW</span>
                            </div>
                        </div>                        
                        <!-- 매도 상세 정보 -->
                        <div class="message-section">
                            <div class="message-section-title">매도 정보</div>
                            <div id="sellDetailsList" class="message-details-list">
                                <!-- 동적으로 생성됨 -->
                            </div>
                            <div class="message-item message-total">
                                <span class="message-label">매도 총 퍼센트:</span>
                                <span class="message-value" id="totalSellPercent">0%</span>
                            </div>
                            <div class="message-item message-total">
                                <span class="message-label">매도 총 금액:</span>
                                <span class="message-value" id="totalSellAmount">0 KRW</span>
                            </div>
                        </div>                        
                        <div class="message-alert" id="messageAlert" style="display:none;"></div>
                    </div>
                </div>
            </div>
        </section>
       <!-- 회원 인증시 임시저장 리스트 출력 -->
        <?php if ($is_member) { ?>
            <section id="autosave_pop" class="Subject-Pop" style="display:none">
                <div>임시 저장 목록</div>
                <div class="Close"><button type="button" class="autosave_close Button2-BOb">닫기</button></div>
                <p></p>
                <ul></ul>
            </section>
        <?php } ?>
       <!-- 글 내용 -->
        <div class="Content-Toggle">
            <button type="button" class="content-toggle-btn" id="contentToggleBtn">
                <span class="toggle-icon">▼</span>
                <span class="toggle-text">글 내용 입력</span>
            </button>
        </div>
        <section class="Content" id="contentSection">
            <div class="wr_content <?php echo $is_dhtml_editor ? $config['cf_editor'] : ''; ?>">
                <?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; // 에디터 사용시는 에디터로, 아니면 textarea 로 노출 ?>
                <?php if($write_min || $write_max) { ?>
                <!-- 최소/최대 글자 수 사용 시 -->
                <div id="char_count_wrap"><span id="char_count"></span>글자</div>
                <?php } ?>
            </div>
        </section>
       <!-- 버튼 -->
        <section class="Button">
            <div class="button-group">
                <a href="<?php echo get_pretty_url($bo_table); ?>" class="btn_cancel btn">취 소</a>
                <button type="submit" id="btn_submit" accesskey="s" class="btn_submit btn">등 록 완 료</button>
            </div>
        </section>
    </form>
   <!-- 스크립트 -->
    <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() {
        // 분류, 코인 라벨에 클래스 추가
        $('#Write .Block .List ul li span').each(function() {
            var text = $(this).text().trim();
            if (text === '분류' || text === '코인') {
                $(this).addClass('label-primary');
            }
        });
        // 매수 라벨에 클래스 추가
        $('#Write .Block .Coin-Options .Left ul li span').each(function() {
            var text = $(this).text().trim();
            if (text.indexOf('매수') !== -1) {
                $(this).addClass('label-buy');
            }
        });
        // 매도 라벨에 클래스 추가
        $('#Write .Block .Coin-Options .Right ul li span').each(function() {
            var text = $(this).text().trim();
            if (text.indexOf('매도') !== -1) {
                $(this).addClass('label-sell');
            }
        });
    });
    // 매수/매도 옵션 추가 버튼 기능
    $(function() {
        // 6~10번째에 값이 있는지 확인하고 자동으로 보이기
        function checkAndShowOptions() {
            // 매수 6~10번째 확인
            for (var i = 6; i <= 10; i++) {
                var buyPercent = $('#buy_percent_' + i).val() || '';
                var buyAmount = $('#buy_amount_' + i).val() || '';
                if (buyPercent.trim() !== '' || buyAmount.trim() !== '') {
                    $('.buy-option-item').eq(i - 1).removeClass('hidden-option').show();
                }
            }
            
            // 매도 6~10번째 확인
            for (var i = 6; i <= 10; i++) {
                var sellPercent = $('#sell_percent_' + i).val() || '';
                var sellAmount = $('#sell_amount_' + i).val() || '';
                if (sellPercent.trim() !== '' || sellAmount.trim() !== '') {
                    $('.sell-option-item').eq(i - 1).removeClass('hidden-option').show();
                }
            }
        }
        
        // 초기 로드 시 6~10번째 값 확인
        checkAndShowOptions();
        
        // 매수 옵션 추가 버튼
        $('#addMoreBuyBtn').on('click', function() {
            $('.buy-option-item.hidden-option').slideDown(300);
            $(this).fadeOut(300, function() {
                $(this).remove();
            });
        });
        
        // 매도 옵션 추가 버튼
        $('#addMoreSellBtn').on('click', function() {
            $('.sell-option-item.hidden-option').slideDown(300);
            $(this).fadeOut(300, function() {
                $(this).remove();
            });
        });
        
        // 초기 상태: 숨겨진 옵션이 없으면 버튼 숨김
        if ($('.buy-option-item.hidden-option').length === 0) {
            $('#addMoreBuyBtn').closest('.add-more-btn-wrapper').hide();
        }
        if ($('.sell-option-item.hidden-option').length === 0) {
            $('#addMoreSellBtn').closest('.add-more-btn-wrapper').hide();
        }
    });
    
    // 특정 금액 기준 필드 표시/숨김 기능
    $(function() {
        function togglePriceCriteria() {
            var categoryValue = $('#coin_criteria').val();
            if (categoryValue === 'specific_price') {
                $('.price-criteria-item').show();
                $('#price_criteria').prop('required', true);
            } else {
                $('.price-criteria-item').hide();
                $('#price_criteria').val(''); // 값 초기화
                $('#price_criteria').prop('required', false);
            }
        }
        
        // 초기 상태 설정
        togglePriceCriteria();
        
        // coin_criteria 선택 변경 시
        $('#coin_criteria').on('change', function() {
            togglePriceCriteria();
        });
    });

    // 신규 토글 상태 텍스트 변경 이벤트
    $(function() {
        $('input[name="x2_ai"]').on('change', function() {
            $('#label_x2_ai').text(this.checked ? '사용' : '비사용');
            calculateTotals();
        });
        $('input[name="x2_force"]').on('change', function() {
            $('#label_x2_force').text(this.checked ? '동일' : '각');
            calculateTotals();
        });
        $('input[name="sell_stop"]').on('change', function() {
            $('#label_sell_stop').text(this.checked ? '정지' : '유지');
            calculateTotals();
        });
    });

    // 동적 UI - 매수/매도 옵션 실시간 계산
    $(function() {
        function calculateTotals() {
            var totalBuyPercent = 0;
            var totalBuyAmount = 0;
            var totalSellPercent = 0;
            var totalSellAmount = 0;
            var hasError = false;
            var errorMessages = [];
            
            // 기본 정보 동적 출력
            function updateBasicInfo() {
                var $basicList = $('#basicInfoList');
                $basicList.empty();
                
                // 분류 기준
                var criteriaValue = $('#coin_criteria').val();
                var criteriaText = '';
                if (criteriaValue === 'start_price') {
                    criteriaText = '시작가 기준';
                } else if (criteriaValue === 'avg_price') {
                    criteriaText = '평균가 기준';
                } else if (criteriaValue === 'specific_price') {
                    criteriaText = '특정금액 기준';
                } else {
                    criteriaText = '-';
                }
                
                // 형태
                var kindValue = $('#coin_kind').val();
                var kindText = $('#coin_kind option:selected').text() || '-';
                if (kindText === '형태 선택') kindText = '-';
                
                // 특정 금액
                var priceCriteria = $('#price_criteria').val() || '';
                var priceCriteriaText = priceCriteria ? formatNumber(parseFloat(priceCriteria.replace(/,/g, '')) || 0) + ' KRW' : '-';
                
                // 코인 종목
                var coinCode = $('#coin_code').val() || '-';
                
                // 한글명
                var wrSubject = $('#wr_subject').val() || '-';
                
                // 데몬 이름
                var daemonFileText = $('#daemon_file').val() || '-';

                // 토글 값
                var aiStatus = $('input[name="x2_ai"]').is(':checked') ? '사용' : '비사용';
                var forceStatus = $('input[name="x2_force"]').is(':checked') ? '동일' : '각';
                var stopStatus = $('input[name="sell_stop"]').is(':checked') ? '정지' : '유지';
                
                // 기본 정보 아이템 생성
                var basicInfoItems = [
                    { label: '분류 기준', value: criteriaText },
                    { label: '형태', value: kindText }
                ];
                
                // 특정금액 기준일 때만 특정금액 표시
                if (criteriaValue === 'specific_price' && priceCriteria) {
                    basicInfoItems.push({ label: '특정금액', value: priceCriteriaText });
                }
                
                basicInfoItems.push(
                    { label: '코인 종목', value: coinCode },
                    { label: '한글명', value: wrSubject },
                    { label: '데몬 상태', value: daemonFileText },
                    { label: 'AI 기능', value: aiStatus },
                    { label: '매도 방식', value: forceStatus },
                    { label: '매도 정지', value: stopStatus }
                );
                
                // 기본 정보 출력
                basicInfoItems.forEach(function(item) {
                    var $item = $('<div class="message-basic-item"></div>');
                    $item.html('<span class="message-basic-label">' + item.label + ':</span>' +
                              '<span class="message-basic-value">' + item.value + '</span>');
                    $basicList.append($item);
                });
            }
            
            // 기본 정보 업데이트
            updateBasicInfo();
            
            // 매수 상세 정보 배열
            var buyDetails = [];
            // 매수 옵션 계산 (1부터 10까지)
            for (var i = 1; i <= 10; i++) {
                var buyPercent = parseFloat($('#buy_percent_' + i).val()) || 0;
                var buyAmount = parseFloat($('#buy_amount_' + i).val().replace(/,/g, '')) || 0;
                
                if (buyPercent > 0 || buyAmount > 0) {
                    buyDetails.push({
                        index: i,
                        percent: buyPercent,
                        amount: buyAmount
                    });
                }
                
                totalBuyPercent += buyPercent;
                totalBuyAmount += buyAmount;
            }
            
            // 매도 상세 정보 배열
            var sellDetails = [];
            // 매도 옵션 계산 (1부터 10까지)
            for (var i = 1; i <= 10; i++) {
                var sellPercent = parseFloat($('#sell_percent_' + i).val()) || 0;
                var sellAmount = parseFloat($('#sell_amount_' + i).val().replace(/,/g, '')) || 0;
                
                if (sellPercent > 0 || sellAmount > 0) {
                    sellDetails.push({
                        index: i,
                        percent: sellPercent,
                        amount: sellAmount
                    });
                }
                
                totalSellPercent += sellPercent;
                totalSellAmount += sellAmount;
            }
            
            // 매수 상세 정보 동적 출력
            var $buyList = $('#buyDetailsList');
            $buyList.empty();
            if (buyDetails.length > 0) {
                buyDetails.forEach(function(item) {
                    var $detail = $('<div class="message-detail-item message-detail-buy"></div>');
                    $detail.html('<span class="message-detail-label">매수.' + item.index + ':</span>' +
                                '<span class="message-detail-value message-detail-value-buy">' + 
                                (item.percent > 0 ? item.percent.toFixed(2) + '%' : '-') + ' / ' +
                                (item.amount > 0 ? formatNumber(item.amount) + ' KRW' : '-') +
                                '</span>');
                    $buyList.append($detail);
                });
            } else {
                $buyList.html('<div class="message-detail-empty">입력된 매수 정보가 없습니다.</div>');
            }
            
            // 매도 상세 정보 동적 출력
            var $sellList = $('#sellDetailsList');
            $sellList.empty();
            if (sellDetails.length > 0) {
                sellDetails.forEach(function(item) {
                    var $detail = $('<div class="message-detail-item message-detail-sell"></div>');
                    $detail.html('<span class="message-detail-label">매도.' + item.index + ':</span>' +
                                '<span class="message-detail-value message-detail-value-sell">' + 
                                (item.percent > 0 ? item.percent.toFixed(2) + '%' : '-') + ' / ' +
                                (item.amount > 0 ? formatNumber(item.amount) + ' KRW' : '-') +
                                '</span>');
                    $sellList.append($detail);
                });
            } else {
                $sellList.html('<div class="message-detail-empty">입력된 매도 정보가 없습니다.</div>');
            }
            
            // 총합 표시
            $('#totalBuyPercent').text(totalBuyPercent.toFixed(2) + '%');
            $('#totalBuyAmount').text(formatNumber(totalBuyAmount) + ' KRW');
            $('#totalSellPercent').text(totalSellPercent.toFixed(2) + '%');
            $('#totalSellAmount').text(formatNumber(totalSellAmount) + ' KRW');
            // 유효성 검사 및 경고 메시지
            var $alert = $('#messageAlert');
            $alert.hide().removeClass('alert-success alert-warning alert-error');
            if (totalBuyPercent > 100) {
                hasError = true;
                errorMessages.push('매수 총 퍼센트가 100%를 초과합니다.');
            }
            if (totalSellPercent > 100) {
                hasError = true;
                errorMessages.push('매도 총 퍼센트가 100%를 초과합니다.');
            }
            if (totalBuyPercent > 0 && totalBuyAmount === 0) {
                errorMessages.push('매수 퍼센트는 입력되었으나 금액이 없습니다.');
            }
            if (totalSellPercent > 0 && totalSellAmount === 0) {
                errorMessages.push('매도 퍼센트는 입력되었으나 금액이 없습니다.');
            }
            // 메시지 표시
            if (errorMessages.length > 0) {
                $alert.addClass(hasError ? 'alert-error' : 'alert-warning')
                      .html('<strong>' + (hasError ? '오류' : '경고') + ':</strong> ' + errorMessages.join('<br>'))
                      .show();
            } else if (totalBuyPercent > 0 || totalSellPercent > 0) {
                $alert.addClass('alert-success')
                      .html('<strong>정상:</strong> 입력값이 올바르게 설정되었습니다.')
                      .show();
            }
            // 값에 따른 색상 변경
            if (totalBuyPercent > 100) {
                $('#totalBuyPercent').addClass('error-value');
            } else {
                $('#totalBuyPercent').removeClass('error-value');
            }
            if (totalSellPercent > 100) {
                $('#totalSellPercent').addClass('error-value');
            } else {
                $('#totalSellPercent').removeClass('error-value');
            }
        }
        // 숫자 포맷팅 함수
        function formatNumber(num) {
            return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',');
        }
        // 모든 매수/매도 입력 필드에 이벤트 리스너 추가 (1부터 10까지)
        for (var i = 1; i <= 10; i++) {
            $('#buy_percent_' + i + ', #buy_amount_' + i + ', #sell_percent_' + i + ', #sell_amount_' + i).on('input change keyup', function() {
                calculateTotals();
            });
        }
        
        // 기본 정보 필드에 이벤트 리스너 추가
        $('#coin_criteria, #coin_kind, #price_criteria, #coin_code, #wr_subject, #daemon_file').on('input change keyup', function() {
            calculateTotals();
        });
        
        // 초기 계산
        calculateTotals();
    });
    // 글 내용 입력 폼 펼침/닫기 기능
    $(function() {
        var $contentSection = $('#contentSection');
        var $toggleBtn = $('#contentToggleBtn');
        var $toggleIcon = $toggleBtn.find('.toggle-icon');
        var $toggleText = $toggleBtn.find('.toggle-text');
        
        // wr_content 값이 있는지 확인하는 함수
        function hasContent() {
            var hasContent = false;
            
            // textarea인 경우
            var $textarea = $('#wr_content, textarea[name="wr_content"]');
            if ($textarea.length > 0) {
                hasContent = $textarea.val().trim() !== '';
            }
            
            // 에디터인 경우 (iframe 내부 확인)
            if (!hasContent) {
                try {
                    var editorFrame = $('iframe[name^="smart"], iframe[id^="smart"]').get(0);
                    if (editorFrame && editorFrame.contentWindow) {
                        var editorDoc = editorFrame.contentWindow.document;
                        var editorBody = editorDoc.body;
                        if (editorBody) {
                            var editorText = editorBody.innerText ? editorBody.innerText.trim() : '';
                            var editorHtml = editorBody.innerHTML ? editorBody.innerHTML.trim() : '';
                            // 빈 내용 체크 (에디터 기본값 제외)
                            hasContent = editorText !== '' && editorHtml !== '' && editorHtml !== '<p><br></p>' && editorHtml !== '<p></p>';
                        }
                    }
                } catch(e) {}
            }
            
            return hasContent;
        }
        // 초기 상태 설정 (wr_content 값이 있으면 열림, 없으면 닫힘)
        var initialOpen = hasContent();
        if (!initialOpen) {
            $contentSection.addClass('collapsed');
            $toggleIcon.text('▶');
            $toggleText.text('글 내용 입력 (닫힘)');
        } else {
            $toggleIcon.text('▼');
            $toggleText.text('글 내용 입력 (열림)');
        }
        
        // 토글 버튼 클릭 이벤트
        $toggleBtn.on('click', function() {
            $contentSection.toggleClass('collapsed');
            
            if ($contentSection.hasClass('collapsed')) {
                $toggleIcon.text('▶');
                $toggleText.text('글 내용 입력 (닫힘)');
            } else {
                $toggleIcon.text('▼');
                $toggleText.text('글 내용 입력 (열림)');
            }
        });
        // wr_content 값이 변경될 때 자동으로 열기
        $('#wr_content, textarea[name="wr_content"]').on('input change', function() {
            if (hasContent() && $contentSection.hasClass('collapsed')) {
                $contentSection.removeClass('collapsed');
                $toggleIcon.text('▼');
                $toggleText.text('글 내용 입력 (열림)');
            }
        });
        // 에디터 내용 변경 감지 (iframe 내부) - wr_content 값만 확인
        setTimeout(function() {
            try {
                var editorFrame = $('iframe[name^="smart"], iframe[id^="smart"]').get(0);
                if (editorFrame && editorFrame.contentWindow) {
                    var editorDoc = editorFrame.contentWindow.document;
                    var editorBody = editorDoc.body;
                    if (editorBody) {
                        // MutationObserver로 에디터 내용 변경 감지
                        var observer = new MutationObserver(function() {
                            if (hasContent() && $contentSection.hasClass('collapsed')) {
                                $contentSection.removeClass('collapsed');
                                $toggleIcon.text('▼');
                                $toggleText.text('글 내용 입력 (열림)');
                            }
                        });
                        observer.observe(editorBody, {
                            childList: true,
                            subtree: true,
                            characterData: true
                        });
                    }
                }
            } catch(e) {}
        }, 1000);
    });
    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)
    {
        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;
            }
        });
        document.getElementById("btn_submit").disabled = "disabled";
        return true;
    }
    </script>
</article>