$(function() {
  var timeout = null;
  var $open = null;
  var height_index = {};

  var offset_top = 35
  var offset_bottom = 35;
  var max_height = (($('#main-content-img').height() - offset_top) - offset_bottom);
  var default_offset_top = ($('#main-content-img').offset().top + offset_top);
    
  function get_rel(elm) {
    return elm.rel;
  }

  function calc_position(params) {
    var elm_offset_top, height_diff, elm_height;
    height_diff = (max_height - params.height - params.offset_top);

    // calculate height
    if (max_height >= params.height) {
      elm_height = params.height;
    } else {
      elm_height = max_height;
    }

    // calculate offset
    if (0 < height_diff) {
      elm_offset_top = params.offset_top; 
    } else if (0 > height_diff && max_height > params.height) {
      elm_offset_top = (Math.floor((max_height - params.height) / 2) + offset_top);
    } else {
      elm_offset_top = default_offset_top;
    }

    return {
      height: elm_height,
      offset_top: elm_offset_top
    };
  }

  function show_content(offset_top) {
    var pos = calc_position({
      height: $open.outerHeight(),
      offset_top: offset_top
    });

    padding = parseInt($open.css('paddingTop').replace(/[^0-9]+/, ''));
    padding += parseInt($open.css('paddingBottom').replace(/[^0-9]+/, ''));

    if ('undefined' != typeof $open) {
      $open
        .offset({ top: pos.offset_top, left: $open.offset().left })
        .height((pos.height - padding) + 'px')
      $open.animate({left:0}, 100);
    }
  }

  function hide_content() {
    if ('undefined' != typeof $open) {
      $open.animate({left:'-387px'}, 100);
      $open = null;
      clearTimeout(timeout);
    }
  }
  
  // event binding
  $('.events-menu li > a')
    .bind('mouseover', function(evt){
     var evt_offset_top = $(evt.target).offset().top;
      if (null != $open) {
        clearTimeout(timeout);
        hide_content();
      }
      $open = $('#' + get_rel(evt.target));
      show_content(evt_offset_top);
    })
    .bind('mouseout', function(evt){
      timeout = setTimeout(function() {
        hide_content();
      }, 500);
    })
    .click(function() { return false; });

  $('#events')
    .bind('mouseover', function() {
      if (null != $open) {
        clearTimeout(timeout);
      }
    })
    .bind('mouseout', function(evt) {
      if (null != $open) {
        timeout = setTimeout(function() {
          hide_content();
        }, 500);
      }
    });

	$("#newsletter").fancybox({
    transitionIn: 'elastic',
    transitionOut: 'elastic',
    height: 530,
    autoDimensions: false
  });
});



