<% if Rails.env == "test" || Rails.env == "development" %>
<script type='text/javascript'>
$(document).ready(function() {
  JK = JK || {};
  JK.websocket_gateway_uri = '<%= Rails.application.config.websocket_gateway_uri %>'.replace(/localhost/,location.hostname);
  if (!(window.jamClient)) { window.jamClient = new JK.FakeJamClient(); }

  // override the onOpen to manage login; do this before connect()
  JK.JamServer.onOpen = function() {
    JK.logger.log("<%=@prefix%> connection_state: onOpen:  logging in: "+'<%=params[:user]%> '+ ' <%=params[:password]%>');
    if ($.cookie("remember_token")) {
      JK.JamServer.rememberLogin();
    <% if params[:user] && params[:password] %>
    } else {
      JK.JamServer.send(JK.MessageFactory.login_with_user_pass('<%=params[:user]%>', '<%=params[:password]%>'));
    <% end %>
    }
  }
  // setup server and app
  JK.JamServer.connect();
  JK.app = JK.JamKazam();
  JK.app.initialize();
  // disable normal heartbeat as we need to test without
  JK.app.heartbeatActive = false;

  // cache of the music_session_id created in the test
  var music_session_id;

  // checks all participants of a music_session for one with our client_id
  function musicSessionContainsClientID(music_session) {
      var pp = music_session['participants'];
      for (ii=0; ii < pp.length; ii++) {
        if (JK.app.client_id == pp[ii]['client_id']) return true;
      }
      return false;
  }

  // checks to see if the music_session has been deleted, as it should be after expire duration delay  
  function isExpired() {
   // do a GET call and check for participant; confirm the participant is not there (based on client_id)
   $.ajax({
    type: 'GET',
    dataType: 'json',
    contentType: 'application/json',
    url: '/api/sessions/'+music_session_id,
    processData: false,
    success: function(music_session) {
      if (musicSessionContainsClientID(music_session)) {
        // FIXME:  report error; connection should be deleted
        JK.logger.log("<%=@prefix%> connection_state: isExpired:  ERROR:  connection NOT deleted");
      } else {
        JK.logger.log("<%=@prefix%> connection_state: isExpired:  SUCCESS:  connection deleted");
      }
    },
    error:function (xhr, ajaxOptions, thrownError){
      if(xhr.status==404) {
        JK.logger.log("<%=@prefix%> connection_state: isExpired:  SUCCESS:  404");
      }
    }
    });
  }

  // after waiting for the stale duration, is the connection still available?  if ok, run isExpire after delay
  function isStale() {
    // do a GET call and check for participant; confirm the participant is there (based on client_id)
   $.ajax({
    type: 'GET',
    dataType: 'json',
    contentType: 'application/json',
    url: '/api/sessions/'+music_session_id,
    processData: false,
    success: function(data) {
      if (musicSessionContainsClientID(data)) {
        JK.logger.log("<%=@prefix%> connection_state: isStale:  connection was found as expected");
        window.setTimeout(isExpired, 
          <%= (Rails.application.config.websocket_gateway_connect_time_expire + 1) * 1000 %>);
      } else {
        // FIXME:  report error; connection should not be deleted
        JK.logger.log("<%=@prefix%> connection_state: isStale:  ERROR:  connection was NOT FOUND");
      }
    },
    error:function (xhr, ajaxOptions, thrownError){
      if(xhr.status==404) {
	// FIXME:  report error
        JK.logger.log("<%=@prefix%> connection_state: isStale:  ERROR:  404");
      }
    }
   });
  }

  function createMusicSession() {
    var data = {
      client_id: JK.app.client_id,
      description: 'asdf',
      as_musician: true,
      legal_terms: true,
      genres: ['classical'],
      musician_access: true,
      fan_chat: true,
      fan_access: true,
      approval_required: true,
      tracks: [{instrument_id: 'electric guitar', sound: "mono"}]
    }
   JK.logger.log("<%=@prefix%> connection_state: createMusicSession: ...  ");
   $.ajax({
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    url: '/api/sessions/',
    data: JSON.stringify(data),
    processData: false,
    success: function(music_session) {
      music_session_id = music_session['id'];
      JK.logger.log("<%=@prefix%> connection_state: createMusicSession:  music_session_id = "+music_session_id);
      window.setTimeout(isStale, 
        <%= (Rails.application.config.websocket_gateway_connect_time_stale + 1) * 1000 %>);
    },
    error:function (xhr, ajaxOptions, thrownError){
      JK.logger.log("<%=@prefix%> connection_state: createMusicSession:  ERROR: "+thrownError);
    }
   });
  }

  function myLoggedIn(header, payload) {
    JK.logger.log("<%=@prefix%> connection_state: myLoggedIn:  "+payload.client_id);
    JK.app.client_id = payload.client_id;
    $.cookie('client_id', payload.client_id);
    JK.logger.log("<%=@prefix%> connection_state: cookie:  "+$.cookie('client_id'));
    $.cookie('remember_token', payload.token);
    createMusicSession();
  }
  JK.JamServer.registerMessageCallback(JK.MessageType.LOGIN_ACK, myLoggedIn);

});
</script>
<% end %> <!-- Rails.env=='test'||'dev' -->
