Toggle the first two languages in SysPrefs-Int'l (Leopard-ready)


(*ChangeLanguage toggles the first two languages in System Preferences >I nternational

The script has to distinguish between Tiger and Leopard,
because Apple has changed the property list format in Leopard.

In Leopard also the chinese languages (zh-Hans, zh-Hant) will be considered

The Finder will be restarted immediately. 
To apply the changes to running applications, quit and restart them 
*)
property rTab : return & tab

set systemVersion to (system attribute "sysv") mod 4096 div 16 -- filters the middle number of the system version
if systemVersion > 3 then
	quit application "Finder"
	set L to (do shell script "defaults read -g AppleLanguages") -- parameter -g = .GlobalPreferences = NSGlobalDomain
	if systemVersion = 5 then -- Leopard
		tell (words of L) to set {langList, cnt} to {it, count it}
		if langList contains "zh" then set {langList, cnt} to convertList(langList) -- convert list if chinese languages are installed
		if cnt < 2 then return
		set L2 to {}
		set end of L2 to rTab & item 2 of langList
		set end of L2 to rTab & item 1 of langList
		if cnt > 2 then
			repeat with i from 3 to cnt
				set end of L2 to rTab & item i of langList
			end repeat
		end if
		set {TID, text item delimiters} to {text item delimiters, ","}
		set L2 to ("(" & L2 as Unicode text) & return & ")"
		set text item delimiters to TID
	else if systemVersion = 4 then -- Tiger
		tell L to set L2 to text 1 & text 6 thru 7 & ", " & text 2 thru 3 & text 8 thru -1
	end if
	do shell script "defaults write -g AppleLanguages " & quoted form of L2
	delay 1
	launch application "Finder"
end if

-- "words" omits quotes and hyphens. In case of the chinese languages
-- the handler converts e.g.  {., zh, Hans,. } to {., "zh-Hans",. }
on convertList(theList)
	set i to 1
	set x to {}
	repeat while i < (count theList)
		if item i of theList is "zh" then
			set end of x to quote & item i of theList & "-" & item (i + 1) of theList & quote
			set i to i + 2
		else
			set end of x to item i of theList
			set i to i + 1
		end if
	end repeat
	return {x, count x}
end convertList