<?php
include_once ("./static_data/code.php");
$arr_theme_reg = array();
for($i=1;$i<=10;$i++) {
	$arr_theme_reg[$i] = '';
}

$arr_section_reg = array();
for($i=1;$i<=10;$i++) {
	$arr_section_reg[$i] = '';
}

$admin_type = $this->session->userdata('Adm_Type');
$admin_id	= $this->session->userdata('Adm_Id');
if($mode=='edit') {
	// 칼럼리스트는 자기 글만 삭제 가능
	$write_id			= $result['write_id'];
	if($admin_type == '2') {
		if($write_id !=$admin_id) {
			gf_alert("잘못된 접근입니다.", "/admin/main");
			exit;
		}
	}

    $title      		= $result['title'];
	$title 				= htmlspecialchars($title);

	$content    		= htmlentities($result['content']);
    $partner_idx  		= $result['partner_idx'];
    $tag    			= $result['tag'];
    $hit_count    		= $result['hit_count'];
    $like_count   		= $result['like_count'];
    $is_auto_setting	= $result['is_auto_setting'];
    $is_display			= $result['is_display'];
    $display_date		= $result['display_date'];
	$main_img			= $result['main_img'];
	$video_url			= $result['video_url'];

	$video_url = str_replace('https://www.youtube.com/embed/','', $video_url);
	
	$arr_display_date  	= explode(' ', $display_date);
	$display_date		= $arr_display_date[0];
	$arr_display_time  	= explode(':', $arr_display_date[1]);
	$display_hour		= $arr_display_time[0];
	$display_min		= $arr_display_time[1];
	$display_sec		= $arr_display_time[2];

	$tag		= str_replace(' ', ',', $tag);

	foreach ($arr_theme as $val) {
		$arr_theme_reg[$val['theme_type']] = $val['rank'];
	}


	foreach ($arr_section as $val) {
		$arr_section_reg[$val['etc_section_type']] = $val['rank'];
	}

	$relation_column_style = "none";
	if($is_auto_setting=='N') {
		$relation_column_style = "block";
	}


} else {

	$title          = '';
	$content        = '';
	$partner_idx	= '';
	$tag            = '';
	$hit_count		= 0;
	$like_count		= 0;
	$is_auto_setting= 'Y';
	$display_date	= '';
	$display_hour	= '';
	$display_min	= '';
	$display_sec	= '';
	$main_img		= '';
	$video_url		= '';

	$relation_column_style = "none";

}

$menu_code = '32';
require_once (APPPATH.'views/skin/admin/_content_comm.php');

?>
<link rel="stylesheet" href="<?=DIR_CSS?>/jquery-ui.min.css" />
<script src="<?=DIR_JS?>/jquery-ui.min.js"></script>
<script src="/ckeditor/ckeditor.js"></script>


<form name="input_form" id="input_form" action="/admin/column/column_reg_proc" method="post" enctype="multipart/form-data">
<input type="hidden" name="idx" id="idx" value="<?=$idx?>">
<input type="hidden" id="search_type" name="search_type" value="<?=$search_type?>">
<input type="hidden" id="search_keyword" name="search_keyword" value="<?=$search_keyword?>">
<input type="hidden" id="search_click1" name="search_click1" value="<?=$search_click1?>">
<input type="hidden" id="search_click2" name="search_click2" value="<?=$search_click2?>">
<input type="hidden" id="sort" name="sort" value="<?=$sort?>">
<input type="hidden" id="page" name="page" value="<?=$page?>">
<input type="hidden" id="mode" name="mode" value="<?=$mode?>">
<input type="hidden" id="img_path" name="img_path">
	

<div class="common_table news">
<table>
<tr>
	<th>컬럼명</th>
	<td class="tl">
		<select name="column_idx">
			<option value="">선택</option>
	<?	foreach ($arr_columnlist as $val) {?>
			<option value="<?=$val['idx']?>" <? if($partner_idx==$val['idx']) { echo 'selected';}?>><?=$val['partner_name']?></option>
	<?	}?>
		</select>
	</td>
</tr>
<tr>
	<th>제목</th>
	<td class="tl">
		<input type="text" name="title" id="title" class="input00" size="100" value="<?=$title?>">
	</td>
</tr>
<tr>
	<th>메인이미지</th>
	<td class="tl">
		<input type="file" name="main_img" id="main_img" class="input00" size="100">
		<? 	if($main_img!='') { ?>
		<input type="checkbox" name="is_del_img" value="Y">삭제
		<img src="<?=$main_img?>" width="100px"></br>
		<?	} else {
				$main_img = '';
			}
		?>
		<input type="hidden" name="org_main_img" id="org_main_img" value="<?=$main_img?>">

	</td>
</tr>
<tr>
	<th>youtube 주소</th>
	<td class="tl">
		https://youtu.be/<input type="text" name="video_url" id="video_url" class="input00" value="<?=$video_url?>" style="width:200px"> (키만 넣어주세요.)
	</td>
</tr>
<tr>
	<th>칼럼내용</th>
	<td>
		<!-- <textarea id="content" name="content"><?=$content?></textarea> -->
		<textarea name="content" id="ir1" style="width:100%; height:500px;" /><?=$content?></textarea>
	</td>
</tr>
<tr>
	<th>태그</th>
	<td class="tl">
		<input type="text" name="tag" id="tag" class="type01" size="50" value="<?=$tag?>"> 최대 5개까지 입력 가능(,로 구분해주세요.)
	</td>
</tr>
<tr>
	<th>조회수</th>
	<td class="tl">
		<input type="text" name="hit_count" id="hit_count" class="type03" size="10" value="<?=$hit_count?>"> (관리자가 임의적으로 조회수를 설정할 수 있습니다.)
	</td>
</tr>
<tr>
	<th>좋아요수</th>
	<td class="tl">
		<input type="text" name="like_count" id="like_count" class="type03" size="10" value="<?=$like_count?>"> (관리자가 임의적으로 좋아요수를 설정할 수 있으나 조회수 이상이 될 수는 없습니다)
	</td>
</tr>
<tr>
	<th>관련연재</td>
	<td class="tl">
		<input type="radio" name="is_auto_setting" id="is_auto_setting" onclick="click_relation_news_auto_setting('Y');" value="Y" <? if($is_auto_setting=='Y') { echo 'checked';}?>> 자동설정&nbsp;&nbsp;
		<input type="radio" name="is_auto_setting" id="is_auto_setting" onclick="click_relation_news_auto_setting('N');" value="N" <? if($is_auto_setting=='N') { echo 'checked';}?>> 수동설정
		<div class="two_box_type01 clearfix" id="no_auto_setting_content" style="display:<?=$relation_column_style?>; margin-top:10px;">
			<div class="con">
			<div class="searh_area fn mb10">
				<input type="text" name="article_keyword" id="article_keyword" class="input00" size="20" placeholder="검색어 입력"  onkeypress="if( event.keyCode==13 ){search_article();}">
				<a href="javascript:search_article();" class="btn"><i class="fa moving_all fa-search" style="margin-left:8px;"></i></a>
			</div>
			 <div class="mb10">
				 <input type="radio" name="article_sort" id="article_sort" value="1"  onclick="search_article();" checked>&nbsp;최신순&nbsp;
				 <input type="radio" name="article_sort" id="article_sort" value="2" onclick="search_article();">&nbsp;오래된순&nbsp;

				&nbsp;&nbsp;&nbsp;검색결과&nbsp;  <span class="mark" id="result_count">0</span>건
			</div>
			<div class="list scs">
				<ul id="result">
				</ul>
			</div>
		</div>
		<div class="con">
			<h3 class="mb10">선택된 뉴스 항목</h3>
			<div class="list type02 scs">
				<ul id="selected_news">
					<? 	$i=1;
						foreach ($arr_relation_article as $val) {?>
						<li><input type="checkbox" name="relation_idxs[]" id="relation_idx_<?=$i?>" value="<?=$val['relation_article_idx']?>" onclick="delete_article('<?=$i?>');" checked><a href="/web/news/column_view/<?=$val['relation_article_idx']?>" target="_blank"><?=$val['title']?></a></li>
					<?		$i=1;
						} 
					
					?>
				</ul>
			</div>
		</div>

	</td>
</tr>
</table>

<? if($admin_type == '0') {?>
<h2 class="subtitle"><span>PC</span>테마설정</h2>
<table>
	<tr>
		<th>헤드라인<br />칼럼<br />(모바일공통)</th>
		<td class="tl">
			<div class="opt_box">

			<select name="theme_type7">
				<option value="">순위설정</option>
		<? for($i=1;$i<=$def_arr_column_theme[7]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_theme_reg[7] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/theme_column_1.png" width="400px">
		</td>
	</tr>
	<tr>
		<th>오늘의<br />칼럼<br/>(모바일공통)</th>
		<td class="tl">
			<div class="opt_box">

			<select name="theme_type8">
				<option value="">순위설정</option>
		<? for($i=1;$i<=$def_arr_column_theme[8]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_theme_reg[8] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/theme_column_2_1.png" width="300px">
			<img src="/img/admin/theme_column_2_2.png" width="600px">

		</td>
	</tr>
	<tr>
		<th>추천연재<br />(모바일공통)</th>
		<td class="tl">
			<div class="opt_box">

			<select name="theme_type9">
				<option value="">순위선택</option>
		<? for($i=1;$i<=$def_arr_column_theme[9]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_theme_reg[9] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/theme_column_3_1.png" width="300px">
			<img src="/img/admin/theme_column_3_2.png" width="400px">
		</td>
	</tr>
</table>

<h2 class="subtitle"><span>모바일</span>테마설정</h2>
<table>
	<tr>
		<th>추천칼럼</th>
		<td class="tl">
			<div class="opt_box">

			<select name="theme_type10">
				<option value="">순위선택</option>
		<? for($i=1;$i<=$def_arr_column_theme[10]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_theme_reg[10] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/theme_column_4.png" width="300px">
		</td>
	</tr>

</table>



<h2 class="subtitle">기타섹션<span>(모바일공통)</span></h2>
<table>

	<tr>
		<th>인기영상</th>
		<td class="tl">
			<div class="opt_box">

			<select name="section_type1">
				<option value="">순위선택</option>
		<? for($i=1;$i<=$def_arr_etc_section[1]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_section_reg[1] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/news_7.png" width="200px">
		</td>
	</tr>
	<tr>
		<th>인기포토</th>
		<td class="tl">
			<div class="opt_box">

			<select name="section_type2">
				<option value="">순위설정</option>
		<? for($i=1;$i<=$def_arr_etc_section[2]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_section_reg[2] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/news_7.png" width="200px">
		</td>
	</tr>
	<tr>
		<th>은혜로운영상<br />(모바일전용)</th>
		<td class="tl">
			<div class="opt_box">
			<select name="section_type3">
				<option value="">순위설정</option>
		<? for($i=1;$i<=$def_arr_etc_section[3]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_section_reg[3] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/section2.png" width="250px">
		</td>
	</tr>
	<tr>
		<th>카드뉴스</th>
		<td class="tl">
			<div class="opt_box">

			<select name="section_type4">
				<option value="">순위설정</option>
		<? for($i=1;$i<=$def_arr_etc_section[4]['count'];$i++){?>
				<option value="<?=$i?>" <? if($arr_section_reg[4] == $i) { echo 'selected';}?>><?=$i?>위</option>
		<?	}?>
			</select>
			</div>
			<img src="/img/admin/news_10.png" width="250px">
		</td>
	</tr>


</table>
<?}?>
<h2 class="subtitle">등록일시설정</h2>
<table>
	<tr>
		<th>등록일시</th>
		<td class="tl">
		<? if($mode=='add') {?>
			<input type="text" name="display_date" id="display_date" value="<?=$display_date?>" class="type02" size="10" placeholder="예약일">
			<input type="text" name="display_hour" id="display_hour" value="<?=$display_hour?>" class="type03" size="3" placeholder="시">:<input type="text" name="display_min" id="display_min" value="<?=$display_min?>" class="type03" size="3" placeholder="분">:<input type="text" name="display_sec" id="display_sec" value="<?=$display_sec?>" class="type03" size="3" placeholder="초">
		<?} else {?>
			<? if($is_display=='N') {?>
				<input type="text" name="display_date" id="display_date" value="<?=$display_date?>" class="type02" size="10" placeholder="예약일">
				<input type="text" name="display_hour" id="display_hour" value="<?=$display_hour?>" class="type03" size="3" placeholder="시">:<input type="text" name="display_min" id="display_min" value="<?=$display_min?>" class="type03" size="3" placeholder="분">:<input type="text" name="display_sec" id="display_sec" value="<?=$display_sec?>" class="type03" size="3" placeholder="초">

			<? } else {?>

				<input type="hidden" name="display_date" value="<?=$display_date?>">
				<input type="hidden" name="display_hour" value="<?=$display_hour?>">
				<input type="hidden" name="display_min" value="<?=$display_min?>">
				<input type="hidden" name="display_sec" value="<?=$display_sec?>">

				<?=$display_date?> <?=$display_hour?>:<?=$display_min?>:<?=$display_sec?>

		<?		}

			}
		?>
		</td>
	</tr>
</table>
</div>
<div class="write_btn tc">
	<a href="javascript:column_reg_proc();">저장하기</a>
	<a href="/admin/column/column_list/3/<?=$page?>?search_type=<?=$search_type?>&search_keyword=<?=$search_keyword?>&sort=<?=$sort?>&search_click1=<?=$search_click1?>&search_click2=<?=$search_click2?>">목록으로</a>
</div>
</form>




<script type="text/javascript">
var oEditors = [];
var oEditors2 = [];

$(function(){
      nhn.husky.EZCreator.createInIFrame({
          oAppRef: oEditors,
          elPlaceHolder: "ir1",
          sSkinURI: "/smarteditor/SmartEditor2Skin.html",  
          htParams : {
              bUseToolbar : true,             
              bUseVerticalResizer : true,     
              bUseModeChanger : true,         
              fOnBeforeUnload : function(){
              }
          }, 
          fOnAppLoad : function(){
          },
          fCreator: "createSEditor2"
      });
      
      nhn.husky.EZCreator.createInIFrame({
          oAppRef: oEditors2,
          elPlaceHolder: "ir2", 
          sSkinURI: "/smarteditor/SmartEditor2Skin.html",  
          htParams : {
              bUseToolbar : true,             
              bUseVerticalResizer : true,     
              bUseModeChanger : true,         
              fOnBeforeUnload : function(){
              }
          }, 
          fOnAppLoad : function(){
          },
          fCreator: "createSEditor2"
      });

});
</script>

<script type="text/javascript">
$(document).ready(function() {
	/*
	CKEDITOR.replace('content', {
		height: '400px'
	});
	*/

	if("<?=$is_auto_setting?>"=="N") {
		$("#no_auto_setting_content").show();
	}

});

function column_reg_proc(){
	//CKEDITOR.instances.content.updateElement();
	oEditors.getById["ir1"].exec("UPDATE_CONTENTS_FIELD", []);
	//oEditors2.getById["ir2"].exec("UPDATE_CONTENTS_FIELD", []);

	console.log($("#content").val());

	if($("#column_idx").val()=='') {
		alert("칼럼명을 선택해주세요.");
		return false;
	}
	if($("#title").val()=='') {
		alert("제목을 입력해주세요.");
		return false;
	}
	if($("#main_img").val()=='' && $("#org_main_img").val()=='') {
		alert("메인이미지를 입력해주세요.");
		return false;
	}
	/*
	if($("#content").val()=='') {
		alert("칼럼내용을 입력해주세요.");
		return false;
	}
	*/
	if($("#ir1").val()=='' || $("#ir1").val()=='null' || $("#ir1").val()=='&nbsp;' || $("#ir1").val()=='<p>&nbsp;</p>') {
		alert("칼럼내용을 입력해주세요.");
		oEditors.getById["ir1"].exec("focus");
		return false;
	}


	var hit_count 	= parseInt($("#hit_count").val());
	var like_count = parseInt($("#like_count").val());
	if(like_count > hit_count) {
		alert("좋아요수가 조회수 이상이 될수 없습니다.");
		return false;
	}


	var is_auto_setting = $("input[type=radio][id=is_auto_setting]:checked").val();
    if(is_auto_setting == 'Y' && $("#tag").val()=='') {
        alert("관련칼럼을 자동설정 하시려면 tag가 필요합니다.");
        return false;
    }

	$("#input_form").submit();

}

function click_relation_news_auto_setting(type){
	if(type == 'Y') {
		$("#no_auto_setting_content").hide();
	} else {
		$("#no_auto_setting_content").show();
		$("#article_keyword").focus();
	}
}


// 칼럼 검색
function search_article(){
	var article_keyword = $("#article_keyword").val();
	var article_sort = $(":input:radio[name=article_sort]:checked").val();

	if(article_keyword == '') {
		alert("검색어를 입력해주세요");
		return false;
	}
	var form_data = {
		"content_type"			: "<?=DEF_COLUMN_CODE?>",
		"article_keyword"		: article_keyword,
		"sort"					: article_sort,
		"type"					: 'JSON'
	};
	$.ajax({
		url: '/admin/search/search_article_list',
		async : false,
		type : 'POST',
		dataType : 'JSON',
		data : form_data,
		success: function (rtnJson) {
			if(rtnJson.result_code == '0000') {
				if(article_sort==1) {
					data = sortJSON(rtnJson.result_data.list,'reg_date', '321'); // 123 or 321
				} else {
					data = sortJSON(rtnJson.result_data.list,'reg_date', '123'); // 123 or 321
				}
				$('#result_count').html(rtnJson.result_data.count);
				$('#result').empty();

				if(rtnJson.result_data.count == 0) {
					$('#result').html("<li>검색된 내용이 없습니다.</li>");
				} else {
					for(key in data) {
						var title = data[key]['title'];
						title = title.replace(/'/g, "&#039;");
						title = title.replace(/"/g, '&quot;');

						$('#result').append('<li class="title"><a href="javascript:;" onclick="select_article(\''+data[key]['idx']+'\', \''+title+'\');">'+title+'</a></li>');

					}
				}

			} else {
				alert("칼럼검색에 실패했습니다.");
				return false;
			}

		},
		error: function(jqXHR, exception) {
			console.log(jqXHR);
		}
	});
}

function select_article(idx, title){
	var index = ($("input[name=\"relation_idxs[]\"]").length)+1;
	$('#selected_news').append('<li><input type="checkbox" name="relation_idxs[]" id="relation_idx_'+index+'"  value="'+idx+'"  onclick="delete_article('+index+');"><a href="/web/news/column_view/'+idx+'" target="_blank">'+title+'</a></li>');
	$("input[name='relation_idxs[]'][value=" + idx + "]").attr("checked", true);

}

function delete_article(idx) {
	var checkbox_id = 'relation_idx_'+idx;
	if($('input:checkbox[id=checkbox_id]').is(":checked") == false){
		$("#"+checkbox_id).parent().remove();
	}
}


// jquery datepicker
$("#display_date").datepicker({
	inline: true,
	dateFormat: 'yy-mm-dd',
	buttonImage:"/img/btn_date.png",
	showOn: "both",
	buttonImageOnly: true

});

</script>