var app = { }

$(document).ready(function(){
  app.nav.setup();
  app.slider.setup();
  app.featurebox.setup();
  app.fancybox.setup();
  app.sidebarscroll.setup($('#search_sidebar'));
});

app.openModular = function(link){
    var newWindow=window.open(link,'window','toolbar=yes,status=no,menubar=yes,scrollbar=yes,width=1024');
    return false;
}

app.sidebarscroll = {
    setup: function(elem){
        $window = $(window);
        
        var top = $('#site').position().top - 10;    // position y - top padding
        var bottom = $('#footer').height() + 100;    // footer height + bottom padding

        $window.scroll(function(){
            var current_top = $window.scrollTop();
            if ($(document).height() < (current_top + elem.height() + bottom)){
                // console.log( 'At the bottom' );
                elem.css({'position': 'absolute', 'bottom': 0, 'top': 'auto'})
            } else if (current_top > top){
                // console.log( 'In the middle' );
                elem.css({'position': 'fixed', 'top': 20, 'bottom': 'auto'});
            } else {
                // console.log( 'At the top' );
                elem.css({'position': 'static'});
            }
        });
    }
};

app.fancybox = {
    setup: function(){
        $(".fancybox-button").fancybox({
            prevEffect      : 'none',
            nextEffect      : 'none',
            closeBtn        : false,
            helpers     : { 
                title   : { type : 'inside' },
                buttons : {}
            }
        });
    }
};

app.nav = {
  li_height: 37,
  setup: function(){
    $("#nav ul.nav_level_1>li").each(function(index, elem){
      var sub_nav = $(elem).find('li')
      ,   count = 0;
      
      if (sub_nav.length > index){
        count = index;
      } else if (sub_nav.length > 1){
        count = sub_nav.length - 1;
      }
      app.nav.ul_offset(elem, count);
      app.nav.indicator_offset(elem, count);
      
    });  
  },
  ul_offset: function(elem, count){
    var rewind = -4 - (count * app.nav.li_height);
    $(elem).find('ul.nav_level_2').css('top', rewind);
    
  },
  indicator_offset: function(elem, count){
    var rewind = - 4 - (count * app.nav.li_height);  
    $(elem).find('.indicator').css('top', 8 - rewind);
  }
}

app.slider = {
  current_offset: 0,
  cell_width: 244,
  total_slides: 0,
  slides_in_view: 4,
  timeout: false,
  box: '.feature-slider-inner',

  setup: function(){
    this.total_slides = $('.fs-item').length;
    if (this.total_slides > this.slides_in_view){
      // only set up slider if there are enough slides
      this.insertPaddingSlides().clickHandlers().hoverState().setTimeout(4000);
    }
  },

  insertPaddingSlides: function(){
    var slides = $(this.box).html()
    ,   padHTML = "<div class='slide-padding'></div>";
    $(this.box).html(slides+padHTML+slides+padHTML+slides);
    this.recenter();
    return this;
  },

  clickHandlers: function(){
    $('.scroll-right').click(function(ev){ app.slider.scrollRight() });
    $('.scroll-left').click(function(ev){ app.slider.scrollLeft() });
    return this;
  },

  hoverState: function(){
    $('#feature-slider').hover(
      function(){
        $('#feature-slider').removeClass('autoplay');
        app.slider.clearTimeout();
      },
      function(){
        $('#feature-slider').addClass('autoplay');
        app.slider.setTimeout(2000);
      }
    );
    return this;
  },

  setTimeout: function(interval){
    if (!this.timeout) {
        this.timeout = setTimeout("app.slider.autoplay()", interval)
    }
    return this;
  },

  clearTimeout: function(){
    if (this.timeout){ clearTimeout(this.timeout); this.timeout = false; }
    return this;
  },

  autoplay: function(){
    this.clearTimeout().scrollRight().setTimeout(4000);
    return this;
  },

  animate: function(){
    $(this.box).animate({'left': app.slider.left()});
    return this;
  },

  move: function(){
    // same as animate without the animation
    $(this.box).css('left', app.slider.left());
  },

  recenter: function(){
    // There are 3 copies of the slides. The default center is
    // with the middle one left aligned.
    this.current_offset = 0 - this.total_slides;
    this.move();
    return this;
  },

  scrollRight: function(){
    if ( this.current_offset <= this.left_rollover() ) this.recenter();
    this.current_offset -= 1;
    this.animate();
    return this;
  },

  scrollLeft: function(){
    if ( this.current_offset >= this.right_rollover() ) this.recenter();
    this.current_offset += 1;
    this.animate();
    return this;
  },

  left: function(){
    return (this.cell_width * this.current_offset) + 'px';
  },

  left_rollover: function(){
    return 0 - (this.total_slides * 2);
  },

  right_rollover: function(){
    return 0;
  }
}

app.featurebox = {
    boxwidth: 980,
    current_offset: 0,
    slide_count: 0,
    timeout: false,
    fadein: 2000,
    fadeout: 80,
    interval: 6000,
    indicator_prefix: 'ft-box-indicator-',
    setup: function(){
        this.slide_count = $('.feature-img-wrapper .feature-img').length;
        this.buildIndicators().clickHandler().animate().setTimeout(app.featurebox.interval);
    },
    buildIndicators: function(){
        var indicators = "";
        for (var i=0; i<this.slide_count; i++) {
            indicators += "<span id='" + this.indicator_prefix + i + "'></span>";
        }
        $('.ft-box-indicators').html(indicators);
        // center the indicators
        $('.ft-box-indicators').css(
            'margin-left',
            (0 - $('.ft-box-indicators').width() / 2)
        );        
        return this; 
    },
    clickHandler: function(){
        $('.ft-box-indicators span').click(function(ev){
            var id = $(ev.currentTarget).attr('id').substr(app.featurebox.indicator_prefix.length);
            app.featurebox.goto(id);
        });
        return this; 
    },
    autoplay: function(){
       this.clearTimeout().scrollRight().setTimeout(app.featurebox.interval);
       return this;
    },
    goto: function(id){
        this.clearTimeout();
        this.current_offset = parseInt(id);
        this.animate().setTimeout(this.interval*1.5);
        return this;
    },
    setTimeout: function(interval){
        if (!this.timeout) {
            this.timeout = setTimeout("app.featurebox.autoplay()", interval);
        }
        return this;
    },
    clearTimeout: function(){
        if (this.timeout){
            clearTimeout(this.timeout);
            this.timeout = false;
        }
        return this;
    },
    scrollRight: function(){
        this.current_offset += 1;
        if (this.current_offset >= this.slide_count){
            this.current_offset = 0;
        }
        this.animate();
        return this;
    },
    animate: function(){
        $('.feature-img-wrapper .feature-img.active').removeClass('active').animate(
            {'opacity': 0},
            app.featurebox.fadeout
        ).hide();
        
        $('.feature-img-wrapper .feature-img').each(function(index, elem){
            if (index == app.featurebox.current_offset){
                $(elem).show().animate(
                    {'opacity': 1},
                    app.featurebox.fadein
                ).addClass('active');
            }
        });
        $('.ft-box-indicators span.active').removeClass('active');
        $('.ft-box-indicators span').each(
            function(index, elem){
                if (index == app.featurebox.current_offset){
                    $(elem).addClass('active');
                }
            }
        );
        return this;
    },
    left: function(){
        return (this.boxwidth * this.current_offset) + 'px';
    }
}
