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

//Action
$action = 'write';

if(!$is_admin && $amina['limit_writer'] && !chk_multiple_admin($member['mb_id'], $board['bo_4'])) {
	alert('본 게시판은 지정된 회원만 글쓰기 가능합니다.');
}

include_once(AMINA_PATH.'/lib/write.lib.php');

if (!$is_admin && $amina['limit_post_cnt'] > 0 && $w != "u") {
	if($amina['limit_post'] == 1) {
		 $chk_time = date("Y-m-d 00:00:01", G5_SERVER_TIME); //오늘 00시 00분 01초 기준 
		 $row = sql_fetch(" select count(*) as cnt from $write_table where wr_is_comment = 0 and mb_id = '{$member['mb_id']}' and wr_datetime >= '$chk_time' "); 
		 if($row['cnt'] >= $amina['limit_post_cnt']) alert("이 게시판은 회원당 하루 최대 {$amina['limit_post_cnt']}개 글만 등록할 수 있습니다. "); 
	} else if ($amina['limit_post'] == 2) {
		 $row = sql_fetch(" select count(*) as cnt from $write_table where wr_is_comment = 0 and mb_id = '{$member['mb_id']}' "); 
		 if($row['cnt'] >= $amina['limit_post_cnt']) alert("이 게시판은 회원당 최대 {$amina['limit_post_cnt']}개 글만 등록할 수 있습니다. "); 
	} else if ($amina['limit_post'] == 3 && $amina['cmt_choice']) {
		 $row = sql_fetch(" select count(*) as cnt from $write_table where wr_is_comment = 0 and mb_id = '{$member['mb_id']}' and wr_5 like '%<no-choice>%' "); 
		 if($row['cnt'] == $amina['limit_post_cnt']) alert("이 게시판은 회원당 최대 {$amina['limit_post_cnt']}개의 미채택 글만 등록할 수 있습니다."); 
	}
}

//쓰기스킨 설정값
if(file_exists($write_skin_path.'/set/set.load.php')) {
	include_once($write_skin_path.'/set/set.load.php');
	$set = amina_set_write($amina['write_set']);
}

//Deco Write
$is_deco_write = ($amina['deco_write'] && $amina['deco_write'] != 'none') ? true : false;

//DHTML for Mobile
if(G5_IS_MOBILE && $is_dhtml_editor) $is_dhtml_editor = false;

//DHTML Editor Type
$dhtml_editor = '';
if($is_dhtml_editor) {
	if($amina['editor'] == 1) {
		$dhtml_editor = "SEditor2"; //NHN SmartEditor2
	} else if($amina['editor'] == 2) {
		$dhtml_editor = "DEditor"; //Daum Editor
	} else {
		if(AMINA) {
			$dhtml_editor = $config['cf_editor'] ? $config['cf_editor'] : 'ckeditor4';
		} else {
			$dhtml_editor = 'cheditor';
		}
	}
}

//기본 카테고리 설정
if ($board['bo_use_category']) {
	if(!$ca_name) $ca_name = $write['ca_name'];
	if(!$ca_name) $ca_name = $sca;

	$category_option = amina_category($ca_name, $board['bo_category_list']);
}

if($w != "r") {
	//값 불러오기(wr_10)
	$wr_post = amina_array_write($write['wr_10']);

	//아이콘및 및 댓글채택
	$wr_icon = amina_array_icon($write['wr_5']);
}

// CSS Load
if(!defined('AMINA_CSS')) include_once(AMINA_PATH.'/css.php');

//영카트 상품코드
if($w == "u" || $w == "r") {
	$wr_8 = $write['wr_8'];
	$wr_4 = $write['wr_4'];
}

//연동값 정리
if(!$wr_8 && $bo_it) $wr_8 = $bo_it;
if(!$wr_4 && $bo_linked) $wr_4 = $bo_linked;

//이모티콘
$is_emoticon = false;
if($amina['view_photo'] == "3") { 
	$is_emoticon = true;
	if(!file_exists($emo_skin_path.'/'.$wr_icon['post_icon'].'.gif')) $wr_icon['post_icon'] = rand(1,$amina['emo_cnt']); //아이콘이 없을 경우
}

//설문조사
$is_poll = false;
if($is_admin || $amina['poll_level'] == 1 || ($amina['poll_level'] > 1 && $member['mb_level'] >= $amina['poll_level'])) {
	$poll = array();
	$is_poll = true;
	$set_poll = false;
	$poll_display = 'none';
	$poll_btn = '설문설정';
	if($wr_post['chk_poll']) {
		$set_poll = true;
		$poll_display = 'block';
		$poll_btn = '설문수정';
	}

	if($set_poll && $wr_id) $poll = sql_fetch(" select * from {$g5['amina_poll']} where bo_table = '$bo_table' and wr_id = '$wr_id' order by poll_id desc limit 0, 1");

	if(!$poll['poll_enddate']) $poll['poll_enddate'] = date("Y-m-d", G5_SERVER_TIME + ( 7 * 24 * 3600 ))." 23:30:00"; 

	$poll['poll_enddate'] = strtotime($poll['poll_enddate']);
}

//열람
$is_po_view = false;
if($member['mb_id'] && $amina['po_view']) { 
	$is_po_view = true;
	if(!$wr_icon['po_view_point']) $wr_icon['po_view_point'] = 0;
}

//다운
$is_po_down = false;
if($member['mb_id'] && $amina['po_down']) { 
	$is_po_down = true;
	if(!$wr_icon['po_down_point']) $wr_icon['po_down_point'] = 0; 
}

//채택
$is_choice = false;
if($member['mb_id'] && $amina['cmt_choice']) { 
	$is_choice = true;	
	if(!$wr_icon['choice_point']) $wr_icon['choice_point'] = 0; 
}

//태그
$is_tag = amina_tag_auth();

//별점
$is_star = false;
if($amina['star'] == "1") {
	$is_star = true;
	$star = amina_array_star($write['wr_7']);
}

//익명
$is_nameless = $amina['nameless_write'];

//리사이징
$is_resize = false;
if($amina['upimg_size'] > 0 && $amina['upimg_quality'] > 0) $is_resize = true;

//옵션
$option = '';
$option_hidden = '';
if ($is_notice || $is_html || $is_secret || $is_mail || $is_nameless) { 
	$option = '';
	if ($is_notice) { 
        $option .= "\n".'<label><input type="checkbox" id="notice" name="notice" value="1" '.$notice_checked.'> 공지</label>';
    }
	if ($is_admin) { 
		if($wr_post['post_main'] == "main") $chk_main = "checked";
		$option .= "\n".'<label><input type="checkbox" id="post_main" name="post_main" value="main" '.$chk_main.'> 메인</label>';

		if($wr_post['post_good'] == "good") $chk_good = "checked";
		$option .= "\n".'<label><input type="checkbox" id="post_good" name="post_good" value="good" '.$chk_good.'> 추천</label>';

		if($wr_post['post_rss'] == "rss") $chk_rss = "checked";
		$option .= "\n".'<label><input type="checkbox" id="post_rss" name="post_rss" value="rss" '.$chk_rss.'> RSS</label>';
	}

    if ($is_html) {
        if ($is_dhtml_editor) {
            $option_hidden .= '<input type="hidden" value="html1" name="html">';
        } else {
            $option .= "\n".'<label><input type="checkbox" id="html" name="html" onclick="html_auto_br(this);" value="'.$html_value.'" '.$html_checked.'> html</label>';
        }
    }

    if ($is_secret) {
        if ($is_admin || $is_secret==1) {
            $option .= "\n".'<label><input type="checkbox" id="secret" name="secret" value="secret" '.$secret_checked.'> 비밀</label>';
        } else {
            $option_hidden .= '<input type="hidden" name="secret" value="secret">';
        }
    }

    if ($is_nameless) {
        if ($is_admin || $is_nameless == "1") {
            $option .= "\n".'<label><input type="checkbox" id="wr_nameless" value="1" name="wr_nameless"> 익명</label>';
        } else {
            $option_hidden .= "<input type=hidden value='1' name='wr_nameless'>";
        }
    }

    if ($is_mail) {
        $option .= "\n".'<label><input type="checkbox" id="mail" name="mail" value="mail" '.$recv_email_checked.'> 답변메일받기</label>';
    }
}

//Uploader
$is_uploader = '';
$is_uploader_script = '';
if ($is_file && !G5_IS_MOBILE && $amina['uploader'] == "1" && $member['mb_id']) {
    ob_start();
	include AMINA_PATH.'/app/swfupload/swfupload.php';
    $is_uploader = ob_get_contents();
    ob_end_clean();

	//if(!$wr_post['img_location']) $wr_post['img_location'] = "insert";
	$is_uploader_script = ' onchange="insert_btn(this.value);"';
}

$action_url = $action_url ? $action_url : G5_HTTPS_BBS_URL.'/write_update.php';

if ($dhtml_editor == "SEditor2") {
	include_once(AMINA_PATH."/lib/SEditor2.lib.php");
	echo editor_load();
} else if ($dhtml_editor == "DEditor") {
	include_once(AMINA_PATH."/lib/DEditor.lib.php");
	echo editor_load();
} else if ($dhtml_editor == "cheditor") {
	include_once(G5_LIB_PATH."/cheditor4.lib.php");
	echo "<script src='{$g5['cheditor4_path']}/cheditor.js'></script>";
    echo cheditor1('wr_content', '100%', '300px');
}

$editor_content = ($w == '') ? $board['bo_insert_content'] : $write['wr_content'];

//Editor Form
switch($dhtml_editor) {
	case 'ckeditor4'	: $editor_form = $editor_html; break;
	case 'cheditor5'	: $editor_form = $editor_html; break;
	case 'cheditor'		: $editor_form = cheditor2('wr_content', $content); break;
	case 'SEditor2'		: $editor_form = editor_run("wr_content", $editor_content); break;
	case 'DEditor'		: $editor_form = editor_run("wr_content", $editor_content); break;
	default				: $editor_form = ''; break;
}

//Captcha
include_once(AMINA_PATH.'/captcha.php');

?>

<script>
	// 글자수 제한
	var char_min = parseInt(<?php echo $write_min; ?>); // 최소
	var char_max = parseInt(<?php echo $write_max; ?>); // 최대
	var editor_type = "<?php echo $dhtml_editor; ?>"; // 에디터 종류
</script>

<link rel="stylesheet" href="<?php echo $write_skin_url.'/'.$amina['write_css']; ?>.css">

<div id="as-write-wrap">
<?php
	if($is_deco_write) {
		echo '<link rel="stylesheet" href="'.AMINA_URL.'/skin/deco/write/'.$amina['deco_write'].'.css">'."\n";
		echo '<div class="deco-write">'."\n"; //데코 전체
		echo '<div class="deco-write-head-back"><div class="deco-write-head-front"><div class="deco-write-head"></div></div></div>'."\n"; //데코 상단
		echo '<div class="deco-write-body-back"><div class="deco-write-body-front">'."\n"; //데코 중단 시작
	}
?>

<form id="fwrite" name="fwrite" action="<?php echo $action_url; ?>" onsubmit="return fwrite_submit(this);" method="post" enctype="multipart/form-data" autocomplete="off" data-ajax="false">
<input type="hidden" name="null"> 
<?php if($is_autosave) { // 임시 저장된 글 기능 ?>
	<input type="hidden" name="uid" value="<?php echo get_uniqid(); ?>">
<?php } ?>
<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; ?>">
<input type="hidden" name="go_url" value="<?php echo $go_url; ?>">
<input type="hidden" name="frame" value="<?php echo $frame; ?>">
<input type="hidden" name="bo_linked" value="<?php echo $bo_linked; ?>">
<input type="hidden" name="bo_it" value="<?php echo $bo_it; ?>">
<input type="hidden" name="bo_row" value="<?php echo $bo_row; ?>">
<input type="hidden" name="bo_all" value="<?php echo $bo_all; ?>">
<input type="hidden" name="wr_8" value="<?php echo $wr_8; ?>">
<input type="hidden" name="wr_4" value="<?php echo $wr_4; ?>">
<input type="hidden" name="bm" value="<?php echo $bm; ?>">

<div id="as-write">
<?php 
	echo $option_hidden;
	if(!$is_emoticon) {
		echo '<input type="hidden" name="post_icon" value="'.$wr_icon['post_icon'].'">'."\n";
		echo '<input type="hidden" name="post_icon_mb" value="'.$wr_icon['post_icon_mb'].'">'."\n";
	}
	if(!$is_admin) { //추천글 체크값
		echo '<input type="hidden" name="post_main" value="'.$wr_post['post_main'].'">'."\n";
		echo '<input type="hidden" name="post_good" value="'.$wr_post['post_good'].'">'."\n";
		echo '<input type="hidden" name="post_rss" value="'.$wr_post['post_rss'].'">'."\n";
	}

	$list_url = G5_BBS_URL.'/board.php?bo_table='.$bo_table.'&sca='.urlencode($sca).$frame_opt.$search_opt;
	include($write_skin_path.'/write.skin.php'); 
?>
</div>

<div class="clear"></div>

<div id="as-write-btn">
	<?php include ($btn_skin_path.'/btn.skin.php'); //Btn Skin?>
</div>

<div class="clear"></div>

<?php if($is_rid) { ?>
	<div style="padding:10px; background:#fafafa; border:1px solid #ddd; color:#333; text-align:center; margin:10px 0px;">
		<label><b style="cursor:pointer;"><input type="radio" id="chk_rid1" name="chk_rid" value="" checked> 적용안함</b></label>
		&nbsp;
		<label><b style="cursor:pointer;"><input type="radio" id="chk_rid2" name="chk_rid" value="1"> 대표아이디</b></label>
		&nbsp;
		<label><b style="cursor:pointer;"><input type="radio" id="chk_rid3" name="chk_rid" value="2"> 내아이디</b></label>
	</div>
<?php } ?>

</form>

<?php
	if($is_deco_write) {
		echo '</div></div>'."\n"; //데코 중단 끝
		echo '<div class="deco-write-tail-back"><div class="deco-write-tail-front"><div class="deco-write-tail"></div></div></div>'."\n"; //데코 하단
		echo '</div>'."\n"; //데코 전체 끝
	}
?>

<div id="loading-icon" style="display:none;">
	<img src="<?php echo AMINA_URL; ?>/img/loader.gif" alt="" />
</div>

</div>

<script>
<?php if($is_uploader_script) { ?>
	function insert_btn(opt) {
		if(opt == 'insert') {
			$('#btnInsert').show();
			$('#btnInsertAll').show();
		} else {
			$('#btnInsert').hide();
			$('#btnInsertAll').hide();
		}
	}
<?php } ?>

function fwrite_submit(f) {

	<?php @include_once ($write_skin_path.'/write.submit.script.php'); ?>

	if (document.getElementById('char_count')) {
	    if (char_min > 0 || char_max > 0) {
		    var cnt = parseInt(document.getElementById('char_count').innerHTML);
			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
		if($dhtml_editor == "ckeditor4" || $dhtml_editor == "cheditor5") {
			echo $editor_js; // 에디터 사용시 자바스크립트에서 내용을 폼필드로 넣어주며 내용이 입력되었는지 검사함
		} else if($dhtml_editor == "SEditor2") { 
			echo editor_submit("wr_content");
		}	
	?>
	
	<?php if($dhtml_editor == "SEditor2") { ?>
		if(wrTrim(f.wr_content.value) == "") {
	        alert("글내용을 입력해 주세요.");
			oEditors.getById["wr_content"].exec("FOCUS");
			return false;
		}
	<?php } else if($dhtml_editor == "DEditor") { ?>
		var validator = new Trex.Validator();
		var DEcontent = Editor.getContent();
		if (!validator.exists(DEcontent)) {
			alert('내용을 입력하세요');
			Editor.focusOnTop();
			return false;
		}
		f.wr_content.value = DEcontent;
	<?php } else if($dhtml_editor == "cheditor") { ?>
		if (document.getElementById('tx_wr_content')) {
		    if (!ed_wr_content.outputBodyText()) { 
			    alert('내용을 입력하십시오.'); 
				ed_wr_content.returnFalse();
		        return false;
		    }
		}
		<?php echo cheditor3('wr_content'); ?>
	<?php } ?>

	var subject = "";
    var content = "";
    $.ajax({
        url: "<?php echo AMINA_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+"')가 포함되어있습니다");
		<?php if($dhtml_editor == "SEditor2") { ?>
			oEditors.getById["wr_content"].exec("FOCUS");
		<?php } else if($dhtml_editor == "DEditor") { ?>
			Editor.focusOnTop();
		<?php } else { ?>
	        if (typeof(ed_wr_content) != "undefined") {
		        ed_wr_content.returnFalse();
	        } else {
		        f.wr_content.focus();
			}
		<?php } ?>
        return false;
    }

	<?php echo $captcha_js; ?>

	document.getElementById('btn_submit').disabled = true;
	document.getElementById('btn_list').disabled = true;
	document.getElementById('loading-icon').style.display = "block";

	<?php if($dhtml_editor == "DEditor") { ?>
		if(!Editor.save()) return false; 
	<?php } ?>

	return true;
}

$('#btn_submit').click(function() { 
	var frm = document.getElementById('fwrite'); 
	var chk = fwrite_submit(frm);
	if(chk) {
		<?php if(AMINA) { ?>
			$('#fwrite').submit();
		<?php } else { ?>
			frm.submit(); 
		<?php } ?>
	}
});
</script>
