/*!
 * Tabs Initializer
 * Copyright (c) 2015 Intense Visions, Inc.
 */
/* global jQuery, intenseModernizr */
var Tabs = {

  tabsWrapClass: '.effeckt-tabs-wrap',
  tabsClass: '.effeckt-tabs a.effeckt-tab',
  tabContentClass: '.effeckt-tab-content',

  isTouchDevice: intenseModernizr.touch,
  supportsOpacity: intenseModernizr.opacity,

  init: function() {

    this.initComponent();
    this.bindUIActions();

    // cludge to make sure the tab is resized if its contents get bigger/smaller
    setInterval(function() {
      Tabs.resizeTabs();
    }, 250);
  },

  initComponent: function() {

    //keep a reference to this (Tabs) object.
    var self = this;
    var $ = jQuery;

    $(this.tabsWrapClass).each(function() {
      var $el = $(this);
      var effect = $el.data('effeckt-type');
      var tabContents = $el.find(self.tabContentClass);
      var activeTabContent = tabContents.filter('.active');
      var tabs = $el.find(self.tabsClass);

      if (!activeTabContent || activeTabContent.length <= 0) {
        activeTabContent = tabContents.first();
        tabs.first().addClass('active');
        tabs.first().parent().addClass('active');
      }

      tabContents.not(activeTabContent).addClass('effeckt-hide');

      activeTabContent.addClass('effeckt-show').removeClass('effeckt-hide');
      activeTabContent.parent().css('background-color', activeTabContent.css('background-color'));

      tabContents.css('visibility', 'visible');
      tabContents.parent().height(activeTabContent.height());
      $el.removeClass('preload');

      if (!self.supportsOpacity) {
        tabContents.not(activeTabContent).hide();
      }
    });

  },

  bindUIActions: function() {

    //keep a reference to this (Tabs) object.
    var $ = jQuery;
    var self = this;

    //Add events to tab
    $(this.tabsClass).each(function() {
      var trigger = $(this).data('trigger');
      var evt = (this.isTouchDevice) ? 'touchstart click' : trigger;
      var tabs = $(this);
      var tabsWrap = tabs.parents('.effeckt-tabs-wrap');

      if (evt === 'mouseenter') {
        $(this).css('cursor', 'pointer');
        $(this).on('click', function(e) {
          e.preventDefault();
        });
      }

      $(this).on(evt, function(e) {
        e.preventDefault();
        self.showTab(this);
      });
    });

    //Add autoplay events
    $(this.tabsWrapClass + ':not(.tabs-bare) > .effeckt-tabs-container').each(function() {
      var startevt = (self.isTouchDevice) ? 'touchstart mouseenter' : 'mouseenter';
      var endevt;
      var tabs = $(this).parent().find(self.tabsClass);
      var tabsWrap = tabs.parents('.effeckt-tabs-wrap');
      var autoplay = tabsWrap.data('autoplay');
      var speed = tabsWrap.data('speed');

      if (typeof autoplay == 'undefined') {
        autoplay = false;
      } else {
        autoplay = (autoplay == '1' && !self.isTouchDevice);
      }

      if (typeof speed == 'undefined') {
        speed = 5000;
      }

      if (typeof delay == 'undefined') {
        delay = 0;
      }

      //if (startevt == 'mouseenter') {
        endevt = 'mouseleave';
      //}

      if (autoplay) {
        self.autoplayTabs(tabs);

        tabsWrap.on(startevt, function(e) {
          e.preventDefault();

          if (autoplay) {
            clearInterval(tabsWrap.data('interval'));
            clearTimeout(tabsWrap.data('timeout'));
          }
        });

        tabsWrap.on(endevt, function(e) {
          e.preventDefault();

          if (autoplay) {
            tabsWrap.data('timeout',
              setTimeout(function() {
                self.autoplayTabs(tabs);
              }, speed)
            );
          }
        });
      }
    });

    //Add bare tab events
    $(this.tabsWrapClass + '.tabs-bare > .effeckt-tabs-container').each(function() {
      var startevt = (self.isTouchDevice) ? 'touchend mouseenter' : 'mouseenter';
      var endevt;
      var tabs = $(this).parent().find(self.tabsClass);
      var tabsWrap = tabs.parents('.effeckt-tabs-wrap');
      var autoplay = tabsWrap.data('autoplay');
      var speed = tabsWrap.data('speed');
      var delay = tabsWrap.data('delay');

      if (typeof speed == 'undefined') {
        speed = 5000;
      }

      if (typeof delay == 'undefined') {
        delay = 0;
      }

      if (typeof autoplay == 'undefined') {
        autoplay = false;
      } else {
        autoplay = (autoplay == '1' && !self.isTouchDevice);
      }

      //if (startevt == 'mouseenter') {
        endevt = 'mouseleave';
      //}

      if (autoplay) {
        self.autoplayTabs(tabs);
      }

      $(this).on(startevt, function(e) {
        if (autoplay) {
          clearInterval(tabsWrap.data('interval'));
          clearTimeout(tabsWrap.data('timeout'));
        } else {
          self.autoplayTabs(tabs);
        }

        //e.preventDefault();
      });

      $(this).on(endevt, function(e) {
        e.preventDefault();

        if (autoplay) {
          tabsWrap.data('timeout',
            setTimeout(function() {
              self.autoplayTabs(tabs);
            }, speed)
          );
        } else {
          var reset = tabsWrap.data('reset');

          if (reset == '1') {
            self.showFirstTab(tabsWrap);
          }

          clearInterval(tabsWrap.data('interval'));
        }
      });
    });
  },

  autoplayTabs: function(tabs) {
    var self = this;
    var tabsWrap = tabs.parents('.effeckt-tabs-wrap');
    var speed = tabsWrap.data('speed');
    var delay = tabsWrap.data('delay');

    if (typeof speed == 'undefined') {
      speed = 5000;
    }

    if (typeof delay == 'undefined') {
      delay = 0;
    }

    setTimeout(function() {
      self.showNextTab(tabsWrap);
    }, delay);

    if (tabs.length > 1 && !self.isTouchDevice) {
      tabsWrap.data('interval',
        setInterval(function() {
          self.showNextTab(tabsWrap);
        }, speed + delay)
      );
    }
  },

  resizeTabs: function() {
    //keep a reference to this (Tabs) object.
    var self = this;
    var $ = jQuery;

    $(this.tabsWrapClass).each(function() {
      var $el = $(this);
      var tabContents = $el.find(self.tabContentClass);
      var activeTabContent = tabContents.filter('.effeckt-show');

      if (activeTabContent.height() != tabContents.parent().height()) {
        tabContents.parent().height(activeTabContent.height());
      }
    });
  },

  showTab: function(el, scrollIntoView, scrollOffset) {
    var $ = jQuery;
    var tab = $(el);
    var tabsWrap = tab.parents(this.tabsWrapClass);
    var tabs = tabsWrap.find(this.tabsClass);
    var tabContents = tabsWrap.find(this.tabContentClass);
    var effect = tabsWrap.data('effeckt-type');    

    var tabID = tab.attr('href');
    var tabContent = tabContents.filter(tabID);

    if (typeof tabID != 'undefined' && tabID[0] == '#' && tabContent.length > 0) {
      //set active to this current clicked tab
      tabs.removeClass('active');
      tabs.parent().removeClass('active');
      tab.parent().addClass('active');
      tab.addClass('active');

      tabContents.filter('.effeckt-show').removeClass('effeckt-show').removeClass('active').addClass('effeckt-hide');
      tabContent.addClass('effeckt-show').removeClass('effeckt-hide');
      tabContent.parent().css('background-color', tabContent.css('background-color'));

      if (!this.supportsOpacity) {
        tabContents.hide();
        tabContent.show();
      }

      //add parent height, just because of position: absolute;
      tabContents.parent().height(tabContent.height());

      if (scrollIntoView) {
        if (!scrollOffset) scrollOffset = 0;
        jQuery("html, body").stop().animate({
          scrollTop: tab.offset().top + scrollOffset
        }, 1000);
      }
    }
  },

  showNextTab: function(tabsWrap) {
    var $ = jQuery;    
    var tabobject = this;

    setTimeout(function() {      
      var tabs = tabsWrap.find(tabobject.tabsClass);
      var activeTab = tabsWrap.find(tabobject.tabsClass + '.active');
      var loop = tabsWrap.data('loop');

      if (activeTab.parent().next().find('a[href^=#]').length > 0) {
        tabobject.showTab(activeTab.parent().next().find('a[href^=#]'));
      } else if (loop != '0' || tabobject.isTouchDevice) {
        tabobject.showFirstTab(tabsWrap);
      }
    }, 200);    
  },

  showFirstTab: function(tabsWrap) {
    var $ = jQuery;
    var tabs = tabsWrap.find(this.tabsClass);
    var firstTab = tabsWrap.find(this.tabsClass).first();

    this.showTab(firstTab);
  }
};

jQuery(window).load(function() {
  Tabs.init();

  if (window.location.hash) {
    var tabHash = window.location.hash.replace('-', '_');
    Tabs.showTab('[href=' + tabHash + ']');
  }

  jQuery('a[href^="#"]').click(function() {
    var tabHash = jQuery(this).attr('href').replace('-', '_');
    Tabs.showTab('[href=' + tabHash + ']');
  });
});