-- `menu_click`, by Jacob Rus, September 2006
--
-- Accepts a list of form: `{"Finder", "View", "Arrange By", "Date"}`
-- Execute the specified menu item. In this case, assuming the Finder
-- is the active application, arranging the frontmost folder by date.

on menu_click(mList)
local appName, car, cdr

-- Validate our input
if mList's length < 3 then error "Menu list is not long enough"

-- Set these variables for clarity and brevity later on
set {appName, car} to (items 1 thru 2 of mList)
set cdr to (items 3 thru end of mList)

-- This overly-long line calls the menu_recurse function with
-- two arguments: cdr, and a reference to the top-level menu
tell app "System Events"
my menu_click_recurse(cdr, ((process appName)'s (menu bar 1)'s (menu bar item car)'s (menu car)))
end tell
end menu_click

on menu_click_recurse(mList, parentObject)
local car, cdr

-- `car` = first item, `cdr` = rest of items
set car to item 1 of mList
if mList's length > 1 then set cdr to (items 2 thru end of mList)

-- either actually click the menu item, or recurse again
tell app "System Events"
if mList's length is 1 then
click parentObject's menu item car
else
my menu_click_recurse(cdr, (parentObject's (menu item car)'s (menu car)))
end if
end tell
end menu_click_recurse

-- ====================================================================
-- END OF HELPER FUNCTIONS
-- ====================================================================


-- Example usage:
tell app "iTunes" to activate
menu_click({"iTunes", "View", "Visualizer", "iTunes Visualizer"})
menu_click({"iTunes", "View", "Turn On Visualizer"})
menu_click({"iTunes", "View", "Full Screen"})


-- ====================================================================
-- This following examples will show how amazingly much better this
-- function is than the way that Apple expects users to do things. ;)

tell app "TextEdit" to activate

-- My new way; 1 simple line:
menu_click({"TextEdit", "Edit", "Speech", "Start Speaking"})

-- The old way; 5 dense lines:
tell app "System Events"
tell ((process "TextEdit")'s (menu bar 1)'s (menu bar item "Edit")'s ¬
(menu "Edit")'s (menu item "Speech")'s (menu "Speech")) to ¬
click menu item "Stop Speaking"
end tell

-- Or Apple's way on apple.com; 15 ridiculous lines:
tell app "System Events"
tell process "TextEdit"
tell menu bar 1
tell menu bar item "Edit"
tell menu "Edit"
tell menu item "Speech"
tell menu "Speech"
click menu item "Start Speaking"
end tell
end tell
end tell
end tell
end tell
end tell
end tell