<?php

class CrmMenu extends CHtml {

	private $_items = array();

	/**
	 * Default Constructor
	 *
	 * @param View $View The View this helper is being attached to.
	 * @param array $settings Configuration settings for the helper.
	 */
	public function __construct() {
		$this->_items = MenuUtil::items();
		// /parent::__construct();
	}

	public function menus() {
		return $this->_menus($this->_items);
	}
	private function _menus($menus, $options = array(), $depth = 0, $parent = false) {
		$options = Hash::merge(array(
			'children' => true,
			'htmlOptions' => array(
				
			),
		), $options);

		if($depth == 0) {
			$options['htmlOptions']['id'] = 'menu';
		}
		if($parent) {
			$options['htmlOptions']['id'] =  'submenu-' . $parent; 
			$options['htmlOptions']['style'] =  'display:block'; 
		}
		$out = null;
		foreach ($menus as $key => $menu) {
			$htmlOptions = $options['htmlOptions'];
			$linkOptions = (isset($linkOptions['linkOptions'])) ? $linkOptions['linkOptions'] : array();
			$liOptions = (isset($options['liOptions'])) ? $options['liOptions'] : array();

			if(!isset($linkOptions['class'])) {
				$linkOptions['class'] = '';
			}
			if(!isset($liOptions['class'])) {
				$liOptions['class'] = '';
			}
			$linkOptions['class'] .=  ' menu-nivel' . $depth;
			$liOptions['class'] .=  ' menu-nivel' . $depth;


			$title = $menu['title'];
			$children = '';
			if (!empty($menu['children'])) {
				$menu['children'] = Hash::sort($menu['children'], '{s}.title', 'ASC');
				$children = $this->_menus($menu['children'], array(
					'children' => true,
				), $depth + 1, $key);

				if(!$children) {
					continue;
				}
			} else {
				$linkOptions['class'] .=  ' no-children';
				$liOptions['class'] .=  ' no-children';
			}
			$link = null;
			$image = '';
			if(isset($menu['icon'])) {
				$iconOptions = array();
				if(isset($menu['icon']['width'])) {
					$iconOptions['width'] = $menu['icon']['width'];
				}
				if(isset($menu['icon']['height'])) {
					$iconOptions['height'] = $menu['icon']['height'];
				}
				$image = CHtml::image(FaHtml::getImgUrl($menu['icon']['icon']),'' ,$iconOptions);
			}
			if($menu['url'] == '#') {
				$linkOptions['onClick'] = "showHide('submenu-".$key."')";
				$image = CHtml::image(FaHtml::getImgUrl('ico-menu-down.png'), '' ,array('height'=>13));
				$link = CHtml::link($menu['title'],'javascript:void(0);', $linkOptions);
			} else {

				if(!isset($menu['target'])) {
					$linkOptions['target'] = 'workFrame';
				} else {
					$linkOptions['target'] = $menu['target'];
				}
				$link = CHtml::link($menu['title'],array($menu['url']), $linkOptions);
			}
			$out .= CHtml::openTag('li', $liOptions) . $image.$link . $children . CHtml::closeTag('li');
		}
		if($out == null) {
			return null;
		}
		return CHtml::openTag('ul', $htmlOptions) . $out . CHtml::closeTag('ul');
	}

}