/** We stick the script here */
var mainDiv;
var mainImage;
var host = 'localhost';

/**
 * Sends a message to the local server
 *
 * @param cmd       the command to send
 * @param callback  the function in which the results go
 *                  of the form String -> Void
 * @param args      arguments to send
 */     
function sendMsg(cmd,callback,args) {
  // Maybe add the div if it doesn't exist
	if (!mainDiv) {
		mainDiv = document.getElementById("mainJS");
	}
	
	// Make the call to the local server
	var script = document.createElement("script");
  var url = constructUrl(cmd,callback,args);
	script.setAttribute('src', url);
  script.setAttribute('type', 'text/javascript');
  mainDiv.appendChild(script);
}

/**
 * Sends a message to the local server with Javascript callback.
 *
 * @param cmd       the command to send
 * @param callback  the function in which the results go
 *                  of the form String -> Void
 * @param args      arguments to send
 */     
function sendImgMsg(cmd,callback,args) {
  var img = document.createElement("img");
  document.body.appendChild(img);
  var url = constructUrl(cmd,null,args);
  img.onload = callback;
  img.onerror = function() {alert("error");};
  img.src = url;
}

function constructUrl(cmd,callback,args) {
  var port = 4444;
	var url = 'http://' + host + ':' + port + '/' + cmd;
	url += url.match(/\?/) ? '&' : '?';

  // Tell the server how to send back the results
  if (!callback) callback = "_null";
	url += 'callback=' + escape(callback);

  // Add the arguments
  if (args) {
    for (var n in args) {
      url += '&' + n + '=' + escape(args[n]);
    }
  }

  // 'Force' a reload of the script
	url += '&_f=' + Math.random();
  return url;
}

function setHost(h) {
  host = h;
}

/**
 * Short cut to create a new node -- really shouldn't be in this file.
 */
function $n(tag,on) {
	var e = document.createElement(tag);
	if (on) on.appendChild(e);
	return e;
}

function now() {
  var currentTime = new Date()
    var hours = currentTime.getHours()
    var minutes = currentTime.getMinutes()
    if (minutes < 10){
      minutes = "0" + minutes
    }
  s = "";
  s += hours + ":" + minutes + " ";
  if (hours > 11) {
    s += "PM";
  } else {
    s += "AM";
  }
  return s;
}

function _null(res) {}

