(function ($) {
  $.fn.fcbTvStatsFilter = function (options) {
    var _that = this;

    this._buildFilter = function (type, records) {
      var NR          = _that['idx']--;
      var ID          = 'jsstatsfilter' + NR;
      var CLEAR_LABEL = 'foo' /* document['LABELS']['CLEAR_FILTER_SELECTION'] */;

      var p = {};
      p[type.toLowerCase()] = records.VALUE;

      var typeValues =
        $(document.createElement('ul')).append(
          $(document.createElement('li')).append(
            $('<a></a>')
              .html(CLEAR_LABEL)
              .click(function () {
                  return false;
              })
          )
        );

      $.each(records.VALUES, function(value, r) {
        p = {};
        p[r.TYPE.toLowerCase()] = r.VALUE;

        if (r.SELECTED) { 
          typeValues.append(
            $(document.createElement('li'))
              .addClass('Entry_1')
              .append(
                $(document.createElement('span'))
                  .html(r.LABEL)
              )
          );
        } else {
          typeValues.append(
            $(document.createElement('li'))
              .append(
                $(document.createElement('a'))
                  .attr('href', '#')
                  .html(r.LABEL)
                  .click(function () {
                      refreshStatistics(p);

                      return false;
                  })
              )
          );
        }
      });

      var jsFilterDiv = $(document.createElement('div'))
        .addClass('FilterSelection')
        .attr('id', ID)
        .css('z-index', NR)
        .bind('click', function () {
          toggle_filter('#' + ID);
        })
        .append(
          $(document.createElement('div'))
            .addClass('Handle')
            .attr('id', type)
            .append('<span id="jsFilterStatsSpan' + type + '">' + records.LABEL + '</span>')
        )
        .append(
          $(document.createElement('div'))
            .addClass('Popout')
            .append(
              $(document.createElement('div'))
                .addClass('Content') 
                .append(typeValues)
            )
            .append(
              $(document.createElement('div'))
                .addClass('Bottom')
                .html('&nbsp;')
            )
        );

      _that.append(jsFilterDiv);
    };

    return this.each(function (args) {
      $.getJSON(
        "service.php",
        {
          "cc":(args['cc'])?args['cc']:'',
          "service":"statistics",
          "method":"getFilterTree",
          "args": args
        },
        function(data) {
          _that['idx'] = 0;
          for (var x in data.result) {
            _that['idx']++ 
          } 
          $.each(data.result, _that._buildFilter);
        }
      );
    });
  }
})(jQuery);

