<?php defined('SYSPATH') or die('No direct access allowed.');

/**
 * This class extends renders OSB menu tree.
 *
 * @package    lnApp
 * @category   lnApp/Controllers
 * @author     Deon George
 * @copyright  (c) 2009-2013 Deon George
 * @license    http://dev.leenooks.net/license.html
 */
class lnApp_Controller_Tree extends Controller_Default {
	/**
	 * @var string page media route as per [Route]
	 */
	protected static $jsmediaroute = 'default/media';

	public function after() {
		$this->response->headers('Content-Type','application/json');
		$this->response->body(json_encode($this->output));

		parent::after();
	}

	public static function js() {
		$mediapath = Route::get(static::$jsmediaroute);

		return '
<div id="tree" class=""></div>
<script type="text/javascript">
<!--
$(function () {
	var use_ajax = false;

	$("#tree").jstree({
		themes : {
			"theme" : "classic",
		},
		ui : {
			"select_limit" : 1,
			"select_node" : false,
		},
		cookies : {
			"save_selected" : false,
			"cookie_options" : { path : "'.URL::site().'" }
		},
		json_data : {
			"correct_state" : "true",
			"progressive_render" : "true",
			"ajax" : {
				"url" : "'.URL::site('tree/json').'",
				"data" : function (n) {
					return { id : n.attr ? n.attr("id") : "N_"+0 };
				}
			}
		},
		plugins : [ "themes", "json_data", "ui", "cookies" ],
	});

	// On selection
	$("#tree").bind("select_node.jstree", function (e, data) {
		if (a = data.rslt.obj.attr(\'id\').indexOf(\'_\')) {
			id = data.rslt.obj.attr(\'id\').substr(a+1);

			if (href = $("#N_"+id).attr("href")) {
				if (! use_ajax) {
					window.location = href;
					return;
				}

				$("#ajBODY").empty().html("<img src=\"'.URL::site('media/img/ajax-progress.gif').'\" alt=\"Loading...\" />");
				$("#ajBODY").load(href, function(r,s,x) {
					if (s == "error") {
						var msg = "Sorry but there was an error: ";
						$("#ajBODY").html(msg + x.status + " " + x.statusText + r);
					}
				});
			} else
				alert("Unknown: "+id+" HREF:"+href);
		}
	});
});
// -->
</script>';
	}

	/**
	 * Draw the Tree Menu
	 *
	 * The incoming ID is either a Branch B_x or a Node N_x
	 * Where X is actually the module.
	 *
	 * @param array $data Tree data passed in by inherited methods
	 */
	public function action_json(array $data=array()) {
		if ($this->_auth_required() AND ! Auth::instance()->logged_in()) {
			$this->output = array('attr'=>array('id'=>'a_login'),
				'data'=>array('title'=>_('Please Login').'...','attr'=>array('id'=>'N_login','href'=>URL::site('login'))));

			return;
		}

		$this->output = array();

		foreach ($data as $branch) {
			array_push($this->output,array(
				'attr'=>array('id'=>sprintf('B_%s',$branch['id'])),
				'state'=>$branch['state'],
				'data'=>array('title'=>$branch['name']),
				'attr'=>array('id'=>sprintf('N_%s',$branch['id']),'href'=>empty($branch['attr_href']) ? URL::link('user',$branch['name'].'/menu',TRUE) : $branch['attr_href']),
				)
			);
		}
	}
}
?>
