<?php

  #
  # Reddy walker is fully customizeable walker for wp_nav_menu
  #

  #
  # Available args keys (% is depth level):
  #  * ul-class-%
  #  * li-class-%
  #  * a-class-%
  #
  #  * ul-style-%
  #  * li-style-%
  #  * a-style-%
  #
  #  * href-%  - render the href on a li which has children
  #  * arrow-% - the arrow (text) for li which has children
  #
  #  * li-class-active-% - for active li's
  #  * li-style-active-% - for active a's
  #  * a-class-active-% - for active li's
  #  * a-style-active-% - for active a's
  #

  function render_attrs($attrs) {
    $res = ' ';
    foreach($attrs as $key => $value)
      $res .= ' ' . $key . '="' . $value . '"';
    return $res . ' ';
  }

  class Reddy_Walker extends Walker_Nav_Menu {

    public function __construct($params = array()) {
      $this->params = $params;
    }

    public function start_lvl( &$output, $depth = 0, $args = array() ) {
      $output .= '<ul' . render_attrs( $this->params['ul-attrs-' . $depth] ) . '>';
    }

    public function end_lvl( &$output, $depth = 0, $args = array() ) {
      $output .= '</ul>';
    }

    public function end_el( &$output, $item, $depth = 0, $args = array() ) {
      $output .= '</li>';
    }

    # Start element draw
    public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {

      if ( is_array($args) ) $args = (object) $args;

      $classes = empty( $item->classes ) ? array() : (array) $item->classes;
      $active = ( in_array( 'current-menu-item', $classes ) ) ? 'active-' : '';

      $a_text   = $item->post_title ? $item->post_title : $item->title;

      $a_href   = ( $args->has_children && $this->params['href-' . $depth] === false ) ? NULL : ($item->url ? $item->url : get_the_permalink( $item->ID ))  ;
      $a_arrow  = $args->has_children ? $this->params['arrow-' . $depth] : NULL;

      # Render itself
      $output .= '<li' . render_attrs( $this->params['li-attrs-' . $active .  $depth] ) . '>';

      $output .= '<a';
      $output .= render_attrs( $this->params['a-attrs-' . $active . $depth] );
      if ( $a_href )  $output .= '  href="' .  $a_href . '"';
      $output .= '>';
      if ( $a_text )  { $output .= $a_text; }
      $output .='</a>';
      
      if ( $a_arrow ) $output .= $a_arrow;
    }

    # Special wrap to retrieve has_children prop
    public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
      if ( ! $element ) return;
      $id_field = $this->db_fields['id'];
      if ( is_object( $args[0] ) ) $args[0]->has_children = ! empty( $children_elements[ $element->$id_field ] );
      parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
    }
  }
