
//*******************************************************************************
//*  Abacast ADSP JavaScript Functions
//*  Implements Abaclient Control via WebScripting
//*
//* Copyright (c) 2001, 2002 Abacast, Inc. All rights reserved.
//* Author: J Morris
//* Version 1.10
//*
//* Modified 08/28/2002 -- Added Embedded WMP Context menu to Right Click
//* Modified 08/14/2002 -- Moved Stor_url's to ClickToListen for reverse compat.
//* Modified 08/13/2002 -- Added Cab downloads for IE users
//* Modified 08/05/2002 -- Modified Auto-Launch procedure for faster start times.
//* Modified 07/24/2002 -- Fixed NS Download bug.  Embedded window now starts stream
//                         For onClick streams too.
//* Modified 07/23/2002 -- Fixed embed bug that always forced status bar to show 
//                         & Player Control Sizes.
//* Modified 07/22/2002 -- Contains embedded player controls for Abaserv 1.10.
//* Modified 06/23/2002 -- added seperate NS and IE Prompts.
//* Modified 06/05/2002 -- added port to download filename.
//******************************************************************************


///////////////////////////////////////////////////////////////////////
/////////////////////////  ALERT TEXT  ////////////////////////////////

var aba_alert_noClient   = 'Before the stream can begin, you will need to download \n'+ 
                           'and install the Abacast streaming media software. Please\n'+
                           'click OK below to download the current Abacast software.';

var aba_alert_noClientIE = 'Before the stream can begin, you will need to download \n'+ 
                           'and install the Abacast streaming media software. Please\n'+
                           'click OK below, then choose OPEN or RUN FROM LOCATION to\n'+
			     		   'install the current Abacast software.';

var aba_alert_noClientNS = 'Before the stream can begin, you will need to download \n'+ 
                           'and install the Abacast streaming media software. Please\n'+
                           'click OK below, then SAVE to download the current Abacast software.\n'+
						   'Choose your desktop as the location to save to.  Once the setup\n'+
						   'program is downloaded to your desktop, double click it to install.';
					   
var aba_alert_WrongOS   =  'Abacast streaming media software currenly \n'+
                           'only supports the Windows Operating System.';

var aba_alert_WrongBrow =  'The Abacast streaming media software currently Supports \n'+
                           'MS Internet Explorer and Netscape Browsers versions 4.0+.\n'+
                           'Please update your browser to listen to the Abacast Stream.';

var aba_alert_MacNoWMP =   'Before the stream can begin, you must first download   \n' +
                           'and install Windows Media Player for Mac. Please go to \n' +
                           'http://windowsmedia.com/download to get Media Player for Mac.';
					 
var aba_alert_MacNoSupport='Abacast is committed to Macintosh users.  Development' +
                           'of a Macintosh client is planned, but not yet complete.' +
                           'Thank you for your patience.';

var aba_alert_NOWMPNS =    'Your Browser does not support this Embedded Windows Media Player.\n'+
                           'A Stand-Alone media player will now open';


///////////////////////////////////////////////////////////////////////
//////////////////////  GLOBAL VARIABLES  /////////////////////////////
var aba_Is_Embedded   = false;
var aba_ScriptLoaded  = true;
var CABDownloadFailed = false;
var stor_url     = null;
var stor_station = null;
var stor_embed   = null;

///////////////////////////////////////////////////////////////////////
////////////// Browser, OS and WMP Detection Code /////////////////////

var aba_CSAg = window.navigator.userAgent;
var aba_agt = navigator.userAgent.toLowerCase();
var aba_appVer = navigator.appVersion.toLowerCase();
var aba_iePos  = aba_appVer.indexOf('msie');
var aba_is_ie   = (aba_iePos!=-1);
var aba_is_win   = ( (aba_agt.indexOf("win")!=-1) || (aba_agt.indexOf("16bit")!=-1) );
var aba_is_win95 = ((aba_agt.indexOf("win95")!=-1) || (aba_agt.indexOf("windows 95")!=-1));
var aba_is_minor = parseFloat(aba_appVer);
var aba_is_major = parseInt(aba_is_minor);
var aba_is_Netscape = (navigator.appName); //returns 'Netscape' if true
var aba_nav6Pos = aba_agt.indexOf('netscape6');
var aba_is_nav = ((aba_agt.indexOf('mozilla')!=-1) && (aba_agt.indexOf('spoofer')==-1)
                && (aba_agt.indexOf('compatible') == -1) && (aba_agt.indexOf('opera')==-1)
                && (aba_agt.indexOf('webtv')==-1));
var aba_is_navonly = (aba_is_nav && ((aba_agt.indexOf(";nav") != -1) || (aba_agt.indexOf("; nav") != -1)) );
if (aba_nav6Pos !=-1) {
       aba_is_minor = parseFloat(aba_agt.substring(aba_nav6Pos+10))
       aba_is_major = parseInt(aba_is_minor)
}
var aba_is_nav6up = (aba_is_nav && aba_is_minor >= 6);
var aba_is_opera = (aba_agt.indexOf("opera") != -1);
var aba_is_mac    = (aba_agt.indexOf("mac")!=-1);
var aba_is_ie4   = (aba_is_ie && aba_is_major == 4);


// Check for MP 6.4 in NS
var WMP64_ns = navigator.mimeTypes && navigator.mimeTypes["video/x-ms-wm"] &&  
				navigator.mimeTypes["video/x-ms-wm"].enabledPlugin && 
				navigator.mimeTypes["video/x-ms-wmv"] && 
				navigator.mimeTypes["video/x-ms-wmv"].enabledPlugin;
				
// Check for MP 7.0 in NS
var WMP70_ns = navigator.mimeTypes && navigator.mimeTypes["video/x-ms-wm"] &&  
				navigator.mimeTypes["video/x-ms-wm"].enabledPlugin && 
				navigator.mimeTypes["video/x-ms-wmv"] && 
				navigator.mimeTypes["video/x-ms-wmv"].enabledPlugin && 
				navigator.mimeTypes["application/x-ms-wms"];

// IE & NS for MAC
var MACHasWMP = navigator.mimeTypes && navigator.mimeTypes["application/x-mplayer2"] && 
				navigator.mimeTypes["application/x-mplayer2"].enabledPlugin;
function aba_CheckMPInstall(){				
	if( WMP64_ns ) abaDebug ('WMP 64 detected');
	if( WMP70_ns ) abaDebug ('WMP 70 detected');
	if ( MACHasWMP ) abaDebug('MAC HAS WMP');
}

///////////////////////////////////////////////////////////////////////
////////////////////////// Misc Functions /////////////////////////////

// Returns true for supported AOL as well.
function aba_IsIE() { 
	if (aba_is_ie && !(aba_is_opera)){
		return true;
	}
	else return false;
}


/* NS & IE Client Installation Detector */
function aba_IsClientInstalled(){
	if(aba_IsIE()){
		VB_Abacheck();
		if(IsInstalled) return true;
		else return false;
	}
	if(aba_is_nav){
		navigator.plugins.refresh(false);
		if ( navigator.plugins["Abacast"] ) return true;
		else return false;
	}
}

var abaDEBUG=false;
var abaDebugOpen=false;
function abaDebug(szMsg){
	if (!abaDEBUG) return;
	if (!abaDebugOpen) { // open window and write style tag
		DebugWind=window.open("", "aba_debug", 'width=200,height=800,toolbar=no,scrollbars=yes,location=no,directories=no,resizable=yes,top=180,left=2');
		DebugWind.document.close(); 
		DebugWind.document.writeln("<STY"+"LE> BODY {background: #000033; color: #00FF33;} </ST"+"YLE>");
		abaDebugOpen=true;
	}
	if( DebugWind.closed ){ abaDebugOpen=false; abaDebug(szMsg); return;}
	DebugWind.document.writeln(szMsg + "<br><hr>"); 
	DebugWind.focus();	
}


////////////////////////////////////////////////////////////////////
/////////////////// Netscape Browser Funtions //////////////////////

// Embed the tags that launch the plugin.  
function NS_AbaCheck(AbaservIP) {
	navigator.plugins.refresh(false);
	var myPlugin = navigator.plugins["Abacast"];
	
	if (myPlugin) {
		OpenWindow=window.open("", "newwin", 'width=278,height=100,menubar=no,scrollbars=no,toolbar=no,location=no,directories=no,resizable=yes,top=81,left=2');
		OpenWindow.document.write("<TI"+"TLE>Abacast Client...</TI"+"TLE>")
		OpenWindow.document.write("<BO"+"DY bgcolor=\"#C6D3DE\" background=\"http://abacast.com/images/loading_stream.gif\" >")
		OpenWindow.document.write("<em"+"bed hidden=true src=\"Abacast.aba\" AbaservIP="+AbaservIP+" type=\"application/x-plugin\" ");
		OpenWindow.document.write("></em"+"bed></BO"+"DY></HT"+"ML>");
		OpenWindow.document.close();
		setTimeout("if(!OpenWindow.closed) OpenWindow.close();", 2000);
	}	
	else { 
		alert(aba_alert_noClientNS);
		aba_Download(AbaservIP);
	}
}

//////////////////////////////////////////////////////////////////
//////////////// IE Browser / ActiveX Functions //////////////////
     
function aba_openADSP(AbaservIP) {
	AbaservURL = ( "adsp://" + AbaservIP );
	AdspWin = window.open( "adsp://" + AbaservIP,"","width=100,height=100,status=no,toolbar=no,menubar=no,left=3000,top=0");
	setTimeout('if(AdspWin && !AdspWin.closed) AdspWin.close()', 1000);
}

function aba_LaunchEmbeddedMacPlayer( name ){
	var url = 'http://mac.abacast.com/partners/index.html?'+name;
	window.open( url, 'embed','width=384,height=170' );
}

function aba_Download( AbaservIP ){
	var aba_DownloadDir = 'http://www.abacast.com/download/files/';
	var encoded_ip = aba_ParseIP( AbaservIP );
	
	if (aba_IsIE()) {
		window.open( aba_DownloadDir + 'abasetup' + encoded_ip + '.exe' );
	}
	else {
		filename = 'ns_abasetup' + encoded_ip + '.exe';
		downurl = aba_DownloadDir + filename;
		setTimeout("document.location.href=downurl;",1);
		return false;
	}
}

function aba_CABDownloadIE(url){

	//CabWin=window.open("http://www.abacast.com/cab/load.php?SID="+url, "cabdown", "width=400,height=200,menubar=no,scrollbars=no,toolbar=no,location=no,directories=no,resizable=yes,top=81,left=2");
	//return;
	
	CabWin=window.open("", "cabdown", 'width=400,height=200,menubar=no,scrollbars=no,toolbar=no,location=no,directories=no,resizable=yes,top=81,left=2');
	cdw = CabWin.document.writeln;
	cdw("<html><head><title>Please Wait while the Abacast Player downloads....</title><meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>");
	cdw('<script language="VBScript">');
	cdw('Function InstallCheck()');
	cdw('On Error Resume Next');
	cdw('InstallCheck = (IsObject(CreateObject("AbacastCheckup.AbacastAuto")))');
	cdw("End Function");
	cdw("Function CheckDownload()");
	cdw("On Error Resume Next");
	cdw("Dim Msg");
	cdw('Msg = "The Abacast software installation failed.  Click RETRY to try again or CANCEL to go manually install the software."');
	cdw("CheckDownload = (MsgBox (Msg, 5, \"Installation Failed...\"))");
	cdw("End Function </script>");
	cdw("</head><body bgcolor='#FFFFFF' text='#000000' topmargin='0' leftmargin='0' marginheight='0' marginwidth='0'>");
	cdw("<a href='http://abacast.com' target='_blank'><img src=http://abacast.com/cab/images/nowloading2.gif width=400 height=200 border='0' alt='Please wait while the Abacast Player Software loads.  This may take a few minutes.  Click YES on the security dialogue to start the installation'></a>");
	cdw("<object CLASSID='clsid:E7DBFB6C-113A-47cf-B278-F5C6AF4DE1BD' CODEBASE='http://www.abacast.com/download/files/Abasetup.cab' BORDER=0 VSPACE=0 HSPACE=0 ALIGN=TOP HEIGHT=0% WIDTH=0%></object>");
	cdw("<script language='javascript'>setTimeout('CheckInstall()',2000); function CheckInstall(){if(!InstallCheck()) { if( CheckDownload() == 4 ) { document.location.reload(true); }else { if(opener && !opener.closed) opener.aba_OnCabDownloadFail(); self.close();}}");
	cdw("else if( opener && !opener.closed ){setTimeout('opener.CallGoAbacast()',1);setTimeout('self.close()',1000);return;}else alert('The software is now installed, Please return to the referring page to begin the stream.');}"); 
	cdw("</script></body></html>");
	CabWin.document.close(); 
	CabWin.document.location.reload(true);
	//MSDEV Generated GUID E7DBFB6C-113A-47cf-B278-F5C6AF4DE1BD
	//AbacastCheckup  GUID 320F76EA-6A30-4E67-B540-3F517AE0A191
}

// start old download process, launch player if embedded
function aba_OnCabDownloadFail(){
	CABDownloadFailed = true;
	CallGoAbacast();
}

function CallGoAbacast(){
	if (!stor_url) return;
	GoAbacast(stor_url, stor_station, stor_embed);
}

////////////////////////////////////////////////////////////////////
/////////////////////// File Name Parsers  /////////////////////////

function aba_ParseIP( AbaservIP ){

	PortSplit = AbaservIP.split(':');
	Sub_Array = PortSplit[0].split('.');
	PortPad = '';
	result  = '';
	pad = '0';
	for ( var i = 0; i < 4; i++ )
	{
		if( !Sub_Array[i] || Sub_Array[i].length >  3 ) return '';
		if( Sub_Array[i].length == 1 ) Sub_Array[i] =  pad + pad + Sub_Array[i];
		else if( Sub_Array[i].length == 2 ) Sub_Array[i] =   pad + Sub_Array[i];
		result += Sub_Array[i];
	}
	if( PortSplit[1] ){
		PortLen = PortSplit[1].length;
		if ( PortLen > 5 ) return '';
		while ( PortLen < 5 ){
			PortPad += pad;
			PortLen++;
		}
		PortPad += PortSplit[1];
		result += PortPad;
	}
	return result;	
}
	
////////////////////////////////////////////////////////////////////
//////////////// Main Body Of Function Execution.  /////////////////

function ClickToListen(AbaservIP, macStation){ 

	// store click info required for callback
	stor_url     = AbaservIP;
	stor_station = macStation;

	if ( aba_is_win )
	{
		if ( aba_IsIE() )
		{
			VB_AbaCheck();
			if( IsInstalled ) aba_openADSP(AbaservIP);
			else 
			{ 
				if( CABDownloadFailed ){
					alert(aba_alert_noClientIE);
					aba_Download(AbaservIP);
				}
				else aba_CABDownloadIE(AbaservIP);
			}
		}	
		else if( aba_is_nav ) NS_AbaCheck(AbaservIP);
		else alert(aba_alert_WrongBrow);
	}
	else if( aba_is_mac )
	{
		if( !macStation || (macStation == 'null') )	alert( aba_alert_MacNoSupport );		
		else aba_LaunchEmbeddedMacPlayer(macStation);
	}
	else alert(aba_alert_WrongOS);	
}




////////////////////////////////////////////////////////////////////
///////// Abacast Embedded Windows Media Player Functions //////////

//**************************************************************
// Writes Embedded Player Code into client html.  
// NOTE: WILL NOT WRITE INTO UNSUPPORTED NETSCAPE 6+ BROWSERS
// Defaults are as follows:
// ShowControls=false, ShowStatus=false, size=320 X 240.
// Client can use own Embedded MediaPlayer code but Object and
// embedded plugin ID MUST BE 'aba_MediaPlayer'
// For Embedded Audio-only Media Player showing VOLUME,
// set width to 255 and height to 1
//**************************************************************
function aba_EmbedPlayer(showcont, showstat, width, height ){
	var autosize = 0;
	if( !width && !height && !showcont && !showstat && aba_is_nav ){ width=height=10; } // fix NS bad wont play if player size < 5
	if( !width && !height && (showcont || showstat) ){ width=255; height=0; } // set minimum size to show controls
	if( height > 10 ) height += 2;
	if( !showcont ) showcont = "0"; // add 27pix if showing controla
	else height += 27;
	if( !showstat ) showstat = "0"; // add 24pix if showing status
	else height += 24;

	// write player ( NS6+ NOT Supported Player will not be drawn )
	if( aba_is_nav6up ) return;
	var wmp = "";
	wmp += "<OBJ"+"ECT ID=\"aba_MediaPlayer\" clas"+"sid=\"CLS"+"ID:22d6f312-b0f6-11d0-94ab-0080c74c7e95\" CODEBASE=\"http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,5,715\" standby=\"Loading Microsoft Windows Media Player components...\" TYPE=\"application/x-oleobject\" width="+width+"  height="+height+" align=\"middle\">";
	wmp += " <PAR"+"AM NAME=\"AnimationatStart\" VALUE=\"true\">";
	wmp += " <PAR"+"AM NAME=\"TransparentatStart\" VALUE=\"false\">";		
	wmp += " <PAR"+"AM NAME=\"AutoStart\" VALUE=\"true\">";		
	wmp += " <PAR"+"AM NAME=\"EnableContextMenu\" VALUE=\"true\">";
	wmp += " <PAR"+"AM NAME=\"showtracker\" VALUE=\"0\">";
	wmp += " <PAR"+"AM NAME=\"showpositioncontrols\" VALUE=\"0\">";
	wmp += " <PAR"+"AM NAME=\"ShowControls\" VALUE="+showcont+">";
	wmp += " <PAR"+"AM NAME=\"ShowStatusBar\" VALUE="+showstat+">";
	wmp += " <PAR"+"AM NAME=\"AutoSize\" VALUE="+autosize+">";
	wmp += " <PAR"+"AM NAME=\"DefaultFrame\" value=\"default\">";
	wmp += " <Emb"+"ed TYPE=\"application/x-mplayer2\"";
	wmp += " pluginspage=\"http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=Media&sba=Plugin&\"";
	wmp += " ShowControls="+showcont+" ShowStatusBar="+showstat+" EnableContextMenu=1 name=\"aba_MediaPlayer\" AutoStart=1 align=\"middle\"transparentatstart=0";
	wmp += " width="+width+" height="+height+" DefaultFrame=\"default\" autosize=0 showpositioncontrols=0 showaudiocontrols="+showcont+" showtracker=0";
	wmp += "></emb"+"ed>";
	wmp += "</OBJ"+"ECT>";
	document.write(wmp);
} 


//**************************************************************
// Calls "ClickToListen" Client detection and launch.
// aba_StartPlayer after 8 second delay if Abaclient IsInstalled.
// StartPlayer is called w/ true or false arguement ID'ing if
// Client is installed or not.
//**************************************************************
function GoAbacast( url, station, embed ){

	// call main function
	ClickToListen( url, station );

	// if its not MS we're done
	if( !aba_is_win ) { return; }  
	
	// if embedded and Client is installed start player.
	if( embed )	{
		stor_embed = true;
		aba_Is_Embedded = true;
		if( aba_IsClientInstalled() || CABDownloadFailed ) { 
			setTimeout("aba_StartPlayer(false)",8000); 
		}
		//var firstrun = !aba_IsClientInstalled();
		//var fn = "aba_StartPlayer("+ firstrun +");";
		//setTimeout( fn, 8000 ); 
	}
}

//**************************************************************
// Sets Embedded WMP filename attribute and Starts Player.
// Tests for mp state 6 in IE.  MediaPlayer.Play() results
// in on page error in IE if WMP is in state 6.
// If Netscape 6, open asx file for stand-alone player.
// If First run, i.e. Client is being installed, will not roll up ports.
// Will attempt to open 5 times before rolling port up to 4002+.
//**************************************************************
var nPort     = 4001;
var attempt   = 0
var gFirstRun = false;
function aba_StartPlayer( FirstRun ){

	// launch standalone if NS 6+	
	if( aba_is_nav6up ) { setTimeout("document.location.href=\"http://asx.abacast.com/StandAlonePlayer.asx\";", 10000); return; }

	// Set/Check connection attempt and port.  If Installing Client, dont roll up WMP ports.
	if ( FirstRun ) gFirstRun = true;
	if ( !gFirstRun ) {
		if( attempt > 5 ) nPort++; 
		if( attempt++ > 9) { attempt=0; nPort=4001 }
	}
	//abaDebug("aba_StartPlayer:<br>attempt = "+attempt+" <br>nPort = "+nPort);

	// Set Filename & Start Player 
	var FilenameURL = 'http://127.0.0.1:' + nPort; 
	if( aba_IsIE() ) { 
		if(aba_MediaPlayer.PlayState == 2) return; 
		var err = setTimeout("document.execCommand('Stop');", 3000);  // This setTimeout works around WMP failing if trying to connect on a port that's already open.
		aba_MediaPlayer.FileName = FilenameURL;
		clearTimeout(err);

		if( aba_MediaPlayer.PlayState == 6 ) {
			setTimeout("aba_StartPlayer()", 2000);
		}
		else { 
			aba_MediaPlayer.Play(); 
			setTimeout("aba_StartPlayer();", 3000); // fix for failed file openings
		}
	}
	else { 
		if( (document.aba_MediaPlayer.GetPlayState() == 2) || (document.aba_MediaPlayer.GetOpenState() == 6) ) { return; }
		document.aba_MediaPlayer.Open( FilenameURL );
		setTimeout("aba_StartPlayer()", 2000);
	}
}



function aba_MPOpenErr(){
	if ( !aba_is_ie4) document.execCommand('Stop');
	else { abaDebug("window.stop"); window.stop; } 
}
//******************************************************************************
//                                  END OF FILE
//******************************************************************************
