Dynamic Optimization of Complementarity Systems