
var VoiceObj = null;
var Voices = null;

var SVSFDefault=0;
var SVSFlagsAsync=1;
var SVSFPurgeBeforeSpeak=2;

// rate can be from 1—slow—to 10—very fast; the volume can be from 0 to 100

//==============================================================================
//Purpose: Returns True SAPI 5.x installed and created OK
//Requires SAPI 5.x COM interface required XP or greater
//==============================================================================
function CreateVoiceObj() {
  if ((VoiceObj == null) || (VoiceObj == undefined) || (typeof(VoiceObj) != "object"))
  {
    try {  
      VoiceObj =  new ActiveXObject('SAPI.SpVoice');
      return(true);
    }
    catch(e) {
      VoiceObj = null;
      return(false);
    }
  }
  else
    return(true);  //already created obj
}

//==============================================================================
//Create 
//==============================================================================
function Agent_Init() {
  var ok = CreateVoiceObj();
  if (!ok)
    if (ActiveXObject) 
      alert("Speech API 5.x (SAPI) not installed on this PC. Or security settings are blocking local ActiveX.");
    else 
      alert('Sorry: Text-to-Speech requires Internet Explorer browser.');
  else {
    Agent_Stop();

    var Voices = VoiceObj.GetVoices();
    //alert("Voice Count: " + Voices.count);
    //Voices(1).GetDescription()
    //if(len >= 2) {
    //   VoiceObj.Voice = Voices(1);
    //   VoiceObj.Rate = 1;
    //   VoiceObj.Volume = 75;
    //   VoiceObj.Speak("Testing 1,2,3!", SVSFlagsAsync);
    //}

  }
  return(ok);
}

function AgentDemo() {
  if (!Agent_Init())
    return(true);

  VoiceObj.Speak("Hello this is test speech.", SVSFlagsAsync && SVSFPurgeBeforeSpeak); 
  VoiceObj.WaitUntilDone(-1);
  VoiceObj.Speak("Speech requires SAPI 5.x COM interface and XP or greater", SVSFlagsAsync);
  VoiceObj.WaitUntilDone(-1);
  }

var g_AgentBarText = /Read Stop Help/;

function get_selection()
{
  var str = new String("");
  if (window.getSelection)   // Moz
  {
    str = window.getSelection().toString();
  }
  else if (document.selection && document.selection.createRange) // IE
  {
    var range = document.selection.createRange();
    str = range.text.toString();
  }

  if (str=="") //Get whole doc text
  {
    //rang = document.body.createTextRange();
    //str = range.text.toString();
    str = document.body.innerText;

    //at the end of every page is the Agent Panel - Don't read this text!!
    str = str.replace(g_AgentBarText,"");
  }
  //Agent uses pipe char to mark alternative random text -- Lets mark | as ! instead
  ra = /\|/g;                    //find all Pipe chars
  str = str.replace(ra,"!");     //Replace with !

  return str;
}


//Mappings -- Say SSS Display DDD \Map="SSS"="DDD"\ == escaped \\Map=\"SSS\"=\"DDD\"\\
// The first array has search text - Switches can be g, i, gi
//   i (ignore case)
//   g (global search for all occurrences of pattern)
//   gi (global search, ignore case)
//
// Script will find XXX and replace it with YYY

var xxxAgentMap = [/Eduscape/g, /Sciface/g];
var yyyAgentMap = ['\\Map=\"ed-u-scape\"=\"Eduscape\"\\','\\Map=\"Sigh-face\"=\"Sciface\"\\'];


function ReadDocText() {
  var MAX_STR_LEN = 100;

  if (!Agent_Init())
    return(true);

  //Agent_Stop();

  try
  {
    var str = get_selection();

    //Agent Word mapping
    for (var i = 0; i < xxxAgentMap.length; i++)
      str = str.replace(xxxAgentMap[i], yyyAgentMap[i]);

    if (str.length < MAX_STR_LEN)
      VoiceObj.Speak(str, SVSFPurgeBeforeSpeak && SVSFlagsAsync);
    else
    {

      //if String is > MAX_STR_LEN chars then break it into multiple calls
      var items = str.split(".");

      var ss = "";
      var firstTime=true;
      for (var i = 0; i < items.length; i++)
      {

         if ((items[i] != "") && (items[i] != " "))
           ss = ss + items[i] + '. ';
         if ((ss.length > MAX_STR_LEN) || (i == items.length-1))
         {
           if (ss.length > 0)
           {
              if (firstTime) 
                 VoiceObj.Speak(ss, SVSFPurgeBeforeSpeak && SVSFlagsAsync);
              else 
                 VoiceObj.Speak(ss, SVSFlagsAsync);
              firstTime = false;  
           }
           ss = "";
         }

      }
    }
  }
  finally {
  }
}

function Agent_ReadText() {
  //AgentDemo()
  ReadDocText();
}

function Agent_Stop() {
  if (VoiceObj != null)
    VoiceObj.Speak(' ', SVSFPurgeBeforeSpeak);
}

function Agent_Demo() {
  AgentDemo();
}

function Agent_PropertySheet() {
  if (!Agent_Init())
    return(true);
  VoiceObj.PropertySheet.Visible = true;
}

function Agent_ShowDefaultCharacterProperties() {
  if (!Agent_Init())
    return(true);
  Agent_Stop();
  VoiceObj.ShowDefaultCharacterProperties(-1, -1);
}



// =========================================================================
// Capture Key Strikes - F9 to Talk, Esc to Shutup
// =========================================================================
function MyKeyDownEvent(){
//if (window.event.shiftKey)
  var VK_F9 = 120;
  var VK_Esc = 27;
  var Code = window.event.keyCode
  if (Code == VK_F9)
    ReadDocText();
  else
  if (Code == VK_Esc)
    Agent_Stop();
}


///--------------------------------------------------------------------------
///
/// Include a JS file from outside the CHM
///
///--------------------------------------------------------------------------
function JS_IncludeExternal(aFilename) {
  var ChmDir = GetChmDir();
  if (ChmDir != "") {           //in CHM - Use path to CHM and stip leading ../
    //Strip off leading ../ and dir info
    aFilename = aFilename.substring(aFilename.lastIndexOf("\\")+1, 999);
    aFilename = aFilename.substring(aFilename.lastIndexOf("/")+1, 999);
    //make full path
    aFilename = ChmDir + aFilename;
  }
  document.writeln('<script src="'+aFilename+'" language="JavaScript1.2" type="text/javascript"></script>');
}

// Return current dir -- 
//    returns "" if in a browser 
//    returns full path to CHM folder if in a CHM (with trailing \\)
// If in browser then - location.href=file:///d:/path/file.htm
// If in CHM then - location.href=mk:@MSITStore:D:\path\help.chm::/file.htm
function GetChmDir() {

  //Not in a CHM - return empty string
  var ra = /::/;
  if (location.href.search(ra) <= 0)
    return("");

  //Strip off any ITS prefix (usually mk:@MSITStore: but have seen its:)
  var S = location.href;
  S = S.replace(/mk:@MSITStore:/,"");
  S = S.replace(/ms-its:/,"");
  S = S.replace(/its:/,"");

  //Grab everything up to the last backslash
  //eg, "d:\folder\test.chm::/path/file.htm"  ==> grab "d:\folder"
  var dir = S.substring(0, S.lastIndexOf("\\"));

  //UnEscape path - EG. Replace %20 with spaces - Return path with trailing \
  return(unescape(dir) + "\\");
}


///--------------------------------------------------------------------------

//==============================================================================
// Scroll Control bar into view
//==============================================================================
  function MyScrollFunc() {
    //Slide the Div section into view if user scrolls
    var xTop = document.all.FloatBox.offsetTop;
    var xScrollTop = document.body.scrollTop;
    if (xTop < xScrollTop)
      document.all.FloatBox.style.top = xTop + ((xScrollTop - xTop)/2);
    else
    if (xTop > xScrollTop)
      document.all.FloatBox.style.top = xScrollTop + ((xTop - xScrollTop)/2);
    //Contracted box
    xTop = document.all.FloatBox_None.offsetTop;
    if (xTop < xScrollTop)
      document.all.FloatBox_None.style.top = xTop + ((xScrollTop - xTop)/2);
    else
    if (xTop > xScrollTop)
      document.all.FloatBox_None.style.top = xScrollTop + ((xTop - xScrollTop)/2);
  }

//==============================================================================
// Hide Show Controlbar
//==============================================================================
  function HideShowAgent(VisibleState) {
    if (VisibleState) {
      document.all.FloatBox.style.visibility = 'visible';
      document.all.FloatBox_None.style.visibility = 'hidden';
    }
    else {
      document.all.FloatBox.style.visibility = 'hidden';
      document.all.FloatBox_None.style.visibility = 'visible';
    }
  }


//-----------------------------------------------------
// Return MS IE major version number
// Return 0 for non-IE browser
//-----------------------------------------------------
function msieversion()
{
  var ua = window.navigator.userAgent.toLowerCase();;
  var msie = ua.indexOf("msie ");
  if (msie > 0) // is Microsoft Internet Explorer; return version number
     return(parseInt(ua.substring(msie+5,ua.indexOf(".", msie))));
  else return(0); // is other browser
}

function IsHTTPLocation()
{
   var aref = location.href.toLowerCase();
   var isHTTP = aref.substring(0, 4) == 'http';
   return isHTTP;
}

//==============================================================================
// Write Floating Control bar
//==============================================================================
function Agent_WriteControlBar() {

    //No point trying to load an ActiveX control except in IE4 or greater
    if ((msieversion() < 4) || IsHTTPLocation())  //Only show in CHM and local drive
       return 0;

    //On helpware.net? adjust path to data files
    var ra = /helpware.net/i;
    var HelpwarePrefix = '';
    if (location.href.search(ra) >= 0)
      HelpwarePrefix = 'http://www.helpware.net/FAR/help';

    //If no external INI file variable found OR Var CONFIG_AGENT_SHOWBUTTONS = true
    if ((typeof(CONFIG_AGENT_SHOWBUTTONS) == "undefined") || (CONFIG_AGENT_SHOWBUTTONS))
    {
      document.writeln('<div class="navbox2_Off" id="FloatBox_None">');
      document.writeln('<a href="javascript:HideShowAgent(true);"');
      document.writeln('  title="Expand Agent Reader bar" class="AgentLink" style="margin:0px -1px -2px -2px; padding: 1px 2px 0px 2px;"><img src="'+HelpwarePrefix+'/Agent/arrow_left.gif" align="middle" border="0" /></a>');
      document.writeln('</div>');

      //Regular expression - global search str for stopping reader from reading Reader bar text
      g_AgentBarText = /Read Stop Help/

      document.writeln('<div class="navbox2" id="FloatBox">');
      document.writeln('<a href="javascript:Agent_ReadText();" class="AgentLink" title="Read selected text');
      document.writeln('  (Shortcut = F9)">Read</a>');
      document.writeln('<a href="javascript:Agent_Stop();" class="AgentLink" title="Stop reading text');
      document.writeln('  (Shortcut = Esc)">Stop</a>');
      document.writeln('<a href="'+HelpwarePrefix+'/Agent/AgentHelp.html" class="AgentLink" title="Help on using Agent">Help</a>');
      document.writeln('<a href="javascript:HideShowAgent(false);" class="AgentLink" style="padding: 2px 4px 3px 3px"');
      document.writeln('  title="Contact Agent Reader bar"><img src="'+HelpwarePrefix+'/Agent/arrow_right.gif" align="middle" border="0" /></a>');
      document.writeln('</div>');

      //Initialize the Timer
      document.all.FloatBox.style.visibility = 'hidden';
      document.all.FloatBox_None.style.visibility = 'visible';
      setInterval("MyScrollFunc()", 150);
    }

    //If no external INI file variable found OR Var CONFIG_AGENT_CAPTURE_KEYS = true
    //Allows F9 and Esc keys to Start/Stop Agent
    if ((typeof(CONFIG_AGENT_CAPTURE_KEYS) == "undefined") || (CONFIG_AGENT_CAPTURE_KEYS))
    {
      document.onkeydown = self.MyKeyDownEvent;
    }

}








