<?
////////////////////////////////////////////////////
// Conciliación: gestión de conciliación de activos
// Version: 1.0
//
// Copyright (C) 2014  Eustotem Multimedia, S.L.
//
// License: MIT, see LICENSE
////////////////////////////////////////////////////


class Controls{
	public $recordset=NULL;
	public $process=NULL;
	public $action="";
	public $resId='';
	public $id='';
	
	private function zeropad($num, $lim){
		return str_repeat("0",max(0,$lim-strlen($num))).$num;
	}
	
	private function extractLang($texto, $idioma){
		$pattern="@\<!-- lang:$idioma --\>(.*)\<!-- \/lang:$idioma --\>@s";
		preg_match($pattern, $texto, $matches, PREG_OFFSET_CAPTURE);
		return ($matches[1][0]);
	}

	private function postprocess($xml,$valor){
		if($this->process==NULL) return $valor;
		if($xml->postprocess){
			$metodo=(string)$xml->postprocess["method"];
			$valor=$this->process->$metodo($valor,(string)$xml->postprocess)->content;
		}
		$valor=str_replace("'","&#39;",$valor);
		return $valor;
	}
	
	function getControl($xml,$value=NULL,$action,$resId,$id=NULL){
		$this->action=$action;
		$this->resId=$resId;
		$this->id=$id;
		$cadena='';
		if($value!=NULL){
			$valor=Content::parse($value);
		}else{
			$valor=$this->action=="insert" ? Content::parse((string)$xml->default) : "";
		}
		
		switch($xml['class']){
			case "dummy":
				$cadena=$this->getDummy($xml,$valor); break;
			case "textfield":
				$cadena=$this->getText($xml,$valor); break;
			case "textarea":
				$cadena=$this->getTextArea($xml,$valor); break;
			case "checkbox":
				$cadena=$this->getCheckBox($xml,$valor); break;
			case "menu":
				$cadena=$this->getMenu($xml,$valor); break;
			case "editablemenu":
				$cadena=$this->getEditableMenu($xml,$valor); break;
			case "calendar":
				$cadena=$this->getCalendar($xml,$valor); break;
			case "hidden":
				$cadena=$this->getHidden($xml,$valor); break;
			case "map":
				$cadena=$this->getMap($xml,$valor); break;
			case "editor":
				$cadena=$this->getEditor($xml,$valor); break;
			case "radio":
				$cadena=$this->getRadio($xml,$valor); break;
			case "slider":
				$cadena=$this->getSlider($xml,$valor); break;
			case "colorpicker":
				$cadena=$this->getColorPicker($xml,$valor); break;
			case "file":
				$cadena=$this->getFile($xml,$valor); break;
			case "related":
				$cadena=$this->getRelated($xml,$valor); break;
			case "password":
				$cadena=$this->getPassword($xml,$valor); break;
			case "imageprocess":
				$cadena=$this->getImageProcess($xml,$valor); break;
			case "relatedselect":
				$cadena=$this->getRelatedselect($xml,$valor); break;
		}
		return $cadena;
	}

	
	
	function getDummy($xml,$param=NULL){
		if(isset($xml->datasource)){
			$consulta=str_replace("{param}",$param,$xml->datasource->sql);
			$q=@mysql_query(Content::parse($consulta));
			if(@mysql_num_rows($q)>0){
				$fet=mysql_fetch_assoc($q);
				$teststr=(string)$xml->text;
				preg_match_all("/{(.*?)}/", $teststr, $arr2);
				for($i=0;$i<count($arr2[0]);$i++){
					$teststr=str_replace($arr2[0][$i],$fet[$arr2[1][$i]],$teststr);
				}
			}else{
				$teststr="<em>No disponible</em>";
			}
			$cadena.=$teststr;
		}else{
			$cadena=Content::parse((string)$xml->text);
		}
		return $cadena;
	}

	
	function getText($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$maxchars=isset($xml->maxchars) ? "maxlength='".$xml->maxchars."' " : '';
		$estilo=isset($xml['style'])? "txt_" . $xml['style'] : "txt_default";
		$valor=Content::parse($value);
		if($xml["type"]=="time") $valor=date("H:i",strtotime("1970-01-01 $valor"));	
		$evento=isset($xml->event) ? $xml->event['type'] . '=javascript:' . $xml->event['call'] . '(this)' : '';
		if($xml['multilang']!="true"){
			$valor=$this->postprocess($xml,$valor);			
			return "<input type='text' name='$nombre' id='$nombre' class='animated $estilo' value='$valor' $maxchars $evento />";
		}else{
			global $lngs;
			$cadena="<div id='{$nombre}_radio'>"; $cadena_h="";
			$in=0; $sel="";
			foreach($lngs as $lng=>$cont){
				if($in==0) $sel=$lng;
				$in++;
				$valor=$this->postprocess($xml,$valor);		
				$hvalue=$_SERVER['REQUEST_METHOD']=='POST' ? $_POST["{$nombre}_h_{$lng}"] : Content::extractLang($valor, $lng);
				$cadena.="<input id='{$nombre}_b_{$lng}' name='{$nombre}_lang' type='radio' class='{$nombre}_lang' value='{$hvalue}' /><label for='{$nombre}_b_{$lng}' class='btn_lang'><img src='../resources/flags/{$lng}.png' alt='{$cont['name']}' /></label>";
				$cadena.="<input type='hidden' name='{$nombre}_h_{$lng}' id='{$nombre}_h_{$lng}' value='".$hvalue."' />";
			}
			$cadena.='</div>';
			$cadena.= "<input type='text' name='$nombre' id='$nombre' class='animated $estilo noradius-tl' value='$hvalue' $maxchars $evento />";
			$cadena.="<script type='text/javascript'>$(document).ready(function(){ initButtonset('{$nombre}','{$sel}'); });</script>";
			return $cadena;
		}
	}
	
	
	function getTextArea($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$cols=(string)$xml->cols;
		$rows=(string)$xml->rows;
		$estilo=isset($xml['style'])? "ta_" . $xml['style'] : "ta_default";
		if($xml->codeeditor=="true") $estilo.=" codeeditor";
		$valor=$value;
		$valor=$this->postprocess($xml,$valor);		
		$enabled=$xml->enabled=="false" ? "disabled='true'" : "";
		$evento=isset($xml->event) ? $xml->event['type'] . '=javascript:' . $xml->event['call'] . '(this)' : '';
		if($xml['multilang']!="true"){
			$valor=$this->postprocess($xml,$valor);				
			$cadena="<textarea name='$nombre' id='$nombre' class='animated $estilo' cols='$cols' rows='$rows' $evento $enabled >$valor</textarea>";
		}else{
			global $lngs;
			$cadena="<div id='{$nombre}_radio'>"; $cadena_h="";
			$valor=$this->postprocess($xml,$valor);		
			$in=0; $sel="";
			foreach($lngs as $lng=>$cont){
				if($in==0) $sel=$lng;
				$in++;
				$hvalue=$_SERVER['REQUEST_METHOD']=='POST' ? $_POST["{$nombre}_h_{$lng}"] : Content::extractLang($valor, $lng);
				$cadena.="<input id='{$nombre}_b_{$lng}' name='{$nombre}_lang' type='radio' class='{$nombre}_lang' value='{$hvalue}' /><label for='{$nombre}_b_{$lng}' class='btn_lang'><img src='../resources/flags/{$lng}.png' alt='{$cont['name']}' /></label>";
				$cadena.="<input type='hidden' name='{$nombre}_h_{$lng}' id='{$nombre}_h_{$lng}' value='".$hvalue."' />";
			}
			$cadena.='</div>';
			$cadena.= "<textarea name='$nombre' id='$nombre' class='animated $estilo noradius-tl' cols='$cols' rows='$rows' $evento $enabled></textarea>";
			$cadena.="<script type='text/javascript'>$(document).ready(function(){ initButtonset('{$nombre}','{$sel}'); });</script>";
		}
		if($xml->codeeditor=="true"){
			$cadena.="<script type='text/javascript'>$(document).ready(function(){\$(\"#{$nombre}\").tabby();});</script>";
		}
		return $cadena;
	}
	
	
	function getCheckBox($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$estilo=isset($xml['style'])? "ch_" . $xml['style'] : "ch_default";
		if($value=="true" || $value=="1"){
			$default="checked='checked'";
		}else{
			$default="";
		}
		$evento=isset($xml->event) ? $xml->event['type'] . '=javascript:' . $xml->event['call'] . '(this)' : '';
		return "<input type='checkbox' id='" . $nombre . "' name='$nombre' value='" . $value . "' " . $default . " $evento class='animated' />" . chr(13) . chr(13);
	}
	
	
	function getMenu($xml,$val=NULL,$style='default'){
		$nombre=$xml['name'];
		$multiple=$xml->multiple=="true" ? " multiple='multiple'" : "";
		$estilo=isset($xml['style'])? "select_" . $xml['style'] : "select_default";
		if($xml->multiple=="true") $estilo.=" select_multiple";
		$size=isset($xml->size) ? "size='" . $xml->size . "'" : "";
		$alcambiar=$multiple=="" ? "" : "onchange='updSelect(this,\"" . $nombre . "\")'";
		$sm=$multiple=="" ? "" : "sm_";
		if($multiple!=""){
			$json = new Services_JSON();
			$valores = $json->decode($val);
		}
		$evento=isset($xml->event) ? $xml->event['type'] . '=javascript:' . $xml->event['call'] . '(this)' : '';		
		$cadena="<select id='$sm$nombre' name='$sm$nombre' class='animated $estilo' $multiple $size $alcambiar $evento>";
		foreach($xml->populate->option as $option){
			if((string)$xml->populate['from']=="list") break;
			$temp=$option->attributes(); 
			if($multiple==""){
				$selected=(string)$temp['value']==(string)$val ? 'selected="selected"' : '';
			}else{
			}
			$option=$this->postprocess($xml,$option);	
			$cadena.='<option value="' . $temp['value'] . '" ' . $selected . '>' . $option . '</option>';
		}
		switch((string)$xml->populate['from']){
			case "list":
				foreach($xml->populate->option as $f){
					if($multiple==""){
						$selected=$f['value']==$val ? 'selected="selected"' : '';
					}else{
						$selected='';
						if($this->action=="edit" && count($valores)>0){
							foreach($valores as $clave=>$propiedad){
								if($f['value']==str_replace("opt_","",$clave)){
									$selected='selected="selected"';
									break;
								}
							}
						}
					}
					$cadena.='<option value="' . $f['value'] . '" ' . $selected . '>' . $f . '</option>';
				}
				break;
			case "sql":
				$q=mysql_query(Content::parse((string)$xml->populate->sql)) or die(mysql_error());
				while($f=mysql_fetch_array($q)){
					if($multiple==""){
						$selected=$f[0]==$val ? 'selected="selected"' : '';
					}else{
						$selected='';
						if($this->action=="edit" && count($valores)>0){
							foreach($valores as $clave=>$propiedad){
								if($f[0]==str_replace("opt_","",$clave)){
									$selected='selected="selected"';
									break;
								}
							}
						}
					}
					if(isset($xml->populate->sql['lang'])) $f[1]=Content::extractLang($f[1],$xml->populate->sql['lang']);
					$f[1]=$this->postprocess($xml,$f[1]);		
					$cadena.='<option value="' . $f[0] . '" ' . $selected . '>' . $f[1] . '</option>';
				}
				break;
		}
		$cadena.="</select>";
		if($multiple!="") $cadena.="<input type='hidden' name='" . $nombre . "' id='" . $nombre . "' value='" . $val . "' />";
		return $cadena;
	}
	
	function getEditableMenu($xml,$val=NULL,$style='default'){
		$nombre=$xml['name']; $options=array();
		$estilo=isset($xml['style'])? "txt_" . $xml['style'] : "txt_default";
		$cadena="<select id='$nombre' name='$nombre' value='$val' class='animated select_editable $estilo' >";
		switch((string)$xml->populate['from']){
			case "list":
				foreach($xml->populate->option as $f){
					$selected=$f['value']==$val ? 'selected="selected"' : '';
					$f=$this->postprocess($xml,$f);		
					$options[]="'{$f}'";
					$cadena.="<option value='{$f}' $selected>{$f}</option>";
				}
				break;
			case "sql":
				$q=mysql_query(Content::parse((string)$xml->populate->sql)) or die(mysql_error());
				while($f=mysql_fetch_array($q)){
					$selected=$f[0]==$val ? 'selected="selected"' : '';
					if(isset($xml->populate->sql['lang'])) $f[0]=Content::extractLang($f[0],$xml->populate->sql['lang']);
					$f[0]=$this->postprocess($xml,$f[0]);		
					$f[0]=addslashes(strip_tags($f[0]));
					$options[]="'{$f[0]}'";
					$cadena.="<option value='{$f[0]}' $selected>{$f[0]}</option>";
				}
		}
		$cadena.="</select>";
		$cadenaoptions="[".implode(",",$options)."]";
		$source=$xml->populate['from']=='remote' ? '"'.$xml->populate['source'].'"' : $cadenaoptions;
		$cadena.=<<<EOT
		<script type="text/javascript">
		$(function(){
			$( "#{$nombre}" ).combobox({
				/*source: {$source},*/
				minLength: 2,
				selected: function( event, ui ) {/* tenemos ui.item.value, ui.item.label y ui.item.id */}
			});
		});
EOT;
		$cadena.="</script>";
		return $cadena;
	}
	
	

	function getEditor($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$estilo=isset($xml['style'])? "txt_" . $xml['style'] : "edit_default";
		$evento=isset($xml->event) ? $xml->event['type'] . '=javascript:' . $xml->event['call'] . '(this)' : '';
		$fbconfig=isset($xml->fbconfig) ? json_encode($xml->fbconfig) : 'null';		
		if($xml['multilang']!="true"){
			$valor=$this->postprocess($xml,$value);		
			$cadena.="<textarea name='{$nombre}' id='{$nombre}' class='animated {$estilo}' cols='65' rows='20' $evento>".$valor."</textarea>";
			$cadena.="<script type='text/javascript'>$(document).ready(function(){
				fbconfig['{$nombre}']={$fbconfig};
			</script>";
			return $cadena;
		}else{
			global $lngs;
			$cadena="<div id='{$nombre}_radio'>"; $cadena_h="";
			$in=0; $sel=""; $inicial="";
			foreach($lngs as $lng=>$cont){
				if($in==0){
					$sel=$lng;
				}
				$valor=$this->postprocess($xml,$value);		
				$hvalue=$_SERVER['REQUEST_METHOD']=='POST' ? $_POST["{$nombre}_h_{$lng}"] : Content::extractLang($valor, $lng);
				if($in==0) $inicial=$hvalue;
				$in++;
				$cadena.="<input id='{$nombre}_b_{$lng}' name='{$nombre}_lang' type='radio' class='{$nombre}_lang' value='{$hvalue}' /><label for='{$nombre}_b_{$lng}' class='btn_lang'><img src='../resources/flags/{$lng}.png' alt='{$cont['name']}' /></label>";
				$cadena.="<input type='hidden' name='{$nombre}_h_{$lng}' id='{$nombre}_h_{$lng}' value='".$hvalue."' />";
			}
			$cadena.='</div>';
			$cadena.= "<textarea name='$nombre' id='$nombre' class='animated $estilo noradius-tl' cols='65' rows='20' $evento >{$inicial}</textarea>";
			$cadena.="<script type='text/javascript'>$(document).ready(function(){
				initButtonset('{$nombre}','{$sel}', true); });
				fbconfig['{$nombre}']={$fbconfig};
			</script>";
			return $cadena;
		}
	}
	
	
	
	function getCalendar($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$nullable=(string)$xml->nullable=="true";									
		$estilo=$xml['type']=="date" || $xml['type']=="time" ? "txt_short wpx90" : "txt_default wpx150";
		$formats=array("date"=>CAL_DATE_FORMAT, "datetime"=>CAL_DATETIME_FORMAT, "time"=>CAL_TIME_FORMAT);
		$lnng=$langs[$_SESSION['userlang']][0];										
		$fecha = new DateTime($value); 												
		$control=(string)$xml['type'];
		$formato=$formats[$control];												
		$fechanula=($value=='' || $value==NULL || $value=='0000-00-00' || $value=='0000-00-00 00:00:00' || $fecha===false);
		if($_SERVER['REQUEST_METHOD']=="POST"){
			$valor_h=Content::parse("{{post:".$nombre."}}");
			$valor_t=Content::parse("{{post:cal_".$nombre."}}");
		}else{
			if($this->action=="insert"){
				$valor_h=$fecha->format($formato); $valor_t=$fecha->format($formato);
				if($fechanula && !$nullable){$valor_h=date($formato); $valor_t=date($formato);}
			}else if($this->action=="edit"){
				$valor_h=$value; $valor_t=$fechanula ? '' : $fecha->format($formato);
			}
		}
		$cadena=<<<EOT
		<input type='text' name='cal_$nombre' id='cal_$nombre' class='animated datepicker $estilo' value='$valor_t' />
		<input type='hidden' name='$nombre' id='$nombre' value='$value' />
		<script type='text/javascript'>
		$(function() {
			//$("#cal_$nombre").datepicker("option",$.datepicker.regional['$lnng']);
			$("#cal_$nombre").{$control}picker({
				changeMonth: true, changeYear: true, 
				onSelect: function(dateText, inst){
					var tipo="{$control}";
					var yuyu=$(this).{$control}picker("getDate");
					$("#$nombre").val(date_js2mysql(tipo, yuyu));
				}
			});
		});
EOT;
		$cadena.="</script>";
		return $cadena;
	}
	
	
	
	function getHidden($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		if((string)$xml['type']=='number' || (string)$xml['type']=='boolean'){
			$valor=$value==NULL ? 0 : $value;
		}else{
			$valor=Content::parse($value);
		}
		return "<input type='hidden' name='$nombre' value='$valor' />";
	}
	
	
	
	function getRadio($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$cadena='';
		$orientacion=($xml->orientation=="horizontal" ? "&nbsp;&nbsp;" : "<br />".chr(13));
		foreach($xml->option as $option){
			$temp=$option->attributes();
			$check=(string)$temp['value']==(string)$value ? "checked='checked'" : "";
			if($value==NULL) $check="";
			$evento=isset($xml->event) ? $xml->event['type'] . '=javascript:' . $xml->event['call'] . '(this)' : '';
			$cadena.="<input type='radio' name='$nombre' value='" . $temp['value'] . "' " . $check . " " . $evento . " />" . $option . $orientacion;
		}
		$cadena.=chr(13) . chr(13);
		return $cadena;
	}
	
	
	
	function getMap($xml,$value=NULL,$style=''){
		$nombre=$xml['name'];
		$valor=$value;
		if($valor=="" || $valor==NULL){
			if(isset($xml->defaul)){
				$valor=$xml->default;		
				$temp=explode(",",$valor);
			}else if(isset($xml->altsource)){
				$metodo=(string)$xml->altsource['method'];
				$param=Content::parse((string)$xml->altsource['src']);
				Content::$data['main']=$this->recordset;
				$valor=$this->process->$metodo($param);
			}
		}		
		$cadena=<<<EOT
		<div id="{$nombre}_container" class="mapa">
			<div id="{$nombre}_map_canvas" class="map_canvas roundcorners"></div>
			<div id="{$nombre}_map_shadow" class="map_shadow roundcorners sombrainner"></div>
			<div class="map_crosshair" id="{$nombre}_map_crosshair">&nbsp;</div>
			<div class="map_controls">
				<input type="button" class="animated btn_spot" id="{$nombre}_map_type" value="" onclick="toggleMapMarkerType('{$nombre}')" />
				<input type="button" class="animated btn_ok" id="{$nombre}_map_get" value="" onclick="grabMapData('{$nombre}')" />
				<input type="button" class="animated btn_reset" id="{$nombre}_map_reset" value="" onclick="resetMap('{$nombre}','{$valor}')" />
				<input type="text" name="str" id="{$nombre}_str" class="animated txt_default" style="width:350px; display:none" />
				<input type="hidden" name="{$nombre}" id="{$nombre}" value="{$valor}" />
			</div>
		</div>
		<script type="text/javascript">mapas['{$nombre}']={};mapas['{$nombre}'].data='{$valor}'
EOT;
		$cadena.="</script>";
		return $cadena;
	}



	function getColorPicker($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		if($value!=NULL && $value!=''){
			if(substr($value,0,1)=="#"){
				$defecto=hexdec(str_replace("#","",$value));
			}else{
				$defecto=$value;
			}
		}else{
			$defecto="0";
		}
		$defecto=$this->zeropad(dechex($defecto),6);
		$palette= isset($xml->palette) ? (string)$xml->palette : "";
		$modes= isset($xml->modes) ? (string)$xml->modes : "";
		$cadena=<<<EOT
		<input type='hidden' name='{$nombre}' id='{$nombre}' value='$value' />
		<span id="cp_{$nombre}"></span>
		<script type="text/javascript">
		$(document).ready(function(){
			$('#cp_{$nombre}').jPicker(
				{
					window:{title:'ColorPicker',expandable: true,position:{x:24, y:0}},
					color:{active: new $.jPicker.Color({ hex: '#{$defecto}' })},
					images:{clientPath:'../jslib/jq/jpicker/images/'}
				},
				function(color, context){
					var all = color.val('all');
					$('#{$nombre}').val(parseInt(all.hex,16));
				}
			);
		});
EOT;
		$cadena.="</script>";
		return $cadena;
	}
	
	
	
	function getSlider($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$valor=($value) ? $value : (string)$xml->min; $min=isset($xml->min) ? $xml->min : 0; $max=isset($xml->max) ? $xml->max : 100;
		$step=isset($xml->step) ? "step:".$xml->step.", " : "";
		$width=(isset($xml->width)) ? (string)$xml->width : '150';
		$template=isset($xml->template) ? $xml->template : "{@@@}";
		$cadena=<<<EOT
		<div style="padding:5px 0">
		<input type='hidden' name='{$nombre}' id='{$nombre}' />
		<div id="slider_{$nombre}" style="width:{$width}px; border:1px solid #666; margin-right:10px; float: left"></div><div id="slider_{$nombre}_template">&nbsp;</div>
		</div>
		<script>
			$(function() {
				slider_{$nombre}_controller({$valor});
				$( "#slider_{$nombre}" ).slider({
					range:"min", value: $valor, min: $min, max: $max, $step
					slide:function(event, ui){
						slider_{$nombre}_controller(ui.value);
					}
				});
				function slider_{$nombre}_controller(param){
					var template="{$template}";
					var cont=template.split("{@@@}").join(param);
					$("#slider_{$nombre}_template").html(cont);
					$("#{$nombre}").val(param);
				}
			});
EOT;
		$cadena.="</script>";
		return $cadena;
	}



	function getFile($xml,$value=NULL,$style='default'){
		$nombre=(string)$xml['name'];						
		$modes=isset($xml->modes) ? (string)$xml->modes : 'upload';	
		$ruta="../.." . SYS_BASE_PATH . SYS_BASE_UPLOAD;	
		$estilo=isset($xml['style'])? "txt_" . $xml['style'] : "txt_default";	
		$rootfolder=isset($xml->fbconfig->rootfolder) ? (string)$xml->fbconfig->rootfolder : $ruta;
		
		$caption=FILECTRL_CURRENT;							
		$linkdelete=FILECTRL_DELETE;						
		$actual=($value==NULL || $value=='') ? FILECTRL_NONE : "{$primage} <a href='". $ruta . $xml->uploaddir . "/" . $xml->preview_prefix.$value."' target='_blank' style='font-weight:bold'>{$preview_prefix}{$value}</a>";
		$preview_prefix=$xml->preview_prefix;
		$primage=isset($xml->preview_image) ? "<img src='". $ruta . $xml->uploaddir . "/" . $xml->preview_image.$value."' style='border:none; vertical-align:middle' /> " : "";
		$cuidado=file_exists("../../" . SYS_BASE_UPLOAD . $xml->uploaddir . "/" . $preview_prefix.$value) ? "" : "&nbsp;<img src='../resources/themes/default/warning.gif' align='absmiddle' alt='".FILECTRL_BROKEN."' title='".FILECTRL_BROKEN."' />";
		$mostrar_delete=$value==NULL ? "none" : "inline";
		
		$_SESSION['currentFiles'][$this->resId][$nombre][0]=$ruta . $xml->uploaddir . "/" . $value;
		$i=1;
		foreach($xml->version as $version){
			$vtemp=explode(".",$value);
			$vext=array_pop($vtemp);
			$vername=$version['prefix'] . implode(".",$vtemp) . $version['suffix'].".".$vext;
			$_SESSION['currentFiles'][$this->resId][$nombre][$i]=$ruta . $version['uploaddir'] . "/" . $vername;
			$i++;
		}
		
		$cadena="<div id='{$nombre}_container' style='display:inline'>";
		$cadena.="<input type='hidden' value='$value' name='$nombre' id='$nombre' />";		
		if(stripos($modes, "upload")!==FALSE){
			$btncaption=FILECTRL_BUTTON1;
			$cadena.="<input type='button' value='{$btncaption}' name='{$nombre}_button' id='{$nombre}_button' class='animated but_default {$nombre}_button' style='display:inline' onClick='javascript:openFilePopup(\"{$nombre}\",\"{$this->resId}\",\"{$xml->subtype}\",\"{$xml->maxsize}\");' />";
		}
		if(stripos($modes, "server")!==FALSE){
			$btncaption=FILECTRL_BUTTON2;
			$cadena.="<input type='button' value='{$btncaption}' name='{$nombre}_button' id='{$nombre}_button' class='animated but_default {$nombre}_button' style='display:inline' onClick='javascript:openFileServerPopup(\"{$nombre}\",\"{$this->resId}\",\"{$xml->subtype}\",\"{$xml->maxsize}\",\"{$rootfolder}\");' />";
		}
		if(stripos($modes, "import")!==FALSE){
			$btncaption=FILECTRL_BUTTON3;
			$cadena.="<input type='button' value='{$btncaption}' name='{$nombre}_button' id='{$nombre}_button' class='animated but_default {$nombre}_button' style='display:inline' onClick='javascript:openFileImportPopup(\"{$nombre}\",\"{$this->resId}\",\"{$xml->subtype}\",\"{$xml->maxsize}\");' />";
		}
		
		$cadena.=<<<EOT
		</div>
		<div id='{$nombre}_caption' style='display:inline'>{$caption} {$actual}{$cuidado}</div>
		<div id='{$nombre}_delete' style='display:{$mostrar_delete}'>&nbsp;&nbsp;<a href='javascript:deleteFile("{$nombre}")'>{$linkdelete}</a></div><br />
		<script type="text/javascript">
		$(document).ready(function(){
			$("#{$nombre}_container").buttonset();
		});
EOT;
		$cadena.="</script>";
		return $cadena;
	}
	
	
	function getPassword($xml,$value=NULL,$style='default'){
		$nombre=$xml['name']; $valor=$value; $mssg=PASSCTRL_STRENGTH;
		$estilo=isset($xml['style'])? "txt_" . $xml['style'] : "txt_default";
		$hidden=isset($xml->hidden) && $xml->hidden=="false" ? FALSE : TRUE;
		$stre=$xml->strength=="true";
		if(!$hidden){
			$cadena="<input type='text' name='$nombre' id='$nombre' class='animated $estilo' value='$value' maxlength='14' />";
		}else{
			$cadena="<input type='password' name='$nombre' id='$nombre' class='animated $estilo' value='' maxlength='14' />";
			$checked=$_SERVER['REQUEST_METHOD']!='POST' || $_POST[$nombre.'_check']=="1" ? " checked='checked'" : "";
			$disabled=$_SERVER['REQUEST_METHOD']!='POST' || $_POST[$nombre.'_check']=="1" ? "disabled='true' style='opacity:0.5'" : "";
			if($this->action=="edit") $cadena.="<input type='checkbox' name='{$nombre}_check' id='{$nombre}_check' value='1' $checked onchange='enableSecondaryField(\"{$nombre}\")' /> " . PASSCTRL_KEEP;
			$cadena.="<br style='margin-bottom:10px;' /><input type='password' name='{$nombre}_2' id='{$nombre}_2' class='animated $estilo' value='' maxlength='14' $disabled />" . PASSCTRL_REPEAT; 
		}
		if($stre){
			$cadena.=<<<EOT
			<br />$mssg: <span id='{$nombre}_marca' style='font-weight: bold'>0/5</span>
			<script type="text/javascript">
			$(document).ready(function(){
				getPassStr($("#{$nombre}").get(0));
				$("#{$nombre}").keyup(function(){
					getPassStr($(this).get(0));
				});
			});
EOT;
			$cadena.="</script>";
		}
		return $cadena;
	}
	
	
	
	function getRelated($xml,$value=NULL,$style='default'){
		$nombre=$xml['name'];
		$href=Content::parse($xml->href);
		if(stripos($href,"?")===false) $href.="?";
		if(stripos($href,"&resId")===false) $href.="&resId=" . $xml->resource;
		if(stripos($href,"&parentId")===false) $href.="&parentId=" . $this->id;
		
		if($this->action=='insert'){
			$cadena=(string)$xml->insMsg;
		}else if($this->action=='edit'){
			$cadena="<div id='{$nombre}' style='width:98%; height:" . $xml->height . "px;'><iframe name='ifr_{$nombre}' id='ifr_{$nombre}' src='" . $href . "' width='100%' height='100%'>";
			$cadena.="</iframe></div>
			<script type='text/javascript'>$( '#{$nombre}' ).resizable();</script>";
		}
		return $cadena;
	}
	
	
	
	function getImageProcess($xml,$value=NULL){
		$nombre=(string)$xml['name'];
		$preview_prefix=$xml->preview_prefix;
		$caption=FILECTRL_CURRENT;
		$btncaption=FILECTRL_BROWSE;
		$linkdelete=FILECTRL_DELETE;
		$ruta="../.." . SYS_BASE_PATH . SYS_BASE_UPLOAD;
		$ancho_popup=!isset($xml->wndwidth) ? "400" : $xml->wndwidth;
		$alto_popup=!isset($xml->wndheight) ? "350" : $xml->wndheight;
		$estilo=isset($xml['style'])? "txt_" . $xml['style'] : "txt_default";
		$primage=isset($xml->preview_image) ? "<img src='". $ruta . $xml->uploaddir . "/" . $xml->preview_image.$value."' style='border:none; vertical-align:middle' /> " : "";
		$actual=($value==NULL || $value=='') ? FILECTRL_NONE : "{$primage} <a href='". $ruta . $xml->uploaddir . "/" . $xml->preview_prefix.$value."' target='_blank' style='font-weight:bold'>{$preview_prefix}{$value}</a>";
		$cuidado=file_exists("../../" . SYS_BASE_UPLOAD . $xml->uploaddir . "/" . $preview_prefix.$value) ? "" : "&nbsp;<img src='../resources/themes/default/warning.gif' align='absmiddle' alt='".FILECTRL_BROKEN."' title='".FILECTRL_BROKEN."' />";
		
		$_SESSION['currentFiles'][$this->resId][$nombre][0]=$ruta . $xml->uploaddir . "/" . $value;
		$i=1;
		foreach($xml->version as $version){
			$vtemp=explode(".",$value);
			$vext=array_pop($vtemp);
			$vername=$version['prefix'] . implode(".",$vtemp) . $version['suffix'].".".$vext;
			$_SESSION['currentFiles'][$this->resId][$nombre][$i]=$ruta . $version['uploaddir'] . "/" . $vername;
			$i++;
		}
		
		$mostrar_delete=$value==NULL ? "none" : "inline";
		$cadena=<<<EOT
		<input type='hidden' value='$value' name='$nombre' id='$nombre' />
		<input type='button' value='{$btncaption}' name='{$nombre}_button' id='{$nombre}_button' class='animated but_default' style='display:inline' onClick='javascript:openImgProcPopup("{$nombre}","{$this->resId}","{$xml->subtype}","{$xml->maxsize}",$ancho_popup,$alto_popup);' />
		<div id='{$nombre}_caption' style='display:inline'>{$caption} {$actual}{$cuidado}</div>
		<div id='{$nombre}_delete' style='display:{$mostrar_delete}'>&nbsp;&nbsp;<a href='javascript:deleteFile("{$nombre}")'>{$linkdelete}</a></div><br />
EOT;
		return $cadena;
	}



	function getRelatedselect($xml,$val=NULL,$style='default'){
		$nombre=$xml['name'];
		$estilo=isset($xml['style'])? "select_" . $xml['style'] : "select_default";
		$size=isset($xml->size) ? "size='" . $xml->size . "'" : "";
		$resId=$this->resId;
		$index=0; $cadena="<div style='width:100%'>";
		foreach($xml->nodes->node as $node){
			$index++; $idcontrol=$nombre.$index;
			$cadena.="<div style='display: inline; float: left; padding: 8px; margin-right:12px; background-color:#F0F0F0' class='roundcorners sombrainner'>";
			$cadena.=$node['caption']."<br />";
			$cadena.="<select class='animated select_default rel_{$nombre}' id='$idcontrol' name='$idcontrol'>";
			$cadena.="<option value='".$node['value0']."'>".$node['option0']."</option>";
			$cadena.="<select>";
			$cadena.="</div>";
		}
		$cadena.="</div><input type='hidden' name='$nombre' id='$nombre' value='$val' />";
		$cadena.=<<<EOT
		<script type="text/javascript">
		initRelatedSelect("$resId","$nombre","$val");
EOT;
		$cadena.="</script>";
		return $cadena;
	}
}
?>