var faqHeight = 0; // total height of all 6 faq elements
var currentlyVisible = -1; // the faq id that is currently opened, -1 if none

function openFaq(faqNum) {
  var faqTop = 0; // the y position to slide the container to
  
  if(currentlyVisible == faqNum) {
    // this faq item opened, lets follow the link
    return true;
  } else if(currentlyVisible != -1) {
    // another faq item clicked, lets close this one and open the new one after that
    closeFaq(currentlyVisible, faqNum);
    return false;
  }
  
  // check the height of one faq item
  if(!faqHeight) faqHeight = document.getElementById("faqItem0").clientHeight;
  
  // set the currently visible faq item
  currentlyVisible = faqNum;
  
  // calculate the y position
  for(var i=0; i<faqNum; i++) {
    if(i==4) break;
    faqTop += document.getElementById("faqItem"+faqNum).clientHeight;
  }
  
  // set container height
  $("#faq .inner").css("height",6*faqHeight+62+"px");
  $("#faqItems").css("height",6*faqHeight+"px");
  
  // change link class
  $("#faqItem"+faqNum+" a").addClass("noArrow");
  
  // animate the container to required y position
  $("#faqAnimation").animate({"marginTop": -faqTop+"px"}, "fast", "swing", function() {
    // increase faq item height
    $("#faqItem"+faqNum).animate({"height": 5*faqHeight+"px"}, "fast", "swing", function() {
      // fade in the faq content and close button
      $("#faqItem"+faqNum+" p").fadeIn("fast");
      $("#faqItem"+faqNum+" .closeFaq").fadeIn("fast");
      
    });
  });
  
  return false;
}

function closeFaq(faqNum, openThis) {

  var faqTop = 0;

  // fade out the content and close button
  $("#faqItem"+faqNum+" p").fadeOut("fast");
  $("#faqItem"+faqNum+" .closeFaq").fadeOut("fast");
  
  var slideTo = "0px";
  
  // animate the faq item height
  $("#faqItem"+faqNum).animate({"height": faqHeight+"px"}, "fast", "swing", function() {
    // change link class
    $("#faqItem"+faqNum+" a").removeClass("noArrow");
    
    // if another element was clicked, calculate the new y position to slide to
    if(openThis != -1) {
      for(var i=0; i<faqNum; i++) {
        if(i==4) break;
        faqTop += document.getElementById("faqItem"+faqNum).clientHeight;
      }
      slideTo = -faqTop+"px";
    }
    
    // animate the container to new y position
    $("#faqAnimation").animate({"marginTop": slideTo}, "fast", "swing", function() {
      if(openThis != -1) {
        openFaq(openThis);
      }
    });  
  });
  
  // every faq item is closed now
  currentlyVisible = -1;
  
  return false;
}

