(function($) {
  // global closure and $ portability

  $(document).ready( function() {
    
    // setup questions trigger
    
    var showQuestions = function() {
      $('#wrap_questions').affix($('a#questions_trigger'), { from: "sw", to: "nw", inset: [-16,-8], glueInsideWindow: false }).stop(true, true).fadeIn($.fadeDuration());
      $("#panel_close").hide();
      $('a#questions_trigger').addClass("on");
    };

    var hideQuestions = function() {
      $('a#questions_trigger').removeClass("on");
      $('#wrap_questions').fadeOut($.fadeDuration());
    };
    
    var hideAnswer = function(withQuestions) {
      $('a#questions_trigger')
        .removeClass("question question_long")
        .html("Questions we've heard from clients over the years...")
        .animate({"top": 283}, {duration: "fast", easing: "easeOutQuart"})
        .queue( function() { if (withQuestions) { showQuestions(); } } );
      
      $('#panel_close').hide();
      $('#answers li:visible').fadeOut();
    };
    
    $('a#questions_trigger').click( function(event) {
        
        
        if ($(this).hasClass("question")) {
          // a question is being answered - slide it back down and open the questions again
          hideAnswer(true);
        }
        else {
          
          if ($('#wrap_questions').is(":visible")) {
            hideQuestions();
          } else {
            showQuestions();
          }
        
        }
        
        event.preventDefault();
    });
    
    
    // setup question clicks
    
    $('ul#questions a').click( function(event) {
      
      $('#wrap_questions').hide();
      
      var answer = $('#' + $(this).anchor());
      
      var className = answer.metadata().question_long ? "question question_long" : "question";
      
      if (answer.length > 0) {
        // slide the question trigger up to the top, and update it to contain the question text
        $('a#questions_trigger').stop(true, true).addClass(className).animate({"top": 24}, {duration: "normal", easing: "easeOutQuart"}).removeClass("on").html(answer.find("h2").html());

        // fade in the answer
        answer.fadeIn($.fadeDuration());

        // show the close button
        $("#panel_close").show();
      }
      
      event.preventDefault();
    });
    
    // setup panel close click
    
    $('#panel_close').click( function() {
      hideAnswer();
    });

    
  });
  
})(jQuery);