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

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

  /*
   * Observable subjects
   */
  this.modelInitialized     = OMVC.makeObservableSubject();
  this.catListUpdated       = OMVC.makeObservableSubject();
  this.seasListUpdated      = OMVC.makeObservableSubject();
  this.updateStarted        = OMVC.makeObservableSubject();
  this.updateCompleted      = OMVC.makeObservableSubject();
  this.filtersResetted      = OMVC.makeObservableSubject();
  this.categoryFixed        = OMVC.makeObservableSubject();

  /*
   * Properties
   */
  var seasons = [];                 // Seasons
  var categories = [];              // Categories
  var filter = {
    seasons: [],                    // Seasons
    categories: [],                 // Selected categories
    genders:    [],                 // Selected genders
    sizes:      [],                 // selected sizes
    statuses:   [],
    features:   [],
    price: {
      from:     20,
      to  :     100
    }
  };
  var zeroFilter = jQuery.extend(true, {}, filter);         // We will need it to reset filter
  var products = []                // Products found
  var fixedCategory = 0            // If category mode, then it contains category id

  /*
   * Methods
   */
  // Any initial stuff
  this.initialize = function(category, season) {
    if(category) {
      fixedCategory = category;
      filter.categories.push(category);
      that.categoryFixed.notifyObservers();
    }
    if(season) {
      filter.seasons.push(season);
    }
    that.getCategories();
    that.getSeasons();
    that.modelInitialized.notifyObservers();
    that.updateContent();
  };

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

  // Get seasons
  this.getSeasons = function() {
    jQuery.ajax({
      url: mwwoolfAjaxUrl,
      data: {action: 'getSeasons'},
      dataType: 'json',
      success: function(result) {
        seasons = result;
        that.seasListUpdated.notifyObservers();
      }
    });
  };

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

  // Update content
  this.updateContent = function() {
    that.updateStarted.notifyObservers();
    jQuery.ajax({
      url: mwwoolfAjaxUrl,
      data: {action: 'getProducts', filter: filter},
      dataType: 'json',
      success: function(result) {
        products = result;
        that.updateCompleted.notifyObservers();
      }
    });
  };

  // Reset filter
  this.resetFilter = function() {
    zeroFilter = jQuery.extend(true, {}, zeroFilter);
    that.filtersResetted.notifyObservers();
    that.updateContent();
  };

  // Update filter
  this.updateFilter = function(newFilter) {
    filter = newFilter;
    that.updateContent();
  };

};

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

  that.filterPriceMin = 20;
  that.filterPriceMax = 100;
  
  that.updateFilter = function() {
    var filter = {
      seasons:    [],
      categories: [],
      genders:    [],
      sizes:      [],
      statuses:   [],
      features:   [],
      price: {
        from:     0,
        to  :     0
      }
    };
    if(model.get('fixedCategory')) {
      filter.categories.push(model.get('fixedCategory'));
    } else {
      jQuery.each(jQuery('input[rel="category"]'), function(){
        var element = jQuery(this);
        if(element.attr('checked')) {
          filter.categories.push(element.val());
        }
      });
    }
    jQuery.each(jQuery('input[rel="season"]'), function(){
      var element = jQuery(this);
      if(element.attr('checked')) {
        filter.seasons.push(element.val());
      }
    });
    jQuery.each(jQuery('input[rel="size"]'), function(){
      var element = jQuery(this);
      if(element.attr('checked')) {
        filter.sizes.push(element.val());
      }
    });
    jQuery.each(jQuery('input[rel="gender"]'), function(){
      var element = jQuery(this);
      if(element.attr('checked')) {
        filter.genders.push(element.val());
      }
    });
    jQuery.each(jQuery('input[rel="features"]'), function(){
      var element = jQuery(this);
      if(element.attr('checked')) {
        filter.features.push(element.val());
      }
    });
    jQuery.each(jQuery('input[rel="status"]'), function(){
      var element = jQuery(this);
      if(element.attr('checked')) {
        filter.statuses.push(element.val());
      }
    });
    filter.price.from = that.filterPriceMin;
    filter.price.to = that.filterPriceMax;
    model.updateFilter(filter);
  };

  // Menu Container
  that.menuContainer = jQuery('<div/>').attr('id', 'filter-menu');

  // Result Container
  that.resultContainer = jQuery('<div/>').addClass('content');

  that.breadcrumbs = jQuery('<div/>')
      .addClass('breadcrumbs')
      .html(_('products'))
      .appendTo(that.menuContainer);

  // Filter fields renderer
  that.renderCheckbox = function(type, id, text) {
    return jQuery('<div/>')
        .append(
            jQuery('<input/>')
              .attr({
                  type: 'checkbox',
                  id: type + id,
                  rel: type,
                  value: id
                })
              .bind('click', that.updateFilter)
        )
        .append(
            jQuery('<label/>')
            .attr('for', type + id)
            .html(text)
        );
  }


  // Season filter
  that.seasonFilterContainer = jQuery('<div/>')
      .addClass('filter-criterion seasons-filter')
      .appendTo(that.menuContainer);
  jQuery('<p/>')
      .addClass('title')
      .html(_('collection_season'))
      .appendTo(that.seasonFilterContainer);

  // Category filter
  that.categoryFilterContainer = jQuery('<div/>')
      .addClass('filter-criterion categofies-filter')
      .appendTo(that.menuContainer);
  jQuery('<p/>')
      .addClass('title')
      .html(_('categories'))
      .appendTo(that.categoryFilterContainer);


  // Gender filter
  that.genderFilterContainer = jQuery('<div/>')
      .addClass('filter-criterion')
      .appendTo(that.menuContainer);
  jQuery('<p/>')
      .addClass('title')
      .html(_('gender'))
      .appendTo(that.genderFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('gender', 'f', _('women')))
      .appendTo(that.genderFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('gender', 'm', _('men')))
      .appendTo(that.genderFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('gender', 'k', _('kids')))
      .appendTo(that.genderFilterContainer);
  jQuery('<div/>').addClass('underline').appendTo(that.genderFilterContainer);


  // Size filter
  that.sizeFilterContainer = jQuery('<div/>')
      .addClass('filter-criterion')
      .appendTo(that.menuContainer);
  jQuery('<p/>')
      .addClass('title')
      .html(_('size_eu'))
      .appendTo(that.sizeFilterContainer);
  for(var i=20; i<47; i++) {
    jQuery('<div/>')
        .addClass('filter-item')
        .append(that.renderCheckbox('size', i, i))
        .appendTo(that.sizeFilterContainer);
  }
  jQuery('<div/>').addClass('underline').appendTo(that.sizeFilterContainer);


  // Status filter
  that.statusFilterContainer = jQuery('<div/>')
      .addClass('filter-criterion')
      .appendTo(that.menuContainer);
  jQuery('<p/>')
      .addClass('title')
      .html(_('status'))
      .appendTo(that.statusFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('status', 'l', 'Lager'))
      .appendTo(that.statusFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('status', 's', 'Standard'))
      .appendTo(that.statusFilterContainer);
  jQuery('<div/>').addClass('underline').appendTo(that.statusFilterContainer);

  // Features filter
  that.featuresFilterContainer = jQuery('<div/>')
      .addClass('filter-criterion features-filter')
      .appendTo(that.menuContainer);
  jQuery('<p/>')
      .addClass('title')
      .html(_('features'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'l', 'Leder'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'p', 'Powerlight'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 's', 'Softshell'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'c', 'Coolmax'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'x', 'PhylonX'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 't', 'Woolf-Tex'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'w', 'Warmfutter'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'v', 'Vibram'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'g', 'Gel-Sohle'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>')
      .addClass('filter-item')
      .append(that.renderCheckbox('features', 'm', 'Non-marking'))
      .appendTo(that.featuresFilterContainer);
  jQuery('<div/>').addClass('underline').appendTo(that.featuresFilterContainer);


  // Price filter
  that.priceFilterContainer = jQuery('<div/>')
      .addClass('filter-criterion')
      .appendTo(that.menuContainer);
  jQuery('<p/>')
      .addClass('title')
      .html(_('buy_price'))
      .appendTo(that.priceFilterContainer);
  that.slider = jQuery('<div/>')
      .attr('id', 'slider')
      .appendTo(that.priceFilterContainer)
      .slider({
        range: true,
        min: 20,
        max: 100,
        values: [ 20, 100 ],
        slide: function( event, ui ) {
          jQuery( "#amount-min" ).val( ui.values[ 0 ] + "\u20ac");
          jQuery( "#amount-max" ).val( ui.values[ 1 ] + "\u20ac");
          that.filterPriceMin = ui.values[ 0 ];
          that.filterPriceMax = ui.values[ 1 ];
          that.updateFilter();
        }
        });

  jQuery('<div/>')
      .addClass('amount')
      .appendTo(that.priceFilterContainer)
      .append(jQuery('<input/>')
          .attr({id:'amount-min', type: 'text', readonly: true})
          .val( that.slider.slider( "values", 0 ) + "\u20ac"))
      .append(jQuery('<input/>')
          .attr({id:'amount-max', type: 'text', readonly: true})
          .val( that.slider.slider( "values", 1 ) + "\u20ac"));

  // Global hiders
  that.resultHider = jQuery('<div/>')
      .addClass('loading')
      .appendTo(that.resultContainer)
      .hide();
  that.menuHider = jQuery('<div/>')
      .addClass('loading')
      .appendTo(that.menuContainer)
      .hide();
  
  // Result List container
  that.resultListContainer = jQuery('<div/>')
      .appendTo(that.resultContainer);

  // Draw product
  that.renderProduct = function(product) {
    return jQuery('<div/>')
        .addClass('product')
        .append(jQuery('<div/>')
            .addClass('image')
            .append(jQuery('<a/>')
                .attr('href', '/')
                .bind('click', function() {
                  document.location.hash = '#p' + product.uid;
                  return false;
                })
                .append(jQuery('<img/>')
                .attr('src', product.pictures[0])
                //.width('108px'))))
                .height('61px'))))
        .append(jQuery('<div/>')
            .addClass('underline'))
        .append(jQuery('<p/>')
            .html(product.article_number))
        .append(jQuery('<p/>')
            .html(product.title))
        .append(jQuery('<div/>')
            .addClass('season')
            .html(product.season));
  };



  that.menuContainer.appendTo(rootObject);
  that.resultContainer.appendTo(rootObject);



  /*
   * Listening methods
   */
  // Model initialization
  model.catListUpdated.addObserver(function () {
    that.categories = model.get('categories');
    jQuery.each(that.categories, function() {
      jQuery('<div/>')
          .addClass('filter-item')
          .append(that.renderCheckbox('category', this.uid, this.name + ' <span class="count">(' + this.count + ')</span>'))
          .appendTo(that.categoryFilterContainer);
    });
    jQuery('<div/>').addClass('underline').appendTo(that.categoryFilterContainer);
    that.menuContainer.find('input').customInput();
    // if category is fixed
    if(model.get('fixedCategory')) {
      var categoryId = model.get('fixedCategory');
      var category = {};
      jQuery.each(that.categories, function() {
        if (this.uid == categoryId) {
          category = this;
        }
      });
      jQuery('<div/>')
          .addClass('breadcrumbs')
          .append(jQuery('<a/>')
              .addClass('link-arrow-right')
              .html(_('products'))
              .attr('href', '/')
              .bind('click', function() {
                    document.location.hash = '#';
                    return false;
                  }))
          .append(jQuery('<span/>').html(' ' + category.name))
          .append(jQuery('<div/>')
              .addClass('right-align')
              .append(jQuery('<a/>')
                  .attr('href', '/')
                  .bind('click', function() {
                    document.location.hash = '#';
                    return false;
                  })
                  .html(_('see_all_products_1'))))
          .prependTo(rootObject);
       that.categoryHeader.attr('src', category.banner);
    }
  });


  model.seasListUpdated.addObserver(function () {
    that.seasons = model.get('seasons');
    var filter =  model.get('filter');
    jQuery.each(that.seasons, function() {
      jQuery('<div/>')
          .addClass('filter-item')
          .append(that.renderCheckbox('season', this.uid, this.name + ' <span class="count">(' + this.count + ')</span>'))
          .appendTo(that.seasonFilterContainer);
    });
    jQuery.each(filter.seasons, function() {
      jQuery('#season' + this).attr('checked', true);
    });
    jQuery('<div/>').addClass('underline').appendTo(that.seasonFilterContainer);
    that.menuContainer.find('input').customInput();
  });


  // Show/hide loading
  model.updateStarted.addObserver(function () {
    that.resultHider.show();
    that.menuHider.show();
  });

  model.updateCompleted.addObserver(function () {
    var products = model.get('products');
    that.resultListContainer.html('');
    jQuery(model.get('fixedCategory') ? '' : '<div/>')
        .addClass('breadcrumbs')
        .html(products.length + ' ' + _('entries'))
        .append(jQuery('<div/>')
            .addClass('right-align')
            .append(jQuery('<a/>')
                .attr('href', '/')
                .bind('click', function() {
                  model.resetFilter();
                  return false;
                })
                .html(_('delete_all_filters'))))
        .appendTo(that.resultListContainer);
    jQuery.each(products, function() {
      that.renderProduct(this).appendTo(that.resultListContainer);
    });
    that.resultHider.hide();
    that.menuHider.hide();
  });

  // Reset filter
  model.filtersResetted.addObserver(function () {
    that.menuContainer.find('input').attr('checked', false);
    that.menuContainer.find('label').removeClass('checked');
    that.updateFilter();
  });

  // Category fixation
  model.categoryFixed.addObserver(function () {
    that.categoryHeader = jQuery('<img/>')
        .width('860px')
        .appendTo(jQuery('<div/>')
            .attr('id', 'content-header')
            .prependTo(rootObject));
    that.categoryFilterContainer.hide();
    that.breadcrumbs.hide();
  });

};

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


