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

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", G4_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']}개 글만 등록할 수 있습니다. "); 
	}
}

// 임시 저장된 글 갯수
$autosave_count = $autosave_count ? $autosave_count : autosave_count($member['mb_id']);

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

//DHTML for Mobile
if(G4_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 {
		$dhtml_editor = (AMINA == 'g4s') ? 'ckeditor' : '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)
	$post = amina_array_write($write['wr_10']);

	//동영상 주소
	if($amina['video']) $movie = amina_array_video($write['wr_6']);

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

	//구글지도
	if($amina['google_map']) $map = amina_array_map($write['wr_2']);
}

// CSS Load
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($post['chk_poll']) {
		$set_poll = true;
		$poll_display = 'block';
		$poll_btn = '설문수정';
	}

	if($set_poll && $wr_id) $poll = sql_fetch(" select * from {$g4['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", G4_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_map = false;
if($amina['google_map']) {
	$is_map = true;
	if($map['map_lat'] && $map['map_lng']) {
		$map_txt = '설정변경';		
	} else {
		$map_txt = '지도설정';
	}
}

//다음 view
$is_daum_view = false;
if($amina['daum_view']) $is_daum_view = true;

//동영상
$is_video = false;
if($amina['video']) $is_video = true;

//별점
$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;

//캡챠
if($is_guest) {
	if(!$captcha_html) {
		$captcha_html = "<img id=\"kcaptcha_image\" />\n";
		$captcha_html .= "<span class=\"captcha_msg\">왼쪽 글자를 입력하세요.</span>\n";
		$captcha_html .= "<input title=\"왼쪽의 글자를 입력하세요.\" type=\"input\" id=\"captcha_key\" name=\"wr_key\" size=12 itemname=\"자동등록방지\" class=\"wr_m\">\n";
	}
} else {
	$captcha_html = '';
}

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

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

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

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

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

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

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

//Uploader
$is_uploader = '';
$is_uploader_script = '';
if ($is_file && !G4_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(!$post['img_location']) $post['img_location'] = "insert";
	$is_uploader_script = ' onchange="insert_btn(this.value);"';
}

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

if ($dhtml_editor && $dhtml_editor != "ckeditor") {
	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 {
		include_once(G4_LIB_PATH."/cheditor4.lib.php");
		echo "<script src='{$g4['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 'ckeditor'	: $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;
}

$is_autosave = ($is_member && $amina['autosave']) ? true : false;

?>

<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>
<?php if($is_autosave) { // 임시 저장된 글 기능 ?>
	<script src="<?php echo AMINA_URL; ?>/js/autosave.js"></script>
<?php } ?>

<link rel="stylesheet" href="<?php echo $write_skin_url; ?>/write.css" />

<div id="bo_write_wrap" class="deco-write">
<?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-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_it" value="<?php echo $bo_it; ?>">
<input type="hidden" name="bo_linked" value="<?php echo $bo_linked; ?>">
<input type="hidden" name="bo_row" value="<?php echo $bo_row; ?>">
<input type="hidden" name="view_it" value="<?php echo $view_it; ?>">
<input type="hidden" name="wr_8" value="<?php echo $wr_8; ?>">
<input type="hidden" name="wr_4" value="<?php echo $wr_4; ?>">

<?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="'.$post['post_main'].'">'."\n";
		echo '<input type="hidden" name="post_good" value="'.$post['post_good'].'">'."\n";
		echo '<input type="hidden" name="post_rss" value="'.$post['post_rss'].'">'."\n";
	}

	if(G4_IS_MOBILE && file_exists($write_skin_path.'/m.write.skin.php')) {
		include($write_skin_path.'/m.write.skin.php'); 
	} else {
		include($write_skin_path.'/write.skin.php'); 
	}
?>
<div class="clear"></div>
<p class='wr_submit'>
	<a id="btn_submit" href="javascript://" class="abtn write_submit" title="등록하기"><b>글쓰기</b><em>Write</em></a>
	<noscript><input type="submit" value="글쓰기" /></noscript>
	<a id="btn_list" href="<?php echo G4_BBS_URL; ?>/board.php?bo_table=<?php echo $bo_table; ?>&sca=<?php echo urlencode($sca).$frame_opt.$search_opt; ?>" class="abtn write_list" title="돌아가기"><b>목록</b><em>List</em></a>
</p>
<div class="clear"></div>
</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";
	}
?>
</div>
<div id="loading" style="display:none; position:fixed; top:50%; left:50%; margin-top:-10px; margin-left:-110px;text-align:center;">
	<img src="<?php echo AMINA_URL; ?>/img/loader.gif" />
</div>
<?php if(AMINA != "g4s") echo '<script src="'.G4_JS_URL.'/jquery.kcaptcha.js"></script>'."\n"; ?>
<script>

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

function fwrite_submit(f) {

	<?php 

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

	if($dhtml_editor == "ckeditor") {
		echo $editor_js; // 에디터 사용시 자바스크립트에서 내용을 폼필드로 넣어주며 내용이 입력되었는지 검사함
	} else { 
		if($dhtml_editor == "SEditor2" || $dhtml_editor == "DEditor") { 
			echo editor_submit("wr_content"); 
		?>
			if(wrTrim(f.wr_content.value) == "") {
		        alert("글내용을 입력해 주세요.");
		        f.wr_content.focus();
		        return false;
			}

		<?php 
		} else { 
			if(AMINA != "g4s") { 
		?>
				if (document.getElementById('tx_wr_content')) {
				    if (!ed_wr_content.outputBodyText()) { 
					    alert('내용을 입력하십시오.'); 
						ed_wr_content.returnFalse();
				        return false;
				    }
				}
		<?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 == "cheditor") 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+"')가 포함되어있습니다");
        if (typeof(ed_wr_content) != "undefined") 
            ed_wr_content.returnFalse();
        else 
            f.wr_content.focus();
        return false;
    }

	<?php if($member['mb_id'] && $amina['po_view']) { ?>
		var po_cnt = parseInt(document.getElementById('po_view_summary').innerHTML);
		if (po_cnt > 250) {
			alert("열람요약글은 250글자 이하로 쓰셔야 합니다.");
			return false;
		}
	<?php } ?>

	<?php if(AMINA == "g4s") { 
		echo $captcha_js; // 캡챠 사용시 자바스크립트에서 입력된 캡챠를 검사함
	} else { ?>
		if (!check_kcaptcha(f.wr_key)) {
		    return false;
	    }
	<?php } ?>

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

	return true;
}

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

</script>
