<?php
/**
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Common\TagLib;
use Think\Template\TagLib;
/**
 * Hc标签库驱动
 */
class Hc extends TagLib{
    protected $tags   =  array(
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'loadcssjs' =>array('attr'=>'css,js,type,id,datatype','close'=>0),
        'text'      => array('attr'=>'id,name,type,style,class,other,datatype,nullmsg,errormsg,tip,placeholder','close'=>1),
		'map'      => array('attr'=>'id,name,type,style,text,text_class,class,other,city_id,datatype,nullmsg,errormsg,tip,placeholder','close'=>1),
	    'linkage'   =>array('attr'=>'id,name,title,notitle,class,real,level,url,suffix,datatype,style,is_one','close'=>1),
		'mlinkage'   =>array('attr'=>'id,name,title,notitle,class,real,level,url,suffix,datatype,style,is_one','close'=>1),
		'editor'    => array('attr'=>'id,name,style,class,width,height,type,mini,manage,datatype','close'=>1),
        'select'    => array('attr'=>'name,options,class,output,multiple,id,size,first,change,default,selected,dbclick,datatype,nullmsg,errormsg','close'=>0),
        'upimage'   => array('attr'=>'id,name,datatype,text,style,class,manage,tip,showimg','close'=>1),//单图片上传
        'upfile'    => array('attr'=>'id,name,datatype,text,style,class,manage','close'=>1),//单文件上传	
        'pictures'  => array('attr'=>'id,name,text,style,class','close'=>1),//多图片上传
     	'calendar'  => array('attr'=>'id,name,ifformat,size,mindate,maxdate,minid,maxid','close'=>1),
        'checkbox'  => array('attr'=>'id,name,checkboxes,default,checked,separator,datatype,errormsg,arr','close'=>0),
        'radio'     => array('attr'=>'id,name,radios,checked,default,separator,datatype,errormsg','close'=>0)
     );
     /**
     * loadcssjs 加载必要的css 和js
     * 格式： <hc:loadcssjs type="editor,calendar" datatype="" css="" js=""/>
     */
     public function _loadcssjs($tag)
	 {
        $typearr=$readyjs=array();
        if(!empty($tag['css']))$css[]=	$tag['css'];
        if(!empty($tag['js']))$js[]	=	$tag['js'];
        $type=!empty($tag['type'])?$tag['type']:'all';
        $id= !empty($tag['id'])?$tag['id']:'myform';
        $datatype= !empty($tag['datatype'])?"<?php echo ".$tag['datatype']."?>":'';
        $typearr=explode(",",$type);$cssjs='';
        if(in_array('calendar',$typearr) || $type=='all')$cssjs.='<script type="text/javascript" src="'.__ROOT__.'/Public/script/MyDate/WdatePicker.js"></script>';//$js[]=__ROOT__."/Public/script/MyDate/WdatePicker.js";
        if(in_array('upimage',$typearr) || $type=='all'){$js[]=__ROOT__."/Public/script/prettyPhoto/js/jquery.prettyphoto.js";$css[]=__ROOT__."/Public/script/prettyPhoto/css/prettyPhoto.css";$readyjs[]="$(\"a[rel^='prettyPhoto']\").prettyPhoto();";}
        if(in_array('Validform',$typearr) || in_array('Validform_no',$typearr) || $type=='all'){$css[]=__ROOT__."/Public/css/validform.css";$js[]=__ROOT__."/Public/script/jquery/Validform_v5.3.2_min.js";$readyjs[]='$("#'.$id.'").Validform({tiptype:3'.$datatype.'});';}
        if(in_array('linkage',$typearr) || $type=='all')$js[]=__ROOT__."/Public/HanChaoUI/js/jquery.cxselect.min.js";
        if(in_array('mlinkage',$typearr) || $type=='all'){$js[]=__ROOT__."/Public/HanChaoUI/js/mobileSelect.js";$css[]=__ROOT__."/Public/HanChaoUI/css/mobileSelect.css";}
        if(in_array('placeholder',$typearr) || $type=='all')$js[]=__ROOT__."/Public/script/placeholder.js";
        if(in_array('editor',$typearr) || $type=='all'){$js[]=__ROOT__."/Public/script/kindeditor/lang/zh_CN.js";$css[]=__ROOT__."/Public/script/kindeditor/themes/default/default.css";$cssjs.='<script type="text/javascript" src="__PUBLIC__/script/kindeditor/kindeditor.js"></script>';}
        if(!empty($css))$cssjs.='<link rel="stylesheet" type="text/css" href="'.min_css($css).'" />';
        if(!empty($js))$cssjs.='<script type="text/javascript" src="'.min_js($js).'"></script>';
        if($readyjs)$cssjs.='<script type="text/javascript">$(function(){'.implode('',$readyjs).'})</script>';
        if(in_array('map',$typearr) || $type=='all'){$cssjs.='<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak='.getconfig('BAIDU_MAP_KEY').'"></script>';}
        return $cssjs;
	}
     /**
     * text标签解析
     * 格式： <hc:text name="name">{$content}</hc:text>
     */
    public function _text($tag,$content)
    {
        $name     = !empty($tag['name'])?$tag['name']:'text'.NOW_TIME;
        $id       = !empty($tag['id'])?$tag['id']:$name;
        $type     = !empty($tag['type'])?$tag['type']:'text';		
        $class    = !empty($tag['class'])?$tag['class']:'form-control f_l';
        $parseStr = '<input type="'.$type.'" name="'.$name.'" id="'.$id.'" value="'.$content.'"';
        if($class)$parseStr .= ' class="'.$class.'"';
        if(!empty($tag['style']))$parseStr .= ' style="'.$tag['style'].'"';
        if(!empty($tag['datatype']))$parseStr.= ' datatype="'.$tag['datatype'].'"';
        if(!empty($tag['nullmsg']))$parseStr .= ' nullmsg="'.$tag['nullmsg'].'"';
        if(!empty($tag['errormsg']))$parseStr.= ' errormsg="'.$tag['errormsg'].'"';
        if(!empty($tag['tip']))$parseStr .= ' tip="'.$tag['tip'].'"';
        if(!empty($tag['placeholder']))$parseStr .= ' placeholder="'.$tag['placeholder'].'"';
        if(!empty($tag['other']))$parseStr .= " ".$tag['other'];
        $parseStr .= '>';
        return $parseStr;
    }
    /**
     * linkage 地区标签
     * 格式： <hc:linkage name="linkage">{$content}</hc:linkage>
     */
	public function _linkage($tag,$content)
	{	
        $areastr=C('AREA_CONFIG');
        if(empty($areastr))$areastr=array('province'=>C('ONE_REGION'),'city_id'=>C('TWO_REGION'),'district'=>C('THREE_REGION'),'town'=>C('FOUR_REGION'),'community'=>C('FIVE_REGION'));
        $areaarr=strtoarray($areastr);
        $name   	=!empty($tag['name'])?$tag['name']:'linkage';$realname=str_replace('|','_',$name);
		$real	    =isset($tag['real'])?$tag['real']:'1';
		$valueinput	=!empty($tag['valueinput'])?$tag['valueinput']:'';//把值付到一个input中
		$id			=!empty($tag['id'])?$tag['id']:$realname;
        $level   	=!empty($tag['level'])?intval($tag['level']):intval(C('ZONE_LEVEL'));if(empty($level))$level=3;
		$title      =!empty($tag['title'])?$tag['title']:L('PLEASE_SELECT');
		$style      =!empty($tag['style'])?' style="'.$tag['style'].'"':'';
        $class      =!empty($tag['class'])?$tag['class']:'form-control selinkage';
		$notitle    =!empty($tag['notitle'])?$tag['notitle']:'';
		$url        =!empty($tag['url'])?$tag['url']:'areadata';//请求url地址
		$suffix     =!empty($tag['suffix'])?$tag['suffix']:implode(',',$areaarr);//后缀        
        $datatype   =!empty($tag['datatype'])?' datatype="'.$tag['datatype'].'"':'';
        
		$ldclass=$id.'_linkage';$str='<span id="'.$realname.'linkage_val">';
		if(!$notitle){$infotitle=explode(',',$suffix);
			foreach($infotitle as $k =>$tv){$t[$k]=$title.$tv;}
		}
        if(str_exists($name,'|')){$idarr=$namearr=explode('|','|'.$name);unset($idarr[0],$namearr[0]);}else{$nameid=array_keys($areaarr);
		foreach($nameid as $k => $v)
		{
		    $key=$k+1;if($key>$level)continue;
			$namearr[$key]=$real?$v:$name."_".$v;
			$idarr[$key]  =$real?$v:$id."_".$v;
		}}
        for($i=1; $i<=$level;$i++){
			$str .="<select class=\"".$ldclass." ".$class." cls_".$namearr[$i]."\" name=\"".$namearr[$i]."\" id=\"".$idarr[$i]."\"";
            if(!empty($t[$i]))$str .=' data-first-title="'.$t[$i].'"';
            if($i==1)$str .=$datatype;
			$str .=$style."></select>";
		}
        $url=str_exists($url,'/')?$url:__ROOT__."/Public/data/".$url.".json";
        $str.='<script type="text/javascript" src="'.$url.'"></script>';
        if($valueinput){ if(is_numeric($valueinput))$valueinput=$id;$str .="<input type='hidden' id='".$valueinput."' name='".$valueinput."' value='' />";}
		$str .="</span><script type=\"text/javascript\">";
		$str .="$(function(){ "."$.cxSelect.defaults.url = '".$url."';";
		$str .="$('#".$realname."linkage_val').cxSelect({selects: ['cls_".implode("','cls_",$namearr)."'],dataValues: [".$content."],valueInput: '".$valueinput."',emptyStyle: 'none'});";
	    $str .="});</script>";
		return $str;		
	}/**
     * mlinkage 手机版联动标签
     * 格式： <hc:mlinkage name="linkage">{$content}</hc:mlinkage>
     */
	public function _mlinkage($tag,$content)
	{	
        $areastr=C('AREA_CONFIG');
        if(empty($areastr))$areastr=array('province'=>C('ONE_REGION'),'city_id'=>C('TWO_REGION'),'district'=>C('THREE_REGION'),'town'=>C('FOUR_REGION'),'community'=>C('FIVE_REGION'));
        $areaarr=strtoarray($areastr);
        $name   	=!empty($tag['name'])?$tag['name']:'linkage';$realname=str_replace('|','_',$name);
		$real	    =isset($tag['real'])?$tag['real']:'1';
		$valueinput	=!empty($tag['valueinput'])?$tag['valueinput']:'';//把值付到一个input中
		$id			=!empty($tag['id'])?$tag['id']:$realname;
        $level   	=!empty($tag['level'])?intval($tag['level']):intval(C('ZONE_LEVEL'));if(empty($level))$level=3;
		$title      =!empty($tag['title'])?$tag['title']:'选择地区';
		$style      =!empty($tag['style'])?' style="'.$tag['style'].'"':'';
        $class      =!empty($tag['class'])?$tag['class']:'form-control selinkage';
		$url        =!empty($tag['url'])?$tag['url']:'citylist';//请求url地址
		$suffix     =!empty($tag['suffix'])?$tag['suffix']:implode(',',$areaarr);//后缀        
        $datatype   =!empty($tag['datatype'])?' datatype="'.$tag['datatype'].'"':'';
        
		$ldclass=$id.'_linkage';$str='<span id="'.$realname.'linkage_val">'.$title.'</span>';		
        if(str_exists($name,'|')){$idarr=$namearr=explode('|','|'.$name);unset($idarr[0],$namearr[0]);}else{$nameid=array_keys($areaarr);
		foreach($nameid as $k => $v)
		{
		    $key=$k+1;if($key>$level)continue;
			$namearr[$key]=$real?$v:$name."_".$v;
			$idarr[$key]  =$real?$v:$id."_".$v;
		}}
        if(str_exists($url,'/')){
            $urlarr=explode('/',$url);$dataname=str_replace('.json','',$urlarr[(count($urlarr)-1)]);
        }else{
            $dataname=$url;$url=__ROOT__."/Public/data/".$url.".json";
        }
        $url=format_url($url);
        $jsondata=file_get_contents($url);if(empty($jsondata))$jsondata='[]';
        if($valueinput){ if(is_numeric($valueinput))$valueinput=$id;$str .="<input type='hidden' id='".$valueinput."' name='".$valueinput."' value='' />";}
        
        
        for($i=1; $i<=$level;$i++){
            $str .="<input id=\"".$idarr[$i]."_name\" type='hidden'>";
			$str .="<input name=\"".$namearr[$i]."\" id=\"".$idarr[$i]."\" type='hidden'";
            if($i==1)$str .=$datatype;
			$str .=">";
		}
        $fuzhi_loop='';
        if($valueinput){
            $fuzhi_loop.="var valinput=ids.join(,); $('#".$valueinput.").val(valinput);\n";
        }else{     
            for($i=1; $i<=$level;$i++){
    			$fuzhi_loop .="if(ids[".($i-1)."]){ $('#".$idarr[$i]."').val(ids[".($i-1)."]);$('#".$idarr[$i]."_name').val(data[".($i-1)."].value);}\n";
    		}
        }
		//$str .="</span><script type=\"text/javascript\">";
		//$str .="$(function(){ "."$.cxSelect.defaults.url = '".$url."';";
		//$str .="$('#".$realname."linkage_val').cxSelect({selects: ['cls_".implode("','cls_",$namearr)."'],dataValues: [".$content."],valueInput: '".$valueinput."',emptyStyle: 'none'});";
	    //$str .="});</script>";
        $str.="<script type=\"text/javascript\">
        var ".$dataname."=".$jsondata.";
    var mobileSelect".$realname." = new MobileSelect({
    trigger: '#".$realname."linkage_val',
    title: '".$title."',
    level: ".$level.",
    wheels: [{data:".$dataname."}],
    position:[".$content."],
    initEnd:function(indexArr, data){
        var selectname='';
        var ids=[];for(var i=0; i<data.length; i++){ if(data[i].id){ids[i]=data[i].id;} if(data[i].value){selectname+=data[i].value+' ';} } if(selectname){ $('#".$realname."linkage_val').html(selectname);}\n";
        $str.=$fuzhi_loop;
    $str.="},
    callback:function(indexArr, data){
        var ids=[];for(var i=0; i<data.length; i++){ if(data[i].id){ids[i]=data[i].id;} }\n";
        $str.=$fuzhi_loop;
    $str.="}  
});</script>";
		return $str;		
	}
    /**
     * map标签解析
     * 格式： <hc:map x_name="x" y_name="y">{$xcontent},{$ycontent}</hc:map>
     */
    public function _map($tag,$content){
        $x_name     = !empty($tag['x_name'])?$tag['x_name']:'x';
        $x_id       = !empty($tag['x_id'])?$tag['x_id']:$x_name;
        $y_name     = !empty($tag['y_name'])?$tag['y_name']:'y';
        $y_id       = !empty($tag['y_id'])?$tag['y_id']:$y_name;
        $search_id = !empty($tag['search_id'])?$tag['search_id']:'';
        $city_id = !empty($tag['city_id'])?$tag['city_id']:'city_id';
        $address_id = !empty($tag['address_id'])?$tag['address_id']:'address';
        $text_class = !empty($tag['text_class'])?$tag['text_class']:'btn btn-primary';
        $text       = !empty($tag['text'])?$tag['text']:'设置经纬度';
        $button_style= !empty($tag['button_style'])?$tag['button_style']:'padding:0;border:0;';
        $class      = !empty($tag['class'])?$tag['class']:'form-control w100';
        $style      = !empty($tag['style'])?$tag['style']:'float:none;';
        $title      = !empty($tag['title'])?$tag['title']:'选择坐标';
        $datatype   =!empty($tag['datatype'])?' datatype="'.$tag['datatype'].'"':'';

        $mapurl='map/';
        if($x_id!='x')$mapurl.='x_name/'.$x_id.'/';
        if($y_id!='y')$mapurl.='y_name/'.$y_id.'/';
        if($address_id)$mapurl.='address_id/'.$address_id.'/';
        if($search_id)$mapurl.='search_id/'.$search_id.'/';
        if($content){
            $contentarr=explode(',',$content);
            $mapurl.='x/'.$contentarr[0].'/y/'.$contentarr[1].'/';
        }else{
            $contentarr=array('','');
        }
        $parseStr = '<div class="f_l">&nbsp;&nbsp;';
        $parseStr .= '<input type="hidden" name="'.$x_name.'" id="'.$x_id.'" class="'.$class.'" value="'.$contentarr[0].'" '.$datatype.'/>';
        $parseStr .= '<input type="hidden" name="'.$y_name.'" id="'.$y_id.'" class="'.$class.'" value="'.$contentarr[1].'" '.$datatype.' />';
        $parseStr .= '<button type="button" class="btn btn-default btn-lg f_l" onclick="openmapselect()" style="'.$button_style.'">';
        $parseStr .= '<span class="'.$text_class.'">'.$text.'</span></button><p class="text-muted showlocation_'.$x_name.$y_name.'"><?php echo showlocation('.strtr($contentarr[0],array('{'=>'','}'=>'')).','.strtr($contentarr[1],array('{'=>'','}'=>'')).');?></p></div>';
        $parseStr .= '<script>function openmapselect(){var cityname=$("#'.$city_id.'").find("option:selected").text();if(!cityname || cityname=="请选择市"){alert("请先选择所在城市");return;}$.openUrl(ROOT_PATH+\'index.php?s=/Home/Public/'.$mapurl.'city_name/\'+cityname,\''.$title.'\',\'_map\',960);}</script>';
        return $parseStr;
    }
    /**
     * editor标签解析 插入可视化编辑器
     * 格式： <hc:editor id="editor" name="remark" type="KINDEDITOR" style="" >{$content}</hc:editor>
     */
    public function _editor($tag,$content) {
        $id			=	!empty($tag['id'])?$tag['id']: strtr($tag['name'],array('['=>'',']'=>'')).'_editor';
        $name   	=	!empty($tag['name'])?$tag['name']:'';
        $mini   	=	!empty($tag['mini'])?$tag['mini']:'';
        $manage   	=	!empty($tag['manage'])?$tag['manage']:'false';
        $style      =	!empty($tag['style'])?$tag['style']:'';
		$class		=	!empty($tag['class'])?$tag['class']:'form-control';//仅适用于textarea
        $datatype   =	!empty($tag['datatype'])?' datatype="'.$tag['datatype'].'"':'';
        $width		=	!empty($tag['width'])?$tag['width']: '100%';
        $height     =	!empty($tag['height'])?$tag['height'] :'320px';
        $type       =   !empty($tag['type'])?$tag['type']:'KINDEDITOR' ;
        if(($manage || C('UPLOAD_FILEMANAGE')) && $manage!='false')$filemanage="allowFileManager : true,";else $filemanage='';
        switch(strtoupper($type)) {
            case 'KINDEDITOR':
                $parseStr='<script> var editor; KindEditor.ready(function(K) { editor = K.create(\'#'.$id.'\', {'.$filemanage;
                $parseStr.='fileManagerJson: "'.U('Home/File/filemanager').'",uploadJson: "'.U('Home/File/upload').'",';
				if($mini)$parseStr.="items : ['source','fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline','removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist','insertunorderedlist', '|', 'emoticons', 'image', 'link']";
				$parseStr.='});});</script><textarea id="'.$id.'" style="'.$style.'" name="'.$name.'" >'.$content.'</textarea>';
                 break;
            default :
                $parseStr  =  '<textarea id="'.$id.'" class="'.$class.'" style="'.$style.'" name="'.$name.'" '.$datatype.'>'.$content.'</textarea>';
        }

        return $parseStr;
    }
    /**  +----------------------------------------------------------
     * calendar标签解析 插入可视化日期调用
     * 格式：<hc:calendar name="star_time" ifformat="yyyy-MM-dd HH:mm:ss">{$content}</hc:calendar>
    */
     public function _calendar($tag,$content){
        $name   	=	!empty($tag['name'])?$tag['name']:'';
		$id			=	!empty($tag['id'])?$tag['id']: $tag['name'];
		$class		=	!empty($tag['class'])?$tag['class']:'Wdate form-control';
		$size		=	!empty($tag['size'])?$tag['size']:'20';        
        $style   	=	!empty($tag['style'])?" style='".$tag['style']."'":'';
		$ifformat	=	!empty($tag['ifformat'])?$tag['ifformat']:'yyyy-MM-dd';	
        $minid   	=	!empty($tag['minid'])?$tag['minid']:'';
        $maxid   	=	!empty($tag['maxid'])?$tag['maxid']:'';
        if(empty($maxid) && $name=='date_from')$maxid='date_to';
        if(empty($minid) && $name=='date_to')$minid='date_from';
        $limitparam=$minDate=$maxData='';
        if(!empty($tag['maxdate'])){
            $maxData=str_exists($tag['maxdate'],'$')?",maxDate:'<?php echo ".$tag['maxdate'].";?>'":",maxDate:'".$tag['maxdate']."'";
        }
        if(!empty($tag['mindate'])){
             $minDate=str_exists($tag['mindate'],'$')?",minDate:'<?php echo ".$tag['mindate'].";?>'":",minDate:'".$tag['mindate']."'";
        }
        if($minid && empty($minDate)){
            $limitparam=strtotime($minid)?$minid:'#F{ $dp.$D(\\\''.$minid.'\\\')}';
            $limitparam=",minDate:'".$limitparam."'";
        }elseif($maxid && empty($maxData)){
            $limitparam=strtotime($maxid)?$maxid:'#F{ $dp.$D(\\\''.$maxid.'\\\')}';
            $limitparam=",maxDate:'".$limitparam."'";
        }
		$parseStr='<input class="'.$class.'" name="'.$name.'" type="text" id="'.$id.'" size="'.$size.'" onFocus="WdatePicker({dateFmt:\''.$ifformat.'\''.$minDate.$maxData.$limitparam.'})" value="'.$content.'" '.$style.'/>';
        return $parseStr;
    }
    /**
     * pictures多图片上传 利用KindEditor实现图片上传
     * 格式： <hc:pictures name="pictures" >{$content}</hc:pictures>
     */
    public function _pictures($tag,$content)
    {
        $name=	!empty($tag['name'])?$tag['name']:'';
        $id			=	!empty($tag['id'])?$tag['id']: strtr($name,array('['=>'',']'=>''));
        $text   	=	!empty($tag['text'])?$tag['text']:L('TAGTIP_PICTURES');
        $style   	=	!empty($tag['style'])?'style="'.$tag['style'].'"':'';
        $class      = !empty($tag['class'])?$tag['class']:'form-control f_l';
        $button     =strtr($tag['name'],array('['=>'',']'=>''));  
        $parseStr_url='fileManagerJson: "'.U('Home/File/filemanager').'",uploadJson: "'.U('Home/File/upload').'"';
       $parseStr='<script>var nowval=newval="";
			KindEditor.ready(function(K) { var editor = K.editor({'.$parseStr_url.'});
            K("#'.$button.'_button").click(function() { editor.loadPlugin("multiimage", function() { editor.plugin.multiImageDialog({ clickFn : function(urlList) { var div = K("#'.$button.'_View");								
			K.each(urlList, function(i, data) { nowval=$("#'.$id.'").val();
             if(!nowval || nowval=="undefined"){ newval=data.url;}else{ newval=nowval+","+data.url;}$("#'.$id.'").val(newval);
             div.append("<img src=\'" + data.url + "\' style=\"max-height:90px;max-width:90px;margin-right:3px\"  align=\"left\">");});editor.hideDialog();}
			});});});});
		</script><input type="text" id="'.$id.'" name="'.$name.'" '.$style.' class="'.$class.'" value="'.$content.'"/> 
		<input type="button" id="'.$button.'_button" class="btn btn-default" value="'.$text.'" />
		<div id="'.$button.'_View">'.str_replace("}","|strimages}",$content).'</div>';
        return $parseStr;
    }
    /**
     * upimage图片上传 利用KindEditor实现图片上传
     * 格式： <hc:upimage name="upimage" >{$content}</hc:upimage>
     */
    public function _upimage($tag,$content)
    {
        $name   	=	!empty($tag['name'])?$tag['name']:'';
        $id			=	!empty($tag['id'])?$tag['id']: strtr($name,array('['=>'',']'=>'')).'_id';
        $manage   	=	!empty($tag['manage'])?$tag['manage']:'false';
        $tip   	    =	!empty($tag['tip'])?$tag['tip']:'';
        $showimg   	=	!empty($tag['showimg'])?$tag['showimg']:'1';
        $text   	=	!empty($tag['text'])?$tag['text']:L('TAGTIP_SELECTPIC');
        $button   	=	strtr($name,array('['=>'',']'=>''))."_button";
        $style   	=	!empty($tag['style'])?$tag['style']:'';
        $datatype   =	!empty($tag['datatype'])?' datatype="'.$tag['datatype'].'"':'';
        $class      = !empty($tag['class'])?$tag['class']:'form-control f_l';
        $showimgstr=$showimg?"$(\"a[rel^='prettyPhoto']\").prettyPhoto();":'';
        if(($manage || C('UPLOAD_FILEMANAGE')) && $manage!='false')$filemanage="allowFileManager : true,";else $filemanage='';        
                $parseStr_url='fileManagerJson: "'.U('Home/File/filemanager').'",uploadJson: "'.U('Home/File/upload').'"';
       $parseStr='<script>KindEditor.ready(function(K) {var editor = K.editor({'.$filemanage.$parseStr_url.'});K("#'.$button.'").click(function() {editor.loadPlugin("image", function() {editor.plugin.imageDialog({imageUrl : K("#'.$id.'").val(),clickFn : function(url, title, width, height, border, align) {K("#'.$id.'").val(url);K("#showupimage_'.$id.'").html("<a href=\""+url+"\" target=\"_bank\" rel=\"prettyPhoto'.$id.'\"><img src=\""+url+"\"/></a>");'.$showimgstr.'editor.hideDialog();}});});});});</script>';
      $parseStr.='<div><div class="upload_img_hanchao"><ul class="clearfix"><li id="showupimage_'.$id.'">';
      $imgname=$this->getvarname($content);
      if($imgname){
       $parseStr.='<?php if(!empty('.$imgname.')){?>';
       $parseStr.='<a href="<?php echo '.$imgname.';?>" target="_bank" rel="prettyPhoto'.$id.'"><img src="<?php echo '.$imgname.';?>" /></a>';
       $parseStr.='<?php }else{?><img src="'.__ROOT__.'/Public/images/add_img_icon.png" /><?php }?>';
      }else{
        $parseStr.='<img src="'.__ROOT__.'/Public/images/add_img_icon.png"/>';
      }
      $parseStr.='</li></ul><input type="hidden" id="'.$id.'" name="'.$name.'"'.$datatype.' class="'.$class.'" value="'.$content.'" /><button type="button" id="'.$button.'" class="btn btn-primary">'.$text.'</button>';
      if($tip)$parseStr.='<p class="text-muted"><span class="glyphicon glyphicon-exclamation-sign"></span>'.$tip.'</p></div></div>';
        return $parseStr;
    }
    /**
     * upfile文件上传 利用KindEditor实现文件上传
     * 格式： <hc:upfile name="upfile" >{$content}</hc:upfile>
     */
	public function _upfile($tag,$content)
    {
        $name   	=	!empty($tag['name'])?$tag['name']:'';
        $id			=	!empty($tag['id'])?$tag['id']: strtr($name,array('['=>'',']'=>'')).'_fileid';
        $manage   	=	!empty($tag['manage'])?$tag['manage']:'false';
        $text   	=	!empty($tag['text'])?$tag['text']:L('TAGTIP_SELECTFILE');
        $button   	=	strtr($name,array('['=>'',']'=>''))."_filebutton";
        $style   	=	!empty($tag['style'])?$tag['style']:'';
        $datatype   =	!empty($tag['datatype'])?' datatype="'.$tag['datatype'].'"':'';
        $class      = !empty($tag['class'])?$tag['class']:'form-control f_l';
        if(($manage || C('UPLOAD_FILEMANAGE')) && $manage!='false')$filemanage="allowFileManager : true,";else $filemanage='';
        $parseStr_url='fileManagerJson: "'.U('Home/File/filemanager').'",uploadJson: "'.U('Home/File/upload').'"';
       $parseStr='<script>KindEditor.ready(function(K){var editor = K.editor({'.$filemanage.$parseStr_url.'});K("#'.$button.'").click(function() {editor.loadPlugin("insertfile", function() {editor.plugin.fileDialog({fileUrl : K("#'.$id.'").val(),clickFn : function(url, title) {K("#'.$id.'").val(url);editor.hideDialog();}});});});});</script>
       <input type="text" id="'.$id.'" name="'.$name.'" style="'.$style.'"'.$datatype.' class="'.$class.'" value="'.$content.'" /> <input type="button" class="btn btn-default ml10" id="'.$button.'" value="'.$text.'" />';
       $filename=$this->getvarname($content);if($filename){
       $parseStr.='<?php if(!empty('.$filename.')){?>';
       $parseStr.=' <a href="<?php echo '.$filename.';?>" target="_bank">'.L('TAGTIP_DOWN').'</a>';
       $parseStr.='<?php }?>';}
        return $parseStr;
    }
    private function getvarname($name){
         $filename=strtr($name,array('{'=>'','}'=>''));
         if(str_exists($filename,'.')){
            $vars=explode('.',$filename);$filename = '';
            foreach ($vars as $key=>$val)$filename .=$key==0?$val: '["'.$val.'"]';
        }return $filename;
    }
    /**
     * select标签解析
     * 格式： <hc:select options="name" selected="value" />
     */
    public function _select($tag) {
        $name       = $tag['name'];$realname=strtr($name,array('['=>'',']'=>''));
        $class      = !empty($tag['class'])?$tag['class']:'form-control';
        $options    = !empty($tag['options'])?$tag['options']:'';
        $output     = !empty($tag['output'])?$tag['output']:'';
        $multiple   = !empty($tag['multiple'])?$tag['multiple']:'';
        $id         = !empty($tag['id'])?$tag['id']:$name;
        $size       = !empty($tag['size'])?$tag['size']:'';
        $first      = !empty($tag['first'])?$tag['first']:'';
        $selected   = isset($tag['selected'])?$tag['selected']:'';
        $style      = !empty($tag['style'])?$tag['style']:'';
        $ondbclick = !empty($tag['dbclick'])?$tag['dbclick']:'';
		$onchange	= !empty($tag['change'])?$tag['change']:'';
        $parseStr = '<select id="'.$id.'" class="'.$class.'" name="'.$name.'" ';
        if(!empty($multiple)) $parseStr .=' multiple="multiple"';
        if(!empty($ondbclick)) $parseStr .=' ondbclick="'.$ondbclick.'"';
        if(!empty($onchange)) $parseStr .=' onchange="'.$onchange.'"';
        if(!empty($size)) $parseStr .=' size="'.$size.'"';
        if(!empty($style)) $parseStr .=' style="'.$style.'"';        
        if(!empty($tag['datatype']))$parseStr.= ' datatype="'.$tag['datatype'].'"';
        if(!empty($tag['nullmsg']))$parseStr .= ' nullmsg="'.$tag['nullmsg'].'"';
        if(!empty($tag['errormsg']))$parseStr.= ' errormsg="'.$tag['errormsg'].'"';
        $parseStr .='>';
        if(!empty($first)) {$parseStr .= '<option value="" >'.$first.'</option>';}
        
        if(str_exists($options,':') || str_exists($options,':') || str_exists($options,',') || str_exists($options,'typeid_')){
            $optionsstr=$options;
            $options=$realname.'_arr';
            $parseStr .= '<?php $'.$options.'=strtoarray("'.$optionsstr.'");?>';
        }        
        if(is_numeric($selected)){
            $selectedstr=$selected;
            $selected=$realname.'_selected';
            $parseStr .= '<?php  $'.$selected.'="'.$selectedstr.'";?>';
        }
        if(!empty($options)){
            $parseStr   .= '<?php if(!empty($'.$options.')){ $'.'selectdvalue=0;foreach($'.$options.' as $key=>$val) { ?>';
            if(!empty($selected)) {
                $parseStr   .= '<?php if(empty($'.$selected.') && !is_numeric($'.$selected.'))$'.$selected.'=array();$'.$selected.'arr=remove_empty_array($'.$selected.');if(in_array($key,$'.$selected.'arr)) { ?>';
                $parseStr   .= '<option selected="selected" value="<?php echo $key ?>"><?php echo $val;$'.'selectdvalue=1; ?></option>';
                $parseStr   .= '<?php }else { ?><option value="<?php echo $key ?>"><?php echo $val ?></option>';
                $parseStr   .= '<?php } ?>';
            }else {$parseStr.=  '<option value="<?php echo $key ?>"><?php echo $val ?></option>';}
            $parseStr   .= '<?php } } ?>';
        }
        $parseStr   .= '</select>'.$output;
        if(!empty($default) || is_numeric($default)){
             $parseStr   .='<?php if($'.'selectdvalue==0)echo "<script>$(\"#'.$id.'\").val(\"'.$tag['default'].'\")</script>";?>';
        }return $parseStr;
    }
    /**
     * checkbox标签解析
     * 格式： <hc:checkboxp checkboxes="" checked="" />
     */
    public function _checkbox($tag) {
        $arr        = !empty($tag['arr'])?$tag['arr']:'';
        $class      = !empty($tag['class'])?$tag['class']:'';
        $name       = !empty($tag['arr'])?$tag['name']:$tag['name'].'[]';$realname=strtr($name,array('['=>'',']'=>''));
        $id         = !empty($tag['id'])?$tag['id']:$realname;
        $checkboxes = !empty($tag['checkboxes'])?$tag['checkboxes']:'';
        $checked    = isset($tag['checked'])?$tag['checked']:'';
        $separator  = !empty($tag['separator'])?$tag['separator']:' ';        
        $datatype   = !empty($tag['datatype'])?$tag['datatype']:'';
        $errormsg   = !empty($tag['errormsg'])?$tag['errormsg']:'';
        $default    = isset($tag['default'])?$tag['default']:'';
        
        $parseStr= '<?php $'.'selectdvalue=0;?>';
        if(str_exists($checkboxes,':') || str_exists($checkboxes,'|') || str_exists($checkboxes,',') || str_exists($checkboxes,'typeid_')){
            $checkboxstr=$checkboxes;
            $checkboxes=$realname.'_arr';
            $parseStr .= '<?php  $'.$checkboxes.'=strtoarray("'.$checkboxstr.'");?>';
        }
        if(is_numeric($checked) || str_exists($checkboxes,',')){
            $checkedstr=$checked;
            $checked=$realname.'_checked';
            $parseStr .= '<?php  $'.$checked.'="'.$checkedstr.'";?>';
        }
        $parseStr .= '<?php $i=1;$total=count($'.$checkboxes.');foreach($'.$checkboxes.' as $key=>$val) { ?>';            
        $parseStr .= '<label class="checkbox-inline '.$class.'"><input type="checkbox" name="'.$name.'" value="<?php echo $key;?>"';
        if($id)$parseStr .=' id="'.$id.'_<?php echo $i;?>"';
        if($checked)$parseStr .= '<?php if(empty($'.$checked.') && !is_numeric($'.$checked.'))$'.$checked.'=array();$'.$checked.'arr=remove_empty_array($'.$checked.');if(in_array($key,$'.$checked.'arr)){echo " checked=\'checked\'";$'.'selectdvalue=1;}?>';
        if($datatype)$parseStr .= '<?php if($i==$total){echo " datatype=\''.$datatype.'\'";}?>';
        if($errormsg)$parseStr .= '<?php if($i==$total){echo " errormsg=\''.$errormsg.'\'";}?>';
        $parseStr .="><?php echo $"."val.'".$separator."';?></label>";
        $parseStr .= '<?php ++$i;} ?>';        
        if(!empty($default) || is_numeric($default)){
             $parseStr   .='<?php if($'.'selectdvalue==0)echo "<script>';
             $defaultarr=remove_empty_array($default);
             foreach($defaultarr as $v){
                $parseStr   .='$(\"input[name=\''.$name.'\'][value=\''.$v.'\']\").attr(\"checked\",true);';
             }$parseStr   .='</script>";?>';
        }
        return $parseStr;
    }

    /**
     * radio标签解析
     * 格式： <hc:radio radios="name" checked="value" />
     */
    public function _radio($tag) {
        $name       = !empty($tag['name'])?$tag['name']:'';$realname=strtr($name,array('['=>'',']'=>''));
        $id         = !empty($tag['id'])?$tag['id']:$realname;
        $radios     = !empty($tag['radios'])?$tag['radios']:'';
        $checked    = isset($tag['checked'])?$tag['checked']:'';
        $separator  = !empty($tag['separator'])?$tag['separator']:' ';     
        $datatype   = !empty($tag['datatype'])?$tag['datatype']:'';
        $errormsg   = !empty($tag['errormsg'])?$tag['errormsg']:'';
        $default    = isset($tag['default'])?$tag['default']:'';
        $parseStr= '<?php $'.'selectdvalue=0;?>';        
        if(str_exists($radios,':') || str_exists($radios,'|') || str_exists($radios,',') || str_exists($radios,'typeid_')){
            $radiosstr=$radios;
            $radios=$realname.'_arr';
            $parseStr .= '<?php  $'.$radios.'=strtoarray("'.$radiosstr.'");?>';
        }
        if(is_numeric($checked)){
            $checkedstr=$checked;
            $checked=$realname.'_checked';
            $parseStr .= '<?php  $'.$checked.'="'.$checkedstr.'";?>';
        }
        $parseStr .= '<?php $i=1;$total=count($'.$radios.');foreach($'.$radios.' as $'.'key=>$'.'val) { ?>';            
        $parseStr .= '<label class="radio-inline"><input type="radio" name="'.$name.'" value="<?php echo $'.'key;?>"';
        if($id)$parseStr .=' id="'.$id.'_<?php echo $i;?>"';
        if($checked)$parseStr .= '<?php if(empty($'.$checked.') && !is_numeric($'.$checked.'))$'.$checked.'=array();if((!empty($'.$checked.') || is_numeric($'.$checked.')) && $'.$checked.'==$'.'key){echo " checked=\'checked\'";$'.'selectdvalue=1;}?>';
        if($datatype)$parseStr .= '<?php if($i==$total){echo " datatype=\''.$datatype.'\'";}?>';
        if($errormsg)$parseStr .= '<?php if($i==$total){echo " errormsg=\''.$errormsg.'\'";}?>';
        $parseStr .="><?php echo $"."val.'".$separator."';?></label>";
        $parseStr .= '<?php ++$i;} ?>';        
        if(!empty($default) || is_numeric($default)){
             $parseStr   .='<?php if($'.'selectdvalue==0)echo "<script>$(\"input[name=\''.$name.'\'][value=\''.$default.'\']\").attr(\"checked\",true);</script>";?>';
        }return $parseStr;
    }
}
?>