<?php

/**
 * Goweb Sitemanager 5 Framework
 *
 * Ficheiro de metodos comuns
 *
 * @version    5.0.25
 * @category   Goweb
 * @package    Goweb_Js_Dhtmlx
 * @subpackage Tree
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2010 (c) Goweb (http://www.goweb.pt)
 */

/**
 * Classe para gerar o javascript do dtree
 *
 * @version    5.0.25
 * @category   Goweb
 * @package    Goweb_Js_Dhtmlx
 * @subpackage Tree
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2010 (c) Goweb (http://www.goweb.pt)
 */
class Goweb_Js_Dhtmlx_Tree {

    /**
     * Nome da variável da tree
     *
     * @var  string
     */
    protected $_name = '';

    /**
     * Valor da tree no caso de haver um formul&aacute;rio
     *
     * @var  string
     */
    protected $_value = null;

    /**
     * Tipo da tree no caso de haver um formul&aacute;rio
     *
     * @var  string
     */
    protected $_type = null;

    /**
     * Valor da tree no caso de haver um formul&aacute;rio
     *
     * @var  string
     */
    protected $_format = 'json';

    /**
     * Titulo da tree
     *
     * @var  string
     */
    protected $_title = '';

    /**
     * Link para carregar dinâmicamente a tree
     *
     * @var  string
     */
    protected $_link = '';

    /**
     * ID do node a abrir
     *
     * @var  int
     */
    protected $_openTo = 0;

    /**
     * Expandir ervore
     *
     * @var  bool
     */
    protected $_expand = false;

    /**
     * Constructor
     *
     * @param  string  $name  Nome
     */
    public function __construct($name, $value = null, $type = null) {
        $this->_name = $name;
        $this->_value = $value;
        $this->_type = $type;
        // default format
        $this->setFormat();
    }

    /**
     * Atribui o titulo e tree.
     *
     * @param  string  $title  O titulo da tree
     */
    public function setTitle($title) {
        $this->_title = $title;
    }

    /**
     * Atribui um valor e tree.
     *
     * @param  string  $value  Valor
     */
    public function setValue($value) {
        $this->_value = $value;
    }

    /**
     * Atribui o ID do node a abrir.
     *
     * @param  int      $id        O ID do node
     */
    public function setOpenTo($id = 0) {
        if (is_null($id)) $id = 0;
        $this->_openTo = $id;
    }

    /**
     * Abre um nó.
     *
     * @param int $id O ID do nó
     * @return string javascript para abrir o nó
     */
    public function openTo($id = 0, $expand = false) {
        $lastId = 0;
        $output = '';
        if (is_array($id)){
            $count = 0;
            foreach (array_keys($id) as $key){
                if ($count > 0) {
                    $output .= '    function ' . $this->_name . '_level' . ($count - 1) . '_doAfterLoading(){' . "\n";
                }
                $output .= ($count > 0 ? '    ' : '') . '    ' . $this->_name . '_treeDhtmlX.loadXML("' . $this->getLink() . '?format=' . $this->getFormat() . '&id=' . $id[$key] . '", ' . $this->_name . '_level' . $count . '_doAfterLoading)' . "\n";
                if ($count > 0) {
                    $output .= '    }' . "\n";
                }
                if ($count == count($id) - 1){
                    $lastId = $id[$key];
                    $output .= '    function ' . $this->_name . '_level' . $count . '_doAfterLoading(){' . "\n";
                    if ($expand || $this->_expand) {
                        $output .= '        ' . $this->_name . '_treeDhtmlX.openAllItems(0);' . "\n";
                    } else {
                        $output .= '        ' . $this->_name . '_treeDhtmlX.openItem(' . $lastId . ');' . "\n";
                    }
                    $output .= '        ' . $this->_name . '_treeDhtmlX.focusItem(' . $lastId . ');' . "\n";
                    $output .= '        ' . $this->_name . '_treeDhtmlX.selectItem(' . $lastId . ', true);' . "\n";
                    $output .= '    }' . "\n";
                }
                $count++;
            }
        } elseif (is_numeric($id)){
            $count = 0;
            $output .= ($count > 0 ? '    ' : '') . '    ' . $this->_name . '_treeDhtmlX.loadXML("' . $this->getLink() . '?format=' . $this->getFormat() . '&id=0", ' . $this->_name . '_level' . $count . '_doAfterLoading)' . "\n";
            $lastId = $id;
            $output .= '    function ' . $this->_name . '_level' . $count . '_doAfterLoading(){' . "\n";
            $count++;
            if ($expand || $this->_expand) {
                $output .= '        ' . $this->_name . '_treeDhtmlX.openAllItems(0);' . "\n";
            } else {
                if ($lastId == 0){
                    $output .= '        ' . $this->_name . '_treeDhtmlX.openItem(0);' . "\n";
                    $output .= '        ' . $this->_name . '_treeDhtmlX.openItem(\'root\');' . "\n";
                } else {
                    $output .= '        ' . $this->_name . '_treeDhtmlX.openItem(' . $lastId . ');' . "\n";
                }
            }
            $output .= '        ' . $this->_name . '_treeDhtmlX.focusItem(' . $lastId . ');' . "\n";
            $output .= '        ' . $this->_name . '_treeDhtmlX.selectItem(' . $lastId . ', true);' . "\n";
            $output .= '    }' . "\n";

        }
        return $output;
    }

    /**
     * Define se e para expandir a ervore
     *
     * @param  boolean  $expand  TRUE para expandir
     */
    public function setExpand($expand) {
        $this->_expand = $expand;
    }

    /**
     * Efectua o rendering e retorna o output do javascript.
     *
     * @param bool $expand
     * @return string O output do javascript
     */
    public function render($expand = false) {
        $view = Zend_Registry::get('view');
        $output  = '<div id="' . $this->_name . '_treeboxbox_tree">' . "\n";
        $output .= '</div>' . "\n";
        $output .= '<script type="text/javascript" charset="' . CHARSET . '">' . "\n";
        $output .= '//<![CDATA[' . "\n";
        $output .= '    ' . $this->_name . '_treeDhtmlX=new dhtmlXTreeObject("' . $this->_name . '_treeboxbox_tree","100%","100%",0);' . "\n";
        $output .= '    ' . $this->_name . '_treeDhtmlX.setImagePath("' . $view->baseUrl . '/admin/media/js/dhtmlx/imgs/");' . "\n";
        $output .= '    ' . $this->_name . '_treeDhtmlX.setXMLAutoLoading("' . $this->getLink() . '?format=' . $this->getFormat() . '")' . "\n";
        $output .= $this->getFormatScript();
        $output .= $this->openTo($this->_openTo, $expand);
        if ($this->_type == 'checkbox') {
            $output .= '    ' . $this->_name . '_treeDhtmlX.attachEvent("onCheck",function(id,state){' . "\n";
            $output .= '        document.getElementById("' . $this->_name . '").value = ' . $this->_name . '_treeDhtmlX.getAllChecked();' . "\n";
            $output .= '    });' . "\n";
            $output .= '    ' . $this->_name . '_treeDhtmlX.enableCheckBoxes(1);' . "\n";

        }
        $output .= '//]]>' . "\n";
        $output .= '</script>' . "\n";
        if ($this->_type == 'checkbox') {
            $output .= '<input type="hidden" id="' . $this->_name . '" name="' . $this->_name . '"';
            // XHTML or HTML end tag?
            $endTag = ' />';
            if (($view instanceof Zend_View_Abstract) && !$view->doctype()->isXhtml()) {
                $endTag= '>';
            }
            $output .= $endTag;
        }
        return $output;
    }

    /**
     * Retorna o link para abrir todos os nodes
     *
     * @return  string
     */
    public function openAllLink() {
        return 'javascript:' . $this->_name . '_treeDhtmlX.openAllItems(\'root\');';
    }

    /**
     * Retorna o link para fechar todos os nodes
     *
     * @return  string
     */
    public function closeAllLink() {
        return 'javascript:' . $this->_name . '_treeDhtmlX.closeAllItems(\'root\');';
    }

    /**
     * Retorna o titulo da tree.
     */
    public function getTitle() {
        return $this->_title;
    }

    /**
     * Configura o link para carregar dinâmicamente a tree
     *
     * @param String $link
     */
    public function setLink($link){
        $this->_link = goweb::link($link);
    }

    /**
     * Retorna o link para carregar dinâmicamente a tree
     *
     * @return String
     */
    public function getLink(){
        return $this->_link;
    }

    /**
     * Configura modo de carregar dinâmicamente a tree
     *
     * @param String $link
     */
    public function setFormat($format = 'json'){
        $this->_format = $format;
    }

    /**
     * Retorna modo de carregar dinâmicamente a tree
     *
     * @return string
     */
    public function getFormat(){
        return $this->_format;
    }

    /**
     * Configura o tipo da tree
     *
     * @param String $link
     */
    public function setType($type = 'checkbox'){
        $this->_type = strtolower($type);
    }

    /**
     * Retorna o tipo da tree
     *
     * @return string
     */
    public function getType(){
        return $this->_type;
    }

    /**
     * Retorna javascript do modo de carregar dinâmicamente a tree
     *
     * @return string
     */
    public function getFormatScript(){
        $output = '';
        switch ($this->_format) {
            case 'xml':
                break;
            default:
                $output .= '    ' . $this->_name . '_treeDhtmlX.setDataMode("json");' . "\n";
                break;
        }
        return $output;
    }
}
