<?php
include_once('./_common.php');

$g5['title'] = $g4['title'] = '연동 게시물 검색';

include_once(G5_PATH.'/head.sub.php');
include_once(AMINA_PATH.'/css.php');

if($action == 'search' && !$bo_sch) alert("연동할 게시판을 선택해 주세요.");

//Naver Style
function search_paging($write_pages, $cur_page, $total_page, $url, $add="") {

		if(!$cur_page) $cur_page = 1;
		if(!$total_page) $total_page = 1;

		$str = '';

		if ($cur_page < 2) {
			//$str .= '<a class="direction" title="맨앞페이지"><span>‹‹</span><em>맨앞</em></a>';
		} else {
			$str .= '<a href="'.$url.'1'.$add.'" class="direction" title="맨앞페이지"><span>처음</span></a>';
		}

		$start_page = ( ( (int)( ($cur_page - 1 ) / $write_pages ) ) * $write_pages ) + 1;
        $end_page = $start_page + $write_pages - 1;

        if ($end_page >= $total_page) { 
			$end_page = $total_page;
		}

        if ($start_page > 1) { 
			$str .= '<a href="'.$url.($start_page-1).$add.'" class="direction" title="이전페이지"><span>이전</span></a>'; 
		} else {
			//$str .= '<a class="direction" title="이전페이지"><span>‹</span><em>이전</em></a>'; 
		}

        if ($total_page > 0){
                for ($k=$start_page;$k<=$end_page;$k++){
                        if ($cur_page != $k) {
		                    $str .= '<a href="'.$url.$k.$add.'">'.$k.'</a>';
                        } else {
	                        $str .= '<strong>'.$k.'</strong> ';
						}
                }
        }

        if ($total_page > $end_page) {
			$str .= '<a href="'.$url.($end_page+1).$add.'" class="direction" title="다음페이지"><span>다음</span></a>';
		} else {
			//$str .= '<a class="direction" title="다음페이지"><em>다음</em><span>›</span></a>';
		}

		if ($cur_page < $total_page) {
			$str .= '<a href="'.$url.($total_page).$add.'" class="direction" title="맨뒤페이지"><span>맨뒤</span></a>';
		} else {
			//$str .= '<a class="direction" title="맨뒤페이지"><em>맨뒤</em><span>››</span></a>';
		}

		return $str;
}

function search_get_selected($field, $value) {
    return ($field==$value) ? ' selected="selected"' : '';
}

$list = array();

$total_count = 0;

if ($stx && $bo_sch) {
	$stx = strip_tags($stx);
	$stx = preg_replace('/[[:punct:]]/u', '', $stx); // 특수문자 제거
	$stx = preg_replace('/\//', '\/', trim($stx));
    $sop = strtolower($sop);
    if (!$sop || !($sop == 'and' || $sop == 'or')) $sop = 'and'; // 연산자 and , or
    $srows = isset($_GET['srows']) ? $_GET['srows'] : 10;
    if (!$srows) $srows = 10; // 한페이지에 출력하는 검색 행수

    $search_query = 'sfl='.urlencode($sfl).'&stx='.urlencode($stx).'&sop='.$sop;

	$text_stx = get_text(stripslashes($stx));

    $op1 = '';

    // 검색어를 구분자로 나눈다. 여기서는 공백
    $s = explode(' ', strip_tags($stx));

    // 검색필드를 구분자로 나눈다. 여기서는 +
    $field = explode('||', trim($sfl));

    $str = '(';
    for ($i=0; $i<count($s); $i++) {
        if (trim($s[$i]) == '') continue;

        $search_str = $s[$i];
        $str .= $op1;
        $str .= "(";

        $op2 = '';
        // 필드의 수만큼 다중 필드 검색 가능 (필드1+필드2...)
        for ($k=0; $k<count($field); $k++) {
            $str .= $op2;
            switch ($field[$k]) {
                case 'mb_id' :
                case 'wr_name' :
                    $str .= "$field[$k] = '$s[$i]'";
                    break;
                case 'wr_subject' :
                case 'wr_content' :
                    if (preg_match("/[a-zA-Z]/", $search_str))
                        $str .= "INSTR(LOWER({$field[$k]}), LOWER('{$search_str}'))";
                    else
                        $str .= "INSTR({$field[$k]}, '{$search_str}')";
                    break;
                default :
                    $str .= "1=0"; // 항상 거짓
                    break;
            }
            $op2 = " or ";
        }
        $str .= ")";

        $op1 = " {$sop} ";
    }
    $str .= ")";

    $sql_search = $str;

    $time1 = get_microtime();

	$tmp_write_table   = $g5['write_prefix'] . $bo_sch;
	$a_total = sql_fetch("select count(*) as cnt from {$tmp_write_table} where wr_is_comment = 0 and $sql_search ", false);
	$total_count = $a_total['cnt'];
    $rows = $srows;
	$total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
    if ($page == "") { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
    $from_record = ($page - 1) * $rows; // 시작 열을 구함

	$sql = " select * from {$tmp_write_table} where wr_is_comment = 0 and {$sql_search} order by wr_id desc limit {$from_record}, {$rows} ";
    $result = sql_query($sql, false);
    for ($i=0; $row=sql_fetch_array($result); $i++) {
		// 비밀글은 검색 불가
		if (strstr($row['wr_option'], 'secret')) $row['wr_content'] = '[비밀글 입니다.]';
		$list[$i] = $row;
    }
}

//검색 게시판 정리
if(!$is_admin) {
	$gr_admin = $is_admin ? '' : "and gr_10 <> 'admin' ";
	$bo_admin = $is_admin ? '' : "and bo_10 <> 'admin' ";
}

if(AMINA) {
	$gr_order = 'gr_order';
	$gr_show = "and gr_show_menu = '1' ".$gr_admin;
	$gr_show .= G5_IS_MOBILE ? "and gr_device <> 'pc'" : "and gr_device <> 'mobile'";
	$bo_order = 'bo_order';
	$bo_show = "and bo_show_menu = '1' ".$bo_admin;
	$bo_search = "and bo_use_search = '1'";
	$bo_sql = G5_IS_MOBILE ? "bo_device <> 'pc'" : "bo_device <> 'mobile'";
} else {
	$gr_order = 'gr_10';
	$gr_show = "and gr_10 <> 'none' ".$gr_admin;
	$bo_order = 'bo_order_search';
	$bo_show = $bo_admin;
	$bo_search = "and bo_use_search = '1'";
	$bo_sql = G5_IS_MOBILE ? "bo_10 <> 'none' and bo_10 <> 'pc'" : "bo_10 <> 'none' and bo_10 <> 'mobile'";
}

//게시판 정리
$bo = array();
$z = 0;
$result = sql_query(" select gr_id from {$g5['group_table']} where 1 $gr_show order by $gr_order ");
for ($i=0; $row=sql_fetch_array($result); $i++) {
	$result1 = sql_query(" select bo_table, bo_subject from {$g5['board_table']} where gr_id = '{$row['gr_id']}' $bo_show and $bo_sql order by $bo_order ");
	for ($k=0; $row1=sql_fetch_array($result1); $k++) {
		$bo[$z] = $row1;
		$z++;
	}
}

if (!$sfl) $sfl = 'wr_subject';
if (!$sop) $sop = 'or';

$sm = G5_IS_MOBILE ? ' class="sm"' : '';

if($action == "linked") {

?>
	<script>
		function initialize() {
			var tmp_bo = parent.document.fwrite.wr_4.value;
			var tmp_wr = parent.document.fwrite.wr_8.value;
			
			if(tmp_bo && tmp_wr) {
				document.location.href = './search.wr.php?bo_info=' + tmp_bo + '&wr_info=' + tmp_wr;
			}
		}

		addLoadEvent(function() {
			initialize();
		});
	</script>
<?php } ?>

<style>
body { margin:0px; padding:0px; font:normal 12px dotum; -webkit-text-size-adjust:100%; background:#fff; color:#222; }
a { color:#222 !important; text-decoration:none; }
a:hover { color:crimson !important; text-decoration:none; }
#at-search { padding:0px 15px; }
#at-search form { padding:0px; margin:0px; overflow:hidden; display:inline !important; }
#at-search select { margin-top:5px; display: inline-block; padding: 4px 6px; font-size: 12px; color: #555555; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; vertical-align: middle; height: 30px; *margin-top: 4px; line-height: 30px; border: 1px solid #cccccc; background-color: #ffffff; }
#at-search select:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; }
#at-search input[type="text"] { margin-top:5px; display: inline-block; height: 20px; padding: 4px 6px; font-size: 12px; color: #555555; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; vertical-align: middle; height: 20px; *margin-top: 4px; border: 1px solid #cccccc; background-color: #ffffff; }
#at-search input[type="text"]{ background-color: #ffffff; border: 1px solid #cccccc; -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -moz-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075); -webkit-transition: border linear .2s, box-shadow linear .2s;  -moz-transition: border linear .2s, box-shadow linear .2s;  -o-transition: border linear .2s, box-shadow linear .2s;  transition: border linear .2s, box-shadow linear .2s; }
#at-search input[type="text"]:focus{ border-color: rgba(82, 168, 236, 0.8); outline: 0; outline: thin dotted \9; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(82,168,236,.6); }
#at-search button[type="submit"] { display: inline-block; *display: inline; *zoom: 1; padding: 4px 12px; margin: 0; margin-top:5px; font-size: 12px; line-height: 20px; text-align: center; vertical-align: middle; cursor: pointer; color: #333333; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); background-color: #f5f5f5; background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6)); background-image: -webkit-linear-gradient(top, #ffffff, #e6e6e6); background-image: -o-linear-gradient(top, #ffffff, #e6e6e6); background-image: linear-gradient(to bottom, #ffffff, #e6e6e6); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe6e6e6', GradientType=0); border-color: #e6e6e6 #e6e6e6 #bfbfbf; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); *background-color: #e6e6e6; filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border: 1px solid #cccccc; *border: 0; border-bottom-color: #b3b3b3; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; *margin-left: .3em; -webkit-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); }
#at-search button[type="submit"]:hover, #at-search input[type="submit"]:focus, #at-search input[type="submit"]:active { color: #333333; background-color: #e6e6e6; *background-color: #d9d9d9; }
#at-search button[type="submit"].active { background-color: #cccccc \9; }
#at-search button[type="submit"]:hover, #at-search input[type="submit"]:focus { color: #333333; text-decoration: none; background-position: 0 -15px; -webkit-transition: background-position 0.1s linear; -moz-transition: background-position 0.1s linear; -o-transition: background-position 0.1s linear; transition: background-position 0.1s linear; }
#at-search button[type="submit"]:focus { outline: thin dotted #333; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; }
#at-search button[type="submit"]:active { background-image: none; outline: 0; -webkit-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); box-shadow: inset 0 2px 4px rgba(0,0,0,.15), 0 1px 2px rgba(0,0,0,.05); }

#at-search .s-box { margin:0px; padding: 15px 30px 15px 15px; border-left-color: rgb(238, 238, 238); border-left-width: 5px; border-left-style: solid; }
#at-search .s-black { color:#fff; font-weight:bold; border-color: rgb(0, 0, 0); background-color: rgb(51, 51, 51); }
#at-search .s-black a { color:#fff; text-decoration:none; }
#at-search .s-nobr { display:block; text-overflow:ellipsis; white-space:nowrap; word-wrap:normal; overflow:hidden;} 

#at-search ul.s-list { list-style:none; padding:0; margin:0; } 
#at-search ul.s-list li { border-bottom:1px solid #ddd; padding:12px; display:block; overflow:hidden;} 
#at-search ul.s-list li a { text-decoration:none; } 
#at-search ul.s-list li strong { display:block; font-weight:bold; font-size:14px; text-overflow:ellipsis; white-space:nowrap; word-wrap:normal; overflow:hidden; padding-top:10px; } 
#at-search ul.s-list li strong.sm { font-size:16px; } 
#at-search ul.s-list li p { display:block; padding:0px; margin:10px 0px 0px; color:#787878; text-overflow:ellipsis; white-space:nowrap; word-wrap:normal; overflow:hidden;} 
#at-search ul.s-list li p a { color:#787878; } 
#at-search ul.s-list li .txt { display:block; padding:0px; margin:10px 0px 0px; color:#787878; line-height:1.5; text-overflow:ellipsis; white-space:nowrap; word-wrap:normal; overflow:hidden;} 
#at-search .new-win { float:right; display:inline-block; padding-left:8px; } 

#at-search .paginate{ padding:15px 0px;text-align:center;line-height:normal; }
#at-search .paginate a, #at-search .paginate strong{ display:inline-block;position:relative;margin:0 -2px;padding:2px 8px;font-weight:bold;font-size:12px;font-family:Tahoma, Sans-serif;color:#333;line-height:normal;text-decoration:none;vertical-align:middle; }
#at-search .paginate a:hover, #at-search .paginate a:active, #at-search .paginate a:focus{ background-color:#f8f8f8; text-decoration:none; color:orangered; }
#at-search .paginate strong{ color:#f60; }
#at-search .paginate .direction{ font-weight:normal;color:#767676;white-space:nowrap; }
#at-search .paginate .direction span{ font:normal 11px dotum; }
#at-search .paginate .direction:hover, #at-search .paginate .direction:active, #at-search .paginate .direction:focus { background-color:#fff;color:#333;text-decoration:none; }

#at-search .sl-thumb { float:left; display:inline-block; margin-right:20px; background:#fff; padding:7px; border:1px solid #bbb;
	-webkit-box-shadow: 0 0px 7px rgba(0, 0, 0, 0.20);
	-moz-box-shadow: 0 0px 7px rgba(0, 0, 0, 0.20); 
	box-shadow: 0 0px 7px rgba(0, 0, 0, 0.20); 
}
#at-search .sl-image { display:block; width:120px; height:70px; overflow:hidden; }
#at-search .sl-image img { display:block; width:100%; height:auto; border:0; }
#at-search .sl-none { display:block; width:100%; text-align:center; padding:150px 0px !important; color:#767676; }
</style>

<div style="height:15px;"></div>

<div id="at-search">
	<div id="at-search-form">	
		<form name="fsearch" onsubmit="return amina_search(this);" method="get">
		<input type="hidden" name="action" value="search">
		<input type="hidden" name="srows" value="<?php echo $srows; ?>">
		<input type="hidden" name="bo_info" value="<?php echo $bo_info; ?>">
		<input type="hidden" name="wr_info" value="<?php echo $wr_info; ?>">
		<select name="bo_sch" id="bo_sch">
			<option value="">연동게시판</option>
			<?php for($i=0; $i < count($bo);$i++) { ?>
				<option value="<?php echo $bo[$i]['bo_table']; ?>"><?php echo $bo[$i]['bo_subject']; ?></option>
			<?php } ?>
		</select>
		<script>document.getElementById("bo_sch").value = "<?php echo $bo_sch ? $bo_sch : $bo_info; ?>";</script>
		<select name="sfl" id="sfl">
			<option value="wr_subject||wr_content"<?php echo search_get_selected($_GET['sfl'], "wr_subject||wr_content") ?>>제목+내용</option>
	        <option value="wr_subject"<?php echo search_get_selected($_GET['sfl'], "wr_subject") ?>>제목</option>
		    <option value="wr_content"<?php echo search_get_selected($_GET['sfl'], "wr_content") ?>>내용</option>
			<option value="mb_id"<?php echo search_get_selected($_GET['sfl'], "mb_id") ?>>회원아이디</option>
	        <option value="wr_name"<?php echo search_get_selected($_GET['sfl'], "wr_name") ?>>이름</option>
		</select>
	    <select name="sop" id="sop">
		    <option value="and"<?php echo search_get_selected($_GET['sop'], "and") ?>>그리고</option>
			<option value="or"<?php echo search_get_selected($_GET['sfl'], "or") ?>>또는</option>
	    </select>
		<input type="text" name="stx" value="<?php echo $text_stx ?>" id="stx" required class="frm_input required" maxlength="20">
		<button type="submit"><i class="fa fa-search fa-lg"></i></button>
		</form>
	</div>

	<div style="height:20px;"></div>

    <?php if ($bo_info && $wr_info) { 
		$link = array();
		$link_write_table   = $g5['write_prefix'] . $bo_info;
		$link = sql_fetch(" select * from {$link_write_table} where wr_id = '{$wr_info}' ", false);

		if($link['wr_id']) {
	 ?>
		<div class="sl-box">
			<div class="s-box s-black s-nobr">
				<span style="float:right;"><a href="javascript:link_insert('', '', 'del');"><span style="color:#fff;font-weight:normal;"><i class="fa fa-times-circle"></i> 삭제</span></a></span>
				<i class="fa fa-check-circle"></i> 현재 다음 게시물과 연동되어 있습니다.
			</div>
			<ul class="s-list">
	        <?php
				$thumb = '';	
				$link['file'] = get_file($bo_info, $link['wr_id']);
				list($img_url) = amina_thumb_img($link['file'], $link['wr_6'], $link['wr_content'], 1, $link['wr_4'], $link['wr_8']);
				$thumb = $img_url ? amina_make_thumb($img_url, 120, 70) : $img_url;
			?>
		        <li style="border:0px;">
				<?php if($thumb) { ?>
					<span class="sl-thumb">
						<a href="javascript:search_insert('<?php echo $bo_info; ?>', '<?php echo $wr_info; ?>');">
							<span class="sl-image"><img src="<?php echo $thumb; ?>" alt="" /></span>
						</a>
					</span>
				<?php } ?>									    
                <strong<?php echo $sm; ?>>
	                <span class="new-win">
						<a href="<?php echo G5_BBS_URL;?>/board.php?bo_table=<?php echo $bo_info; ?>&wr_id=<?php echo $wr_info; ?>" target="_blank"><i class="fa fa-eye"></i></a>
					</span>
					<a href="javascript:link_insert('<?php echo $bo_info; ?>', '<?php echo $wr_info; ?>');"><?php echo amina_text($link['wr_subject']); ?></a>
				</strong>
				<div class="txt"><?php echo amina_cut($link['wr_content'], 160); ?></div>
                <p>
					<i class="fa fa-user"></i> <?php echo $link['wr_name'] ?>
					&nbsp;&nbsp;
					<i class="fa fa-clock-o"></i> <?php echo $link['wr_datetime'] ?>
				</p>
	            </li>
			</ul>
		</div>
	<?php } } ?>

	<div id="at-search-result">
		<div class="s-box s-black s-nobr">
			<i class="fa fa-check-circle"></i> 
			<?php if ($stx && $bo_sch) { ?>
				총 <b><?php echo number_format($total_count); ?></b>개의 연동 가능한 게시물이 있습니다.
			<?php } else { ?>
				검색어는 두글자 이상 / 공백은 하나만 입력해 주세요.
			<?php } ?>
		</div>

	    <?php if ($stx && $bo_sch) { ?>
	        <ul class="s-list">
	        <?php
				$sch_cnt = count($list);

				for ($i=0; $i < $sch_cnt; $i++) {
					$thumb = '';	
					$list[$i]['file'] = get_file($bo_sch, $list[$i]['wr_id']);
					list($img_url) = amina_thumb_img($list[$i]['file'], $list[$i]['wr_6'], $list[$i]['wr_content'], 1, $list[$i]['wr_4'], $list[$i]['wr_8']);
					$thumb = $img_url ? amina_make_thumb($img_url, 120, 70) : $img_url;
			?>
		        <li>
				<?php if($thumb) { ?>
					<span class="sl-thumb">
						<a href="javascript:link_insert('<?php echo $bo_sch; ?>', '<?php echo $list[$i]['wr_id']; ?>');">
							<span class="sl-image"><img src="<?php echo $thumb; ?>" alt="" /></span>
						</a>
					</span>
				<?php } ?>									    
                <strong<?php echo $sm; ?>>
	                <span class="new-win">
						<a href="<?php echo G5_BBS_URL;?>/board.php?bo_table=<?php echo $bo_sch; ?>&wr_id=<?php echo $list[$i]['wr_id']; ?>" target="_blank"><i class="fa fa-eye"></i></a>
					</span>
					<a href="javascript:link_insert('<?php echo $bo_sch; ?>', '<?php echo $list[$i]['wr_id']; ?>');"><?php echo amina_text($list[$i]['wr_subject']); ?></a>
				</strong>
				<div class="txt"><?php echo amina_cut($list[$i]['wr_content'], 160); ?></div>
                <p>
					<i class="fa fa-user"></i> <?php echo $list[$i]['wr_name'] ?>
					&nbsp;&nbsp;
					<i class="fa fa-clock-o"></i> <?php echo $list[$i]['wr_datetime'] ?>
				</p>
            </li>
	        <?php }  ?>
			<?php if($sch_cnt == 0) { ?>
		        <li class="sl-none">
					찾으시는 게시물이 없습니다.
	            </li>
			<?php } ?>
			</ul>

			<div class="paginate">
			<?php 
				if(AMINA) {
					$page_rows = G5_IS_MOBILE ? $config['cf_mobile_pages'] : $config['cf_write_pages'];
				} else {
					$page_rows = $config['cf_write_pages'];
				}
				$search_paging_href = $_SERVER['PHP_SELF'].'?'.$search_query.'&bo_sch='.$bo_sch.'&srows='.$srows.'&bo_info='.$bo_info.'&wr_info='.$wr_info.'&page=';
				echo search_paging($page_rows, $page, $total_page, $search_paging_href); ?>
			</div>
		<?php } ?>
	</div>

	<script> 
		function link_insert(link_bo, link_wr, link_del) {
			parent.document.fwrite.wr_4.value = link_bo;
			parent.document.fwrite.wr_8.value = link_wr;
			if(link_del) {
				parent.document.getElementById('wr_linked').innerHTML = '연동하기';
			} else {
				parent.document.getElementById('wr_linked').innerHTML = '연동수정';
			}
			parent.jQuery.fancybox.close();
	    }
	</script>
	<div class="clear"></div>
</div>

<div style="height:15px;"></div>

<?php include_once(G5_PATH.'/tail.sub.php'); ?>
