Automate log-in


I am in desperate need of a script to help log in to a mail website. Currently I have to access a mail system through a web browser (safari or other) using a two-step log-in. On the first page I have to put in a username and then a password composed of a fixed code and a random string generated by a key-fob that I carry. I then hit return and am directed to a new page where I put in a username and fixed password, hit enter and then am directed to my in-box.

Unfortunately, the site logs me off after only a few minutes of inactivity, so I end up spending most of my time doing this incredibly cumbersome log-in routine all the time - sometimes even after reading only one email. I am told that there is no way to pull my emails down to my laptop using an email client with this system.

So, I would like to create a script which would
1. Open a browser window and navigate to login page 1
2. Enter predefined username in field 1
3. Enter predefined password string in field 2
4. Invite user to enter string to append to password in field 2
5. Select return
6. Wait for next page to appear
7. Enter predefined username string in field 1
8. Enter predefined password in field 2
9. Select (click) submit button

So far, I have the following script:

tell application "Safari"
do JavaScript "'')" in document 1
end tell
tell application "System Events"
tell process "SystemUIServer"
keystroke "myusername"
end tell
end tell

It does navigate to the site, but unfortunately it only sometimes will fill in the "username". I have not figured out why it only does this sometimes but not others. I am also not sure how to get it to hit "return" and navigate to the next page.

Any thoughts GREATLY appreciated.