
(function($){
  $.fn.kstTabs = function(options) {
    var opts = $.extend($.fn.kstTabs.defaults,options);
    var mThis = this;
    mThis.navIndex = opts.start;
    mThis.menu = opts.menu;
    mThis.menu_only_anchor = opts.menu_only_anchor;
    mThis.content = opts.content;
    mThis.duration = opts.duration;
    mThis.rotation = null;
    
    if (mThis.menu_only_anchor=='') {
      mThis.nav_handle = $(mThis.menu, mThis);
      mThis.nav = $(mThis.menu, mThis);
      var handle = 0;
    } else {
      mThis.nav_handle = $(mThis.menu_only_anchor, mThis);
      mThis.nav = $(mThis.menu, mThis);
      var handle = 1;
    }
    //console.log(handle);
    mThis.panel = $(mThis.content, mThis);

    this.nav_handle.hover(
      function(e) {
        if (handle==0) hThis = $(this); else hThis = $(this).parents('li');
        mThis.navIndex = hThis.index();
        mThis.nav.each( function(i, el) {
          $(el).removeClass('selected');
          clearTimeout(mThis.rotation);
        });
        mThis.panel.each( function(i, el) {
          if (!$(el).hasClass('hide')) {
            $(el).addClass('hide');
          }
        });
        hThis.addClass('selected');
        mThis.panel.eq(mThis.navIndex).removeClass('hide');
      }, function(e) {
          mThis.startAutoSlide();
      } 
    ); 
    
    this.panel.hover(
      function(e) {
          clearTimeout(mThis.rotation);
      }, function(e) {
          mThis.startAutoSlide();
      } 
    ); 
    
    this.nextItem = function(index) {
        mThis.nav.each( function(i, el) {
          if ($(el).hasClass('selected')) {
            $(el).removeClass('selected');
          }
        });
        mThis.panel.each( function(i, el) {
          if (!$(el).hasClass('hide')) {
            //$(el).fadeOut("slow", function (){ $(this).addClass('hide');});
            $(el).addClass('hide');
          }
        }); 
        
        mThis.nav.eq(index).addClass('selected');
        mThis.panel.eq(index).removeClass('hide')//.fadeIn("slow"); 
      this.startAutoSlide();
      //console.log(mThis.content);
    };
    
    this.startAutoSlide = function() {
      var sThis = this;
      clearTimeout(mThis.rotation);
      mThis.rotation = setTimeout(function() {
        sThis.nextItem( ++mThis.navIndex < mThis.nav.length ? mThis.navIndex : mThis.navIndex=0 );
      }, mThis.duration);
    };
    
    this.startAutoSlide(); 
    
  
  };
  $.fn.kstTabs.defaults = {
      start: 0,
      menu: 'li',
      menu_only_anchor: '',
      content: '.panel',
      duration: 3000
  }
})(jQuery);
