jQuery(function($) {
  var curTags = {};

  $(document)
    .on('click', '#item_web .rwscript_clear', function(event) {
      $('.rwscript li.active').removeClass('active');
      curTags = {};
      update(curTags);
    })
    .on('click', '#item_web .rwscript li', function(event) {
      // get element
      var $tag = $(this);
      var tag = $tag.text();

      // check current status
      if (tag in curTags) {
        delete curTags[tag];
      }
      else {
        curTags[tag] = undefined;
      }

      update(curTags);
    });

  function update(curTags) {
    // BK: Ignore cloned elements by iCarousel.
    var $webContainer = $('[id=item_web]').eq(1);

    $webContainer.find('.results_rwscript li')
      .each(function(i, el) {
        var $tag = $(el);
        if ($tag.text() in curTags) {
          $tag.addClass('active');
        }
        else {
          $tag.removeClass('active');
        }
      });

    // filter by tag
    var $items = $webContainer.find('.results_area_list .results_area');
    $items.each(function(i, el) {
      var $item = $(el);
      var tags = {};
      $item.find('.rwscript li').each(function(i, el) {
        tags[$(el).text()] = undefined;
      });

      var matched = true;
      for (var tag in curTags) {
        if (!(tag in tags)) {
          matched = false;
          break;
        }
      }

      if (matched) {
        $item.fadeIn(function() {
          $(this).css('display', '');
        });
      }
      else {
        $item.fadeOut();
      }
    });
  }
});

