Improved logic for selecting the active tab