var isIE;

function pre_load_init () {

  // hide the body while elements are being
  // loaded and positioned.
  // NOTE - doesn't work because we don't have a
  //        body element yet.
  /*document.body.style.visibility = "hidden";*/

  // are we dealing with the worst browser on earth?
  isIE = document.all?true:false;

  // preload all rotator images
  // loadRotatorAnchorImages();

}

function post_load_init () {
  initMenu();
  initRotator();
  initNews();
  initNav();
  initDocument();
  initFancyZoom();
  fixIeSix();

  // everything should be ready to be presented to
  // the user - so show it!
  document.body.style.visibility = "visible";
}


/******************************************************************************
 * URL Helper script
 ******************************************************************************
 */

function getUrl () {
  return window.location.href;
}

function getRootUrl () {
  return window.location.protocol + window.location.host;
}

function getRelativeUrl () {
  return window.location.pathname + window.location.hash;
}

function showUrlInfo () {
  var msg;
  msg  = getUrl() + "\n";
  msg += getRootUrl() + "\n";
  msg += getRelativeUrl() + "\n";

  alert(msg);
}


/******************************************************************************
 * Menu script
 ******************************************************************************
 */

function getMainMenuDivWidth () {
  var div_width = document.getElementById("main_menu").offsetWidth;
  return div_width;
}

function getMainSfMenuWidth () {
  var menu_width = document.getElementById("main_sf-menu").clientWidth;
  return menu_width;
}

function initSuperfish () {
  $("ul.sf-menu").supersubs({
    minWidth:    12,   // minimum width of sub-menus in em units
    maxWidth:    27,   // maximum width of sub-menus in em units
    extraWidth:  1     // extra width can ensure lines don't sometimes turn over
                       //   due to slight rounding differences and font-family
  }).superfish();      // call supersubs first, then superfish, so that subs are
                       //   not display:none when measuring. Call before initialising
                       //   containing tabs for same reason.
}

function setMenuSelection() {
  var url = getRelativeUrl();
  var url_parts;
  var a_expr;
  var a_elmnt;

  // Account for the home page special case.
  // It's included in every url and should only be shown as
  // selected if the user is actually on the home page
  if(url.length <= 1) {
    $("ul.sf-menu a[href='/']").addClass("selected");
    return;
  }

  // Remove the trailing '/' character before an implied
  // 'index.html' reference
  if(url.charAt(url.length - 1) == "/") url = url.substr(0, url.length - 1);

  // Break the URL into components
  var url_parts = url.split("/");

  // If the last part of the URL contains an id reference - remove it.
  // This should be handled by nav - no id refs in the menu
  if(url_parts[url_parts.length - 1].indexOf("#") != -1) url_parts.pop();

  // Clear the url string so we can use it to build it back up.
  url = "";

  // Loop through the path parts selecting menu anchors as we go.
  // Start the loop at one since the array will always have
  // empty string at the first index as per our URL spec.
  for(var i = 1; i < url_parts.length; i++) {
    url += "/" + url_parts[i];
    a_expr = "ul.sf-menu a[href^=\'" + url + "\']";
    a_elmnt = $(a_expr).get(0);
    if(!a_elmnt) {
      dbug_alert("Didn't get a menu anchor element");
      break;
    }
    $(a_elmnt).addClass("selected");
  }
}

function initMenu () {
  initSuperfish();

  /*
  var div_width = getMainMenuDivWidth();
  var menu_width = getMainSfMenuWidth();
  var x = Math.round((div_width - menu_width) / 2);

  var menuElmnt = document.getElementById("main_sf-menu");
  menuElmnt.style.position = "relative";
  menuElmnt.style.left = x + "px";
  */

  setMenuSelection();
}



/******************************************************************************
 * Rotator script
 ******************************************************************************
 */

var arr_rotSteps;
var arr_rotButtons;

var int_rotWidth = 860;
var int_rotHeight = 210;

var int_rotCount = 0;
var int_newRotCount = 0;
var int_maxCount = 0;
var int_rotateInervalId;
var int_rotateInterval = 10000;
var int_fadeSpeed = 500;

var img_rotImage;
var anc_rotAnchor;
var div_rotCntrls;

function rotate () {
  int_newRotCount = (int_rotCount + 1) % int_maxCount;
  beginUpdate();
}

function startRotator () {
  int_rotateInervalId = setInterval("rotate()", int_rotateInterval);
}

function stopRotator () {
  clearInterval(int_rotateInervalId);
}

function rotStep (imageSrc, imageAlt, anchorHref) {
  this.image = new Image(int_rotWidth, int_rotHeight);
  this.image.src = imageSrc;
  this.image.alt = imageAlt;
  this.href = anchorHref;
}

function updateAnchor () {
  $(anc_rotAnchor).attr("href", arr_rotSteps[int_newRotCount].href);
}

function updateImage () {
  $(img_rotImage).attr("src", arr_rotSteps[int_newRotCount].image.src);
  $(img_rotImage).attr("alt", arr_rotSteps[int_newRotCount].image.alt);
}

function updateControls () {
  $(arr_rotButtons[int_rotCount]).removeClass("selected");
  $(arr_rotButtons[int_newRotCount]).addClass("selected");
}

function beginUpdate () {
  $(img_rotImage).fadeOut(int_fadeSpeed, function() { endUpdate() });
}

function endUpdate () {
  updateAnchor();
  updateImage();
  updateControls();
  int_rotCount = int_newRotCount;
  $(img_rotImage).fadeIn(int_fadeSpeed);
}

function buttonClick (event) {
  event.preventDefault();
  stopRotator();
  int_newRotCount = event.data.index;
  beginUpdate();
  // startRotator();  /* do not rotate when user is navigating via buttons */
}

function insertControls () {
  for(var i = 0; i < int_maxCount; i++) {
    $(div_rotCntrls).append("<div><a href=\".\">" + (i + 1).toString() + "</a></div>");
  }

  arr_rotButtons = $(div_rotCntrls).find("a").get();

  for(var i = 0; i < int_maxCount; i++) {
    $(arr_rotButtons[i]).bind("click", {index : i }, function(event) { buttonClick(event); });
  }
}

function initRotator () {
  if(!($("div.rotator").get(0))) return;

  anc_rotAnchor = $("div.rotator > a").get(0);
  img_rotImage = $(anc_rotAnchor).children("img").get(0);
  div_rotCntrls = $("div.rotator div.rot_ctrls").get(0);

  int_maxCount = arr_rotSteps.length;
  insertControls();

  beginUpdate();

  startRotator();
}


/******************************************************************************
 * News script
 ******************************************************************************
 */
var arr_newsElements;
var int_newsCount = 0;
var int_newNewsCount = 0;
var int_maxNewsCount = 0;
var int_newsIntervalId;

function loadNews (newsUrl) {
  var xmlDoc;

  // IE 5 and IE 6
  if (isIE) {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async=false;
    xmlDoc.load(newsUrl);
    return xmlDoc;
  }

  else if (window.XMLHttpRequest){
    xmlDoc = new window.XMLHttpRequest();
    xmlDoc.open("GET", newsUrl, false);
    xmlDoc.send("");
    return xmlDoc.responseXML;
  }

  dbug_alert("Error loading document");
  return null;
}

function createNewsElement (title, link, description, pubDate) {
  // format the date data
  var arr_dateParts = pubDate.split(" ");
  var day = arr_dateParts[1];
  var month = arr_dateParts[2];
  var year = arr_dateParts[3];

  var newsElmnt = "<div class=\"news_content\">\n"                        +
                  "  <a class=\"news_date\" href=\"" + link + "\">\n" +
                  "    <div class=\"date\">\n"                        +
                  "      <div class=\"month\">" + month + "</div>\n"  +
                  "      <div class=\"day\">" + day + "</div>\n"      +
                  "      <div class=\"year\">" + year + "</div>\n"    +
                  "    </div>\n"                                      +
                  "  </a>\n"                                          +
                  "  <div class=\"news_item\">\n"                     +
                  "    <a href=\"" + link + "\">" + title + "</a>\n"  +
                  "    <p>" + description + "</p>\n"                  +
                  "  </div>\n"                                        +
                  "</div>\n";

  return newsElmnt;
}

function prevNewsItem () {
  stopNewsRotator();
  int_newNewsCount = (int_newsCount == 0) ? (int_maxNewsCount - 1) : (int_newsCount - 1);
  beginNewsUpdate();
  startNewsRotator();
}

function nextNewsItem () {
  stopNewsRotator();
  int_newNewsCount = (int_newsCount + 1) % int_maxNewsCount;
  beginNewsUpdate();
  startNewsRotator();
}


function newsRotate () {
  int_newNewsCount = (int_newsCount + 1) % int_maxNewsCount;
  beginNewsUpdate();
}

function startNewsRotator () {
  int_newsInervalId = setInterval("newsRotate()", int_rotateInterval);
}

function stopNewsRotator () {
  clearInterval(int_newsInervalId);
}

function beginNewsUpdate () {
  $("div.news div.contents").fadeOut(int_fadeSpeed, function() { endNewsUpdate() });
}

function endNewsUpdate () {
  int_newsCount = int_newNewsCount;
  $("div.news div.news_content").replaceWith(arr_newsElements[int_newsCount]);
  $("div.news div.contents").fadeIn(int_fadeSpeed);
}


function initNews () {
  if(!($("div.news").get(0))) return;

  var arr_newsItems;

  var title = null;
  var link = null;
  var description = null;
  var puDate = null;

  var newsDoc = loadNews("/news/news_rss_20.xml");
  if(!newsDoc) return;

  arr_newsItems = newsDoc.getElementsByTagName("item");
  int_maxNewsCount = arr_newsItems.length;
  arr_newsElements = new Array(int_maxNewsCount);

  for(var i = 0; i < int_maxNewsCount; i++) {
    title       = arr_newsItems[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
    link        = arr_newsItems[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
    description = arr_newsItems[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
    pubDate     = arr_newsItems[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;

    arr_newsElements[i] = createNewsElement(title, link, description, pubDate);
  }

  $("div.news div.news_content").replaceWith(arr_newsElements[int_newsCount]);

  startNewsRotator();
}

/* Extra function for constructing the "View All News" page. */

function buildNewsPage () {
  var arr_newsItems;

  var title = null;
  var link = null;
  var description = null;
  var puDate = null;

  var newsDoc = loadNews("/news/news_rss_20.xml");
  if(!newsDoc) return;

  arr_newsItems = newsDoc.getElementsByTagName("item");
  int_maxNewsCount = arr_newsItems.length;
  arr_newsElements = new Array(int_maxNewsCount);

  for(var i = 0; i < int_maxNewsCount; i++) {
    title       = arr_newsItems[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
    link        = arr_newsItems[i].getElementsByTagName("link")[0].childNodes[0].nodeValue;
    description = arr_newsItems[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
    pubDate     = arr_newsItems[i].getElementsByTagName("pubDate")[0].childNodes[0].nodeValue;

    // format the date data
    var arr_dateParts = pubDate.split(" ");
    var str_date = arr_dateParts[0] + " " +
                   arr_dateParts[1] + " " +
                   arr_dateParts[2] + " " +
                   arr_dateParts[3];

    var newsEntry = "<h2><a href=\"" + link + "\">" + title + "</a></h2>\n"  +
                    "<p style=\"margin-top: -6px; font-weight: bold;\">\n"   +
                    "  " + str_date                                          +
                    "</p>\n"                                                 +
                    "<p>\n"                                                  +
                    "  " + description + "\n"                                +
                    "</p> <br />\n";

    $("div.content>div").append(newsEntry);

  }
}


/******************************************************************************
 * Nav script
 ******************************************************************************
 */

function clearNavSelection () {
  $("div.nav_bar ul a.selected").removeClass("selected");
}

function setNavSelection () {
  var url = getRelativeUrl();
  var a_expr;
  var nav_anchors;

  // Check to make sure we have a nav_bar
  if(!($("div.nav_bar ul").get(0))) {
    dbug_alert("No Nav Bar on this page!");
    return;
  }

  a_expr = "div.nav_bar ul a[href=\'" + url + "\']";

  nav_anchors = $(a_expr).get();
  if(!nav_anchors[0]) return;

  $(nav_anchors).addClass("selected");
}

function setNavSelectEvent () {
  if(!($("div.nav_bar ul").get(0))) return;

  $("div.nav_bar ul a").click(function() {
    clearNavSelection();
    window.location.href = $(this).attr("href");
    setNavSelection();
  });
}

function initNav () {
  setNavSelectEvent();
  setNavSelection();
}


/******************************************************************************
 * Fancy Zoom script
 ******************************************************************************
 */

function insertPhotoCaptions () {
  if($("div.content div.photo").get(0)) {
    $("div.content div.photo a").append("<span>Click To Enlarge</span>");
  }
}

function insertVideoCaptions () {
  if($("div.content div.video").get(0)) {
    $("div.content div.video a").append("<span>Click To Watch</span>");
  }
}

function initFancyZoom () {
  $('div.photo a').fancyZoom({scaleImg: true, closeOnClick: true});
  $('div.video a').fancyZoom({scaleImg: true, closeOnClick: true});
  insertPhotoCaptions();
  insertVideoCaptions();
  
  $('a.imgdialog').click(function(event) {
    var $link = $(this);
    var href = $link.attr('href');
    var title = $link.attr('title');
    $('<div><img src="' + href + '" alt="' + title + '"></div>')
        .dialog({
            title: title,
            modal: true,
            show: 'fade',
            width: 'auto',
            buttons: { "Close": function() { $(this).dialog("close"); } },
            close: function() { $(this).remove(); }
        });
    return false;  // prevent link follow
  });

  /*
  $('#medium_box_link').fancyZoom({width:400, height:300});
  $('#large_box_link').fancyZoom();
  $('#flash_box_link').fancyZoom();
  */
}


/******************************************************************************
 * Document modification script
 ******************************************************************************
 */

/* Ordered Lists */
function colorOrderedListMarkers () {
  // $(".content ol li").wrapInner("<span class=\"ol_li_text-color\"></span>");
  //$(".content ol li").contents().filter(function(){ return this.nodeType == 3; }).wrap("<span class=\"ol_li_text-color\"></span>");
  $(".content li").wrapInner("<span class=\"list-text-color\"></span>");
}

function colorTightUnorderedListMarkers () {
  // the following doesn't work for nested lists as it does for ordered lists.
  // $(".content ul.tight li").wrapInner("<span class=\"ol_li_text-color\"></span>");
  //$(".content ul.tight li").contents().filter(function(){ return this.nodeType == 3; }).wrap("<span class=\"ol_li_text-color\"></span>");
}


/* Tables */
function alternateTableRowColors () {
  //$(".content table tr:odd td").addClass("oddrow");
}

function styleTableColumns () {
  var tables = $("div.content table").get();
  var columns;
  var rows;
  var data;
  var col_class;
  var col_style;

  for(var i = 0; i < tables.length; i++) {
    columns = $(tables[i]).find("colgroup col").get();
    rows    = $(tables[i]).find("tr").get();

    for(var j = 0; j < rows.length; j++) {
      data = $(rows[j]).find("td").get();

      for(var k = 0; k < columns.length; k++) {
        if(!data[k]) continue;

        if(col_class = $(columns[k]).attr("class")) {
          $(data[k]).attr("class", col_class);
        }

        if(col_style = $(columns[k]).attr("style")) {
          $(data[k]).attr("style", col_style);
        }
      }
    }

    for(var l = 0; l < columns.length; l++) {
      if($(columns[l]).attr("class")) $(columns[l]).removeAttr("class");
      if($(columns[l]).attr("style")) $(columns[l]).removeAttr("style");
    }
  }
}

/* Anchors */
function undecorateImageAnchors () {
  $("div.content img").parent("a").css("border", "none");
}

/* Navigation Bar */
function clearNavBar () {
  $("div.content").append("<br class=\"clear\" />");
}

function initDocument () {
  colorOrderedListMarkers();
  colorTightUnorderedListMarkers();
  alternateTableRowColors();
  styleTableColumns();
  undecorateImageAnchors();
  clearNavBar();
  
  if ($("#home_autospacer").length == 1) {
    $(window).resize(home_resize);
    home_resize();
  }
}

function home_resize() {
  if ($("#home_autospacer").length == 1) {
    var window_height = $(window).height();
    var home_autospacer_top = $("#home_autospacer").offset().top;
    var home_foot_height = $("#home_foot").height();
    var spacer_height = Math.max(window_height - home_foot_height - home_autospacer_top - 8, 0);
    $("#home_autospacer").height(spacer_height);
  }
}


/******************************************************************************
 * IE 6 script (fix the worst F'n' browser on earth!)
 ******************************************************************************
 */

function fixIeSix () {
  var arVersion = navigator.appVersion.split("MSIE");
  var version = parseFloat(arVersion[1]);

  if ((version < 8.0) && (document.body.filters)) {
    fixNav();
  }
}

function fixNav () {
  if(!($("div.nav_bar ul").get(0))) return;

  $("div.nav_bar > ul > li a").css("font-weight", "bold");
  $("div.nav_bar > ul").before("<img src=\"/images/nav_cap_top.png\" alt=\"Nav cap top\" />");
  $("div.nav_bar > ul").after("<img src=\"/images/nav_cap_bottom.png\" alt=\"Nav cap bottom\" style=\"margin-bottom: 20px;\"/>");
}



/******************************************************************************
 * Debug script
 ******************************************************************************
 */

var DBUG = 0;

function print(message) {
  message = message.replace("\n", " <br />");
  $("#test_content").append(message);
}

function println(message) {
  message += " <br />";
  print(message);
}

function dbug_alert(message) {
  if(DBUG) {
    alert(message);
  }
}
