﻿$(document).ready(function(){
    
    // begin splash slideshow scroller setup via ajax
    $.getJSON(slideshowJSONFeed, function(slideshowData) {
      
      // setup vert scroller
      $('#splashvertscroller').scrollable({
        items: '.vscrollable',
        speed: 1200,
        vertical: true,
        next: '.down',
        prev: '.up',
        keyboard: false
      });
    
      // build splash nav
      var imgCount = 0;
      var defaultSpeed = 1600;
      var nextAutoplay = '';
      if (slideshowData.section && !(slideshowData.sections)) {  slideshowData.sections = slideshowData.section; }
      $(slideshowData.sections).each(function(sindex, section){
        
        if (section.menuItem) {
          var snavitem = $('<div><\/div>').attr({'class': 'splashnavitem', 'style': 'background-color: #'+ section.menuItem.linkColor.substring(2) });
            snavitem.data('bgcolor', '#' + section.menuItem.linkColor.substring(2));
            snavitem.data('firstimg', imgCount);
          
          var snavdetails = $('<div><\/div>').attr('class', 'details').css('display', 'none');
            
          var snavdetailtext = $('<div>' + section.menuItem.linkHiddenCopy + '<\/div>').attr('class', 'detailtext');
            snavdetails.append(snavdetailtext);
          
          var snavdetaillinks = $('<div><\/div>').attr('class', 'detaillinks');
            var booklink, learnlink = '';
            if (section.menuItem.learnLink) {
              learnlink = $('<a>Learn<\/a>').attr({'class': 'learnlink', 'href': section.menuItem.learnLink });
              snavdetaillinks.append(learnlink);
            }
            if (section.menuItem.bookLink) {
              booklink = $('<a>Book<\/a>').attr({'class': 'booklink', 'href': section.menuItem.bookLink });
              if (section.menuItem.learnLink) { snavdetaillinks.append(' &middot; '); }
              snavdetaillinks.append(booklink);
            }
            snavdetails.append(snavdetaillinks);
          
          snavitem.append('<h3>' + section.menuItem.linkLabel + '<\/h3>');
          snavitem.append(snavdetails);
          
          $('.splashnav').append(snavitem);
        }
        
        // setup horizontal scroller for each nav item
        var hscrolleritems = $('<div><\/div>').attr('class', 'hscrollable');
        var hscroller = $('<div><\/div>').attr({'class': 'splashhscroller', 'id': 'splashhscroller' + sindex});
          hscroller.append(hscrolleritems);
        var hscrollerwrapper = $('<div><\/div>').attr('class', 'hscrollwrapper');
          hscrollerwrapper.append('<a class="arrow hprev">PREV<\/a> <a class="arrow hnext">NEXT<\/a>');
          hscrollerwrapper.append(hscroller);
        
        // force images to load in order
        var orderedImages = new Array();
        $(section.images).each(function(index, value){
          orderedImages[imgCount] = value;
          imgCount++;
        });
        var max = orderedImages.length;
        if (max > 0) { $.LoadImage(0, hscrolleritems, orderedImages, max, hscroller.data('scrollable'), slideshowData.pathToImages); }
        
        // add horizontal scroller to vertical
        $('#splashvertscroller .vscrollable').append(hscrollerwrapper);
       
      });

      // setup splash nav animation
      $('#splash .splashnavitem h3').click(function(e) {
        
        // expand selected panel
        if ($(this).data('state') === 'open') { 
          location.href = $(this).parent().find('.learnlink').attr('href');
          
        } else {
          $(this).data('state', 'opening');
          $(this).toggleClass('active').siblings('.details').slideDown();
          var sParent = $(this).closest('.splashnavitem');
          sParent.animate({ backgroundColor: (sParent.css('backgroundColor') == 'rgb(255, 255, 255)' ? sParent.data('bgcolor') : 'rgb(255, 255, 255)') }, 600);
          
          // close others
          $('#splash .splashnavitem h3').not(this).each(function(){ 
            $(this).data('state', 'closing');
            $(this).removeClass('active').siblings('.details').slideUp();
            var parent = $(this).closest('.splashnavitem');
            parent.animate({ backgroundColor: parent.data('bgcolor') });
            $(this).data('state', 'closed');
          });

          // scroll vertically
          verticalSeekTo($('.splashnavitem').index(sParent));
          $(this).data('state', 'open');

        }
        
      });

      // init horizontal scrollers
      $('.splashhscroller')
        .scrollable({
          items: '.hscrollable',
          speed: defaultSpeed,
          vertical: false,
          prev: '.hprev',
          next: '.hnext',
          keyboard: false,
          initialIndex: 0,
          onBeforeSeek: function(e,i) {
            var nextIndex = $('.hscrollwrapper').index(this.getItemWrap().closest('.hscrollwrapper')) + 1;
            if (i === this.getSize() - 1) {
              nextIndex = (nextIndex === slideshowData.sections.length) ? 0 : nextIndex;
              $('.splashnav .splashnavitem:eq('+nextIndex+')').find('h3').click();
              return false;
            } 
            if (i === 0) {
              this.getItemWrap().closest('.hscrollwrapper').find('.hprev').addClass('disabled');
            } else {
              this.getItemWrap().closest('.hscrollwrapper').find('.hprev').removeClass('disabled');
            }
          }
        })
        .autoscroll({
          interval: slideshowData.slideShowDelay * 1000,
          autoplay: false
        })
      ;

      // init vert scroller
      $('#splashvertscroller').scrollable({
        items: '.vscrollable',
        speed: defaultSpeed,
        vertical: true,
        keyboard: false
      });

      function verticalSeekTo(index) {
        clearTimeout(nextAutoplay);
        $('.splashhscroller').each(function(){
          $(this).children('.hscrollable').stop();
          $(this).data('scrollable').stop();
        });
        var activeapi = $('#splashhscroller'+index).data('scrollable');
        activeapi.seekTo(0,0);
        $('#splashvertscroller').data('scrollable').seekTo(index, defaultSpeed);
        nextAutoplay = setTimeout(function(){activeapi.play(); }, slideshowData.slideShowDelay * 1000);

      }

      // setup next, prev arrows
      $('#splash .hscrollwrapper .arrow').css('top', slideshowData.arrowYposition - 75).fadeTo('fast', 0.01);
      $('#splash .hscrollwrapper .arrow').hover(
        function () {
          $(this).fadeTo('default', 1);
        }, 
        function () {
          $(this).fadeTo('default', 0.01);
        }
      );


      // show start position (second image) after all loaded & setup
      $('#splash .splashnavitem:first h3').click();
      $('#splashvertscroller .vscrollable').removeClass('loading');
      $('#splashhscroller0').data('scrollable').play();

      
  }); // end splash slideshow scroller setup ajax
});

// recursive ordered image loader function
// not attached to the window object so IE does not stack overflow on r=13
jQuery.LoadImage = function(index, scroller, orderedImages, max, api, path) {
  if (index < max) {
    // If the image path is undefined skip it.
    if ( undefined == orderedImages[index] )
    {
        $.LoadImage(index+1, scroller, orderedImages, max, api, path);
        return;
    }

    var img = new Image();
    $(img)
      .load(function(){
        // add and then reset back to start position
        scroller.append(this);
        $.LoadImage(index+1, scroller, orderedImages, max, api, path);
      })
      .error(function(){
        // skip to the next image
        $.LoadImage(index+1, scroller, orderedImages, max, api, path);
      })
      .attr('src', path + orderedImages[index])
    ;
  }
};


