Trigger Script When App Opens?

What’s the best way to trigger a script based on the status of an application?

I’d like to run a script when an app opens, when it quits, when it’s in front, when it’s not in front… you get the idea.

As usual, I’m over my head and any hints would be most welcome.

Thanks,
Bryan