Javascript Finite State Machine