global myList

tell application "Pages"
	activate
	tell the front document
		set myList to {}
		repeat with aPage in pages
			repeat with aItem in body text of aPage
				set fieldString to aItem as text
				my searchAndAddTokenString(fieldString)
			end repeat
		end repeat
		
		my searchTables(tables)
		my searchShapes(shapes)
		my searchTextItems(text items)
		
		repeat with aGroup in my flattenedGroups(groups)
			my searchTables((tables of aGroup))
			my searchShapes((shapes of aGroup))
			my searchTextItems((text items of aGroup))
		end repeat
		
	end tell
	
	return myList
end tell

on searchTables(someTables)
	tell application "Pages"
		repeat with aTable in someTables
			tell aTable
				repeat with aCell in cells
					my searchAndAddTokenString(value of aCell as text)
				end repeat
			end tell
		end repeat
	end tell
end searchTables

on searchShapes(someShapes)
	tell application "Pages"
		repeat with aShape in someShapes
			repeat with aItem in object text of aShape
				my searchAndAddTokenString(aItem as text)
			end repeat
		end repeat
	end tell
end searchShapes

on searchTextItems(someTextItems)
	tell application "Pages"
		repeat with aTextItem in someTextItems
			repeat with aItem in object text of aTextItem
				my searchAndAddTokenString(aItem as text)
			end repeat
		end repeat
	end tell
end searchTextItems

on flattenedGroups(someGroups)
	local groupList
	set groupList to {}
	tell application "Pages"
		repeat with aGroup in someGroups
			if (count of aGroup) > 0 then
				repeat with bGroup in my flattenedGroups((groups in aGroup))
					copy bGroup to the end of groupList
				end repeat
			end if
			copy aGroup to the end of groupList
		end repeat
	end tell
	return groupList
end flattenedGroups

on searchAndAddTokenString(fieldString)
	if fieldString contains "<$" then
		(*We found an occurance*)
		set y to length of fieldString
		set x to 1
		repeat until x is y
			set tokenString to ""
			set nextCharacter to x + 1
			if character x of fieldString contains "<" and character nextCharacter of fieldString contains "$" then
				(*We found the start*)
				repeat until character x of fieldString contains "$" and character nextCharacter of fieldString contains ">"
					set tokenString to tokenString & character x of fieldString
					set x to x + 1
					set nextCharacter to x + 1
					set tokenString to my replace_chars(tokenString, "<$", "")
				end repeat
				if length of tokenString > 0 then
					copy tokenString to the end of myList
				end if
			end if
			set x to x + 1
		end repeat
	end if
end searchAndAddTokenString

on replace_chars(this_text, search_string, replacement_string)
	set AppleScript's text item delimiters to the search_string
	set the item_list to every text item of this_text
	set AppleScript's text item delimiters to the replacement_string
	set this_text to the item_list as string
	set AppleScript's text item delimiters to ""
	return this_text
end replace_chars