$(document).ready(function() {  
  // support for modal windows (aka lightboxes)
  $("a.tinybox").tinybox();

  // load flash movie for homepage
  swfobject.embedSWF("flash/recoverystartshere_intro.swf", "home_movie", "570", "276", "8.0.0", "flash/expressInstall.swf", {}, {'wmode':'transparent'});

  // determine our base element to scroll based on the browser
  var msie6 = ($.browser.msie && $.browser.version == 6);
  var baseElement = (msie6) ? $(".wrapper") : $(window);

  // fixes bug where FF2 always wants to move the content to some weird position after window resize
  $(window).resize(function() {
    baseElement.scrollTo(previousElement, 0, { 'axis': 'yx', 'queue':true});
  });

  // start the page at the home section (since it isn't 0,0 centered)
  $("#home").show();
  
  baseElement.scrollTo('#home', 0, { 'axis': 'xy' });

  // support for custom scroll bar on content panels
  $('.scroll-pane').jScrollPane( { 'scrollbarWidth': 2, 'scrollbarMargin': 10 } );
  
  // support for tabbed navigation fade in/out. The select function ensures that the tab state changes before 
  // the fade animation, and also re-scrolls any other scroll panes to their top
  $(".content").tabs({ 'fx': { 'opacity': 'toggle' }, 'select': function(event,ui) {
      setTimeout(function() {
        $(ui.panel).siblings(".panel").find(".scroll-pane").each(function() {
          if (this.scrollTo) { this.scrollTo(0); }
        })
      }, 300);
      
      $(ui.tab).closest('li').siblings().removeClass('ui-tabs-selected').end().addClass('ui-tabs-selected');
      $(ui.tab).blur();
    } 
  });
  
  // support for opening a tab from a text link
  $('.panel a.learn_more').click(function() {
      $(this).closest(".content").tabs('select', 1);
      return false;
  });
  
  // we keep track of the previous element so that:
  // 1. we can re-set its tab state to the landing page when we leave it and,
  // 2. (for FF2) we can re-center the viewport on the element if the window gets resized
  var previousElement = $("#home");
  
  // support for panning across the desktop between sections with the nav showing/hiding as appropriate
  $("a[href^=#]").click(function(event) {
    if (event.isPropagationStopped()) { return; }
    if ($(":animated").length > 0) { return false; }
    if ($(this).hasClass('selected')) { $(this).blur(); return false; } 
    
    idToScrollTo = $(this).attr('href');
    var elementToScrollTo = $(idToScrollTo);
    var navigationElement = $('#navigation');
    
    navigationElement.animate({'top':'-84px'}, function() {
      var timingData = timings[previousElement.attr('id')][elementToScrollTo.attr('id')];
      var transitionSpeed = $(timingData['transition']);
      var navigationAnimationDelay = timingData['navigation'];
      
      if (transitionSpeed.length == 2) {
        baseElement.scrollTo(elementToScrollTo, transitionSpeed[0], { 'axis': 'y', 'onAfter': function() {
            baseElement.scrollTo(elementToScrollTo, transitionSpeed[1], { 'axis': 'x' });
            selectInitialTabOfPreviousElement(elementToScrollTo);
          }
        });
      } else {
        baseElement.scrollTo(elementToScrollTo, transitionSpeed[0], { 'axis': 'yx', 'queue':true, 'onAfter': function() {
            selectInitialTabOfPreviousElement(elementToScrollTo);
          } 
        });
      }
      
      setTimeout(function() {
        // this z-Index change is to force FF2 to allow us to, y'know, work.
        navigationElement.css({ 'zIndex':75 });
        navigationElement.find('a').css({'height':''}).removeClass('selected').end().find("a[href=" + idToScrollTo + "]").addClass('selected');
        if ("#home" != idToScrollTo) { navigationElement.animate({'top':0}, 'slow'); }        
      }, navigationAnimationDelay);
    });
    
    $(this).blur();
    return false;
  });
  
  function selectInitialTabOfPreviousElement(elementToScrollTo) {
    previousElement.find(".content").tabs('select', 0);
    previousElement = elementToScrollTo;    
  }
  
  // support for animated bounce on navigation menu
  $("#navigation a").hover(
    function() {
      $(this).animate({'height': '84px'}, {'duration': 200});
    },
    function() {
      if ($(this).hasClass('selected')) { return; }
      $(this).animate({'height': '72px'}, {'duration': 200});
    }
  );
    
  // support for expand/collapse of FAQs
  $("#related_questions dt").hover(function() {
    $(this).addClass("hovered");
  }, function() {
    $(this).removeClass("hovered");
  });
  
  $("#related_questions dt").click(function() {
    var that = $(this);
    if (that.next('dd').is(':visible')) { return; }
    
    $("dt.selected").removeClass('selected');
    that.addClass("selected").siblings("dd:visible").slideUp('slow').end().next('dd').slideDown('slow').end().blur().closest('.jScrollPaneContainer').blur();
    
    setTimeout(function() { 
      that.closest('.scroll-pane').jScrollPane( { 'scrollbarWidth': 2, 'scrollbarMargin': 10 } );
    }, 500);
  });
  
  // support for only showing the label elements in the form fields when there's no text in the field
  $("#contact form input, #contact form textarea").focus(function() {
    $(this).prev("label").hide();
  }).blur(function() {
    var labelElement = $(this).prev("label")
    if ($(this).val() == '') { labelElement.show(); }
  });
  
  // support for submitting the form via ajax, bringing in the post submission HTML, and allowing that to
  // be faded out in lieu of the form again
  $('#contact_form_submit').click(function() {
      $("#contact form").ajaxSubmit({ 'beforeSubmit': function(formData, jqForm, options) {
        var isValidSubmission = true;
        $("#contact_name, #contact_email, #contact_question").each(function() {
          $(this).parent().removeClass('required').find("span").remove();
          
          if ($(this).val() == '') {
            $(this).parent().addClass('required').children('label').append("<span>, required information</span>");
            isValidSubmission = false; 
          }
        })

        return isValidSubmission;
      },
      'success': function(responseText,statusText) {
          $("#contact_form_wrapper").before(responseText).slideUp('slow', function() {
            $("#contact form").clearForm();
            $("#contact form label").show();
            $("#contact_post_submission .tinybox_close").click(function() {
              var overlay = $("#tinybox_overlay");
              $(".tinybox_content").fadeOut('slow', function() {
                overlay.fadeOut('slow');
                $(this).removeClass("tinybox_content");
                $("#related_questions_button").fadeOut('slow');

                $("#contact_post_submission").hide();
                $("#contact_form_wrapper").show();
                
              });

              return false;
            });
            
            $("#contact_post_submission").slideDown('slow');
          });
          
          $("#contact_post_submission #ask_again").click(function() {
            $("#contact_post_submission").slideUp('slow', function() {
              $("#contact_form_wrapper").slideDown('slow');
            });
            
            return false; 
          });
        } 
      });
      return false;
  });
  
  // support for heading to a specific section and tab when the 'professional evaluate' link is clicked
  $("#professional_evaluate_link").click(function() {
    $("#section_three .content").tabs('select', 1);
    return false; 
  });
  
  // this is here for IE (since the h4s are inside jscrollpanes, it has to happen after those are converted)
  Cufon.replace('h4', { 'fontFamily': 'Verlag Bold' });
});
