<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	2011/6/5 Lay
*/

require '../../include/loader.php';

html_start("广告位编辑 - VeryIDE");
?>

<!--body start-->
<?php

	//module
	require 'naver.php';
	
	Cached :: loader($appid,"table.adsarea");
	
	$jump = getgpc('jump');
	$parent = getgpc("parent");
	$action = getgpc('action');
	
	$model = getgpc("model");

	//连接数据库
	System :: connect();

	if($action){
	
		$id = getgpc("id");
		$name = getgpc('name');
		$key=trim(getgpc("key"));
		$quote = getgpc("quote");
		$preview = getgpc("image");
		$number = getnum("number",1);
		$show = getnum("show",1);
		$price = getnum("price",0);
		$unit = getgpc("unit");
		$tag = getgpc("tag");
		$description = getgpc("description");
		
		//配置
		$config = $_POST['config'];
		
		//删除空白字符
		$config = fix_white( $config );
		
		$config = format_json( fix_json( $config ) );
		
		$width = getnum("width",0);
		$height = getnum("height",0);
		
		$variable=FilterHtml($_POST["variable"]);
		
		if($model=="type"){
			$parent=0;
		}
		
		switch($action){
			case"add":
			
				//检查权限
				System :: check_func("mod-adsarea-add", false );				
			
				if (!$name || !$key || !preg_match('/^[A-Za-z0-9-_]{2,16}$/',$key) ){
					
					if( !$key ){
						$_G['project']['message']="广告位标识不能为空！";
					}elseif( !$name ){
						$_G['project']['message']="新增类别名称不能为空！";
					}else{
						$_G['project']['message']="标识中有非法字符！";
					}
					
					$_G['project']['class']	="wrong";
					
				}else{
				
					$sql="SELECT id from `mod:adsarea` WHERE `key`= '".$key."'";
					$row = System :: $db -> getOne( $sql );
					
					if( $row ){
						
						$_G['project']['message']="分类标识已经存在！";						
						$_G['project']['class']	="wrong";
						
						$row = array();
						$row["key"] = $key;
						$row['name'] = $name;
						$row["quote"] = $quote;
						
					}else{
						
						$sql="INSERT INTO `mod:adsarea`(name,`key`,parent,quote,number,`show`,preview,price,unit,`description`,width,height,aid,account,dateline,tag,variable,config) values('".$name."','".$key."','".$parent."','".$quote."',".$number.",".$show.",'".$preview."',".$price.",'".$unit."','".$description."',".$width.",".$height.",".$_SESSION['Manager']['id'].",'".$_SESSION['Manager']['account']."',".time().",'".$tag."','".$variable."','".$config."')";
						
						System :: $db -> execute( $sql );
						
						$id = System :: $db -> getInsertId();
						
					}
					
				}
				
			break;
			
			case "edit":
			
				//检查权限
				System :: check_func("mod-adsarea-mod", false );				
			
				$sql="SELECT * FROM `mod:adsarea` WHERE id=".$id;
				
				$row = System :: $db -> getOne( $sql );
				
				if( $row ){					
					$config = fix_json( $row['config'] );					
				}else{
					System :: redirect($jump,"未找到相关广告位!");
				}
				
			break;
			
			case "update":
			
				//检查权限
				System :: check_func("mod-adsarea-mod", false );				
			
				$sql="UPDATE `mod:adsarea` SET name='".$name."',parent='".$parent."',quote='".$quote."',number=".$number.",price=".$price.",`modify`=".time().",preview='".$preview."',`show`=".$show.",unit='".$unit."',description='".$description."',height=".$height.",width=".$width.",tag='".$tag."',variable='".$variable."',config='".$config."' WHERE id=".$id;
				System :: $db -> execute( $sql );
				
				//生成广告
				Adsview :: create("SELECT * FROM `mod:adsarea` WHERE id=".$id);
				
			break;
		}
	
		//更新分类数组缓存
		Cached :: table( $appid, 'mod:adsarea', array( 'jsonde' => array('config') ) );		
		
		//更新分类脚本缓存
		Cached :: script( $appid,"SELECT id,parent,name,`show`,width,height,number,`key`,config FROM `mod:adsarea` WHERE parent>0","ADSAREA","mod.adsarea",array( 'record'=>' #var[{table:id}] = {"id":{table:id},"parent":{table:parent},"name":"{table:name}","show":{table:show},"size":"{table:width}×{table:height}","number":{table:number},"key":"{table:key}","config":{table:config}};'.chr(13) ) );
		
	}

	//转向
	if($action!="edit" && $action && !$_G['project']['message']){
		if($jump){
			System :: redirect($jump,"成功完成操作!");
		}
	
		if($parent){
			System :: redirect("adsarea.list.php?s=key&q=".$key,"广告位编辑成功!");
		}else{
			System :: redirect("adsarea.channel.php","广告分类编辑成功!");
		}
		
	}
	
	?>
    
	<?php   
	echo loader_script(array(VI_BASE."js/mo.color.js"),$_G['product']['charset'],$_G['product']['version']);    
	?>
    
	<script type="text/javascript">
	function _getModel(){
		
		var mod= Mo("input[name=model]").value();
		
		if( mod == "box" ){
			
			Mo("input[name=model]").value("box");
			
			Mo("#extra").show();
			
			Mo("#mode-type").hide();
			Mo("#mode-box").show();
			
		}else{
			
			Mo("input[name=model]").value("type");
			
			Mo("#extra").hide();
			
			Mo("#mode-type").hide();
			Mo("#mode-box").show();
		}
		
	}
	
	function _getExp(){
		Mo("#variable").value("\nif(document.getElementById('test')){	\n\t{SELF}.variable=document.getElementById('test').value;	\n}",true);	
	}
	</script>

	<?php
	
	//显示权限状态
	switch($action){
		case "":
			echo System :: check_func("mod-adsarea-add",true);
		break;
		
		case "edit":
			echo System :: check_func("mod-adsarea-mod",true);
		break;
	}
	
	?>

	<div id="box">
		<form method="post" action="?" mode="edit" verify="true">
        
        <table cellpadding="0" cellspacing="0" class="form">
            
            <tr><td colspan="2" class="section"><strong>基本信息</strong></td></tr>
            
        	<tr>
            	<td width="60"><strong>分类类型：</strong></td>
                <td>
                    <label><input type="radio" class="radio" name="model" value="type" onchange="_getModel();" onclick="_getModel();" /> 频道 </label>
                    <?php
					if( !$action && !count($_CACHE['adsview']['adsarea']) ){
						echo '（添加频道后再添加广告位）';
					}else{
						echo '<label><input type="radio" class="radio" name="model" value="box" onchange="_getModel();" onclick="_getModel();" /> 广告位 </label>';	
					}
					?>
                    <br />
                </td>
                
            </tr>
        
        	<!--tr>
            	<td></td>
                <td>
                    <span id="mode-type">将广告位进行分类管理，可以与网站频道（栏目）一致</span>
                    <span id="mode-box">具体的页面广告位，较多时可以配合分类功能进行方便管理</span>
                </td>                
            </tr-->
        
        	<tr>
            	<td><strong>位置标识：</strong></td>
                <td>
				  <?php
                    if ($action=="edit"){
                        echo '
                        <b class="text-main">'.$row["key"].'</b>
                        <input name="key" type="hidden" id="key" value="'. $row["key"].'" size="35" readonly="true"> ';
						
                    }else{
                        echo '<input name="key" type="text" class="text" id="key" value="'.$row["key"].'" size="35" style="ime-mode:disabled" fix_name="位置标识" fix_desc="请输入位置标识，英文和数字" fix_null="yes" fix_safe="yes" />';
						echo ' <script type="text/javascript">Mo.Tools("Tip","此广告位唯一标识，添加后无法更改<br />必须为英文（尽量不要包含 AD / Clcik / Banner 等字符）");</script>';
						
						echo '
						<a href="javascript:void(0);" onclick="Mo(\'#key\').value(Mo.random(8));">随机生成</a>
						<a href="javascript:void(0);" onclick="Mo(\'#key\').value(\'\');">清空</a>
						';
                    }
                   ?>
                   
                </td>
            </tr>
        
        	<tr>
            	<td><strong>位置别名：</strong></td>
                <td><input name="name" type="text" class="text" id="name" value="<?php echo $row['name'];?>" size="35" fix_name="位置别名" fix_desc="请输入广告位名称" fix_null="yes" />
                <script type="text/javascript">Mo.Tools("Tip","此广告位别名，用于管理和查找");</script>
                </td>
                
            </tr>
            
            <tr>
                <td><strong>所在页面：</strong></td>
                <td><input name="quote" type="text" class="text" id="quote" value="<?php echo $row["quote"];?>" size="70" />
                <script type="text/javascript">Mo.Tools("Tip","此广告位所在页面地址，用于预览广告位，建议不要留空");</script>
                </td>                
            </tr>
        
            <tbody id="extra" cellpadding="0" cellspacing="0" class="form">
            
                <tr><td colspan="2" class="section"><strong>属性设置</strong></td></tr>
            
                <tr>
                    <td width="60"><strong>所属频道：</strong></td>
                    <td>
                        <select name="parent" id="parent">
						<?php			
                        //输出频道
                        foreach($_CACHE['adsview']['adsarea'] as $key){
                            if($key["parent"]=="0"){
                                echo '<option value="'.$key["id"].'">'.$key["name"].'</option>';
                            }
                        }						
                        ?>
                        </select>
                    </td>
                    
                </tr>
                
                <?php
				
		//载入控制文件
		include("include.area.php");
		
		?>
		
		<?php
			//编辑时出现
			if( $action == "edit" && $row["parent"] ){
			
				//加载替补缓存
				Cached :: loader($appid,"table.alternate");				
				
				//替补列表
				$spare = array();
				foreach( $_CACHE['adsview']['alternate'] as $a ){
					if( $a['type'] == $row["type"] ){
						$spare[] = $a;
					}
				}
				
				//////////////////////////////
				
				//已有广告数
				$sql="SELECT name,start,expire FROM `mod:adsview` WHERE `state`>0 and `type`=".$row['id']." and expire>".time()." ORDER BY sort asc,id desc";
				$result = System :: $db -> getAll($sql);
				
			?>
	    
			<tr>
				<td><strong>广告详情：</strong></td>
				<td>
		    
		    <table cellpadding="0" cellspacing="1" border="0" class="gird">			
			<thead>
			    <td colspan="2">
				<b>有效广告：</b><b class="text-yes"><?php echo count($result);?></b> 个
			    </td>
			</thead>
			<?php
			$x = 1;
			foreach( $result as $res ){
			?>
			 <tr>
			    <td colspan="2">
				<b class="text-yes"><?php echo $x++;?>.</b>
				<?php echo $res["name"];?>（<?php echo date("Y/m/d",$res["start"]);?> - <?php echo date("Y/m/d",$res["expire"]);?>）
			    </td>
			</tr>
			<?php
			}
			?>
			<thead>
			    <td colspan="2">
				<b>替补数量：</b><b class="text-yes"><?php echo count($spare);?></b> 个
			    </td>
			</thead>
			<?php
			$x = 1;
			foreach( $spare as $a ){
			?>
			 <tr>
			    <td colspan="2">
				<b class="text-yes"><?php echo $x++;?>.</b>
				<?php echo $a["name"];?>
				<?php
				if( $a["id"] == $row['id'] ){
					echo '<span class="text-no">（当前）</span>';
				}
				?>
			    </td>
			</tr>
			<?php
			}
			?>
		   </table>
		    
				</td>
				
			</tr>
	    
	    <?php
			}
			?>

            <tr><td colspan="2" class="section"><strong>备注信息</strong></td></tr>
            
                <tr>
                    <td><strong>广告价格：</strong></td>
                    <td>
                        <input name="price" type="text" class="text" id="price" value="<?php echo $row["price"];?>" size="35" />
                        
                        <select name="unit" id="unit">
                            <option value="天">每天</option>
                            <option value="周">每周</option>
                            <option value="月">每月</option>
                            <option value="年">每年</option>
                        </select>
                    </td>
                    
                </tr>            
            
                <tr>
                    <td><strong>广告样例：</strong></td>
                    <td>
						<script type="text/javascript">
                        new Serv.Upload("image","<?php echo $row["preview"];?>",{'format':['<?php echo implode("','",$_G['upload']['image']);?>'],'again':true,'recovery':true,'input':false});
                        </script>                    
                    </td>
                    
                </tr>
            
                <tr>
                    <td><strong>广告说明：</strong></td>
                    <td><textarea name="description" rows="5" cols="70" id="description"><?php echo $row["description"];?></textarea></td>
                    
                </tr>
             
                <!--tr text='引用外部变量,用于点击统计的分类, <span class="text-key">{SELF}</span> 为广告位实际'>
                    <td><strong>统计变量：</strong></td>
                    <td><textarea name="variable" rows="5" id="variable"><?php echo $row["variable"];?></textarea>  <a href="javascript:void(0);" onclick="_getExp();">示例</a></td>
                    
                </tr-->
            
            </tbody>
            
            <tbody cellpadding="0" cellspacing="0" class="form">
           
                <tr class="nobr">
                    <td><strong></strong></td>
                    <td>
                        <?php
                        
                        if ($action=="edit"){
                            echo '
                            <input type="submit" name="Submit5" value="修改此分类" class="submit" />
                            <input name="action" type="hidden" id="action" value="update" />
                            <input name="id" type="hidden" id="id" value="'.$row['id'].'">
                            <input name="jump" type="hidden" id="jump" value="'.$jump.'">';
                            
                        }else{
                            echo '
                            <input type="submit" name="Submit5" value="新增此分类" class="submit" />
                            <input name="action" type="hidden" id="action" value="add" />';
                        }
                        
                        echo '<input name="jump" type="hidden" id="jump" value="'.$jump.'" />';
                        ?>
                    </td>
                    
                </tr>
                
             </tbody>
             
			<?php
            if( $action && $row["parent"] ){
				
				$link = "adsview.preview.php?action=channel&key=".$row["key"]."&show=".$row["show"];
            ?>
            <tbody>
            
                <tr><td colspan="2" class="section"><span><a href="<?php echo $link;?>" target="_blank">新窗口预览&raquo;</a></span><strong>广告预览</strong></td></tr>
            
                <tr>
                	<td><strong></strong></td>
                    <td>
                        <iframe name="iframe" id="iframe" src="<?php echo $link;?>" frameborder="0" style="width:100%; height:<?php echo ($row["height"]+200);?>px;"></iframe>
                    </td>
                </tr>
            </tbody>            
            <?php
            }
            ?>
            
        </table>
		  
		<script type="text/javascript">
        <?php
        if($row["parent"]){
            echo 'Mo("input[name=model]").value("box");';
        }
		
	if( $model ){
		echo 'Mo("input[name=model]").value("'.$model.'");';
	}
		
        //关闭数据库
	System :: connect();
		
        ?>
        
        _getModel();
        Mo("#unit").value("<?php echo $row["unit"];?>");
        Mo("#parent").value("<?php echo $row["parent"];?>");        
        </script>
        
		</form>
	
	</div>
		
<!--body end-->

<?php html_close();?>