/**/
///	hostClientInit.js

var doorID;
var sPluginInstallationMessage;
var hostClientOBJ=0;
var debug = 0;
var hostUI;
var hostUIDoc;
var initiated=0;
var loaded = 0;

var is_nav;
var is_ie;
var is_mac;
var host;

var initTimeOut;
var initSleep;
var initLimit;
var initCounter;
var displayDiv;
var hostClientIEInstalled = 1;
var bIsVHSS = false;

// ready states

var RS_LOADED;

// Play states

var PS_PLAY;
var PS_STOP;
var PS_REC;

// flag for unsaved file
var isUnsaved=0;

var noClient=0;
var consoleService ;
var jsConsoleService ;

var debugWindow ;

function debugOut(str){
    if (debug==1){
    	if(!debugWindow || debugWindow.closed){
			debugWindow = window.open(sDocumentsDir + "pluginDebug.html","debugWindow","width=640,height=640,toolbar=no,scrollbars=auto,resizable=yes");
    	}
    	if(debugWindow){
    		var oDivElem = debugWindow.document.getElementById("debugDiv");
    		if(oDivElem)
    			oDivElem.innerHTML += str + "<br>\r\n";
    		
    	}else
		     alert(str);
    }
    //perc.innerText = str;
    //document.myForm.perc.value=str;
}

function callHostUILabel(sLabel){
	if(hostUI){
		//debugOut("Calling hostUI label - " + sLabel);
		hostUI.TCallLabel("/", sLabel);
	//}else{
	//	debugOut("hostUI not defined. not callin label " + sLabel);
	}
}

/// Mozilla installation functions

function xpinstallCallback(url, status)
{
	var msg;
	if (status == 0){
	   msg = "XPInstall Test:  "+url+" PASSED\n";
	   window.location.reload();
	}else{
	   msg = "XPInstall Test:  "+url+" FAILED with code "+status+"\n";
	   if(clientSideEditorExists==1){
       	 callHostUILabel( hostUIDoc.NOPLUGIN);
  		}

	}
	dump(msg);
	// alert(msg);
}

function InstallXPI2(){
	var xpi={'Oddcast Host plugin':pickupUrlSTR+'NPGeckoHost32.php'};
	var retval= 0;
	retval= InstallTrigger.install(xpi,xpinstallCallback);
	if(!retval){
		//alert("could not install plugin from " + pickupUrlSTR);
	   if(clientSideEditorExists==1){
       	 callHostUILabel( hostUIDoc.NOPLUGIN);
  		}
	}
	navigator.plugins.refresh(true);
//	

}
function InitMozillaConsole(){
	netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
	jsConsoleService = Components.classes['...@mozilla.org/consoleservice;1'].getService();
	jsConsoleService.QueryInterface(Components.interfaces.nsIConsoleService);
	jsConsoleService.logStringMessage('Set up logging.') 
}

function init(){
    debugOut('init()');


	// ready states
	RS_LOADED = 1;
	host = hostStr;
	if(0==doorID)
		doorID  = accountID;
	var pickupUrl = pickupUrlSTR;

	// Play states
	PS_PLAY = 1;
	PS_STOP = 2;
	PS_REC = 3;

	initSleep=100;
	initLimit=10;
	initCounter=0;

	var agt = navigator.userAgent.toLowerCase();
	is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
	       && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
	       && (agt.indexOf('webtv')==-1));
	is_ie   = (agt.indexOf("msie") != -1);
	
	is_mac = (agt.indexOf("mac") != -1);

	var sURL = document.location.href ;
	
	bIsVHSS = (sURL.indexOf("vh")!=-1);
	
	// CreateObjectCode(pickupUrl);


	hostUIDoc=parent.frames.hostUI;
	displayDiv = document.getElementById('perc');
		
	evalLayer();
	initWait();
	debugOut("client debug on");
	debugOut('init: done');

}

function initWait(){
    if (noClient==1){
	    debugOut("No client!");
        return;
    }

    if (loaded!=1 && is_nav && FindPlugin()){
        loaded=hostClientOBJ.getReadyState();
        //loaded=hostClientOBJ.ReadyState;
        debugOut("loaded= " + loaded);
    }

    if  ( (loaded==1) || (initLimit < initCounter++)) {
        window.clearTimeout(initTimeOut);
        /**/
        if (loaded==1) debugOut("loaded==1");
        else {
	        debugOut("initCounter="+initCounter+", initSleep="+initSleep+", loaded="+loaded);
	        evalLayer();
	        initCounter = 0;
	        initSleep = initSleep * 2;
	        initTimeOut = window.setTimeout("initWait();",initSleep);
	        return;
        }
        

        if(is_nav) {
            setUserid(accountID); // account id hook for NETSCAPE
			setTrackid(adminID); // admin id hook for NETSCAPE
        }else{

        }
        setHost(host);
        setDoorid(doorID);
		setAdminID(adminID);
		setAccountID(accountID);
        // build the mixer name vector

        hostClientOBJ.AddMixerName('Mix');
        hostClientOBJ.AddMixerName('Stereo Out');
        hostClientOBJ.AddMixerName('What U Hear');
        hostClientOBJ.AddMixerName('Loopback');
        hostClientOBJ.AddMixerName('Loop Back');
        hostClientOBJ.AddMixerName('Sum');
        hostClientOBJ.AddMixerName('�~�L�T?[');
        hostClientOBJ.AddMixerName('�~�b�N�X');
        hostClientOBJ.Init();

        // a workaround for netscape problem with live connect vs. windows race

        if (is_nav){
          //  ReadyStateChanged(RS_LOADED);
        }

    }//else 
    if (loaded!=1 /*&& is_nav*/){
//	    alert("setting timeout");
        initTimeOut = window.setTimeout("initWait();",initSleep);
     }/*else{
        NoClient();
     }*/
}
function reloadMe(){
	//document.location = document.location+" ";
	
	document.location.reload();
}

function installXPI(){
	 InstallTrigger.startSoftwareUpdate (pickupUrlSTR+"NPGeckoHost32.php");
}



function getCookie (name){
  debugOut('getCookie('+name+')');
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen)
  {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break; 
  }
  return null;
}

function getCookieVal (offset){
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1)	endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
var activeXInst;
var sInitPluginInstallationMessage = 'To enable microphone recording, please install our Plugin. Click OK to proceed';
// if there was a string previously defined - use it
if(sPluginInstallationMessage!=undefined)
	sInitPluginInstallationMessage = sPluginInstallationMessage;

function NoClient(){
   debugOut('No plugin');
   noClient=1;
	var notToInstallCookie = (debug?null:getCookie('noInstallActiveX'));
	
	if( notToInstallCookie==null ){
		var sInstallationPage = '';
		if(!is_mac){
			if(is_ie){
				sInstallationPage = 'activeXInstallation.html';
			}else if(is_nav ){
				sInstallationPage = 'GeckoPluginInstallation.html'; 
			}
		}
		if(sInstallationPage.length>0 && confirm(sInitPluginInstallationMessage)){
			sInstallationPage = sDocumentsDir + sInstallationPage;
			debugOut('opening ' + sInstallationPage);
			activeXInst = window.open(sInstallationPage,"activeXInst","width=600,height=320,toolbar=no,scrollbars=auto,resizable=no");
			if(activeXInst){
				activeXInst.focus();
				ok = waitForInstallationCompletion();
			}else{
				alert('Please deactivate all pop-up blocking software to allow Saving and Audio Recording.');
			}
		}else{
			callHostUILabel( hostUIDoc.NOPLUGIN);
		}
	}else{
		callHostUILabel( hostUIDoc.NOPLUGIN);
	}
}

function FlashNoClient(){
   debugOut('No plugin - Flash');
   noClient=1;
	var notToInstallCookie = (debug?null:getCookie('noInstallActiveX'));
	
	if( notToInstallCookie==null ){
		var sFlashUILabel = '';
		if(!is_mac){
			if(is_ie){
				sFlashUILabel = hostUIDoc.IE_INSTALLATION;
			}else if(is_nav ){
				sFlashUILabel = hostUIDoc.FIREFOX_INSTALLATION; 
			}
		}
		if(sFlashUILabel.length>0 && confirm(sInitPluginInstallationMessage)){
			callHostUILabel(sFlashUILabel);
			if(is_nav)
				InstallXPI2();
			//ok = waitForInstallationCompletionInFlash();
		}else{
			callHostUILabel( hostUIDoc.NOPLUGIN);
		}
	}else{
		callHostUILabel( hostUIDoc.NOPLUGIN);
	}
}


function NoFlashNoClient(){
   debugOut('No plugin - no Flash');
   noClient=1;
	var notToInstallCookie = (debug?null:getCookie('noInstallActiveX'));
	
	if( notToInstallCookie==null ){
		if(confirm(sInitPluginInstallationMessage)){
			//ok = waitForInstallationCompletionInFlash();
		}
	}
}

function waitForInstallationCompletion(){

	if(activeXInst&&!activeXInst.closed){
		setTimeout("waitForInstallationCompletion();",1000);
	}else{
    	var now = new Date();
	    now.setTime(now.getTime()+86400000); // set cookie expiration time in 1 day
		document.cookie = "noInstallActiveX=1; expires="+ now.toGMTString() + "; domain=oddcast.com";
		callHostUILabel( hostUIDoc.NOPLUGIN);
		return;
	}
}

function waitForInstallationCompletionInFlash(){

	if(activeXInst&&!activeXInst.closed){
		setTimeout("waitForInstallationCompletionInFlash();",1000);
	}else{
    	var now = new Date();
	    now.setTime(now.getTime()+86400000); // set cookie expiration time in 1 day
		document.cookie = "noInstallActiveX=1; expires="+ now.toGMTString() + "; domain=oddcast.com";
		callHostUILabel( hostUIDoc.NOPLUGIN);
		return;
	}
}

// *** do browser specific stuff

function evalLayer() {
    debugOut('evalLayer');

    if(is_nav) {

 //       initSleep=100;
        initLimit=10;
        initCounter=0;
        
        // sitepal
        if(hostUIDoc!=undefined){
        	hostUI=eval('hostUIDoc.document.vhss_bhe');
        	
	        if(!hostUI) // workshop
	        	hostUI=eval('hostUIDoc.document.hostMov');
	
			// installation message 
			if(hostUIDoc.sPluginInstallationMessage!=undefined)
				sInitPluginInstallationMessage = hostUIDoc.sPluginInstallationMessage;
    	}


        if (! isEmbedObjReady() ){
	        debugOut("no plugin found");
 	        InstallXPI2();
			if(bIsVHSS){
				if(clientSideEditorExists)
					FlashNoClient();
				else
					NoFlashNoClient();
			}else
	            NoClient();
            //reloadMe();
            return;
        }else{
            hostClientOBJ = eval("document.hostCntrlNS");
            //alert("hostClientOBJ="+hostClientOBJ );
        }
    }else{
		var vHostDoc ; // undefined
        if(hostUIDoc!=vHostDoc){
   	   		hostUI=eval('hostUIDoc.vhss_bhe');
	        if(!hostUI) // workshop
	        	hostUI=eval('hostUIDoc.hostMov');
			// installation message 
			if(hostUIDoc.sPluginInstallationMessage!=vHostDoc)
				sInitPluginInstallationMessage = hostUIDoc.sPluginInstallationMessage;
       }
        // check that the plugin object is defined
        
	    debugOut('document.all.karCntrlIE = ' + document.all.karCntrlIE);
        if (! document.all.karCntrlIE || !hostClientIEInstalled){
			if(bIsVHSS){
				if(clientSideEditorExists)
					FlashNoClient();
				else
					NoFlashNoClient();
			}else
	            NoClient();
            return;
        }else{
            hostClientOBJ = eval('document.all.karCntrlIE');
            // prod it to fire an event
            //hostClientOBJ.Stop();
            debugOut("ready state is " + hostClientOBJ.ReadyState);
        }
    }
}

function CreateObjectCode(sPickupURL){
	if (window.ActiveXObject)
	{
	
	// browser supports ActiveX
	// Create object element with 
	// download URL for IE OCX
	
	document.write('<OBJECT CLASSID="CLSID:72C9EA8F-8965-40C2-ABAD-D460A5815F86"');
	document.write(' CODEBASE="'+sPickupURL);
	document.write('hostClientIE.cab#version=1,6,2,0"');
	document.write(' WIDTH=1 HEIGHT=1 ID="karCntrlIE">');
	document.write('<SCRI'+'PT LANGUAGE="JavaScript">hostClientIEInstalled = 0;</SCRIP'+'T>');
	document.write('<\/OBJECT>');
	
	}
	
	else
	{
	
	// browser supports Netscape Plugin API
	
	document.write('<OBJECT id="hostCntrlNS" name="hostCntrlNS"');
	document.write(' type="application/x-Netscape-Windows-Oddcast-Host-Plugin"');
	document.write(' codebase="'+sPickupURL);
	document.write('NPGeckoHost32.php"');
	document.write(' width="1" height="1">');
	document.write('<p><a href="javascript:InstallXPI2();" > Click here to install the VHost plugin (to add saving and recording features).</a></p>');
	document.write('<\/OBJECT>'); 
	
	}
}

function isEmbedObjReady()
{
	return FindPlugin();
}

function FindPlugin(){
	var i = 0;
	navigator.plugins.refresh(true);
	for (i=0; i < navigator.plugins.length; i++) {
		if( (navigator.plugins[ i] != null) ) {
			if(navigator.plugins[ i].filename.toLowerCase().indexOf("npgeckohost32")>-1){
				debugOut("found "+ navigator.plugins[ i].filename);
				return true;
			}
		}
		
	}
	return false;
}
//****** API PROPERTIES SET FUNCTIONS

function setUserid(userID){
    //alert('IN setUserid: '+userID);
    if(is_nav) {
        hostClientOBJ.setUserID(userID);
    }else{
        hostClientOBJ.userid=userID-0; // cast to int
    }
    debugOut('OUT setUserid');
}
function setHost(sHost){
   debugOut('IN setHost: '+sHost);
	if(is_nav) {
        hostClientOBJ.setHost(sHost);
	}else{
        hostClientOBJ.host=sHost;
	}

	debugOut('OUT setHost');
}


function setDoorid(door_ID){
   debugOut('IN setDoorid: '+door_ID);
	if(is_nav) {
		hostClientOBJ.setDoorID(door_ID);
	}else{
		hostClientOBJ.doorid=door_ID-0; // cast to int
	}
	debugOut('OUT setDoorid');
}

function setTrackid(trackID){
    debugOut('IN setTrackid: '+trackID);
    if(is_nav) {
        hostClientOBJ.setTrackID(""+trackID);
    }else{
        hostClientOBJ.trackid=trackID-0;// cast to int
    }
    debugOut('OUT setTrackid');
}

function setClientid(clientID){
    debugOut('IN setClientid: '+clientID);
    if(is_nav) {
        hostClientOBJ.setClientID(clientID);
    }else{
        hostClientOBJ.client=clientID-0;// cast to int
    }
    debugOut('OUT setClientid');
}

function setContest(contest){
    debugOut('IN setContest: '+contest);
    if(is_nav) {
        hostClientOBJ.setContest(contest);
    }else{
        hostClientOBJ.contest=contest-0;
    }
    debugOut('OUT setContest');
}

function setStrVar(strVar){
    debugOut('IN setStrVar: '+strVar);
    if(is_nav) {
        hostClientOBJ.setStrVar(strVar);
    }else{
        hostClientOBJ.strVar=strVar;
    }
    debugOut('OUT setStrVar');
}

function setAdminID(admin_id){
    debugOut('IN setAdminID: '+admin_id);
    if(is_nav) {
        hostClientOBJ.setAdminID(admin_id);
    }else{
        hostClientOBJ.AdminID=admin_id-0;
    }
    debugOut('OUT setAdminID');
}

function setAccountID(account_id){
    debugOut('IN setAccountID: '+account_id);
    if(is_nav) {
        hostClientOBJ.setAccountID(account_id);
    }else{
        hostClientOBJ.AccountID=account_id-0;
    }
    debugOut('OUT setAccountID');
}

function setNormalization(normalization){
    debugOut('IN setNormalization: '+normalization);
    if(is_nav) {
        hostClientOBJ.setNormalization(normalization);
    }else{
        hostClientOBJ.Normalization=normalization;
    }
    debugOut('OUT setNormalization');
}


function ReadyStateChanged(state){
    debugOut('ReadyStateChanged IN ' + state);
    loaded=1;
    if (state==RS_LOADED){
        debugOut('ReadyStateChanged:ready');
        debugOut('hostClientOBJ = '+hostClientOBJ);
        if (! hostClientOBJ){
            debugOut('NO hostClientOBJ');
            return;
        }
	    debugOut("clientSideEditorExists = " + clientSideEditorExists );
	    if( clientSideEditorExists)
       	 	callHostUILabel( hostUIDoc.LOADED);
        debugOut('ReadyStateChanged: done');
    }else
        debugOut('ReadyStateChanged:'+state);
}
