<?php 
require_once 'library/top_application.php';
require_once 'library/logged.php';

//權限 
$sql_right = mysql_query('SELECT `manage_product` FROM `'.TBL_USER.'` WHERE `uid` = '.$_SESSION['Logged_Uid']);
$row_right = mysql_fetch_assoc($sql_right);

if($row_right['manage_product'] != 1){
	header("Location: listUser.php");
}

$sql_cate = mysql_query('SELECT * FROM `cate` ORDER BY `rank` ASC');
$row_cate = mysql_fetch_assoc($sql_cate);


$sql_lang = mysql_query('SELECT `first_language` FROM `general_setting` WHERE `id` = 1');
$row_lang = mysql_fetch_assoc($sql_lang);

if ($row_lang['first_language'] == 1){
	//eng
	$must_subject = 'cat_name';
	$must_sub_subject = 'subcat_name';
	$lang_btn = 'btn_lang_switch_en';
	
	$new_cat_txt = 'Name of new category (ENG)';
	$new_subcat_txt = 'Name of new sub-category (ENG)';
} elseif ($row_lang['first_language'] == 2){
	//tc
	$must_subject = 'cp_cat_name';
	$must_sub_subject = 'cp_subcat_name';
	$lang_btn = 'btn_lang_switch_tc';
	
	$new_cat_txt = '新分類名稱 (繁中)';
	$new_subcat_txt = '新副分類名稱 (繁中)';
} elseif ($row_lang['first_language'] == 3){
	//sc
	$must_subject = 'sp_cat_name';
	$must_sub_subject = 'sp_subcat_name';
	$lang_btn = 'btn_lang_switch_sc';
	
	$new_cat_txt = '新分类名称 (简中)';
	$new_subcat_txt = '新副分类名称 (简中)';
}

function list_subcate($list_cat_id){
	$sql_subcate = mysql_query('SELECT * FROM subcate WHERE match_cat_id = '.$list_cat_id.' ORDER BY rank ASC');
	$row_subcate = mysql_fetch_assoc($sql_subcate);
	if ($row_subcate){
		do {
			if($row_subcate['show']==2){
				$b_color = 'FFB6B6';
			} else {
				$b_color = 'cccccc';
			}
			
			echo '<li id="listSubItem_'.$row_subcate["subcat_id"].'">
					<table border="0" cellpadding="1" cellspacing="1" class="content" bgcolor="#'.$b_color.'">
				  <tr bgcolor="#ffffff">
					<td><div class="green_handle"></td>
					<td width="20" align="center"><div class="sub_rank_no"></div></td>
					<td width="300">
					<input class="subcat_name_input subcat_name" id="subcat_name_'.$row_subcate["subcat_id"].'" type="text" value="'.$row_subcate["subcat_name"].'" style="width:200px" onChange="onlyTextSubCat(\'subcat_name\', '.$row_subcate["subcat_id"].')">
                  <span id="er_subcat_name_'.$row_subcate["subcat_id"].'" class="er_msg"></span>
                  <input class="subcat_name_input cp_subcat_name" id="cp_subcat_name_'.$row_subcate["subcat_id"].'" type="text" value="'.$row_subcate["cp_subcat_name"].'" style="width:150px" onChange="onlyTextSubCat(\'cp_subcat_name\', '.$row_subcate["subcat_id"].')">
                  <span id="er_cp_subcat_name_'.$row_subcate["subcat_id"].'" class="er_msg"></span>
                  <input class="subcat_name_input sp_subcat_name" id="sp_subcat_name_'.$row_subcate["subcat_id"].'" type="text" value="'.$row_subcate["sp_subcat_name"].'" style="width:150px" onChange="onlyTextSubCat(\'sp_subcat_name\', '.$row_subcate["subcat_id"].')">
                  <span id="er_sp_subcat_name_'.$row_subcate["subcat_id"].'" class="er_msg"></span>
					</td>
					<td width="24" align="center" class="show_edit_2">';
					if ($row_subcate['show'] == 1){
                        echo '<a class="showing" rel="show" rev="'.$row_subcate['subcat_id'].'" style="display:block"></a><a class="not_showing" rel="show" rev="'.$row_subcate['subcat_id'].'" style="display:none"></a>';
					}  else {  
                        echo '<a class="showing" rel="show" rev="'.$row_subcate['subcat_id'].'" style="display:none"></a><a class="not_showing" rel="show" rev="'.$row_subcate['subcat_id'].'" style="display:block"></a>';
					} 
			  echo '</td>
                    <td width="24" align="center">
					<a class="btn_delete_2" title="刪除" rel="'.$row_subcate['subcat_id'].'"></a>
					</td>
				  </tr>
				</table>
			</li>';
			
		 } while ($row_subcate = mysql_fetch_assoc($sql_subcate));
	} else {
		echo '<span style="color:red">There is no Subcategory!</span>';
	}
	mysql_free_result($sql_subcate);
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Artech Creative</title>
<link href="css/css_admin.css" rel="stylesheet" type="text/css">
<link href="../css/tiny.css" rel="stylesheet" type="text/css">
<link href="css/drag_list.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-min.js"></script>
<script type="text/javascript" src="../js/tinybox_product.js"></script>
<!--[if IE]>
    <script src="../js/html5.js"></script>
<![endif]-->
<script type="text/javascript">
  // When the document is ready set up our sortable with it's inherant function(s)
$(document).ready(function() {
	var table_name = 'cate';
	var rank_name = 'rank';
	var id_name = 'cat_id';
	var table_name_2 = 'subcate';
	var rank_name_2 = 'rank';
	var id_name_2 = 'subcat_id';
	
	rerank()
	re_subrank()
	
	$('.cat_name_input, .subcat_name_input').css('display', 'none');
	$('.<?php echo $must_subject;?>, .<?php echo $must_sub_subject;?>').css('display', 'block');
	$('#<?php echo $lang_btn;?>').addClass('selected');
	
    $("#content-list").sortable({
      handle : '.handle',
      update : function () {
		  rerank()
		  var order = $(this).sortable('serialize');
  		$("#info").load('ajax/update_rank.php?'+order+'&sortList='+table_name+'&rank_name='+rank_name+'&id_name='+id_name);
      }
    });
	var _preventDefault = function(evt) { evt.preventDefault(); };
	$(".handle").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);
	
	
	$(".sub-list").sortable({
      handle : '.green_handle',
      update : function () {
		  re_subrank()
		  var order = $(this).sortable('serialize');
  		$("#info").load('ajax/update_rank.php?'+order+'&sortList='+table_name_2+'&rank_name='+rank_name_2+'&id_name='+id_name_2);
      }
    });
	var _preventDefault = function(evt) { evt.preventDefault(); };
	$(".green_handle").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);
	
	/***add Cate***/
	$('#btn_add').click(function(){
		$('#new_cate').fadeIn(300);
	});
	$('.btn_close_new_cat').click(function(){
		$('#new_cate').fadeOut(300);
	});
	
	$('.add_cat_ok').click(function(){
		var this_input_value = $('#new_cat_box').val();
		$.ajax({
			type: "POST",
			url: "ajax/update_cate.php",
			data: {"add_cate" : 'yes', "input_field" : '<?php echo $must_subject;?>' , "input_val" : this_input_value },
			cache: false,
			success: function(html){
				window.location.reload(true);
			}
		});
	});
	$('.show_edit').each(function(){
		var btn_show = 	$('.showing', this);
		var btn_not_show = $('.not_showing', this);
		var this_id_name = 'cat_id';
		var this_table = 'cate';
		var this_tr = $(this).closest("table");

		btn_show.click(function(){
			var this_field = $(this).attr('rel');
			var this_id = parseInt($(this).attr('rev'));
			$.ajax({
				type: "POST",
				url: "ajax/update_yesno.php",
				data: {"id_name" : this_id_name, "id" : this_id, "update_field" :this_field, "show" : 2, "table": this_table},
				cache: false,
				success: function(html){
					btn_show.hide();
					btn_not_show.show();
					this_tr.css('background', '#FFB6B6');
				}
			});
		})
		
		btn_not_show.click(function(){
			var this_field = $(this).attr('rel');
			var this_id = parseInt($(this).attr('rev'));
			$.ajax({
				type: "POST",
				url: "ajax/update_yesno.php",
				data: {"id_name" : this_id_name, "id" : this_id, "update_field" :this_field, "show" : 1, "table": this_table},
				cache: false,
				success: function(html){
					btn_show.show();
					btn_not_show.hide();
					this_tr.css('background', '#cccccc');
				}
			});
		})
	})
	
	$('.show_edit_2').each(function(){
		var btn_show = 	$('.showing', this);
		var btn_not_show = $('.not_showing', this);
		var this_id_name = 'subcat_id';
		var this_table = 'subcate';
		var this_tr = $(this).closest("table");

		btn_show.click(function(){
			var this_field = $(this).attr('rel');
			var this_id = parseInt($(this).attr('rev'));
			$.ajax({
				type: "POST",
				url: "ajax/update_yesno.php",
				data: {"id_name" : this_id_name, "id" : this_id, "update_field" :this_field, "show" : 2, "table": this_table},
				cache: false,
				success: function(html){
					btn_show.hide();
					btn_not_show.show();
					this_tr.css('background', '#FFB6B6');
				}
			});
		})
		
		btn_not_show.click(function(){
			var this_field = $(this).attr('rel');
			var this_id = parseInt($(this).attr('rev'));
			$.ajax({
				type: "POST",
				url: "ajax/update_yesno.php",
				data: {"id_name" : this_id_name, "id" : this_id, "update_field" :this_field, "show" : 1, "table": this_table},
				cache: false,
				success: function(html){
					btn_show.show();
					btn_not_show.hide();
					this_tr.css('background', '#cccccc');
				}
			});
		})
	})
	$('.btn_delete').click(function(){
		var this_id = parseInt($(this).attr('rel'));
		var table_name = 'cate';
		var this_id_name = 'cat_id';
		var this_table = $(this).closest("table");
		
		if (confirm("Confirm to delete this content ?")){
			$.ajax({
				type: "POST",
				url: "ajax/delete.php",
				data: {"table" : table_name, "id_name" : this_id_name, "del_id" : this_id},
				cache: false,
				success: function(html){
					$('#info').html(html);
					if(html.indexOf('Delete Success') != -1){
						this_table.fadeOut(300, function(){
							this_table.remove();
							rerank()
						});
					}
				}
			});
		} else {
			return false;
		}
	})
	
	$('.btn_delete_2').click(function(){
		var this_id = parseInt($(this).attr('rel'));
		var table_name = 'subcate';
		var this_id_name = 'subcat_id';
		var this_table = $(this).closest("table");
		
		if (confirm("Confirm to delete this content ?")){
			$.ajax({
				type: "POST",
				url: "ajax/delete.php",
				data: {"table" : table_name, "id_name" : this_id_name, "del_id" : this_id},
				cache: false,
				success: function(html){
					$('#info').html(html);
					if(html.indexOf('Delete Success') != -1){
						this_table.fadeOut(300, function(){
							this_table.remove();
							re_subrank()
						});
					}
				}
			});
		} else {
			return false;
		}
	})
	
	/****edit Cate****/
	$('#content-list > li').each(function(){
		var cat_id = $(this).attr('id').replace('listItem_', '');
		
		var this_input_box = $('.input_cat_name input', this);
		var this_add_subcat = $('.btn_addcate', this);
		var this_new_subcate = $('.new_subcate', this);
		var this_new_subcate_input_box = $('.new_subcate input', this);
		var this_add_subcat_ok = $('.add_subcat_ok', this);
		var this_add_subcat_close = $('.btn_close_new_sub', this);
		

		/*****add subcate*****/
		this_add_subcat.click(function(){
			this_new_subcate.fadeIn(300)
		});
		this_add_subcat_close.click(function(){
			this_new_subcate.fadeOut(300)
		});
		this_add_subcat_ok.click(function(){
			var this_input_value = this_new_subcate_input_box.val();
			$.ajax({
				type: "POST",
				url: "ajax/update_cate.php",
				data: {"match_cat_id" : cat_id, "input_val" : this_input_value, "subcat_name" : '<?php echo $must_sub_subject;?>'},
				cache: false,
				success: function(html){
					window.location.reload(true);
				}
			});
		});
	})
});

function rerank(){
	var i = 1;
	$('.rank_no').each(function(){
		$(this).text(i);
		i = i+1;
	})
}
function re_subrank(){
	$('.sub-list').each(function(){
		var j = 1;
		$('.sub_rank_no', this).each(function(){
			$(this).text(j);
			j = j+1;
		})
	})
}

function onlyTextCat(input_name, id){
	var input_val =  $.trim($('#'+input_name+'_'+id).val());
	var table = 'cate';
	var iChars = "!#$%^@&*+=[]\\\'/{}|\":<>?~_";
	var error = false;
	
	if (!input_val){
		$('#'+input_name+'_'+id).addClass("error");
		$('#er_'+input_name+'_'+id).show();
		$('#er_'+input_name+'_'+id).text("不能留空");	
		error = true
	}
	
	for (var i = 0; i < input_val.length; i++) {
		if (iChars.indexOf(input_val.charAt(i)) != -1) {
			$('#'+input_name+'_'+id).addClass("error");
			$('#er_'+input_name+'_'+id).show();
			$('#er_'+input_name+'_'+id).text("不能有符號");	
			error = true
			break;			  
		} else {
			$('#er_'+input_name+'_'+id).hide();
			$('#'+input_name+'_'+id).removeClass("error");			
		}
	}
	
	if(error == true){
		return
	} else {
		$.ajax({
			type: "POST",
			url: "ajax/update_cate.php",
			data: {"table" : table, "val" : input_val, "field" : input_name, "id" : id},
			cache: false,
			success: function(html){
				$('#er_'+input_name+'_'+id).show();
				$('#er_'+input_name+'_'+id).text("更新城功");
				$('#er_'+input_name+'_'+id).stop(true, true).delay(2000).fadeOut(300);
			}
		});
	}
}

function onlyTextSubCat(input_name, id){
	var input_val = $.trim($('#'+input_name+'_'+id).val());
	var table = 'subcate';
	var iChars = "!#$%^@&*+=[]\\\'/{}|\":<>?~_";
	var error = false;
	
	if (!input_val){
		$('#'+input_name+'_'+id).addClass("error");
		$('#er_'+input_name+'_'+id).show();
		$('#er_'+input_name+'_'+id).text("不能留空");	
		error = true
	}
	
	for (var i = 0; i < input_val.length; i++) {
		if (iChars.indexOf(input_val.charAt(i)) != -1) {
			$('#'+input_name+'_'+id).addClass("error");
			$('#er_'+input_name+'_'+id).show();
			$('#er_'+input_name+'_'+id).text("不能有符號");	
			error = true
			break;			  
		} else {
			$('#er_'+input_name+'_'+id).hide();
			$('#'+input_name+'_'+id).removeClass("error");			
		}
	}
	
	if(error == true){
		return
	} else {
		$.ajax({
			type: "POST",
			url: "ajax/update_cate.php",
			data: {"table" : table, "val" : input_val, "field" : input_name, "id" : id},
			cache: false,
			success: function(html){
				$('#er_'+input_name+'_'+id).show();
				$('#er_'+input_name+'_'+id).html(html);
				$('#er_'+input_name+'_'+id).text("更新城功");
				$('#er_'+input_name+'_'+id).stop(true, true).delay(2000).fadeOut(300);
			}
		});
	}
}

function switch_lang(id){
	if(id == 'en'){
		must_name = 'cat_name';
		must_sub_name = 'subcat_name';
		btn = 'btn_lang_switch_en';
	}
	if(id == 'tc'){
		must_name = 'cp_cat_name';
		must_sub_name = 'cp_subcat_name';
		btn = 'btn_lang_switch_tc';
	}
	if(id == 'sc'){
		must_name = 'sp_cat_name';
		must_sub_name = 'sp_subcat_name';
		btn = 'btn_lang_switch_sc';
	}
	$('.cat_name_input, .subcat_name_input').css('display', 'none');
	$('.'+must_name+', .'+must_sub_name).css('display', 'block');
	
	$('#btn_lang_switch_content a').removeClass('selected');
	$('#'+btn).addClass('selected');
}
</script>
</head>
<body>
<div id="wrap">
  <section id="column_left">
    <?php include 'library/left_menu.php';?>
  </section>
  <section id="column_right">
    <div class="admin_content"> <a id="btn_add">
      <div id="add_img"></div>
      新增</a>
      <h1>產品分類管理</h1>
      <hr>
      <div id="info" class="content">(Drag the <span style="color:red">red square</span> to re-arrange the order.)</div>
      <div id="btn_lang_switch_content"><a href="javascript:switch_lang('en')" id="btn_lang_switch_en">ENG</a> | <a href="javascript:switch_lang('tc')" id="btn_lang_switch_tc">繁</a><br>
        <br>
      </div>
      <table width="100%" border="0" cellpadding="2" cellspacing="1" bgcolor="#CCCCCC" class="content">
        <tr bgcolor="#80031A">
          <td width="15" bgcolor="#EEEEEE"></td>
          <td width="40" bgcolor="#EEEEEE" >Order</td>
          <td width="300" bgcolor="#EEEEEE" >Category Name</td>
          <td bgcolor="#EEEEEE" >Sub-categories</td>
          <td width="60" align="center" bgcolor="#EEEEEE" >Action</td>
          <td width="24" align="center" bgcolor="#EEEEEE" ></td>
        </tr>
      </table>
      <div id="new_cate" style="display:none">
        <table width="100%" border="0" cellpadding="2" cellspacing="1" bgcolor="#FF3333" class="content" style="margin:5px 0 7px 0;">
          <tr bgcolor="#ffffff">
            <td><input value="<?php echo $new_cat_txt;?>"  maxlength="30" style="width:300px;" id="new_cat_box">
              <a class="btn_small_ok add_cat_ok" title="新增分類" style="margin: 8px 2px"></a></td>
            <td width="24" align="center"><a class="btn_close_new_cat" title="關閉" ></a></td>
          </tr>
        </table>
      </div>
      <ul id="content-list">
        <?php
		$i =1;
		do { 
			if($row_cate['show']==2){
				$b_color = 'FFB6B6';
			} else {
				$b_color = 'cccccc';
			}
			?>
          <li id="listItem_<?=$row_cate["cat_id"]?>" >
            <table width="100%" border="0" cellpadding="2" cellspacing="1" bgcolor="#<?php echo $b_color;?>" class="content" >
              <tr bgcolor="#FFFFFF">
                <td align="center" width="15" class="handle"></td>
                <td width="40" align="center" valign="middle"><div class="rank_no"></div></td>
                <td width="300" valign="middle" ><input class="cat_name_input cat_name" id="cat_name_<?=$row_cate["cat_id"]?>" type="text" value="<?php echo $row_cate["cat_name"]; ?>" style="width:200px" onChange="onlyTextCat('cat_name', <?=$row_cate["cat_id"]?>)">
                  <span id="er_cat_name_<?=$row_cate["cat_id"]?>" class="er_msg"></span>
                  <input class="cat_name_input cp_cat_name" id="cp_cat_name_<?=$row_cate["cat_id"]?>" type="text" value="<?php echo $row_cate["cp_cat_name"]; ?>" style="width:200px" onChange="onlyTextCat('cp_cat_name', <?=$row_cate["cat_id"]?>)">
                  <span id="er_cp_cat_name_<?=$row_cate["cat_id"]?>" class="er_msg"></span>
                  <input class="cat_name_input sp_cat_name" id="sp_cat_name_<?=$row_cate["cat_id"]?>" type="text" value="<?php echo $row_cate["sp_cat_name"]; ?>" style="width:200px" onChange="onlyTextCat('sp_cat_name', <?=$row_cate["cat_id"]?>)">
                  <span id="er_sp_cat_name_<?=$row_cate["cat_id"]?>" class="er_msg"></span>
                  </td>
                  <td valign="baseline"><ul class="sub-list">
                    <?php list_subcate($row_cate['cat_id']) ?>
                    <li id="new_subcate_<?=$row_cate['cat_id']?>" class="new_subcate" style="display:none">
                      <table border="0" cellpadding="1" cellspacing="1" class="content" bgcolor="#FF3333" width="360">
                        <tr bgcolor="#ffffff">
                          <td><input value="<?php echo $new_subcat_txt;?>"  maxlength="30" style="width:200px" style="float:left">
                            <a class="btn_small_ok add_subcat_ok" title="新增副分類" style="margin:8px 8px"></a></td>
                          <td width="24"><a class="btn_close_new_sub" title="關閉"></a></td>
                        </tr>
                      </table>
                    </li>
                  </ul></td>
                <td width="60" align="center" class="show_edit"><?php if ($row_cate['show'] == 1){?>
                  <a class="showing" rel="show" rev="<?php echo $row_cate['cat_id'];?>" style="display:block"></a> <a class="not_showing" rel="show" rev="<?php echo $row_cate['cat_id'];?>" style="display:none"></a>
                  <?php }  else {  ?>
                  <a class="showing" rel="show" rev="<?php echo $row_cate['cat_id'];?>" style="display:none"></a> <a class="not_showing" rel="show" rev="<?php echo $row_cate['cat_id'];?>" style="display:block"></a>
                  <?php } ?>
                  <a class="btn_addcate" title="新增分類" style="cursor:pointer"></a></td>
                <td width="24" align="center"><a class="btn_delete" title="刪除" rel="<?php echo $row_cate['cat_id']; ?>"></a></td>
              </tr>
            </table>
          </li>
          <? $i++;
                } while ($row_cate = mysql_fetch_assoc($sql_cate));
				?>
      </ul>
    </div>
  </section>
</div>
<?php include 'library/bottom.php'; ?>
</body>
</html>