﻿(function ($) {
  $.fn.tabify = function (options) {
    var defaults = {
      activeIndex: 0,
      activateOnHover: true,
      returnToDefault: false,
      returnToDefaultWait: 1500
    };
    var options = $.extend(defaults, options);


    return this.each(function () {
      var $tabItems = $(this).find('.tab-menu-item');

	  if ($tabItems.length == 0)
		$tabItems = $(this).find('li');

      var $tabContentAreas = $(this).find('.tabbed_content');

      $tabItems.eq(options.activeIndex).addClass('tab-selected');
      $tabContentAreas.not(':eq(' + options.activeIndex + ')').hide();

      var _timerId;

      $(this)
        .mouseleave(function () {
          if (options.returnToDefault) {
            _timerId = Math.floor(Math.random() * 9999).toString();
            $.doTimeout(_timerId, options.returnToDefaultWait, activateDefaultTab);
          }
        })
        .mouseenter(function () {
          cancelTimer();
        });

      var activateDefaultTab = function () {
        $tabItems.removeClass('tab-selected');
        $tabItems.eq(0).click();
      }

      var cancelTimer = function () {
		try
		{
			if (options.returnToDefault)
				$.doTimeout(_timerId);
		}
		catch(exc)
		{		}
      }

      $tabItems.each(function (index) {
        $(this).bind({
          click: function () {
            cancelTimer();

            if (!$(this).hasClass('tab-selected')) {
              $tabItems.not(this).removeClass('tab-selected');
              $(this).addClass('tab-selected');

              $tabContentAreas.not(':eq(' + index + ')').hide();
              $tabContentAreas.eq(index).show();
            }
          },
          mouseenter: function () {
            cancelTimer();

            if (!$(this).hasClass('tab-selected') && options.activateOnHover) {
              $tabItems.not(this).removeClass('tab-selected');
              $(this).addClass('tab-selected');

              $tabContentAreas.not(':eq(' + index + ')').hide();
              $tabContentAreas.eq(index).show();
            }
          }
        });
      });
    });
  };
})(jQuery);
