var news_tabs = function() {

  var container = $('div.news_and_events');

  if (container.length > 0) {

    var list = $('<ul></ul>', {'class':'nav'}),
        h3s = container.find('h3');

    h3s.each(function() {
      $(this).parent().attr('id', $(this).text());
      $(this).appendTo(list).wrap('<li></li>');
    });

    list.find('li:first-child').addClass('active');
    list.prependTo(container);

    container.find('.news, .events').hide().first().show();

    list.find('li').bind('click', function() {
      list.find('li').removeClass('active');
      $(this).addClass('active');

      container.find('>div').hide();
      container.find('div#' + $(this).text()).fadeIn();
      set_box_height();
    });

    var link = $('<a></a>', {
      "class": "view_all",
      text: "Expand",
      click: function() {
        var div = container.find('.news:visible, .events:visible'),
            height = div.css("height");

        if(height === 'auto') {
          set_box_height();
        } else {
          div.css('height', 'auto');
          $(this).text("Collapse");
        }
      }
    });

    container.append(link);


    var set_box_height = function() {
      var events = container.find(".events"),
          news   = container.find(".news"),
          n_li   = $(news.find('li')[1]),
          e_li   = $(events.find('li')[1]),
          css    = {position: 'relative', overflow: 'hidden'},
          n_h, e_h;

      events.css(css);
      news.css(css);

      if(n_li.length > 0) {
        n_h = n_li.position().top;
        news.height(n_h);
      }
      if(e_li.length > 0) {
        e_h = e_li.position().top + e_li.height();
        events.height(e_h);
      }

      (news.is(':visible') && news.find('li').length > 2 || events.is(':visible') && events.find('li').length > 2) ? link.show() : link.hide();

      link.text("Expand");
    };

    set_box_height();

    container.find('div li a').hover(function() {
      var link = $(this).clone(),
          text = $(this).closest('li').find('p').clone(),
          top, left, popout;

      if(bh.popout) bh.popout.remove();

      bh.popout = $('<div class="popout news_events"></div>').css('position', 'absolute');

      popout = bh.popout;

      link.text(link.attr('title'));

      $('<div></div>').append(link).append(text).appendTo(popout);

      popout.appendTo('body');

      popout.hide().fadeIn();

      top = ($(this).offset().top - popout.height()) + 112;
      left = $(this).offset().left - popout.width();

      popout.css({
        top: top,
        left: left
      });


    }, function() {
      if(bh.popout) bh.popout.remove();
    })

  }


};


$(function() {
  news_tabs();
});

