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

// common variables
var checkTimer			= null;
var theBrowser			= null;
var thePlugin			= null;
var thePluginParameters	= null;
var thePluginName		= "cgp";
var checkInterval		= 200 // in miliseconds
var checkTimerCounter	= 5; // check plugin for checkInterval times 

function loadMediaPlugin(pluginName, params) {
	thePluginName = pluginName;
	thePluginParameters = params;
	theBrowser = getBrowser();
	if (!theBrowser){
		if (pronto && pronto.mediaPluginInitialized)
			pronto.mediaPluginInitialized(false, {browser:"unsupportedBrowser"});
		return;
	}

	clearInterval(checkTimer);
	
	var force = false; 
	if (thePluginParameters && thePluginParameters.hasOwnProperty('force'))
		force = thePluginParameters.force; 
	
	// if force == true - try to load plugin no matter what (usually when try to load it again)
	if (!force){
		var pluginCheck = getQueryVariable('pluginInstalled') != ""; // already tried to load
		var pluginInstalled = getQueryVariable('pluginInstalled') == "true";
		// if always tried to load - do not try again
		if (pluginCheck && !pluginInstalled){
			if (pronto && pronto.mediaPluginInitialized){
				pronto.mediaPluginInitialized(false, {browser:theBrowser, status:'installationCancelled'});
			}
			return;
		}
	}
	
	return addObjectToPage(true);
}

//	add plugin to page to start loading
function addObjectToPage(startCheck){
	var obj = getObject(thePluginName);
	if(obj != null) {
		document.getElementById("MediaPlugin").innerHTML = obj;
		if (startCheck){
			checkTimerCounter = 5;
			checkTimer = setInterval(checkLoaded, checkInterval);
		}
		return "Loading";
	}
	return "Unsupported browser";
}
//-------------------------------------
// This function is called periodically. It checks if the Plugin has been loaded
//-------------------------------------
function checkLoaded() {
	checkTimerCounter--;

	// time is up
	if (checkTimerCounter < 0){
		clearInterval(checkTimer);
		// try to load plugin in chrome
		if (theBrowser == "Chrome"){
			// if this parameter is true - check infinite for plugin loading in chrome browser
			var chromeCheckInfinite = false; 
			if (thePluginParameters.hasOwnProperty('chromeCheckInfinite'))
				chromeCheckInfinite = thePluginParameters.chromeCheckInfinite; 
			
			if (chromeCheckInfinite)
				checkTimer = setInterval(infiniteCheckChromeLoaded, 3000);
			
			window.location = getPluginURL(theBrowser);
		}
		
		if (pronto && pronto.mediaPluginInitialized)
			pronto.mediaPluginInitialized(false, {browser:theBrowser, status:'start', infinite:chromeCheckInfinite});
			
		return;
	}
	
	if (checkPluginSuccess())
		clearInterval(checkTimer);

}

// infinite check for plugin load in chrome
function infiniteCheckChromeLoaded(){
	addObjectToPage(false);
	if (checkPluginSuccess())
		clearInterval(checkTimer);
}

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, {browser:theBrowser, infinite:true});
				return true;
			}
			break;
	}
	return false;
}

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

// ----------------------------------------------------------------------------

//-------------------------------------
// additional public methods udingin Pronto!
//-------------------------------------

// get link to load plugin
function GetLoadLink() {return getPluginURL(theBrowser);}

// need to show plugin URL for correct installation
function ShowPluginInstallationParam(param) {return checkBrowserInstallNeeds(param, theBrowser);}


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

//-------------------------------------
// main plugin functionality
//-------------------------------------
// legs methods	
function createLeg(leg, inp, out)	{return traceResult( thePlugin.CreateLeg (leg, inp, out));}
function destroyLeg(leg)			{return traceResult( thePlugin.DestroyLeg(leg));}
function activateLeg(leg)			{return traceResult( thePlugin.Activate  (leg));}
function deactivateLeg(leg)			{return traceResult( thePlugin.Deactivate(leg));}
function setHold(leg,flag )			{return traceResult( thePlugin.SetHold(leg, flag));}

// sdp methods	
function getLocalSDP(leg)			{return traceResult( thePlugin.GetLocalSDP(leg,"xml") );}
function setRemoteSDP(leg,sdp)		{return traceResult( thePlugin.SetRemoteSDP(leg, sdp, "xml"));}
function sendDTMF(leg,symbol)		{return traceResult( thePlugin.SendDTMF (leg, symbol) );}
	
// play, volume methods	
function playToLocal(leg, data, loop)	{return traceResult( thePlugin.PlayToLocal(leg, data, loop) );}
function playToRemote(leg, data, loop)	{return traceResult( thePlugin.PlayToRemote(leg, data, loop) );	}
function setInputVolume(leg, level)  	{return traceResult( thePlugin.SetInputVolume(leg, level) );}
function setOutputVolume(leg, level)	{return traceResult( thePlugin.SetOutputVolume(leg, level) );}

//media mixing (for gips plugin only)
function attachToMixer(id)	{return traceResult( thePlugin.AttachToMixer(id) );}
function attachToMixer(id)	{return traceResult( thePlugin.AttachToMixer(id) );}

//media muting (for gips plugin only)
function setMute(leg, mute)			{return traceResult( thePlugin.SetMute(leg, mute) );}
function isMute(leg)				{return traceResult( thePlugin.IsMute(leg) );}
function setMuteRemote(leg, mute)	{return traceResult( thePlugin.SetMuteRemote(leg, mute) );}
function isMuteRemote(leg)	 		{return traceResult( thePlugin.IsMuteRemote(leg) );}

//GIPS plugin license
function getLicenseChallenge() 				{return traceResult( thePlugin.GetLicenseChallenge() );}
function processLicenseResponse(responce)	{return traceResult( thePlugin.ProcessLicenseResponse(responce) );}

// connection  properties
function setLocalIP(id)	 		{return traceResult( thePlugin.SetLocalIP(id) );}
function detachFromMixer(id)	{return traceResult( thePlugin.DetachFromMixer(id) );}
	
function getVersion()			{return thePlugin.GetVersion();}
	
// advanced methods		
function listDevices(value)		{return thePlugin.ListDevices(value);}	
function setLogLevel(logLevel)	{return traceResult( thePlugin.SetLogLevel(logLevel));}

// ----------------------------------------------------------------------------
//
// IE plugin installer (do not relogin pronto 3 times)
//
// ----------------------------------------------------------------------------

var installPluginWindow = null;
var loginParameters = ""; // SSID, username, to redirect
// true if install process running
var installationProcess = false;


// when popup is reloaded it looses responce function
var checkReloadTimer = null;

function installer_handler(result){
	if (!result){
		if (!installationProcess)
			finishPluginInstall(false);
		else
			setTimeout(checkWindowReload, 1000);
	} else {
		installationProcess = false;
		finishPluginInstall(true);
	}
}

function finishPluginInstall(success){
	if (success){
		addObjectToPage(true);
	} else {
		pronto.mediaPluginInitialized(false, {browser:theBrowser, status:'finish'});
	}
}

function installIEPlugin(){
	installationProcess = true;
	
	var skinName = "Pronto-"; 
	if (thePluginParameters && thePluginParameters.hasOwnProperty('skinName'))
		skinName = thePluginParameters.skinName; 
	var language = ""; 
	if (thePluginParameters && thePluginParameters.hasOwnProperty('language'))
		language = thePluginParameters.language; 
		
	installPluginWindow = window.open("plugininstaller.wssp?Skin="+skinName+"&Language="+language,"pluginInstaller",
	   "width=600,height=450,location=no,toolbar=no,menubar=no,status=no,scrollbars=yes,resizable=no");
	
	var newLocation = "plugininstaller.wssp?Skin="+skinName+"&Language="+language;
	if (!installPluginWindow){
		newLocation += "&backURL=/Pronto/"+
			"&plugin="+thePluginName;
		if (thePluginParameters && thePluginParameters.hasOwnProperty('redirect'))
			newLocation += "&"+thePluginParameters.redirect;
			
		window.location = newLocation;
	} else {
		setTimeout(popupStart, 100);
	}
}

function popupStart(){
	installPluginWindow.start(installer_handler, thePluginName);
	installPluginWindow.focus();
}

function checkWindowReload(){
	if (typeof installPluginWindow.checkReload == "unknown") {
		installationProcess = false;
		finishPluginInstall(false);
		return;
	}
	
	var result = installPluginWindow.checkReload();
	if (result){
		clearInterval(checkReloadTimer);
		installPluginWindow.start(installer_handler, thePluginName, 'confirmedInstallation');
	}
	
}


