automatically calculate contrast

A user can change the default design of his site by selecting a color. This color is applied to the menu background color. The problem is that I have to change the menu text color depending on the selected color (eg if the user choose darkgreen then teh text color needs to be white).

I only want to use or white or black as a text color for the menu and want to know how I can calculate whether white or black results in best readability.

Update

The website is aimed at soccerteams. Since soccerteams often have specific colors I want to give them the option to add teamcolors to the site. templates won't do because I can't provide all the colors with templates. I also opt not to give them the option to define the text color since I think this is a physics problem (contrast)