/** 
 * DXStudio Tools
 * 
 * @author Stephen Wright
 * @date nov 10th, 2009
 * 
 * A tool to assist in handeling dxs docs
 * 
 * DXStudioTool (dxst)
 */

var dxst = { 

	debug_mode: false,	// if true, addition information will be outputed
	trace_mode: false,	// if true, WAY more information will be outputed, like... a LOT

	isIE: 		(navigator.userAgent && navigator.userAgent.indexOf("MSIE") != -1),

	// callbacks
	cb: 		{ 	load: []
					},
		
	ref: 		null,	// reference to the DXStudio Document Object
	loaded: 	false,	// for keeping track of state
	reachable: 	false, 	// set to true if player ping was successfull
	version:	null,

	log: 		function (txt) { return; },
	debug: 		function (txt) { if (dxst.debug_mode) dxst.log(txt); },
	trace: 		function (txt) { if (dxst.trace_mode) dxst.log(txt); },
	
	/**
	 * if name is passed in, will set the handle to the dxs doc 
	 * returns a handle to the dxstudio element 
	 * @param name don't set to get handle, set to find a document
	 */
	getRef: function (name) {
		if (name != undefined) { // get the reference
			try {
				var h = null;
				if (!dxst.isIE && document.embeds && document.embeds[name]) h = document.embeds[name];
				else if (window.document[name]) h = window.document[name];
				if (h == null) h = document.getElementById(name);
				if (h == null) dxst.log('* Could not find the requested DXStudio document.');
				dxst.ref = h;
			}
			catch (e) { dxst.log("* error getting refference to dxs doc: " + e); }
		}
		return dxst.ref;
	},
	
	/**
	 * send a command to the DXStudio document
	 * @param cmd command to send
	 */
	send: function (cmd) {
		dxst.debug('>> Sending the following command to the DXStudio document: ' + cmd);
		try { dxst.getRef('dxs').Send(cmd); }
		catch (e) { dxst.log("* Could not send cmd to control. " + e); }
	},
	
	/**
	 * enables the console in dxstudio and prints a test message
	 */
	enableConsole: function () {
		dxst.log('attempting to enable the console.');
		dxst.send(' system.consoleHide = false; ');
		dxst.send(' print("console enabled");  ');
	},
	
	/** 
	 * clean up the dxs doc to free up some resources 
	 */
	unload: function () { 
		dxst.log('unloading the DXStudio document.');
		dxst.ref = null; 
		document.getElementById('dxsDoc').innerHTML = ''; 
	},
	
	/**
	 * second load event, called when the document is loaded (for real)
	 * and the ping test has completed successfully
	 */
	load2: 		function () {},
	pingFailed: function () {},
	
	/**
	 * Compare version strings
	 * 
	 * @param v1 version string, eg: "3.2.8.0"
	 * @param v2 version string
	 * @return 
	 *   1 if v1 is bigger
	 *   0 if both are the same
	 * 	-1 if v2 is bigger
	 */
	vcomp: function (v1, v2) {
		dxst.trace("dxst.vcomp: [" + v1 + "]=[" + v2 + "]");
		var v1a = v1.split(".");
		var v2a = v2.split(".");
		var a,b,i;
		if (v1a == null || v1a.length == 0 || v2a == null || v2a.length == 0) {
			dxst.debug("invalid argument");
			return 0;
		}
		while(v1a.length < 5) v1a[v1a.length] = "0";
		while(v2a.length < 5) v2a[v2a.length] = "0";
		for (i = 0; i < 5; ++i) {
			a = parseInt(v1a[i]);
			b = parseInt(v2a[i]);
			if (a > b) return  1;
			if (a < b) return -1;
		}
		return 0;
	},
	
	do_load: function () {
		if (dxst.debug_mode) dxst.enableConsole();
		dxst.log('document loaded. [<a href="#unload" onclick="dxst.unload(); return false;">unload</a>]');
		dxst.loaded = true;
		
		dxst.send(' shell.send("ver:" + system.version); ');
	//	dxst.debug("version: " + (dxst.version = dxst.getRef('dxs').Version));
		
		dxst.send(' shell.send("ping"); ');
		
		setTimeout(function (){ if (!dxst.reachable) dxst.pingFailed(); }, 10000);
		// run through onload callbacks
		var f = null;
		while (f = dxst.cb.load.shift()) f.call();
	},
	
	// Events triggered by the dxstudio control
	// -------------------------------------------------------------------------
	events: {
		
		load: function (done) {
			dxst.debug(">> Loaded, done: " + done);
			if (done) {
				// Set a slight delay, because sometimes IE reports being done prematurely
				setTimeout( dxst.do_load, 500 );
			}
		},
		
		receive: function (msg) { 
			dxst.trace('>> Received message from plugin: ' + msg);
			
			if (msg == "ping") {
				dxst.reachable = true; 
				dxst.load2.call();
			}
			else if (msg.indexOf('ver:') != -1) {
				dxst.version = msg.replace('ver:', '');
				dxst.debug("version: " + dxst.version);
			}
			else {
				try { eval(msg); } catch (e) { dxst.trace('* Could not eval msg'); }
			}
		},
		
		update: function (eTime) {
		//	dxst.trace('>> Update, elapsed time: ' + eTime);
		}
	}
};
