////////////////////////////////////////////////////////////////////////////////
// PURPOSE OF THIS FILE                                                       //
//                                                                            //
// Contains javascript functions that are used by multiple pages on the PBC   //
// website. Generally this file should not be updated - required only if      //
// changing the basic functionality of the website. Familiarity with          //
// javascript is essential - any errors here will affect the entire site.     //
//                                                                            //
// Data used by these functions is stored in a separate file "navdata.js" -   //
// if you simply want to add a new navigation button or menu item then edit   //
// that file.                                                                 //
//                                                                            //
// Neville Whitlock and Lisa Martell                                          //
// Website developers                                                         //
// May 2007 and following                                                     //
////////////////////////////////////////////////////////////////////////////////


//==============================================================================
// OPEN MAIN PAGE TABLE - BEFORE PAGE CONTENTS
function openPageTable(bannergraphic) {

  // Set default banner graphic to beach
  bannergraphic = ( !bannergraphic ? "beach.jpg" : bannergraphic);

  // Top row of graphics: corner ... top ... corner
  var output = "<table width='100%' height='100%' border='0' cellpadding='0' cellspacing='0'><tr height='32'>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/topleft.gif' width='32' height='32'></td>\n";
  output    += "  <td><img src='" + getLeader() + "images/top.gif' width='100%' height='32'></td>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/topright.gif' width='32' height='32'></td>\n";
  output    += "</tr><tr height='100'>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/left.gif' width='32' height='100'></td>\n";

  // Second row, middle cell: banner graphic and PBC logo. Lines must not start with spaces
  output    += "<td>";
  output    += "<img src='" + getLeader() + "images/" + bannergraphic + "' width='100%' height='100'>";
  output    += "<a href='" + getLeader() + "index.html'>";
  output    += "<img src='" + getLeader() + "images/pbclogo.gif' width='139' height='81' border='0' style='position: absolute; top: 40; left: 40' alt='Petone Baptist Church - return to home page'>";
  output    += "</a>";
  output    += "</td>\n";

  // Two rows of graphics between banner and main page content
  output    += "  <td width='32'><img src='" + getLeader() + "images/right.gif' width='32' height='100'></td>\n";
  output    += "</tr><tr height='32'>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/bottomleft.gif' width='32' height='32'></td>\n";
  output    += "  <td><img src='" + getLeader() + "images/bottom.gif' width='100%' height='32'></td>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/bottomright.gif' width='32' height='32'></td>\n";
  output    += "</tr><tr height='32'>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/topleft.gif' width='32' height='32'></td>\n";
  output    += "  <td><img src='" + getLeader() + "images/top.gif' width='100%' height='32'></td>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/topright.gif' width='32' height='32'></td>\n";
  output    += "</tr><tr valign='top'>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/left.gif' width='32' height='100%'></td>\n";
  output    += "  <td>\n";

  // Table within main page content cell. Allows optional insertion of navigation table
  output    += "<table width='100%' border='0' cellpadding='10' cellspacing='0'><tr valign='top' bgcolor='#cfc7b8'><td>\n";

  // Display output
  document.write(output);

  // On local drive only: run data validation function
  if (/\/pbcwebsite\//.test(document.location) == true) {
    setTimeout("validNavigation()", 100);
  }

  // Trigger breadcrumb function
  document.write(makeBreadcrumb());

}

//==============================================================================
// CLOSE MAIN PAGE TABLE - AFTER PAGE CONTENTS
function closePageTable() {

  // Assemble output for return to calling page
  var output = "  </td></tr></table>\n\n";
  output    += "</td>\n";
  output    += "<td width='32'><img src='" + getLeader() + "images/right.gif' width='32' height='100%'></td>\n";
  output    += "</tr><tr height='32'>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/bottomleft.gif' width='32' height='32'></td>\n";
  output    += "  <td><img src='" + getLeader() + "images/bottom.gif' width='100%' height='32'></td>\n";
  output    += "  <td width='32'><img src='" + getLeader() + "images/bottomright.gif' width='32' height='32'></td>\n";
  output    += "</tr></table>\n";

  document.write(output);
}

//==============================================================================
// CREATE BREADCRUMB TRAIL AT TOP OF PAGE
function makeBreadcrumb() {

  // Determine path steps from top directory to current file
  var cut = /(\.org\.nz\/|\/pbcwebsite\/)/;             // Split at ".org.nz/" or "/pbcwebsite/"
  var url = document.location.toString();               // Save document location (URL) as a string
  var urlbits = url.split(cut);                         // Split at splitpoint as defined above
  var fragments = urlbits[urlbits.length-1].split("/"); // Split final segment at slashes 

  // Breadcrumb trail starts with "You are here" and home link
  var output = "<p class='breadcrumb'><nobr>You are here: &nbsp; ";
  output += "<a href='" + getLeader() + "index.html'>PBC Home</a>"

  // Add a link for each fragment in the chain
  for (i = 0; i < fragments.length; i++) {

    // Final HTML link - but not "index.html" because it's covered by folder links
    if (/\.html$/.test(fragments[i]) == true) {
      if (fragments[i] != "index.html") {
        output += " &gt; " + document.title;
      }
    }

    // Intermediate folder steps - refer to "crumbs" array in file "navdata.js"
    else {
      for (var j = 0; j < crumbs.length; j++) {
        if (fragments[i] == crumbs[j][0]) {
          output += " &gt; <a href='";

          // Work out how many steps down up from current page and step back accordingly
          for (var k = i + 2; k < fragments.length; k++) {output += "../"}

          output += "index.html'>" + crumbs[j][1] + "</a>";
          break;
        }
      }
    }
  }

  output += "</nobr></p>";
  return output;

}

//==============================================================================
// DRAW NAVIGATION BUTTONS INTO PAGE
function drawNavigation() {

  // Start of blue table surrounding buttons
  var output = "<span id='buttontable'>";

  output    += "<table width='152' border='0' cellpadding='0' cellspacing='0' bgcolor='#003333'><tr height='16'>\n"; // Lisa's actual color of #162533 can't match corber graphics
  output    += "  <td width='16'><img src='" + getLeader() + "images/navtopleft.gif' height='16' width='16'></td>\n";
  output    += "  <td width='120' style='font-size: 8pt'>&nbsp;</td>\n";
  output    += "  <td width='16'><img src='" + getLeader() + "images/navtopright.gif' height='16' width='16'></td>\n";
  output    += "</tr><tr valign='top'>\n";
  output    += "  <td colspan='3' align='center'>\n";


  // Create buttons: loop through "buttons" array in file "navdata.js"
  for (var i = 0; i < buttons.length; i++) {
    output += " <input type='button' class='nav' value='" + buttons[i][1] + "' ";

      // buttons ending with .html suffix - no submenu
      if (/\.html$/.test(buttons[i][0]) == true) {
      output += "onclick=location.href='" + getLeader() + buttons[i][0] +"'>";
      }

      // All other buttons have a submenu
      else {
      output += "onclick='showMenu(\"" + buttons[i][0] + "\")' ";
      output += "ondblclick=location.href='" + getLeader() + buttons[i][0] + "/index.html'>";
      }

    output += "<span id='" + buttons[i][0] + "'></span>";
    if (i < buttons.length - 1) {output += "<br>"}
    output += "\n";
  }


  // Instructions button - local disk addresses only
  if (/\/pbcwebsite\//.test(document.location) == true) {
  output += "<br><input type='button' class='nav' value='Web instructions' style='color: red' ";
  output += "onclick='window.open(\"" + getLeader() + "instructions.html\")'>";
  }


  // End of blue table surrounding buttons
  output    += "  </td>\n";
  output    += "</tr><tr valign='top'>\n";
  output    += "  <td width='16'><img src='" + getLeader() + "images/navbottomleft.gif' height='16' width='16'></td>\n";
  output    += "  <td width='120' style='font-size: 8pt'>&nbsp;</td>\n";
  output    += "  <td width='16'><img src='" + getLeader() + "images/navbottomright.gif' height='16' width='16'></td>\n";
  output    += "</tr></table>\n";
  output    += "</td><td>\n";
  output    += "</span>\n";

  document.write(output);

}

//==============================================================================
// DISPLAY DROPDOWN NAVIGATION MENUS
function showMenu(whichmenu){

  // Default "whichemenu" - or make blank if same menu already showing
  whichmenu = ( !whichmenu ? "" : whichmenu);
  if (whichmenu != "" && document.getElementById(whichmenu).innerHTML != "") {whichmenu = ""}


  // Get menu list from buttons array and close all menus
  for (var i = 0; i < buttons.length; i++) {
    if (buttons[i][0] != "") {
      document.getElementById(buttons[i][0]).innerHTML = "";
    }
  }

  // If a menu is required, collate and display it
  if (whichmenu != "") {


    // Start of menu
    var output = "<table border='0' cellpadding='2' cellspacing='0' style='width: 30mm; margin-top: -1.5mm'>";
    output    += "<tr valign='top'><td>";


    // Find menu items that start with matching folder name ("menus" array is in file "navdata.js")
    var soughtfolder = new RegExp("^" + whichmenu);
    for (var i = 0; i < menus.length; i++) {
    if (soughtfolder.test(menus[i][0]) == true) {
      output += "<input type='button' class='subnav' value='" + menus[i][1] + "' ";
      output += "onclick=location.href='" + getLeader() + menus[i][0] + "'><br>\n";
    }}

    // End of menu, then display in appropriate span
    output += "</td></tr></table>";
    document.getElementById(whichmenu).innerHTML = output;

  }

}

//==============================================================================
// PROVIDE WRAPPING TABLE FOR PHOTO COLUMN ON RIGHT SIDE OF PAGE
function phototable(section){

  // Ensure supplied argument is "top" or "bottom"
  if (/^(top|bottom)$/i.test(section) == false) {
    alert ("Oops: when calling function 'phototable', must use either 'top' or 'bottom' - not '" + section + "'");
    return null;
  }

  var output = "";

  // Table opening - above photos
  if (section.toLowerCase() == "top") {
    output += "<table border='0' cellpadding='0' cellspacing='0' bgcolor='#003333' align='right'>";
    output += "<td width='16'><img src='" + getLeader() + "images/navtopleft.gif' height='16' width='16'></td>";
    output += "<td style='font-size: 8pt'>&nbsp;</td>";
    output += "<td width='16'><img src='" + getLeader() + "images/navtopright.gif' height='16' width='16'></td>";
    output += "</tr><tr valign='top'>";
    output += "<td>&nbsp;</td>";
    output += "<td align='center'>";
  }

  // Table closing - below photos
  else if (section.toLowerCase() == "bottom") {
    output += "</td>";
    output += "<td>&nbsp;</td>";
    output += "</tr><tr valign='top'>";
    output += "<td width='16'><img src='" + getLeader() + "images/navbottomleft.gif' height='16' width='16'></td>";
    output += "<td style='font-size: 8pt'>&nbsp;</td>";
    output += "<td width='16'><img src='" + getLeader() + "images/navbottomright.gif' height='16' width='16'></td>";
    output += "</tr></table>";
  }

  // Display whatever was collated
  document.write(output);

}

//==============================================================================
// REALIGN <H1> LAYERS FOR NETSCAPE - DOESN'T READ CSS POSITIONING AS INTENDED
function nsAlign() {

  if (window.navigator.appName == "Netscape") {
    var h1 = document.getElementsByTagName("h1");
    for (var i = 0; i < h1.length; i++) {h1[i].style.top = 4}
  }

}

//==============================================================================
// DETERMINE HOW MANY STEPS FROM CURRENT FILE TO TOP OF TREE, AND CREATE LEADER
function getLeader(){

  var cut = /(\.org\.nz\/|\/pbcwebsite\/)/;           // Split at ".org.nz/" or "/pbcwebsite/"
  var url = document.location.toString();             // Save document location (URL) as a string
  var urlbits = url.split(cut);                       // Split at "cut" as defined above
  var steps = urlbits[urlbits.length-1].split("/");   // Split final segment at slashes 

  // Create leader for calculated number of steps
  var output = "";
  for (var i = 1; i < steps.length; i++) {output += "../"}
  return output;

}

//==============================================================================
// VALIDATE DATA IN FILE "navdata.js" ... IN CASE A NEW ENTRY IS NOT ACCEPTABLE
function validNavigation() {

  var errors = "";

  //----------------------------------------------------------------------------
  // "buttons" array
  for (var i = 0; i < buttons.length; i++) {


    // element[0] must be lower case with no whitespace or punctuation (other than .html suffix)
    if (buttons[i][0] != buttons[i][0].toLowerCase())                               {errors += "'" + buttons[i][1] + "' button: folder name must not contain capital letters.\n"}
    if (/\W/.test(buttons[i][0]) == true && /\.html$/.test(buttons[i][0]) == false) {errors += "'" + buttons[i][1] + "' button: folder name must not contain punctuation or spaces.\n"}


    // Every button menu must have at least one menu item (other than files ending in .html)
    var menufilled = false;
    for (var j = 0; j < menus.length; j++) {
      var menubits = menus[j][0].split("/");
      if (buttons[i][0] == menubits[0] || /\.html$/.test(buttons[i][0]) == true) {
        menufilled = true;
        break;
      }
    }
/* Uncomment next line once all pages are created
    if (menufilled == false)                          {errors += "'menus' list contains no entries for '" + buttons[i][1] + "' menu.\n"}
*/

    // No two buttons can have the same folder/menu name (other than blank)
    var duplicatebuttons = false;
    for (var j = i+1; j < buttons.length; j++) {
      if (buttons[i][0] == buttons[j][0] && buttons[i][0] != ""){
        duplicatebuttons = true;
        break;
      }
    }
    if (duplicatebuttons == true)                     {errors += "Buttons: cannot have more than one folder with name '" + buttons[i][0] + "'.\n"}


  }

  //----------------------------------------------------------------------------
  // "menus" array
  for (var i = 0; i < menus.length; i++) {

    // element[0] must be lower case with a least one slash and end with ".html"
    if (menus[i][0] != menus[i][0].toLowerCase()) {errors += "'" + menus[i][1] + "' dropdown menu link: folder/file name must not contain capital letters.\n"}
    if (/\//.test(menus[i][0]) == false)          {errors += "'" + menus[i][1] + "' dropdown menu link: folder/file name must contain a slash between folder and file names.\n"}
    if (/\.html$/.test(menus[i][0]) == false)     {errors += "'" + menus[i][1] + "' dropdown menu link: file name must end with '.html'.\n"}

    // Pre-slash must match a button folder
    folderbits = menus[i][0].split("/");
    var foldermatchesbutton = false;
    for (var j = 0; j < buttons.length; j++) {
      if (folderbits[0] == buttons[j][0]) {
        foldermatchesbutton = true;
        break;
      }
    }
    if (foldermatchesbutton == false)             {errors += "'" + menus[i][1] + "' dropdown menu link: top level folder name must match a folder name in the 'buttons' list.\n"}
  }

  //----------------------------------------------------------------------------
  // "crumbs" array
  for (var i = 0; i < crumbs.length; i++) {

    // element[0] must be lower case with no whitespace or punctuation
    if (crumbs[i][0] != crumbs[i][0].toLowerCase()) {errors += "'" + crumbs[i][1] + "' breadcrumb: folder name must not contain capital letters.\n"}
    if (/\W/.test(crumbs[i][0]) == true)            {errors += "'" + crumbs[i][1] + "' breadcrumb: folder name must not contain punctuation or spaces.\n"}

    // No two folders can have the same name
    var duplicatefolders = false;
    for (var j = i+1; j < crumbs.length; j++) {
      if (crumbs[i][0] == crumbs[j][0]){
        duplicatefolders = true;
        break;
      }
    }
    if (duplicatefolders == true)                   {errors += "Breadcrumbs list: cannot have more than one folder with name '" + crumbs[i][0] + "'.\n"}

  }

  //----------------------------------------------------------------------------
  // Report any problems
  if (errors != ""){
    errors = "Oops - problems detected in file 'navdata.js':\n\n" + errors;
    alert(errors);
    return null;
  }

}

//==============================================================================