/**
 * @author diccon
 */
function JSONSocketObject(httpRoot){
	
	this.httpRoot = httpRoot;
	
	this.jsonObjects = new Object();
	this.callbacks = new Object();
	
	
	this.makeCall = function(name,action,data,callback){
		
		var url = this.httpRoot+directoryIndex+"?action="+action;
		
		if(data != null){
			url += "&data="+urlEncode(this.serialize(data));
		}
		
		if(callback != null){
			url += "&callback="+this.registerCallback(name,callback);
		
		}
		
		//alert(url);
		
		if(this.jsonObjects[name] != null){
			this.jsonObjects[name].removeScriptTag();
		}
		
		this.jsonObjects[name] = new JSONscriptRequest(url); 
		// Build the dynamic script tag
		this.jsonObjects[name].buildScriptTag(); 
		// Add the script tag to the page
		this.jsonObjects[name].addScriptTag(); 
	}
	
	this.registerCallback = function(name,func){
		this.callbacks[name] = func;
		return "JSONSocket.callbacks['"+name+"']";
	}
	
	// Javascript serialize - thanks http://blog.stchur.com/2007/04/06/serializing-objects-in-javascript/

	this.serialize = function(_obj){
		
		if(_obj == null){
			return null;
		}
	   // Let Gecko browsers do this the easy way
	   if (typeof _obj.toSource !== 'undefined' && typeof _obj.callee === 'undefined'){
	      return _obj.toSource();
	   }
	
	   // Other browsers must do it the hard way
	   switch (typeof _obj){
	      // numbers, booleans, and functions are trivial:
	      // just return the object itself since its default .toString()
	      // gives us exactly what we want
	      case 'number':
	      case 'boolean':
	      case 'function':
	         return _obj;
	         break;
	
	      // for JSON format, strings need to be wrapped in quotes
	      case 'string':
	         return '\'' + _obj + '\'';
	         break;
	
	      case 'object':
	         var str;
	         if (_obj.constructor === Array || typeof _obj.callee !== 'undefined'){
	            str = '[';
	            var i, len = _obj.length;
	            for (i = 0; i < len-1; i++) { str += this.serialize(_obj[i]) + ','; }
	            str += this.serialize(_obj[i]) + ']';
	         } else {
	            str = '{';
	            var key;
	            for (key in _obj) { str += key + ':' + this.serialize(_obj[key]) + ','; }
	            str = str.replace(/\,$/, '') + '}';
	         }
	         return str;
	         break;
	
	      default:
	         return 'UNKNOWN';
	         break;
	   }
	}
	
}


var JSONSocket = new JSONSocketObject(httpRoot);