var jargonId = 1;
var jargonUrl = 'a.jargon';
var _ActiveJargon = null;
var LiveMapDataUrl = "http://localhost/TranspowerInternet/default.lmd";
var _Timer;
var _AutoTimer;
var _ActiveArea = 0;
var _ActiveAutoTimer = false;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Init
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

$(document).ready(function(){
  jQuery("ul#quicklinks").superfish({animation : {height:'show', speed:'fast'}});
  InitNavigation();
  FixImages();
  InitJargonBuster();
  InitHoverButtons();
  InitLiveMapData();
  InitMap();
  InitChooseGraph();
  InitGallery();
});


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Graph
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitChooseGraph(){
  if($('div#choose-graph-wrapper').length > 0){
    $('div#choose-graph-wrapper img').click(function() { 
      var node = $('div#choose-graph-dropdown');
      
      if(node.length > 0){
        if($(node[0]).css('display') != 'block'){
          $(node[0]).show('slow');
        } else {
          $(node[0]).hide('slow');
        }
      }
    });
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Map
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitMap(){
  if($('div#zone-loading').length > 0){
    $('div#mapHoverProjects').find('*').each(function(){
      $(this).mouseover(function(){ CancleHide(); });
      $(this).mouseout(function(){ RequestHideZone(); });
    });

    $('img#mapOverlay').mouseout(function(){ ActivateCycle(); });

    setInterval("AutoShow()", 2000 );
    ActivateCycle();
  }
}

function ActivateCycle(){
  _ActiveAutoTimer = true;
}

function DeActivateCycle(){
  _ActiveAutoTimer = false;
}

function AutoShow(){
  if(_ActiveAutoTimer){
    _ActiveArea = _ActiveArea + 1;

    if(_ActiveArea > 14){
      _ActiveArea = 1;
    }

    ShowArea('zone' + _ActiveArea);
  }
}

function ImageOn(zone){
  DeActivateCycle();
  ShowArea(zone);
}

function ShowArea(zone){
  _StillActive = true;
  clearTimeout(_Timer);
  HideAll();
  $('div#popup-' + zone).show();
  $('img#hover-' + zone).show();
}

function ImageOff(zone){
  RequestHideZone();
}

function HideAll(){
  $('img.hover-zone').each(function(){
    $(this).hide();
  });
  
  $('div.popup-zone').each(function(){
    $(this).hide();
  });
}

function CancleHide(){
  clearTimeout(_Timer);
  _StillActive = true;
}

function RequestHideZone(){
  _StillActive = false;
  _Timer = setTimeout('HideZone()', 200);
}

function HideZone(){
  if(!_StillActive){
    HideAll();
    _StillActive = false;
  }
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Loads the MapData
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitLiveMapData(){
  if($('div#live-data-map-wrapper').length > 0){
    setInterval("UpdateMap()", 5000 );
  }
}

function UpdateMap(){
  $.getJSON(LiveMapDataUrl,
    function(data){
      $.each(data, function(i,item){
        if(i == 'live-data-map-total-value'){
          var text = 'TOTAL NEW ZEALAND POWER SYSTEM - ' + item + 'MW';
          try{
            sIFR.replacements["h2#live-data-map-heading"][0].replaceText(text, text);
          } catch (err){}
        } else if (i.indexOf('-value') > -1)  {
          $('span#' + i).html(item);
        } else {
          if(item == 'true'){
            $('div#' + i).addClass('live-data-trend-up');
            $('div#' + i).removeClass('live-data-trend-down');
          } else {
            $('div#' + i).addClass('live-data-trend-up');
            $('div#' + i).removeClass('live-data-trend-down');
          }
        }
      });
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Loads the navigation
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitNavigation(){
  if($.browser.msie && ($.browser.version < 7) && $('select').length > 0){
    $("ul#navigation").superfish({animation : {height:'show', speed:'fast'}}).find('ul').bgIframe({opacity:false});
  } else {
    $("ul#navigation").superfish({animation : {height:'show', speed:'fast'}});
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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')});
    });
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Subscription
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function ClearAll(){
  $('form#newSubcribers').find("input[type='checkbox']").each(function(){
    this.checked = false;
  });
}

function SelectAll(){
  $('form#newSubcribers').find("input[type='checkbox']").each(function(){
    this.checked = true;
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FixImages
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function FixImages(){
  $('.imageRight, .imageLeft, .imageTop').each(function(){
    $(this).css('width' , $(this).find('img').width() + 'px');
  });
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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' : '#d1e7ec', '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', 'static'); };
    div.onclick = function(){ $(this).css('display', 'none'); $(node[0]).css('position', 'static'); };
    node[0].onmouseout = function(){ $(this).css('position', 'static'); $(div).css('display', 'none'); };

    $(div).css('visibility', 'hidden');
    $(node[0]).append(div);
    
    //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');
    }
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Indexer - Needs updating
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function UpdateIndexer(pageId, indexerId, pageNumber){
	var url = 'default.csf?id=' + pageId + '&indexer=' + indexerId + '&page=' + pageNumber;
	
	new Ajax(url, {
		method: 'get',
		update: $('indexer-' + indexerId)
	}).request();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// QuickLinks - Needs updating
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function AddToFavorites(pageId){
	Favorites('so_add.fav?pageid=' + pageId + "&currentpageid=" + pageId);
}

function RemoveFavorites(pageId, currentpageid){
	Favorites('so_remove.fav?pageid=' + pageId + "&currentpageid=" + currentpageid);
}

function Favorites(url){
	$.get(url, function(data){
    $('ul#quicklinks-inner').html(data);
  });
}