﻿(function ($) {

  function initTabs (element) {
    var container = $(element);

    function clickHandler (event) {
      var $this = $(this),
          href  = $this.attr('href'),
          li    = $this.parent('li');

      hideChildren();
      inactiveTabs();
      li.addClass('active');
      container.find(href).show();

      return false;
    }

    function hideChildren () {
      container.find('.page').hide();
    }

    function inactiveTabs () {
      container.find('ul#viewNav li.active').removeClass('active');
    }

    hideChildren();
    //inactiveTabs();
    container.find('ul#viewNav li a')
      .click(clickHandler);
	$("ul#viewNav li.active a").click();    
    //.filter(':first').click();
  }

  function initLightbox (element) {
    var link      = $(element),
        overlay   = $('#overlay'),
        lightbox  = $('.lightbox#' + link.attr('data-lightbox')),
        closeLink = lightbox.find('a.btnClose');

    function showHandler (event) {
      overlay.show();
      lightbox.show();

      return false;
    }

    function hideHandler (event) {
      overlay.hide();
      lightbox.hide();

      return false;
    }

    function formHander (event) {
      closeLink.click();
      return true;
    }

    link.click(showHandler);
    closeLink.click(hideHandler);
    overlay.click(hideHandler);
    lightbox.find('form').submit(formHander);
  }

  function initSteps (element) {
    var steps = $(element).find('li[id^=hoverstep]'),
        index = 0;

    function nextStep () {
      var step = steps.eq(index);
      index += 1;
      if (index >= steps.length) {
        index = 0;
      }
      return step;
    }

    function rotateStep () {
      steps.trigger('rotateoff');
      nextStep().trigger('rotateon');
    }

    function onRotatehandler (event) {
      $(this).fadeTo(800, 1);
    }

    function offRotatehandler (event) {
      $(this).fadeTo(800, 0);
    }

    function onHoverHandler (event) {
      clearInterval(rotator);
      steps.css('opacity', 0);

      var $this = $(this);
      $this.css('opacity', 1);
      $('#' + $this.attr('id') + '_bubble').show();
    }

    function offHoverHandler (event) {
      rotator = setInterval(rotateStep, 3000);

      var $this = $(this);
      steps.css('opacity', 0);
      $('#' + $this.attr('id') + '_bubble').hide();
    }

    steps.bind('rotateon', onRotatehandler)
      .bind('rotateoff', offRotatehandler)
      .hover(onHoverHandler, offHoverHandler);
    var rotator = setInterval(rotateStep, 3000);
  }

  $.fn.extend({
    mmlTabs : function () {
      return this.each(function () { initTabs(this); });
    },
    mmlLightbox : function () {
      return this.each(function () { initLightbox(this); });
    },
    mmlSteps : function () {
      return this.each(function () { initSteps(this); });
    }
  });

})(jQuery);

