(function($) {  
  // responsible for creating the overlay the first time it's needed
  var constructOverlay = function() {
    if (!$("#tinybox_overlay").length) {
      $(document.body).append('<div id="tinybox_overlay"></div>')

      // sets up the click handler such that clicking on the overlay (e.g. outside the modal window) hides it
      $("#tinybox_overlay, .tinybox_close").click(function() {
        var overlay = $("#tinybox_overlay");
        
        $(".tinybox_content").fadeOut('slow', function() {
          overlay.fadeOut('slow', function() {
            $("dt.selected").next("dd").hide().end().removeClass('selected');
            $("#related_questions .scroll-pane")[0].scrollTo(0);
          });
          $(this).removeClass("tinybox_content");
          
          $("#related_questions_button").fadeOut('slow');
        });
        
        return false;
      });
    }
  }
  
  $.fn.extend({
    tinybox: function() {
      return this.each(function() {        
        $(this).click(function() {
        
        
          // kg added
          // --- if opening a #contact box, reset it always!
          if ($(this).attr('href') == '#contact')
          {
             // reset things always (v2)
            $("#contact_form_wrapper").slideDown('slow');
            $("#contact_post_submission").hide();
            
          } 
          // end kg added 
        
          var delayFade = false;
          
          // allows for switching out content of a currently shown tinybox without fading out the overlay
          if ($(".tinybox_content").length) {
            $(".tinybox_content").fadeOut(600);
            $("#related_questions_button").show();
            delayFade = true
          }
          constructOverlay();

          var content = $($(this).attr('href'));
          content.addClass('tinybox_content');
          content.hide();
          content.css({ 'top': '5%'});

          $("#tinybox_overlay").css({ 'opacity': "0.7" }).fadeIn('slow', function() {
            setTimeout(function() { content.fadeIn('slow'); }, (delayFade ? 700 : 0));
          });
          
          return false;
        });
      });
    }
  });
})(jQuery);
