/** var $css = pulp.cssQuery; */
pulp.Modules.cssQuery = '$css';

(function() {
  
  var $p = pulp.base;
  
  /**
   * @class  Return an array of HTMLElements matching the given css selector
   * @param {String} selector  A css selector (css 3 supported)
   * @param {HTMLElement} [context=pulp.document]  The node from which to start looking
   * @param {Object|Array} [data]  An object on which to set matches instead of a vanilla array
   * @return {Array}  List of matched Elements
   *
   * @requires base
   */
  pulp.cssQuery = function(selector, context, data) {
    var match;
    selector = $p.trim(selector);
    if (pulp.node && (context instanceof pulp.node)) {
      context = context.raw;
    }
    if (context && context.nodeType === 1 && (match = selector.match(/^[+~>]/))) {
      selector = '#' + $p.identifyNode(context) + match[0] + selector;
      context = pulp.document;
    }
    return NW.Dom.select(selector, context, data);
  };
  // TODO: add inline docs for pertinent NW.Dom functions
  $p.extend(pulp.cssQuery, NW.Dom);
  
  if ('node' in pulp) {
    pulp.node.extendPrototype(/** @lends pulp.node# */{
      /**
       * Return an array of descendent nodes that match the given selector
       * If pulp.nodeList is available, return the results in a pulp.nodeList object
       *  
       * @param {String} selector  The CSS query to use
       * @return {Array|pulp.nodeList}
       */
      select: function(selector) {
        var results = pulp.cssQuery(selector, this.raw);
        if ('nodeList' in pulp) {
          return new pulp.nodeList(results);
        }
        return results;
      },
      /**
       * Return true if the node matches the given CSS selector
       * 
       * @param {String} selector  The CSS query to use
       * @return {Boolean}
       */
      match: function(selector) {
        return pulp.cssQuery.match(this.raw, selector);
      }
    });
  }

})();