/*******************************************************************************
 * Model
 */

OMVC.CatListModel = function () {
  var that = this;

  /*
   * Observable subjects
   */
  this.modelInitialized     = OMVC.makeObservableSubject();
  this.catListUpdated       = OMVC.makeObservableSubject();

  /*
   * Properties
   */
  var categories = [];              // Categories


  /*
   * Methods
   */
  // Any initial stuff
  this.initialize = function() {
    that.getCategories();
    that.modelInitialized.notifyObservers();
  };

  // Gt categories
  this.getCategories = function() {
    jQuery.ajax({
      url: mwwoolfAjaxUrl,
      data: {action: 'getCategories'},
      dataType: 'json',
      success: function(result) {
        categories = result;
        that.catListUpdated.notifyObservers();
      }
    });
  };

  // Getter
  this.get = function(varName) {
    return eval(varName);
  }

};

/*******************************************************************************
 * View
 */
OMVC.CatListView = function (model, rootObject) {
  var that = this;
  /*
   * HTML oblects
   */

  // ProductFinder
  that.productFinderLinkContainer = jQuery('<div/>')
      .addClass('dropdown-menu-foot');

  that.productFinderLink = jQuery('<a/>')
      .html('zum Produktfinder')
      .attr('href', jQuery('a.dropdown').attr('href'))
      .appendTo(that.productFinderLinkContainer);

  // Item renderer
  that.makeItem = function(item) {
    return jQuery('<a/>')
        .addClass('item')
        .attr('href', '/')
        .bind('click', function() {
          document.location.hash = '#c' + item.uid;
          return false;
        })
        .append(jQuery('<img/>').attr('src', item.image).width('108px'))
        .append(jQuery('<span/>')
            .addClass('title')
            .append(item.name + ' '))
            .append(jQuery('<span/>')
               .addClass('count')
               .html('(' + item.count + ')'));
  }

  /*
   * Listening methods
   */
  // Model initialization
  model.catListUpdated.addObserver(function () {
    var items = model.get('categories');
    var item;
    var counter = 0;
    var container;
    jQuery.each(items, function(){
      if(counter == 0) {
        container = jQuery('<div/>').addClass('line');
      }
      item = that.makeItem(this);
      jQuery(item).appendTo(container);
      if(counter++ == 3) {
        counter = 0;
        jQuery(rootObject).append(container);
      }
    });
    if(counter > 0) {
      jQuery(rootObject).append(container);
    }
    jQuery(rootObject).append(that.productFinderLinkContainer);
  });


};

/*******************************************************************************
 * Controller
 */
OMVC.CatListController = function (model, view) {
  model.initialize();
};






