/* * * Top of Copyright for twisty.js, version 1.1 * * *
(c) 2009 John F. Kelley (except as noted).  All rights reserved.
http://wellhost.com/contact.html?to=webmaster&subject=OpenSource_twisty_js&force=1

The following terms are based on the BSD License:
http://www.opensource.org/licenses/bsd-license.php

Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.

* Neither the name of copyright holder nor the names of the copyright holder's employer may be used
to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* * * End of Copyright * * */

/* * * Top of ReadMe * * *
 Setup:
   1. Put into current directory: twisty.js, twisty_opened.gif, twisty_closed.gif
   2. Add a line to the <head> of your html file:
     <script src="twisty.js"   type="text/javascript"></script>
 Use:
   * Add class="twisty" to any <h> tag and immediately follow it with a <div> block, e.g.
       <h2 class="twisty">Click here to see optional stuff</h2>
       <div>
       stuff
       </div>
   * When clicked, that heading will open or close the div that follows it.

 Notes:
   * Your divs will start closed unless you tag them as follows:
       <div twisty="open">
   * You can change the appearance of the twisty headers by defining class "twisty" in the <head> section:
       <style type="text/css">
       .twisty {
         background-color:#DDDDDD;
         }
       </style>
   * You can specify a second image to appear after the twisties as follows:
       <h2 class="twisty" twistyImg="finger.png">
   * You can modify the header text when opened or closed as follows:
       <h2 class="twisty" twistyReplace="Click here to see|Click here to hide">
     (which will insert these two messages at the beginning when closed and opened)
   * You can cause a javascript command to be issued when the twisty is opened (first time or every time):
       <h2 class="twisty" twistyOpen="myOpenFunction()">
       <h2 class="twisty" twistyOpenFirst="myOneTimeFunction()">
     (If both are present, the OpenFirst will be executed the first time, the Open will execute every time thereafter.)
   * You can see the on-open events in the window status bar if you add to your onload js:
       twisty_debug=true;
 * * * End of ReadMe * * */

var twisty_debug = false;

var twisty_vars = new Object()
var twisty_openedOnce = new Object()

twisty_vars["path"]="" // assumes images will be in same directory
twisty_vars["twisties"] = new Object()

//twisty_vars["rc"] = twisty_addEvent(window,"load",twisty_init)
twisty_vars["rc"] = twisty_addEvent(window,"load",twisty_init)

function twisty_init() {
  var elem = twisty_findElementsByClassName(document,'twisty')

  var hObj,dObj,stname,stval,arrow,tatt,ddisp,iname
  for (var i = 0; i < elem.length; i++) {
    hObj = elem[i]
  //alert((hObj.textContent) ? hObj.textContent : hObj.innerText)
    dObj = twisty_nextSiblingElement(hObj)
    if (dObj.nodeName == "DIV") {
      var attrep = hObj.getAttribute("twistyReplace")
      if ((attrep) && ((-1 < attrep.indexOf("|")))) {
        var toopen=attrep.split("|")[0]
        var toclose=attrep.split("|")[1]
        }
      else {
        var toopen=''
        var toclose=''
        }
      hObj.style.display="block"
      hObj.style.width="99%"
      hObj.style.cursor="pointer"
      tatt=dObj.getAttribute("twisty")
      if (tatt && tatt=="open") {
        ddisp=""
        iname="twisty_opened.gif"
        }
      else {
        ddisp="none"
        iname="twisty_closed.gif"
        }
      hObj.style.marginBottom = "0px"
      dObj.className="twistydiv"
      dObj.style.marginTop = "0px"
      dObj.style.display=ddisp

      if (toopen) {
        if (ddisp == "none") var pretxt = document.createTextNode(toopen + " ")
        else var pretxt = document.createTextNode(toclose + " ")
        hObj.insertBefore(pretxt,hObj.firstChild)
        }

      xtraimg = hObj.getAttribute("twistyImg")
      if (xtraimg) {
        arrow = document.createElement("img")
        arrow.style.paddingRight="2px"
        arrow.src = xtraimg
        arrow.style.verticalAlign = "bottom"
        hObj.insertBefore(arrow,hObj.firstChild)
        }


      arrow = document.createElement("img")
      arrow.style.marginRight="2px"
      arrow.src=twisty_vars["path"]||iname
      hObj.insertBefore(arrow,hObj.firstChild)

      twisty_vars["twisties"][i] = hObj
      eval('twisty_addEvent(hObj,"click",function(event) {twisty_toggle(' + i + '); } )');
      }
    }
  }

function twisty_toggle(hInd) {
  hObj = twisty_vars["twisties"][hInd]
  var dObj = twisty_nextSiblingElement(hObj)
  if (dObj.nodeName == "DIV") {
    var attrep = hObj.getAttribute("twistyReplace")
    if ((attrep) && ((-1 < attrep.indexOf("|")))) {
      var toopen=attrep.split("|")[0]
      var toclose=attrep.split("|")[1]
      }
    else {
      var toopen=''
      var toclose=''
      }
    if (dObj.style.display == "none") { // so, open it
      if (toopen) hObj.innerHTML = hObj.innerHTML.replace(new RegExp(toopen),toclose)
      var nsrc = 'twisty_opened.gif'
      dObj.style.display=""
      var exFirst = hObj.getAttribute("twistyOpenFirst")
      var exAlways = hObj.getAttribute("twistyOpen")
      if ((exFirst) && (!twisty_openedOnce[hInd])) {
        try {
          eval(unescape(exFirst))
          if (twisty_debug) setTimeout('window.status="twisty.js* Execute: ' + unescape(exFirst) + '"',2000)
          }
        catch(e) {
          if (twisty_debug) setTimeout('window.status="twisty.js* Execution failed: ' + unescape(exFirst) + '"',2000)
          }
        twisty_openedOnce[hInd] = true
        }
      else if (exAlways) {
        try {
          eval(unescape(exAlways))
          }
        catch(e) {
          }
        }
      }
    else {                              // so, close it
      if (toopen) hObj.innerHTML = hObj.innerHTML.replace(new RegExp(toclose),toopen)
      var nsrc = 'twisty_closed.gif'
      dObj.style.display="none"
      }
    var iObj = hObj.getElementsByTagName("IMG")[0]
    iObj.parentNode.removeChild(iObj)
    var arrow = document.createElement("img")
    arrow.style.paddingRight="2px"
    arrow.src=twisty_vars["path"]||nsrc
    hObj.insertBefore(arrow,hObj.firstChild)
    }
  }

function twisty_nextSiblingElement(mObj) {
  mObj = mObj.nextSibling;
  while (mObj && (mObj.nodeType == 3 || mObj.nodeName.substring(0,1) == "/")) {
    mObj = mObj.nextSibling;
    }
  return mObj;
  }

function twisty_addEvent(myObj,myEv,fn) {
  if (myObj.addEventListener) {
    myObj.addEventListener(myEv,fn,true);
    return true
    }
  else if (myObj.attachEvent) { // IE
    var ret = myObj.attachEvent("on"+myEv,fn);
    return ret;
    }
  else return false;
  }

function twisty_findElementsByClassName(pobj,cl) {
  var retnode = [];
  var myclass = new RegExp('\\b'+cl+'\\b');
  var elem = pobj.all || pobj.getElementsByTagName('*');
  for (var i = 0; i < elem.length; i++) {
    var classes = elem[i].className;
    if (myclass.test(classes)) retnode.push(elem[i]);
    }
  return retnode;
  }

