var pollingTimerID;
var inputCommand;
var iframeDocBodyPreNode;
var iframeDoc;

function initCommandShell() {
  startPollingTimer();
  iframeDoc = window.frames.shellOutputFrame.document;
  if (iframeDoc)
  {
    iframeDoc.body.style.fontFamily = "monospace";

    var tagPre = iframeDoc.createElement('pre');
    if (tagPre)
    {
      iframeDocBodyPreNode = iframeDoc.body.appendChild(tagPre);
    }
  }
  printResult('Help:\n');
  printResult('Type OS command in the text box above and click [Send]\n');
  printResult('To resize output area resize the browser window and click CommandShell again\n');
  printResult('Use !c to clean this box\n');
  resizeTextAreas();
};

function getWindowWidth()
{
    var scrW = self.screen.width;
    var scrH = self.screen.height;
    
    if (self.innerWidth)
    {
      scrW = self.innerWidth;
      scrH = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientWidth)
    {
      scrW = document.documentElement.clientWidth;
      scrH = document.documentElement.clientHeight;
    }
    else if (document.body)
    {
      scrW = document.body.clientWidth;
      scrH = document.body.clientHeight;
    }

    return scrW;
}

function getWindowHeight()
{
    var scrH = self.screen.height;
    
    if (self.innerWidth)
    {
      scrH = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight)
    {
      scrH = document.documentElement.clientHeight;
    }
    else if (document.body)
    {
      scrH = document.body.clientHeight;
    }

    return scrH;
}

function resizeTextAreas()
{
  var commandShellURL = document.getElementById("commandShellURL");
  if (commandShellURL)
  {
    var scrW = getWindowWidth();
    var scrH = getWindowHeight();
    commandShellURL.href='?u='+userHashKey+'?commandshell:sw='+scrW+':sh='+scrH+":";
  }
}

function sendCommand() {
  
  do
  {
    inputCommand = document.getElementById("shellCommandInput");
    if (!inputCommand)
    {
       break;
    }
    if (!inputCommand.value)
    {
       break;
    }
    var command = inputCommand.value;
    if (!command)
    {
       break;
    }
	 if (command.length <= 0)
	 {
		 break;
	 }
	 var isTerminalCommand = executeTerminalCommand(command);
	 if (isTerminalCommand)
	 {
		 break;
	 }
    var url = '?u='+userHashKey+'?command='+command+"\n";
    // send HTTP request to the daemon
    makeHttpRequest(url, false);
  }
  while (false);
};

function executeTerminalCommand(command)
{
	var result = false;
	do
	{
		if (command.charAt(0) != '!')
		  break;
		
		if (command == '!c')
		{
			result = true;
         var iframeDoc = window.frames.shellOutputFrame.document;
         if (!iframeDoc)
         {
           break;
         }
			iframeDoc.body.innerHTML = '';
		}
	}
	while (false);
	return result;
}

function startPollingTimer() {
   pollServer();
   return 1;
};

function pollServer() {
  var url = '?u='+userHashKey+'?update';
  makeHttpRequest(url, true);
};

function makeHttpRequest(url, startTimer)  {
   var http_request = false;
   if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        if (http_request.overrideMimeType) {
            http_request.overrideMimeType('text/xml');
        }
    } 
    else if (window.ActiveXObject) { // IE
        try {
             http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } 
            catch (e) {printWarning("failed to issue HTTP request");}
         }
    }

    if (!http_request) {
         printWarning('Browser doesn\'t support HTTPRequest feature.');
         return false;
     }

     http_request.onreadystatechange = function() 
     {
          if (http_request.readyState == 4) 
          {
             if (http_request.status == 200) 
             {
                if (startTimer)
                {
                   printResult(http_request.responseText);
                }
             }
             else 
             {
                printWarning('There was a problem with the request.(Code: ' + http_request.status + ')');
             }
             if (startTimer)
             {
               pollingTimerID = setTimeout("pollServer()", 2000);
             }
           }
     }
     try 
     {
       http_request.open('GET', url, true);
     }
     catch (e)
     {
       printWarning('Failed to open httpRequest');
     }
     try 
     {
       http_request.send(null);
     }
     catch (e)
     {
       printWarning('Failed to send htt request');
     }
};

function printWarning(message) {
   printResult('JS: '+message+'\n');
   return true;
};

function printResult(result_string)  {
  do
  {
    if (!result_string) 
    {
      break;
    }
    var stringLength = result_string.length; 
    if (stringLength <= 0) 
    {
      break;
    }
    
    if (!iframeDocBodyPreNode)
    {
       break;
    }
    // excellent i know where to print and i know what to print
     

    var textNode = iframeDoc.createTextNode(result_string);
    if (!textNode)
    {
       break;
    }

    iframeDocBodyPreNode.appendChild(textNode);
    window.frames.shellOutputFrame.scrollBy(0, stringLength*400);
  }
  while (false);

  return true;
};
   

