function get_nested_categories($default = 0, $parent = 0) {
 global $post_ID, $mode, $wpdb;

 if ($post_ID) {
   $checked_categories = $wpdb->get_col("
     SELECT category_id
     FROM $wpdb->categories, $wpdb->post2cat
     WHERE $wpdb->post2cat.category_id = cat_ID AND $wpdb->post2cat.post_id = '$post_ID'
     ");

   if(count($checked_categories) == 0)
   {
     // No selected categories, strange
     $checked_categories[] = $default;
   }

 } else {
   $checked_categories[] = $default;
 }

 $cats = return_categories_list($parent, TRUE);
 $result = array();

 foreach($cats as $cat)
 {
   $result[$cat]['children'] = get_nested_categories($default, $cat);
   $result[$cat]['cat_ID'] = $cat;
   $result[$cat]['checked'] = in_array($cat, $checked_categories);
   $result[$cat]['cat_name'] = get_the_category_by_ID($cat);
 }

 return $result;
}
function get_nested_categories($default = 0, $parent = 0)
{
    global $post_ID, $mode, $wpdb;
    if ($post_ID) {
        $checked_categories = $wpdb->get_col("\n\t\t     SELECT category_id\n\t\t     FROM {$wpdb->categories}, {$wpdb->post2cat}\n\t\t     WHERE {$wpdb->post2cat}.category_id = cat_ID AND {$wpdb->post2cat}.post_id = '{$post_ID}'\n\t\t     ");
        if (count($checked_categories) == 0) {
            // No selected categories, strange
            $checked_categories[] = $default;
        }
    } else {
        $checked_categories[] = $default;
    }
    $cats = return_categories_list($parent);
    $result = array();
    if (is_array($cats)) {
        foreach ($cats as $cat) {
            $result[$cat]['children'] = get_nested_categories($default, $cat);
            $result[$cat]['cat_ID'] = $cat;
            $result[$cat]['checked'] = in_array($cat, $checked_categories);
            $result[$cat]['cat_name'] = get_the_category_by_ID($cat);
        }
    }
    usort($result, 'sort_cats');
    return $result;
}