You will need to take a look at some scripting tutorials for working with wireless. To answer the question left in the comment of Jim's answer: StackExchange Ubuntu had a solution.
Take this and modify it to copy the correct config file into the proper place based on if you are connected or not, then restart networking.
You will want to have your configs figured out, tested and working ahead of time, save them separately(One for adhoc, one for normal use), and then use the script to determine which one to use.
Bash would probably be my language of choice for this particular task.
Once you have your script working, you can run it on boot with a cron job, and you should be good to go.
Good luck! Share your code when you are done please!