-- Campfire Beep.app
-- by Manton Reece
-- http://www.manton.org/2006/02/campfire_beep.html
-- last updated Feb 20, 2006

-- simple global to keep track of the HTML for the chat messages
-- it's a list of records that look like: {href:"http://you.campfirenow.com/room/123", html:"abcdef"}
global saved_source_list
set saved_source_list to {}

on idle
   
   try
      
      -- get frontmost app
      -- we'll use this to not beep if Safari is in the front, because it can be annoying while chatting
      tell application "System Events" to set front_list to name of every process whose frontmost is true and visible is not equal to false
      
      tell application "Safari"
         repeat with d in documents
            set the_url to URL of d as string
            if the_url contains "campfirenow.com/room/" then
               
               -- we can't get the full page source via Apple Events because the contents are updated via Ajax
               -- this little JavaScript will only retrieve the HTML from the chat messages table
               set js to "return document.getElementById('chat').innerHTML"
               set new_source to do JavaScript js in d
               
               -- try to find the page in our HTML source cache list
               set found_page to false
               repeat with info in saved_source_list
                  if href of info is equal to the_url then
                     set found_page to true
                     if new_source is not equal to html of info then
                        if item 1 of front_list is not equal to "Safari" then
                           beep
                        end if
                     end if
                     set html of info to new_source
                  end if
               end repeat
               
               -- if wasn't already cached, add it to end of list
               if not found_page then
                  set new_info to {href:the_url, html:new_source}
                  set saved_source_list to saved_source_list & {new_info}
               end if
            end if
         end repeat
         
      end tell
      
   on error error_text
      -- could enable this for debugging
      -- the error is probably hardmless and we don't want to be bothered
      --display dialog error_text
   end try
   
   -- try again in 2 seconds
   return 2
end idle