
var AgentObj;
var MerlinID;
var MerlinACS;
var MerlinCh;
var MerlinLoaded = false;

//==============================================================================
//Purpose: Returns True if Agent 2.0 is installed and created OK
//Requires IE5
//==============================================================================
function CreateAgentObj() {
  var NotFound = ((AgentObj == null) || (AgentObj == undefined) || (typeof(AgentObj) != "object"));
  if (NotFound)
  {
    try {
      AgentObj =  new ActiveXObject("Agent.Control.2");
      return(true);
    }
    catch(e) {
      return(false);
    }
  }
  else
    return(true);  //already created obj
}

//==============================================================================
//Create Agent Object + Connect + Load Nerlin - Return FALSE if Agent not found
//==============================================================================
function Agent_Init() {
  var ok = CreateAgentObj();
  if (!ok)
    alert("Agent not installed on this PC");
  else {
    Agent_Stop();
    AgentObj.Connected = true;
    if (!MerlinLoaded)
      MerlinLoaded = AgentObj.Characters.Load(MerlinID, MerlinACS);
    if (!MerlinCh)
      MerlinCh = AgentObj.Characters.Character(MerlinID);
  }
  return(ok);
}


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

  MerlinCh.Show();
  MerlinCh.Play("Surprised");
  MerlinCh.Play("GetAttention");
  MerlinCh.Play("Blink");
  MerlinCh.speak("Hello Ralph well here it is. Each HTML Topic simply needs to include the JS file in the header.");
  MerlinCh.Play("Blink");
  MerlinCh.Play("Confused");
  MerlinCh.MoveTo(600,400);
  MerlinCh.Play("Surprised");
  MerlinCh.Play('GestureRight');
  MerlinCh.speak("Note that you will require IE5 and greater. Is that a problem?");
  MerlinCh.speak("Also not that I have provided links but all the user needs is F9 and Esc key to talk and shutup");
  MerlinCh.MoveTo(200,450);
  MerlinCh.Play('GestureLeft');
  MerlinCh.speak("Ralph what do you think?");
  MerlinCh.Play('DoMAgic1');
  MerlinCh.Play('DoMAgic2');
  MerlinCh.Play("Blink");
  MerlinCh.speak("Good bye");
  MerlinCh.Hide();
  }

var g_AgentBarText = /Read Stop Hide Options Character 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;
}


function ReadDocText() {
  var MAX_STR_LEN = 200;

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

  Agent_Stop();

  try
  {
    var str = get_selection();
    MerlinCh.Show();

    if (str.length < MAX_STR_LEN)
      MerlinCh.speak(str);
    else
    {

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


      var ss = "";
      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)
             MerlinCh.speak(ss);
           ss = "";
         }

      }
    }
  }
  finally {
  }
}

function Agent_ReadText() {
  ReadDocText();
}

function Agent_Stop() {
 if (MerlinCh) {
   if (MerlinCh.Visible)
     MerlinCh.StopAll('');        //Shut him up
   }
}

function Agent_HideFast() {
 if (MerlinCh) {
   if (MerlinCh.Visible)
     MerlinCh.StopAll('');        //Shut him up
     MerlinCh.Hide(1);            //Hide fast
   }
}

function Agent_Hide() {
 if (MerlinCh) {
   if (MerlinCh.Visible)
     MerlinCh.StopAll('');        //Shut him up
     MerlinCh.Play("Wave");
     MerlinCh.Hide();
   }
}

function Agent_Demo() {
  AgentDemo();
}

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

function Agent_ShowDefaultCharacterProperties() {
  if (!Agent_Init())
    return(true);
  Agent_Stop();
  AgentObj.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) + "\\");
}


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

//  CSS-P   Positioning notes
//
//http://it.maconstate.edu/tutorials/JSDHTML/ 
//http://codepunk.hardwar.org.uk/acss.htm
//http://msdn.microsoft.com/library/default.asp?url=/workshop/author/dhtml/overview/dhtml_overviews_entry.asp
//
// position <div> "absolute" cords - position: absolute; top: 0px; right: 340; position: relative;
// IE supports the use of "right:" and "bottom:" as well as "left:" and "top:".
// Float: Absolute positioning doesn't work when floating boxes. "position: relative; float: left;". 
// floats may need <br clear="all"> tag to make a line break
// Layering -- div.box1{z-index: 3;} div.box2{z-index:2;} div.box3{z-index: 1;}
// Visiblility -- div.box{visibility: hidden;} div.box{visibility: visible;}
// Overflow -- adds scroll bars - #box{width: 200px;height: 200px;overflow: scroll;}
//          -- Or clips the content - #box{width: 200px;height: 200px;overflow: hidden;}
// Forget SetTimer() use
//    my_polling_prog = setInterval("my_function()", 500);
//    clearInterval(my_polling_prog);

// DHTML = (document.getElementById || document.all || document.layers)
//   if (!DHTML) return;


//==============================================================================
// 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
}

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

    //No point trying to load an ActiveX control except in IE4 or greater
    if (msieversion() < 4)
       result(0);

    //On helpware.net? adjust path to data files
    var ra = /helpware.net/i;
    var HelpwarePrefix = '';
    if (location.href.search(ra) >= 0)
      HelpwarePrefix = 'http://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 Hide Options Character 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="javascript:Agent_HideFast();" class="AgentLink"  title="Hide Agent character">Hide</a>');
      document.writeln('<a href="javascript:Agent_PropertySheet();" class="AgentLink" title="Show Agent Options dialog">Options</a>');
      document.writeln('<a href="javascript:Agent_ShowDefaultCharacterProperties();" class="AgentLink" title="Select Agent character dialog">Character</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;
    }

}

