Switch between a call and an announcement

We accept an incoming call, play an announcement, and call a number. The user can press 1 to listen to that announcement press 2 to talk to the called number. This can go on forever, 1,2,1,2,1,2, switching back and forth.


var agentConnected = false;
var incomingCallId = x.answer();
listenForDigit();   //Wait for the caller to enter a digit
x.say("15");        //Play an announcement
var outgoingCallId = x.call("3614446028", {    //Call another user
  onAnswer: function() {
      agentConnected = true;
      x.log("Called just picked up");
    }
});

//Depending on the digit, if 1 play announcement, if 2 connect to the outgoing call we made
function switchMe(digit) {
    if (digit=="1") {
      x.say("15");
    } else if (digit =="2" && agentConnected == true ) {
      x.join([incomingCallId,outgoingCallId]);
    } else {
      x.log("digit: " + digit + " Doing NOTHING");
    }
    listenForDigit();  //Wait for a new digit
}

function listenForDigit() {
 x.listen({
   callId: incomingCallId,
   onChoice: function(event) {
      x.log("caller entered digit: " + event.value );
      switchMe(event.value);
    }
 });
}