/**
 * The MIT License
 * 
 * Copyright (c) 2008 KUMAGAI Kentaro GMO Internet lab. <kentaro-kumagai*gmo.jp>
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

/*
var scraper_def =  {
	'table.ebItemlist tr.single': {
		'auctions[]': {
			'h3.ens>a': {
					description: 'TEXT',
					url: '@href'
			},
			'td.ebcPr>span': {
				price: "TEXT"
			},
			'div.ebPicture >a>img': {
				image: "@src"
			}
		}
	}
};
*/

function WebScraper(rule) {
	var VERSION = '0.0.1';
	return {
		scrape: function (context) {
			var result = {};
			for (var rowExpression in rule) {
				var keyAndAttributePairs = rule[rowExpression];
				for ( var key in keyAndAttributePairs ) {
					var attribute = keyAndAttributePairs[key];

					// determine whether exp is XPath or CSS selector by
					// evaluating it as XPath. in sccuess, it is maybe XPath.
					var exp = rowExpression;
					var isCSS = false;
					try {
						var d = (context.ownerDocument || context);
						d.createExpression(rowExpression, null);

						// most CSS selector is valid xpath expression (ex. "h3.main > img")
						// we need to find these valid xpath CSS selector expressions.

						/** TESTCODE
						 * [
						 * 	'h3 > img',
						 * 	'h3.main > img',
						 * 	'img[@src="mox.jpg"]',
						 * 	"img[@src='mox.jpg']",
						 * 	"img[@src='mox.mox.jpg']",
						 * ].map( function (x){
						 * 	return [
						 * 		x.match( /(['"]).*?\.\w+\b.*?(?=\1)/ ) ,
						 * 		x.match( /(['"]).*?[<+\->]*?(?=\1)/ ) ,
						 * 	];
						 * } );
						 **/

						// non-quoted \.\w+ is not popular syntax in XPath
						// search for it and treat them as CSS.
						if ( rowExpression.match( /\./ ) &&
								! rowExpression.match( /(['"]).*?\.\w+\b.*?(?=\1)/ ) ) {
							isCSS = true;
						} else if ( rowExpression.match( /[<+\->]/ ) &&
								! rowExpression.match( /\[.*?[<+\->]*?\]/ ) ) {
							// its rare in XPath non-quoted <a ,+, -, >.
							isCSS = true;
						}
					} catch(e) {
						isCSS = true;
					}

					// convertSelectorToXPath() returns XPath
					// that uses root node as a context node.
					// add "." to make it context aware expression.
					if ( isCSS ) {
						exp = "." + document.convertSelectorToXPath(rowExpression);
					}

					var result;
					if ( typeof attribute == 'object' ) {
						if ( key.match( /\[\]$/ ) ) {
							var r = {};
							r[key] = $X(exp, context).map( function (c) {
								return WebScraper(attribute).scrape(c);
							} );
							return r;
						} else {
							throw("this version assumes [] is always used with sub scraper definition.");
						}
					} else if (typeof attribute == 'string' ) {
						if ( attribute == 'TEXT' ) {
							exp += "//text()";
						} else if ( attribute == 'text' )  {
							throw( {msg:'"TEXT" must be writen in upper case  string attribute'} );
						} else if ( attribute.match(/^@\w+$/) )  {
							exp += "/" + attribute;
						} else {
							throw( {msg:"unknown string attribute", hint: attribute, obj: [keyAndAttributePairs,rule] } );
						}
						// Web::Scraper XPath compatibility hack.
						if ( exp.match(/^(\(?)(\/\/.+)/ ) ) {
							if ( RegExp.$1 == '' ) {
								exp = "." + exp;
							} else {
								exp = RegExp.$1 + "." + RegExp.$2;
							}
						}
						result[key] = $X(exp, context, String);
					} else {
						throw( {
							msg: "unknown attribute",
							typeOf: (typeof attribute),
							hint: attribute
						} );
					}
				}
			}
			return result;
		}
	}
}

// extend version of $X
// $X(exp);
// $X(exp, context);
// $X(exp, type);
// $X(exp, context, type);
// http://lowreal.net/blog/2007/11/17/1
function $X (exp, context, type /* want type */) {
	 //console.log(String(exp));
	if (typeof context == "function") {
		type    = context;
		context = null;
	}
	if (!context) context = document;
	var exp = (context.ownerDocument || context).createExpression(exp, function (prefix) {
		var ns = { "atom" : "http://purl.org/atom/ns#", "hatena" : "http://www.hatena.ne.jp/info/xmlns#" };
		return document.createNSResolver((context.ownerDocument == null ? context
		                                                                : context.ownerDocument).documentElement)
		               .lookupNamespaceURI(prefix) || ns[prefix] || document.documentElement.namespaceURI;
	});

	switch (type) {
		case String:
			return exp.evaluate(
				context,
				XPathResult.STRING_TYPE,
				null
			).stringValue;
		case Number:
			return exp.evaluate(
				context,
				XPathResult.NUMBER_TYPE,
				null
			).numberValue;
		case Boolean:
			return exp.evaluate(
				context,
				XPathResult.BOOLEAN_TYPE,
				null
			).booleanValue;
		case Array:
			var result = exp.evaluate(
				context,
				XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
				null
			);
			var ret = [];
			for (var i = 0, len = result.snapshotLength; i < len; ret.push(result.snapshotItem(i++)));
			return ret;
		case undefined:
			var result = exp.evaluate(context, XPathResult.ANY_TYPE, null);
			switch (result.resultType) {
				case XPathResult.STRING_TYPE : return result.stringValue;
				case XPathResult.NUMBER_TYPE : return result.numberValue;
				case XPathResult.BOOLEAN_TYPE: return result.booleanValue;
				case XPathResult.UNORDERED_NODE_ITERATOR_TYPE: {
					// not ensure the order.
					var ret = [];
					var i = null;
					while (i = result.iterateNext()) {
						ret.push(i);
					}
					return ret;
				}
			}
			return null;
		default:
			throw(TypeError("$X: specified type is not valid type."));
	}
}


//
// http://piro.sakura.ne.jp/latest/blosxom/webtech/javascript/2007-07-31_selectorjs.htm
//
/* 
対応表

!        ... サポートできないかもしれない
?        ... サポートできそうでやってない
それ以外 ... サポート済み

CSS2:
    *
    E
    E F
    E > F
    E + F
    E[foo]
    E[foo="warning"]
    E[foo~="warning"]
    E[lang|="en"]
    E.myClass
    E#myID
    E:first-child
    ?E:lang(c)
    E:first-line
    E:first-letter
    !E:before
    !E:after
    E:link
    ?E:visited
    !E:active
    !E:hover
    !E:focus
CSS3:
    E[foo^="bar"]
    E[foo$="bar"]
    E[foo*="bar"]
    E:root
    E:nth-child(n)
    E:nth-last-child(n)
    E:nth-of-type(n)
    E:nth-last-of-type(n)
    E:last-child
    E:first-of-type
    E:last-of-type
    E:only-child
    E:only-of-type
    E:empty
    E:target
    E:enabled
    E:disabled
    E:contains("foo")
    E::first-line
    E::first-letter
    ?E::selection
    !E::before
    !E::after
    E:not(s)
    E ~ F
*/

/*
NAME: selector.js[mod] - Get elements by CSS selector
Author :  |
    SHIMODA "Piro" Hiroshi <piro@p.club.ne.jp>
    http://piro.sakura.ne.jp/
Original Auther:  |
    Nyarla, <thotep@nyarla.net>
    http://nyarla.net/blog/
License: |
    This libary Copyright (c) 2006, Nyarla,
    (c) 2007, SHIMODA "Piro" Hiroshi

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
    OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
    ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
    OTHER DEALINGS IN THE SOFTWARE.
*/

/*

USAGE:

	// simple case 1
	var nodes = document.getElementsBySelector('p > em:first-of-type');
	for (var i in nodes)
		nodes[i].style.border = 'red solid 1px';

	// simple case 2
	var resolver = {
			lookupNamespaceURI : function(aPrefix) {
				switch (aPrefix)
				{
					case 'html':
						return 'http://www.w3.org/1999/xhtml';
				}
				return null;
			}
		};
	var nodes = document.getElementsBySelector('html|p:nth-child(even), html|li:nth-child(2n+1)', resolver);
	for (var i in nodes)
		nodes[i].style.background = 'blue';


	// with specificity of each selector
	var report   = '';
	var spec     = {};
	document.getElementsBySelector('p > li, #foobar ul li', null, spec);
	for (var i in spec.specificity)
	{
		report += 'selector: '+spec.specificity[i].selector+'\n'+
				'specificity: '+spec.specificity[i].value+'\n'+
				'nodes: '+spec.specificity[i].targets+'\n----\n';

		var nodes = spec.specificity[i].targets;
		for (var j in nodes)
			nodes[i].style.color = 'purple';
	}
	alert(report);
	// The sample above will show a report like:
	//
	//	selector: p > li
	//	specificity: [0, 0, 0, 2]
	//	nodes: 4
	//	----
	//	selector: #foobar ul li
	//	specificity: [0, 1, 0, 2]
	//	nodes: 5
	//	----
	//
	// What is "specificity"?
	// See: http://www.w3.org/TR/CSS21/cascade.html#specificity

*/

document.getElementsBySelector = function(aSelector, aNSResolver, aSpecificity) {
	var nodes = [];
	var count = 0;

	if (!aSelector) return nodes;

	var expression = this.convertSelectorToXPath(aSelector, aNSResolver, aSpecificity);
	if (!expression.length) return nodes;

	if (aSpecificity) {
		for (var i = 0, maxi = expression.length; i < maxi; i++)
		{
			var result = this.getNodesByXPath(expression[i], aNSResolver);
			aSpecificity.specificities[i].targets = [];
			var targetCount = 0;
			for (var j = 0, maxj = result.snapshotLength; j < maxj; j++)
			{
				aSpecificity.specificities[i].targets[targetCount++] = nodes[count++] = result.snapshotItem(j);
			}
		}
	}
	else {
		var result = this.getNodesByXPath(expression, aNSResolver);
		for (var i = 0, maxi = result.snapshotLength; i < maxi; i++)
		{
			nodes[count++] = result.snapshotItem(i);
		}
	}
	return nodes;
};

document.convertSelectorToXPath = function(aSelector, aNSResolver, aSpecificity, aInNotPseudClass) {

	// ???のドキュメントを???じりたくな???場合???、falseにすること???
	// If you don't want to modify original document, set this to false.
	var silhouettePseudElementsAndClasses = false;

//------------------------------------------------------------------------

	var makeOneExpression = false;
	if (!aSpecificity) {
		makeOneExpression = true;
		aSpecificity = {};
	}

	var self = this;
	var foundElements = [this];

	var tokens = aSelector
				.replace(/\s+/g, ' ')
				.replace(/\s*([>+])\s*/g, '$1');

	tokens = tokens.split('');

	var buf = {
		'element'     : '',
		'attributes'  : [],
		'attribute'   : '',
		'id'          : '',
		'class'       : '',
		'pseud'       : '',
		'pseuds'      : [],
		'combinators' : ' ',
		'clear'       : function () {
			this.element     = '';
			this.attributes  = [];
			this.attribute   = '';
			this.id          = '';
			this.class       = '';
			this.pseud       = '';
			this.pseuds      = [];
			this.combinators = '';
		},
		isEmpty : function() {
			return !(this.element || this.attributes.length || this.id || this.class || this.pseuds.length);
		}
	};

	var mode = 'element';

	var steps              = [];
	var stepsCount         = 0;
	var expressions        = [];
	var expressionsCount   = 0;

	var selector               = '';
	aSpecificity.id            = 0;
	aSpecificity.element       = 0;
	aSpecificity.condition     = 0;
	aSpecificity.specificities = [];
	var specificityCount       = 0;

	function evaluate(aExpression, aTargetElements, aNSResolver)
	{
		if (!aExpression) return aTargetElements;
		var found = [];
		var foundCount = 0;
		for (var i = 0, maxi = aTargetElements.length; i < maxi; i++)
		{
			var nodes = self.getNodesByXPath(aExpression, aTargetElements[i], aNSResolver);
			for (var j = 0, maxj = nodes.snapshotLength; j < maxj; j++)
			{
				found[foundCount++] = nodes.snapshotItem(j);
			}
		}
		return found;
	}

	function makeLocationStep(aStep, aConditions)
	{
		var step = aStep;
		if (aConditions.length) {
			step += '['+aConditions.join('][')+']';
		}
		return step;
	}

	function getElementsByCondition( callback, targetElements )
	{
		var elements = [];
		var elmCount = 0;
		for ( var i = 0, len = targetElements.length; i < len; i++ ) {
			var element = targetElements[i];
			if ( callback(element) > 0 ) {
				elements[elmCount++] = element;
			}
		}
		return elements;
	}

	function getFirstLetters(targetElements)
	{
		var elements = [];
		var count = 0;
		var first = self.createElement('span');
		first.setAttribute('class', '_moz-first-letter-pseud');
		for (var i = 0, len = targetElements.length; i < len; i++)
		{
			var firsts = self.getNodesByXPath('descendant::*[@class = "_moz-first-letter-pseud"]', targetElements[i], aNSResolver);
			if (firsts.snapshotLength) {
				elements[count++] = firsts.snapshotItem(0);
			}
			else {
				var text = self.getNodesByXPath('descendant::text()', targetElements[i], aNSResolver);
				var node = text.snapshotItem(0);
				node.nodeValue = node.nodeValue.replace(/^(\s*[\"\'\`\<\>\{\}\[\]\(\)\u300c\u300d\uff62\uff63\u300e\u300f\u3010\u3011\u2018\u2019\u201c\u201d\uff3b\uff3d\uff5b\uff5d\u3008\u3009\u300a\u300b\uff08\uff09\u3014\u3015]*.)/, '');
				var newFirst = first.cloneNode(true)
				node.parentNode.insertBefore(newFirst, node)
					.appendChild(self.createTextNode(RegExp.$1));
				elements[count++] = newFirst;
			}
		}
		return elements;
	}

	function getFirstLines(targetElements)
	{
		var elements = [];
		var count = 0;
		var d = self;
		var first = d.createElement('span');
		first.setAttribute('class', '_moz-first-line-pseud');
		var dummy = d.createElement('span');
		dummy.setAttribute('class', '_moz-pseud-dummy-box');
		var dummy1 = dummy.cloneNode(true);
		var dummy2 = dummy.cloneNode(true);
		var range = d.createRange();
		for (var i = 0, len = targetElements.length; i < len; i++)
		{
			var firsts = self.getNodesByXPath('descendant::*[@class = "_moz-first-line-pseud"]', targetElements[i], aNSResolver);
			if (firsts.snapshotLength) {
				elements[count++] = firsts.snapshotItem(0);
			}
			else {
				var text = self.getNodesByXPath('descendant::text()', targetElements[i], aNSResolver);
				var lineEnd = false;
				for (var j = 0, maxj = text.snapshotLength; j < maxj; j++)
				{
					var node = text.snapshotItem(j);
					var parent = node.parentNode;
					var firstPart = first.cloneNode(true);
					firstPart.appendChild(d.createTextNode(''));
					parent.insertBefore(dummy1, node);
					var y = dummy1.offsetTop;
					for (var k = 0, maxk = node.nodeValue.length; k < maxk; k++)
					{
						range.selectNodeContents(parent);
						range.setStart(dummy1.nextSibling, k);
						range.collapse(true);
						range.insertNode(dummy2);
						range.setStartBefore(parent.firstChild);
						if (dummy2.offsetTop != y) {
							firstPart.firstChild.nodeValue = firstPart.firstChild.nodeValue.substring(0, firstPart.firstChild.nodeValue.length-1);
							parent.removeChild(dummy2);
							parent.normalize();
							lineEnd = true;
							break;
						}
						firstPart.firstChild.nodeValue += parent.textContent.charAt(k);
						parent.removeChild(dummy2);
						parent.normalize();
					}
					parent.removeChild(dummy1);
					if (firstPart.firstChild.nodeValue.length &&
						!/^\s*$/.test(firstPart.firstChild.nodeValue)) {
						range.selectNodeContents(parent);
						range.insertNode(firstPart);
						range.selectNodeContents(parent);
						range.setStartAfter(firstPart);
						range.setEnd(firstPart.nextSibling, firstPart.firstChild.nodeValue.length);
						range.deleteContents();
						elements[count++] = firstPart;
					}
					if (lineEnd) break;
				}
			}
		}
		range.detach();
		return elements;
	}

	function search(aEndOfPath)
	{
		if (!buf.isEmpty()) {
			aSpecificity.element++;

			var con       = [];
			var conCount  = 0;

			var stepNamePart = '';
			var tagName      = ((buf.element || '').replace(/^(\w+|\*)\|/, '') || '*');
			var ns           = (buf.element || '').match(/^(\w+|\*)\|/) ? RegExp.$1 : '' ;
			if (ns && ns != '*') {
				stepNamePart = ns+':'+tagName;
			}
			else if (tagName != '*') {
				stepNamePart = '*[local-name() = "'+tagName+'" or local-name() = "'+tagName.toUpperCase()+'"]';
			}
			else {
				stepNamePart = '*';
			}

			var step =
				buf.combinators == '>' ? stepNamePart :
				buf.combinators == '+' ? 'following-sibling::*[1][local-name() = "'+tagName+'" or local-name() = "'+tagName.toUpperCase()+'"]' :
				buf.combinators == '~' ? 'following-sibling::'+stepNamePart :
				'descendant::'+stepNamePart ;

			if (buf.id.length) {
				con[conCount++] = '@id = "'+buf.id+'"';
				aSpecificity.id++;
			}

			if (buf.class.length) {
				var classes = buf.class.split('.').map(function(aItem) {
						return 'contains(concat(" ",@class," "), " '+aItem+' ")'
					});
				con[conCount++] = classes.join(' and ');
				aSpecificity.condition += classes.length;
			}

			var attributes = buf.attributes;
			if (attributes.length) {
				for (var i = 0, attr_len = attributes.length; i < attr_len; i++)
				{
					var attribute = attributes[i];
					/^(\w+)\s*(?:([~\|\^\$\*]?=)\s*["]?(.+?)["]?)?$/.test(attribute);
					var attrName  = RegExp.$1;
					var operator  = RegExp.$2;
					var attrValue = RegExp.$3;
					attributes[i] =
						operator == '=' ? '@'+attrName+' = "'+attrValue+'"' :
						operator == '~=' ? 'contains(concat(" ",@'+attrName+'," "), " '+attrValue+' " )' :
						operator == '|=' ? '@'+attrName+' = "'+attrValue+'" or starts-with(@'+attrName+', "'+attrValue+'-")' :
						operator == '^=' ? 'starts-with(@'+attrName+', "'+attrValue+'" )' :
						operator == '$=' ? 'substring(@'+attrName+', string-length(@'+attrName+') - string-length("'+attrValue+'") + 1) = "'+attrValue+'"' :
						operator == '*=' ? 'contains(@'+attrName+', "'+attrValue+'" )' :
							'@'+attrName;
				}
				con[conCount++] = attributes.length > 1 ? '('+attributes.join(') and (')+')' : attributes[0] ;
				aSpecificity.condition += attributes.length;
			}

			var pseuds = buf.pseuds;
			pseudRoop:
			for (var i = 0, maxi = pseuds.length; i < maxi; i++)
			{
				var pseud = pseuds[i];
				if (!pseud) continue;
				var pseudEvaluated = true;
				aSpecificity.condition++;
				switch (pseud)
				{
					case 'first-child':
						con[conCount++] = 'not(preceding-sibling::*)';
						break;
					case 'last-child':
						con[conCount++] = 'not(following-sibling::*)';
						break;
					case 'first-of-type':
						con[conCount++] = 'not(preceding-sibling::'+stepNamePart+')';
					case 'last-of-type':
						con[conCount++] = 'not(following-sibling::'+stepNamePart+')';
						break;
					case 'only-child':
						con[conCount++] = 'count(parent::*/child::*) = 1';
						break;
					case 'only-of-type':
						con[conCount++] = 'count(parent::*/child::'+stepNamePart+') = 1';	
						break;
					case 'empty':
						con[conCount++] = 'not(*) and not(text())';
						break;
					case 'link':
						con[conCount++] = '@href and contains(" link LINK a A area AREA ", concat(" ",local-name()," "))';
						break;
					case 'enabled':
						con[conCount++] = '(@enabled and (@enabled = "true" or @enabled = "enabled" or @enabled != "false")) or (@disabled and (@disabled = "false" or @disabled != "disabled"))';
						break;
					case 'disabled':
						con[conCount++] = '(@enabled and (@enabled = "false" or @enabled != "enabled")) or (@disabled and (@disabled = "true" or @disabled = "disabled" or @disabled != "false"))';
						break;
					case 'checked':
						con[conCount++] = '(@checked and (@checked = "true" or @checked = "checked" or @checked != "false")) or (@selected and (@selected = "true" or @selected = "selected" or @selected != "false"))';
						break;
					case 'indeterminate':
						con[conCount++] = '(@checked and (@checked = "false" or @checked != "checked")) or (@selected and (@selected = "false" or @selected != "selected"))';
						break;
					case 'root':
						con[conCount++] = 'not(parent::*)';
						break;
					default:
						var axis = /^nth-last-/.test(pseud) ? 'following-sibling' : 'preceding-sibling' ;
						var condition = /^nth-(last-)?of-type/.test(pseud) ? stepNamePart : '*' ;

						if (/not\(\s*(.+)\s*\)$/.test(pseud)) {
							var spec = {};
							con[conCount++] = 'not('+self.convertSelectorToXPath(RegExp.$1, aNSResolver, spec, true)+')';
							aSpecificity.id        += spec.id;
							aSpecificity.element   += spec.element;
							aSpecificity.condition += spec.condition;
							aSpecificity.condition--;
						}

						else if (/nth-(last-)?(child|of-type)\(\s*([0-9]+)\s*\)/.test(pseud)) {
							con[conCount++] = 'count('+axis+'::'+condition+') = '+(parseInt(RegExp.$3)-1);
						}
						else if (/nth-(last-)?(child|of-type)\(\s*([0-9]+)n\s*(([\+\-])\s*([0-9]+)\s*)?\)/.test(pseud)) {
							con[conCount++] = '(count('+axis+'::'+condition+')'+(RegExp.$6 ? ' '+RegExp.$5+' '+RegExp.$6 : '' )+') mod '+RegExp.$3+' = 1';
						}
						else if (/nth-(last-)?(child|of-type)\(\s*(odd|even)\s*\)/.test(pseud)) {
							con[conCount++] = 'count('+axis+'::'+condition+') mod 2 = '+(RegExp.$3 == 'even' ? '1' : '0' );
						}

						else if (/contains\(\s*["'](.+)["']\s*\)/.test(pseud)) {
							con[conCount++] = 'contains(descendant::text(), "'+RegExp.$1+'")';
						}

						else {
							aSpecificity.condition--;
							pseudEvaluated = false;
						}
						break;
				}
				if (!pseudEvaluated) {
					foundElements = evaluate(steps.join('/')+'/'+makeLocationStep(step, con), foundElements);
					switch (pseud)
					{
/*
						case 'visited':
							if (silhouettePseudElementsAndClasses) {
								var history = Components.classes['@mozilla.org/browser/global-history;2'].getService(Components.interfaces.nsIGlobalHistory2);
								foundElements = getElementsByCondition(function(aNode) {
									var uri = aNode.href || aNode.getAttribute('href');
									var isLink = /^(link|a|area)$/i.test(aNode.localName) && uri;
									var isVisited = false;
									if (isLink) {
										try {
											isVisited = history.isVisited(self.makeURIFromSpec(uri));
										}
										catch(e) {
											dump(uri+' / '+self.makeURIFromSpec(uri));
											dump(e+'\n');
										}
										if (isVisited) aNode.setAttribute('_moz-pseud-class-visited', true);
									}
									return isLink && isVisited ? 1 : -1 ;
								}, foundElements);
								con[conCount++] = '@_moz-pseud-class-visited = "true"';
								aSpecificity.condition++;
								break;
							}
*/

						case 'target':
							if (silhouettePseudElementsAndClasses) {
								foundElements = getElementsByCondition(function(aNode) {
									(/#(.+)$/).test(aTargetDocument.defaultView.location.href);
									var isTarget = RegExp.$1 && aNode.getAttribute('id') == decodeURIComponent(RegExp.$1);
									if (isTarget) aNode.setAttribute('_moz-pseud-class-target', true);
									return isTarget ? 1 : -1 ;
								}, foundElements);
								con[conCount++] = '@_moz-pseud-class-target = "true"';
								aSpecificity.condition++;
								break;
							}

/*
						case 'hover':
						case 'focus':
						case 'active':
							if (silhouettePseudElementsAndClasses) {
								foundElements = getElementsByCondition(function(aNode) {
									aNode.setAttribute(''+pseud, true);
									return 1;
								}, foundElements);
								aSpecificity.condition++;
								break;
							}
*/

						case 'first-letter':
							if (silhouettePseudElementsAndClasses) {
								steps[stepsCount++] = makeLocationStep(step, con);
								foundElements = getFirstLetters(foundElements);
								steps[stepsCount++] = 'descendant::*[@class = "_moz-first-letter-pseud"]';
								step = null;
								break;
							}

						case 'first-line':
							if (silhouettePseudElementsAndClasses) {
								steps[stepsCount++] = makeLocationStep(step, con);
								foundElements = getFirstLines(foundElements);
								steps[stepsCount++] = 'descendant::*[@class = "_moz-first-line-pseud"]';
								step = null;
								break;
							}

						default:
							aSpecificity.id        = 0;
							aSpecificity.element   = 0;
							aSpecificity.condition = 0;
							step       = '';
							con        = [];
							conCount   = 0;
							steps      = [];
							stepsCount = 0;
							foundElements = [aTargetDocument];
							break pseudRoop;
					}
				}
			}

			if (step) steps[stepsCount++] = makeLocationStep(step, con);
		}
		buf.clear();

		if (aEndOfPath) {
			if (stepsCount && aInNotPseudClass) {
				steps.reverse();
				var isFirst = true;
				for (var i = 0, maxi = steps.length; i < maxi; i++)
				{
					if (isFirst) {
						steps[i] = steps[i]
									.replace(/^[^:\*]*(::)?/, 'self::');
						isFirst = false;
					}
					else {
						steps[i] = steps[i]
									.replace(/^([^:\*]*(::?)|child::)/, 'parent::')
									.replace(/^descendant/, 'ancestor');
					}
				}
			}
			if (stepsCount) {
				expressions[expressionsCount++] = (aInNotPseudClass ? '' : '/' ) + steps.join('/');
				aSpecificity.specificities[specificityCount++] = {
					selector : selector,
					value    : [
						0,
						aSpecificity.id || 0,
						aSpecificity.condition || 0,
						aSpecificity.element || 0
					]
				};
				aSpecificity.id        = 0;
				aSpecificity.element   = 0;
				aSpecificity.condition = 0;
			}

			steps      = [];
			stepsCount = 0;
			selector   = '';
		}
	};

	var escaped    = false;
	var parenLevel = 0;
	for ( var i = 0, len = tokens.length; i < len; i++  )
	{
		var token = tokens[i];
		selector += token;

		if (escaped) {
			buf[mode] += token;
			escaped = false;
			continue;
		}
		else if (token == '\\') {
			escaped = true;
			continue;
		}
		else if (parenLevel && token != ')') {
			if (token == '(')  parenLevel++;
			buf[mode] += token;
			continue;
		}
		else if (mode == 'attribute' && token != ']') {
			buf[mode] += token;
			continue;
		}
		switch (token)
		{
			// selector
			case '[':
				if (mode == 'pseud' && !parenLevel) {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				mode = 'attribute';
				break;
			case ']':
				buf.attributes.push(buf.attribute);
				buf.attribute = '';
				mode = 'element';
				break;
			case '.':
				if (mode == 'pseud' && !parenLevel) {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				else if (mode == 'class') {
					buf[mode] += token;
				}
				mode = 'class';
				break;
			case '#':
				if (mode == 'pseud' && !parenLevel) {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				mode = 'id';
				break;

			case ':':
				if (mode == 'pseud' && !parenLevel) {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				mode = 'pseud';
				break;
			case '(':
				if (mode == 'pseud') {
					parenLevel++;
				}
				buf[mode] += token;
				break;
			case ')':
				buf[mode] += token;
				if (mode == 'pseud') {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				if (parenLevel) {
					parenLevel--;
					if (!parenLevel) mode = 'element';
				}
				break;

			// combinators
			case ' ':
			case '>':
			case '+':
			case '~':
				if (mode == 'pseud' && !parenLevel) {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				search();
				buf.combinators = token;
				mode = 'element';
				break;

			// elements
			case '*':
				if (mode == 'pseud' && !parenLevel) {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				else {
					buf.element = '*';
				}
				break;

			case ',':
				if (mode == 'pseud' && !parenLevel) {
					buf.pseuds.push(buf.pseud);
					buf.pseud = '';
				}
				selector = selector.replace(/,$/, '');
				search(true);
				buf.combinators = ' ';
				foundElements = [self]
				mode = 'element';
				break;

			// default
			default :
				buf[mode] += token;
				break;

		}
		if (!foundElements.length) {
			return makeOneExpression ? expressions.join(' | ') : expressions ;
		}
	}
	if (mode == 'pseud' && !parenLevel) {
		buf.pseuds.push(buf.pseud);
		buf.pseud = '';
	}
	search(true);

	return makeOneExpression ? expressions.join(' | ') : expressions ;
};

document.getNodesByXPath = function(aExpression, aContext, aNSResolver, aLive) 
{
	var aContext = aContext || this;
	var type = aLive ? XPathResult.ORDERED_NODE_ITERATOR_TYPE : XPathResult.ORDERED_NODE_SNAPSHOT_TYPE ;
	var nodes;
	try {
		nodes = this.evaluate(aExpression, aContext, (aNSResolver || null), type, null);
	}
	catch(e) {
	}
	return nodes;
};

var $S = function () {
    if ( arguments.length == 1 ) {
        return document.getElementsBySelector(arguments[0]);
    }
    else {
        var results  = [];
        var resCount = 0;
        for ( var i = 0, len = arguments.length; i < len; i++ ) {
            results[resCount++] = document.getElementsBySelector(arguments[i]);
        }
        return results;
    }
}

1;
