var d2dHandler = Class.create();
var d2d;
d2dHandler.prototype = {

	initialize: function() {
		try {
			this.oShell = new ActiveXObject("Shell.Application");
		} catch (e) {
			if (console != undefined) console.info('ActiveX object Shell.Application unavailable');
			this.oShell = false;
		}
		this.url = "C:\\Day2Day\\";
		this.Day2DayClient   = "Program\\Day2DayClient.exe";
		this.D2DFocusChanger = "OdenseKomune\\D2DFocusChanger.exe";
		this.d2dExportData	= "KioskFolders\\WebData\\D2DExportData.xml";
		this.isSiteKiosk = false;
		this.lastLoad = this.getLastLoad();
		this.container = $('categoryLowerContainer');
		this.originalContent = $('categoryLowerContainer').innerHTML;
		this.loadingContent = '<img src="gfx/global/d2dloading.gif" alt="loading..." id="d2dloading" />';
	},
	
	execute: function(inputparms) {
		try {
			window.external.InitScriptInterface();
			this.isSiteKiosk = true;
		} catch(e) {
			this.isSiteKiosk = false;
		}
		
		if(inputparms != "") {
			var commandParms = this.url + this.Day2DayClient + " " + inputparms;
		} else {
			var commandParms = this.url + this.Day2DayClient;
		}
		    
		var commandtoRun = this.url + this.D2DFocusChanger;
		
		try {
			// Invoke the execute method.
			if(this.isSiteKiosk) {
				SiteKiosk.ExternalApps.Run(commandtoRun + " " + commandParms, true);
			} else {
				this.oShell.ShellExecute(commandtoRun, commandParms, "", "open", "1");
			}
		} catch (e) {
			return false;
		}
	},
	
	getLastLoad: function()
	{
		var xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
		xmlDoc.async = false;
		
		try	{
			var loaded = xmlDoc.load(this.url+this.d2dExportData);
			if (!loaded) {
				return null;
			}
		} catch(e) {
			alert("Error: This site is not set as trusted site." );
			return null;
		}
		try {
			return parseInt((xmlDoc.getElementsByTagName('kioskLoaded')[0]).childNodes[0].nodeValue);
		} catch(e) {
			return null;
		}
	},
	
	isLoaded: function()
	{
		return (this.lastLoad != this.getLastLoad());
	},
	
	open: function(inputparms)
	{
		this.container.innerHTML = this.loadingContent;
		this.lastLoad = this.getLastLoad();
		if (this.execute(inputparms) == false) this.container.innerHTML = this.originalContent;
		setTimeout(this.checkLoaded.bind(this), 1000);
	},
	
	checkLoaded: function()
	{
		if (this.isLoaded()) {
			setTimeout(this.onLoaded.bind(this), 6000); // allow 6 seconds for focus change
		} else {
			setTimeout(this.checkLoaded.bind(this), 1000);
		}
	},
	
	onLoaded: function()
	{
		this.container.innerHTML = this.originalContent;
	}
}


addLoadEvent(function() { //initialize and start object
	d2d = new d2dHandler();
});
