// ===================================================
// ASF Support

var PC_CALL_GE = 12;	// New Generic PC-GE call
var PC_GE_CALL_STEAMING_TYPE = 1;

var PC_STREAM_WAVE = 10; 

var STREAM_INIT_PLAYER = 1;
var STREAM_PAUSE = 2;
var STREAM_STOP = 3;
var STREAM_PLAY = 4;
var STREAM_GETPLAYSTATE = 5;
var STREAM_GETCURRENTPOSITION = 6;
var STREAM_SETCURRENTPOSITION = 7;
var STREAM_GETDURATION = 8;
var STREAM_SETFILENAME = 9;
var STREAM_GETOVERRUNS = 10;	         // number of times we were starved for data on each play
var STREAM_GETUNCOMPRESSEDTOTAL = 11;    // uncompressed total size 
var STREAM_GETUNCOMPRESSEDUSED = 12;     // uncompressed bytes already used
var STREAM_GETCOMPRESSEDTOTAL = 13;      // acelp bytes total
var STREAM_GETCOMPRESSEDDOWNLOADED = 14; // acelp bytes downloaded so far
var STREAM_SET_PAUSE_TIME = 15;
var STREAM_GETSTREAMINGTYPE = 16;

var PC_DELETE_AUDIO_FILES = 28;
var PC_IS_AUDIO_FILE_AVAILABLE = 33;

var GE_Streaming = false;
var savedfilename = ""; // locally saved current filename
var asfPlayer = 0;
var playerExists = false;

//parameter isn't used
function initPlayer (player)
{
	if (playerExists)
		return;
 
	if (hasMediaPlayer && !forcePC()) {
		GE_Streaming = false;
		asfPlayer = p.getFrame(0).document.nsPlay;
	} else
		GE_Streaming = true;
 
	playerExists = true;
}

function ClearUserSounds(objectId){
	// Supported in 2.0.0.36 and above. Clear audio files if objectId is different from last call
	// call is ignored with earlier comps that delete sounds each time pc is unloaded

	// Due to registry write errors we are now saving the ObjectId associated with the most recent
	// Record and Play activity within a cookie.

	var strObjectId=""+getCookie("RP_ObjectId");
	if (!strObjectId.length||(""+objectId)!=strObjectId){
		ctrl().PC(PC_DELETE_AUDIO_FILES,"","",objectId);
		setCookie("RP_ObjectId",""+objectId,true);
	}
}

// -1 error, 0 not file, 1 file found
function IsAudioFileAvailable(index){
	return ctrl().PC(PC_IS_AUDIO_FILE_AVAILABLE,"","",index);
}

var lastDuration = -1;
var gDuration = 0;
function asfIsPlaying ()
{
var result = false;

	if (!playerExists)
		return false;
	var state = asfGetPlayState();
	var curpos = asfGetCurrentPosition();
	var duration = asfGetDuration();
	// necessary to use gDuration because asfPlayer.currentMedia.duration was sometimes returning 0 after it already
	// had positive values.
	if (duration > gDuration)
		gDuration = duration;
	//defaultStatus = duration + "|" + state + "|" + curpos + "|" + asfPlayer.playState;
	if (GE_Streaming){
		if ( state == 2 && (duration == 0 || curpos < duration))
			result = true;
    }
    else if (state == 2 && curpos < gDuration)
		result = true;
	else{ // Special case to handle situation with MP9 where the audio is done playing
	// before MP9 tells us that it has started playing. We use the fact that the duration changed.
	if (hasMP9 && "WIN98" == OS && state == 0 && duration != 0 && lastDuration == 0)
		result = true;
	}
   lastDuration = duration;
   if (result == false)
		gDuration = 0;
   return result;
}

function asfStop (fileName)
{
	if (!mainLoaded)
		return;
	initPlayer();
	if (GE_Streaming)
	{
		var result = ctrl().PC(PC_STREAM_WAVE,"","",STREAM_STOP);
		var result = ctrl().PC(PC_STREAM_WAVE,"0","",STREAM_SETCURRENTPOSITION);
		asfSetFileName('');
	}
	else
	{
		if (asfGetFileName() != '') {
			if (hasMP9)
				asfPlayer.controls.stop();
			else
				asfPlayer.Stop();
			asfSetCurrentPosition(0);
			asfSetFileName('');
		} 
	}
}

function asfStopOnly ()
{
	if (!mainLoaded)
		return;
	initPlayer();
	if (GE_Streaming) {
		var result = ctrl().PC(PC_STREAM_WAVE,"","",STREAM_STOP);
	} else {
		if (asfGetFileName() != '') {
			if (hasMP9)
				asfPlayer.controls.stop();
			else
				asfPlayer.Stop();
		} 
	}
}

function asfGetPlayState()
{
	if (!playerExists)
		return false;
	if (GE_Streaming)
		return ctrl().PC(PC_STREAM_WAVE,"","",STREAM_GETPLAYSTATE);
	else{
		if (hasMP9){
			var state = asfPlayer.playState;
				if (2 == state)
					return 1;
				else
				if (3 == state)
					return 2;
				else
					return 0;
			}
		else
			return asfPlayer.PlayState;
	}
}

function asfGetDuration()
{
	if (!playerExists)
		return 0;
	if (GE_Streaming) {
		var result = 0;
		result = result + ctrl().PC(PC_STREAM_WAVE,"","",STREAM_GETDURATION);

		if (result > 0)
			result = result / 1000;

		return result;
	} else{
		if (hasMP9){
			var objMedia = asfPlayer.currentMedia;
			if (objMedia == null)
				return 0;
			else
				return objMedia.duration;
		}
		else
			return asfPlayer.Duration;
	}
}

function asfGetFileName()
{
	if (!playerExists)
		return '';

	if (GE_Streaming) {
		if (savedfilename == "")
			return '';
		else
			//return 'http://209.0.28.99:80/content/' + savedfilename;
			return savedfilename;
	} else{
		if (hasMP9)
			return asfPlayer.URL;
		else
			return asfPlayer.FileName;
	}
}

function asfGetCurrentPosition()
{
    //Moved the variable declaration to global for this function Ref: Mantis Issue#: 18,8 - Shabeer - 25-Nov-2008
    var result = 0;
	if (!playerExists)
		return -1;
	if (GE_Streaming) {
		
		result = result + ctrl().PC(PC_STREAM_WAVE,"","",STREAM_GETCURRENTPOSITION);

		if (result > 0)
			result = result / 1000;

		return result;
	} else{
		if (hasMP9){
		    //If conddition added by shabeer Ref: Mantis Issue#: 18,8 - Shabeer - 25-Nov-2008
		    if(asfPlayer.controls.currentPosition)
		    {		    
			    return asfPlayer.controls.currentPosition;
			}
			else
			{
			    return result;
			}
		}
		else
			return asfPlayer.CurrentPosition;
	}
}

function asfSetCurrentPosition (pos)
{
	if (!playerExists)
		return;
	if (GE_Streaming) {	
		var pos_in_milliseconds = pos * 1000;
		var pos_str = "" + pos_in_milliseconds;
		ctrl().PC(PC_STREAM_WAVE,pos_str,"",STREAM_SETCURRENTPOSITION);
	} else {
		if (hasMP9)
		    //Added if condition for fixing the issue Ref: Issue# : 18,8 by Shabeer on 25-Nov-2009		    
		    if(asfPlayer.controls.currentPosition)
			asfPlayer.controls.currentPosition = pos;
		else
			asfPlayer.CurrentPosition = pos;
	}
}

function CONSOLE(str){
	java.lang.System.out.println(str);
}

function asfSetFileName (filename_part, relativePath)
{
	initPlayer();
	var nameStr = filename_part;
	var result = 0;
	var protocol_part = '';

	if (filename_part != '' && filename_part.indexOf('../template') < 0 && !relativePath) {
		var lower_case_filename = filename_part.toLowerCase();
		var where;

		where = lower_case_filename.indexOf('.asf',0) + 1; // Is this an asf file?

		if (where != 0)
	    		protocol_part = Ini.ASFPath;
		else
	    		protocol_part = Ini.WavPath;

		nameStr = protocol_part + filename_part;
	}
	if (GE_Streaming) {
		savedfilename = filename_part;
		var tempfn = "" + protocol_part + filename_part;
		if (filename_part  == "")
			tempfn = "";
		if (relativePath)
			tempfn = Ini.GlobalPath + filename_part;
		if (filename_part.toUpperCase().indexOf('HTTP://') >= 0)
		    tempfn = filename_part;
		result = ctrl().PC(PC_STREAM_WAVE, tempfn ,"",STREAM_SETFILENAME);
	} else {
		if (relativePath)
			nameStr = Ini.GlobalPath + filename_part;
		if (filename_part.toUpperCase().indexOf('HTTP://') >= 0)
		    nameStr = filename_part;
		if (hasMP9){
			asfPlayer.URL = nameStr;
		}
		else
			asfPlayer.FileName = nameStr;
	}
}

//var gfilename = '';
function asfPlaySafe (fileName, relativePath)
{
	if (!mainLoaded)
		return;

	initPlayer();
	if (!asfIsPlaying()) {
		if (asfGetFileName() == '' || asfGetCurrentPosition() == 0)
			asfSetFileName(fileName, relativePath);
		if (GE_Streaming) {
			ctrl().PC(PC_STREAM_WAVE,"",isIE ? "1" : "2",STREAM_PLAY);
		} 
		else{
/*			if (asfGetFileName().indexOf(fileName) < 0) {
				asfSetFileName(fileName, relativePath);
				gfilename = fileName;
			} else if (gfilename != '') {
				asfSetFileName(gfilename, relativePath);
				gfilename = ''
	
*/
			if (asfPlayer.HasError)	{
				if (fileName != "" && fileName != "undefined"){
					if (hasMP9 && asfPlayer.URL == "")
						asfSetFileName(fileName);
					else
					if (!hasMP9 && asfPlayer.FileName == "")
						asfSetFileName(fileName);
				}
				
				var url = document.location.href.toLowerCase();
				if (url.indexOf("audioalert") >= 0) 
					alert(asfPlayer.ErrorCode);
			}
			
			if (!(asfPlayer.HasError && (asfPlayer.ErrorCode == -2147220906 || asfPlayer.ErrorCode == -2147467259))){
				if (hasMP9)
					asfPlayer.controls.play();
				else
					asfPlayer.Play();
			}
		}
	}
}
var oldFileName = "";
function asfPlay (fileName, relativePath)
{
	if (!mainLoaded)
		return;

	var playIt = true;
	initPlayer(0);
	var curFileName = stripNasties(asfGetFileName());
	var newFileName = stripNasties(fileName);
	if (GE_Streaming)
	{
		curFileName = stripNasties(savedfilename);
		if (curFileName != '' && curFileName.indexOf (newFileName, 0) >= 0) {
			if (asfGetPlayState() == 2)
				playIt = false;
		}	   
		asfStop(fileName);
		if (playIt) 
			asfPlaySafe (fileName, relativePath);
	}
	else
	{
		if (curFileName != '' && curFileName.indexOf (newFileName, 0) >= 0) {
			var curPos = asfGetCurrentPosition();
			if (curPos > 0 && curPos < asfGetDuration())
			{
				playIt = false;
			}
		}
		asfStop(fileName);
		if (playIt) 
			asfPlaySafe (fileName, relativePath);
	}
	oldFileName = fileName;
}
function asfPlayRecordedVoice(fileName)
{
	initPlayer(0);
	if (forcePC()) {
		if (hasMediaPlayer)
			asfPlayer = p.getFrame(0).document.nsPlay;
		else
			wrtErrAlrt("Trying to play uploaded audio through Media Player but user does not have Media Player");
	}
	if (hasMP9){
		asfPlayer.URL = fileName;
		asfPlayer.controls.play();
	}
	else{
		asfPlayer.FileName = fileName;
		asfPlayer.Play();
	}
	setTimeout('waitForRecVoice()', 1000);
}
function waitForRecVoice()
{
	if (asfIsPlaying())
		setTimeout('waitForRecVoice()', 500);
}
function asfPlayAt (fileName, pos)
{
	if (!mainLoaded)
		return;
	initPlayer (0);
	asfSetCurrentPosition(pos);
	asfPlaySafe (fileName);
}

function asfPause ()
{
	if (!mainLoaded)
		return;

	initPlayer();
	if (GE_Streaming)
		ctrl().PC(PC_STREAM_WAVE,"","",STREAM_PAUSE);
	else {
			if (hasMP9){
				if (asfIsPlaying())
					asfPlayer.controls.pause();
			}
			else{
				if (asfIsPlaying())
					asfPlayer.Pause();
			}
	}
}

function asfPlayerPlay()
{
	initPlayer();
	if (GE_Streaming)
		ctrl().PC(PC_STREAM_WAVE,"",isIE ? "1" : "2",STREAM_PLAY);
	else{
		if (hasMP9)
			asfPlayer.controls.play();
		else
			asfPlayer.Play();
	}
}

function asfPlayerSetPauseTime(pause_time)
{
	if (GE_Streaming) {
		var pos_in_milliseconds = pause_time * 1000;
		var pos_str = "" + pos_in_milliseconds;
		ctrl().PC(PC_STREAM_WAVE,pos_str,"",STREAM_SET_PAUSE_TIME);
	}
}

function asrInstallLink()
{
	if(Obj.ClassId==6||Obj.ClassId==7) validExit=1;
	installComponents(SAPI);	
}

function initASRLink()
{
	if (!ctrlExists()) {
		setTimeout ('initASRLink()', 100);
		return;
	}

	if (!asrExists() && hasFeature(16) && hasFeature(42) && Obj.Special != 3) {
		if (isIE)
			getFrame(1).document.all.item('asrLink').innerHTML = getASRLink();
		else 
			getFrame(1).document.asrLink.visibility='visible';
	}

}

function stripNasties (str)
{
	if (str == '' || typeof str != 'string') 
		return str;

	var len = str.length;
	var s = "";
	for (var i = 0; i < str.length; i++) {
		var c = str.charAt(i);
		var add = true;
		if (c == ' ' && str.charAt(i+1) == ' ')
			add = false;
		else if (c == '\r' || c == '\n' || c == '\\' || c == '/')
			add = false;
		else if (c == '\"')
			c = '\'';

		if (add) 
			s += c;
	}
	return s;
}	

//SAFE PLAYING FOR AUDIO FILES
var AsfPlayerIsPlaying;
var AsfPlayerSafePlayStartTime;
function AsfPlayerSafePlay(strFileName) {
	if (null != strFileName) asfSetFileName(strFileName);
	asfPlayerPlay();
	AsfPlayerIsPlaying = false;
	AsfPlayerSafePlayStartTime = new Date();
}

function AsfPlayerSafeIsPlaying() {
	// If audio hasn't started playing then wait, timeout after 20 seconds
	if (!AsfPlayerIsPlaying) {
		AsfPlayerIsPlaying = asfIsPlaying();
		if (!AsfPlayerIsPlaying && (new Date()).getTime()-AsfPlayerSafePlayStartTime.getTime() > 20000) {
			return false;
		}
		return true;
	}
	// Audio is playing, check to to see if it's complete
	return asfIsPlaying();
}
