$(function() {
  Evader.inCommandShell = false;

  window.OpenShell = function() {
    $.get('/shell/reader_html', function(html) {
      // IE won't let me insert the script just like that
      // so this is a workaround
      var $html = $('<div>' + html + '</div>');
      $html.filter('script').each(function() {
        $.globalEval(this.text || this.textContent || this.innerHTML || '');
      });

      $.colorbox({
        title: "Command Shell",
        html: $html.html(),
        onComplete: function() {
          Evader.inCommandShell = true;
        },
        onCleanup: function() {
          CloseShell();
          Evader.inCommandShell = false;
          setTimeout(function() {
            $('[value="LOG"]').click();            
          }, 1000);
        }
      });
    });
  };

  window.CloseShell = function(callback) {
    $.ajax({
      url: '/shell/close',
      success: function() {
        var $log = $('.log');
        if($log.length > 0) {
          var $log = $('.log');
          $log.append('<br/>Closing shell..<br/>');
          setTimeout(function() {
            $.get('/log?session_id=' + Evader.sessionId + '&random=' + new Date().getTime(), function(data) {
              $log.append(data);
            });            
          }, 1000);
        }

        if(callback) {
          callback();
        }
      }
    });      
    
    if(window.commandShellRefreshId != null) {
      clearInterval(window.commandShellRefreshId);
      window.commandShellRefreshId = null;
    }
  };

  $(document).keypress(function(e) {
    if(Evader.inCommandShell) {
      e.stopPropagation();
      e.preventDefault();

      var code = 0;

      if(e.keyCode === 0 && e.charCode === 0) {
        alert( "Keypress, both keyCode and charCode are 0 - internal error" );
      } else if(e.keyCode !== 0) {
        code = e.keyCode;
      } else {
        code = e.charCode;
      }
      
      if(code === 13) {
        $('.command_shell').append('<br>');
      }

      $.ajax({
        url: "/shell/write",
        data: "input=" + code + "&session_id=" + Evader.sessionId,
        dataType: "text",
        success: function(data) {
          if(data.length > 0) {
            $('.command_shell').append(data);
          }
        }
      });
    }
  });
});