var widgetIDs = [];

$(document).ready(function() {
  // Intro
  var scrollOffset = 250;
  var currentSection = 0;
  
  function introGoto(n) {
    $('#intro-container').stop(true).animate({scrollTop: scrollOffset * n}, {duration: 500, easing: 'easeOutExpo'});
    $('#intro-navi a').removeClass('active');
    $('#btn-intro-' + n).addClass('active');
    currentSection = parseInt(n);
  }
  
  $('#intro-navi a').not('.prev, .next').click(function() {
    introGoto($(this).attr('id').split('-')[2]);
    return false;
  });
  $('#intro-navi a.prev').click(function() {
    introGoto(currentSection == 0 ? 2 : currentSection - 1);
    return false;
  });
  $('#intro-navi a.next').click(function() {
    introGoto(currentSection == 2 ? 0 : currentSection + 1);
    return false;
  });
  
  // Widgets
  function changeWidget(widget, x, y) {
    if (widgetIDs[x][y]['src']) {
      var iframe = $(widget).find('.widget-example-content iframe');
      iframe.attr('src', widgetIDs[x][y]['src']).css({height: widgetIDs[x][y]['height']})
        .parents('div.cs-js-d, div.cs-js-f').css({height: widgetIDs[x][y]['height']});
    } else {
      $(widget).find('.widget-embed').hide();
      $(widgetIDs[x][y]['id']).show();
    }
    // Change the widget title
    $(widget).find('.widget-title').text($(widget).find('.btn-widget-' + y).attr('title'));
    // Highlight the current widget
    $(widget).find('.widget-navi a').removeClass('active');
    $(widget).find('.btn-widget-' + y).addClass('active');
  }
  
  $.each($('.widget'), function(i, widget) {
    var widgetLinks = $(widget).find('.widget-navi a').not('.next');
    widgetLinks.click(function() {
      changeWidget(widget, i, parseInt($(this).text()) - 1);
      return false;
    });
    $(widget).find('.widget-navi a.next').click(function() {
      var currentWidget = parseInt($(widget).find('.widget-navi a.active').text());
      changeWidget(widget, i, currentWidget >= widgetLinks.length ? 0 : currentWidget);
      return false;
    });
  });
});