(function( $ ){

  var methods = {
    init : function( options ) {

      var settings = {
        'selectedItem'  : 0,
        'callback'      : null,
        'categories'    : null
      };

      return this.each(function(){

        if ( options ) {
          $.extend( settings, options );
        }

        var $this = $(this),
            data = $this.data('ajax_filter');

         // If the plugin hasn't been initialized yet
         if ( ! data ) {

           $this.data('ajax_filter', {
               target : $this
           });

           $this.find('li').children('a').bind('click.ajax_filter', {'settings': settings, 'filter': $this}, methods.select);

           settings.selectedItem.children('a').addClass('selected');
           settings.selectedItem.parentsUntil('.level_1').show();

         }
       });
     },
     destroy : function( ) {

       return this.each(function(){

         var $this = $(this),
             data = $this.data('ajax_filter');

         // Namespacing FTW
         $this.find('li').children('a').unbind('.ajax_filter');
         data.ajax_filter.remove();
         $this.removeData('ajax_filter');

       })

     },
    select : function(e) {
      var $this = $(this).parent('li');

      e.data.filter.find('a.selected').removeClass('selected');
      $(this).addClass('selected');
      
      if ($this.children('ul').length)
      {
        if($this.children('ul:hidden').length)
        {
          $this.siblings().find('ul').hide();
          $this.children('ul').show();
        }
        else
        {
          $this.find('ul').hide();
        }

      }

      e.data.settings.selectedItem = $this.attr('id').split('_')[1];
      
      if(e.data.settings.callback)
      {
        var category_class = '';

        if(e.data.settings.categories)
        {
          for(var i = 0; i < e.data.settings.categories.length; i++)
          {
            if ($this.hasClass(e.data.settings.categories[i]))
            {
              category_class = e.data.settings.categories[i];
              break;
            }
          }
        }
        e.data.settings.callback(e.data.settings.selectedItem, category_class);
      }
      
    },
     show : function( ) {  },
     hide : function( ) {  },
     update : function( content ) { }
  };

  $.fn.ajaxFilter = function( method ) {

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.ajaxFilter' );
    }

  };

})( jQuery );
