var timerTasksInterval = 1.0;
var lasttimeclientrunning = 0;
var isclientrunningHysteresisInterval = 30000;
var timeoutClientAlive = 2000;
var timeStart = (new Date()).getTime();
var cacaowebStatus = 'Unknown';

function include_script(script_filename, scriptname) { 
	var html_doc = document.getElementsByTagName('body').item(0);
	if ($(scriptname)) { $(scriptname).remove() }; 
	html_doc.appendChild(new Element('script', { 'id': scriptname, 'language': 'javascript',
		'type': 'text/javascript', 'src': script_filename
	}));
}

function checkcacaowebInstalled() {
    var i = Math.floor(Math.random() * 1000000);
    if (lasttimeclientrunning == 0 || (new Date()).getTime() - lasttimeclientrunning > isclientrunningHysteresisInterval) {
		include_script('http://127.0.0.1:4001/isrunning?unique=' + i, 'isrunningscript');
	}
}

function callbackisrunning() { lasttimeclientrunning = (new Date()).getTime(); }

function updateStatusVariable() {
	if ((new Date()).getTime() - lasttimeclientrunning < timeoutClientAlive + isclientrunningHysteresisInterval) {
		cacaowebStatus = 'On';
	} else if ((new Date()).getTime() - timeStart < 2000) {
		cacaowebStatus = 'Unknown';
	} else {
		cacaowebStatus = 'Off';
	}
}

new PeriodicalExecuter(checkcacaowebInstalled, timerTasksInterval);
new PeriodicalExecuter(updateStatusVariable, timerTasksInterval);


function downloadcacaoweb() {
	var platform = "Windows";
	if ( navigator.platform != null ) {
		if ( navigator.platform.indexOf( "Win32" ) != -1 ) {
			platform = "Windows";
		} else if ( navigator.platform.indexOf( "Win64" ) != -1 ) {
			platform = "Windows";
		} else if ( navigator.platform.indexOf( "Win" ) != -1 ) {
			platform = "Windows";
		} else if ( navigator.platform.indexOf( "Linux" ) != -1 ) {
			platform = "Linux";
		} else if ( navigator.platform.indexOf( "SunOS i86pc" ) != -1 ) {
			platform = "Solaris x86";
		} else if ( navigator.platform.indexOf( "SunOS sun4u" ) != -1 ) {
			platform = "Solaris SPARC";
		} else if ( navigator.platform.indexOf( "SunOS" ) != -1 ) {
			platform = "Solaris SPARC";
		} else if ( navigator.platform.indexOf( "Mac" ) != -1 && navigator.platform.indexOf( "Intel" ) != -1 ) {
			platform = "Mac OSX Intel";
		} else if ( navigator.platform.indexOf( "Mac" ) != -1 && navigator.platform.indexOf( "PPC" ) != -1 ) {
			platform = "Mac OSX PPC";
		} else if ( navigator.platform.indexOf( "Mac" ) != -1 ) {
			platform = "Mac OSX" ;
		} else
			platform = navigator.platform;
	}
	
	var uri;
	if (platform == "Windows"){
		uri = "http://www.sourceforge.net/projects/cacaoweb/files/cacaoweb.exe/download";
	} else if (platform == "Mac OSX" || platform == "Mac OSX Intel") {
		uri = "http://www.sourceforge.net/projects/cacaoweb/files/cacaoweb.dmg/download";
	} else if (platform == "Linux") {
		uri = "http://www.sourceforge.net/projects/cacaoweb/files/cacaoweb/download";
	}
		
	setTimeout( window.location.href = uri,  500 );
}
