// ============================================= //
//       CommuniGate Media Plugin loader         //
//                                               //
// Version 1.3                                   //
// Copyright (c) Stalker Software, Inc.          //
// 2010 - 2011                                   //
// ============================================= //

// common variables
var ERROR_UNSUPPORTED_BROWSER = "plugin not available";

var thePlugin;

var pluginToLoad = "cgp";
var checkTimer			= null;
var checkInterval		= 200; // in miliseconds
var checkTimerCounter	= 5; // check plugin for checkInterval times 

var chromeTimer;
var ieLongTimer;
var ieLongCheckCounter = 5;

function loadMediaPlugin(pluginName) {
	var browser = getSaneBrowser();
	if (!browser)
		return ERROR_UNSUPPORTED_BROWSER;

	clearInterval(checkTimer);
	
	pluginToLoad = pluginName;
	
	return addObjectToPage(true);
}
function stopPolling(){
	if (chromeTimer){
		clearInterval(chromeTimer);
		chromeTimer = null;
	}
}

//	add plugin to page to start loading
function addObjectToPage(startCheck){
	var browser = getSaneBrowser();
	var obj = getObject(pluginToLoad);
	
	if(obj != null) {
		//if IE add plugin object in different way (to get events from video window)
		if (browser.name == "msie") {
			document.getElementById("MediaPlugin").appendChild(document.createElement(obj));
		} else {
			document.getElementById("MediaPlugin").innerHTML = obj;
		}
		if (startCheck) {
			checkTimerCounter = 5;
			checkTimer = setInterval(checkLoaded, checkInterval);
		}
		return "";
	}
	
	return ERROR_UNSUPPORTED_BROWSER;
}
//-------------------------------------
// This function is called periodically. It checks if the Plugin has been loaded
//-------------------------------------
function checkLoaded() {
	checkTimerCounter--;

	if (checkPluginSuccess() || checkTimerCounter < 0) {
		clearInterval(checkTimer);
		
		if (checkTimerCounter < 0 && !chromeTimer)
		{ // load failed
			if (pronto && pronto.mediaPluginInitialized)
				pronto.mediaPluginInitialized(false);
			
			var browser = getSaneBrowser();
			if (browser.name == 'chrome')
			{ 
				clearInterval(chromeTimer);
				chromeTimer = setInterval(chromeCheck, 3000);
			}
			else if (browser.name == 'msie')
			{ // IE installs plugin automatically sometimes. We can try again.
				setTimeout(ieSimpleCheck, 3000);
			}
		}
	}
}

function chromeCheck() {
	if (isPluginAvailable(pluginToLoad) == 'yes')
	{
		clearInterval(chromeTimer);
		chromeTimer = null;
		addObjectToPage(true);
	}
}

function ieSimpleCheck() {
	addObjectToPage(false);
	setTimeout(ieCheckSuccess, 500); // give plugin some time to initialize
}

function ieSecondCheck() {
	clearInterval(ieLongTimer);
	ieLongCheckCounter = 10;
	ieLongTimer = setInterval(ieCheck, 3000);
}

function ieCheck() {
	ieLongCheckCounter--;
	if (ieLongCheckCounter == 0 || thePlugin)
		clearInterval(ieLongTimer);
	ieSimpleCheck();
}

function ieCheckSuccess() {
	var success = checkPluginSuccess();
	if (ieLongTimer && success)
		clearInterval(ieLongTimer);
	else if (!ieLongTimer && !success) //initial check
		setTimeout(ieSecondCheck, 10000); // give considerable time to load and install plugin
}

function checkPluginSuccess(){
	thePlugin = document.getElementById("CommuniGateAV");
	
	switch(typeof thePlugin) {
		case 'undefined':
			break; 
		case 'object':
		case 'function':
			if(typeof thePlugin.GetVersion != 'undefined' ) {
				if (pronto && pronto.mediaPluginInitialized)
					pronto.mediaPluginInitialized(true);

				return true;
			}
			break;
	}
	
	return false;
}

// ----------------------------------------------------------------------------
//
// plugin methods
//
// ----------------------------------------------------------------------------

//-------------------------------------
// main plugin functionality
//-------------------------------------
var pluginOperations = [];

var dontNeedTraceResult = ["GetOutputVolume", "GetInputLevel", "GetVersion", "ListDevices", "GetVideoDevices",
	"GetAvailableControls", "GetVideoStatistics", "GetSizePos", "AddMenuItem"];

var operationCallback;

function setOperationCallback(name) {
	operationCallback = function (operationId, result) {
		if (pronto && typeof pronto[name] != "undefined")
			pronto[name](operationId, result);
	};
}

function traceResult( operationResult )	{
  return (operationResult === "" || operationResult == 0 || operationResult == "0" || operationResult == null) ? "" : operationResult;
}

function execute() {
	var args = Array.prototype.slice.call(arguments);
	var operationId = args.shift();
	var name = args.shift();
	name = name.charAt(0).toUpperCase() + name.substr(1);
	//var isAsynq = (name == "StartVideoCapture" || name == "SetRenderingMode");
	var isAsynq = true;
	var operation = {operationId: operationId, name: name, args: args};
	if (pluginOperations.length == 0 && !isAsynq) {
		runOperation(operation);
	}
	else {
		pluginOperations.push(operation);
		if (pluginOperations.length > 1)
			return;
		
		// handle one operation at a time
		var f = function () {
			if (pluginOperations.length > 0) {
				var op = pluginOperations.shift();
				runOperation(op);
				
				if (pluginOperations.length > 0)
					setTimeout(f, 50);
			}
		};
		setTimeout(f, 50);
	}
}

function runOperation(op) {
	if (op.name == "SetResolution")
	{
		operationCallback(op.operationId, "");
		return;
	}
	var argsstr = "";
	for (var i = 0; i < op.args.length; i++) {
		var arg = op.args[i];
		if (typeof arg == "string")
			argsstr += "'" + arg + "',";
		else
			argsstr += arg + ",";
	}
	argsstr = argsstr.substring(0, argsstr.length-1);
	argsstr = argsstr.replace(/(\n(\r)?)/g, "");
	var result;
	try {
		result = eval("thePlugin." + op.name + "(" + argsstr + ")");
	} catch (e) {
		operationCallback(op.operationId, String(e));
		return;
	}
	var dontTrace = false;
	var i = 0;
	for (i = 0; i < dontNeedTraceResult.length; i++) {
		if (dontNeedTraceResult[i] == op.name) {
			dontTrace = true;
			break;
		}
	}
	if (!dontTrace)
		result = traceResult(result);
	operationCallback(op.operationId, result);
}

function setUserActionCallback(name) {
	thePlugin.onUserAction = function (commandId, param1, param2) {
		if (pronto && typeof pronto[name] != "undefined")
			pronto[name](commandId, param1, param2);
	};
}
