-- Script that gets the content of window 1 of LaTeXiT 
-- and inserts it at the  beginning of the current selection 
-- of the front document in TeXShop. 
-- If there is no open document in TeXShop 
-- it asks if you want to create one.
-- Ramon Figueroa-Centeno (April 3, 2009)
-- http://www2.hawaii.edu/~ramonf

activate application "LaTeXiT"
tell application "System Events"
	get system attribute "sysv"
	if result is greater than or equal to 4144 then -- Mac OS X 10.3.0
		if UI elements enabled then
			tell application "TeXShop"
				try -- to get the front document of TeXShop
					set front_document to the front document
				on error
					beep
					tell application "System Events"
						activate
						set myButton to button returned of (display dialog "No open document in TeXShop!" & return & "Do you want to create a new one?" buttons {"Yes", "No"} default button 2)
					end tell
					tell application "LaTeXiT" to activate
					if myButton is "No" then
						
						return
					else
						try
							make new document
							set front_document to the front document
						on error
							return
						end try
					end if
				end try
			end tell
			tell application process "LaTeXiT"
				-- insert GUI Scripting statements here
				
				try
					set LaTeXiTwindow to the value of attribute "AXMainWindow"
					set the equation to the value of text area 1 of scroll area 2 of splitter group 1 of group 1 of LaTeXiTwindow
				on error
					beep
					return
				end try
				
				
				-- Check to see if the LaTeXiT window is not empty
				if the equation as string is not "" then
					tell application "TeXShop"
						try
							-- Comment if you do not want to replace the TeXShop selection:
							--set length of the selection of the front_document to 0
							set content of the selection of the front_document to the equation
						on error
							return
						end try
						activate
					end tell
				end if
			end tell
		else
			beep
			activate
			display dialog "GUI Scripting is not enabled" & return & return & "Open System Preferences and check Enable Access for Assistive Devices in the Universal Access preference pane, then run this script again." with icon stop
			if button returned of result is "OK" then
				tell application "System Preferences"
					activate
					set current pane to pane "com.apple.preference.universalaccess"
				end tell
			end if
		end if
	else
		beep
		activate
		display dialog "This computer cannot run this script" & return & return & "The script uses GUI Scripting technology, which requires an upgrade to Mac OS X 10.3 Panther or newer." with icon caution buttons {"Quit"} default button "Quit"
	end if
end tell