Finite State Machine (javascript)