 $(document).ready(function(){

// round corners
  $('div#main div.note, div#main div.summary, div#main div.challenge, div#main div.crosslink, div#main h1, div#float h1, div#menu').corner('tl br');
  $('#navpanel .current').corner();  

// TOC controls
  $('#TOC .TOCswitch').css('display', 'inline');
  $('#TOC .subTOC').addClass('hidden');
  $('#TOC .current .TOCswitch a').each(function(){
    swap($(this));
    });  
  $('.TOCswitch a').click(function(){
    swap($(this));
    return false;
  });

// navpanel accordion
  var icons = {
    header: "ui-icon-circle-arrow-e",
    headerSelected: "ui-icon-circle-arrow-s"
  };
  var activePanel = $('#navpanel > div').index($('#TOC'));

  var navpanel = 
  $("#navpanel").accordion({
    autoHeight: false,
    navigation: false,
    collapsible: true,
    icons: icons,
    active: Math.max(activePanel, 0),
    clearStyle: true
  });

// menu
  $("ul.sf-menu").supersubs({
    minWidth:    12,   // minimum width of sub-menus in em units
    maxWidth:    27,   // maximum width of sub-menus in em units
    extraWidth:  1     // extra width can ensure lines don't sometimes turn over
    // due to slight rounding differences and font-family
  }).superfish({pathClass:  'current'});
  $('ul#nav li').hover(function() {
    $(this).addClass('sfhover');
  }, function() {
    $(this).removeClass('sfhover');
  });  
  
// dashboard control   
  if ($('#float').length) {
    var top = $('#float').offset().top - parseFloat($('#float').css('marginTop').replace(/auto/, 0));
    var navtop = $('#dashboard').offset().top;
  }  

  $(window).resize(function(event) {
    $('#float, #dashboard').css({width: $('#float').parent().width()});
    if ($('#float.fixed').length && $('#float.fixed').offset().top > $('#footer').offset().top) {
      $('div#float').css({top: '0px'});
      $('div#dashboard').css({top: '0px'});
    }
    if ($('#float').is('.out')) {
      $('#float').css({paddingLeft: 100 + $('#dashboard').position().left + 'px'});
      $('div#dashboard').css({'position': 'absolute', width: $('div#dashboard').parent().width() +'px'}).animate({ top: $('div#float.fixed').offset().top + $('#float.fixed').height()}, { queue: false, duration: 500, easing: 'easeInOutSine' });
    }
    highlightCurrent();
  });
  
  $(window).scroll(function (event) {
    // what the y position of the scroll is
    var y = $(this).scrollTop();
    // whether that's below the form
    if (y >= top) {
      // if float is fixed already
      if ($('#float').is('.fixed')) {
        // hide dashboard control on scroll
        if ($('#float').is('.out')) {
          $('#float').removeClass('out').animate({left:'-20%', marginLeft: '0px', 'paddingLeft': '0px'}, { queue: true, duration: 500, easing: 'easeInOutSine' });
        }
      }
      // fix dashboard control when scrolled down to screen top border
      else {
        $('#float').addClass('fixed').animate({width: $('div#dashboard').width(), left: '-20%'}, { queue: true, duration: 500, easing: 'easeInOutSine' }).children('h1').uncorner().corner('br').css({paddingLeft:'100px', marginLeft: '-100px'});
      }
    } else {
      // re-integrate dashboard control when page is scrolled to top
      if ($('#float').is('.fixed')) {    
        $('div#dashboard').css({'position': 'relative'}).animate({ top: '0'}, { queue: false, duration: 500, easing: 'easeInOutSine' });          
        $('#float').animate({paddingLeft: '0px', marginLeft: '0px', left:'0px'}, { queue: true, duration: 500, easing: 'easeInOutSine' }).removeClass('fixed').removeClass('out').children('h1').corner('tl').css({paddingLeft:'', marginLeft: ''});
        // highlight 1st TOC item only when full page is shown
        if ($('#TOC > .TOC:first > a').length && $('#TOC > .TOC:first > a').attr('href').match(/^#/)) {
          $('#TOC > .TOC').removeClass('current');
          $('#TOC > .TOC:first').addClass('current').corner();
        }
      }
    }
  });  
  
  $('#float.fixed').live('mouseover', function(event) {
    if (event.type == 'mouseover') {
      if (!$(this).is(':animated') ) {
        $(this).addClass('out').animate({left: '0px', marginLeft: '-100px', paddingLeft: 100 + $('#dashboard').position().left + 'px'}, { queue: true, duration: 500, easing: 'easeInOutSine' });
      }
      $('div#dashboard').css({'position': 'absolute', width: $('div#dashboard').parent().width() +'px'}).animate({ top: $(this).offset().top + $('#float.fixed').height()}, { queue: false, duration: 500, easing: 'easeInOutSine' });
      
      if ($('#TOC').length && $('#TOC > .TOC:first > a').attr('href').match(/^#/)) {
        highlightCurrent();
      }
    } else {
      if (!$(this).is(':animated') ) {
        $(this).removeClass('out').animate({left:'-20%', marginLeft: '0px', 'paddingLeft': '0px'}, { queue: true, duration: 500, easing: 'easeInOutSine' });
      }
    }
  });

  $('span.toplink a').click(function(){
    $(window).scrollTop(0);
    return false;
  });

// small page elements 
  $('a.showtarget').click(function(){
    $('#'+ $(this).attr('href').replace( /.*#(.*)/g, "$1")).toggle();
    return false;
  });
  $('.copylink').click(function(e){
    var src = $('#'+ $(this).attr('href').replace( /.*#(.*)/g, "$1"));
    var srcTxt = src.text().replace(/[\u00A0]/g, ' ').replace(/\n/g, '\n').replace(/^\s+</, '<').replace(/(\s+)</g, '\n$1<');
    $('#appFrame').contents().find('#query').val(srcTxt);
    return false;
  });

// exercises: stretch appFrame height
 if ($('div#exTabs').length) {
  $('#appFrame').height(Math.max($('#appFrame').height(), $('#footer', top.document).offset().top - $('#exTabs').offset().top - 200))
 } 
  var $tabs = $('div.exercise #exTabs').tabs({
    cache: true,
    select: function(event, ui){
      var index = $('a[href=#exSum]', $('#navpanel')).index('#navpanel > h2 > a');
      if (ui.index == 1 && $(navpanel).accordion( "option", "active" ) != index) {
        $(navpanel).accordion('activate', index);
        $('#appFrame').height(Math.max($('#appFrame').height(), $('#footer', top.document).offset().top - $('#exTabs').offset().top - 200))
      }
    }
  });
  $('div.exercise .copylink').click(function(){
    $tabs.tabs('select', 1);
  });

// images: initialise overlay
  $('a.img').colorbox({transition:"fade"});

  
// quiz //
  $('div#wrapper.test #MainDiv').each(function(){
    StartUp();
    $('div#InstructionsDiv, div#MainDiv, div#FeedbackDiv,').corner('tl br');
  });

// insert piwik tracking code dynamically (to avoid tracking of local /dev pages):
// inspired on: http://www.hardcode.nl/archives_139/article_478-insert-google-analytics-with-jquery
  if (window.location.host.match('(tbe.kantl.be|teibyexample)', 'i')) {
    var pkBaseURL = (("https:" == document.location.protocol) ? "https://kantl.be/ctb/piwik/" : "http://kantl.be/ctb/piwik/");
    $.getScript(pkBaseURL + 'piwik.js', function() {
      try {
        var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 4);
        piwikTracker.trackPageView();
        piwikTracker.enableLinkTracking();
      } catch( err ) {}
    });
  }
});
  
function swap(el) {
  var switchtext = (el.hasClass('TOCshow'))? '-': '+';
  var target = $('#' + el.attr('href').replace( /.*#(.*)/g, "$1"));

  target.toggle();
  el.text(switchtext);
  el.toggleClass('TOCshow').toggleClass('TOChide');
}

function highlightCurrent() {
  var TOC = $('#TOC > .TOC');
  TOC.removeClass('current');
  var current = TOC.each(function(){
    var test = $('#main div' + $(this).children('a').attr('href').replace(/.*(#.*)/, '$1'))
    if (test.length && Math.round(test.position().top) <= $(window).scrollTop() && (test.position().top + test.height()) > $(window).scrollTop()) {
      $(this).addClass('current');
      $(this).corner();
      return false;
    }
  });
}