on run
	set the_result to display dialog "Status message" default answer "Away" with icon 1 buttons {"Cancel", "Set available", "Set away"} default button "Set away"
	set button_pressed to button returned of the_result
	set text_typed to text returned of the_result
	if button_pressed is "Set available" then set text_typed to "[::available::]" & text_typed
	if button_pressed is not "Cancel" then
		my update(text_typed)
	end if
end run

on update(status)
	if appIsRunning("Adium") then adium(status)
	if appIsRunning("Skype") then skype(status)
	if appIsRunning("iChat") then ichat(status)
	twitter(status)
	if appIsRunning("GrowlHelperApp") then my growl(status)
end update

on twitter(status)
	if status begins with "[::available::]" then set status to my trimStatus(status)
	tell application "FCSApplescriptAdditions"
		activate
		post to url "http://twitter.com/statuses/update.xml" parameters {status:status}
		quit
	end tell
end twitter

on adium(status_message)
	tell application "Adium"
		if status_message begins with "[::available::]" then
			set my status type to available
			set status_message to my trimStatus(status_message)
		else
			set my status type to away
		end if
		set my status message to status_message
	end tell
end adium

on skype(status)
	tell application "Skype"
		if status begins with "[::available::]" then
			send command "SET USERSTATUS ONLINE" script name "Status (script)"
		else
			send command "SET USERSTATUS AWAY" script name "Status (script)"
		end if
	end tell
end skype

on ichat(status_message)
	if status_message begins with "[::available::]" then
		set status to available
		set status_message to my trimStatus(status_message)
	else
		set status to away
	end if
	tell application "iChat"
		set status message to status_message
	end tell
end ichat

on growl(status)
	tell application "GrowlHelperApp"
		register as application "Status (script)" all notifications {"ChangesMade"} default notifications {"ChangesMade"} icon of application "Script Editor"
		notify with name "ChangesMade" title "Status has been updated" description my trimStatus(status) application name "Status (script)"
	end tell
end growl

on appIsRunning(appName)
	tell application "System Events"
		return (name of every process) contains appName
	end tell
end appIsRunning

on trimStatus(status)
	if status does not contain "]" then return status
	set l to {}
	repeat with c in status
		if c as string is "]" then exit repeat
		set l to l & c
	end repeat
	return characters ((length of l) + 2) thru (length of status) of status as string
end trimStatus