/*jslint node:true*/
'use strict';

var cheerio = require('cheerio');
var WebcheckPlugin = require('webcheck/plugin');

var pkg = require('./package.json');

/**
 * Cheerio plugin for webcheck
 * @author Arne Schubert <atd.schubert@gmail.com>
 * @param opts
 * @augments Webcheck.Plugin
 * @constructor
 */
var CheerioPlugin = function (opts) {
    WebcheckPlugin.apply(this, arguments);

    this.middleware = function (result, next) {
        var triggered,
            $,
            error,
            cbList = [];
        if(!/html|xml/.test(result.response.headers['content-type'])) {
            return next();
        }
        /**
         * GetCheerio function added to webcheck result.
         * @param {CheerioPlugin~getCheerio} cb
         * @returns {*}
         */
        result.getCheerio = function getCheerio(cb) {
            var chunks = [];

            if ($ || error) {
                return cb(error, $);
            }
            cbList.push(cb);
            if (!triggered) {
                triggered = true;
                result.response.on('data', function (chunk) {
                    chunks.push(chunk.toString());
                });
                result.response.on('end', function () {
                    var i;
                    try {
                        $ = cheerio.load(chunks.join(''));
                    } catch (err) {
                        error = err;
                    }
                    for (i = 0; i < cbList.length; i += 1) {
                        /**
                         * @callback CheerioPlugin~getCheerio
                         * @params {null|error} error - Error if there was one
                         * @params {cheerio.load} $ - Cheerio representation of DOM
                         */
                        cbList[i](error, $);
                    }
                });
            }
        };
        next();
    };
};

CheerioPlugin.prototype = {
    __proto__: WebcheckPlugin.prototype,
    package: pkg
};

module.exports = CheerioPlugin;

@@ -246,20 +246,159 @@
  @param 
-opts
+%7B%7B%7D%7D %5Bopts%5D - Options for this plugin%0A * @param %7BRegExp%7C%7Btest:Function%7D%7D %5Bopts.filterContentType%5D - Filter content-type (defaults xml and html)
 %0A * @aug
@@ -521,16 +521,108 @@
 ents);%0A%0A
+    opts = opts %7C%7C %7B%7D;%0A%0A    opts.filterContentType = opts.filterContentType %7C%7C /html%7Cxml/;%0A%0A
     this
@@ -757,20 +757,33 @@
   if
+ 
 (!
-/html%7Cxml/
+opts.filterContentType
 .tes
@@ -2185,16 +2185,17 @@
 = %7B%0A    
+'
 __proto_
@@ -2195,16 +2195,17 @@
 _proto__
+'
 : Webche

Enhance filtering of content-type by argument