/*
 *  Copyright (c) 2009 by Frank J. Edwards
 *  The contents herein are licensed under the Apache License v2 or
 *  later.
 */

/*
 *  This code looks for all <button>'s with a class of "spoiler".  These
 *  buttons have a function bound to the click event that toggles the
 *  display of the following <div> with a class of "spoiler".  It also
 *  changes the message on the button to correspond to the word "Show"
 *  or "Hide" as appropriate.  When JavaScript is not enabled, the
 *  foreground text color is set to the same as the background text
 *  color of the <div> so that text can only be read by highlighting the
 *  block.  This is done using the "spoiler" CSS class.
 */
$( function() {
    $('button.spoiler').click(showHideToggle).show().each(setupButton);
});

/*
 *  This function finds the DOM element following this one which is a
 *  <div> with a class of "spoiler".  The current element is expected
 *  to be a <button class="spoiler"> and the element following it is
 *  expected to be a <div>.
 *
 *  The jQuery object that represents this <div> is saved under the
 *  name "div" in the current jQuery object so that it can easily be
 *  retrieved later in the button's click handler.
 *
 *  In addition, a <br> element is added immediately after the <button>.
 */
function setupButton(idx) {
    var jq = $(this);
    //debugFields($('#debug'), "this", jq);
    var nextDiv = $('+ div.spoiler', jq);
    nextDiv.hide().removeClass('hiddenText');
    jq.data( "div", nextDiv );
    if (jq.text() == null || jq.text() == "")
	jq.text("Spoiler");
}

/*
 *  As an event handler, this function is passed "this" to refer to the
 *  object being affected and "event" which is the event object itself.
 *  Since this function is only registered as a click handler, there's
 *  no reason for any parameters at all, since "this" is enough.
 */
function showHideToggle(event) {
    event.preventDefault();
    var nextDiv = $(this).data("div");
    nextDiv.toggle();
    //debugFields($('#debug'), "data(div)", nextDiv);

    var msg = $(this).val();
    if (msg == "Show")
	$(this).val("Hide");
    else
	$(this).val("Show");
}
