(function($) {
  
  var initialize_organigram = function() {
    $('#organigram .expandable').bind('click', show_expanded_box).append('<a href="javascript:;">+</a>');
  },
  _currentOverlay = null,
  show_expanded_box = function(e) {
    var $t = $(this),
    title = $t.find('.title').html(),
    name = $t.find('h4').html(),
    studies = $t.find('.studies').html(),
    picture = $t.find('img').attr('src'),
    level = $t.attr('class').match(/level-(\d+)/)[1],
    $overlay =build_overlay({
      title: title,
      name: name,
      studies: studies,
      picture: picture,
      level: level
    });
    closeCurrent();
    $overlay.find('.close').click(closeCurrent);
    if (!$.browser.msie) {
      $overlay.css('opacity', '0');      
    }
    else {
      $overlay.css('visibility', 'hidden');
    }
    
    $overlay.appendTo(document.body);
    
    centerInView($overlay);
    
    if (!$.browser.msie) {
      $overlay.animate({ opacity: 1 }, 800);
    }
    else {
      $overlay.css('visibility', 'visible');
    }
    setTimeout(setupCloseBindings, 0);
    _currentOverlay = $overlay;
  },
  build_overlay = function(data) {
    var container = '<div class="box-expanded level-%level%"><div class="top"></div><div class="mid"><h4>%name%</h4><p class="title">%title%</p><p class="studies">%studies%</p><img src="%picture%" alt="" /></div><div class="bot"></div><a class="close" href="javascript:;">x</a></div>';
    $.each(data, function(k, v) {
      container = container.replace('%' + k + '%', v);
    });
    return $(container);
  },
  centerInView = function($el) {
    var w = $el.outerWidth(),
    h = $el.outerHeight(),
    $w = $(window),
    vpW = $w.width(),
    vpH = $w.height(),
    scrollTop = $w.scrollTop();

    $el.css({
      top: (vpH - h) / 2 + scrollTop + 'px',
      left: (vpW - w) / 2 + 'px'
    });
  },
  closeCurrent = function() {
    if (_currentOverlay) {
      if (!$.browser.msie) {
        _currentOverlay.animate({opacity: 0}, 400, function() { $(this).remove() });        
      }
      else {
        _currentOverlay.remove();
      }
    }
    _currentOverlay = null;
    removeCloseBindings();
  },
  setupCloseBindings = function() {
    $(document).bind('click.organigramCloseMethods keypress.organigramCloseMethods', function(e) {
      if ((e.type == 'click' && !$(e.target).closest('.box-expanded').length) || (e.type == 'keypress' && e.keyCode == 27)) {
        closeCurrent();
      }
    });
  },
  removeCloseBindings = function() {
    $(document).unbind('.organigramCloseMethods');
  };
  
  $(initialize_organigram);
  
  
}(jQuery));