/*
  tabGenerator plugin for jQuery
  created by Cosmic Communication
  parameters: @separator : element which define the différent panels of content
                a header tag (h2,h3,hr) can be choosen as delimiter > a div wraps each section beginning by this tag
              @navigation : element which contains the tabs
*/

(function($) {
  $.fn.tabGenerator = function(options) {
    // Default options
    var settings = {
      separator : 'h4', // separator
      navigation: '.nav', // tab links class or id
      tabClassName: '.tabApplied',
      anchorActivate: false
    };
    if(options) $.extend(settings, options);
    function c(classSelector) { return classSelector.substr(1, classSelector.length); }  // remove the "." form the class selector
    // Element to exclude from the creation of wrapper div
    var arr = [ 'div' , 'dl' , 'ul' , 'li' ];

    $(this).addClass(c(settings.tabClassName));
    return $(this).each(function(i, elem) {
      // if object exists
      if ($(elem).length) {
        // initialize variables
        var div = false;
        var linkNavigTab = new Array();
        var idConteneur = null;
        var createWrappers = null;
        var wrapper = '';

        if (jQuery.inArray(options.separator, arr) < 0) {
          createWrappers = true
        }

        if (!options.anchorActivate)
          wrapper = '_wrapper'

        var wrapperElement = options.separator;
        /* Each elements delimited by the
         separator is wrapped by a div */

        // if element is not in the exclusion list to wrap with a div
        if (createWrappers) {
          $(elem).children().each(function(){
            if( $(this).is(options.separator) ){
              div = document.createElement("div");
              $(div).insertBefore(this);
              $(div).append(this);
              return;
            }
            if( div != false ){
              $(div).append(this);
            }
          });
          wrapperElement = 'div';
        }

        /* Id attribute of each created div */
        var parentElement = $(elem).find(wrapperElement).not(options.navigation);
        if (wrapperElement == 'li' && $(elem).find('ul').length == 2) {
          parentElement = $(elem).find('ul:eq(1)').find(wrapperElement).not(options.navigation);
        }

        parentElement.each(function(i,item) {
          var idConteneur;
          if (createWrappers) {
            idConteneur = $(this).find(options.separator).attr('id');
            $(this).attr('id',idConteneur+wrapper).addClass('panel').hide();
            idConteneur = $(this).find(options.separator).attr('id',idConteneur+'_title');
          } else {
            idConteneur = $(this).attr('id');
            $(this).attr('id',idConteneur+wrapper).addClass('panel').hide();
          }
        })

        /* If a url hash is present in the URL */

        if (window.location.hash) {
          var offsetElem = $(settings.tabClassName).offset().top
          $('html,body').animate({ scrollTop: offsetElem }, 0)
          var navigTabHash = window.location.hash; // hash variable
          if ($(elem).find(navigTabHash+wrapper).length) {
            $(elem).find(navigTabHash+wrapper).show(); // show !!!
            $(elem).find("a[href$='"+navigTabHash+"']").parent('li').addClass('active'); // give the 'active' class to the active tab
          }
          // else we show the first element
          else {
            $(elem).find('.panel:first').show(); // show !!!
            $(elem).find(options.navigation).find('li:first').addClass('active'); // give the 'active' class to the first tab
          }
        } else {
          $(elem).find('.panel:first').show();
          $(elem).find(settings.navigation).find('li:first').addClass('active');
        }

        // when the user click on a tab
        $(options.navigation).bind('click', function (e){
          var $target = $(e.target);
          if ($target.is("a[href*='#']")) {
            if ($target.parent('li').hasClass('active')) { return; }
            $(options.navigation).find("a").parent('li.active').removeClass('active'); // remove the 'active' class
            $target.parent('li').addClass('active'); // give the 'active' class to the active tab
            var hashValue = $target.attr("href"); // 'href' attribute of the clicked tab
            var lengthHref = $target.attr("href").length; // size of the url
            var checkhashValue = hashValue.lastIndexOf('#'); // search for the last # in the url
            if (checkhashValue > -1) {
              var targetHash = hashValue.substr(checkhashValue,lengthHref); // give the real hash value
              if ($(elem).find(targetHash)) {
                $(elem).find('.panel:visible').hide(); // hide the previous panel
                $(elem).find(targetHash+wrapper).fadeIn(); // show the called panel by the tab link
              }
            }
          }
        });
      }
    });
  }
})(jQuery);
