(function($){
  Drupal.behaviors.ylex = function (context) {
    //Facebook groups -block shows one group at a time. Clicking the navi link changes the shown group
    $('#ylex-facebook-groups:not(.ylex-processed)').each(function() {
      $(this).addClass('ylex-processed');
      var container = $(this);
      var content = $('#ylex-facebook-groups-content');
  
      $('#ylex-facebook-groups-navi a', container).click(function(e) {
        //Current and new groups
        var current_group_url = $('#ylex-facebook-groups-navi .active', container).attr('href');
        var current_group_url_encoded = encodeURIComponent(current_group_url);
        var clicked_group_url = $(this).attr('href');  
        var clicked_group_url_encoded = encodeURIComponent(clicked_group_url);
  
        //Change the active link at the navigation
        $('#ylex-facebook-groups-navi .active').removeClass('active');
        $('#ylex-facebook-groups-navi [href="' + clicked_group_url + '"]').addClass('active');
  
        //Get the content, replace the HTML with new one, output the content
        var html = $(content).html();
        content.addClass('loading');
        html = html.replace(current_group_url_encoded, clicked_group_url_encoded);
        content.removeClass('loading');
        content.html(html);
  
        //Prevent the link follow
        e.preventDefault();
      });
    });

    // Set information about loaded CSS and JS files.
    if (Drupal.settings.YlexQtAJAX && Drupal.quicktabs) {
      $(Drupal.settings.YlexQtAJAX.css).each(function(i, item) {
        Drupal.quicktabs.css[item] = item;
      });
    }
    if (Drupal.settings.YlexQtAJAX && Drupal.quicktabs) {
      $(Drupal.settings.YlexQtAJAX.scripts).each(function(i, item) {
        Drupal.quicktabs.scripts[item] = item;
      });
    }
  };

  $.YlexCleanId = $.YlexCleanId || {};
  $.fn.ylexCleanId = $.fn.ylexCleanId || function(id) {
    var _id = arguments.length == 1 ? id : null;
    return this.each(function(i, elem) {
      var id = $(elem).attr('id') || _id || 'ylex-clean-id'; 
      $.YlexCleanId[id] = $.YlexCleanId[id] || 0;
      $(elem).attr('id', id + ($.YlexCleanId[id] > 0 ? '-' + $.YlexCleanId[id] : ''));
      $.YlexCleanId[id] ++;
    });
  };

//delay plugin, .delay() added after 1.4 jQuery. http://james.padolsey.com/javascript/jquery-delay-plugin/
  $.fn.delay = $.fn.delay || function(time, callback){
    // Empty function:
    $.fx.step.delay = function(){};
    // Return meaningless animation, (will be added to queue)
    return this.animate({delay:1}, time, callback);
  };
})(jQuery);

