if (!this.PowerLoader) {
    PowerLoader = {};
}
(function () {
function resetLoader()
{
	PowerLoader.isAX = false;
	PowerLoader.isNP = false;
	PowerLoader.plugin = null;
	PowerLoader.valid = false;
	PowerLoader.isOldVersion = false;
}
resetLoader();

PowerLoader.logError = function(entry)
{
	var extraData = "";
	if( PowerLoader.isAX )
		extraData += ",ax";
	else if( PowerLoader.isNP )
		extraData += ",np";
	else
		extraData += ",none";
	extraData += "," + location.href;
	extraData += "," + navigator.appName;
	extraData += "," + navigator.appVersion;
	extraData += "," + navigator.userAgent;
	extraData += "," + navigator.systemLanguage;
	extraData += "," + navigator.userLanguage;
	try {
		extraData += "," + PowerLoader.plugin.getTopLoaderVersion();
	} catch(e)
	{
		extraData += ",toploader_version_unavailable";
	}
	try {
		extraData += "," + PowerLoader.plugin.getLoaderVersion();
	} catch(e)
	{
		extraData += ",loader_version_unavailable";
	}
	$.post("common/applet/loaderLogReceiver.php?", {"logentry":entry + extraData} );
}

function compactSignature(signature)
{
	return signature.substr(0,24) + "..." + signature.substr(1000);
}

PowerLoader.createPlugin = function ( domainPattern, domainSignature, requiredVersion )
{
	if( PowerLoader.isAX )
	{
		//document.write( "<div style=\"position: absolute\"><OBJECT ID=\"PowerLoaderObject\" CLASSID=\"CLSID:4BFD075D-C36E-4F28-BB0A-5D472795197A\" width=\"0\" height=\"0\"></OBJECT></div>" );
		$("body").append("<OBJECT ID=\"PowerLoaderObject\" CLASSID=\"CLSID:B58A2970-7C42-11DE-8A39-0800200C9A66\" width=\"0\" height=\"0\"></OBJECT>");
		PowerLoader.plugin = document.getElementById("PowerLoaderObject");
	} 
	else if( PowerLoader.isNP ) 
	{
		//document.write( "<div style=\"position: absolute\"><EMBED ID=\"PowerLoaderObject\" TYPE=\"application/powerloader\" width=\"0\" height=\"0\" /></div>");
		$("body").append("<EMBED ID=\"PowerLoaderObject\" TYPE=\"application/powerloader\" width=\"0\" height=\"0\" />");
		PowerLoader.plugin = document.getElementById("PowerLoaderObject");
	}
	
	if( PowerLoader.plugin != null ) {
		try {
			PowerLoader.valid = PowerLoader.plugin.validate( domainPattern, domainSignature );
			if( PowerLoader.valid )
			{
				if( PowerLoader.plugin.getTopLoaderVersion() < requiredVersion )
				{
					PowerLoader.logError("old_top_loader," + PowerLoader.plugin.getTopLoaderVersion() + "," + requiredVersion);
					resetLoader();
					PowerLoader.isOldVersion = true;
				}
			} else {
				PowerLoader.logError("validation_failed, " + domainPattern + "," + compactSignature(domainSignature) );
			}
		} catch(e) {
			PowerLoader.logError("validation_threw_exception," + domainPattern + "," + compactSignature(domainSignature) );
			resetLoader();
		}
	}
}

PowerLoader.getTopLoaderVersion = function ()
{
	if( PowerLoader.plugin == null || !PowerLoader.valid )
		return -1;
	
	return PowerLoader.plugin.getTopLoaderVersion();
}

PowerLoader.getLoaderDllVersion = function ()
{
	if( PowerLoader.plugin == null || !PowerLoader.valid )
		return -1;
	
	return PowerLoader.plugin.getLoaderVersion();
}

PowerLoader.isGameRunning = function( gameId )
{
	if( PowerLoader.plugin == null || !PowerLoader.valid )
		return false;
		
	return JSON.parse(PowerLoader.plugin.command(JSON.stringify({"command": "isGameRunning","gameid":gameId})));
}

PowerLoader.constructDownloadTask = function( game, url, lastModified, signature, size, target )
{
	var task =  {"command":"download","game":game,"lastmodified":lastModified,"signature":signature,"filename":target,"url":url}
	if( size != 0 )
		task.size = size;
	return task;
}

PowerLoader.constructExecuteTask = function( game, filename, commandline )
{
	return {"command":"execute","game":game,"filename":filename,"commandline":commandline}
}

PowerLoader.constructUpgradeTask = function()
{
	return {"command":"upgrade"}
}

PowerLoader.startTask = function( task )
{
	if( PowerLoader.plugin == null || !PowerLoader.valid )
		return null;

	var command = {"command":"startTask","task":task};
	var result = JSON.parse(PowerLoader.plugin.command(JSON.stringify(command)));
	return result;
}

PowerLoader.stopTask = function()
{
	if( PowerLoader.plugin == null || !PowerLoader.valid )
		return null;

	var command = {"command":"stopTask"};
	var result = JSON.parse(PowerLoader.plugin.command(JSON.stringify(command)));
	return result;
}


PowerLoader.ping = function()
{
	if( PowerLoader.plugin == null || !PowerLoader.valid )
		return null;
		
	var command = {"command":"ping"};
	return JSON.parse(PowerLoader.plugin.command(JSON.stringify(command)));
}

PowerLoader.getTestLog = function(game)
{
	if( PowerLoader.plugin == null || !PowerLoader.valid )
		return null;
		
	var command = {"command":"getTestLog","game":game};
	return JSON.parse(PowerLoader.plugin.command(JSON.stringify(command)));
}

function detectNPPlugin( plugin ) 
{
	navigator.plugins.refresh(false);
    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) 
	{
		var pluginsArrayLength = navigator.plugins.length;
		// for each plugin...
		for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
			// loop through all desired names and check each against the current plugin name
			var numFound = 0;
			// if desired plugin name is found in either plugin name or description
			if( (navigator.plugins[pluginsArrayCounter].name.indexOf(plugin) >= 0) || 
				(navigator.plugins[pluginsArrayCounter].description.indexOf(plugin) >= 0) ) {
				// this name was found
				return true;
			}   
		}
	}
    return false;
}

// Here we write out the VBScript block for MSIE Windows
if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) 
{
	// TODO: It is possible to do this with JS instead, and we should also use the created object, instead of throwing it away

    document.writeln('<script language="VBscript">');

    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');

    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectAXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectAXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectAXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');
    document.writeln('</scr' + 'ipt>');
}

PowerLoader.detectPowerLoader = function() 
{
    PowerLoader.isNP = detectNPPlugin("Power Challenge Loader");
    // if not found, try to detect with VisualBasic
    if(!PowerLoader.isNP && typeof(detectableWithVB) != 'undefined') 
	{
		if(detectableWithVB)
			PowerLoader.isAX = detectAXControl("PowerChallenge.PowerLoader2");
	}
}

// Create a hidden div we can use to bounce loader events
document.writeln('<div style="display: none;" id="PowerLoaderEvent"></div>');

PowerLoader.detectPowerLoader();
}());

function setLoaderIconIdle()
{
	if( $("#pc_loader_icon").length )
	{
		$("#pc_loader_icon").css("background", "none");
		$("#pc_loader_icon").attr("title", "");
		//$("#pc_loader_icon").css("background", "url(common/img/icons/plugin_18.png)");
		//$("#pc_loader_icon").attr("title", "Power Challenge Game Plugin");
	}
}

function setLoaderIconError(message)
{
	if( $("#pc_loader_icon").length )
	{
		$("#pc_loader_icon").css("background-position", "0px 0px");
		$("#pc_loader_icon").css("background", "url(common/img/icons/busy_16.png) no-repeat");
		$("#pc_loader_icon").attr("title", message);
	}
}

function setLoaderIconWorking(message, progress)
{
	if( $("#pc_loader_icon").length )
	{
		$("#pc_loader_icon").css("background", "url(common/img/icons/pie_chart.png)");
		$("#pc_loader_icon").css("background-position", -Math.round(progress*16)*18 + "px 0px");
		$("#pc_loader_icon").attr("title", message);
	}
}

function initializePlugin( domainPattern, domainSignature, requiredVersion )
{	
	bindPowerLoaderEvent( "task_failed", function(event, arg) {
		PowerLoader.logError("task_failed," + JSON.stringify(arg));
	});

	bindPowerLoaderEvent( "validation_log", function(event, arg) {
		PowerLoader.logError("validation_log," + JSON.stringify(arg));
	});
	
	bindPowerLoaderEvent( "toploader_log", function(event, arg) {
		PowerLoader.logError("toploader_log," + JSON.stringify(arg));
	});

	PowerLoader.createPlugin( domainPattern, domainSignature, requiredVersion );
	
	if( PowerLoader.valid )
	{
		triggerPowerLoaderEvent("update_game", null);
	} else {
		if( PowerLoader.plugin == null )
			setLoaderIconError("Latest version of Power Challenge Plugin not installed");
		else
			setLoaderIconError("Power Loader could not be started properly.");
	}
}

function onPowerLoaderEvent(arg)
{
	if( typeof(arg) == "object" && typeof(arg.event) == "string" )
	{
		triggerPowerLoaderEvent(arg.event, arg);
	}
}

function triggerPowerLoaderEvent(event, data)
{
	$("#PowerLoaderEvent").trigger(event, data);
}

function bindPowerLoaderEvent(event, func)
{
	$("#PowerLoaderEvent").bind(event, func);
}

function bindPowerLoaderEventOnce(event, func)
{
	$("#PowerLoaderEvent").one(event, func);
}

function unbindPowerLoaderEvent(event, func)
{
	$("#PowerLoaderEvent").unbind(event, func);
}
