<?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_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
	$p_name = 'ep_p_name';
	$cat_name = 'cat_name';
	$subcat_name = 'subcat_name';
} elseif ($row_lang['first_language'] == 2){
	//tc
	$p_name = 'cp_p_name';
	$cat_name = 'cp_cat_name';
	$subcat_name = 'cp_subcat_name';
} elseif ($row_lang['first_language'] == 3){
	//sc
	$p_name = 'sp_p_name';
	$cat_name = 'sp_cat_name';
	$subcat_name = 'sp_subcat_name';
}

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



if (isset($_GET['cat_id'])) {
	$cat_id=$_GET['cat_id'];
	$sql_subcate = mysql_query('SELECT * FROM subcate WHERE match_cat_id = '.$cat_id.' AND  `show` = 1 ORDER BY rank ASC'); 
	$row_subcate = mysql_fetch_assoc($sql_subcate);
} 


if (isset($_GET['subcat_id'])) {
  $subcat_id=$_GET['subcat_id'];
}

if ($cat_id){
	if ($subcat_id){
		//-------------Product Photo List---------->
		$sql_product = mysql_query("SELECT * FROM product_list WHERE p_subcat_id = ".$subcat_id." ORDER by `rank` ASC");
		$row_product = mysql_fetch_assoc($sql_product);
	} else {
		//-------------Product Photo List---------->
		$sql_product = mysql_query("SELECT * FROM product_list WHERE p_cat_id = ".$cat_id." ORDER by `rank` ASC");
		$row_product = mysql_fetch_assoc($sql_product);
	}
} elseif (!$cat_id){
	$sql_product = mysql_query("SELECT * FROM product_list ORDER by `rank` ASC");
	$row_product = mysql_fetch_assoc($sql_product);	
}


$sql_size = mysql_query('SELECT `photo_w`, `photo_h` FROM `general_setting` WHERE `id` = 1');
$row_size = mysql_fetch_assoc($sql_size);
if(!$row_size['photo_w']){
	$pic_w = DEFAULT_PHOTO_W;
} else {
	$pic_w = $row_size['photo_w'];
}
if(!$row_size['photo_h']){
	$pic_h = DEFAULT_PHOTO_H;
} else {
	$pic_h = $row_size['photo_h'];
}


function count_subcat($count_id){
	$sql = mysql_query('SELECT * FROM `subcate` WHERE match_cat_id = '.$count_id);
	$num_rows = mysql_num_rows($sql);
	if ($num_rows){
		echo $num_rows.' 個副分類';
	} else {
		echo '沒有分類';
	}
}
function count_product($count_id){
	$sql = mysql_query('SELECT * FROM `product_list` WHERE p_cat_id = '.$count_id);
	$num_rows = mysql_num_rows($sql);
	if ($num_rows){
		echo $num_rows.' 件產品';
	} else {
		echo '沒有產品';
	}
}
?>
<!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 rel='stylesheet' href='css/photo.css' type='text/css' media='all' />
<link href="css/css_admin.css" rel="stylesheet" type="text/css">
<link href="../css/tiny.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>
<script type="text/javascript">
$(window).load(function(){
	$('img').each(function(){
		var img_h = $(this).height();
		var img_w = $(this).width();
		var h_fix = (150-img_h)/2;
		var w_fix = (150-img_w)/2;
		
		if (img_w > img_h){
			$(this).css('margin-top',  h_fix+'px');
		} else if (img_h > img_w){
			$(this).css('margin-left', w_fix +'px');
		}
	})
});
  // When the document is ready set up our sortable with it's inherant function(s)
$(document).ready(function() {
	<?php if (!$row_product){?>					   
	$('.check_all, .btn_delete_all').css('display', 'none');
	<?php }?>
						   
  	$('.check_all input[type=checkbox]').click(function(){
		var check_status = $(this).is(':checked');
		if(check_status == true){
			$('input[type=checkbox]').attr('checked', true);
		} else {
			$('input[type=checkbox]').attr('checked', false);
		}
	});

	$('.btn_delete_all').click(function(){
		updateDelete();
		var delete_id = $('#delete_val').val();
		var dataString = 'delete_items='+ delete_id;
		var count = $(".checkbox:checked").length;
		
		if(!delete_id){
			alert('請選擇要刪除的產品');
		} else {		
			if (confirm("要刪除選擇的 "+count+" 件產品?")){
				$.ajax({
					type: "POST",
					url: "ajax/delete_multi_product.php",
					data: dataString,
					cache: false,
					success: function(html){
						$("#info").html(html);
					}
				});
			}
		}
	});

	var table_name = 'product_list';
	var rank_name = 'rank';
	var id_name = 'p_id';
	
	$("#photo-list").sortable({
      handle : '.handle',
      update : function () {
		  var order = $('#photo-list').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);
	
	
	$('#select_cate').change(function(){
		var select_value = $(this).val();
		location.href = '?cat_id=' + select_value;
	});
	
	$('#select_subcate').change(function(){
		var select_value = $(this).val();
		if (select_value==''){
			location.href = '?cat_id=<?php echo $cat_id;?>';
		} else {
			location.href = '?cat_id=<?php echo $cat_id;?>&subcat_id='+select_value;
		}
	});
	
	
	$('.delete').click(function(){
		var this_id = parseInt($(this).attr('rel'));
		var table_name = 'product_list';
		var this_id_name = 'p_id';
		
		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){
					location.reload();
				}
			});
		} else {
			return false;
		}
	})
});

function updateDelete() {         
	var allVals = [];
	$('.checkbox:checked').each(function() {
		allVals.push($(this).val());
	});
	$('#delete_val').val(allVals)
}
	 
function closeJS(){
	location.reload();
}

function dis_upload(){
	var statue = $("#multi_uploader").css("display")
	if (statue == 'none'){
		$("#multi_uploader").css("display", 'block')
		$("#upload_iframe").attr('src', 'upload/upload_multi_product_photo.php?cat_id=<?php echo $cat_id;
			if ($subcat_id){
				echo '&subcat_id='.$subcat_id;
			}
			?>&pic_w=<?php echo $pic_w;?>&pic_h=<?php echo $pic_h;?>')
	} else {
		$("#multi_uploader").css("display", 'none')
		$("#upload_iframe").attr('src', '')
	}
}


</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 href="listOptions.php" id="btn_option">產品屬性</a>
        <?php if ($cat_id){?>
			<a href="listProduct.php" id="btn_back">返回目錄</a>
            <a onClick="dis_upload()" id="btn_add"><div id="add_img"></div>新增</a>
            <?php ;}?>
        <h1>產品管理</h1>
        <table width="100%" border="0" cellpadding="0" cellspacing="1" class="content">
			<tr>
            <td><hr></td>
          </tr>
          <?php if (!$cat_id){?>
          <tr>
          	<td>
            <h2>請選擇分類</h2>
            </td>
          </tr>
          <tr>
          	<td >
            	<?php do { ?>
                <a href="listProduct.php?cat_id=<?=$row_cate["cat_id"]?>">
            	<div class="choose_cate">
                	 <div class="choose_cate_text"> 
                	<?=$row_cate[$cat_name]?><br>
                    <span class="grey_text"><?php count_subcat($row_cate["cat_id"]);?><br>
					<?php count_product($row_cate["cat_id"]);?></span>
                    </div>
                </div>
                </a>
                <?php } while ($row_cate = mysql_fetch_assoc($sql_cate))?>
            </td>
          </tr>
          	<td>
               <span style="color:red">*選擇分類後即可上傅產品<br>
					*按"產品屬性"修改產品屬性
                </span>
            </td>
          
          	<td>&nbsp;
               
            </td>
          
            <?php if ($cat_id){?>
            
            <tr id="multi_uploader">
            <td height="320" >
            <iframe id="upload_iframe" frameborder="0" height="300" width="100%" scrolling="yes" style="display:block"></iframe>
            </td>
            </tr>
            <?php 
            mysql_free_result($sql_subcate);
            mysql_free_result($sql_product);
            }  } else { ?>
          <tr>
          	<td>
            <table width="100%" border="0" cellspacing="0" cellpadding="0" class="content">
              <tr>

                <td width="200"><h2>請選擇副分類</h2></td>
                <td align="right"><a href="listProduct">產品管理</a> - <select id="select_cate" style="width:150px">
           <?php do {?>
              <option value="<?=$row_cate["cat_id"]?>" <?php if ($cat_id==$row_cate["cat_id"]){echo 'selected';}?>><?=$row_cate[$cat_name]?></option>
		   <?php } while ($row_cate = mysql_fetch_assoc($sql_cate));
           ?>
            </select> - 
            <select id="select_subcate" style="width:150px">
              <option value="" <?php if (!$row_subcate){echo 'selected';}?>>顯示所有</option>
           <?php 
		   if ($row_subcate){
			   do {?>
				  <option value="<?=$row_subcate["subcat_id"]?>" <?php if ($subcat_id==$row_subcate["subcat_id"]){echo 'selected';}?>><?=$row_subcate[$subcat_name]?></option>
			   <?php } while ($row_subcate = mysql_fetch_assoc($sql_subcate));
		   }?>
            </select>
				</td>
              </tr>
            </table>
            </td>
          </tr>
          <tr>
            <td>
            <div id="info">
              <p>Drag to re-arrange the order. <br>
                Click the photo to edit the detail of the products.<br>
                Click <span style="background:#090; width:15px; color:#fff">&nbsp; + </span> &nbsp;to add more photos.
              </p>
            </div>
             <div class="check_all"><input type="checkbox" value=""> 選擇所有</div> <a href="#" class="btn_delete_all" title="刪除選擇">刪除選擇</a>
             <div class="clearfix"></div>
            <hr>
            <ul id="photo-list">
            <?php
			    if (!$row_product){
					echo '<span class="submenu" style="color:red">There is no product in this category / subcategory.</span>';
				} else {
					$i =1;
					do {
						if ($row_product["show"] == 2){
							$style = 'style="border: 1px solid #f33"';
						} else {
							$style = '';
						}
						echo '<li id="listItem_'.$row_product["p_id"].'" '.$style.'>
							<input name="deleteProduct" type="checkbox" value="'.$row_product["p_id"].'" class="checkbox">
							<a onclick="TINY.box.show({iframe:\'addProduct.php?p_id='.$row_product["p_id"].'\',boxid:\'frameless\',width:960,height:800,fixed:true,maskid:\'blackmask\',maskopacity:70, closejs:function(){closeJS()}})"><img src="../upload/product_images/'.$row_product["p_image"].'" class="handle"></a>
							<a onClick="TINY.box.show({iframe:\'listProductPhoto.php?id='.$row_product['p_id'].'&album_name='.$row_product[$p_name].'\',boxid:\'frameless\',width:960,height:800,fixed:true,maskid:\'blackmask\',maskopacity:70, closejs:function(){closeJS()}})" class="add_more_photo"></a>
							<a class="delete" rel="'.$row_product['p_id'].'"  title="Delete this photo"></a>
							
							<div class="product_name">'.$row_product[$p_name].'<br>'.$row_product['p_code'].'</div>
						</li>';
						$i++;
					} while ($row_product = mysql_fetch_assoc($sql_product));
				}
                ?>	
            </ul>
            <div class="clearfix"></div>
            <hr>
            <div class="check_all"><input type="checkbox" value=""> 選擇所有</div> <a href="#" class="btn_delete_all" title="刪除選擇">刪除選擇</a> 
            <input type="hidden" id="delete_val" value="">
            </td>
            </tr>
            <?php if ($cat_id){?>
            
            <tr id="multi_uploader">
            <td height="320" width="100%">
            <iframe id="upload_iframe" frameborder="0" height="300" width="100%" scrolling="yes" style="display:block"></iframe>
            </td>
            </tr>
            <?php 
            mysql_free_result($sql_subcate);
            mysql_free_result($sql_product);
            } 
			}?>
           </table>
    	</div>
        </section>
	
</div>

<?php include 'library/bottom.php'; ?>
</body>
</html>