var _PROBLEM_REPORTED = false;

function sysLog(message){
    if(IS_DEBUG){
       console.log(message);
    }
}

function initBandwidthParameters(serverFilePath, serverPHPath){
    document.vueliveapplet.initBandwidthParameters(serverFilePath, serverPHPath);
}

function registerBandwidthEvents(downloadBandwidthNotify, uploadBandwidthNotify){
    document.vueliveapplet.registerBandwidthEvents(downloadBandwidthNotify, uploadBandwidthNotify);
}

function determineBandwidth(){
	   document.vueliveapplet.determineBandwidth();
}

function findDownBandwidth(){
    document.vueliveapplet.findDownBandwidth();
}
	
function findUpBandwidth(){
    document.vueliveapplet.findUpBandwidth();
}
function downloadBandwidthNotify(timeDiffMillisecs, filesize){
    if(typeof waitTillSysVerifyDone !== "undefined" && waitTillSysVerifyDone){
        return;
    }
    if(arguments.length === 1){
        //It must be an error
        if(document.getElementById("bandwidth-error") !== null){
            document.getElementById("bandwidth-error").innerHTML = " Download speed can\'t be determined <br/>"+
            arguments[0];
            document.getElementById("bandwidth-error").style.visibility = "visible";
            document.getElementById("bandwidth-error").style.display = "";
            return;
        }
        _PROBLEM_EXISTS = true;
    }
    var downspeed = ((filesize/timeDiffMillisecs)*1000)/1024;
    var dnbandwidth = downspeed * 8; //bandwidth in Kbps
    var dnbandwidthMbps = dnbandwidth/1024; //bandwidth in Mbps
    var strdnbandwidth = "Unknown";
    if(dnbandwidthMbps > 1)
    {
        strdnbandwidth = (dnbandwidthMbps).toFixed(2) + ' Mbps';
    }
    else
    {
        strdnbandwidth = (dnbandwidthMbps*1024).toFixed(2) + ' Kbps';
    }
    if(document.getElementById('down-percentage-bar') !== null){
        document.getElementById('downloadDiv').style.width = "100%";
        document.getElementById('down-percentage-bar').innerHTML = "" + strdnbandwidth;
    }
    /*if(document.getElementById("stopDownload") !== null){
        document.getElementById("stopDownload").style.visibility = "hidden";
        document.getElementById("stopDownload").style.display = "none";
    }
    if(document.getElementById("downloadAnalysisId") !== null){
       document.getElementById("downloadAnalysisId").innerHTML = analyzeDownload(dnbandwidth);//in Kbps
    }*/
}

function uploadBandwidthNotify(timeDiffMillisecs, filesize){
	//alert(timeDiffMillisecs + " "+filesize)
	startUploadDownload =0;
	if(document.getElementById("cancelDiv")!=null)
		document.getElementById("cancelDiv").style.display= "none";
    if(typeof waitTillSysVerifyDone !== "undefined" && waitTillSysVerifyDone){
        if(document.getElementById('statusImg') !== null){
            document.getElementById('statusImg').src="../uploader/images/uploader.gif";
        }
        //Report it only once
        if(typeof(isReported) === "undefined"){
            report(confId,attName);
        }
        return;
    }
     if(arguments.length === 1){
        //It must be an error
        if(document.getElementById("bandwidth-error") !== null){
            document.getElementById("bandwidth-error").innerHTML = " Upload speed can\'t be determined <br/>"+
            arguments[0];
            document.getElementById("bandwidth-error").style.visibility = "visible";
            document.getElementById("bandwidth-error").style.display = "";
            return;
        }
        _PROBLEM_EXISTS = true;
    }
    var upspeed = ((filesize/timeDiffMillisecs)*1000)/1024;
    var upbandwidth = upspeed * 8; //bandwidth in Kbps
    var upbandwidthMbps = upbandwidth/1024; //bandwidth in Mbps
    var strupbandwidth = "Unknown";
    if(upbandwidthMbps>1)
    {
        strupbandwidth = (upbandwidthMbps).toFixed(2) + ' Mbps';
    }
    else
    {
        strupbandwidth = (upbandwidthMbps*1024).toFixed(2) + ' Kbps';
    }
    if(document.getElementById('up-percentage-bar')!== null){
        document.getElementById('uploadDiv').style.width = "100%";
        document.getElementById('up-percentage-bar').innerHTML = "" + strupbandwidth ;
    }
    enableReportProblem();

}
/*Not in use*/
function analyzeDownload(dspeed){
   var _users = parseInt(dspeed)/300;
   var analysis = "";
   if (_users >= 10){
       analysis = "Based on the download speed test, You have sufficient Bandwidth to receive 10 participants and a desktop window. "+
           "<b>Note</b>: running other applications that use bandwidth could reduce this number.";
   }else if(parseInt(_users) < 1){
       analysis = "You don't seem to have enough bandwidth to be in a conference.";
       if(document.getElementById('bandwdthimgpass')!== null){
        document.getElementById("bandwdthimgpass").style.visibility = "hidden";
        document.getElementById("bandwdthimgpass").style.display = "none";
    }
    if(document.getElementById('bandwdthimgfail')!== null){
        document.getElementById("bandwdthimgfail").style.visibility = "visible";
        document.getElementById("bandwdthimgfail").style.display = "";
    }
   }
   else if(parseInt(_users) === 1){
       analysis = "Based on the download speed test, You have sufficient Bandwidth to receive a participant or a desktop window."+
                   "<b>Note</b>: running other applications that use bandwidth could reduce this number.";
   }
   else{
       analysis = "Based on the download speed test, You have sufficient Bandwidth to receive " + parseInt(_users-1) + " participants and a desktop window."+
                   "<b>Note</b>: running other applications that use bandwidth could reduce this number.";
   }
   return analysis;
}
/*Not in use*/
function analyzeUpload(uspeed){
    var analysis = "";
    if(parseInt(uspeed) > 400){
       analysis = "Based on the upload speed test, You have sufficient Bandwidth to broadcast your camera and share a desktop application."+
                "<b>Note</b>: running other applications that use bandwidth could reduce this number.";
   }else {
       analysis = "You don't seem to have enough bandwidth to broadcast at this time.";
       if(document.getElementById('bandwdthimgpass')!== null){
        document.getElementById("bandwdthimgpass").style.visibility = "hidden";
        document.getElementById("bandwdthimgpass").style.display = "none";
    }
    if(document.getElementById('bandwdthimgfail')!== null){
        document.getElementById("bandwdthimgfail").style.visibility = "visible";
        document.getElementById("bandwdthimgfail").style.display = "";
    }
   }
   return analysis;
}

var start = 0;
function updateUploadDownloadProgress(type, data){
    if( document.getElementById('up-percentage-bar') !== null ||
        document.getElementById('down-percentage-bar') !== null){
        start = data;  //expect an int
        if (document.getElementById) {
            o = (type === "upload") ?document.getElementById("up-percentage-bar") : document.getElementById("down-percentage-bar") ;
            if (start <= 100) {
                //setWidth(o, start);
                //Show progression percentage near the progress bar
                if(type === "upload"){
                    document.getElementById('up-percentage-bar').innerHTML = (start/5)*5 + "%";
                    document.getElementById('uploadDiv').style.width= start+"%";
                }
                else{
                    document.getElementById('down-percentage-bar').innerHTML = (start/5)*5 + "%";
                    document.getElementById('downloadDiv').style.width= start+"%";
                }
                start += 1;
            }
        }
    }
}
 
function setWidth(o, start) {
    if(o !== null){
        o.style.width = start+"%";
    }
}



function vueliveApplet_appletLoadNotify(){
   
	
    var loadString = arguments[0];
   
    if(loadString == "ACCESS_CONTROL_EXCEPTION"){
    	access_error=true;
    	document.getElementById("textMessage").style.display = "";
		document.getElementById("textMessage").innerHTML=access_error_msg;
	}else{
	    var instJreVer = arguments[1];
	    if(instJreVer.indexOf('-') != -1)
	    	instJreVer = instJreVer.substring(0,instJreVer.indexOf('-'));
	    
	    if(loadString == "APPLET_LOAD_TRUE" && safariJREVerionCheck(instJreVer) == true)
	    {
	    	isAppletLoaded = 1;
	    	initGblVars();
	    	disableReportProblem();
	    	startSystemInfo("|$|", "SystemInfo_getData", "systemInfo/SystemData.exe");
	    }
	}
}

function safariJREVerionCheck(instJreVer)
{
	var blResult = true; 
	if(SystemInfo.getBrowserName()=="Safari" || SystemInfo.getOSName()=="MacOS") {

		var jjrree = jreVer;
		if(SystemInfo.getOSName()=="MacOS")	
			jjrree = jreMacVer;

		
		if(!deployJava.versionCheckForSafari(jjrree+'+',instJreVer))
		{
			document.getElementById("JavaEnabledMark").style.display = "";
			document.getElementById("BrowserMark").style.display = "";
			document.getElementById("platMark").style.display = "";
			document.getElementById("textMessage").style.display = "";
			document.getElementById("textMessage").innerHTML="*Need to have latest JRE version with java enabled to calculate RAM, CPU and bandwidth.";

			document.getElementById("systemRAMDiv").innerHTML = "------";
			document.getElementById("systemCPUDiv").innerHTML = "------";
			    document.getElementById("webBrowserDiv").innerHTML = SystemInfo.getBrowserName()+" (version:"+SystemInfo.getBrowserVersion()+")";
			document.getElementById("systemPlatformDiv").innerHTML = SystemInfo.getOSName();
		
			if(!SystemInfo.isBrowserSupport())
				document.getElementById("BrowserMark").src= "images/cross_img.png";
			
			if(!SystemInfo.isOSSupport())
				document.getElementById("platMark").src= "images/cross_img.png";
			
			if(deployJava.appletLoad=="Yes") {
						document.getElementById("isJavaEnabledDiv").innerHTML = "No";
						_JAVA_PASSED = false;
						document.getElementById("versionJREDiv").innerHTML = "------";
						
						document.getElementById("JavaEnabledMark").src= "images/cross_img.png";
					//	document.getElementById("JreVersionMark").src= "images/cross_img.png";
			}
			else {
						document.getElementById("JreVersionMark").style.display = "";
						_JRE_PASSED = false;
						document.getElementById("isJavaEnabledDiv").innerHTML = "Yes";
						document.getElementById("versionJREDiv").innerHTML = "Older version (<span class=\"smallariallink fntbold\" onclick=\"installJre();\">install latest</span>)";
						document.getElementById("JreVersionMark").src= "images/cross_img.png";
			}
			verifyConnections();
			enableReportProblem();
			blResult = false;
		}
	}
	return blResult;
}

function startSystemInfo(endTerminator,systemDataNotify,systemInfoEXEPath){
    document.vueliveapplet.registerSystemInfoEvents(endTerminator,systemDataNotify);
initBandwidthParameters("../attach/", "../php/");
    document.vueliveapplet.initSystemInfoParameters(/*systemInfoEXEPath*/);
    document.vueliveapplet.getSystemInfo();
}

function startSystemBandwidth(downloadBandwidthNotify, uploadBandwidthNotify){
    if(document.getElementById("bandwidthTestRaw") != null){
        document.getElementById("bandwidthTestRaw").style.visibility= "visible";
        document.getElementById("bandwidthTestRaw").style.display = "";
    }
    registerBandwidthEvents(downloadBandwidthNotify, uploadBandwidthNotify);
    determineBandwidth();
    /*findDownBandwidth();
    findUpBandwidth();*/
}

function SystemInfo_getData(){
	
    sysLog(["Java called with argument :" , arguments]);
    
    var systemData = arguments[0];
    if(systemData === "UNKNOWN" || systemData === ""){
        printEnvironmentValues("UNKNOWN");
    }
    else{
		var webBrwserName = "";
		var webBrwserVers = "";
		webBrwserName = SystemInfo.getBrowserName();
		webBrwserVers = SystemInfo.getBrowserVersion();
		webBrowser = webBrwserName+" (version:"+webBrwserVers+")";
		
	    var sysArray = systemData.split('|#|');
	    var newsysArray = new Array();
	    for (var key in sysArray)
	    {
	        var retVal = new Array();
	        retVal =	sysArray[key].split("=");
	        var retValKey = retVal[0];
	        retValKey = retValKey.replace('|$|','');
	        var retValValue = retVal[1];
	        newsysArray[retValKey] = retValValue;
			
	    }
	
	    var ram = newsysArray["RAM"];
	    var cpu = newsysArray["CPU"];
	    var os = newsysArray["OS"];
  //alert(os); debugger;
	    os = os.replace('?', '');
	    os = os.replace('?', '');
	    os = os.replace('?', '');
		
	    var jv = newsysArray["JAVA"];
	    
	    printEnvironmentValues(ram, cpu, os, jv);
    }
     sysLog("now showBrowserDetails");
    showBrowserDetails();
     sysLog("now testEjabberConnection");
     verifyConnections();
     sysLog("now startSystemBandwidth");
    startSystemBandwidth("downloadBandwidthNotify", "uploadBandwidthNotify");
	
}


function printEnvironmentValues(ram, cpu, os, jv)
{
	//alert("ram : "+ ram + "  CPU : " + cpu + "  OS : " + os);
	
	if(arguments.length === 1){
		/*need to complete this task*/
        ram = cpu = os = jv ="UNKOWN";
    }
	var systemPlatform = ""+trim(os)+"";
	var arrSysPlat = systemPlatform.split(" ");
	
	if(arrSysPlat[0]=="Mac") {
		systemRAM = ram;
		systemCPU = cpu;
	}
	else {
		systemRAM = (parseFloat(ram)/(1024*1024*1024)).toFixed(2);
		systemRAM = systemRAM+" GB";
		systemCPU = cpu;
		
		systemCPU = Number(systemCPU).toFixed(2);
		systemCPU = systemCPU +" GHz";
	}

	versionJRE = jv + " detected";
	isJavaEnabled = SystemInfo.checkJavaEnabled();
	isJavaEnabled = ((isJavaEnabled=='true' || isJavaEnabled==true)?'Yes':'No');


	if(document.getElementById("systemPlatformDiv")!=null) {
		document.getElementById("systemPlatformDiv").innerHTML = systemPlatform;
	}
	document.getElementById("systemRAMDiv").innerHTML = systemRAM;
	displayRAMResultImg(systemRAM, systemPlatform);
	
	document.getElementById("systemCPUDiv").innerHTML = systemCPU;
	displayCPUResultImg(systemCPU);
	
	document.getElementById("isJavaEnabledDiv").innerHTML = isJavaEnabled;
	document.getElementById("JavaEnabledMark").src= "images/checkMark.png";
	document.getElementById("versionJREDiv").innerHTML = versionJRE;
	document.getElementById("JreVersionMark").style.display = "";
	document.getElementById("JreVersionMark").src= "images/checkMark.png";
}

function showBrowserDetails()
{
	var webBrwserName = "";
	var webBrwserVers = "";
	webBrwserName = SystemInfo.getBrowserName();
	webBrwserVers = SystemInfo.getBrowserVersion();
	webBrowser = webBrwserName+" (version:"+webBrwserVers+")";
	document.getElementById("webBrowserDiv").innerHTML = webBrowser;
}

function displayRAMResultImg(ram, os)
{
	var ram = ""+trim(ram)+"";
	var ramVal = ram.substring(0, ram.indexOf(" "));
	var res = 0;
	if(os == "Mac OS X"){
		//res = SystemInfo.CompareVersions(ramVal, MIN_MAC_RAM);
                res = (Number(ramVal) >= MIN_MAC_RAM)? 1:0;
	}
	else {
		//res =  SystemInfo.CompareVersions(ramVal, MIN_RAM);
                res = (Number(ramVal) >= MIN_RAM)?1:0;
	}
	document.getElementById("RAMMark").style.display = "";
	if(res==0) {
		document.getElementById("RAMMark").src = "images/cross_img.png";
		_PROBLEM_EXISTS = true;
	} 
}


function displayCPUResultImg(cpu)
{
	cpu = ""+trim(cpu)+"";
	var cpuVal = cpu.substring(0, cpu.indexOf(" "));
	var res = 0;
//	res = SystemInfo.CompareVersions(cpuVal, MIN_CPU);
        res = (Number(cpuVal)>= MIN_CPU)  ?1 : 0;
	document.getElementById("CPUMark").style.display = "";
	if(res==0) {
		document.getElementById("CPUMark").src = "images/cross_img.png";
		_PROBLEM_EXISTS = true;
	} 
}

/*****Connection check*******/


function makeJConnectionVerify(jServerAddress, jServerPort){

    sysLog("Ejabber test on :" + jServerAddress + " and port :" + jServerPort);
    var isConn = document.vueliveapplet.makeConnectionVerification(jServerAddress, jServerPort);
    if(isConn.toString() == "true"){isConn = true;}else{isConn = false;}
    return isConn;
}



/***********************************************************************/


/*Logger related functions*/

var uploadLoggerAppletReady = false;

function loggerAppletLoadNotify(){ 
	
	if(arguments.length > 0){
    	_LOGGER_APPLET_VALUE = arguments[0];
        if(arguments[0] === "FILE_UPLOADER_READY"){
        	 
            
        }else if(arguments[0] === "SERVER_URL_INVALID"){
            alert("Upload Server url is invalid.");
        }else if(arguments[0] == "ACCESS_CONTROL_EXCEPTION"){
        	access_error=true;
        	document.getElementById("textMessage").style.display = "";
    		document.getElementById("textMessage").innerHTML=access_error_msg;
	}
    }
	
}

function loggerFinished(){
	if(_PROBLEM_REPORTED == false)
	{
		_PROBLEM_REPORTED = true;
		if(isAppletLoaded == 0)
			reportAProblemCompleted();
	}
	else
		reportAProblemCompleted();
}

function loggerErrored(){
	if(arguments.length >0) {
		//alert(arguments[0]);
		}
	else{
		alert("One or more log files may not have been saved on our server properly.");
	}
}

function reportAProblemCompleted()
{
	var strHtml = 'Your problem has been reported. Thank You.';
	document.getElementById('userInfoSubmitDiv').innerHTML = strHtml;
}

/*Not in use*/
function report(){

        var arg1 = null;
        var arg2 = null;
        if(arguments.length == 2 ){
            arg1 = arguments[0];
            arg2 = arguments[1];
           }
        document.loggerapplet.startUpload(arg1,arg2);
}



/*Utility functions*/
function stripAlphaChars(pstrSource) 
{ 
	var m_strOut = new String(pstrSource); 
    m_strOut = m_strOut.replace(/[^0-9.]/g, ''); 

    return m_strOut; 
}

function trim(stringToTrim) {
	if(typeof(stringToTrim)=="string")
		return stringToTrim.replace(/^\s+|\s+$/g,"");
	else
		return stringToTrim;
}

function installJre()
{
    var attributes = { style:"left:-1px;top:-1px;visibility:hidden;height:0px;",
					  visible:"false",
					  codebase:'jar/',
                      code:'com.oac.main.CheckOACInstance.class',
                      name:'OpenACircleAssistant',
                      id:'OpenACircleAssistant',
				      width:'0px',
					  height: '0px',
					  border: '0',
					  archive:"SCheckOACInstance.jar, SOACPlugin.jar",
					  MAYSCRIPT:'true',
                      width:0, height:0} ;
    var parameters = {scriptable:'true',eval_start_exit:'openACircleAssistantInstalled'} ;

	if(SystemInfo.getOSName()=="MacOS")
	   	deployJava.runApplet(attributes, parameters, jreMacVer);
	else
	   	deployJava.runApplet(attributes, parameters, jreVer);
}

