var jargonId = 1;
var jargonUrl = 'a.jargon';
var projectUrl = '';

var timer;
var _ActiveJargon = null;
var _ActiveArea = null;
var _StillActive = false;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Init
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function() {
  $("ul#quicklinks").superfish({ animation: { height: 'show', speed: 'fast'} });
  $("ul#navigation").superfish({ animation: { height: 'show', speed: 'fast'} });
  FixImages();
  InitJargonBuster();
  InsertControlImages();
  InitializeRegistation();
  InitHoverButtons();
  InitTextbox('#password');
  InitTextbox('#email');
  showEmergencyInfo();
  InitializeWpElements();
  InitGallery();

  $("li#customer-link-glossary a").colorbox(
    { href: "/customer-glossary?glossary=true", width: 680, opacity: 0.75 }
  );
});

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// InitGlossaryLink
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$().bind('cbox_complete', InitGlossaryLink);

function InitGlossaryLink() {
  $("a.glossary-link").click(function() {
    var href = "/customer-glossary?glossary=true&letter=" + $(this).html();
    $(this).colorbox(
      { href: href, opacity: 0.75 }
    );

    if (!$.browser.msie) {
      $('div#glossary-column').load(href + '&ajax=true', InitGlossaryLink);
    }

    return false;
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// InitTextbox
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitTextbox(elem) {
  $(elem).blur(function() {
    if ($(this).val() == '') {
      $(this).css('background-position', '6px 5px');
    }
  });

  $(elem).focus(function() {
    $(this).css('background-position', '-500px 5px');
  });

  if ($(elem).val() != '') {
    $(elem).css('background-position', '-500px 5px');
  }
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Adds hover state to ie6 buttons
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitHoverButtons() {
  if ($.browser.msie && ($.browser.version < 7)) {
    $('input.hoverbutton, input.formButton, input.searchButton').each(function() {
      $(this).mouseover(function() { $(this).css('background-position', 'top right') });
      $(this).mouseout(function() { $(this).css('background-position', 'top left') });
    });
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Jargon
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function InitJargonBuster() {
  objShowBuster = $("#jBusterListItem");

  if (objShowBuster.length > 0) {
    $(objShowBuster[0]).css('display', 'block');

    if ($("#jBustToggleOn")[0].checked) {
      ActivateJargonBuster(false);
    } else {
      DeActivateJargonBuster(false);
    }
  }
}

function ActivateJargonBuster(sendRequest) {
  $('span.jargonHighlight').each(function() {
    $(this).css({ 'background-color': '#e1f4fd', 'zIndex': '1' });
    $(this).mouseover(function() { GetJargonDecription(this); });
  });

  if (sendRequest) {
    $.ajax({
      type: "GET",
      url: jargonUrl,
      data: "action=on"
    });
  }
}

function DeActivateJargonBuster(sendRequest) {
  $('span.jargonHighlight').each(function() {
    $(this).css({ 'background-color': 'transparent' });
    $(this).mouseover(function() { });
  });

  if (sendRequest) {
    $.ajax({
      type: "GET",
      url: jargonUrl,
      data: "action=off"
    });
  }
}

function GetJargonDecription(node) {
  $(node).css('position', 'relative');

  if (node.id == "") {
    node.id = 'jargon' + jargonId++;
    node.onmouseout = function() { _ActiveJargon = null; };

    var url = jargonUrl;
    var postdata = 'jargonid=' + node.id + '&word=' + escape(node.innerHTML);

    $.getJSON(url, postdata,
      function(data) {
        CreateJargonPopup(data.id, data.text);
      });

  } else {
    var divNode = $(node).find('div');
    if (divNode.length > 0) {
      $(divNode[0]).css('display', 'block');
    }
  }

  _ActiveJargon = node.id;
}

function CreateJargonPopup(nodeId, text) {
  var node = $("#" + nodeId);

  if (node.length > 0) {

    var div = document.createElement('div');

    $(div).html(text);
    $(div).addClass('jargonPopUp');

    div.onmouseout = function() { $(this).css('display', 'none'); $(node[0]).css({ 'position': 'relative', 'z-index': '1' }); };
    div.onclick = function() { $(this).css('display', 'none'); $(node[0]).css({ 'position': 'relative', 'z-index': '1' }); };
    node[0].onmouseout = function() { $(this).css({ 'position': 'relative', 'z-index': '1' }); $(div).css('display', 'none'); };
    node[0].onmouseover = function() { $(this).css({ 'position': 'relative', 'z-index': '10' }); };

    $(div).css('visibility', 'hidden');
    $(node[0]).append(div);
    $(node[0]).css({ 'position': 'relative', 'z-index': '10' });

    //Determine if popup should be displayed above or below the highlight.
    //Popup will be displayed below if it touches outside the content-column

    if ($('#content-column').length > 0) {
      var offsetLimit = $('#content-column').offset().top;
    } else {
      var offsetLimit = 0;
    }
    var divPos = parseInt($(div).offset().top) - parseInt(div.offsetHeight);
    if ((divPos) >= offsetLimit) {
      $(div).css('top', (-div.offsetHeight) + 'px');
    } else {
      $(div).css('top', (node[0].offsetHeight) + 'px');
    }
    $(div).css('visibility', 'visible');

    if (nodeId == _ActiveJargon) {
      $(div).css('display', 'block');
    } else {
      $(div).css('display', 'none');
    }
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Emergency Info
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function showEmergencyInfo() {
  var emergency = $('div#emergency-popup');

  if (emergency.length > 0) {
    var html = $(emergency).html();
    $(emergency).remove();

    $('body').append('<div id="jquery-overlay"></div>');
    $('body').append('<div id="emergency-popup">' + html + '</div>');

    var arrPageSizes = GetPageSize();

    $('#jquery-overlay').css({
      backgroundColor: '#000000',
      opacity: 0.8,
      width: arrPageSizes[0],
      height: arrPageSizes[1],
      position: 'absolute',
      top: '0px',
      left: '0px',
      zIndex: 10000
    }).fadeIn();

    $('#emergency-popup').css({
      display: 'block',
      zIndex: 10001
    }).fadeIn();

    $('#button-emergency-close').hover(
      function() { $(this).css('cursor', 'hand'); },
      function() { $(this).css('cursor', ''); }
    ).click(function() {
      $('div#jquery-overlay').remove();
      $('div#emergency-popup').remove();
    });
    
  }
}

function GetPageSize() {
  var xScroll, yScroll;
  if (window.innerHeight && window.scrollMaxY) {
    xScroll = window.innerWidth + window.scrollMaxX;
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
    xScroll = document.body.scrollWidth;
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    xScroll = document.body.offsetWidth;
    yScroll = document.body.offsetHeight;
  }
  var windowWidth, windowHeight;
  if (self.innerHeight) {	// all except Explorer
    if (document.documentElement.clientWidth) {
      windowWidth = document.documentElement.clientWidth;
    } else {
      windowWidth = self.innerWidth;
    }
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowWidth = document.documentElement.clientWidth;
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowWidth = document.body.clientWidth;
    windowHeight = document.body.clientHeight;
  }
  // for small pages with total height less then height of the viewport
  if (yScroll < windowHeight) {
    pageHeight = windowHeight;
  } else {
    pageHeight = yScroll;
  }
  // for small pages with total width less then width of the viewport
  if (xScroll < windowWidth) {
    pageWidth = xScroll;
  } else {
    pageWidth = windowWidth;
  }
  arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
  return arrayPageSize;
};


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Indexer
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function UpdateIndexer(pageId, indexerId, pageNumber) {
  var url = 'default.csf?pageid=' + pageId + '&indexer=' + indexerId + '&page=' + pageNumber;

  $.ajax({
    type: 'GET',
    url: url,
    success: function(html) {
      $('#indexer-' + indexerId).html(html);
    }
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// QuickLinks
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function AddToFavorites(pageId) {
  Favorites('tr_add.fav?pageid=' + pageId + "&currentpageid=" + pageId);
}

function RemoveFavorites(pageId, currentpageid) {
  Favorites('tr_remove.fav?pageid=' + pageId + "&currentpageid=" + currentpageid);
}

function Favorites(url) {
  $.ajax({
    type: 'GET',
    url: url,
    success: function(html) {
      $('#quicklinks-inner').html(html);
    }
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FixImages
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function FixImages() {
  $('div.imageRight, div.imageLeft, div.imageTop').each(function() {
    var width = $(this).find('img').width();
    $(this).find('span.imageCaption').width(width);
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Show Comments
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function ShowComments(nodeId) {
  $(nodeId).toggle();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Initialize Registation
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function InitializeRegistation() {
  if ($('#registration-wrapper').length < 1) {
    return;
  }

  $('tr.js-delete').each(function() {
    $(this).remove();
  });

  $('td.relations-checkboxes input').each(function() {
    $(this).click (function() { ToggleRegistrationSections(); });
  });

  ToggleRegistrationSections();
}

function ToggleRegistrationSections() {
  $('tr.extra-data').each(function() {
    $(this).css('display', 'none');
  });

  $('td.relations-checkboxes input').each(function() {
    if (this.checked) {
      $('tr.' + this.name).each(function() {
        $(this).css('display', '');
      });
    }
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Subscription
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

// Toggles the subscribe list to expand and close by changing it's display attribute
function ToggleList(element, subList) {
  if (element && subList) {
    if (subList.style.display != 'block') {
      subList.style.display = 'block';
      element.src = siteRoot + '/notion/site/transpowerinternet/images/transpower/subscription-contract.gif';
    } else {
      subList.style.display = 'none';
      element.src = siteRoot + '/notion/site/transpowerinternet/images/transpower/subscription-expand.gif';
    }
  }
  return false;
}

// Inserts "expand" icons into the top level list items
function InsertControlImages() {
  $('ul.subList').each(function() {
    var image = '<img class="controlImages" src="' + siteRoot + '/notion/site/transpowerinternet/images/transpower/subscription-expand.gif" />';
    $(this).prev().before(image);
    $(this).css('display', 'none');
    var list = this;
    $('.controlImages').click(function() { ToggleList(this, list); });
  });
  return false;
}

// Select all list item checkboxes
function SelectAll() {
  SetTextbox(true);
}

// Untick all check boxes on the subscribable area list
function ClearAll() {
  SetTextbox(false);
}

// Set all textboxes
function SetTextbox(val) {
  $('div#subscribeAreas input[type=checkbox]').each(function() {
    $(this).checked = val;
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Outages
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


//entry point for toggling the wp elements
function wpChanged(elementName) {

  if (elementName == "outage-window") {
    toggleWp("#outage-window-requests", "#outage-plant-requests");
  }
  else if (elementName == "outage-plant") {
    toggleWp("#outage-plant-requests", "#outage-window-requests");
  }
  return false;
}

//display one of the wp elements and hide the other depending on which one is selected 
function toggleWp(show, hide) {
  $(show).css('display', 'block');
  $(hide).css('display', 'none');
  return false;
}

//hide one of the wp elements when the page loads
function InitializeWpElements() {
  $("#outage-plant-requests").css('display', 'none');
  return false;
}

//entry point fo toggling the Site list options based on user selection
function toggleSiteList(selectBox) {
  var selected = selectBox[selectBox.selectedIndex].value;
  if (selected != "*") {
    setSiteList(selected);
  } else {
    resetSiteList();
  }
  return false;
}

//set the the site list to show user selected options only
function setSiteList(selected) {
  $('div#outage-site ul li').css('display', 'none');
  $('div#outage-site ul li.' + selected).css('display', 'block');
  return false;
}

//reset the site list so that all options are displayed
function resetSiteList() {
  $('div#outage-site ul li').css('display', 'block');
}

function deselectSelectAll(node) {
  if (node.checked) {
    $('#site-all').each(function() {
      this.checked = false;
    });
  }
}

function deselectSelect() {
  $('div#outage-site ul li input').each(function() {
    this.checked = false;
  });
}