/* js
   
   This file is part of arena.

   arena is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation; either version 3 of the License or, at your
   option, any later version.

   arena is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABLITY
   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
   License for more details.

   You should have received a copy of the GNU General Public License along
   with arena.  If not, see <http://www.gnu.org/licenses/>.
*/

/* This file defines a utility class that allows for dynamic content
   generation using AJAX.
*/

// A dynamic element
subclass(ADynamicElement, AnObject);

// Construct an element handler
function ADynamicElement(id) {
  this.identifier = id;
  this.element = document.getElementById(this.identifier);
}

// Fetch the contents of the element using the specified URL
ADynamicElement.prototype.fetch = function(url, queryString, blocking) {
  if (url == "")
    return;

  // Construct an HTTP request to retrieve the post content
  var Request = new AnAjaxRequest("GET")
  // If we failed to create the request, we cannot fetch the content
  if (!Request) 
    return;

  Request.url = url;

  if (queryString)
      Request.queryString = queryString;

  Request.caller = this;

  Request.callback = function () {
    // Check the server response
    if (Request.request.readyState == 4) {
      // Everything went well
      if (Request.request.status == 200) {
        // Replace the contents of the element
        Request.caller.element.innerHTML = Request.request.responseText;
      }
    }
  }

  // Send the request
  Request.send(blocking);
}

// Show the element
ADynamicElement.prototype.show = function() {
  if (this.element.style.visibility == "hidden") {
      this.element.style.visibility = "visible";
      this.element.style.display = "block";
  }
}

// Hide the element
ADynamicElement.prototype.hide = function() {
  if (this.element.style.visibility != "hidden") {
      this.element.style.visibility = "hidden";
      this.element.style.display = "none";
  }
}

// Toggle the visibility of the element
ADynamicElement.prototype.toggleVisibility = function(anchor) {
  // Get the display style of the element
  display = this.element.style.visibility;

  if (display != "hidden") 
    this.hide();
 
  else 
    this.show();

  // If the anchor that allows the user to toggle was specified...
  if (anchor) {
    anchorText = anchor.firstChild.firstChild;
    if (!anchorText)
      return; 

    // ...update the anchor text to indicate the element has been toggled
    if (display != "hidden") {
      anchorText.textContent = "+";
      anchor.title = "Show this section";
    }
    
    else {
      anchorText.textContent = "-";
      anchor.title = "Hide this section";
    }
  }   
}
