Shuping,
Thanks for the new code. The legend is now working with my service, thanks. However, when the map loads only two layers are visible on the map and in the legend, yet all of the checkboxes in the TOC are checked. If I uncheck one of them it fires the functions and suddenly all the other layers appear all at once, both in the map and in the legend.
It's very close! Just this last bug and it'll will be perfect. Thanks for your help. Any ideas?