
//=== Utility Functions ======================== 
  
//Returns a random integer UP to the maximum number fast. (defaults 10).
function randnum(maxnum)
{
   if(typeof maxnum =="undefined") { var maxnum=10; }
   var randomnumber=Math.floor(Math.random()*maxnum)
   return randomnumber;
}

//toggles an elements height between two values (by Id)
function toggleheight(objid,val1,val2)
{
   var newval=val1;
   var obj=document.getElementById(objid);
   var currentval=parseInt(obj.style.height);
   if(currentval==val1 || isNaN(currentval)) { newval=val2; }
   obj.style.height=newval+"px";
}
  
// Returns the X (left) position of an object
function getXPos(myobj)
  {
    var posleft = 0;
    if (myobj.offsetParent) {while (myobj.offsetParent) {posleft += myobj.offsetLeft; myobj = myobj.offsetParent;}}
    else if (myobj.x) { posleft += myobj.x; }
    return posleft;
  }
  
// Returns the Y (top) position of an object 
function getYPos(myobj)
  {
    var postop = 0;
    if (myobj.offsetParent) {while (myobj.offsetParent) {postop += myobj.offsetTop; myobj = myobj.offsetParent; } }
    else if (myobj.y) { postop += myobj.y; }
    return postop;
  }  

//prevent submission of empty all-optional fields  
function validateOptional(obj)
  {
    var elements = obj.elements
    var hasContent = false
    for (var i = 0; i < elements.length; i ++)
      {
        if (!elements[i].type.match(/hidden|submit|button|reset/) && elements[i].value != ''){hasContent = true; break}
      }
    if (!hasContent) {alert('If you wish to submit the form, please enter some data.')}
    return hasContent
  }
  
function getScroll()
  {
    var x,y;
    if (self.pageYOffset) // all except Explorer
    {
    	x = self.pageXOffset;
    	y = self.pageYOffset;
    }
    else if (document.documentElement && document.documentElement.scrollTop)
    	// Explorer 6 Strict
    {
    	x = document.documentElement.scrollLeft;
    	y = document.documentElement.scrollTop;
    }
    else if (document.body) // all other Explorers
    {
    	x = document.body.scrollLeft;
    	y = document.body.scrollTop;
    }
   var returnObj = {vert:y,horiz:x}
   return returnObj
  } 
    
//function to validate form fields
function validateFields(formObj)
  {
    var badFields = new Array()
    var fnameArray = formObj.required.value.split(',')
    var formLabels = formObj.getElementsByTagName('LABEL')
    var thisfield,fieldOK
    for (var i = 0; i < fnameArray.length; i++)
      {
        thisfield = formObj.elements[fnameArray[i]]
        
        for (var j = 0; j < formLabels.length; j++) {if(formLabels[j].htmlFor == thisfield.id || formLabels[j].id.replace(/lb_/,'') == fnameArray[i]) {thisfield.label = formLabels[j]; break}}
        if (thisfield.length && !thisfield.type ) //validate checkboxes
          {
            fieldOK = false
            for (var f= 0; f < thisfield.length; f++) {if (thisfield[f].checked) {fieldOK = true; break}}
          }
        else //text inputs, selects
          {
            fieldOK = thisfield.value != '';
            if (fieldOK && thisfield.name.match(/email/)) {fieldOK = validateMailString(thisfield.value,false)} //hook in email validation
          }            
                           
        if (!fieldOK)//invalid field, set class names
          {
            badFields[badFields.length] = thisfield.label.firstChild.nodeValue
            if (!thisfield.length) {$(thisfield).addClassName('badfield')}; //highlight field if simple input
            $(thisfield.label).addClassName('badfieldlabel');
          }
        else //valid field, clear the class names
          {
            if (!thisfield.length) {$(thisfield).removeClassName('badfield'); }
            $(thisfield.label).removeClassName('badfieldlabel');
          }        
        
      }//end, for
    return badFields
  }
  
//function to send form values
function sendForm(formObj)
  {
    var sendObj = $(formObj).serialize(true)
    var temp = new Ajax.Request('/contact/emailer_ajx.cfm',{
      method:'post',
      parameters:sendObj
      }
     )
  }
  
 function debugResponse(responseText)
  {    
     var tmp = window.open();
     tmp.document.open();
     tmp.document.write(responseText);
     tmp.document.close();
     
  }
  
  
function validateMailString(emailval,checkBlank)
  {
      var pattern=/(^[\-_\.a-zA-Z0-9]+)@((([0-9]{1,3}\.){3}([0-9]{1,3})((:[0-9])*))|(([a-zA-Z0-9\-]+)(\.[a-zA-Z]{2,})+(\.[a-zA-Z]{2})?((:[0-9])*)))/;
      if (emailval == ""){
      	if (checkBlank){alert("Please enter an e-mail address.");}
         return false;
      }
      else if (emailval.search(pattern) == -1) {
      	alert("Please enter a valid e-mail address.");
         return false;
      }
      return true
  
  }
      
//=== Menu Functions =========================================    
    
function hideMenus()
  {
    for(var mn = 0; mn < navLx.length; mn++) 
      {
        navLx[mn].className = '';
        if (navLx[mn].submenu != null) {navLx[mn].submenu.style.visibility = 'hidden'}
      }
  }
    
function linkOn()
  {
   if (menutimer) {clearTimeout(menutimer)}; 
   hideMenus();
   this.className = 'over'
   if (!this.offsetWidth) {this.offsetWidth} //taking a good guess if we can't measure  
  
   if (this.submenu != null) 
    {
      var xPos = getXPos(this)
      if (xPos + 230 > 958)
        {
          xPos = xPos - (230 - this.offsetWidth)
        }
      this.submenu.style.left = xPos + 'px'; this.submenu.style.visibility = 'visible'  
    }             
  }
      
   
function linkOff()
  {
    menutimer = setTimeout("hideMenus()",menuDelay)  
  }
      
      
    
  if (document.getElementById && document.createElement)
  {
    //rollovers on site search button
    var goButton = document.getElementById('srch_go')
    var imgPath = '/images/bxhp/'
    goButton.onmouseover = function(){this.src = imgPath + 'searchbutton_over.gif'}
    goButton.onmouseout = function() {this.src = imgPath + 'searchbutton.gif'}    
    
    //set site search default value (as a label)
    var defaultText = 'Search'    
    var searchfield = document.searchform.searchstring
    
    try 
      {
        searchfield.onfocus = function(){if (this.value == defaultText) this.value = ''}
        searchfield.onblur = function(){if (this.value == '') this.value = defaultText}
        searchfield.onblur()
      }
    catch(e) {}
    
    var menuDelay = 500; //ms
    var menutimer; 
    
    var mainNav = document.getElementById('mainnav')     
    var navLx = mainNav.getElementsByTagName('A')     
    
    var currLk, submenu 
    var activeLink = null 
    
    //add the menu event handlers
    for(var mn = 0; mn < navLx.length; mn++) 
      {
        currLk = navLx[mn]
        submenu = document.getElementById(currLk.id.replace(/mn/,'sn')) 
        
        if (submenu != null) 
          {
            submenu.main = currLk;
            submenu.className = 'menu'                  
            if (!document.all){submenu.getElementsByTagName('DIV')[0].style.backgroundColor = 'transparent'}//IE requires a background color to avoid a painting bug, otherwise, we can use a nice transparent BG
            
            submenu.onmouseover = function(){clearTimeout(menutimer)} ;  
            submenu.onmouseout = linkOff ;    
            
            currLk.submenu = submenu                  
          }
        currLk.onmouseover = linkOn
        currLk.onmouseout = linkOff        
      }    
    
         
    
    //=== Begin Opacity/Form Stuff ======
    //globals  
    var opacStep = 25 
    var opacInterval = 75 //time between increments
    var currOpacity = 0
    var currObj //defining; will be set to whatever object is being faded in/out
    var currStep = 0 //current step in the form process
    var terminalFunction = null //function to be executed when decOpacity finishes fading out an element
    var backgroundOpacity = 75 //opacity of the background when dimmed
    
    var logo = document.getElementById('identity')
    var isSubpage = (logo.firstChild.nodeType == 1) //subpages have a link back to the homepage within the logo; the home page doesn't
    
        
    //function to set the opacity of all children of the container element, with exceptions
    function setBGOpacity(opVal)
      {
        var container = document.getElementById('outercontainer')
        var underlay = document.getElementById('underlay')
        var contentarea = document.getElementById('innercontainer')
        var kids = container.childNodes
        var thisKid
        for (i = 0 ; i < kids.length; i++) { thisKid = kids[i]; if (thisKid.className != 'palette200'  && thisKid != underlay &&thisKid.nodeType == 1 && !(isSubpage && thisKid == contentarea )) { setOpacity(thisKid,opVal)}}        
      }    
    
    //function to actually set the opacity of an element. Sets several cross-browser properties.
    function setOpacity(obj,opVal)
      {
        obj.style.opacity = (opVal * .01)
        obj.style.mozOpacity = (opVal * .01)
        obj.style.khtmlOpacity = (opVal * .01) 
        obj.style.filter = "alpha(opacity=" + opVal + ")"; //for IE          
      }
    
    function incOpacity()
      {
        this.currOpacity += this.opacStep
        if (this.currOpacity > 100) {this.currOpacity = 100}
        setOpacity(this.currObj,this.currOpacity)
        if (this.currOpacity < 100)
          {
            var thisobj = this; 
            var thisInc = function() {incOpacity.apply(thisobj)}
            setTimeout(thisInc,thisobj.opacInterval)
            }
        else if (this.terminalFunctionInc != null) {this.terminalFunctionInc()}    
      }
      
      //decrements opcacity, runs terminalFunction if it *is* a function when done 
      function decOpacity()
      {
      this.currOpacity -= this.opacStep
      if (this.currOpacity < 0) {this.currOpacity = 0}
      setOpacity(this.currObj,this.currOpacity)
      if (this.currOpacity > 0)
        {
          var thisobj = this; 
          var thisInc = function() {decOpacity.apply(thisobj)}
          setTimeout(thisInc,thisobj.opacInterval)
          }
          
      else if (this.terminalFunction != null) {this.terminalFunction()}          
      }   
   
   //advances from one step of the call form process to the next.   
   function incrementStep()
    {
      if (currStep == 0) { var newObj = form2 }
      else 
        {
          var newObj = thx
          closeLink.firstChild.nodeValue = 'Close '
        }
      currObj.style.display = 'none' //hide the current step
      setOpacity(newObj,0)//make the new step fully transparent, so we can fade it up
      newObj.style.display = '' //unhide it
      currStep++ //increment step tracking
      currObj = newObj //reset the current object
      currOpacity = 0 //reset opacity tracking variable
      incOpacity()
    } 
    
    //event handler for the service requested dropbox; adds an 'other services' input if that is chosen; removes it (if present) if not.
    function serviceHandler()
      {
        var parentDiv = document.getElementById('servdiv')
        if (this.checked)
          {
            var temp = document.createElement('LABEL')
            temp.setAttribute('id','lb_other_services')
            var txt = document.createTextNode('Other Services')
            temp.appendChild(txt)
            parentDiv.appendChild(temp) 
            
            var temp = document.createElement('INPUT')
            temp.type = 'text'
            temp.name = 'other_services'
            temp.setAttribute('id','other_services')
            parentDiv.appendChild(temp)            
          }
         else if (document.getElementById('other_services') != null)
          {
            parentDiv.removeChild(document.getElementById('lb_other_services'))
            parentDiv.removeChild(document.getElementById('other_services'))
          }
      }
    
      
      
    //function to handle "submission" of both steps of call forms
    function submitStep()
      {      
        if (currStep == 0) 
          { 
            var msg = document.getElementById('cf_msg1') 
            currObj = form1 
            var sendObj = form1
           }//end, step 1 handling
        else 
          {
            var msg = document.getElementById('cf_msg2')       
            currObj = form2    
            var sendObj = form2  
          }//end, step 2 handling
          
        var badFields  = validateFields(currObj)  
        if (badFields.length > 0 )
          {
            msg.firstChild.nodeValue = 'Please complete the following fields: ' +  badFields.join(', ').toLowerCase() + '.';
            return
          }
        else {msg.firstChild.nodeValue = '\u00A0'}//housekeeping - set msg content to nbsp. 
        
        sendForm(sendObj)  
        terminalFunction = incrementStep      
        decOpacity()      
      }
      
     
     //client login submission handler
     function doLogin()
      {
        var badFields  = validateFields(document.loginform)  
        var msg = document.getElementById('lg_msg')
        
        if (badFields.length > 0 ) {msg.firstChild.nodeValue = 'Your login information was incomplete; please try again'; return }
       //do AJAX here  
      }
      
     /* event handler to show palette 
        paletteID = id of palette to show
        targetID = element palette is positioned in relation to
        offsetX = horizontal offset
        offsetY = vertical offset 
        alignmentEdge = ['top' || 'bottom'] which edge of palette to align. This DOES affect your offset Y */
     
     function showPalette(paletteID,targetID,offsetX,offsetY,alignmentEdge)
      {         
        if (!alignmentEdge){alignmentEdge = 'top'}
        var palettediv = document.getElementById(paletteID)
        if (palettediv == null) {return false}
         
        var targetEl = document.getElementById(targetID)
        
        var container = document.getElementById('outercontainer')
        
        if (alignmentEdge == 'top') 
          { 
            
            var xCoord = getXPos(targetEl) - getXPos(container) + offsetX
            var yCoord = getYPos(targetEl) - getYPos(container)  + offsetY
            palettediv.style.top = yCoord + 'px';
          }
        else 
          {
            var landmark = document.getElementById('lastwords')//bottom of page            
            var xCoord = getXPos(targetEl) - getXPos(container) + offsetX
            var yCoord = getYPos(landmark) - getYPos(targetEl)  + offsetY
            
            palettediv.style.top = 'auto';
            palettediv.style.bottom = yCoord + 'px';;
           }
       
        palettediv.style.left = xCoord + 'px';
        palettediv.style.zIndex = 200             
        
        //setBGOpacity(backgroundOpacity)//dim the background 
        /*var strength = backgroundOpacity -35
        if (isSubpage)
          {
            var contentdivid = 'maincontent'  
            setOpacity(document.getElementById('sidebar'),strength)
            setOpacity(document.getElementById('headings'),strength)
          }
        else
          {
            var contentdivid = 'innercontainer'
          }
            
        var bg =  document.getElementById(contentdivid)
        setOpacity(bg,strength)   */         
        
        palettediv.style.visibility = 'visible'
        //find the palette's first form, and focus on the first element.
        try 
          {
            var firstForm = palettediv.getElementsByTagName('FORM')[0]        
            if (firstForm != null) {firstForm.elements[0].focus()}
          }
        catch(e){}
        currObj = palettediv
         
        incOpacity()            
        return false;          
          
      }
    
    //housekeeping function to reset page
    function putAwayPalette()
      {        
        currObj.style.visibility = 'hidden'
        closeLink.firstChild.nodeValue = 'Cancel '
        currObj.style.top = '0'
        currObj.style.left = '0'
        currObj.style.bottom = 'auto'
        currObj.style.zIndex = 0
        //housekeeping - reset to initial state.
        form1.style.display = ''
        setOpacity(form1,100)
        
        form2.style.display = 'none'
        setOpacity(form2,0)
        thx.style.display = 'none'
        setOpacity(thx,0)        
        
        setBGOpacity(100)//restore the background
        var contentdivid = (isSubpage)?'maincontent' : 'innercontainer'       
        var bg =  document.getElementById(contentdivid)
        
        if (isSubpage)
          {
            setOpacity(document.getElementById('sidebar'),100)
            setOpacity(document.getElementById('headings'),100)
          }        
        setOpacity(bg,100)        
        currStep = 0
      }
    
    //event handler to begin process of hiding palette    
    function hidePalette(paletteID)
      {
        var palettediv = document.getElementById(paletteID)
        terminalFunction = putAwayPalette
        if (palettediv == null) {return false}         
        currObj = palettediv;
        decOpacity()      
        return false;            
      }
    
   function escapePopup()
    {      
      window.open(this.href,'fullwin')
      
      try {
        if (self.opener){self.opener.blur()}
        self.close()
        }
      catch(e){}
      return false
    }  
    
     //== Add event handlers ====
    var callLink = document.getElementById('call')
    if (callLink)
      {
         if (isSubpage){callLink.onclick =  function(){return showPalette('calldiv','call',-32,5,'bottom')}}
         else{callLink.onclick =  function(){return showPalette('calldiv','call',-35,5,'bottom')}}
      }
      
     
    var loginLink = document.getElementById('mn_login')
    var loginpalette = document.getElementById('logindiv')
    if (loginLink && loginpalette) 
      {
        loginLink.onclick =  function(){return showPalette('logindiv','mn_login',-80,45)}
        var logClose  = document.getElementById('lg_close')
        if (logClose){ logClose.onclick = function (){return hidePalette('logindiv')}}
        document.getElementById('dologin').onclick = doLogin
      }
    
    var closeLink = document.getElementById('cf_close')
    closeLink.onclick = function (){return hidePalette('calldiv')}
    
    
           
   
    document.getElementById('callme').onclick =  submitStep
    document.getElementById('donebutton').onclick =  submitStep
    document.getElementById('services_requested_other').onclick = serviceHandler
    
    var form1 = document.getElementById('callform')
    var form2 = document.getElementById('callform2')
    var thx =  document.getElementById('thx')
    form2.style.display = 'none'
    thx.style.display = 'none'  
    var terminalFunctionInc = null
    var cr = '\n' //for debugging alerts 
    
    var bodyElem = document.getElementsByTagName('BODY')[0]
    
    var isPopup = (bodyElem.className == 'popup')
    if (isPopup) //add special event handlers to [almost] all links within a popup
      {
        var allLinks = bodyElem.getElementsByTagName('A'); var thisA
        for (var al = 0; al < allLinks.length; al++)
          {
            thisA = allLinks[al];
            if (!thisA.href.match(/popup/)) {thisA.onclick = escapePopup}
             
          }
      
      }
    
    var els2check = [$('subnav'),$('sn_login')]
    for (var e = 0; e< els2check.length; e++)
      {
        if (els2check[e])
          {
           snLK = els2check[e].getElementsByTagName('A')
           for (aLk = 0; aLk < snLK.length; aLk++)
            {
               if (snLK[aLk].href.match(/logout.cfm/)){snLK[aLk].onclick = function(){return confirm('Are you sure you want to log out?')}}
            }
          }
      }
  }
  
//----------------------------------------------------------------------------
//togglelayer shows or hides an object based on the display property (not visibility)
//it will detect the kind element it is and therefore the cross-browser method of hiding or showing the object.
//Garry Harstad: Oct 20006: enhanced to allow passing of an SPF flag (assumes the divid+"_spf" iframe exists) and will toggle accordingly.
//               Also, added 4th parameter to position the elements in the middle of the screen (flag).
//----------------------------------------------------------------------------
function togglelayer(divid,override,spf,positionmiddle)
{
   //alert("Display: "+divid+"\noverride:"+override);
   var myobj = document.getElementById(divid);
   if(!myobj) { window.status="[fn togglelayer] Problem! Could find element with ID '"+divid+"' to toggle."; return; }
   var mytagname = myobj.tagName
   //get the proper display style value, depending on element and browser
   //use self.innerHeight, which IE doesn't support, to determine block or table style
   switch (mytagname)
   {
      case 'DIV': { var  showstyle = "block"; break; }
      case 'SPAN': { var  showstyle = "inline"; break; }
      case 'I': { var  showstyle = "inline"; break; }
      case 'P': { var  showstyle = "block"; break; }
      case 'TABLE': { var  showstyle = self.innerHeight ? "table" : "block"; break; }
      case 'TR': { var  showstyle = self.innerHeight ? "table-row" : "block"; break; }
      case 'TD': { var  showstyle = self.innerHeight ? "table-cell" : "block"; break; }
      default: { var  showstyle = "block"; break; }
   }
   if(override == 1) { myobj.style.display = showstyle; if(spf==1) { blockburnthru(divid+"_spf",divid); } return;}
   if(override == 0) { myobj.style.display = "none"; if(spf==1) { blockburnthru(divid+"_spf",divid,true); } return;}
   if ((myobj.style.display == showstyle)||(myobj.style.display=="")||(myobj.style.display==null)) { myobj.style.display = "none"; if(spf==1) { blockburnthru(divid+"_spf",divid,true); } }
   else { myobj.style.display = showstyle; if(spf==1) { blockburnthru(divid+"_spf",divid); } }
}


//Function that creates an SPF iframe for an element/layer to be displayed if it doesn't have one.
//Also calls the togglelayer function to turn on or off the div/layer and SPF frame.
//Garry Harstad: Oct 2006
function togglelayer2(containerid,onoroff,positioninthemiddle)
{
   var cobj=objectMaker(containerid); if(!cobj) { return; }
   var spfobj=objectMaker(containerid+"_spf");
   if(spfobj==null && document.all)
   {
      spfobj=document.createElement("iframe");
      spfobj.id=containerid+"_spf";
      spfobj.name=containerid+"_spf";
      
      spfobj.src=jsprefixout+"blank.html";
      spfobj.className = "spf_iframe"
      
      document.body.appendChild(spfobj); 
      
   }
   togglelayer(containerid,onoroff,1);
   //alert(parseInt(onoroff))
   //if(parseInt(onoroff)==1) { blockburnthru(spfobj.id,containerid) }
   //else { blockburnthru(spfobj.id,containerid,1); }
   if(positioninthemiddle==true) { positionmiddle(cobj,onoroff,spfobj.id); }
}

//----------------------------------------------------------------------------
// START: Add and Remove Events
//----------------------------------------------------------------------------
function addEvent(elm, evType, fn, useCapture)
{
  if(typeof fn=="string") { fn=new Function(fn); }
  if (elm.addEventListener)
  {
    elm.addEventListener(evType,fn,useCapture);
    return true;
  }
  else if (elm.attachEvent)
  {
    var r = elm.attachEvent("on"+evType,fn);
    
    return r;
  }
  else { alert("[fn addEvent]\naddEventListener AND attachEvent not supported by Object Element.\nElement type="+elm); }
}

function removeEvent(elm, evType, fn,useCapture)
{
  if(typeof fn=="string") { fn=new Function(fn); }
  if (elm.addEventListener)
  {
    elm.removeEventListener(evType,fn,useCapture)
    return true;
  }
  else if (elm.attachEvent)
  {
    var r = elm.detachEvent("on" + evType, fn);
    return r;
  }
  else { alert("[fn removeEvent]\nremoveEventListener AND detachEvent not supported by Object Element.\nElement type="+elm); }
}
//----------------------------------------------------------------------------
// END: Add and Remove Events
//----------------------------------------------------------------------------

//function to get the text of a DOM node.
//calls itself recursively to burrow down into child nodes if first child isn't text.
function getNodeText(obj)
{
  if (obj.nodeType == 3)  {return(obj.nodeValue)}//obj is a text node, return its value    
  if(obj.firstChild == null) {return null;} //obj doesn't have children, return null    
  return getNodeText(obj.firstChild) //obj's an element, call myself. 
}

//get the [st] (search Term) query string value if it exists and highlight matching words within the body tag
function hilist()
{
   try
   {
      var nvp=""; var thispair=""; var thisname=""; var thisvalue=""; var thisvalarray="";
      var thisurl=window.location.href;
      if(!thisurl.match(/\?/)) { return; } // if no "?" then abort.
      var querystring=thisurl.split("?")[1];
      if(querystring=="") { return; }
      nvp=querystring.split("&");
      
      for (var i=0; i<nvp.length; i++)
      {
         thispair=nvp[i].split("=");
         if(thispair.length == 2)
         {
            var thisname=thispair[0].toLowerCase();
            if(thisname=="st" || thisname=="q")
            {
               thisname=thispair[0];
               thisvalue=thispair[1];
               highlightSearchTerms(unescape(thisvalue));
               //break;
            }
         }
      }
      //if(thisvalue == "") { return; }
      //highlightSearchTerms(unescape(thisvalue));
   }
   catch(e) { }
   
   
   //Do multiple keyowrds later. Try 1 first.
   //thisvalarray=thisvalue.split
   //alert(thisname+"="+thisvalue);
   /*
   var contentbox=document.getElementById(contentboxid);
   var tagnamearray="P,DIV,LI,A,SPAN".split(",");
   var keywordregex = /\b(\w+)BX\w+\b/;
   for(var L=0; L<tagnamearray.length; L++)
   {
      thistagname=tagnamearray[L];
      var collection=contentbox.getElementsByTagName(thistagname);
      for(var i=0; i<collection.length; i++)
      {
         thisobj=collection[i];
         thisobjtext=getNodeText(thisobj);
         if(thisobjtext != "" && thisobjtext!=null)
         {
            newtext=thisobjtext.gsub(keywordregex,"#{1}XXXXX");
            alert(thisobj.id+"\n"+thisobjtext+"\n"+newtext);
         }
      }
   }
   */
}

addEvent(window, "load", hilist)
//document.onload="hilist();";



/*
This is the function that actually highlights a text string by
adding HTML tags before and after all occurrences of the search
term. You can pass your own tags if you'd like, or if the
highlightStartTag or highlightEndTag parameters are omitted or
are empty strings then the default <font> tags will be used.
*/
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
   try
   {
        // the highlightStartTag and highlightEndTag parameters are optional
        if ((!highlightStartTag) || (!highlightEndTag)) {
          highlightStartTag = "<span class='hilisearchtext'>";
          highlightEndTag = "</span>";
        }
        
        // find all occurences of the search term in the given text,
        // and add some "highlight" tags to them (we're not using a
        // regular expression search, because we want to filter out
        // matches that occur within HTML tags and script blocks, so
        // we have to do a little extra validation)
        var newText = "";
        var i = -1;
        var lcSearchTerm = searchTerm.toLowerCase();
        var lcBodyText = bodyText.toLowerCase();
          
        while (bodyText.length > 0) {
          i = lcBodyText.indexOf(lcSearchTerm, i+1);
          if (i < 0) {
            newText += bodyText;
            bodyText = "";
          } else {
            // skip anything inside an HTML tag
            if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
              // skip anything inside a <script> block
              if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
                newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
                bodyText = bodyText.substr(i + searchTerm.length);
                lcBodyText = bodyText.toLowerCase();
                i = -1;
              }
            }
          }
        }
        return newText;
     }
     catch(e) { }
}


/*
This is sort of a wrapper function to the doHighlight function.
It takes the searchText that you pass, optionally splits it into
separate words, and transforms the text on the current web page.
Only the "searchText" parameter is required; all other parameters
are optional and can be omitted.
*/
var contentboxid="mcinner"; // the id of the DOM container that will be searched for matching search strings to highlight.
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
  
  var contentboxobj=document.getElementById(contentboxid);
  try
  {
     
     // if the treatAsPhrase parameter is true, then we should search for 
     // the entire phrase that was entered; otherwise, we will split the
     // search string so that each word is searched for and highlighted
     // individually
     if (treatAsPhrase) {
       searchArray = [searchText];
     } else {
       searchArray = searchText.split(" ");
     }
     
     if (!contentboxobj || typeof(document.body.innerHTML) == "undefined") {
       if (warnOnFailure) { return;
         alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
       }
       return false;
     }
     
     //var bodyText = document.body.innerHTML;
     var bodyText = contentboxobj.innerHTML;
     
     for (var i = 0; i < searchArray.length; i++) {
       bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
     }
     
     //document.body.innerHTML = bodyText;
     contentboxobj.innerHTML = bodyText;
     
     if(addPaginationHandlers)
      {
       function redoPagination() {addPaginationHandlers(document.getElementById('resultSet'))}
       setTimeout(redoPagination,100) //reinstate pagination handlers 
      }
     
     return true;
  }
  catch(e) { }
}
//new Draggable('ql',{snap:false,revert:true});