jQuery().ready(function () {

  // Stop conflicts with mootools
  jQuery.noConflict();

  //Initialize home chart
  InitializeHomeChart()

  if (jQuery('a.bookmark')) {
    jQuery('a.bookmark').bind('click', function (e) {
      e.preventDefault();
      e.stopPropagation();
      return !bookmarkMe(this);
    });
  }

  if (jQuery('#graphthumbs div')) {
    // Hide the current hidden graph
    jQuery('#graphthumbs div[class=current-graph]').hide();
    jQuery('#graphthumbs div').bind('click', function () {
      var img = jQuery(this).children('img').get(0);
      var me = this;
      // Hide the one we clicked on
      jQuery(this).fadeOut(500, function () {
        // hide it
        jQuery(this).addClass('current-graph');
        // show other one
        //alert(jQuery(this).siblings('div[class=current-graph]'));
        jQuery(this).siblings('div[class=current-graph]').fadeIn(500, function () {
          jQuery(this).removeClass('current-graph');
        });
      });

      // Set the big image's 
      // ~/(-thumb).gif/.gif/
      jQuery('#graph-area p img').fadeTo(500, 0.01, function () {
        jQuery('#graph-area p img').attr('src', img.src.replace(/-thumb\.gif/i, '.gif')).attr('title', img.title);
        jQuery('#graph-date').text(img.getAttribute('alt'));
        jQuery(this).fadeTo(500, 1);
      })
    });

    jQuery('#graphutilities a[rel=next]').bind('click', IMO.graph.next);
    jQuery('#graphutilities a[rel=prev]').bind('click', IMO.graph.previous);
  }
});

IMO = {
  graph: {
    next: function () {
      jQuery('#graphthumbs div').siblings('div[class=current-graph]').next().trigger('click');
      return false;
    },
    previous: function () {
      jQuery('#graphthumbs div').siblings('div[class=current-graph]').prev().trigger('click');
      return false;
    }
  }
};

function InitPage() {
  DisplayNavOnHover();
  FixImages();
  InitUtilities();
  AdjustSlideshowHeight();
  StyleDataTables();
  InitCollapseExpandRegionEvent();
}

function toggleProfile(targetId) {

  var div = document.getElementsByTagName('div');

  for (i = 0; i < div.length; i++) {
    if (div[i].id.match('staffprofile')) {
      div[i].style.display = "none";
    }
  }

  if (document.getElementById) {
    target = document.getElementById(targetId);
    if (target.style.display == 'none') {
      target.style.display = '';
    }
  }
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// DisplayNavOnHover
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function DisplayNavOnHover() {
  jQuery('ul#tabnav li').hover(function () {
    // Get the width of the parent li and set it as the width of the hover nav so they match up
    var parentWidth = jQuery(this).outerWidth();
    jQuery('ul:first > li', this).css('width', parentWidth - 3);
    jQuery('ul:first > li > ul.subNavLevel2', this).css('left', parentWidth - 3);
    jQuery('ul:first', this).css('visibility', 'visible').css('display', 'block');
    if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
      jQuery('select').css('visibility', 'hidden');
    }
  }, function () {
    jQuery('ul:first', this).css('visibility', 'hidden').css('display', 'none');
    if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
      jQuery('select').css('visibility', '');
    }
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FixImages
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function FixImages() {
  var classArray = Array('imageRight', 'imageLeft');

  for (var i = 0; i < classArray.length; i++) {
    var divNodes = getElementsByClass(classArray[i], null, 'div')
    for (var j = 0; j < divNodes.length; j++) {
      var divNode = divNodes[j];
      var divWidth = '100px';

      var imageNodes = divNode.getElementsByTagName('img');
      var captionNode = getElementsByClass('imageCaption', divNodes[j], 'div')

      for (k = 0; k < imageNodes.length; k++) {
        if (parseInt(imageNodes[k].width) > parseInt(divWidth)) {
          divWidth = imageNodes[k].width;
        }
      }
      if (captionNode.length > 0) {
        captionNode[0].style.width = (18 + parseInt(divWidth)) + 'px';
      }
    }
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Indexer - Using Jquery
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function UpdateIndexer(pageId, indexerId, pageNumber, thisHref) {
  //alert("PageID: " + pageId + " IndexerID: " + indexerId + " page Number: " + pageNumber + " thisHref: " + thisHref );
  var updateNode = jQuery('#indexer-' + indexerId);

  var url = 'default.csf?pageid=' + pageId + '&indexer=' + indexerId + '&page=' + pageNumber;

  jQuery.ajax({
    type: 'GET',
    url: url,
    success: function (html) {

      updateNode.html(html);
    }
  });
}

function getElementsByClass(searchClass, node, tag) {
  var classElements = new Array();
  if (node == null) {
    node = document;
  }

  if (tag == null) {
    tag = '*';
  }

  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");

  for (i = 0, j = 0; i < elsLen; i++) {
    if (pattern.test(els[i].className)) {
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utilities
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitUtilities() {
  jQuery('div#utilities').css("visibility", "visible");
  InitNextPreviousBtns();
  return;
}

function InitNextPreviousBtns() {
  jQuery("a#btnNext").click(function () { history.forward(); return false; });
  jQuery("a#btnBack").click(function () { history.back(1); return false; });
  return;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Slide show
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var sshowConHeight = '100px';
var sshowSpeed = 5000;
var sshowType = 'sequence';
var sshowTimeout = 8000;

function AdjustSlideshowHeight() {
  var slideshows = jQuery("div.slideshow");
  if (slideshows) {
    for (var i = 0; i < slideshows.length; i++) {
      var container = jQuery(slideshows[i]);
      var firstImage = container.find('img:first');

      if (container.length > 0 && firstImage.length > 0) {
        container.css("height", firstImage.height());
      }
    }
  }
  return;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Styling HTML Data tables that are XSLT Transformed
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function StyleDataTables() {

  var tables = jQuery("table.dataTransform");

  tables.each(function (i) {
    AddCssClassToTable(this);
  }
	)
}

function AddCssClassToTable(table) {
  var rowCount = jQuery(table).find("tr").length;
  jQuery(table).find("tr:odd").addClass("alt");


  jQuery(table).find("tr:last").addClass('last');
  jQuery(table).find("tr:last td:first").addClass('bottomleft');
  jQuery(table).find("tr:last td:last").addClass('bottomright');
  return;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Homepage Chart
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var chartContainer;
var homeImg;
var graphImg;
var GraphImgUrl;

function InitializeHomeChart() {
  chartContainer = jQuery('div#homeChartHolder');
  if (chartContainer.length < 1) {
    return false;
  }

  homeImg = jQuery('img#homeImg');
  graphImg = jQuery('img#homeChartImg');
  GraphImgUrl = graphImg.attr("src");
  graphImg.hide();
  setTimeout('FadeHomeImage()', 3000);
  setTimeout('FadeInGraph()', 3000);
  setTimeout("RefreashGraphImage()", 1000 * 60 * 5)
}

function FadeHomeImage() {
  homeImg.fadeOut(5000);
}

function FadeInGraph() {
  graphImg.fadeIn(5000);
}

function RefreashGraphImage() {
  var randomStr = GetRandomString();
  graphImg.attr("src", GraphImgUrl + "&ver=" + randomStr);
  setTimeout("RefreashGraphImage()", 1000 * 60 * 5);
}

function GetRandomString() {
  var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
  var string_length = 5;
  var randomstring = '';
  for (var i = 0; i < string_length; i++) {
    var rnum = Math.floor(Math.random() * chars.length);
    randomstring += chars.substring(rnum, rnum + 1);
  }
  return randomstring;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Collapsible Region
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitCollapseExpandRegionEvent() {
  jQuery(".regionHeading").click(function () { CollapseExpandRegion(jQuery(this)); });
  jQuery(".collapseContentSections").each(function () { CollapseExpandRegion(jQuery(this)); });
}

function CollapseExpandRegion(element) {
  element.parent().find(".collapsibleContentSections").slideToggle(250);
  var heading = element.parent().find("h5");
  if (heading.css("background-image").indexOf("bulletIconDown.png") != -1) {
    heading.css("background-image", heading.css("background-image").replace("bulletIconDown.png", "bulletIconRight.png"));
  } else {
    heading.css("background-image", heading.css("background-image").replace("bulletIconRight.png", "bulletIconDown.png"));
  }
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Organisation Structure popup
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function displayPopup(ProfileIdOrPageUrl, IsExternalConentRequest) {

  jQuery('#backgroundPopup').css({ 'opacity': '0.7' }).fadeIn('slow');

  var popupText;

  if (!IsExternalConentRequest) {
    popupText = jQuery(ProfileIdOrPageUrl).html();
    jQuery('#popupText').html(popupText);
    jQuery('#popupContainer').center();
    jQuery('#popupContainer').fadeIn('slow');
  }
  else {
    jQuery.ajax({
      type: "GET",
      url: ProfileIdOrPageUrl,
      dataType: "html",
      async: true,
      success: function (data) {
        jQuery('#popupText').html(data);
        jQuery('#popupContainer').center();
        jQuery('#popupContainer').fadeIn('slow');
      }
    });
  }
}

function closePopup() {
  jQuery('#backgroundPopup, #popupContainer').fadeOut('slow', function () {
    jQuery('#popupText, #closePopup').removeAttr('style');
    jQuery('#popupContainer').css({ 'top': '', 'left': '' });
    jQuery('#popupText').html('');
  });
}

jQuery.fn.center = function () {
  if (this.height() > jQuery(window).height()) {
    jQuery(this).find('#closePopup').css('right', '26px');
    jQuery(this).find('#popupText').css({ 'height': '600px', 'overflow': 'auto' });
  }
  else {
    jQuery(this).find('#closePopup').css('right', '10px');
    jQuery(this).find('#popupText').css('height', 'auto');
  }

  this.css('left', (jQuery(window).width() - this.width()) / 2 + jQuery(window).scrollLeft() + 'px');
  this.css('top', (jQuery(window).height() - this.height()) / 2 + jQuery(window).scrollTop() + 'px');

  return this;
}

// if esc button is pressed && the popup box is currently showing then close it
jQuery(document).keyup(function (e) {
  if (e.keyCode == 27 && jQuery('#backgroundPopup').length) { 	// esc key
    closePopup();
  }
});

// Clicking on the backgroundPopup div will close the popup box
jQuery('#backgroundPopup').live('click',
	function () {
	  closePopup();
	  return false;
	});

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////




window.onload = InitPage;
