var jargonId = 1;
var jargonUrl = 'a.jargon';
var projectUrl = '';

var timer;
var _ActiveJargon = null;
var _ActiveArea = null;
var _StillActive = false;

var majorProjectsTimer;
var majorProjectsActive = false;

function Init(){
  InitNavigation();
  InitMapPopUp();
  InitHomePageMap();
  InitSubscription();
  FixImages();
  InitJargonBuster();
  InitHoverButtons();
  InitGallery();
  InitMajorProjectsMap();
  $('#news-viewport').newsslider();
  InitImageGalleryEvents();
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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')});
    });
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Project map
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitMapPopUp() {
  $('#smallMapLink').css('display', 'block');
}

function displayMap() {
  $('#largeMap').css({'top' : '20px', 'display' : 'block'});
}

function hideMap() {
  $('#largeMap').css('display', 'none');
}

function toggleMapKey() {
  $('#largeMapKey').toggle();
}

function largeMapPrint() {
  var content = document.getElementById("largeMapImg");

  if (content) {
    var docprint=window.open("","","toolbar=no,location=no,directories=no,menubar=no,scrollbars=no,width=auto,height=auto,left=100,top=25");
    docprint.document.open();
    docprint.document.write('<html><head></head><body>');
    docprint.document.write(content.innerHTML);
    docprint.document.write('</body></html>'); 
    docprint.document.close();
    docprint.print();
    docprint.close();
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Homepage map
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitHomePageMap(){
  $('div.regPopUp').each(function(){
    $(this).css({'visibility' : 'hidden', 'display' : 'block'});

    $(this).find('.popup-body').each(function(){
      if($(this).height() > 180){
        $(this).css({'height' : '180px', 'overflow' : 'hidden'});
        $(this).jScrollPane({showArrows:true, scrollbarWidth: 16});
      }
    });

    var posY = $(this).offset().top - $(this).parent().offset().top - $(this).height();

    if(posY > -20){
      $(this).css({'top' : posY + 'px'});
    } else {
      $(this).css({'top' : '-20px'}).find('.pullOut').css({'bottom' : (-posY - 10) + 'px'});
    }

    $(this).css({'display' : 'none', 'visibility' : 'visible'});
    
    $(this).mouseout(function(e){ 
      var top = $(this).offset().top;
      var bottom = top + $(this).height();
      var left = $(this).offset().left;
      var right = left + $(this).width();
      
      if(e.clientY < top || e.clientY > bottom || e.clientX < left || e.clientX > right){
        StartTimer();
      }
    });
    
    $(this).mouseover(function(){ CancleHide(); });
    $(this).find('*').each(function(){
      $(this).mouseover(function(){ CancleHide(); });
    });
  });
}

function HideAll(area){
  $('div#mapHoverImages img').each(function(){
    if($(this).id != area){
      $(this).css('display', 'none');
    }
  });

  $('div#mapHoverProjects div.regPopUp').each(function(){
    if($(this).id != 'popup-' + area){
      $(this).css('display', 'none');
    }
  });
}

function ImageOn(area) {
  _StillActive = true;

  HideAll(area);

  var elem = $('#' + area);
  var popup = $('#popup-' + area);

  if(elem.length > 0 && popup.length > 0){
    _ActiveArea = area;
    $(elem[0]).css('display', 'block');
    $(popup[0]).css('display', 'block');
  }
}

function ImageOff(area) {
  StartTimer();
}

function CancleHide(){
  clearTimeout(timer);
  _StillActive = true;
}

function StartTimer() {
  _StillActive = false;
  timer = setTimeout('HideProjectInfo()', 200);
}

function HideProjectInfo() {
  if(!_StillActive){
    var elem = $('#' + _ActiveArea);
    var projectInfo = $('#popup-' + _ActiveArea);
    if(elem.length > 0 && projectInfo.length > 0){
      $(elem[0]).css('display', 'none');
      $(projectInfo[0]).css('display', 'none');
      _StillActive = false;
    }
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Subscription
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function InitSubscription(){
  $('ul.region').each(function(){
    $(this).css('display', 'none');
      
    $(this).parent().find('img').each(function(){
      this.src = this.src.replace('CloseIconWhite.gif','OpenIconWhite.gif');
    });
      
    $(this).parent().find('a').each(function(){
      $(this).html('open section');
    });
  });
}

function toggleChildren(obj, imgNodeId, path){
  $(obj).parent().find('ul:first').each(function(){
    var imgNode = $('#' + imgNodeId);

    if(imgNode.length > 0){
      if($(this).css('display') != 'none'){
        $(this).css('display' , 'none');
        $(obj).html('open section');
        imgNode[0].src = path + 'OpenIconWhite.gif';
      } else {
        $(this).css('display' , 'block');
        $(obj).html('close section');
        imgNode[0].src = path + 'CloseIconWhite.gif';
      }
    }
  });
}

function ClearAll(){
  var node = $('#subOptions');

  if(node.length > 0){
    DeActiveAllChildCheckboxes(node[0]);
  }
}

function SelectAll(){
  var node = $('#subOptions');

  if(node.length > 0){
    ActiveAllChildCheckboxes(node[0]);
  }
}

function CheckChildren(obj){
  if(obj.checked == true){
    ActiveAllChildCheckboxes(obj.parentNode);
  } else {
    DeActiveParentCheckboxes(obj, 'subOptions');
  }
}

function UnCheckParents(obj){
  if(obj.checked == false){
    DeActiveParentCheckboxes(obj, 'subOptions');
  }
}

function UnCheckGrandParents(obj){
  if(obj.checked == false){
    DeActiveParentCheckboxes(obj.parentNode.parentNode.parentNode.parentNode, 'subOptions');
  }
}

function ActiveAllChildCheckboxes(obj){
  SetValueAllChildCheckboxes(obj, true);
}

function DeActiveAllChildCheckboxes(obj){
  SetValueAllChildCheckboxes(obj, false);
}

function SetValueAllChildCheckboxes(obj, value){
  $(obj).find("input[type='checkbox']").each(function(){
    this.checked = value;
  });
}

function DeActiveParentCheckboxes(obj, topNodeId){
  while(obj.parentNode != null && obj.parentNode.id != topNodeId){
    obj = obj.parentNode;
    var childNodes = obj.childNodes;

    for(var i = 0; i < childNodes.length; i++){
      var currentNode = childNodes[i];

      if(currentNode.type == 'checkbox'){
        currentNode.checked = false;
      }
    }
  }
}


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// InitMajorProjectsMap
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function InitMajorProjectsMap(){
  $('#majorprojects-region-map-map').find('area').hover(
    function() {
      var id = $(this).attr('rel');
      if (id) {
        majorProjectsActive = true;

        $('#mapHoverImages img').each(function() {
          $(this).css('display', 'none');
        });

        $('#' + id).css('display', 'block');
      }
    },
    function() {
      var id = $(this).attr('rel');
      if (id) {
        majorProjectsActive = false;
        timer = setTimeout('majorProjectsHide()', 200);
      }
    }
  );

  $('#mapHoverImages img').mouseover(function() {
    clearTimeout(majorProjectsTimer);
    majorProjectsActive = true;
  });
}

function majorProjectsHide(area) {
  if(!majorProjectsActive){
    $('#mapHoverImages img').each(function(){
      $(this).css('display', 'none');
    });
  }
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// 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' : '#dce5e9', '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');
    }
  }
}

var isDetailsOpen = false;
function InitImageGalleryEvents(){
  
  var galleryContainer = $('#gallery-image');    
  var imageDetails = $('div#gallery-image-details');
  var imageTools =  $('div#div#tools');
  
  galleryContainer.bind('mouseover', function(event) {
    
    if(isDetailsOpen){
     return;
    }
    
    ToggleGalleryDetails(true);
  });
  
  galleryContainer.bind('mouseout', function(event) {
    onGalleryMouseOut(event);
  });
  
  imageDetails.bind('mouseout', function(event) {
    onGalleryMouseOut(event);
  });
  
  imageTools.bind('mouseout', function(event) {
    onGalleryMouseOut(event);
  });
   
}

function onGalleryMouseOut(event){
  if(!isDetailsOpen){
   return;
  }

  if(CheckGalleryBoundry(event)){
    return;
  }
  ToggleGalleryDetails(false);
}

function CheckGalleryBoundry(event){
  var galleryContainer = $('#gallery-image');  
  var imageDetails = $('div#gallery-image-details');
  var galleryContainerHeight = parseInt(galleryContainer.css("height"));
  var galleryContainerTopPos = galleryContainer.offset().top;
  var imageDetailsHeight = imageDetails.outerHeight();
     
  var a = galleryContainerTopPos + galleryContainerHeight;
  var b = a - imageDetailsHeight - 20;

  if(event.pageY <= a && event.pageY >= b){      
    return true;
  } else{
    return false;
  }
}

//Used by NIGUP Image gallery 
function ToggleGalleryDetails(openDetails){
  
  var imageDetails = $('div#gallery-image-details');
  var tools = $('div#tools');
  
  if(openDetails){
    imageDetails.fadeIn(100, function(){isDetailsOpen = true});
    tools.fadeIn(100);
  } else {
    imageDetails.fadeOut(100, function(){isDetailsOpen = false});
    tools.fadeOut(100);
  }
}

window.onload = Init;