var myConnection;
var myRoom = null;
var hisRoom = null;

var myCameraStarted = true;

function startConnectionVideo(){
  Apideo.handleError = function(type, message){
    switch(type){
      case 'cameraMuted' :
        myCameraStarted = false;
        myRoom.sendEvent({}, 'closeStream');
        hideViewer('cameraDiv');
        break;
      default :
        openErrorForm('Error: '+type, message)
        break;
    }
  };
  myConnection = Apideo.connect("9080700161E258902A")
}


function startVideoChat(){
  myCameraStarted = true;

  $('privateChat.profileContainer').innerHTML = '<div id="playerDiv"></div><div id="cameraDiv"></div><input type="button" onclick="stopVideoChat();" value="Stop video chat" style="padding:5px; margin:5px;">';

  var myHandle = myLoginStatus.idUser;

  closeCams();
  showViewer('cameraDiv');
  showViewer('playerDiv');

  myRoom = myConnection.joinRoom(myHandle+' - '+openedChat);
  myRoom.startCamera("cameraDiv","mystream", {width:215, height:138});
  myRoom.onUserJoin = function (){
    if(!myCameraStarted){
      myRoom.sendEvent({}, 'closeStream');
    }
  };
  myRoom.onCameraStarted = function (){
    if(myCameraStarted){
      myRoom.sendEvent({}, 'openStream');
    }
  };

  hisRoom = myConnection.joinRoom(openedChat+' - '+myHandle);
  hisRoom.onUserQuit = function(){
    hideViewer('playerDiv');
  }
  hisRoom.playStream("playerDiv","mystream", {width:215, height:138});
  hisRoom.registerListener(function (){
    hideViewer('playerDiv');
  }, 'closeStream');
  hisRoom.registerListener(function (){
    showViewer('playerDiv');
  }, 'openStream');
}

function hideViewer(viewer){
  $(viewer).style.height = '1px';
  $(viewer).style.overflow = 'hidden';
}

function showViewer(viewer){
  $(viewer).style.height = '138px';
  $(viewer).style.overflow = 'hidden';
}

function closeCams(){
  closeCam('myRoom');
  closeCam('hisRoom');
  $('cameraDiv').style.height = '138px';
  $('playerDiv').style.height = '138px';
}

function closeCam(myCam){
  if(myCam=='myRoom'){
    if(myRoom!=null)myConnection.quitRoom(myRoom);
    myRoom = null;
  } else {
    if(hisRoom!=null)myConnection.quitRoom(hisRoom);
    hisRoom = null;
  }
}

function stopVideoChat(){
  closeCams();
  displaySmallProfile(getTheUser(openedChat));
//  $('videoForm').style.display = 'none';
}
