<?php

$item_list = top_menu_process(cw_top_menu_make_sql_query());
$smarty->assign('top_menu', $item_list);
function top_menu_process($r, $pid = '0', $lev = 1, $path_to = '')
{
    $r2 = array();
    foreach ($r as $v) {
        if ($v['pmid'] == $pid) {
            $r2[] = $v;
        }
    }
    if (empty($r2)) {
        return array();
    }
    foreach ($r2 as $v) {
        extract($v);
        $title_orig = $title;
        if ($title2 != '') {
            $title = $title2;
        }
        $children = '';
        if ($type == 'ucat') {
            $link = link2url($link);
        }
        if (preg_match("'^[a-z]*\\://.*'i", $link)) {
            $target = " target=\"_blank\"";
        } else {
            $target = "";
        }
        $subitems = top_menu_process($r, $mid, $lev + 1, "{$path_to}{$title} &#187;");
        if (APP_AREA == 'customer' && $pid == '0' && empty($subitems) && $pcount > 0) {
            $subitems['pseudo'] = array('title' => "{$pcount} " . cw_get_langvar_by_name('prod_fnd_ins') . " {$title} &#187;", 'link' => $link, 'subitems' => array());
        }
        $pcount += $subitems['tcount'];
        unset($subitems['tcount']);
        $children .= "\t" . $subitems['allchildren'];
        unset($subitems['allchildren']);
        $children = preg_replace("'\t+'", ",", trim($children));
        if (APP_AREA == 'customer') {
            $items[$mid] = compact('title', 'link', 'subitems', 'pcount', 'target', 'type', 'lev');
        } else {
            $items[$mid] = compact('pmid', 'lev', 'title', 'link', 'title_orig', 'subitems', 'path_to', 'pcount', 'active', 'pos', 'children', 'type');
        }
        if ($pid != '0') {
            if (!isset($items['tcount'])) {
                $items['tcount'] = $pcount;
            } else {
                $items['tcount'] += $pcount;
            }
        }
        if ($pid != '0') {
            if (!isset($items['allchildren'])) {
                $items['allchildren'] = "{$children}\t{$mid}";
            } else {
                $items['allchildren'] .= "\t{$children}\t{$mid}";
            }
        }
    }
    return $items;
}