var isDev = false;
//============================================================
/*
 * swaps between the icon and the tools-plus-text toolbar view
 */
function ToolbarToggle(on,off,value) {
    var toggleto = document.getElementById(on);
    var toggleoff = document.getElementById(off);
    if (toggleto != null && toggleoff != null) {
        toggleto.style.display = "inline";
        toggleoff.style.display="none";
    }
    var topleftframe = top.frames["Corner"];
    var toprightframe = top.frames["Navbar"];
    if (topleftframe && toprightframe) {  // if framed we have to fix the top 2 frames --- go for the frameset.
        var oframeset = top.document.getElementById('OUTERFRAMESET');
        if (oframeset) {
            rows =  oframeset.getAttribute("rows");
            var where = rows.indexOf(',');
            var start = rows.indexOf('"');
            if (start == -1) {
                start = 0;
            }
            var height = parseInt(rows.substring(start,where));
            var incr = 26;
            if (value == 0)   {
                incr = -26;
            }
            height += incr;
            oframeset.setAttribute("rows",height + ",*");
            var doc = topleftframe.document;
            var elm = doc.getElementById("USERBARCONTENT");
            if (elm) {
                elm.style.height = elm.offsetHeight + incr;
            }
            elm = doc.getElementById("USERBARCONTENTLINE");
            if (elm) {
                elm.style.height = elm.offsetHeight + incr;
            }
        }
    }
    else  {
        var divs = document.getElementsByTagName("div");
        for (var i = 0;i < divs.length; i++)  {
            var div = divs[i];
            if (div.className == "b24-btb-icon") {
                if (value == 0)   {
                    div.style.display="inline";                    
                }
                else {
                    div.style.display="none";                    
                }
            }
            else if (div.className=="b24-btb-icontext") {
                if (value == 1)   {
                    div.style.display="inline";                    
                }
                else {
                    div.style.display="none";                    
                }
            }
        }
    }
    // now post the change back to the homeplanet where it'll get stored in the preferences
    var url = "/AjaxServices/B24Objects.aspx?method=SetPreference&key=bbt&value=" + value;
    if (isDev) {
        url = url + "./";
    }
    var _datenow = new Date();
    url += "&time=" + _datenow.getTime();  // make absolutely sure nobody caches it
    var xmlhttp = initXMLHttp();
    xmlhttp.open("GET", url);
    xmlhttp.onreadystatechange = function() { // don't care
    }
    xmlhttp.send(null);
}

var XMLHttpRequestObject;
//============================================================
function InsertCT(twistieTarget, sText)   {
    //    alert("InsertCT");
    var twistieImgId = "twist" + twistieTarget.substring(1);
    var twistieColumn = "twistietarget" + twistieTarget.substring(1);
    var img1 = document.getElementById(twistieImgId + "-closed");
    var img2 = document.getElementById(twistieImgId + "-working");
    var img3 = document.getElementById(twistieImgId + "-open");
    var col = document.getElementById(twistieColumn);
    if (img1 != null) {
        img1.style.display = 'none';
    }
    if (img2 != null) {
        img2.style.display = 'none';
    }
    if (img3 != null) {
        img3.style.display = 'inline';
    }
    if (col == null) {
        return;
    }
    if (col.className == "b24-annotation-content-locator") {
        var holder = document.createElement('div');
        holder.innerHTML = sText;
        //        holder.className="b24-annotation-show";
        col.appendChild(holder);
        return;
    }
    while (col && col.parentNode.nodeName != "TR") {  // find which is our column (otherwise can't locate our expanded text in the next row correctly */
        col = col.parentNode;
    }
    var row = col.parentNode;
    var up = row.parentNode;
    table = up;
    for(var i=0;i<table.rows.length;i++) {
        if (table.rows[i] == row) {
            var foundCell = 1;
            for (var j=0; j < row.cells.length; j++) {
                if  (row.cells[j] == col) {
                    foundCell = j;
                    break;
                }
            }
            var newrow = table.insertRow(i+1);
            var newcell = null;
            for (var j = 0; j < foundCell; j++) {
                var c = newrow.insertCell(j);
                c.colSpan = row.cells[j].colSpan;
            }
            newcell = newrow.insertCell(j);
            newcell.align = "left";
            if (col.colSpan == 1) {
                newcell.colSpan = 1;
                for (j++; j < row.cells.length; j++) {
                    newcell.colSpan += row.cells[j].colSpan;
                }
            }
            else {
                newcell.colSpan =col.colSpan;
            }
            newcell.innerHTML = sText;
            break;
        }
    }
}

  //==========================================================
function HideCT(bid, cid, lowrowid,justthisrowid)    {
    var cstable = null;
    var twistieImgId = "twist";
    var tableid = null;
    var onView = false;
    var onToc = false;
    var thisdoc = document;
    var contentframe = top.frames["Content"];
    if (contentframe != null) {
        framed = true;
        thisdoc = contentframe.document;
    }
    if (thisdoc.getElementById("ContentPage")) {
        onView = true;
    }
    else {
        onToc = true;
    }
    if (cid == null) {   // annotations in the list (only a bookid)
        tableid = "ANN"+bid;
        twistieImgId += bid;
    }
    else if (lowrowid != null) {  // annotations in the toc or chapter content
        tableid="ANN"+cid;
        twistieImgId += cid;
        if (onView) {  // it's in the content, only want this rowid.
            tableid += "-" + lowrowid;
        }
        var twistieImgId = "twist" + cid;
        if (lowrowid != null && (justthisrowid || onToc)) {
            twistieImgId += "-" + lowrowid;
        }
    }
    else {   // it's a chapter twistie
        tableid = "CS"+cid;
        twistieImgId += cid;
    }
    cstable = document.getElementById(tableid);
    if (cstable != null) {
        cstable.openstyle = cstable.style.display;
        cstable.style.display = 'none';
    }

    var img1 = document.getElementById(twistieImgId + "-closed");
    var img2 = document.getElementById(twistieImgId + "-working");
    var img3 = document.getElementById(twistieImgId + "-open");
    if (img1 != null) {
        img1.style.display = 'inline';
        img2.style.display = 'none';
        img3.style.display = 'none';
    }
}
//==========================================================
function ExpandDivForAnno(form_divID,control_divID)
{
document.getElementById(form_divID).style.display = "block";
document.getElementById(control_divID).innerHTML="<a href=\"javascript:CloseDivForAnno('" + form_divID +"','"+ control_divID+ "');\">" +
"<img class='b24-expando' src='images/dui_arrowdown.gif' alt='Hide All' title='Hide All' border='0' width='13' height='12'></img></a>";

}
function CloseDivForAnno(form_divID,control_divID)
{
document.getElementById(form_divID).style.display = "none";
document.getElementById(control_divID).innerHTML="<a href=\"javascript:ExpandDivForAnno('" + form_divID + "','"+ control_divID+ "');\">" +
"<img class='b24-expando' src='images/dui_arrowup.gif' alt='Show All' title='Show All' border='0' width='13' height='13'></img></a>";


}
function showdiv(img,code)
  {
  var thisdoc = document;
  var thebubblediv = (thisdoc.getElementById("thebubblediv")!=null)? thisdoc.getElementById("thebubblediv") : null;
  
  if(thebubblediv)
    {
        thebubblediv.tovar = setTimeout("reallyShow()",500);
        thebubblediv.img = img;
        thebubblediv.code = code;
    }
  }
function reallyShow()
{
  var thisdoc = document;
  var thebubblediv = (thisdoc.getElementById("thebubblediv")!=null)? thisdoc.getElementById("thebubblediv") : null;
  if (thebubblediv.tovar == null) {  // its timed out thank goodness
      return;
  }
  thebubblediv.tovar = null; 
  var img = thebubblediv.img;
  var code = thebubblediv.code;
  var thisdoc = document;
  var elepos = getPosition(img);
  var viewportdem = getViewportSize(thisdoc);
  var scrollpos = getScrollingPosition(thisdoc);
  var relobjpos = elepos[1] - scrollpos[1]; 
  var halfviewport = Math.round(viewportdem[1]/2);
  var tailgoes = ((relobjpos<halfviewport) || (location.href.indexOf("toc.asp")>=0) || (location.href.indexOf("viewer_r.asp")>=0))? "up" :  (relobjpos>halfviewport)? "down" : null;
  var bubbletable = (thisdoc.getElementById("bubble"+tailgoes)!=null)? thisdoc.getElementById("bubble"+tailgoes) : null;
  var otherbubble = (tailgoes=="up")? thisdoc.getElementById("bubbledown") : thisdoc.getElementById("bubbleup")
  var icontable = (thisdoc.getElementById("bubble"+tailgoes+"icons"))? thisdoc.getElementById("bubble"+tailgoes+"icons") : null;
  
  if(thebubblediv && bubbletable && icontable)
  {
      thebubblediv.style.display = "";
      bubbletable.style.display = "";
      otherbubble.style.display = "none"; 
      for(var x=1;x<icontable.rows.length;x++)
          {
              tr = thisdoc.getElementById(icontable.rows[x].id);
              var rowid = parseInt(tr.id.substr(1));
              if(code & rowid)
                  icontable.rows[x].style.display = "";
              else
                  icontable.rows[x].style.display = "none";
          }
      var bubbleheight = bubbletable.offsetHeight;
      if(tailgoes=="up")
          poptop = elepos[1] + 10;
      else 
          poptop = elepos[1] - bubbleheight + 6;
      thebubblediv.style.top = parseInt(poptop) + "px";
      thebubblediv.style.left = parseInt(elepos[0] - 76) + "px";
  }
   
}
//=========================================================
function hidediv()
  {
  var thebubblediv = document.getElementById("thebubblediv");
  if(thebubblediv) {
      thebubblediv.tovar = null;
      if (thebubblediv.style.display != "none") {
          pausecomp(1000);
      }
      thebubblediv.style.display = "none"; 
  }
  }

/* 
   try to get the style info for the annotation selector 
   from the stylesheet.  It still must be assigned using javascript
*/
var annotationBackgroundColor = null;
function getAnnotationBackgroundColor() {
    annotationBackgroundColor = "#DCEEF6";
    return annotationBackgroundColor;
}
/* set the annotation style and handle any css set background colors 
   gets called with the element to highlight 
*/
function setAnnotationSelectedParaStyle(target) {
    if (target == null || typeof target == "undefined") {
        return;
    }
    var container = document.createElement("span");
    container.className = "b24-notes-selectedpara";
    var child = target.firstChild;
    while (child != null) {
        var next = child.nextSibling;
        target.removeChild(child);
        container.appendChild(child);
        child = next;
    }
    target.appendChild(container);
}
function unsetAnnotationSelectedParaStyle(target) {
    if (target == null || typeof target == "undefined") {
        return;
    }
    var container = target.firstChild
    if (container.className != "b24-notes-selectedpara")  {
        return;
    }
    target.removeChild(container);
    var child = container.firstChild;
    while (child != null) {
        var next = child.nextSibling;
        container.removeChild(child);
        target.appendChild(child);
        child = next;
    }
}

//=========================================================
function pausecomp(millis)
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); }
while(curDate-date < millis);
} 
//=========================================================
// display the download dialog
//==========================================================
function ShowDown(id, chk)
{
  var bid = (id && isNaN(id))? null : id;
  var cid = (chk && isNaN(chk))? null : chk;
  if(bid==null) return;
  var param = "?svc=down";
  var framed = false;
  var thisdoc = document;
  var contentframe = top.frames["Content"];
  if (contentframe != null) 
  {
    framed = true;
    thisdoc = contentframe.document;
  }

  var scrollpos = getScrollingPosition(thisdoc);
  //var clouddem = getViewportSize(thisdoc);
  var cloud = thisdoc.getElementById('overlay');
  var bubble = thisdoc.getElementById('download');
  AnnotationRemoveContentDecorations(bubble,thisdoc);

  /*  if (bubble.style.display == "inline" && bubble.className == "b24-download_bubble") {
      SunDown();
  }
  */
  bubble.innerHTML = "";
    
  param += "&data="+bid;
  if(cid) param +="&data="+cid;
  //window.frames["dataframe"].location.href = "data.asp"+param;
  var dataSource =  "data.asp" + param; 
  XMLHttpRequestObject.open("GET", dataSource);
  XMLHttpRequestObject.onreadystatechange = function()
  {
    if (XMLHttpRequestObject.readyState == 4 &&
        XMLHttpRequestObject.status == 200) {
            bubble.innerHTML = XMLHttpRequestObject.responseText;
  }
  if (XMLHttpRequestObject.readyState == 4 &&
      XMLHttpRequestObject.status == 403) {
          if (XMLHttpRequestObject.responseText.indexOf("code='1'") != -1) {
              window.location.reload();
          }
          else if (XMLHttpRequestObject.responseText.indexOf("code=\"1\"") != -1) {
              window.location.reload();
          }
          else if (XMLHttpRequestObject.responseText.indexOf("code=1") != -1) {
              window.location.reload();
          }
          else 
          {
              bubble.innerHTML = XMLHttpRequestObject.responseText;
          }
      }
    }
  XMLHttpRequestObject.send(null);
  bubble.className = "b24-download_bubble";
  bubble.style.width = 380;
  bubble.style.left = "195px";
  bubble.style.top = ((location.href.indexOf("viewer")>=0)? 10+scrollpos[1] : 130+scrollpos[1]) + "px";
  bubble.style.display = "inline";
}
// move the annotation dialog to a specific spot on the page.
//
function MoveDialog(rowid,elementid,labeltitleid) {
  var thisdoc = document;
  var contentframe = top.frames["Content"];
  if (contentframe != null)
  {
    framed = true;
    thisdoc = contentframe.document;
  }
  //var clouddem = getViewportSize(thisdoc);
  var bubble = thisdoc.getElementById('download');
  if (!bubble) {
      return;
  }
  bubble.WasMoved = true;
  bubble.WasMovedRow = rowid;
  bubble.WasMovedElementId = elementid;
  bubble.WasMovedLableTitleId = labeltitleid;
  if (bubble.elementid) {
      var prevtarget = thisdoc.getElementById(bubble.elementid);
      if (prevtarget) {
          unsetAnnotationSelectedParaStyle(prevtarget);
      }
  }
  var targ = thisdoc.getElementById(elementid);
  if (targ != null) {
      var elepos = getPosition(targ);
      var viewportdem = getViewportSize(thisdoc);
      var scrollpos = getScrollingPosition(thisdoc);
      var relobjpos = elepos[1] - scrollpos[1]; 
      var halfviewport = Math.round(viewportdem[1]/2);
      var tailgoes = ((relobjpos<halfviewport) || (location.href.indexOf("toc.asp")>=0) || (location.href.indexOf("viewer_r.asp")>=0))? "up" :  (relobjpos>halfviewport)? "down" : null;
      var bubbleheight = bubble.offsetHeight;
      var poptop;
      poptop = elepos[1] + 30;
      if (bubbleheight + relobjpos + 30 > viewportdem[1]) {
          //          var adjustment = viewportdem[1] - bubbleheight - relobjpos;
          poptop = poptop - bubbleheight - 30;
          if (poptop < 0) {
              poptop =0;
          }
      }
      var inputElement = thisdoc.getElementById("rowid");  // so it'll move along with our form post
      if (inputElement != null) {  // set the rowid hidden input element
          inputElement.value = rowid;
      }
      inputElement = thisdoc.getElementById("elementid");
      if (inputElement != null) { // the elementid hidden elementid
          inputElement.value = elementid;
      }
      bubble.rowid=rowid;  // store where we are so if we're moved, we can unset the highlight color
      bubble.elementid=elementid;
      bubble.prevBackgroundColor = targ.style.backgroundColor;
      bubble.style.top = parseInt(poptop) + "px";
      setAnnotationSelectedParaStyle(targ);
  }
  var title = thisdoc.getElementById(labeltitleid);
  if (title != null) {
      var titletext = "";
      if (title.className.indexOf("label") != -1) {
          title = title.parentNode;
      }
      if (title.innerText) {
          titletext = title.innerText;
      }
      else {
          titletext = title.textContent;
      }
      var original = thisdoc.getElementById("bmkoriginallabel");      
      var otext = "";
      if (original) {
          if (original.innerText) {
              otext = original.innerText;
          }
          else  {
              otext = original.textContent;
          }
      }
      if (otext.length > 0) {
          var where = otext.indexOf('-');
          var ocompare = otext;
          if (where > 0 && where < otext.length / 2) {
              ocompare = trim(otext.substring(where + 1));
          }
          where = titletext.indexOf(':');
          var tcompare = titletext;
          if (where > 0 && where < titletext.length / 2) {
              tcompare = trim(titletext.substring(where + 1));
          }
          if (ocompare.indexOf(tcompare) == -1)   {
              titletext = trim(otext) + " (" + trim(titletext) + ")";
          }
      }
      var label = thisdoc.getElementById("bmklabl2");
      
      if (label != null) {
          label.setAttribute("VALUE",titletext);
          label.value = titletext;
      }
  }
}

function RandomClick(targetid)
{
   var bubble = document.getElementById('download');
   if (bubble == null)    {
       lastClickInContentId = targetid;
       return;
   }
   if (bubble.style.display == "inline" && bubble.className == "b24-annotation_dialog") {
       /*       // our bubble is in view! we want to do a move!
       var target = document.getElementById(targetid);
       if (target) {
           var links = target.getElementsByTagName("a");
           for (var i = 0; i < links.length; i++) {
               var a = links[i];
               if (a.parentNode.className == "b24-annotation-target")  {
                   eval(a.getAttribute("href"));
                   break;
               }
           }
       }
       */
       // pam rightly pointed out that the above means you can cut and paste when the bubble is a float
   }
   else {  // just record the click
       lastClickInContentId = targetid;
   }
}
// 
// manages the annotations on the content page.
//
// we don't want to deliver them with the actual book content
// as that would complicate our Akamai content cache
//
// So it's stored at the bottom of the html and this bit of
// javascript scoops it up
//
// this also highlights the annotated text
//
function AnnotationHighlight(elementid) {
  var framed = false;
  var thisdoc = document;
  var contentframe = top.frames["Content"];
  if (contentframe != null)
  {
    framed = true;
    thisdoc = contentframe.document;
  }
  var qbookmark = false;
  var quickbookmark = thisdoc.getElementById("isquickbookmark");
  if (quickbookmark != null) {
      qbookmark = true;
      var itsnewhome = thisdoc.getElementById("annotationlabel-first");
      if (itsnewhome != null) {
          quickbookmark.parentNode.removeChild(quickbookmark);
          var firstchild = itsnewhome.firstChild;
          itsnewhome.insertBefore(quickbookmark,firstchild);
      }
  }
  /*  don't highlight at the moment
      if (elementid != null) { // want to highlight the annotated text
      var target = thisdoc.getElementById(elementid);
      if (target != null) {
          setAnnotationSelectedParaStyle(target);
      }
      } */
  var imgtarget = null;
  var targetSpans = thisdoc.getElementsByTagName("span");
  for (var i = 0; i < targetSpans.length; i++)
      {
          var span = targetSpans[i];
          if (span.className != "b24-annotation-target") {  // someplace we can annotation
              continue;
          }
          var onclick = span.getAttribute("ids");
          var args = onclick.split(',');
          var onclickArg = "MoveDialog(";
          if (args.length > 0)  {
              onclickArg += args[0] + ",";
              if (args.length > 1) {
                  onclickArg += "'" + args[1] + "',";
                  if (args.length > 2) {
                      onclickArg += "'" + args[2] + "'";
                      if (span.getAttribute("labelid") == '')     {
                          span.setAttribute("labelid",args[2]);
                      }
                  }
              }
          }
          onclickArg += ")";
          span.onclick = new Function(onclickArg);
          span.on
          var child = span.firstChild;          
          while (child != null) {  // 
              if (child.nodeName.toLowerCase() == "a") {
                  if (imgtarget == null) {
                      child.innerHTML = "<img class='b24-expando' SRC='images/tool_annotate_sm.gif' WIDTH='12' HEIGHT='12' BORDER='0' STYLE='display:inline;'  ALT='Add a Note Here' TITLE='Add a Note Here'/>"; 
                      imgtarget = child.firstChild;
                  }
                  else {
                      child.appendChild(imgtarget.cloneNode(true));
                  }
                  break;
              }
              child = child.nextSibling;
          }
          if (child == null) {
              if (imgtarget == null) {
                  span.innerHTML = "<img class='b24-expando' SRC='images/tool_annotate_sm.gif' WIDTH='12' HEIGHT='12' BORDER='0' STYLE='display:inline;'  ALT='Add a Note Here' TITLE='Add a Note Here'/>"; 
                  imgtarget = span.firstChild;
              }
              else {
                  span.appendChild(imgtarget.cloneNode(true));
              }
          }
          var target = null;
          var parent = null;
          try {
              parent = span.parentNode;
          } catch (e)
              {
                  continue;
              }
          parent.onmousedown=function() {
              RandomClick(this.getAttribute("id"));
          }
          //          parent.setAttribute("onmousedown","RandomClick('" + target + "')");
          /*          while (span)  {   // flag all the text nodes inside it
              var next = span.nextSibling;
              if (span.nodeType == 3)  {
                  hotspot = thisdoc.createElement("span");
                  parent.insertBefore(hotspot,span);
                  parent.removeChild(span);
                  hotspot.appendChild(span);
                  hotspot.setAttribute("onmousedown","RandomClick('" + target + "')");
                  hotspot.setAttribute("onclick","RandomClick('" + target + "')");
              }
              span = next;
          }
          */
      }
  var annotations = thisdoc.getElementById("AnnotationOrigin");
  if (annotations != null) {  // find any annotations and move them up to their rightful place
      var note = annotations.firstChild;
      while (note != null) {
          var next = note.nextSibling;
          if (note.className == "b24-viewer-annotation" || note.className == "b24-annotation")  {
              var target = note.getAttribute("LOCATOR");
              if (target != null && target.indexOf("bookmark") != -1) {
                  if (target == "bookmark" && qbookmark)
                      {
                          note = next;
                          continue;
                      }
                  target = target.substring(8);
                  var properplace = thisdoc.getElementById(target);
                  var unattached = false;
                  if (properplace == null) {
                      properplace = thisdoc.getElementById("ContentPage");
                  }
                  if (properplace != null) {
                      note.parentNode.removeChild(note);
                      if (unattached) {
                          properplace.parentNode.insertBefore(note,properplace);
                      }
                      else {
                          var wrapper = thisdoc.createElement("div");
                          wrapper.className = "b24-annotation_wrapper";
                          properplace.parentNode.insertBefore(wrapper,properplace);
                          properplace.parentNode.removeChild(properplace);
                          wrapper.appendChild(properplace);
                          wrapper.appendChild(note);
                          IGEInitializeNotesAndComments(note)
                      }
                  }
              }
          }
          note = next;
      }
      /*
      for (var i = 0; i < annotations.childNodes.length; i++) {
          var note = annotations.childNodes[i];
          if (note.className == "b24-annotation")  {
              var target = note.getAttribute("LOCATOR");
              if (target != null && target.indexOf("bookmark") != -1) {
                  target = target.substring(8);
                  var properplace = thisdoc.getElementById(target);
                  if (properplace != null) {
                      note.parentNode.removeChild(note);
                      properplace.parentNode.insertBefore(note,properplace);
                      i--;
                  }
              }
          }
      }
      */
  }
}

function ShowAnnotationBuildBubble(thisdoc,bid,cid) {
  var bubble = thisdoc.getElementById('download');
  if (bubble == null) {
      bubble = thisdoc.createElement("div");
      bubble.className = "b24-download-bubble";
      bubble.setAttribute("id", "download");
      thisdoc.body.appendChild(bubble);
  }
  
  if (bubble.style.display == "inline" && bubble.className == "b24-annotation_dialog") {
      SunDown();
      return null;
  }

  bubble.editMode = false;
  bubble.annotationTargetsVisible = false;
  bubble.elementid = null;
  
  var scrollpos = getScrollingPosition(thisdoc);
  //  var clouddem = getViewportSize(thisdoc);
  bubble.innerHTML = "";
  bubble.className = "b24-annotation_dialog";
  //bubble.style.width = 380;
  bubble.style.width = 580;
  bubble.style.left = parseInt(245) + "px";
  if (!bubble.WasMoved) {
      bubble.style.top = "0px";
      if (location.href.indexOf("viewer")>=0)  {
          bubble.style.left = parseInt(100) + "px";
          bubble.style.top = parseInt(50+scrollpos[1]) + "px";
          var player = thisdoc.getElementById("b24-videoPlayer");
          if (player != null) {
              var elepos = getPosition(player);
              bubble.style.left = parseInt(elepos[0] + player.clientWidth + 10) + "px";
              bubble.style.top = parseInt(elepos[1]) + "px";
          }
      }
      else { 
          bubble.style.top = parseInt(200+scrollpos[1]) + "px";
          if (isIE6) {
              bubble.style.top = parseInt(300+scrollpos[1]) + "px";
          }
      }
  }
  var focuser = new Focuser("focusitem1");
  focuser.SetIntervalID(setInterval(focuser.SetFocus, 2000));

  bubble.bookid = bid;
  bubble.chunkid = cid;

  return bubble;
}

function ShowAnnotationCompleteBubble(bubble,responseHTML,thisdoc,dialogtitle) {
    var html = "";
    html += "<div class='dialog' id='AnnDialog'> ";
    html += "<div class='annocontent'>";
    html += "<div class='annot'></div>";
    html += "<div id='annomovetarget' class='annomovetarget'><span>&nbsp;</span>";
    html += "<p class='hd'>" + dialogtitle + "</p>";
    html += "</div>";
    html += responseHTML;
    html += "</div>";
    html += "<div class='annobottom'><div class ='fixed' >&#160;</div></div>";
    var browser = navigator.appName;
    /* didnt work
    if (browser == "Microsoft Internet Explorer") {
        html = "<iframe class='ie6bleedthrough' id='menu4iframe' src=\"javascript:'';\" > ";
        html += "</iframe>";
        }
    */
    bubble.innerHTML = html;
    bubble.style.display = "inline";
    var movetarget = thisdoc.getElementById("annomovetarget");
    if (bubble.toolbutton != null) {
        bubble.toolbutton.disabled = false;
        bubble.toolbutton.style.cursor = "default";
        if (bubble.toolbuttonimagefolder) {
          bubble.toolbutton.src = bubble.toolbuttonimagefolder + '/' + bubble.toolbuttonpushedimg;
        }
    }
    else if (bubble.editlink != null) {
        bubble.editlink.className='inactive';
        bubble.editlink.style.cursor = "default";
        bubble.editlink.style.color = "#0000FF";
    }

    new Draggable(bubble,movetarget);
}

//=========================================================
// display the annoation dialog
//
function ShowAnnotationDialog(id, chk, bookmarkid,iscorporatenote,ispublic) {
  if (iscorporatenote == null) {
     iscorporatenote = 0;
  }
  if (ispublic == null)
      {
          ispublic = true;
      }
  var toolbutton = null;
  var editlink = null;
  if (bookmarkid == null) {
      toolbutton = document.getElementById("ShowAnnotationDialogButton");
      if (toolbutton) {
          toolbutton.disabled = true;
          toolbutton.style.cursor = "wait";
          toolbutton.savealt = toolbutton.alt;
          toolbutton.savetitle=toolbutton.title;
          toolbutton.alt="Please wait for the note creation dialog";
          toolbutton.title="Please wait for the note creation dialog";
      }
  }
  else {
      editlink = document.getElementById("editlink" + bookmarkid);
      if (editlink != null) {
          var children = editlink.getElementsByTagName("a");
          if (children && children.length>0) {
              editlink = children[0];
              editlink.className='active';
              editlink.style.cursor = "wait";
              editlink.style.color = "pink";
          }
      }
  }
  var bid = (id && isNaN(id))? null : id;
  var cid = (chk && isNaN(chk))? null : chk;
  if(bid==null) return;
  var thisdoc = document;
  var contentframe = top.frames["Content"];
  if (contentframe != null)
  {
    thisdoc = contentframe.document;
    contentframe.ShowAnnotationDialog_inner(top,thisdoc, id, chk, bookmarkid,iscorporatenote,ispublic, toolbutton,editlink);
  }
  else {
     ShowAnnotationDialog_inner(top,thisdoc, id, chk, bookmarkid,iscorporatenote,ispublic,toolbutton,editlink);
  }
}

var lastClickInContentId = null;

function ShowAnnotationDialog_inner (ourframe,thisdoc,id, chk, bookmarkid,iscorporatenote,ispublic,toolbutton,editlink) {
  var bid = (id && isNaN(id))? null : id;
  var cid = (chk && isNaN(chk))? null : chk;
  var bubble = ShowAnnotationBuildBubble(thisdoc,bid,cid);
  if (bubble == null) {
      return;
  }
  bubble.toolbutton = toolbutton;
  bubble.editlink = editlink;
  if (toolbutton) {
      bubble.toolbuttonwaitingimg = "tool_annotate_waiting.gif";
      bubble.toolbuttonpushedimg = "tool_annotate_bruised.gif";
      var img = bubble.toolbutton.src;
      if (img) {
          var where = img.lastIndexOf('/');
          bubble.toolbuttonimagefolder = img.substr(0,where);
          bubble.toolbuttondefaultimg = img.substring(where + 1);
          bubble.toolbutton.src = bubble.toolbuttonimagefolder + '/' + bubble.toolbuttonwaitingimg;
      }
  }
  if (bookmarkid != null) {
      bubble.editMode = true;
  }
  var annotationTitle = "Edit Note";
  if (!bubble.editMode) {  // this displays the annotation target links along the left.
      toggleHighlight('zannotationtargettoggle.css', 'annotationtargetson', 'annotationtargetssoff', 'noinlineannotationtargets');
      bubble.annotationTargetsVisible = true;
      annotationTitle = "Create Note";
  }
  var param = "?svc=anndialog";
  param += "&data="+bid;
  if(cid != null) param +="&data="+cid;
  if(bookmarkid) param +="&data="+escape(bookmarkid);
  if (iscorporatenote == 1) {
      param += "&corpnote=1";
  }
  if (ispublic) {
      param += "&ispublic=1";
  }
  var elmid = InitialBubblePosition(thisdoc,bubble);
  var d = new Date();
  param += "&timeoffset=" + d.getTimezoneOffset();
  //window.frames["dataframe"].location.href = "data.asp"+param;
  var dataSource =  "data.asp" + param; 
  var _datenow = new Date();  
  dataSource += "&time=" + _datenow.getTime();  // make absolutely sure nobody caches it

  xmlrequest =  initXMLHttp();
  xmlrequest.open("GET", dataSource);
  xmlrequest.setRequestHeader("Content-Type"," application/x-javascript; charset=ISO-8859-1"); 
  xmlrequest.onreadystatechange = function() {
      if (xmlrequest.readyState == 4 &&
          xmlrequest.status == 200) {
          /*
          */
              if (lastClickInContentId != null )
              {
                  elmid = InitialBubblePosition(thisdoc,bubble);
              }
              if (bubble.toolbutton != null) {
                  if (bubble.toolbutton.savealt) {
                      bubble.toolbutton.alt = bubble.toolbutton.savealt;
                      bubble.toolbutton.title=bubble.toolbutton.savetitle;
                      bubble.toolbutton.savealt = null;
                      bubble.toolbutton.savetitle = null;
                  }
              }

              var responseHTML = xmlrequest.responseText;
              ShowAnnotationCompleteBubble(bubble,responseHTML,thisdoc,annotationTitle);
              if (bubble.WasMoved) {
                  MoveDialog(bubble.WasMovedRow,bubble.WasMovedElementId,bubble.WasMovedLableTitleId);
                  bubble.WasMoved = false
                      bubble.WasMovedRow = null;
                  bubble.WasMovedElementId = null;
                  bubble.WasMovedLableTitleId = null;
              }
              else {
                  if (!bubble.editMode) {  // this if the first annotatable spot on the page.  Move the dialog here.  This will also set the elementid to be 
                      if (elmid) {
                          MoveDialog(-1,elmid,bubble.labelToUse);
                          var scrollpos = getScrollingPosition(thisdoc);
                          bubble.style.top = ((location.href.indexOf("viewer")>=0)? 100+scrollpos[1] : 130+scrollpos[1]) + "px";
                      }
                  }
              }
          }
      if (xmlrequest.readyState == 4 &&
          xmlrequest.status == 403) {
              if (xmlrequest.responseText.indexOf("code='1'") != -1) {
                  ourframe.location.reload();
              }
              else if (xmlrequest.responseText.indexOf("code=\"1\"") != -1) {
                  ourframe.location.reload();
              }
              else if (xmlrequest.responseText.indexOf("code=1") != -1) {
                  ourframe.location.reload();
              }
              else 
              {
                  bubble.innerHTML = xmlrequest.responseText;
              }
              bubble.style.display = "inline";
          }
  }
  xmlrequest.send(null);
}
function InitialBubblePosition(thisdoc,bubble)
{
    if (bubble.elementid) {
        var prevtarget = thisdoc.getElementById(bubble.elementid);
        if (prevtarget) {
            unsetAnnotationSelectedParaStyle(prevtarget);
        }
    }

    var elmid = null;
    var target = thisdoc.getElementById('b24-first-annotationtarget');
    if (lastClickInContentId != null) {
        elmid = lastClickInContentId;
        target = thisdoc.getElementById(elmid);
        if (target == null) {
            target = thisdoc.getElementById('b24-first-annotationtarget');
            lastClickInContentId = null;
        }
    }
    if (target != null && !bubble.editMode) {  // this if the first annotatable spot on the page.  Move the dialog here.  This will also set the elementid to be 
        bubble.labelToUse = "annotationlabel-first";
        elmid = target.getAttribute("targetid");
        if (lastClickInContentId != null) {
            elmid = lastClickInContentId;
        }                
        lastClickInContentId = null;
        var viewportdem = getViewportSize(thisdoc);
        var scrollpos = getScrollingPosition(thisdoc);
        var elepos = getPosition(target);
        var relobjpos = elepos[1] - scrollpos[1]; 
        //                  alert(elepos[1] + "/" + scrollpos[1]);
        if (elepos[1] <= scrollpos[1]) {
            var spans = thisdoc.getElementsByTagName("span");
            for (var i = 0; i < spans.length; i++) {
                if (spans[i].className == "b24-annotation-target") {
                    elepos = getPosition(spans[i]);
                    if (elepos[1] >= scrollpos[1]) {
                        if (i < spans.length - 1) {  // pick next to make sure it's all visible (not sliced in half)
                            i++;
                        }
                        elmid = spans[i].parentNode.getAttribute("id");
                        //                                  alert(elmid);
                        if (elmid != null) {
                            if (spans[i].getAttribute("labelid")) {
                                bubble.labelToUse = spans[i].getAttribute("labelid");
                            }
                            break;
                        }
                    }
                }
            }
        }
        var targ = thisdoc.getElementById(elmid);
        if (targ != null) {
            bubble.elementid = elmid;
            setAnnotationSelectedParaStyle(targ);
        }
    }
    return elmid;
}

function Draggable(el,movetarget)
{

  var  isMozilla = (document.all) ? 0 : 1;

  var xDelta = 0, yDelta = 0;
  var xStart = 0, yStart = 0;
  var moveme = movetarget;
  if (moveme == null) {
      moveme = el;
  }
  // remove the events
  function enddrag()
  {
    document.onmouseup = null;
    document.onmousemove = null;
  }

  // fire each time it's dragged
  function drag(e)
  {
    e = e || window.event;
    xDelta = xStart - parseInt(e.clientX);
    yDelta = yStart - parseInt(e.clientY);
    xStart = parseInt(e.clientX);
    yStart = parseInt(e.clientY);
    if (parseInt(el.style.top) - yDelta < 0)  {
      return;
    }
    el.style.top = (parseInt(el.style.top) - yDelta) + 'px';
    el.style.left = (parseInt(el.style.left) - xDelta) + 'px';
  }
  // fire each time it's dragged
  function hover(e)
  {
  }
  
  // initiate the drag
  function md(e)
  {
    e = e || window.event;
    xStart = parseInt(e.clientX);
    yStart = parseInt(e.clientY);
    /*    el.style.top = parseInt(getStyle(el,'top')) + 'px';
          el.style.left = parseInt(getStyle(el,'left')) + 'px';
    */
    document.onmouseup = enddrag;
    document.onmousemove = drag;
    return false;
  }

  // tie it into the element
  moveme.onmousedown = md;
  moveme.onmouseover = hover;
}


//=========================================================
// display the managetitle dialog
//
function ShowManagetitleDialog(type,id, chk) {
  var toolbutton = null;
  if (type=="manage") {
      toolbutton = document.getElementById("BrowseToolManageBookId" + id);
  }
  else {
      toolbutton = document.getElementById("BrowseToolFolderId" + id);
  }
  if (toolbutton) {
      toolbutton.disabled = true;
      toolbutton.style.cursor = "wait";
  }

  var bid = (id && isNaN(id))? null : id;
  var cid = (chk && isNaN(chk))? null : chk;
  if(bid==null) return;
  var thisdoc = document;
  var contentframe = top.frames["Content"];
  if (contentframe != null)
  {
    thisdoc = contentframe.document;
    contentframe.ShowManagetitleDialog_inner(type,top,thisdoc, id, chk,toolbutton);
  }
  else {
     ShowManagetitleDialog_inner(type,top,thisdoc, id, chk,toolbutton,toolbutton);
  }
}
// have to make sure we're executing in the right frame
function ShowManagetitleDialog_inner(type,ourframe,thisdoc,id, chk,toolbutton) {
  var bid = (id && isNaN(id))? null : id;
  var cid = (chk && isNaN(chk))? null : chk;
  if(bid==null) return;

  var bubble = ShowAnnotationBuildBubble(thisdoc,bid,cid);
  if (bubble == null) {
      return;
  }
  bubble.toolbutton = toolbutton;
  bubble.managetype=type;
  var param = "?svc=managetitle";
  param += "&data="+bid;
  if(cid != null) param +="&data="+cid;
  //window.frames["dataframe"].location.href = "data.asp"+param;
  var dataSource =  "data.asp" + param; 
  var _datenow = new Date();  
  dataSource += "&time=" + _datenow.getTime();  // make absolutely sure nobody caches it
  xmlrequest =  initXMLHttp();
  xmlrequest.open("GET", dataSource);
  xmlrequest.onreadystatechange = function() {
      if (xmlrequest.readyState == 4 &&
          xmlrequest.status == 200) {
          /*
          */
              var responseHTML = xmlrequest.responseText;
              ShowAnnotationCompleteBubble(bubble,responseHTML,thisdoc,"Manage Title");
          }
      if (xmlrequest.readyState == 4 &&
          xmlrequest.status == 403) {
              if (xmlrequest.responseText.indexOf("code='1'") != -1) {
                  ourframe.location.reload();
              }
              else if (xmlrequest.responseText.indexOf("code=\"1\"") != -1) {
                  ourframe.location.reload();
              }
              else if (xmlrequest.responseText.indexOf("code=1") != -1) {
                  ourframe.location.reload();
              }
              else 
              {
                  bubble.innerHTML = xmlrequest.responseText;
              }
              bubble.style.display = "inline";
          }
  }
  xmlrequest.send(null);
 
}
function AuthorReverse(author) {
    var parts = author.split(' ');
    var splitAt = 0;
    if (parts.length < 2) {
        return author;
    }
    if (parts[1].length == 1 || parts[1].indexOf('.') > 0) {
        splitAt = 2;
    }
    else {
        splitAt = 1;
    }
    var name = "";
    for (var i = splitAt; i < parts.length; i++) {
        if (name.length > 0) {
            name += ' ';
        }
        name += parts[i];
    }
    name += ',';
    for (var i = 0; i < splitAt; i++) {
        name += ' ' + parts[i];
    }
    return name;
}

//=========================================================
function ShowCitation(id, _type, chk, offsetfromclick) {
  var reposition = (offsetfromclick) ? true : false;
  var bid = (id && isNaN(id))? null : id;
  var cid = (chk && isNaN(chk))? null : chk;
  var booktype = (_type == null || isNaN(_type)) ? 1 : _type
  if(bid==null) return;
  var param = "?svc=down";
  var framed = false;
  var thisdoc = document;
  var bubble = thisdoc.getElementById('download');
  if (bubble == null) {
      var contentframe = top.frames["Content"];
      if (contentframe != null)  {
          framed = true;
          thisdoc = contentframe.document;
      }
      bubble = thisdoc.getElementById('download');
  }
  var scrollpos = getScrollingPosition(thisdoc);
  //var clouddem = getViewportSize(thisdoc);
  var bubble = thisdoc.getElementById('download');

  AnnotationRemoveContentDecorations(bubble,thisdoc);

  if (bubble.style.display == "inline" && bubble.className == "b24-citation_bubble") {
      SunDown();
      if (!reposition) {
          return;
      }
  }
  bubble.innerHTML = "";
  bubble.className = "b24-citation_bubble";
  bubble.style.left = 195 + "px";
  bubble.style.top = ((location.href.indexOf("viewer")>=0)? 10+scrollpos[1] : 130+scrollpos[1]) + "px";
  if (reposition) {
      var linkpos = document.getElementById("citelink" + bid);
      if (linkpos) {
          var elepos = getPosition(linkpos);
          bubble.style.top = (elepos[1] + 10) + "px";
      }
  }
  bubble.style.width = 380;
  bubble.style.display = "inline";
  var focuser = new Focuser("focusitem1");
  focuser.SetIntervalID(setInterval(focuser.SetFocus, 2000));
  var bookSpan = thisdoc.getElementById('b24-booktype-' + bid);
  if (bookSpan) {
      if (bookSpan.innerText) {
          booktype = bookSpan.innerText;
      }
      else {
          booktype = bookSpan.textContent;
      }
  }
  var html = "<div class='dialog'>";
  html += "<div class='content'>";
  //  html += "<div class='t'><span class='close'><A HREF='javascript:void(0)' onclick='javascript:SunDown();'><IMG align='right' SRC='images/dialog_close.gif' border='0' height='13' width='17' alt='click here to close' onclick='javascript:SunDown();'></A></span></div>";
  html += "<div class='t'></div>";
  //  html += "<div class='r'><LABEL STYLE='display:none' FOR='dialog-close'>Close</LABEL><A ID='dialog-close' HREF='javascript:void(0)' onclick='javascript:SunDown();'>x</A></span></div>";
  html += "<div class='r'><A HREF='javascript:void(0)' onclick='javascript:SunDown();'><IMG SRC='images/bubble_x.gif' border='0' height='7' width='5' alt='click here to close' title='click here to close' onclick='javascript:SunDown();'></A></div>";
  html += "<p class='hd'>Citation for this title:</p>";
  //  html += "<h1>Citation for this title:</h1>";
  html += "<p><div class='b24-citations-content'>";
  if (booktype == 3 || booktype == 7) {
      var authorSpan = thisdoc.getElementById('b24-editor-' + bid);
      if (authorSpan) {
          html += "<span class='b24-citations_'>";
          if (authorSpan.innerText) {
              html += authorSpan.innerText;
          }
          else {
              html += authorSpan.textContent;
          }
          html += " ed";
          html += "</span>";
          html += ". ";
      }
  }
  else {
      var authorSpan = thisdoc.getElementById('b24-bookauthor-' + bid);
      if (authorSpan) {
          var nmAuthors = 0;
          for (var i = 0; i < authorSpan.childNodes.length; i++) {
              var child = authorSpan.childNodes[i];
              if (child.className == 'b24-bookauthor') {
                  nmAuthors++;
              }
          }
          var authors = 0;
          for (var i = 0; i < authorSpan.childNodes.length; i++) {
              var child = authorSpan.childNodes[i];
              if (child.className == 'b24-bookauthor') {
                  authors++;
                  if (authors > 1 && authors == nmAuthors) {
                      html += ", and ";
                  }
                  else if (authors > 1) {
                      html += ", ";
                  }
                  html += "<span class='b24-citations_author'>";
                  var name = "";
                  for (var j = 0; j < child.childNodes.length; j++) {
                      name += child.childNodes[j].nodeValue;
                  }
                  if (authors == 1) {
                      html += AuthorReverse(name); 
                  }
                  else {
                      html += name;
                  }
                  html += "</span>";
              }
          }
          html += ". ";
      }
  }
  bookSpan = thisdoc.getElementById('b24-chaptertitle');
  if (bookSpan) {
      html += "\"<span class='b24-citations_chaptertitle'>";
      if (bookSpan.innerText) {
          html += bookSpan.innerText;
      }
      else {
          html += bookSpan.textContent;
      }
      html += "</span>\"";
      html += ". ";
  }
  bookSpan = thisdoc.getElementById('b24-booktitle-'+bid);
  if (bookSpan) {
      html += "<span class='b24-citations_title'>";
      if (bookSpan.innerText) {
          html += bookSpan.innerText;
      }
      else {
          html += bookSpan.textContent;
      }
      html += "</span>";
      html += ". ";
  }
  if (booktype == 3 || booktype==7) {
      bookSpan = thisdoc.getElementById('b24-soundview-copyright');
      var authorSpan = thisdoc.getElementById('b24-bookauthor-' + bid);
      if (authorSpan) {
          var first = true;
          html += "by ";
          for (var i = 0; i < authorSpan.childNodes.length; i++) {
              var child = authorSpan.childNodes[i];
              if (child.className == 'b24-bookauthor') {
                  if (first) {
                      first = false;
                  }
                  else if (i + 1 == authorSpan.childNodes.length) {
                      html += " and ";
                  }
                  else {
                      html += ", ";
                  }
                  html += "<span class='b24-citations_author'>";
                  for (var j = 0; j < child.childNodes.length; j++) {
                      html += child.childNodes[j].nodeValue;
                  }
                  html += "</span>";
              }
          }
          html += ". ";
      }
  }

  bookSpan = thisdoc.getElementById('b24-bookimprint-'+bid);
  if (bookSpan) {
      html += "<span class='b24-citations_bookimprint'>";
      if (bookSpan.innerText) {
          html += bookSpan.innerText;
      }
      else {
          html += bookSpan.textContent;
      }
      html += "</span>";
      html += ". ";
  }
  bookSpan = thisdoc.getElementById('b24-bookrights-' + bid);
  if (bookSpan) {
      html += "<span class='b24-citations_bookrights'>";
      if (bookSpan.innerText) {
          html += bookSpan.innerText;
      }
      else {
          html += bookSpan.textContent;
      }
      html += "</span>";
      html += ". ";
  }

  if (booktype == "8") {
      html += "<span class='b24-citations_type'>Online Video Clip</span>, ";
  }
  else if (booktype =="9") {
      html += "<span class='b24-citations_type'>Online Audio File</span>, ";
  }
  
  if (booktype == "3" || booktype=="7") {
      bookSpan = thisdoc.getElementById('b24-product-' + bid);
      if (bookSpan) {
          html += "<span class='b24-citations_bookimprint'>";
          if (bookSpan.innerText) {
              html += bookSpan.innerText;
          }
          else {
              html += bookSpan.textContent;
          }
          html += "</span>";
          html += ". ";
      }
  }
  html += "<span class='b24-citation_resource'>Books24x7</span>. ";
  html += "&lt;<span class='b24-citations_link'>http://common.books24x7.com/book/id_" + bid + "/book.asp</span>&gt;";
  html += " (accessed <span class='b24-citations_date'>";

  var m_names = new Array("January", "February", "March", 
                          "April", "May", "June", "July", "August", "September", 
                          "October", "November", "December");  
  var d = new Date();
  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  html += m_names[curr_month] + " " + curr_date + ", " + curr_year;
  html += "</span>)  ";
  html += "</div></p>";
  html += "</div>";
  html += "<div class='b'><div></div></div>";
  html += "</div>";
  /* example */
  /*
  html ="<div class='dialog'>";
  html +=" <div class='content'>";
  html +="  <div class='t'></div>";
  html +="  <!-- Your content goes here -->";
  html +="  <h1>Even <em>More</em> Rounded Corners With CSS</h1>";
  html +="  <p>Here is a very simple example dialog.</p>";
  html +="  <p>Note that if gradients are used, you will need a 'min-height' (or fixed height) rule on the body of the dialog. If these examples appear funny at the bottom, it is because they do not enforce the min-height rule.</p>";
  html +=" </div>";
  html +=" <div class='b'><div></div></div>";
  html +="</div>";
  */
  bubble.innerHTML = html;

}


function AnnotationRemoveContentDecorations(bubble,thisdoc) {
  if (bubble.annotationTargetsVisible) {  // must turn off the annotation markers 
      toggleHighlight('zannotationtargettoggle.css','annotationtargetson','annotationtargetssoff','noinlineannotationtargets');
      bubble.annotationTargetsVisible = false;
  }
  if (bubble.elementid != null) {
      var targ = thisdoc.getElementById(bubble.elementid);
      unsetAnnotationSelectedParaStyle(targ);
      bubble.elementid = null;
  }
}

//=========================================================
function SunDown()
{
  lastClickInContentId = null;
  thisdoc = document;
  // hide the bubble
  var contentframe = top.frames["Content"];
  if (contentframe != null) 
  {
    framed = true;
    thisdoc = contentframe.document;
    }
  var bubble = thisdoc.getElementById('download');
  if (bubble.toolbutton != null) {
      bubble.disabled = false;
      if (bubble.toolbutton.savealt) {
          bubble.toolbutton.alt = bubble.toolbutton.savealt;
          bubble.toolbutton.title=bubble.toolbutton.savetitle;
          bubble.toolbutton.savealt = null;
          bubble.toolbutton.savetitle = null;
      }
      bubble.style.cursor = "default";
      if (bubble.toolbuttonimagefolder) {
          bubble.toolbutton.src = bubble.toolbuttonimagefolder + '/' + bubble.toolbuttondefaultimg;
      }
      bubble.toolbutton = null;
      bubble.toolbuttonimagefolder=null;
  }
  else if (bubble.editlink != null) {
      bubble.editlink.className='inactive';
      bubble.editlink.style.cursor = "default";
      bubble.editlink.style.color = "#0000FF";
      bubble.editlink = null;
  }
  bubble.WasMoved = null;
  AnnotationRemoveContentDecorations(bubble,thisdoc);
  //var cloud = thisdoc.getElementById('overlay');
  bubble.innerHTML = "";
  bubble.style.display = "none";
}
//------------------------
// adds/removes a stylesheet
//---------------------------
function toggleHighlight(_css,_onid,_offid,_statename) {
    var css = (_css == null) ? "zshowkeywords.css" : _css;
    var onid = (_onid == null) ? "highlighton" : _onid;
    var offid = (_offid == null) ? "highlightoff" : _offid;
    var statename = (_statename == null) ? "nokeywords" : _statename;
    var _nokeywords = 0;
    var framed = false;
    var doc = document;
    var contentframe = top.frames["Content"];
    if (contentframe != null) {
        framed = true;
        doc = contentframe.document;
    }
    var links = doc.getElementsByTagName("LINK");
    if (links != null && links.length > 1) {
        var _found = false;
        for (var i = 0; i < links.length; i++) {
            var attr = links[i].getAttribute("HREF");
            if (attr.indexOf(css) != -1) {
                if (links[i].disabled) {
                    links[i].disabled = false;
                    _nokeywords = 0;
                }
                else {
                    links[i].disabled = true;
                    _nokeywords = 1;
                }
                _found = true;
                break;
            }
        }
        if (!_found) {
            var link = doc.createElement("LINK");
            link.setAttribute("HREF",css);
            link.setAttribute("TYPE","text/css");
            link.setAttribute("REL","stylesheet");
            links[0].parentNode.appendChild(link);
            _nokeywords = 0;   
        }
        var imgOn = document.getElementById(onid);
        var imgOff = document.getElementById(offid);
        if (imgOn && imgOff) {
            if (_nokeywords == 0) {
                imgOn.style.display="inline";
                imgOff.style.display="none";
            }
            else {
                imgOn.style.display="none";
                imgOff.style.display="inline";
            }
        }
        var dataSource =  "data.asp?svc=state&data=" + statename + "&data=" + _nokeywords;
        var _datenow = new Date();  
        dataSource += "&time=" + _datenow.getTime();  // make absolutely sure nobody caches it
        XMLHttpRequestObject.open("GET", dataSource);
        XMLHttpRequestObject.onreadystatechange = function() { // don't care
        }
        XMLHttpRequestObject.send(null);
    }
}
//=========================================================
// Function for setting the focus to an element returned
// by AJAX
// Example: 
//  var focuser = new Focuser("downloadtxt");
//  focuser.SetIntervalID(setInterval(focuser.SetFocus, 1000));
//=========================================================
function Focuser(objID)
{
  // Private members
  var id = objID;                   // ID of the element to receive focus
  var intervalID = null;            // This is the id returned by setInterval, used for clearing the intervals

  // Public Members
  
  //----------------------------------------------------
  // Set the focus to object having id "id"
  //----------------------------------------------------
  this.SetIntervalID = function SetIntervalID(intID)
  {
    intervalID = intID;
  }           

  //----------------------------------------------------
  // Set the focus to object having id "id"
  //----------------------------------------------------
  this.SetFocus = function SetFocus()
  {
    var thisdoc = document;
    var contentframe = top.frames["Content"];
    if (contentframe != null) 
      thisdoc = contentframe.document;
    if(id) {
      var focusItem = thisdoc.getElementById(id);
      if(focusItem) {
        focusItem.focus();
        if(intervalID)
          clearInterval(intervalID);
      }
    } 
  } // SetFocus
}

//=========================================================
function getScrollingPosition(doc)
{
    var position = [0, 0];

    if (typeof window.pageYOffset != 'undefined')
        {
            position = [
                        window.pageXOffset,
                        window.pageYOffset
            ];
        }

    else if (typeof doc.documentElement.scrollTop
             != 'undefined' && (doc.documentElement.scrollTop > 0 ||
                                doc.documentElement.scrollLeft > 0))
        {
            position = [
                        doc.documentElement.scrollLeft,
                        doc.documentElement.scrollTop
            ];
        }

    else if (typeof doc.body.scrollTop != 'undefined')
        {
            position = [
                        doc.body.scrollLeft,
                        doc.body.scrollTop
            ];
        }

    return position;
}


//=========================================================
function getViewportSize(doc)
{
    var size = [0, 0];

    if (typeof window.innerWidth != 'undefined')
        {
            size = [
                    window.innerWidth,
                    window.innerHeight
            ];
        }
    else if (typeof doc.documentElement != 'undefined'
             && typeof doc.documentElement.clientWidth != 'undefined' 
             && doc.documentElement.clientWidth != 0)
        {
            size = [
                    doc.documentElement.clientWidth,
                    doc.documentElement.clientHeight
            ];
        }
    else
        {
            size = [
                    doc.getElementsByTagName('body')[0].clientWidth,
                    doc.getElementsByTagName('body')[0].clientHeight
            ];
        }

    return size;
}

//=========================================================
function getPosition(theElement)
{
    var positionX = 0;
    var positionY = 0;

    while (theElement != null)
        {
            positionX += theElement.offsetLeft;
            positionY += theElement.offsetTop;
            theElement = theElement.offsetParent;
        }

    return [positionX, positionY];
}
//---- viewer image popping
function PopImage(id, src, width, height)
  {
  if(id)
    {
    var img1 = document.getElementById(id);
    if(img1)
      {
      img1.style.display = 'none';
      var img2 = document.getElementById(id+'$');
        {
        if(img2)
          {
          img2.style.display = 'inline';
          }
        else
          {
          node = img1.parentNode.parentNode
          node.innerHTML += '<IMG ID="'+id+'$" SRC="'+src+'" WIDTH="'+width+'" HEIGHT="'+height+'" ALT="Click to collapse" TITLE="Click to collapse" onClick="UnPopImage(\''+id+'\')" >'
          }
        }
      }
    }
  }

function UnPopImage(id)
  {
  if(id)
    {
    var img1 = document.getElementById(id);
    var img2 = document.getElementById(id+'$');
    if(img2) img2.style.display = 'none';
    if(img1) img1.style.display = 'inline';
    }
  }
// collection all params used in managetitle area
  function collectParamsForTitle() {
      //get task from the radio button
      var param = "";
      var task1 = document.getElementById("task1");
      var task2 = document.getElementById("task2");
      var task3 = document.getElementById("task3");
      if (task1 && task1.checked) param = "&titletask=" + task1.value ;
      if (task2 && task2.checked) param = "&titletask=" + task2.value ;
      if (task3 && task3.checked) param = "&titletask=" + task3.value ;
      var addfolderid = document.getElementById("toexistingfolder");
      if (addfolderid && addfolderid.value !='') param += "&afid=" + addfolderid.value;
      var movefolderid = document.getElementById("mfid");
      if (movefolderid) param += "&mfid=" + movefolderid.value;
      var delfolderid = document.getElementById("fromfolder");
      if (delfolderid) param += "&dfid=" + delfolderid.value;
      var purgebookmarks = document.getElementById("purgebmk");
      if (purgebookmarks && purgebookmarks.checked) param += "&purgebmk=" + purgebookmarks.value;
      var keepcopy = document.getElementById("keepcopy");
      if (keepcopy && keepcopy.checked) param+="&keep=" + keepcopy.value;
      var newfoldername = document.getElementById("newfolder");
      if (newfoldername) param += "&afname=" + newfoldername.value;
      var myplanid = document.getElementById("myplan");
      if (myplanid) param += "&myplan=" + myplanid.value;
      //   var efolderid = document.getElementById("toexistingfolder2");
      //   if (efolderid) param +="&afid=" + efolderid.value;
      return param;
  
  }
 //ajaxly manage title
 function managetitle(bookmarkid,bookid,chunkid)
 {
     var bubble = document.getElementById('download');

    //get task from the radio button
    var param = "";
    var task1 = document.getElementById("task1");
    var task2 = document.getElementById("task2");
    var task3 = document.getElementById("task3");
    if (task1 && task1.checked)  param = "task=" + task1.value + "&mode=ajaxbookmark";
    if (task2 && task2.checked) param = "task=" + task2.value + "&mode=ajaxbookmark";
    if (task3 && task3.checked) param = "task=" + task3.value + "&mode=ajaxbookmark";
   var addfolderid = document.getElementById("toexistingfolder");
   if (addfolderid && addfolderid.value !='')  param +="&afid=" + addfolderid.value;
   var movefolderid = document.getElementById("mfid");
   if (movefolderid) param +="&mfid=" + movefolderid.value;
   var delfolderid =document.getElementById("fromfolder");
   if (delfolderid) param+="&dfid=" + delfolderid.value;
   var purgebookmarks = document.getElementById("purgebmk");
   if(purgebookmarks && purgebookmarks.checked)param+="&purgebmk=" + purgebookmarks.value;
   var keepcopy = document.getElementById("keepcopy");
   if (keepcopy && keepcopy.checked) param+="&keep=" + keepcopy.value;
   var newfoldername = document.getElementById("newfolder");
   if (newfoldername) param +="&afname=" + escape(newfoldername.value);
   var myplanid = document.getElementById("myplan");
   if (myplanid) param += "&myplan=" + myplanid.value;
//   var efolderid = document.getElementById("toexistingfolder2");
//   if (efolderid) param +="&afid=" + efolderid.value;
  if (bookmarkid) param +="&bmkid=" + bookmarkid;
  if (bookid) param +="&bkid=" + bookid;
  if (chunkid) param += "&chnkid=" +chunkid ;
  var dataSource = "annotation.asp?" + param;
  var _datenow = new Date();
  dataSource += "&time=" + _datenow.getTime();  // make absolutely sure nobody caches it
  var url = "annotation.asp";
  XMLHttpRequestObject.open("GET", dataSource);

  XMLHttpRequestObject.onreadystatechange = function() { // don't care
      if (XMLHttpRequestObject.readyState == 4 &&
        XMLHttpRequestObject.status == 200) {
          SunDown();
          if (bubble.managetype && bubble.managetype == 'add') {
              var i_bookIcon = document.getElementById("64");
              if (i_bookIcon) {
                  i_bookIcon.style.display = "inline";
              }
              var toggleToolAddBook = document.getElementById("BrowseToolFolderId" + bookid);
              if (toggleToolAddBook) {
                  toggleToolAddBook.style.display = "none";
                  toggleToolAddBook.parentNode.style.display = "none";
              }
              var toggleToolManageBook = document.getElementById("BrowseToolManageBookId" + bookid);
              if (toggleToolManageBook) {
                  toggleToolManageBook.style.display = "inline";
                  toggleToolManageBook.parentNode.style.display = "inline";
              }
          }
          if (purgebookmarks && purgebookmarks.checked) { // must refresh so that all annotations are expunged
              window.location.reload();
          }
          else {
              currentpageName = document.location.href.substring(document.location.href.length, document.location.href.lastIndexOf('/') + 1);
              if (currentpageName.indexOf("books.asp") < 0) {
                  location.reload();
              }
          }
      }
  }
  XMLHttpRequestObject.send(null);
 }

// move through the list of annotations
function nextChapTocNote(dir) {
    //        alert("calling next hit chunk");
    var hitrow = document.getElementById("CurrentNote");
    var thisrow = hitrow;
    if (hitrow != null) {
        //        alert("have hit row");
        hitrow=hitrow.parentNode;  // was really a hit TD
        thisrow = hitrow;
        if (dir == "forward") {
            while (null != (hitrow = hitrow.nextSibling)) { // the next row
                if (hitrow.nodeType == 1 && hitrow.className != "b24-annotationtoctexttr") {  // firefox throws text nodes our way
                    break;
                }
            }
        }
        else {
            while (null != (hitrow = hitrow.previousSibling)) { // the next row
                if (hitrow.nodeType == 1 && hitrow.className != "b24-annotationtoctexttr") {  // firefox throws text nodes our way
                    break;
                }
            }
        }
    }
    if (hitrow == null) {  // this is a pain.  we're at the end or they were sitting on a chunk that isnt in the hit list,  just position at the first.  will make the whole thing seem like a loop
        if (thisrow == null) {  // a royal pain this chunk wasn't in the search results
            var hittable = document.getElementById("ANNOTATIONSTABLE");
            if (hittable == null) {
                //                    alert("no hit table at all");
                return;
            }
            thisrow = hittable.firstChild;
            while (thisrow.nodeType != 1 && null != (thisrow = thisrow.nextSibling)) { // the next row
            }
            if (thisrow == null) {
                //                    alert("crap");
            }
        }
        var tbody = thisrow.parentNode;
        if (dir == "forward") {
            hitrow = tbody.firstChild;
            while (null != (hitrow = hitrow.nextSibling)) { // the next row
                if (hitrow.nodeType == 1 && hitrow.className != "b24-annotationtoctexttr") {  // firefox throws text nodes our way
                    break;
                }
            }
        }
        else {
            hitrow = tbody.lastChild;
            while (null != (hitrow = hitrow.previousSibling)) { // the next row
                if (hitrow.nodeType == 1 && hitrow.className != "b24-annotationtoctexttr") {  // firefox throws text nodes our way
                    break;
                }
            }
        }
    }
    
    if (hitrow != null) {
        //            alert("have next hit row:" + hitrow.nodeName);
        var nextchunk = hitrow.getElementsByTagName("A");
        var href = null;
        if (nextchunk != null) {
            //                alert("have next chunk:" + nextchunk.length + ":" + nextchunk[0].nodeName);
            for (var a = 0; a < nextchunk.length; a++) {
                    //  alert("a:" + a);
                var A = nextchunk[a];
                href = A.href;
                if (A.className == "B24-notelink") {
                    if (href != null && href.length > 0) {
                        break;
                    }
                }
            }
        }
        if (href != null) {
            //                alert("href:" + href);
            top.location.href=href;
        }
    }
}

//Utils
// Javascript function that will return an array of elements based on DOM element, tag, and class name.
// For instance, getElementsByClassName(document, 'tr', 'INFO') will get all "tr" tags under the document node with the "INFO" class and return an array of them
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	    var arrReturnElements = new Array();
	    strClassName = strClassName.replace(/\-/g, "\\-");
	    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	    var oElement;
	    var attr = "class";
	    //detect browser
	    var browser = navigator.appName;
	    if (browser == "Microsoft Internet Explorer") {
	        attr = "className";
	    }
	    for(var i=0; i<arrElements.length; i++){
	        oElement = arrElements[i];
	        if(oRegExp.test(oElement.getAttribute(attr))){
	            arrReturnElements.push(oElement);
	        }
	    }
	    return (arrReturnElements);
	}
//Utils
// Javascript function that will return an array of elements based on DOM element, tag, and class name.
// For instance, getElementsByAttributeName(document, 'tr', 'INFO','attributeName') will get all "tr" tags under the document node with the attribute with the name "attributeName"
// and value is "INFO"  and return an array of them
function getElementsByAttributeName(oElm, strTagName, strAttributeName, strAttribute){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	    var arrReturnElements = new Array();
	    strClassName = strAttributeName.replace(/\-/g, "\\-");
	    var oRegExp = new RegExp("(^|\\s)" + strAttributeName + "(\\s|$)");
	    var oElement;
	    for(var i=0; i<arrElements.length; i++){
	        oElement = arrElements[i];
	        if(oRegExp.test(oElement.getAttribute(strAttribute))){
	            arrReturnElements.push(oElement);
	        }
	    }
	    return (arrReturnElements);
	}


function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function htmlEncode(result)
{
	// ampersands (&)
	result = result.replace(/\&/g,'&amp;');

	// less-thans (<)
	result = result.replace(/\</g,'&lt;');

	// greater-thans (>)
	result = result.replace(/\>/g,'&gt;');

  return result;
}

//=========================================================
// Start of common code to support AJAX
//=========================================================

/*
coded by Kae - http://verens.com/
use this code as you wish, but retain this notice
*/


var kXHR_instances=0;
var kXHR_objs = new Array();
var debugIframe = false;

IFrameXMLHttpRequest=function(){

	var i=0;
	var url='';
	var responseText='';
	var iframe='';
  var isPost = false;
	this.onreadystatechange=function(){
		return false;
	}
  this.abort=function() {  // do nothing.  just don't break IE6
  }
	this.open=function(method,url,nothing){
      if (debugIframe) {
          alert("iframe open:" + method + "|" + url);
      }
		//TODO: POST methods
		this.i=++kXHR_instances; // id number of this reques
    if (url.indexOf('?') != -1) {
        this.url=url + "&iframe=1";
    }
    else {
        this.url = url + "?iframe=1";
    }
      //  unneeded.  the IE activex version has cache problems too.  handle it in the url construction
      //    var _datenow = new Date();  
      //    this.url += "&time=" + _datenow.getTime();  // make absolutely sure nobody caches it

    var el=document.getElementById('kXHR_iframe_'+this.i);
    if (el != null) {
        el.parentNode.removeChild(el);
    }
    //		document.body.appendChild(document.createElement('<iframe id="kXHR_iframe_'+this.i+'" style="display:none" src="/"></iframe>'));	
    var elm = document.createElement("iframe");
		elm.setAttribute("id",'kXHR_iframe_'+this.i);
    elm.setAttribute("style","display:none");
    elm.setAttribute("height","1");
    elm.setAttribute("width","1");
    //    elm.setAttribute("src","/");
		document.body.appendChild(elm);
  }
	this.send=function(postdata){
		//TODO: use the postdata
		var el = document.getElementById('kXHR_iframe_'+this.i);
    if (postdata != null && postdata.length > 0) {
        this.isPost = true;
        if (-1 == this.url.indexOf('?')) {
            this.url = this.url + '?' + postdata;
        }
        else {
            this.url = this.url + '&' + postdata;
        }
    }
    if (debugIframe) {
        alert("iframe send:" + this.url + "|" + postdata);
    }
    el.setAttribute("src",this.url);
		kXHR_objs[this.i]=this;
		setTimeout('IFrameXMLHttpRequest_checkState('+this.i+',2)',2);
	}
  this.setRequestHeader = function(name,value) {  // fake from post
  }

	return true;
}


function IFrameXMLHttpRequest_setErrorCode(responseText) {
    var t = "" + responseText;
    t = t.toLowerCase();
    var span = t.indexOf("span");
    if (span > 0 && span < 5) {
        var cls = t.indexOf("b24-duierror");
        if (cls > 0 && cls < 20) {
            return 403;
        }
    }
    else {
        return 200;
    }
}
IFrameXMLHttpRequest_checkState=function(inst,delay){
	var el=document.getElementById('kXHR_iframe_'+inst);
	if(el.readyState==null) {
      var responseText=document.frames['kXHR_iframe_'+inst].document.body.innerHTML;
      if (responseText != null) {
          kXHR_objs[inst].responseText=responseText;
          if (debugIframe) {
              alert("post response:" + responseText);
          }
          kXHR_objs[inst].readyState=4;
          kXHR_objs[inst].status= IFrameXMLHttpRequest_setErrorCode(responseText);
          el.parentNode.removeChild(el);
          kXHR_objs[inst].onreadystatechange();
      }
      else {
          delay*=1.5;
          setTimeout('IFrameXMLHttpRequest_checkState('+inst+','+delay+')',delay);
      }
  }
	else if(el.readyState=='complete'){
    var responseText=document.frames['kXHR_iframe_'+inst].document.body.innerHTML;
		kXHR_objs[inst].responseText=responseText;
    if (debugIframe) {
       alert("post response:" + responseText);
    }
		kXHR_objs[inst].readyState=4;
    kXHR_objs[inst].status= IFrameXMLHttpRequest_setErrorCode(responseText);
		el.parentNode.removeChild(el);
		kXHR_objs[inst].onreadystatechange();
	}else{
		delay*=1.5;
		setTimeout('IFrameXMLHttpRequest_checkState('+inst+','+delay+')',delay);
	}
}
 
function initXMLHttp() {
    var xmlhttp = null;
    if (window != null && window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    }
    else if (window != null && window.ActiveXObject){ 
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
              xmlhttp = new IFrameXMLHttpRequest();
        	}
        }
        /*
        xmlhttp = new IFrameXMLHttpRequest();
        */
    }
    else {
        xmlhttp = new XMLHttpRequest();
        if (xmlhttp == null) {
            xmlhttp = new IFrameXMLHttpRequest();
        }
    }
    return xmlhttp;
}

XMLHttpRequestObject = initXMLHttp();
