//    Copyright (c) Franz J Mayrhofer, Gavilan College.  All rights reserved.

//-----------------------------------------------------------------
//    WMP code adapted from WMP SDK Samples:  PlayerDetection.js            
//-----------------------------------------------------------------

//------------------------
//-- Global Vars 
//------------------------

var WMPVer = "unknown";       // Set to WMP version string detected
var fHasWMP = false;          // True if either WMP v6.4 or v7+ found
var fHasWMP64 = false;        // True if WMP v6.4 found
var fHasWMP7 = false;         // True if WMP v7+ (8, 9) found
var fAppletRunning = false;   // True if v9 Applet is in use
var fPluginRunning = false;   // True if v6.4 Netscape plugin is in use
var player = null;            // Identifies window opened by play function
var dict = null;              // Identifies window opened by lookup function
var pop = null;               // Identifies window opened by popup function
var dictInit = null;          // True if initial communication established

//-----------------------------------------------
// Name:  GetBrowser
// Purpose: Get Browser Information
//-----------------------------------------------
function GetBrowser()
{
   var agt=navigator.userAgent.toLowerCase();
   if( ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1)) )
       return "IE";
   else if( ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
         && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
         && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1)) )
       return "Netscape";
   else
       return "unknown";
}


//------------------------------------------------
// Name:  GetBaseURL
// Purpose: Get URL of web directory containing current page
//------------------------------------------------
function GetBaseURL()
{
      var s = window.location.href;
	var i = s.lastIndexOf("/");
	if ((s.substring(0,4)=="http") && (i>0)) {
		return s.substring(0,i+1);
		}
	else
		return "";
}


//------------------------------------------------
// Name:  GetIEMajorVer
// Purpose: Get Internet Explorer Major Version Number
//------------------------------------------------
function GetIEMajorVer()
{
      var agt=navigator.userAgent.toLowerCase();
	var s = agt.split(";");
	if (s[1]) {
		var c = s[1];
		c = c.substring(6);
		c = c.split(".");
		return c[0];
		}
	else
		return("unknown");
}


//-------------------------------------------------
// Name:  GetIEMinorVer
// Purpose: Get Internet Explorer Minor Version Number.
//-------------------------------------------------
function GetIEMinorVer()
{
      var agt=navigator.userAgent.toLowerCase();
	var s = agt.split(";");
	if (s[1]) {
		var c = s[1];
		c = c.substring(6);
		c = c.split(".");
		if (c[1])
			return c[1];
		else
			return("unknown");
		}
	else
		return("unknown");
}

//------------------------------------------------
// Name:  GetPlayerMajorVer
// Purpose: Get Media Player Major Version Number
//------------------------------------------------
function GetPlayerMajorVer()
{
	var strVer = new String(WMPVer);
	var s = strVer.split(".");
    return s[0];
}


//-------------------------------------------------
// Name:  GetPlayerMinorVer
// Purpose: Get Media Player Major Version Number.
//-------------------------------------------------
function GetPlayerMinorVer()
{
	var strVer = new String(WMPVer);
	s = strVer.split(".");
	if (s[1])
		return s[1];
	else
		return("unknown");
}


//-----------------------------------------------------------------
// Name: IsNSPluginInstalled
// Purpose: Checks mime types to determine if the WMP 6.4 Netscape 
//          Plugin is installed.
//-----------------------------------------------------------------
function IsNSPluginInstalled()
{
    // See if 6.4 pluggin installed
    if (navigator.mimeTypes && navigator.mimeTypes["application/x-mplayer2"] && navigator.mimeTypes["application/x-mplayer2"].enabledPlugin)
		return(true);
	else
		return(false);
}


//-----------------------------------------------------------------
// Name: play(audioFile [startPosition])
// Purpose: Creates a customized version of the WMPlayer in a new window.
//          The content depends on WMPVer and BrowserVer detected.
//-----------------------------------------------------------------

function play(audioName) {
player=window.open("","player",'toolbar=no,location=no,status=no,resizable=yes,width=310,height=85');
doc=player.document.open("text/html");
doc.writeln('<html><head><title>reproduciendo...</title></head>');

var br = GetBrowser();        // Returns either "IE" or "Netscape"
var pm = GetPlayerMajorVer(); // Returns Windows Media Player major version #
var pn = GetPlayerMinorVer(); // Returns Windows Media Player minor version #

// Case 1: Media Player version is unknown, using Netscape and
//         plugin installed and supported by Netscape version
if (pm=="unknown" && br=="Netscape" && IsNSPluginInstalled())  
   {
doc.writeln('<body background="images/fondo5.gif" onLoad="RefreshPlugin();">');
doc.writeln('<p>');
doc.writeln('<Embed type="application/x-mplayer2"');
doc.writeln('  pluginspage="http://www.microsoft.com/windows/windowsmedia/"');
doc.writeln('  src="'+GetBaseURL()+audioName+'"');
if (play.arguments.length==2) {
  doc.writeln('  currentPosition='+play.arguments[1]);}
doc.writeln('  name="MediaPlayer"');
doc.writeln('  autoStart=1');
doc.writeln('  autoSize=1');
doc.writeln('  showDisplay=0');
doc.writeln('  showStatusBar=1');
doc.writeln('  showControls=1');
doc.writeln('  showTracker=1');
doc.writeln('  enableTracker=1');
doc.writeln('  showPositionControls=1');
doc.writeln('  enablePositionControls=1');
doc.writeln('  width=286');
doc.writeln('  height=71>');
doc.writeln('  </embed>');
doc.writeln('<'+'script language="javascript"'+'>');
doc.writeln('fPluginRunning=true;');
doc.writeln('function RefreshPlugin()');
doc.writeln('{');
doc.writeln('  navigator.plugins.refresh();');
doc.writeln('}');
doc.writeln('<'+'/script'+'>');
   }	
// Case 2: Netscape alone detected.  Attempt WMP v9 applet.  If
//         applet fails user will be asked to download WMP
else if (br=="Netscape") 
   {
doc.writeln('<body background="images/fondo5.gif" onLoad="CheckForApplet();">');
doc.writeln('<p>');
doc.writeln('<APPLET NAME="MediaPlayer" CODE="WMPNS.WMP" WIDTH="290" HEIGHT="68" MAYSCRIPT VIEWASTEXT>');
doc.writeln('  <PARAM NAME="URL" VALUE="'+GetBaseURL()+audioName+'">');
if (play.arguments.length==2) {
  doc.writeln('  <PARAM NAME="currentPosition" VALUE="'+play.arguments[1]+'">');}
doc.writeln('  <PARAM NAME="autoStart" VALUE="true">');
doc.writeln('  <PARAM NAME="enabled" VALUE="true">');
doc.writeln('  <PARAM NAME="balance" VALUE="50">');
doc.writeln('  <PARAM NAME="volume" VALUE="50">');
doc.writeln('  <PARAM NAME="uiMode" VALUE="full">');
doc.writeln('  </APPLET>');
doc.writeln('<script language="javascript">');
doc.writeln('fAppletRunning=true;');
doc.writeln('function CheckForApplet()');
doc.writeln('{');
doc.writeln('  navigator.plugins.refresh();');
doc.writeln('  if (!navigator.javaEnabled())');
doc.writeln('      alert("Java is not enabled.  Windows Media Player applet for Netscape requires a Java runtime.");');
doc.writeln('  if (!(document && document["MediaPlayer"])');
doc.writeln('      alert("cannot find Windows Media Player applet for Netscape.");');
doc.writeln('}');
doc.writeln('<'+'/script'+'>');
   }	
// Case 3: IE and WMP 7 or greater detected.		
else if (br=="IE" && pm>=7)
   {
doc.writeln('<body background="images/fondo5.gif">');
doc.writeln('<p>');
doc.writeln('<OBJECT ID="MediaPlayer"');
doc.writeln('  CLASSID=CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6');
doc.writeln('  standby="Loading Microsoft Windows Media Player components..."');
doc.writeln('  TYPE="application/x-oleobject" width="290" height="64" VIEWASTEXT>');
doc.writeln('  <PARAM NAME="url" VALUE="'+audioName+'">');
if (play.arguments.length==2) {
  doc.writeln('  <PARAM NAME="currentPosition" VALUE="'+play.arguments[1]+'">');}
doc.writeln('  <PARAM NAME="AutoStart" VALUE="true">');
doc.writeln('  <PARAM NAME="uiMode" VALUE="full">');
doc.writeln('</OBJECT>');
   }	
// Case 4: IE and WMP 6.4 detected.		
else if (br=="IE" && pm==6 && pn==4)
   {
doc.writeln('<body background="images/fondo5.gif">');
doc.writeln('<p>');
doc.writeln('<OBJECT ID="MediaPlayer" WIDTH=290 HEIGHT=68');
doc.writeln('  CLASSID="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95"');
doc.writeln('  STANDBY="Loading Windows Media Player components..."');
doc.writeln('  TYPE="application/x-oleobject" VIEWASTEXT>');
doc.writeln('  <PARAM NAME="FileName" VALUE="'+audioName+'">');
if (play.arguments.length==2) {
  doc.writeln('  <PARAM NAME="CurrentPosition" VALUE="'+play.arguments[1]+'">');}
doc.writeln('  <PARAM NAME="ShowStatusBar" VALUE="True">');
doc.writeln('  <PARAM NAME="AutoStart" VALUE="True">');
doc.writeln('  <PARAM NAME="AutoSize" VALUE="True">');
doc.writeln('  <PARAM NAME="ShowDisplay" VALUE="False">');
doc.writeln('  <PARAM NAME="ShowControls" VALUE="True">');
doc.writeln('  <PARAM NAME="ShowTracker" VALUE="True">');
doc.writeln('  <PARAM NAME="EnableTracker" VALUE="True">');
doc.writeln('  <PARAM NAME="ShowPositionControls" VALUE="True">');
doc.writeln('  <PARAM NAME="EnablePositionControls" VALUE="True">');
doc.writeln('</OBJECT>');
   }	   
// Default Case:  no player found, inform user.	
else	
   {
doc.writeln('<body background="images/fondo5.gif">');
doc.writeln('<p>');
doc.writeln('<font size="2" face="Trebuchet MS">Windows Media Player is required to play audio</font>'); 
   }		

doc.writeln('</p>');
doc.writeln('</body>');
doc.writeln('</html>');
doc.close();
player.focus();
}

//-----------------------------------------------------------------
// Name: closePlayerWin
// Purpose: close window opened by play function
//-----------------------------------------------------------------

function closePlayerWin() {
  if (player && player.open && !player.closed) player.close();
}


//-----------------------------------------------------------------
// Name: lookup
// Purpose: communicate with Dictionary Lookup ActiveX control
//-----------------------------------------------------------------

function lookup(searchArg) {
dict=window.open("","dict",'toolbar=no,location=no,status=no,resizable=yes,width=1,height=1');
doc=dict.document.open("text/html");
doc.writeln('<html><head><title>Dict lookup</title></head>');
doc.writeln('<body background="images/fondo5.gif">');
doc.writeln('<SCRIPT>');
doc.writeln('window.status="'+searchArg+'";');
doc.writeln('bResult=window.clipboardData.setData("Text","'+searchArg+'");');
doc.writeln('<'+'/script'+'>');
doc.writeln('<p align="CENTER">');
doc.writeln('<OBJECT');
doc.writeln('	  classid="clsid:CE4F4CF4-52E4-48CC-A996-B37D93028D34"');
doc.writeln('	  codebase="http://hhh.gavilan.edu/fmayrhofer/download/lookup.inf"');
doc.writeln('	  width=1');
doc.writeln('	  height=1');
doc.writeln('	  align=center');
doc.writeln('	  hspace=0');
doc.writeln('	  vspace=0');
doc.writeln('>');
doc.writeln('</OBJECT>');
doc.writeln('<font size="2" face="Trebuchet MS">Dictionary initialized</font>');
doc.writeln('<FORM>');
doc.writeln('<INPUT TYPE="button" VALUE="more info"');
doc.writeln(' onclick="window.open(');
doc.writeln("'bin/dictinfo.html','Info','toolbar=no,location=no,status=no,resizable=yes,width=415,height=430')");
doc.writeln('">');
doc.writeln('</FORM>');
doc.writeln('</p>');
doc.writeln('</body>');
doc.writeln('<SCRIPT>');
doc.writeln('window.status=window.clipboardData.getData("Text");');
doc.writeln('window.opener.window.status=window.clipboardData.getData("Text");');
doc.writeln('<'+'/script'+'>');
doc.writeln('</html>');
doc.close();
}

//-----------------------------------------------------------------
// Name: popup
// Purpose: display supplemental dictionary information
//-----------------------------------------------------------------

function popup(info) {
var x=(window.screen.width-300)/2;
var y=(window.screen.height-30)/2;
pop=window.open("","pop",'toolbar=no,location=no,status=no,resizable=yes,width=300,height=30,left='+x+',top='+y);
doc=pop.document.open("text/html");
doc.writeln('<html><head><title>supplemental information</title></head>');
doc.writeln('<body bgColor="#C0C0C0" text="#800000" onclick="window.close()">');
doc.writeln('<p align="LEFT">');
doc.writeln('<font face="Ariel" size="4">');
doc.writeln(info);
doc.writeln('</font></p>');
doc.writeln('</body>');
doc.writeln('</html>');
doc.close();
}


//-----------------------------------------------------------------
// Name: testSel
// Purpose: call lookup if some text selected
//          first strip linefeeds, tabs, carriage returns
//          check for "ref_" dictionary re-directions 
//                or  "rep_" supplemental definitions
//-----------------------------------------------------------------

function testSel(x,y) {
  closePopWin();
  var R=document.selection.createRange().text;
  if (R) {
    var re=/[\f\n\r\t\v]/;
    var S=R.split(re,1);
    if (S[0]) {
      var sel=S[0].toLowerCase();
      sel = sel.split(/[ ]/,1);
      sel = sel[0];
//    alert("sel = '"+sel+"', typeof(sel) = "+typeof(sel));
      if (eval("typeof ref_"+sel)=="string") { 
         lookup(eval("ref_"+sel));
         window.status="";
         }
       else if (eval("typeof rep_"+sel)=="string") { 
         popup(eval("rep_"+sel));
         }
       else {  
         lookup(S[0]);
         window.status="";
         }
       }
     }  
}

//-----------------------------------------------------------------
// Name: closePopWin
// Purpose: close window opened by popup function
//-----------------------------------------------------------------

function closePopWin() {
  if (pop && pop.open && !pop.closed) pop.close();
}

//-----------------------------------------------------------------
// Name: closeDictWin
// Purpose: close window opened by lookup function
//-----------------------------------------------------------------

function closeDictWin() {
  if (dict && dict.open && !dict.closed) dict.close();
}

//-----------------------------------------------------------------
// Name: closeAll
// Purpose: close windows opened by play and lookup functions,
//-----------------------------------------------------------------

function closeAll() {
  closePlayerWin();
  closeDictWin();
  closePopWin();
}

//-----------------------------------------------------------------
// Function: initDict
// Purpose: tries to initialize the communication, 
// sets global var "dictInit" to reflect the result,
// and returns focus to the text window
//-----------------------------------------------------------------

function initDict() {
  if (br=="IE" && (bm>5 || (bm==5 && bn==5))) {
    lookup("<DictInitialize>");
    if (window.status=="<Dictionary initialized>") {
      dictInit=true;
      self.focus();
      }
    else {
      dictInit=false;
      dict.close();
      window.status="done";
      }
    window.clipboardData.setData("Text","");
    }
  else {
    dictInit=false;
    }
}

//-----------------------------------------------------------------
// Function: installDict
// Purpose: tries to initialize the communication, 
// sets global var "dictInit" to reflect the result.
// on failure asks user to confirm activeX install,
// and to wait for completion
//-----------------------------------------------------------------

function installDict() {

  var S = 'If you have the Gavilan Dictionary on your system,\x0a'
        + 'you can use it to look for unfamiliar words.\x0a'
        + '\x0a'
        + 'You need to install the Lookup ActiveX Control first.\x0a'
        + '(You may need to set your browser security level to "Low"\x0a'
        + 'to permit this - remember to restore it to "Medium" afterwards.)\x0a'
        + '\x0a'
        + 'Please leave this window open until the install has finished.\x0a';

  if (br=="IE" && (bm>5 || (bm==5 && bn==5))) {
    lookup("<DictInitialize>");
    if (window.status=="<Dictionary initialized>") {
      dictInit=true;
      }
    else if (window.status=="<Dictionary not installed>") {
        dictInit=false;
        window.status="done";
        }
    else {
      if (confirm(S)) {
        initDict();
        }
      else {
        dictInit=false;
        window.status="done";
        }
      }
    window.clipboardData.setData("Text","");
    dict.close();
    }
  else {
    dictInit=false;
    }
}

//-----------------------------------------------------------------
// Name: checkIE
// Purpose: check Internet Explorer version, warn if too low
//-----------------------------------------------------------------
function checkIE() {
  if ((!brChecked) && (!(br=="IE" && (bm>5 || (bm==5 && bn==5)))))
	alert("To enjoy all the features of these pages, you should use Internet Explorer 5.5 or better.");
  brChecked=true;
}

var br = GetBrowser();        // Returns either "IE" or "Netscape"
var bm = GetIEMajorVer();     // Returns Internet Explorer major version #
var bn = GetIEMinorVer();     // Returns Internet Explorer minor version #

if (br=="IE" && (bm>5 || (bm==5 && bn==5))) { // clipboard only avail in IE 5.50 or later
  window.clipboardData.setData("Text","");
  }
