<?php
class AppFormulario extends Zend_Form{

	
	protected $_defaultDisplayGroupClass = 'AppForm_DisplayGroup';
	
	const SUBFIJO_ACCION = 'Accion';
	
	const TIPO_LABELSUPERIOR = 'lsuperior';
	const TIPO_ENLINEA = 'en_linea';
	const TIPO_NORMAL = 'normal';
	
	const MODO_OBJETO = 'objeto';
	const MODO_CONFIGURACION = 'configuracion';
	const MODO_SESION = 'sesion';
	const MODO_NORMAL = 'normal';
	protected $_label_superior = false;
	protected $_elementos_en_linea = false;
	protected $_addClassFormHorizontal = true;
	protected $refrescaGrids = false;
	
	
	
	protected $_cargaEnDestino = array();
	public $dec_form_normal;
	public $dec_fichero_normal;
	public $dec_elemento_normal;
	public $dec_elemento_html;
	public $dec_elemento_oculto;
	public $dec_elementocheck_normal;
	public $dec_submit_normal;
	
	protected $_stilo = self::TIPO_NORMAL;
	protected  $_objeto ;
	protected $_eventos = array();
	protected $_modo = self::MODO_OBJETO;
	
	protected $_url_traseditar='';
	private $grids = array();
	
	protected $_nombre_sesion = '';
	
	protected $_anchoLabel = 2;

	
	protected $_elementos = array();
	
	public function  setAnchoLabel(){
		
	}
	
	
	public function addCargaEnDestino($id, $url){
		$this->_cargaEnDestino[] = array(
				'id'=> $id,'url'=>$url
		);
	}
	
	/**
	 * Valor por defecto false si se pone true actualiza todos los grid o se puede filtras mediante una cadena
	 * @param Boolean|String $valor
	 */
	public function setRefrescaGrid($valor){
		$this->refrescaGrids = $valor;
	}
	
	public function getLabelSuperior(){
		return $this->_label_superior;
	}
	
	public function setModo($modo){
		$this->_modo = $modo;
	}
	
	public function __construct($options = null)
	{
		if (is_array($options)) {
			$this->setOptions($options);
		} elseif ($options instanceof Zend_Config) {
			$this->setConfig($options);
		}
		
		
		$this->dec_elemento_oculto= array(
				'ViewHelper'
		);
	
		
		
		// Extensions...
		$this->init();
		
		$this->aplicarEstilo();

		//Comprobamos los eventos
		
		
		
		if(isset($_REQUEST['modal']) && $_REQUEST['modal']){
			$this->populate($_GET);
		}
		
		switch ($this->_modo) {
			case self::MODO_OBJETO:
				$objeto = $this->getObjeto();
				//var_dump($objeto->toArray());
				if($objeto instanceof AppObjeto){
					$this->populate($objeto->toArray());
				}
				break;
			case self::MODO_CONFIGURACION :
				$datos = array();
				foreach ($this->getElements() as $element){
					if(! $element instanceof EFSubmit){
							
						$datos[$element->getName()] = Configuracion::get($element->getName());
							
					}
				}
				$this->populate($datos);
				break;
			case self::MODO_SESION:
				$sesion = Session::getSession($this->_nombre_sesion? $this->_nombre_sesion: get_class($this));
				if(isset($sesion->datos) && is_array($sesion->datos))
					$this->populate($sesion->datos); 
				break;
				
			case self::MODO_NORMAL:
				
				$this->populate($_POST);
				
				break;
			default:
				;
			break;
		}
		
		$this->eventos();
		
		$this->loadDefaultDecorators();
	}
	
	/**
	 * 
	 * @param boolean $valor
	 */
	public function setAddClassFormHorizontal($valor){
		$this->_addClassFormHorizontal = $valor;
	}
	
	public function generaDecoradores(){
		$this->dec_form_normal=array(
                            'FormElements', 
	                        'Form'

       );
		
		
		
		 $getId = create_function('$decorator',
                                     'return $decorator->getElement()->getId()
                                             . "-element";');
		 
		 $getId = create_function('$content, $element, array $options',
		 		'return $element->getId();');
		 

		 $this->dec_elemento_html = array(
		 		'ViewHelper',
		 		'Errors',
		 		array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'')),
		 		
		 		
		 );
		 
		
		$this->dec_elemento_normal = array(
				'ViewHelper',
				array('Description', array('tag' => 'p', 'class' => 'help-block')),
				'Errors',
	             array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'col-sm-8')),
	             array(array('labelDtClose' => 'HtmlTag'), array('tag' => 'label', 'closeOnly' => true, 'placement' => 'prepend' )),
    			'Label',
				array(array('labelDtOpen' => 'HtmlTag'), array('tag' => 'label', 'openOnly' => true, 'placement' => 'prepend', 'class'=> 'col-sm-4 control-label')),
				
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'form-group'))
		);
		
		$this->dec_elemento_oculto= array(
				'ViewHelper'
				
		);
		
		
		
		$this->dec_fichero_normal = array(
				'File',
				array('Description', array('tag' => 'p', 'class' => 'help-block')),
				'Errors',
				array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'controls')),
				array(array('labelDtClose' => 'HtmlTag'), array('tag' => 'label', 'closeOnly' => true, 'placement' => 'prepend', )),
				'Label',
				array(array('labelDtOpen' => 'HtmlTag'), array('tag' => 'label', 'openOnly' => true, 'placement' => 'prepend', 'class' => 'col-sm-4 control-label')),
				array('Description', array('tag' => 'a', 'class' => 'description', 'data-toggle'=>"tooltip", 'title'=>"first tooltip")),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'form-group'))
		);
		
		
		
		
		$this->dec_elementocheck_normal = array(
				'ViewHelper',
			    'Errors',
				array('Label',array('placement'=>'APPEND')),
				array(array('data'=>'HtmlTag'),array('tag'=>'label', 'class'=>'checkbox' ,'for' => array('callback' => $getId))),
				
				array('decorator' => array('Holder' => 'HtmlTag'), 'options' => array('tag' => 'div', 'class'=>'controls')),
	             array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'form-group'))
		);
		
		
		
		
		$this->dec_submit_normal = array(
				'ViewHelper',
				'Errors',
				array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'col-sm-offset-4 col-sm-8')),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'form-group  control-submit'))
		);
		
	
	}
	
	
	
	public function generaDecoradoresLabelSuperior(){
		$this->dec_form_normal=array(
				'FormElements',
				'Form'
	
		);
		
	
	
	
		$getId = create_function('$decorator',
				'return $decorator->getElement()->getId()
                                             . "-element";');
			
		$getId = create_function('$content, $element, array $options',
				'return $element->getId();');
			
	
	
		$this->dec_elemento_normal = array(
				'ViewHelper',
				'Errors',
				array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'controls')),
				array(array('labelDtClose' => 'HtmlTag'), array('tag' => 'label', 'closeOnly' => true, 'placement' => 'prepend')),
				'Label',
				array(array('labelDtOpen' => 'HtmlTag'), array('tag' => 'label', 'openOnly' => true, 'placement' => 'prepend', 'class' => 'control-label')),
				array('Description', array('tag' => 'a', 'class' => 'description', 'data-toggle'=>"tooltip", 'title'=>"first tooltip")),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'control-group'))
		);
	
		
	
	
		$this->dec_fichero_normal = array(
				'File',
				'Errors',
				array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'controls')),
				array(array('labelDtClose' => 'HtmlTag'), array('tag' => 'label', 'closeOnly' => true, 'placement' => 'prepend')),
				'Label',
				array(array('labelDtOpen' => 'HtmlTag'), array('tag' => 'label', 'openOnly' => true, 'placement' => 'prepend', 'class' => 'control-label')),
				array('Description', array('tag' => 'a', 'class' => 'description', 'data-toggle'=>"tooltip", 'title'=>"first tooltip")),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'control-group'))
		);
	
	
		$this->dec_elementocheck_normal = array(
				'ViewHelper',
				'Errors',
				array('Label',array('placement'=>'APPEND')),
				array(array('data'=>'HtmlTag'),array('tag'=>'label', 'class'=>'checkbox' ,'for' => array('callback' => $getId))),
	
				array('decorator' => array('Holder' => 'HtmlTag'), 'options' => array('tag' => 'div', 'class'=>'controls')),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'control-group'))
		);
	
	
	
	
		$this->dec_submit_normal = array(
				'ViewHelper',
				'Errors',
				array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'controls')),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'control-group control-submit'))
		);
	
		
	
	
		
	}
	
	
	public function generaDecoradoresEnLInea(){
		$this->dec_form_normal=array(
				'FormElements',
				'Form'
	
		);
	
	
	
		$getId = create_function('$decorator',
				'return $decorator->getElement()->getId()
                                             . "-element";');
			
		$getId = create_function('$content, $element, array $options',
				'return $element->getId();');
			
	
	
		$this->dec_elemento_normal = array(
				'ViewHelper',
				'Errors',
				array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'form-group')),
				array(array('labelDtClose' => 'HtmlTag'), array('tag' => 'label', 'closeOnly' => true, 'placement' => 'prepend')),
				'Label',
				array(array('labelDtOpen' => 'HtmlTag'), array('tag' => 'label', 'openOnly' => true, 'placement' => 'prepend', 'class' => 'control-label')),
				array('Description', array('tag' => 'a', 'class' => 'description', 'data-toggle'=>"tooltip", 'title'=>"first tooltip")),
				
		);
	
	
	
		$this->dec_fichero_normal = array(
				'File',
				'Errors',
				array(array('data'=>'HtmlTag'),array('tag'=>'div', 'class'=>'controls')),
				array(array('labelDtClose' => 'HtmlTag'), array('tag' => 'label', 'closeOnly' => true, 'placement' => 'prepend')),
				'Label',
				array(array('labelDtOpen' => 'HtmlTag'), array('tag' => 'label', 'openOnly' => true, 'placement' => 'prepend', 'class' => 'control-label')),
				array('Description', array('tag' => 'a', 'class' => 'description', 'data-toggle'=>"tooltip", 'title'=>"first tooltip")),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'control-group'))
		);
	
	
	
		$this->dec_elementocheck_normal = array(
				'ViewHelper',
				'Errors',
				array('Label',array('placement'=>'APPEND')),
				array(array('data'=>'HtmlTag'),array('tag'=>'label', 'class'=>'checkbox' ,'for' => array('callback' => $getId))),
	
				array('decorator' => array('Holder' => 'HtmlTag'), 'options' => array('tag' => 'div', 'class'=>'controls')),
				array(array('row'=>'HtmlTag'),array('tag'=>'div', 'class'=>'control-group'))
		);
			
	
		$this->dec_submit_normal =array(
				'ViewHelper',
				'Errors',
				//	array(array('data'=>'HtmlTag')),
	
		);
	
		

	
		
	}
	
	public function setLabelSuperior($valor){
		$this->setAddClassFormHorizontal(!$valor);
		$this->_label_superior = $valor;
		$this->aplicarEstilo();
	}
	
	public function setElementosEnLinea($valor){
		$this->_elementos_en_linea = $valor;
		$this->aplicarEstilo();
	}
	
	protected function aplicarEstilo(){
		
		$this->generaDecoradores();
		if($this->_addClassFormHorizontal)
			$this->addAttribs(array('class'=> 'form-horizontal'));
		if(!$this->_elementos_en_linea && !$this->_label_superior){
			$this->generaDecoradores();
			
		}elseif(!$this->_elementos_en_linea && $this->_label_superior){
			$this->generaDecoradoresLabelSuperior();	
		}elseif($this->_elementos_en_linea && !$this->_label_superior){
			$this->generaDecoradoresEnLInea();
			
		}else{
			$this->generaDecoradores();
			
		}

		$this->aplicarEstiloFormulario();
		
	}
	
	public function aplicarEstiloFormulario(){
		
		$this->setDecorators($this->dec_form_normal);
		$this->setElementDecorators($this->dec_elemento_normal);
		
		foreach ($this->getElements() as  $elemento){
			
			
			if(!$elemento instanceof EFSubmit && !$elemento instanceof EFCheckbox){
				$elemento->setAttrib('class', 'form-control');
			}
			
			
			if($elemento instanceof EFSubmit){
				//$elemento->setAttrib('class', 'btn btn-default');
				
				$elemento->setDecorators($this->dec_submit_normal);
			}elseif($elemento instanceof EFCheckbox){
				$elemento->setDecorators($this->dec_elementocheck_normal);
			}elseif($elemento instanceof EFFichero){
				$elemento->setAttrib('class', '');
				$elemento->setDecorators($this->dec_fichero_normal);
			}elseif($elemento instanceof EFHidden){
				//print_r($this->dec_elemento_oculto);
				$elemento->setDecorators(array('ViewHelper'));
			}elseif($elemento instanceof EFHtml){
				//print_r($this->dec_elemento_oculto);
				$elemento->setDecorators($this->dec_elemento_html);
			}elseif($elemento instanceof EFRadio){
				$elemento->setAttrib('class', '');
			}elseif($elemento instanceof EFMultiCheckbox){
				$elemento->setAttrib('class', '');
			}
		}
	}
	
	public function aplicarEstiloHorizontal(){
		
		$this->setDecorators($this->dec_form_normal);
		$this->setElementDecorators($this->dec_elemento_normal);
		
		foreach ($this->getElements() as $elemento){
			if($elemento instanceof EFSubmit){
				$elemento->setDecorators($this->dec_submit_normal);
			}
			
			if($elemento instanceof EFBoton){
				$elemento->setDecorators($this->dec_submit_normal);
			}
		}
	}
	
	/*public function setEstilo($stilo){
		$this->_stilo = $stilo;
	}*/
	
	protected function conversionObjetoForm($datos, $inverso = false){
		$relacion = $this->getRelacionCampos();
		
		
		$valores = array();
		foreach ($relacion as $key => $value){
			if($inverso){
				if(array_key_exists($key, $datos))
					$valores[$key] = $datos[$value];
			}else{
				if(array_key_exists($key, $datos)){
					$valores[$value] = $datos[$key];
				}
					
			}
		
		}
		return $valores;
	}
	public function populate(array $datos){
		
		$valores = $this->conversionObjetoForm($datos, true);
		
		parent::populate($valores);
	}
	
	public function getValues($suppressArrayNotation = false){
		$valores = parent::getValues($suppressArrayNotation);
		
		$valores = $this->conversionObjetoForm($valores);
		
		return $valores;
	}
	
	Private function getRelacionCampos(){
		$salida = array();
		foreach ($this->getElements() as $key => $element) {
			if($element instanceof AppElementoFormulario){
				$salida[$key] = $element->getNombreObjeto();
			}
		}
		return $salida;
		
	}
	
	
	public function getEvento($distparador){
		if(isset($this->_eventos[$distparador]))
			$this->_eventos[$distparador];
	}
	
	
	public function init(){
		parent::init();
		
		
		$microtime = '';
		$microtime = microtime(true);
		$microtime -= floor($microtime);
		$microtime *=1000000;
		$microtime = floor($microtime);
		$this->setName('fomulario_'. get_class($this). date('His').$microtime);
		
		$accion = new EFHidden('accion');
		$this->addElement($accion);
		
		
	}
	
	public function setAction($action, $ajax = true){
		if($ajax){
			$evento = new EVAjax(AppEvento::APP_EVENTO_SUBMIT);
			$evento->setUrl($action);
			//	$evento->setCorrecto('alert("Se guardo correctamente");');
			$this->addEvento($evento);
		}
		parent::setAction(BASEURL . $action);
	}
	public function addParametroAction($nombre_Parametro, $valor_parametro){
		
		if($ajax){
			$evento = new EVAjax(AppEvento::APP_EVENTO_SUBMIT);
			$evento->setUrl($action);
			//	$evento->setCorrecto('alert("Se guardo correctamente");');
			$this->addEvento($evento);
		}
		parent::setAction(BASEURL . $action);
		
		
	}
	
	
	
	
	/**
	 * Nos regresa el select de jQ del formulario
	 * @return string
	 */
	public function identificadorScript(){
		$nombre = $this->getName();
		if(strlen($nombre)>0)
			return '#'.$nombre;
		else
			return '';
			
	}
	/**
	 * Añade un evento al formulario
	 * @param AppEvento $evento
	 */
	public function addEvento(AppEvento &$evento){
		
	 
	 
	 if(isset($this->_eventos[$evento->getDisparador()])){
	 	
	 	AppEvento::destroyEvento($this->_eventos[$evento->getDisparador()]);
	 	unset($this->_eventos[$evento->getDisparador()]);
	 }
	 	
	 
	 $evento->setPadre($this);
	 $this->_eventos[$evento->getDisparador()] = $evento;
	}
	
	public function inicializarEventos(){
		
	}
	
	public function setObjeto(AppObjeto $objeto){
		$this->_objeto = $objeto;
	}
	public  function  &getObjeto(){
		return $this->_objeto;
	}
	public function datosFormulario(){
		$datos = array();
		if(isset($_REQUEST['formulario']) && substr($_REQUEST['formulario'], 0,strlen($this->getName()) -12) == substr($this->getName(), 0 ,strlen($this->getName()) -12)){
			
			return $_POST;
		}
		
		return $datos;
		 
	}
	public function existeAccionFormulario($accion){
		return method_exists($this,$accion.self::SUBFIJO_ACCION);
	}
	
	public function eventos(){

		if(isset($_REQUEST['formulario']) && substr($_REQUEST['formulario'], 0,strlen($this->getName()) -12) == substr($this->getName(), 0 ,strlen($this->getName()) -12)){
			
			$this->setName($_REQUEST['formulario']);
			$datos = $this->datosFormulario();
		//	AppAjax::setMensajeError('indices', implode(',',$_POST));
		//	AppAjax::setMensajeError('indices', implode(',',array_keys($_POST)));			
			if(isset($datos['accion'])){
				if($this->existeAccionFormulario( $datos['accion'])){
					call_user_func(array($this, $datos['accion'].self::SUBFIJO_ACCION),$datos);
					
				}else{
					AppAjax::setMensajeError($this->identificadorScript(), 'No existe el metodo '.$datos['accion']);
					
				}
			}
		}
	}
	
	public function buscarAccion($datos){
		
		
		if($this->isValid($datos)){
		
		
			$valores = $this->getValues();
			unset($valores['accion']);
			
			$sesion = Session::getSession($this->_nombre_sesion? $this->_nombre_sesion: get_class($this));
			
			$sesion->datos = $valores;
			
			
			
			if(isset($_REQUEST['destino_autocomplete'])&& $_REQUEST['destino_autocomplete']){
				AppAjax::setValores($_REQUEST['destino_autocomplete'], $objeto->id);
			}elseif(strlen($this->_url_traseditar)>0){
				AppAjax::setRedirigir(BASEURL . $this->_url_traseditar);
			}
		
		
		}else{
			foreach ($this->getElements() as $element){
				if($element instanceof AppElementoFormulario){
					if(count($element->getMessages()>1))
					foreach($element->getMessages() as $mensaje){
						AppAjax::setMensajeError($element->identificadorScript(), $mensaje);
					}
				}
					
			}
		}
	}
	
	
	public function guardarconfAccion($datos){
	
	
		if($this->isValid($datos)){
	
	
			$valores = $this->getValues();
			unset($valores['accion']);

			
			
			foreach ($valores as $key => $value){
	
				Configuracion::set($key, $value);
			}
	
	
			if(isset($_REQUEST['destino_autocomplete'])&& $_REQUEST['destino_autocomplete']){
				AppAjax::setValores($_REQUEST['destino_autocomplete'], $objeto->id);
			}elseif(strlen($this->_url_traseditar)>0){
				AppAjax::setRedirigir(BASEURL . $this->_url_traseditar);
			}
	
	
		}else{
			foreach ($this->getElements() as $element){
				if($element instanceof AppElementoFormulario){
					if(count($element->getMessages()>1))
					foreach($element->getMessages() as $mensaje){
						AppAjax::setMensajeError($element->identificadorScript(), $mensaje);
					}
				}
					
			}
		}
	}
	
	public function guardarAccion($datos){
		
		$objeto = $this->getObjeto();
		if($objeto instanceof AppObjeto)
			if($this->isValid($datos)){
				
				try{
				
					$valores = $this->getValues();
					$objeto->setDatos($valores);
					$objeto->save();
					$ficheros = array();
					
					foreach ($this->getElements() as $element){
						if($element instanceof EFFichero){
							$valor = $element->recibir($objeto->id);
							if($valor){
								$ficheros[$element->getName()] = $valor;
							}
							
						}
					}
					if(count($ficheros)>0){
						$objeto->setDatos($ficheros);
						$objeto->save();
					}
					
					
					if(isset($_REQUEST['destino_autocomplete'])&& $_REQUEST['destino_autocomplete']){
						AppAjax::setValores($_REQUEST['destino_autocomplete'], $objeto->id);
					}elseif(strlen($this->_url_traseditar)>0){
						AppAjax::setRedirigir(BASEURL . $this->_url_traseditar);
					}else{
						if ($this->refrescaGrids !== false){
							if(is_string($this->refrescaGrids)){
								AppAjax::addRefrescaGrid($this->refrescaGrids);
							}else{
								AppAjax::addRefrescaGrid();
							}
						}
						
						foreach($this->_cargaEnDestino as $destino){
							AppAjax::addCargarEnDestino($destino['id'], $destino['url']);
						}
					}
				} catch (Exception $e) {
					AppAjax::setMensajeError($this->identificadorScript(), $e->getMessage());
				}
				
			}else{
				
				foreach ($this->getElements() as $element){
					if($element instanceof AppElementoFormulario){
						if(count($element->getMessages()>1))
							foreach($element->getMessages() as $mensaje){
								AppAjax::setMensajeError($element->identificadorScript(), $mensaje);
							}
					}
							
				}
			}
			
	}
	
	
	public function validarAccion($datos){
	AppAjax::esAjax(true);
			if($this->isValid($datos)){
	
			}else{
		
				foreach ($this->getElements() as $element){
					if($element instanceof AppElementoFormulario){
						if(count($element->getMessages()>1))
							foreach($element->getMessages() as $mensaje){
								if(strlen($datos[$element->getName()]))
									AppAjax::setMensajeError($element->identificadorScript(), $mensaje);
							}
					}
						
				}
			}
			
	}
	
	
	
	public function getMensajesError($datos){
		
	//	print_r($datos);
		$objeto = $this->getObjeto();
		if($objeto instanceof AppObjeto)
		$salida = array();
		if($this->isValid($datos)){
	
			
	
		}else{
	
			foreach ($this->getElements() as $element){
				if($element instanceof AppElementoFormulario){
					if(count($element->getMessages()>1))
					foreach($element->getMessages() as $mensaje){
						$salida[$element->getName()] = $mensaje;
						
					}
				}
					
			}
			
		}
		return $salida;
			
	}
	
	
	
	public function eliminar(){
		$objeto = $this->getObjeto();
		$objeto->eliminar();
	}
	
	public function addElement($element, $name = null, $options = null)
	{
		parent::addElement($element, $name , $options );
		
		if($element instanceof AppElementoFormulario){
			$element->setPadre($this);
			
		}
		if($element instanceof EFHidden){
			$this->addElementoVista($element);
		}
		
	}
	
	/**
	 *
	 * Ponemos un campo en solo lectura si se especificara , sino ponemos todo el formulario y eliminamos los submit
	 * @param string $name Campo a poner en solo lectura
	 */
	public function soloLectura($name = null){
		 
		if(is_null($name)){
			foreach ($this->getElements() as $key => $element) {
				if($key == 'accion'){
					continue;
				}
				$element->setValue(utf8_encode($element->getValue()));
				
				if($element instanceof AppElementoFormularioMulti){
						
					$opciones = $element->options;
					$valor = $this->getValue($element->getName());
						
					if(isset($opciones[$valor]))
						$element->setValue($opciones[$valor]);
					else{
						$element->setValue('');
					}
				}
				
				if($element->helper == 'formSubmit'){
					$this->removeElement($element->getName());
	
					$volver = new EFBoton('volver');
					$volver->setAttrib('onclick', 'javascript:location.href=\''.BASEURL.'/index/back\'');
					
					$volver->setDecorators($this->dec_submit_normal);
					$volver->setValue('Volver');
					$this->addElement($volver);
					
	
					foreach ($this->getSubForms() as $subform){
						$subform->soloLectura();
					}
	
				//	$this->volver->setDecorators($this->_divElementoSubmit);
	
				}else{
	
					$element->helper = 'formNote';
					$element->setRequired(false);
	
				}
		   
		   
				if(get_class($element) == 'Zend_Dojo_Form_Element_ComboBox'){
		    
					$opciones = $element->options;
					$valor = $this->getValue($element->getName());
	
					if(isset($opciones[$valor]))
						$element->setValue($opciones[$valor]);
					else{
						$element->setValue('');
					}
	
				}
	
		   
		   
			}
		}else{
			if(isset($this->$name)){
	
				 
				 
				 
				 
				$this->$name->helper = 'formNote';
	
				if(get_class($this->$name) == 'Zend_Dojo_Form_Element_ComboBox'){
					 
					$opciones = $this->$name->options;
					$valor = $this->getValue($name);
					if(isset($opciones[$valor]))
						$this->$name->setValue($opciones[$valor]);
					else{
						$this->$name->setValue('');
					}
				}
				 
				 
				 
				 
			}
		}
	}
	public function addGrid(AppListado $listado){
		$this->grids[] = $listado;
	} 	
	
	public function getGrids(){
		return $this->grids;
	}
	
	

	/**
	 * Add a display group
	 *
	 * Groups named elements for display purposes.
	 *
	 * If a referenced element does not yet exist in the form, it is omitted.
	 *
	 * @param  array $elements
	 * @param  string $name
	 * @param  array|Zend_Config $options
	 * @return Zend_Form
	 * @throws Zend_Form_Exception if no valid elements provided
	 */
	public function addDisplayGroup(array $elements, $name, $options = null)
	{
		$group = array();
		foreach ($elements as $element) {
			if (isset($this->_elements[$element])) {
				$add = $this->getElement($element);
				if (null !== $add) {
					unset($this->_order[$element]);
					$group[] = $add;
				}
			}
		}
		if (empty($group)) {
			require_once 'Zend/Form/Exception.php';
			throw new Zend_Form_Exception('No valid elements specified for display group');
		}
	
		$name = (string) $name;
	
		if (is_array($options)) {
			$options['elements'] = $group;
		} elseif ($options instanceof Zend_Config) {
			$options = $options->toArray();
			$options['elements'] = $group;
		} else {
			$options = array('elements' => $group);
		}
	
		if (isset($options['displayGroupClass'])) {
			$class = $options['displayGroupClass'];
			unset($options['displayGroupClass']);
		} else {
			$class = $this->getDefaultDisplayGroupClass();
		}
	
		if (!class_exists($class)) {
			require_once 'Zend/Loader.php';
			Zend_Loader::loadClass($class);
		}
		$this->_displayGroups[$name] = new $class(
				$name,
				$this->getPluginLoader(self::DECORATOR),
				$options
		);
	
		if (!empty($this->_displayGroupPrefixPaths)) {
			$this->_displayGroups[$name]->addPrefixPaths($this->_displayGroupPrefixPaths);
		}
	
		$this->_order[$name] = $this->_displayGroups[$name]->getOrder();
		$this->_orderUpdated = true;
		return $this;
	}
	

	public function addUrlAmigambles(){
		$url_amigable = new EFTexto('url_amigable');
		$url_amigable->setLabel('Url amigable');
		$this->addElement($url_amigable);
	} 
	
	public function addElementoVista($contenedor){
		$this->_elementos[] = $contenedor;
	}
	public function eleiminaElemento($elemento){
		foreach ($this->_elementos as $key => $value){
			if($value == $elemento){
				unset($this->_elementos[$key]);
			}
		}
	}
	public function render(Zend_View_Interface $view = null){
				
		$html = '';
		$html .= '<form id="'.$this->getName().'"';
		foreach ($this->getAttribs() as $key => $value){
			
			$html .= ' '.$key.'="'.$value.'" ';
		}
		$html .= ' method="'.$this->getMethod().'" ';
		
		$html .= ' action="'.$this->getAction().'" ';
		$html .= ' enctype="'.$this->getEnctype().'"';
		$html .='>';
		
		
		foreach($this->_elementos as $elemento){
			if(is_object($elemento)){
				$html .= $elemento->render();
			}else{
				$html .= $elemento;
			}
		}
		$html .='</form>';
		$html .= '';
		return $html;
		
		
	}
	
}