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

goweb::loadClass('Zend_Json');
goweb::loadClass('Goweb_Js_TafelTree_Branch');

/**
 * Classe para gerar o javascript do tafeltree
 * baseado em TafelTree.class.php
 *
 * @version    5.0.0
 * @category   Goweb
 * @package    Goweb_Js
 * @subpackage TafelTree
 * @author     I&D <dev@goweb.pt>, Pedro Pinto <ppinto@goweb.pt>
 * @copyright  2009 (c) Goweb (http://www.goweb.pt)
 */
class Goweb_Js_TafelTree {

    /**
     * Identificação da Arvore
     *
     * @var string
     */
    protected  $_id;

    /**
     * Largura da Arvore
     *
     * @var string
     */
    protected $_width;

    /**
     * Altura da Arvore
     *
     * @var string
     */
    protected $_height;

    /**
     * Caminho para as imagens
     *
     * @var unknown_type
     */
    protected $_pathImgs;

    /**
     * Opções para carregar a arvore
     *
     * @var array
     */
    protected $_options;
    
    /**
     * Items da arvore
     *
     * @var array
     */
    protected  $_items = array();

    /**
     * Elementos da arvore
     *
     * @var array
     */
    protected  $_elements = array();
    
    /**
     * Numero máximo de niveis a abrir
     *
     * @var unknown_type
     */
    protected $_maxLevel = 0;

    /**
     * Contructor
     *
     * @param string $id Identificação da arvore
     * @param string $imgs caminho para as imagens
     * @param integer $width largura das imagens
     * @param integer $height altura das imagens
     * @param array $options opções da arvore
     */
    public function __construct($id, $imgs = 'imgs/', $width = '100%', $height = 'auto', $options = array()){
        if (is_numeric($id)) $id = 'tafel_' . $id;
        $this->_id = $id;
        $this->_pathImgs = $imgs;
        $this->_width = $width;
        $this->_height = $height;
        $this->_options = array();
        foreach ($options as $property => $value) {
            $this->_options[$property] = $value;
        }
    }

    /**
     * Enter description here...
     *
     * @param string $json a string JSON
     * @param string $imgs caminho para as imagens
     * @param integer $width largura das imagens
     * @param integer $height altura das imagens
     * @param array $options opções da arvore
     * @return TafelTree A arvore criada
     */
    public function loadJSON ($json, $id, $imgs = 'imgs/', $width = '100%', $height = 'auto', $options = array()) {
        $tree = new TafelTree($id, $imgs, $width, $height, $options);
        $service = new Zend_Json();
        $tree->items = TafelTree::loadServiceJSON($service->decode($json));
        return $tree;
    }

    /**
     * Load les infos depuis un objet Zend_Json
     *
     * @param 	Zend_Json	$service				L'objet Zend_Json
     * @return 	array									Les Goweb_Js_TafelTree_Branch cr��es
     */
    public function loadServiceJSON ($service) {
        $branches = array();
        foreach ($service as $branch) {
            $branches[] = Goweb_Js_TafelTree_Branch::loadServiceJSON($branch);
        }
        return $branches;
    }



    /**
     *------------------------------------------------------------------------------
     *							Fonctions getters et setters
     *------------------------------------------------------------------------------
     */

    protected function _getId() {
        return $this->_id;
    }
    protected function _getPathImgs() {
        return $this->_pathImgs;
    }
    protected function _getWidth() {
        return $this->_width;
    }
    protected function _getHeight() {
        return $this->_height;
    }


    /**
     *------------------------------------------------------------------------------
     *							Fonctions publiques
     *------------------------------------------------------------------------------
     */

    /**
     * Ajoute une branche comme enfant
     *
     * @param 	Goweb_Js_TafelTree_Branch		$branch				La branche � ajouter
     * @return 	void
     */
    public function add (Goweb_Js_TafelTree_Branch $branch) {
        $this->_items[] = $branch;
    }

    /**
     * Ajoute une sous-branche � l'arbre
     *
     * @param 	string			$id						L'id de la sous-branche
     * @param 	string			$txt					Le texte de la sous-branche
     * @param 	array			$options				Les informations compl�mentaires
     * @return 	Goweb_Js_TafelTree_Branch							La sous-branche
     */
    public function addBranch ($id, $txt, $options = array(), $level = 0) {
        $branch = new Goweb_Js_TafelTree_Branch ();
        $branch->setMaxLevel($this->_maxLevel);
        $branch->setId($id);
        $branch->setText($txt);
        if ($level > $this->_maxLevel && isset($options['open'])) unset($options['open']);
        foreach ($options as $property => $value) {
            if ($property != 'items') {
                $branch->setParam($property, $value);
            }
        }
        if (isset($options['items'])) {
            foreach ($options['items'] as $opt) {
                $level++;
                $branch->addBranch(null, null, $opt, $level);
                $level--;
            }
        }
        $this->_items[] = $branch;
        return $branch;
    }

    /**
     * Affiche la m�thode d'initialisation de l'arbre
     *
     * @param 	integer			$debug					Mettre 1 ou 2 pour avoir un affichage plus lisible
     * @return 	string									La string de la m�thode JS d'initialisation
     */
    public function display ($debug = 0) {
        $d = "\n";
        if (count($this->_options) > 0) {
            $s = new Zend_Json();
            $options = ','.$s->encode($this->_options);
        }
        $str = '<script type="text/javascript">'.$d;
        $str .= '/* <![CDATA[ */'.$d;
        $str .= "var tree_".$this->_getId()." = null;".$d;
        $str .= "TafelTreeInit = function() {".$d;
        $str .= "tree_".$this->_getId()." = new TafelTree (".$d;
        $str .= "'".$this->_getId()."', ".$d;
        $str .= $this->getJSON().", ".$d;
        $str .= "'".$this->_getPathImgs()."', ".$d;
        $str .= "'".$this->_getWidth()."', ".$d;
        $str .= "'".$this->_getHeight()."'".$options;
        $str .= ");".$d;
        $str .= "};".$d;
        $str .= '/* ]]> */'.$d;
        $str .= '</script>'.$d;
        $str .= "<div id='".$this->_getId()."'></div>";
        return $str;
    }
    
    /**
     * Construir arvore
     *
     * @param Goweb_Tree $tree
     * @param Goweb_Js_TafelTree_Branch $branch
     */
    protected function _build($tree, $branch = null, $level = 0){
        $options = array();
        if ($level <= $this->_maxLevel) $options['open'] = true;
        if (is_null($branch)){
            $branch = $this->addBranch('r1', translate('Raiz'), $options, -1);
            $branch->setMaxLevel($this->_maxLevel);
        }
        if ($tree) {
            foreach ($tree as $node) {
                if ($level <= $this->_maxLevel){
                    $options['open'] = true;
                } else if (isset($options['open'])){
                    unset($options['open']);
                }
		$tmp = $branch->addBranch($node->id, $node->nome ? $node->nome : $node->titulo, $options, $level);
                $tmp->setMaxLevel($this->_maxLevel);
                if (count($node->childs) > 0) {
                    $level++;
                    $this->_build($node->childs, $tmp, $level);
                    $level--;
                }

            }
        }
    }
    
    /**
     * elementos da arvore
     *
     * @param Goweb_Tree $elements
     */
    public function setTreeElements($elements){
        $this->_elements = $elements;
        $this->_build($this->_elements);
        
    }

    /**
     * Affiche la structure JSON de l'arbre
     *
     * @return 	string									La structure JSON de l'arbre
     */
    public function getJSON () {
        $service = new Zend_Json();
        return $service->encode($this->_items);
    }
    
    /**
     * Configurar o nível máximo para abrir a arvore
     *
     * @param int $level
     */
    public function setMaxLevel($level = 1){
        $this->_maxLevel = $level;
    }
}
