<?php

/*
*	Copyright VeryIDE,2007-2010
*	http://www.veryide.com/
*
*	$Id: ,v1 10:39 2008-7-27 Leilei $
*/

require("../../include/header.php");

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

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

	//module
	require("naver.php");
	
	loader_cache($appid,"table.adsarea");
	
	$jump = GetQuery("jump");
	$parent = GetQuery("parent");
	$action = GetQuery("action");
	
	$model = GetQuery("model");

	//mysql open
	reader_mysql();

	if($action){
	
		$id = GetQuery("id");
		$name = GetQuery("name");
		$key=trim(GetQuery("key"));
		$quote = GetQuery("quote");
		$preview = GetQuery("image");
		$number = GetNumber("number",1);
		$show = GetNumber("show",1);
		$price = GetNumber("price",0);
		$unit = GetQuery("unit");
		$tag = GetQuery("tag");
		$description = GetQuery("description");
		
		$config=$_POST["config"];
		
		$width = GetNumber("width",0);
		$height = GetNumber("height",0);
		
		$variable=FilterHtml($_POST["variable"]);
		
		
		if($model=="type"){
			$parent=0;
		}
		
		switch($action){
			case"add":
			
				//检查权限
				checker_func("mod-adsarea-add");				
			
				if (!$name || !$key || !preg_match('/^[A-Za-z0-9-_]{2,16}$/',$key) ){
					
					if( !$key ){
						$Project["message"]="广告位标识不能为空！";
					}elseif( !$name ){
						$Project["message"]="新增类别名称不能为空！";
					}else{
						$Project["message"]="标识中有非法字符！";
					}
					
					$Project["class"]	="wrong";
					
				}else{
				
					$sql="select id from ".VI_DBMODPRE."adsarea where `key`='".strtolower($key)."'";
					$result=mysql_query($sql,$mysql);
					
					$Project["queries"]++;
					
					if( mysql_num_rows($result)>0 ){
						
						$Project["message"]="分类标识已经存在！";						
						$Project["class"]	="wrong";
						
						$row = array();
						$row["key"] = $key;
						$row["name"] = $name;
						$row["quote"] = $quote;
						
					}else{
						
						$sql="insert into ".VI_DBMODPRE."adsarea(name,`key`,parent,quote,number,`show`,preview,price,unit,`description`,width,height,aid,account,dateline,tag,variable,config) values('".$name."','".strtolower($key)."','".$parent."','".$quote."',".$number.",".$show.",'".$preview."',".$price.",'".$unit."','".$description."',".$width.",".$height.",".$_SESSION["Manager"]["id"].",'".$_SESSION["Manager"]["account"]."',".time().",'".$tag."','".$variable."','".$config."')";
						
						mysql_query($sql,$mysql);
						
						$Project["queries"]++;
						
						$id = mysql_insert_id($mysql);
						
						//错误处理
						if (!$id) {
							trigger_error($sql, E_USER_ERROR);
							exit();
						}						
						
					}
					
				}
				
			break;
			
			case "edit":
			
				//检查权限
				checker_func("mod-adsarea-mod");				
			
				$sql="select * from ".VI_DBMODPRE."adsarea where id=".$id;
				$result=mysql_query($sql,$mysql);
				
				$Project["queries"]++;
				
				if(mysql_num_rows($result)==1){
					$row=mysql_fetch_assoc($result);
					
					//兼容GBK中文
					if( $Project["charset"] == "gbk" ){
						$array = json_decode(iconv('GBK', 'UTF-8', $row["config"]),true);
						
						$config = array();
						
						if( is_array($array) ){
							foreach ($array as $key => $val){
								$config[$key] = iconv('UTF-8', 'GBK', $val);
							}
						}
					}else{
						//配置
        $config = fix_json( $row["config"] );	
					}
						
					
				}else{
					reader_redirect($jump,"未找到相关广告位!");
					exit();
				}
			break;
			
			case "update":
			
				//检查权限
				checker_func("mod-adsarea-mod");				
			
				$sql="update ".VI_DBMODPRE."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;
				mysql_query($sql,$mysql);
				
				//exit($sql);
				
				$Project["queries"]++;
				
				//生成广告
				ad_create("SELECT * FROM ".VI_DBMODPRE."adsarea where id=".$id,$mysql);
				
			break;
		}
	
		//更新分类数组缓存
		cache_table($appid,$mysql,VI_DBMODPRE."adsarea",'<option value=\'{table:id}\'>{table:name}</option>');		
		
		//更新分类脚本缓存
		cache_script($appid,$mysql,"SELECT id,parent,name,`show`,width,height,number FROM ".VI_DBMODPRE."adsarea where parent>0","ADSAREA","mod.adsarea",'	#var[{table:id}] = [{table:id},{table:parent},"{table:name}",{table:show},"{table:width}×{table:height}",{table:number}];'.chr(13));	
	}

	//转向
	if($action!="edit" && $action && !$Project["message"]){
		if($jump){
			reader_redirect($jump,"成功完成操作!");
			exit();
		}
	
		if($parent){
			reader_redirect("adsarea.list.php?s=key&q=".$key,"广告位编辑成功!");
		}else{
			reader_redirect("adsarea.channel.php","广告分类编辑成功!");
		}
		
	}
	
	//mysql close
	reader_mysql(true);
	?>
    
	<?php   
    echo loader_script(array(VI_BASE."js/color.js"),$Project["charset"],$Project["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 checker_func("mod-adsarea-add",true);
		break;
		
		case "edit":
			echo checker_func("mod-adsarea-mod",true);
		break;
	}
	
	?>

	<div id="box">
		<form method="post" action="?" mode="edit" verify="true">
        
        <textarea name="config" cols="50" rows="6" id="config" style="display:none;"><?php echo $row["config"];?></textarea>
        
        <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($VICACHE["mod.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_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_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>
                
                <?php
				
				//载入控制文件
				include("include.area.php");
				
				?>
            
                <tr>
                    <td width="60"><strong>所属频道：</strong></td>
                    <td>
                        <select name="parent" id="parent">
						<?php
						
						//输出频道
						foreach($VICACHE["mod.adsarea"] as $key){
							if($key["parent"]=="0"){
								echo '<option value="'.$key["id"].'">'.$key["name"].'</option>';
							}
						}
						
                        ?>
                        </select>
                    </td>
                    
                </tr>
            
            
				<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>
                        </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("','",$Upload["image"]);?>'],'again':true,'recovery':true,'input':true});
                        </script>                    
                    </td>
                    
                </tr>
            
                <tr>
                    <td><strong>广告说明：</strong></td>
                    <td><textarea name="description" rows="5" 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.'");';
		}
		
        ?>
        
        _getModel();
        Mo("#unit").value("<?php echo $row["unit"];?>");
        Mo("#parent").value("<?php echo $row["parent"];?>");        
        </script>
        
		</form>
	
	</div>
		
<!--body end-->

<?php html_close();?>