JavaScript Finite State Machine