--
-- bookmark__toggle_open_close_all/3
--
create or replace function bookmark__toggle_open_close_all(
  p_browsing_user_id bigint,
  p_closed_p boolean,
  p_root_id integer
) returns int4 as $$

DECLARE
BEGIN
    -- Change the value of closed_p for all folders belonging to the
    -- user (except the root folder)
    UPDATE bm_in_closed_p SET closed_p = p_closed_p
    WHERE bookmark_id IN
    (
        SELECT bm.bookmark_id FROM bm_bookmarks bm, bm_bookmarks bm2
        WHERE tree_level(bm.tree_sortkey) > 1
          and bm2.bookmark_id = p_root_id
          and bm.tree_sortkey between bm2.tree_sortkey and tree_right(bm2.tree_sortkey)
    );

    -- Update the value of in_closed_p for all bookmarks belonging to
    -- this user. We close/open all bookmarks except the top level ones.
    UPDATE bm_in_closed_p SET in_closed_p = p_closed_p
    WHERE bookmark_id IN
    (
        SELECT bookmark_id FROM bm_bookmarks
        WHERE  tree_level(tree_sortkey) > 2
    )
    AND in_closed_p_id = p_browsing_user_id;

    RETURN 0;
END;
$$ language plpgsql;