<?php

Goweb::loadClass('Index_Controller', ADMIN_PATH);

/**
 * Goweb Sitemanager 5 Framework
 * @version    5.0.25
 * @category   Backoffice
 * @package    Form
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2010 (c) Goweb (http://www.goweb.pt)
*/
class Form_GenericController extends Index_Controller {

    /**
     * Titulo do Modulo
     * @var string
    */
    protected $_title;
    
    /**
     * Controller do Modulo
     * @var string
    */
    protected $_controller = 'form';
    
    /**
     * Seccoes do Modulo
     * @var array
    */
    protected $_sections;
    
    /**
     * Seccao default do modulo
     * @var string
    */
    protected $_section = 'form';
    
    /**
     * Objecto Form_Model_Form
     * @var Form_Model_Form
    */
    protected $_formModel = null;
    
    /**
     * Objecto Form_Model_Element
     * @var Form_Model_Element
    */
    protected $_elementModel = null;

    /**
     * Mensagem de erro
     *
     * @var strint
    */
    protected $_error = null;
    
    /**
     * Mensagem de sucesso
     *
     * @var strint
    */
    protected $_message = null; 
    
    /**
     * Objecto Goweb_Db_Model_Adapter
     * @var Goweb_Db_Model_Adapter
    */
    protected $_dbAdapter = null;

    /**
     * Objecto Goweb_Config_Ini
     * @var Goweb_Config_Ini
    */
    protected $_moduleConfig = null;

    /**
     * Parametros para a criacao da arvore
     *
     * @var array
    */
    protected $_categoriasTreeParams = array('target'         => null,
                                             'folderLinks'    => true,
                                             'useSelection'   => true,
                                             'useCookies'     => false,
                                             'useLines'       => true,
                                             'useIcons'       => true,
                                             'useStatusText'  => false,
                                             'closeSameLevel' => false,
                                             'inOrder'        => false);

    /**
     * Parametros para a criacao dos n&oacute;s da arvore
     *
     * @var array
    */
    protected $_categoriasNodesParams = array('rootName'   => 'Raiz',
                                              'id'         => 'id',
                                              'pid'        => 'pai_id',
                                              'name'       => 'titulo',
                                              'url'        => '/form/list_form/categoria_id/',
                                              'urlId'      => 'id',
                                              'target'     => null,
                                              'title'      => null,
                                              'icon'       => null,
                                              'iconOpen'   => null,
                                              'open'       => null,
                                              'url_1'      => '/form/edit/section/categorias/id/',
                                              'url_1_icon' => '/media/images/icon_edit.png',
                                              'url_2'      => '/form/delete/section/categorias/id/',
                                              'url_2_icon' => '/media/images/icon_delete.gif',
                                              'url_3'      => '/form/add/section/categorias/pai_id/',
                                              'url_3_icon' => '/media/images/icon_add.png');
    /**
     * @var array
     */
    protected $_rootCategoriasNodeParams = null;
    
    /**
     * Construtor da classe
    */
    public function init() {
        if ($this->_getParam('section') && strcmp($this->_getParam('section'), 'form') === 0) $this->_forward('listForm');
        
        $this->_title = translateAdmin('Gest&atilde;o de Formul&aacute;rios');
        $this->_sections = array(array('title'   => translateAdmin('Formul&aacute;rios'),
                                       'section' => 'form',
                                       'link'    => '/form/listForm/'));
        
        parent::init();
        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_formModel = Goweb::getModelInstance('Form_Model_Form', 'db');
        $this->_elementModel = Goweb::getModelInstance('Form_Model_Element', 'db');
        $this->_rootCategoriasNodeParams =  $this->_categoriasNodesParams;
        $this->_rootCategoriasNodeParams['url_1'] = null;
        $this->_rootCategoriasNodeParams['url_1_icon'] = null;
        $this->_rootCategoriasNodeParams['url_2'] = null;
        $this->_rootCategoriasNodeParams['url_2_icon'] = null;
        $this->_moduleConfig = new Goweb_Config(Goweb_Config_Ini::load(APPLICATION_PATH . DIRECTORY_SEPARATOR . 'Form' . DIRECTORY_SEPARATOR . 'config.ini', 'base'));
        $this->_paginatorParams = array('rows_per_page' => 40, 'links_per_page' => 10);
        $this->_initDefaultLinks();
        $this->view->sections = $this->_sections;
        $this->view->title   = $this->_title;              
    }

    /**
     * Metodo chamado quando nenhuma action &eacute; fornecida
    */
    public function indexAction() {
        return $this->listFormAction();
    }
    
    /**
     * Listagem dos formularios
    */
    public function listFormAction() {
        $this->_links['elements']   = '/form/list_elements/form_id/';
        $this->_links['submissoes'] = '/form/list_submissoes/form_id/';
        $this->_links['edit']       = '/form/editForm/id/';
        $this->_links['add']        = '/form/addForm/id/';
        $this->_links['delete']        = '/form/deleteForm/id/';
        $this->_links['deletelist']        = '/form/deletelistForm/id/';
        
        Goweb::loadClass('Goweb_Admin_Section');        
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Formul&aacute;rios'));
        $section->setTitleSingular(translateAdmin('Formul&aacute;rio'));
        $section->setModel($this->_formModel);
        $section->setListCols(array('titulo', 'email', 'submissoes', 'criado'));
        $section->setSearchCols(array('titulo'));
        $section->setOrdering('titulo');
        if ($this->_formModel->colExists('categoria_id')){
            $categoriaId = $this->_getParam('categoria_id');
            $tree = $this->_getTreeObject(true);
            if ($tree instanceof Goweb_Js_Dhtmlx_Tree && $categoriaId > 0){
                $this->_categoriaModel->loadForeigns(false);
                $cats = $this->_categoriaModel->getPais($categoriaId);
                $cats = array_reverse($cats, true);
                $this->_categoriaModel->loadForeigns(true);
                $tree->setOpenTo($cats);
            } else {
                $tree->setOpenTo($categoriaId);
            }
            $section->setTreeObject($tree);
        }
        
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->action  = translateAdmin('Listagem');
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_listGeneric($section, $this->view, false);
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->section_title = $section->getTitle();
        $this->_helper->viewRenderer->setRender('base');        
    }

    /**
     * Adicionar formularios
     *
     * @param boolean
    */
    public function addFormAction($cleanValues = false) {        
        $this->_links['save'] = '/form/saveForm/';
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Formul&aacute;rios'));
        $section->setTitleSingular(translateAdmin('Formul&aacute;rio'));
        $section->setModel($this->_formModel);
        
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->action  = translateAdmin('Inser&ccedil;&atilde;o');
        $this->view->output = $this->_addGeneric($section, $this->view, null, null, $cleanValues, true, false);
        $this->view->section_title = $section->getTitle();
        $this->_helper->viewRenderer->setRender('base');        
    }
    
    /**
     * Editar formularios
    */
    public function editFormAction() {
        $this->_links['save'] = '/form/saveForm/id/' . $this->_getParam('id') . '/';
        if (!$this->_validateId($this->_getParam('id')) || !$this->_formModel->find($this->_getParam('id'))) {
            return $this->listFormAction();
        }        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Formul&aacute;rios'));
        $section->setTitleSingular(translateAdmin('Formul&aacute;rio'));
        $section->setModel($this->_formModel);
        
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->action  = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->output = $this->_editGeneric($section, $this->view);
        $this->view->section_title = $section->getTitle();
        $this->_helper->viewRenderer->setRender('base');
        
    }

    /**
     * Salvar formularios
    */
    public function saveFormAction() {        
        $this->_links['save'] = '/form/saveForm/id/' . $this->_getParam('id') . '/';
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Formul&aacute;rios'));
        $section->setTitleSingular(translateAdmin('Formul&aacute;rio'));
        $section->setModel($this->_formModel);
        $this->view->action  = translateAdmin('Gravar');
        
        $createFlag = false;
        if (!$this->_formModel->find($this->_getParam('id'))) {
            $createFlag = true;
        }
        
        $output = $this->_saveGeneric($section, $this->view);
        
        if (is_bool($output)) {
            if ($createFlag) {
                $this->_createTable($this->_formModel->id);
            }
            
            if ($this->_request->submit) {
                return $this->listFormAction();
            }
            if ($this->_request->submit_and_new) {
                return $this->addFormAction(true);
            }
        }
        
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->output = $output;
        $this->view->section_title = $section->getTitle();
        $this->_helper->viewRenderer->setRender('base');        
    }
    
    /**
     * Apagar formularios
    */
    public function deleteFormAction() {        
        $id = $this->_getParam('id');
        if (!$this->_validateId($id) || !$this->_formModel->find($id)) {
            return $this->listFormAction();
        }
        $this->_message = translateAdmin('O Formul&aacute;rio foi removido com sucesso.');
        // apaga a tabela de submissees
        $this->_dropTable($this->_formModel->id);
        // apaga todos elementos com o ID do formul&aacute;rio
        $this->_elementModel->deleteWhere("form_id='$id'");
        // apaga o formul&aacute;rio
        $this->_formModel->delete();        
        $this->listSubmissoesAction();        
    }

    /**
     * Apagar listagem de formularios
    */
    public function deletelistFormAction() {
        
        if (count($this->_request->ids) > 0) {
            $ids = implode(',', $this->_request->ids);
            // apaga as tabelas de submissoes
            foreach ($this->_request->ids as $id) {
                $this->_dropTable($id);
            }
            // apaga os formularios
            $this->_formModel->deleteWhere('id IN (' . $ids . ')');
            
            // apaga os elementos com o id dos formularios removidos
            $this->_elementModel->deleteWhere('form_id IN (' . $ids . ')');
            
            $this->_message = translateAdmin('Os registos seleccionados foram eliminados com sucesso!');
            $this->listFormAction();
            return true;
        }
        
        $this->_error = translateAdmin('Nenhum registo foi seleccionado para ser eliminado.');
        $this->listFormAction();
        return false;
    }
    
    /**
     * Listagem das Submissoes
    */
    public function listSubmissoesAction() {
        $formId = $this->_getParam('form_id');     
        if (!$this->_validateId($formId) || !$this->_formModel->find($formId)) {
            return $this->listFormAction();
        }
        $this->_links['list'] = '/form/list_submissoes/form_id/' . $formId .'/';
        $this->_links['edit'] = '/form/edit_submissao/form_id/' . $formId . '/id/';
        $this->_links['delete'] = '/form/delete_submissao/form_id/' . $formId . '/id/';
        $this->_links['deletelist'] = '/form/delete_submissoes/form_id/' . $formId . '/';
        // $model = $this->_getFormModel($formId);
        if ($this->_getParam('export')){
            $model = $this->_getFormModel($formId);
        } else {
            $model = $this->_getFormModel($formId, 6);
        }
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Submiss&otilde;es'));
        $section->setTitleSingular(translateAdmin('Submiss&atilde;o'));
        $section->setModel($model);
        $cols = $model->getCols();

        unset($cols['id']);
        unset($cols['form_id']);
        unset($cols['actualizado']);
        unset($cols['ip']);
        $cols = array_keys($cols);
        $listCols = $cols;
        $section->setListCols($listCols);
        $section->setOrdering('-criado');
        
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;
        $this->view->action  = translateAdmin('Listagem');
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_listGeneric($section,
                                                   $this->view,
                                                   false,
                                                   'list_submissoes.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Remover Submissoes
    */
    public function deleteSubmissoesAction() {
        $formId = $this->_getParam('form_id');     
        if (!$this->_validateId($formId) || !$this->_formModel->find($formId)) {
            return $this->listFormAction();
        }
        
        
        if (count($this->_request->ids) > 0) {
            $adapter = $this->_elementModel->getAdapter();
            
            $ids = implode(',', $this->_request->ids);
            
            // apagar as submissoes seleccionadas
            $sql = 'DELETE FROM form_id_' . $formId . ' WHERE id IN (' . $ids . ')';
            $adapter->query($sql);
            
            $sql = 'SELECT COUNT(*) AS count FROM form_id_' . $formId;
            $result = $adapter->fetchAll($sql);
            
            $nro_submissoes = 0;
            if (array_key_exists('0', $result)) {
                if (array_key_exists('count', $result['0'])) {
                    $nro_submissoes = $result['0']['count'];
                }
            }
            
            // actualizar o numero de submissoes do form
            if ($this->_formModel->find($formId)) {
                $this->_formModel->submissoes = $nro_submissoes;
                $this->_formModel->save();
            }
            $cache = Zend_Registry::get('cache');
            $cache->clean(Zend_Cache::CLEANING_MODE_ALL);
            clearstatcache(); 
            $this->_message = translateAdmin('Os registos seleccionados foram eliminados com sucesso!');
            $this->_forward('list_submissoes', 'form', array('form_id' => $formId));
            return true;
        }
        
        $this->_error = translateAdmin('Nenhum registo foi seleccionado para ser eliminado.');
        $this->listFormAction();
        return false;
    }
    
    /**
     * Editar Submissoes
    */
    public function editSubmissaoAction() {        
        $formId = $this->_getParam('form_id');
        $id = $this->_getParam('id');
        $this->_links['save'] = '/edit_submissao/save/form_id/' . $formId . '/id/' . $id . '/';

        if (!$this->_validateId($formId) || !$this->_formModel->find($formId)) {
            return $this->listFormAction();
        }
        $model = $this->_getFormModel($formId);

        if (!$this->_validateId($id) || !$model->find($id)) {
            return $this->listFormAction();
        }

        $form = $this->_getForm($formId, $id);
        $form->submit = $form->Submit();
        $form->submit->value = translateAdmin('Gravar');
        $form->submit->class = 'form_submit';

        $this->_elementModel->where($this->_elementModel->getTableName() . '.form_id=?', $formId);
        $rowset = $this->_elementModel->fetchAll();

        if ($rowset) {
            foreach ($rowset as $row) {
                $nome = 'element_' . $row->id;
                $form->{$nome}->value = preg_match("/a:?[0-9]:{.*}/", $model->{$nome}) > 0 ? unserialize($model->{$nome}) : $model->{$nome};                
            }
        }
        $form->render();

        $this->view->upload_path = $this->_moduleConfig->files->target . DIRECTORY_SEPARATOR;
        $this->view->form = $form;
        $this->view->model = $model;
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->action  = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->section_singular  = translateAdmin('Submiss&atilde;o');
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('form_submissao.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }

    /**
     * Salvar Submissoes
    */
    public function saveSubmissaoAction() {                
        $formId = $this->_getParam('form_id');
        $id = $this->_getParam('id');
        $this->_links['save'] = '/edit_submissao/save/form_id/' . $formId . '/id/' . $id . '/';
        
        if (!$this->_validateId($formId) || !$this->_formModel->find($formId)) {
            return $this->listFormAction();
        }
        $model = $this->_getFormModel($formId);

        if (!$this->_validateId($id) || !$model->find($id)) {
            return $this->listFormAction();
        }

        $form = $this->_getForm($formId, $id);
        $form->submit = $form->Submit();
        $form->submit->value = translateAdmin('Gravar');
        $form->submit->class = 'form_submit';

        if (!$form->validate()) {
            if (count($form->getErrorMessages()) > 1) {
                $this->_error = translateAdmin('Corrija por favor os erros no formul&aacute;rio');
            } else {
                $this->_error = translateAdmin('Corrija por favor o erro no formul&aacute;rio');
            }
        } else {
            $this->_message = translateAdmin('A Submiss&atilde;o foi actualizada com sucesso');

            $upload_path = WWW_PATH . $this->_moduleConfig->files->target;
            foreach ($form->getElementsNames() as $element) {
                if (is_array($form->{$element}->value)) {
                    if (array_key_exists('tmp_name', $form->{$element}->value) && $form->{$element}->value['tmp_name'] != '') {
                        // fazer o upload do ficheiro                        
                        if (!file_exists($upload_path)) {
                            mkdir($upload_path);
                            chmod($upload_path, 0755);
                        } elseif ((!is_readable($upload_path)) || (!is_writable($upload_path))) {
                            try {
                                chmod($upload_path, 0755);
                            } catch (Exception $e) {
                                throw new Exception("N&atilde;o foi poss&iacute;vel atribuir permiss&otilde;es e pasta '$upload_path'");
                            }
                        }
                        
                        if ((array_key_exists('name', $form->{$element}->value) && ($form->{$element}->value['name']!=''))) {                            
                            if ($model->{$element} != '') {
                                try {
                                    if (is_writable($upload_path . DIRECTORY_SEPARATOR . $model->{$element})) {
                                        unlink($upload_path . DIRECTORY_SEPARATOR . $model->{$element});
                                    }
                                } catch (Exception $e) {
                                    // ignora
                                }
                            }
                            $tmp_name = $form->{$element}->value["tmp_name"];
                            $filename = time() . '_' . $form->{$element}->value['name'];
                            move_uploaded_file($tmp_name, $upload_path . DIRECTORY_SEPARATOR . $filename);
                            chmod($upload_path . DIRECTORY_SEPARATOR . $filename, 0777);
                            $model->{$element} = $filename;
                        }
                    } elseif ($element != 'submit' && $form->{$element}->type != 'file') {
                        // array com opcoes
                        $model->{$element} = serialize($form->{$element}->value);
                    }
                } elseif ($element != 'submit' && $form->{$element}->type != 'file') {
                    $model->{$element} = $form->{$element}->value;
                }
                if ($form->{$element}->type == 'file' && $this->_request->{$element . '_del'} == '1') {                    
                    try {
                        if (is_writable($upload_path . DIRECTORY_SEPARATOR . $model->{$element})) {
                            unlink($upload_path . DIRECTORY_SEPARATOR . $model->{$element});
                        }
                    } catch (Exception $e) {
                        // ignora
                    }
                    $model->{$element} = '';
                }
            }
            $model->save();
        }
        
        $form->render();

        $this->view->upload_path = $this->_moduleConfig->files->target . DIRECTORY_SEPARATOR;
        $this->view->form = $form;
        $this->view->model = $model;
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->action  = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->section_singular  = translateAdmin('Submiss&atilde;o');
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->view->render('form_submissao.tpl');        
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->_helper->viewRenderer->setRender('base');
    }    
    
    /**
     * Remover Submissoes
    */
    public function deleteSubmissaoAction() {
        $formId = $this->_getParam('form_id');     
        if (!$this->_validateId($formId) || !$this->_formModel->find($formId)) {
            return $this->listFormAction();
        }
        $model = $this->_getFormModel($formId);
        $id = $this->_getParam('id');
        if (!$this->_validateId($id) || !$model->find($id)) {
            return $this->listFormAction();
        }
        $this->_message = translateAdmin('A Submiss&atilde;o foi removida com sucesso.');
        $model->delete();
        
        $adapter = $this->_elementModel->getAdapter();

        $sql = 'SELECT COUNT(*) AS count FROM form_id_' . $formId;
        $result = $adapter->fetchAll($sql);
        
        $nro_submissoes = 0;
        if (array_key_exists('0', $result)) {
            if (array_key_exists('count', $result['0'])) {
                $nro_submissoes = $result['0']['count'];
            }
        }
        
        // actualizar o numero de submissoes do form
        if ($this->_formModel->find($formId)) {
            $this->_formModel->submissoes = $nro_submissoes;
            $this->_formModel->save();
        }
        
        $this->listSubmissoesAction($formId);
    }

    /**
     * Remover todas as Submissoes seleccionadas
    */
    public function deletelistSubmissoesAction() {
        $ids = $this->_request->ids;        
        if (count($ids) == 0) {            
            return $this->listFormAction();
        }
        $model = $this->_getFormModel($formId);
        $firstId = $ids[0];
        if (!$this->_validateId($firstId) || !$model->find($firstId)) {
            return $this->listFormAction();
        }
        $formId = $model->form_id;
        foreach ($ids as $id) {
            if ($model->find($id)) {
                $model->delete();
            }
        }
        $this->_message = translateAdmin('As Submiss&atilde;o seleccionadas foram removidas com sucesso.');
        $this->listSubmissoesAction($formId);
    }
    
    /**
     * Gravar a ordem dos elementos
     *
     * @return null
     */
    public function saveElementsOrdemAction(){
        $this->_helper->viewRenderer->setNoRender();
        if (!$this->_request->isAjax()) return false;
        parse_str($this->_request->data, $ordemList);
        foreach (current($ordemList) as $ordem => $id){
            if ($this->_validateId($id) && $this->_elementModel->find($id)){
                $this->_elementModel->ordem = $ordem;
                $this->_elementModel->save();
            }
        }
    }
    
    /**
     * Listagem de Elementos
    */
    public function listElementsAction($formId = null) {        
        if (!$formId) {
            $formId = $this->_getParam('form_id');
        }
        $this->_links['list'] = '/form/list_elements/form_id/' . $formId .'/';
        $this->_links['add'] = '/form/add_element/form_id/' . $formId . '/';        
        $this->_links['edit'] = '/form/edit_element/id/';
        $this->_links['delete'] = '/form/delete_element/id/';
        $this->_links['deletelist'] = null;
        $this->_links['save_ordem'] = 'gowebSubmitListOrder("'.$this->view->link("/form/save-elements-ordem/").'");';
        if (!$this->_validateId($formId) || !$this->_formModel->find($formId)) {
            return $this->listFormAction();
        }        
        $this->_elementModel->where($this->_elementModel->getTableName() . '.form_id=?', $formId);
        //$elements = $this->_elementModel->fetchAll();
        $this->view->elements_types = $this->_elementModel->getElementsTypes();        
        Goweb::loadClass('Goweb_Admin_Section');
        $section = new Goweb_Admin_Section();
        $section->setTitle(translateAdmin('Campos'));
        $section->setTitleSingular(translateAdmin('Campo'));
        $section->setModel($this->_elementModel);
        $section->setListCols(array('ordem', 'label', 'form', 'actualizado', 'criado'));
        $section->setSearchCols(array('titulo'));
        $section->setOrdering(array('ordem', '-criado'));
        
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->action  = translateAdmin('Listagem');
        $this->view->setViewsPath(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'views');
        $this->view->output = $this->_listGeneric($section, $this->view, false, 'list_elements.tpl');
        $this->view->setViewsPath(GENERIC_VIEWS_PATH);
        $this->view->section_title = $section->getTitle();
        $this->_helper->viewRenderer->setRender('base');
        
    }
    
    public function verifyConnectivityAction() {
        for ($i = 0; $i < 7000000; $i++) {}
        
        $connectionStatus = true;
        
        switch ($this->_request->db_type) {
        case 'mysql':
            $connectionStatus = mysql_connect($this->_request->host, $this->_request->user, $this->_request->pass);
            break;
        case 'oracle':
            $connectionStatus = ora_logon($this->_request->user, $this->_request->pass);
            break;
        case 'mssql':
            $connectionStatus = mssql_connect($this->_request->host, $this->_request->user, $this->_request->pass);
            if ($connectionStatus <= 0) {
                $connectionStatus = false;
            }
            break;
        }
        
        $html = "";
        if ($connectionStatus) {
            $html = '<img id="image_db_test" src="/admin/media/images/icon_true.gif">&nbsp;<font color="#2A931C">'.translateAdmin('Conex&atilde;o testada com sucesso!') . '</font>';
        } else {
            $html = '<img id="image_db_test" src="/admin/media/images/icon_false.gif">&nbsp;<font color="#FF000">'.translateAdmin('Conex&atilde;o falhou!') . '</font>';
        }
        
        $html .= '<br /><img id="image_db_test" src="/admin/media/images/icon_warning.png">&nbsp;<a href="javascript:testarConexao($(\'db_type\'), $(\'db_host\'), $(\'db_user\'), $(\'db_pass\'));" style="color:#999999;">'.translateAdmin('Testar Conex&atilde;o') . '</a>';
        
        echo $html;
    }
    
    /**
     * Adicionar Elementos
    */
    public function addElementAction($formId = null, $element = null) {        
        if (!$formId) {
            $formId = $this->_getParam('form_id');
        }
        
        if (!$element) {
            $element = $this->_request->element;                
        }
        
        $this->_links['save'] = '/form/save_element/form_id/' . $formId . '/';
        if (!$this->_validateId($formId) || !$this->_formModel->find($formId)) {
            return $this->listFormAction();
        }
        
        $elementsTypes = $this->_elementModel->getElementsTypes();        
        if (!$element || !array_key_exists($element, $elementsTypes)) {
            return $this->listFormAction();
        }
        
        $elementForm = 'Form_' . ucfirst($element);
        
        Goweb::loadClass($elementForm, ADMIN_PATH . DIRECTORY_SEPARATOR . 'Form');
        $form = new $elementForm($this->_section, $this->_links['save']);
        $form->setModel($this->_elementModel);
        $form->setup();
        $form->addHidden('element', $element);
        $form->render();
        
        if ($element == 'combo') {
            $this->view->combo = 1;
        } else {
            $this->view->combo = 0;
        }
        
        $this->view->sections         = $this->_sections;
        $this->view->links            = $this->_links;        
        $this->view->error            = $this->_error;
        $this->view->message          = $this->_message;        
        $this->view->model            = $this->_elementModel;
        $this->view->form             = $form;
        $this->view->action           = translateAdmin('Inser&ccedil;&atilde;o');
        $this->view->title            = $this->_title;
        $this->view->section          = translateAdmin('Campos');
        $this->view->section_singular = translateAdmin('Campo');        
        $this->view->output           = $this->view->render('form.tpl');
        $this->view->section_title    = translateAdmin('Campos');
        
        $this->_helper->viewRenderer->setRender('base');        
    }

    /**
     * Editar Elementos
    */
    public function editElementAction() {        
        $id = $this->_getParam('id');
        $this->_links['save'] = '/form/save_element/id/' . $id . '/';
        
        if (!$this->_validateId($id) || !$this->_elementModel->find($id)) {
            return $this->listFormAction();
        }
        
        $elementForm = 'Form_' . ucfirst($this->_elementModel->element);
        Goweb::loadClass($elementForm, ADMIN_PATH . DIRECTORY_SEPARATOR . 'Form');
        $form = new $elementForm($this->_section, $this->_links['save']);
        $form->setModel($this->_elementModel);
        $form->setup();
        $form->label->value = $this->_elementModel->label;
        $form->ordem->value = $this->_elementModel->ordem;
        
        if ($this->_elementModel->element != 'separator') {
            $form->required->value = $this->_elementModel->required;
        }
        
        if ($this->_elementModel->element == 'text') {
            $form->size->value = $this->_elementModel->size;
            if (strlen($this->_elementModel->validators)) {
                $validators = unserialize($this->_elementModel->validators);                
                $form->validators->value = $validators;
            }
            if ($this->_elementModel->colExists('email') && $form->elementExists('email')){
                $form->email->value = $this->_elementModel->email;
            }
        }
        
        if ($this->_elementModel->element == 'textarea') {
            $form->cols->value = $this->_elementModel->cols;
            $form->rows->value = $this->_elementModel->rows;
        }
        
        if ($this->_elementModel->element == 'select') {
            $form->multiple->value = $this->_elementModel->multiple;
            $form->rows->value = $this->_elementModel->rows;
        }
        if ($this->_elementModel->element == 'checkbox') {
            $form->multiple->value = $this->_elementModel->multiple;
        }
        
        if ($this->_elementModel->element == 'combo') {
            $form->db_type->value          = $this->_elementModel->db_type;
            $form->db_host->value          = $this->_elementModel->db_host;
            $form->db_user->value          = $this->_elementModel->db_user;
            $form->db_pass->value          = $this->_elementModel->db_pass;
            $form->db_name->value          = $this->_elementModel->db_name;
            $form->db_table->value         = $this->_elementModel->db_table;
            $form->db_table_value->value   = $this->_elementModel->db_table_value;
            $form->db_table_desc->value    = $this->_elementModel->db_table_desc;
            $form->clausulas_extras->value = $this->_elementModel->clausulas_extras;
        }
        
        if (strlen($this->_elementModel->options)) {
            //$options = unserialize($this->_elementModel->options);
            $options = $this->_elementModel->options;
            if (is_array($options)) {
                $form->options->value = implode("\n", $options);
            } elseif (strlen($options)) {
                $form->options->value = $options;
            }
        }
        
        if ($this->_elementModel->element == 'combo') {
            $this->view->combo = 1;
        } else {
            $this->view->combo = 0;
        }
        
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->error = $this->_error;
        $this->view->message = $this->_message;
        $form->render();
        $this->view->model = $this->_elementModel;
        $this->view->form = $form;
        $this->view->action  = translateAdmin('Edi&ccedil;&atilde;o');
        $this->view->title   = $this->_title;
        $this->view->section = translateAdmin('Campos');
        $this->view->section_singular = translateAdmin('Campo');
        $this->view->output = $this->view->render('form.tpl');
        $this->view->section_title = translateAdmin('Campos');
        $this->_helper->viewRenderer->setRender('base');        
    }

    /**
     * Salvar Elementos
    */
    public function saveElementAction() {        
        $id = $this->_getParam('id');
        $formId = $this->_getParam('form_id');
        $elementsTypes = $this->_elementModel->getElementsTypes();
        $element = $this->_request->element;
        $action = translateAdmin('Inser&ccedil;&atilde;o');
        if ($this->_validateId($id) && $this->_elementModel->find($id)) {            
            $this->_links['save'] = '/form/save_element/id/' . $id . '/';
            $element = $this->_elementModel->element;
            $action = translateAdmin('Edi&ccedil;&atilde;o');
        } elseif (!$this->_validateId($formId) || !$this->_formModel->find($formId) || !$element || !array_key_exists($element, $elementsTypes)) {
            return $this->listFormAction();
        } else {
            $this->_links['save'] = '/form/save_element/form_id/' . $formId . '/';
            $this->_elementModel->form_id = $formId;
            $this->_elementModel->element = $element;
        }        
        $elementForm = 'Form_' . ucfirst($element);
        Goweb::loadClass($elementForm, ADMIN_PATH . DIRECTORY_SEPARATOR . 'Form');
        $form = new $elementForm($this->_section, $this->_links['save']);
        $form->setModel($this->_elementModel);
        $form->setup();
        $form->addHidden('element', $element);        
        if (!$form->validate()) {
            if (count($form->getErrorMessages()) > 1) {
                $this->_error = translateAdmin('Corrija por favor os erros no formul&aacute;rio');
            } else {
                $this->_error = translateAdmin('Corrija por favor o erro no formul&aacute;rio');
            }
        } else {            
            $this->_elementModel->label = $form->label->value;
            $this->_elementModel->ordem = $form->ordem->value;
            if ($element != 'separator') {
                $this->_elementModel->required = $form->required->value;                
            }
            if ($element == 'text') {
                $this->_elementModel->size = $form->size->value;
                $validators = serialize($form->validators->value);
                $this->_elementModel->validators = serialize($form->validators->value);
                if ($this->_elementModel->colExists('email') && $form->elementExists('email')){
                    $this->_elementModel->email = $form->email->value;
                }
            }
            if ($element == 'textarea') {
                $this->_elementModel->cols = $form->cols->value;
                $this->_elementModel->rows = $form->rows->value;
            }
            if ($element == 'select') {
                $this->_elementModel->multiple = $form->multiple->value;
                $this->_elementModel->rows = $form->rows->value;
                //$this->_elementModel->options = serialize(trim($form->options->value));
                $this->_elementModel->options = trim($form->options->value);
            }
            if ($element == 'combo') {
                $this->_elementModel->db_type          = $form->db_type->value;
                $this->_elementModel->db_host          = $form->db_host->value;
                $this->_elementModel->db_user          = $form->db_user->value;
                $this->_elementModel->db_pass          = $form->db_pass->value;
                $this->_elementModel->db_name          = $form->db_name->value;
                $this->_elementModel->db_table         = $form->db_table->value;
                $this->_elementModel->db_table_value   = $form->db_table_value->value;
                $this->_elementModel->db_table_desc    = $form->db_table_desc->value;
                $this->_elementModel->clausulas_extras = $form->clausulas_extras->value;
            }
            if ($element == 'checkbox') {
                $this->_elementModel->multiple = $form->multiple->value;
                //$this->_elementModel->options = serialize(trim($form->options->value));
                $this->_elementModel->options = trim($form->options->value);
            }
            if ($element == 'radio') {
                //$this->_elementModel->options = serialize(trim($form->options->value));
                $this->_elementModel->options = trim($form->options->value);
            }
            $this->_elementModel->save();
            if ($this->_validateId($id)) {
                $this->_message = translateAdmin('O Campo foi actualizado com sucesso.');                
            } else {
                $this->_addCol();
                $this->_message = translateAdmin('O Campo foi inserido com sucesso.');
            }
            if ($this->_request->submit) {
                return $this->listElementsAction($this->_elementModel->form_id);
            }
            if ($this->_request->submit_and_new) {
                return $this->addElementAction($this->_elementModel->form_id, $this->_elementModel->element);
            }
            $form->setAction('/form/form/save_element/id/' . $this->_elementModel->id . '/');
        }
        $form->render();
        
        if ($element == 'combo') {
            $this->view->combo = 1;
        } else {
            $this->view->combo = 0;
        }
        $this->view->sections = $this->_sections;
        $this->view->links = $this->_links;        
        $this->view->error = $this->_error;
        $this->view->message = $this->_message;        
        $this->view->model = $this->_elementModel;
        $this->view->form = $form;
        $this->view->action  = $action;
        $this->view->title   = $this->_title;
        $this->view->section = translateAdmin('Campos');
        $this->view->section_singular = translateAdmin('Campo');
        $this->view->error = $this->_error;
        $this->view->message = $this->_message;
        $this->view->output = $this->view->render('form.tpl');
        $this->view->section_title = translateAdmin('Campos');
        $this->_helper->viewRenderer->setRender('base');
    }
    
    /**
     * Remover Elementos
    */
    public function deleteElementAction() {
        $id = $this->_getParam('id');
        if (!$this->_validateId($id) || !$this->_elementModel->find($id)) {
            return $this->listFormAction();
        }
        $this->_message = translateAdmin('O Campo foi removido com sucesso.');
        $formId = $this->_elementModel->form_id;
        $this->_dropCol();
        $this->_elementModel->delete();
        $this->listElementsAction($formId);
    }
    
    /**
     * Criar tabela
     *
     * @param integer
    */
    protected function _createTable($formId) {
        $model = $this->_getFormModel($formId);
        $sql = $model->createTableSql();        
        $model->getAdapter()->query($sql['form_id_' . $formId]['sql']);
        if (array_key_exists('indexes', $sql['form_id_' . $formId])) {
            foreach ($sql['form_id_' . $formId]['indexes'] as $index) {                
                $model->getAdapter()->query($index);
            }
        }
    }
    
    /**
     * Remover tabela
     *
     * @param integer
    */
    protected function _dropTable($formId) {
        $db = $this->_elementModel->getAdapter();
        if (!$this->_dbAdapter) {
            $adapterType = 'Goweb_Db_Model_Adapter_' . ucfirst(substr(get_class($db), strrpos(get_class($db), '_')+1));
            Goweb::loadClass($adapterType);
            $this->_dbAdapter = new $adapterType();
        }
        $sql = $this->_dbAdapter->getDropTable(true) . ' form_id_' . $formId;
        $db->query($sql);
    }
    
    /**
     * Adicionar Coluna a tabela
    */
    protected function _addCol() {
        $db = $this->_elementModel->getAdapter();
        if (!$this->_dbAdapter) {
            $adapterType = 'Goweb_Db_Model_Adapter_' . ucfirst(substr(get_class($db), strrpos(get_class($db), '_')+1));
            Goweb::loadClass($adapterType);
            $this->_dbAdapter = new $adapterType();
        }
        
        $params = array('notnull' => null,
                        'default' => null,
                        'maxlength' => null);
        $colType = '';
        if ($this->_elementModel->element == 'text'     ||
            $this->_elementModel->element == 'checkbox' ||
            $this->_elementModel->element == 'radio'    ||
            $this->_elementModel->element == 'select'   ||
            $this->_elementModel->element == 'combo'    ||
            $this->_elementModel->element == 'file'     ||
            $this->_elementModel->element == 'separator') {
            $method = 'getChar';
            $params['maxlength'] = '255';
        } elseif ($this->_elementModel->element == 'textarea') {
            $method = 'getText';
        }
        $params['notnull'] = false;
        $sql = $this->_dbAdapter->getAddCol('form_id_' . $this->_elementModel->form_id);
        $sql .= ' element_' . $this->_elementModel->id . ' ' . $this->_dbAdapter->{$method}($params);
        $db->query($sql);
    }

    /**
     * Remover Coluna a tabela
    */
    protected function _dropCol() {
        $db = $this->_elementModel->getAdapter();
        if (!$this->_dbAdapter) {
            $adapterType = 'Goweb_Db_Model_Adapter_' . ucfirst(substr(get_class($db), strrpos(get_class($db), '_')+1));
            Goweb::loadClass($adapterType);
            $this->_dbAdapter = new $adapterType();
        }
        if (array_key_exists('element_' . $this->_elementModel->id, $db->describeTable('form_id_' . $this->_elementModel->form_id))) {
            $sql = $this->_dbAdapter->getDropCol('form_id_' . $this->_elementModel->form_id) . ' element_' . $this->_elementModel->id;
            $db->query($sql);
        }
    }

    /**
     * Métodos Privados
     */
    protected function _getTreeObject($cleanModelParts = true) {
        if (is_dir(WWW_PATH.'/admin/media/js/dhtmlx/')){
            Goweb::loadClass('Goweb_Js_Dhtmlx_Tree');
            $tree = new Goweb_Js_Dhtmlx_Tree('categorias');
            $tree->setLink('/form/treeDhtmlx/');
            $tree->setTitle(translateAdmin('Categorias'));
            goweb::loadCss('/admin/media/js/dhtmlx/dhtmlx.css');
            goweb::loadCss('/admin/media/css/dhtmlx.css');
            goweb::loadJavascript('/admin/media/js/dhtmlx/dhtmlx.js');
            goweb::loadJavascript('/admin/media/js/dhtmlx/connector.js');
            return $tree;
        }
        $this->_categoriaModel = Goweb::getModelInstance('Form_Model_Categoria', 'db');
        goweb::loadCss('/admin/media/css/dtree.css');
        goweb::loadJavascript('/admin/media/js/dtree.js');
        // cria o objecto Goweb_Js_Tree
        Goweb::loadClass('Goweb_Js_Tree');
        $tree = new Goweb_Js_Tree('categorias');
        $tree->setTitle(translateAdmin('Categorias'));

        // adiciona os parâmetros
        foreach ($this->_categoriasTreeParams as $param => $value) {
            $tree->{$param} = $value;
        }

        $nodesParams = $this->_categoriasNodesParams;

        // valida se foram passados os campos necessário para o node
        if (!array_key_exists('id', $nodesParams)) {
            throw new Goweb_Exception("O campo 'id' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('pid', $nodesParams)) {
            throw new Goweb_Exception("O campo 'pid' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('name', $nodesParams)) {
            throw new Goweb_Exception("O campo 'name' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('urlId', $nodesParams)) {
            throw new Goweb_Exception("O campo 'urlId' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }

        $idCol = $nodesParams['id'];
        $pidCol = $nodesParams['pid'];
        $nameCol = $nodesParams['name'];
        // $this->_categoriaModel->order($nameCol);
        if ($this->_categoriaModel->colExists('ordem')) $this->_categoriaModel->order('ordem');

        // não carregar as chaves estrangeiras
        $this->_categoriaModel->loadForeigns(false);
        // limpa todas as partes do SELECT
        if ($cleanModelParts) {
            $this->_categoriaModel->cleanParts();
        }

        if ($this->_categoriaModel->colExists('ordem')) $this->_categoriaModel->order('ordem');
        $fetchCols = array($idCol, $pidCol, $nameCol);
        if ($this->_categoriaModel->colExists('activo')){
            $fetchCols[] = 'activo';
        }
        $rowset = $this->_categoriaModel->fetchAll($fetchCols);

        unset($nodesParams['id']);
        unset($nodesParams['pid']);
        unset($nodesParams['name']);
        $urlBase = Zend_Controller_Front::getInstance()->getRequest()->getBaseUrl();
        if (strpos($nodesParams['url'], $urlBase) === false) $nodesParams['url'] = $urlBase . $nodesParams['url'];
        $node = new Goweb_Js_Tree_Node('0', '-1', '', $nodesParams['url'] . '0/');
        if (array_key_exists('rootName', $nodesParams)) {
            $node->name = $nodesParams['rootName'];
            unset($nodesParams['rootName']);
        }

        if ($this->_rootCategoriasNodeParams) {
            $rootNodeParams = $this->_rootCategoriasNodeParams;
        } else {
            $rootNodeParams = $nodesParams;
        }
        if (strpos($rootNodeParams['url'], $urlBase) === false) $rootNodeParams['url'] = $urlBase . $rootNodeParams['url'];
        
        // configura os links e icons extra
        for ($i=1; $i<=5; $i++) {
            $param = 'url_' . $i . '_icon';
            if  (array_key_exists($param, $rootNodeParams) && $rootNodeParams[$param]) {
                if (strpos($rootNodeParams[$param], $urlBase) === false){
                    $rootNodeParams[$param] = str_replace('/index.php', '', $urlBase) . $rootNodeParams[$param];
                }
                $node->{$param} = $rootNodeParams[$param];
                $param = 'url_' . $i;
                if (array_key_exists($param, $rootNodeParams) && $rootNodeParams[$param]) {
                    if (strpos($rootNodeParams[$param], $urlBase) === false) $rootNodeParams[$param] = $urlBase . $rootNodeParams[$param];
                    $node->{$param} = $rootNodeParams[$param] . '0/';
                }
            }
        }

        $tree->addNode($node);
        if ($rowset) {
            if (strpos($nodesParams['url'], $urlBase) === false) $nodesParams['url'] = $urlBase . $nodesParams['url'];
            foreach ($rowset as $row) {
                $titulo = $row->{$nameCol};
                if ($this->_categoriaModel->colExists('activo') && !$row->activo){
                    $titulo = '<span class="disabled_page">' . $titulo . '</span>';
                }
                $node = new Goweb_Js_Tree_Node($row->{$idCol},
                                               $row->{$pidCol},
                                               $titulo,
                                               $nodesParams['url'] . $row->{$idCol} . '/',
                                               $nodesParams['urlId'],
                                               $nodesParams['target'],
                                               $nodesParams['title'],
                                               $nodesParams['icon'],
                                               $nodesParams['iconOpen'],
                                               $nodesParams['open']);

                // configura os links e icons extra
                for ($i=1; $i<=5; $i++) {
                    $param = 'url_' . $i . '_icon';
                    if  (array_key_exists($param, $nodesParams) && $nodesParams[$param]) {
                        if (strpos($nodesParams[$param], $urlBase) === false){
                            $nodesParams[$param] = str_replace('/index.php', '', $urlBase) . $nodesParams[$param];
                        }
                        $node->{$param} = $nodesParams[$param];
                        $param = 'url_' . $i;
                        if (array_key_exists($param, $nodesParams) && $nodesParams[$param]) {
                            if (strpos($nodesParams[$param], $urlBase) === false) $nodesParams[$param] = $urlBase . $nodesParams[$param];
                            $node->{$param} = $nodesParams[$param] . $row->{$idCol} . '/';
                        }
                    }
                }

                // adiciona o node
                $tree->addNode($node);
            }
        }

        // retorna o Goweb_Js_Tree
        return $tree;
    }
    /**
     * Criação dinâmica da àrvore, componente dhtmlx
     *
     */
    public function treeDhtmlxAction(){
        $this->_helper->viewRenderer->setNoRender();
        $categoriaModel = Goweb::getModelInstance('Form_Model_Categoria', 'db', false);

        $idCat = $this->_request->id;
        if (!is_numeric($idCat)) {
            $idCat = 0;
        }
        $nodesParams = $this->_categoriasNodesParams;

        // valida se foram passados os campos necessário para o node
        if (!array_key_exists('id', $nodesParams)) {
            throw new Goweb_Exception("O campo 'id' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('pid', $nodesParams)) {
            throw new Goweb_Exception("O campo 'pid' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('name', $nodesParams)) {
            throw new Goweb_Exception("O campo 'name' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }
        if (!array_key_exists('urlId', $nodesParams)) {
            throw new Goweb_Exception("O campo 'urlId' &eacute; necess&aacute;rio nos par&aacute;metros dos nodes.");
        }

        $idCol = $nodesParams['id'];
        $pidCol = $nodesParams['pid'];
        $nameCol = $nodesParams['name'];
        $categoriaModel->where($categoriaModel->getTableName() . '.' . $pidCol . ' = ?', $idCat);
        $rowset = $categoriaModel->fetchAll();

        $data = array('id' => $idCat, 'item' => array());
        if ($idCat == 0){
            $data['item'][0] = array(
                        'id' => 'root', 
                        'text' => $this->_addTreeOptions(translateAdmin('Raiz'), 0, $this->_rootCategoriasNodeParams),
                        'item' => array());
        }
        if ($rowset){
            $items = array();
            foreach ($rowset as $item){
                $childs = $categoriaModel->getCountFilhos($item->{$idCol});
                $items[] = array(
                            'id' => $item->{$idCol}, 
                            'text' => $this->_addTreeOptions($item->{$nameCol}, $item->{$idCol}), 
                            'child' => $childs);
            }
            if ($idCat == 0){
                $data['item'][0]['item'] = $items;
            } else {
                $data['item'] = $items;
            }
        }

        if ($this->_getParam('format') == 'xml'){
            throw new Goweb_Exception('not completed');
            $this->getResponse()->setHeader('Content-Type', 'text/xml; charset=' . CHARSET);
            $output = '<tree id=\'' . $idCat . '\'>' . "\n";
            foreach ($data['item'] as $item){
                $output .= "<item ";
                foreach ($item as $key => $value){
                    if ($key != 'text'){
                        $output .= $key . "='" . $value . "' ";
                    } else {
                        $output .= $key . "='" . htmlspecialchars($value, ENT_QUOTES, CHARSET, false) . "' ";
                    }
                }
                $output .= '></item>' . "\n";
            }
            $output .= '</tree>' . "\n";
            $this->view->output = $output;
            $this->view->setViewsPath(VIEWS_PATH);
            $this->_helper->viewRenderer->setRender('vazia');
            $this->_helper->viewRenderer->setNoRender(false);

        } else {
            $this->_helper->json($data);
        }

    }

    /**
     * Devolve um determinado formulario
     *
     * @param integer
     * @param integer
     * 
     * @return Goweb_Form
    */
    protected function _getForm($formId, $id = 0) {
        Goweb::loadClass('Form_Barebone', APPLICATION_PATH . '/Form/');
        $form = new Form_Barebone('form', '/form/save_submissao/form_id/' . $formId . '/id/' . $id . '/');
        $form->setup($formId);
        return $form;
    }
    
    /**
     * Devolve um model
     *
     * @param integer
     *
     * @return Form_Model_Barebone
    */
    protected function _getFormModel($formId, $limite = 0) {
        Goweb::loadModel('Form_Model_Barebone');
        $bareboneModel = new Form_Model_Barebone($this->_formModel->getAdapter());        
        $bareboneModel->setup($formId,$limite);
        return $bareboneModel;
    }
}
