// Copyright © 2006 Paul Chaplin. All rights reserved. Licence to be determined.

/*
As far as I can tell, jQuery does not distinguish between CSS and XPath,
 and simply re-maps XPath expressions to its native CSS-handling code.
 However, I do not believe one may "mix and match" XPath expressions and
 CSS selectors, so it *may* be possible to enhance $() with this, but I
 think $X() is the best bet for now.
*/

/*
TO-DO:

Thoroughly check a as well as c - it seems jQuery may allow weird things 
 for a...
*/

// Alias (var $X) and 'register' the plugin... /// DELETE: "XPathNative" could always be replaced with "X" to allow less verbose use in chains: $('selector').whatever().X('xpath').etc();.
/// DELETE: var X = jQuery.fn.XPathNative = function(a, c)
var $X = jQuery.fn.X = function(a, c)
{
	if ( document.evaluate )
	{
		// If there's a context (c), can we use it with XPath?
		// Seems we can, as long as we [CHECK IT'S A VALID CONTEXT AND] check for a jQuery object and handle it correctly.
		if ( !c || (c && !c.jquery) /* I think we must also check if a is an array... */ )
		{
			// "if (a.replace)"? ...Can we chain them? a.replace().replace()...? I think so, but am unsure (of browser support, too).
			var r = a.replace;
			
			r(/:first/ig, '[0]');
			r(/:last/ig, '[last()]');
			r(/:eq\((\d+)\)/ig, '[$1]');
			r(/:lt\((\d+)\)/ig, '[position()<$1]');
			r(/:gt\((\d+)\)/ig, '[position()>$1]');
			
			// Should we use snapshots as the result type? Must look into that...
			return jQuerify(document.evaluate(a, c || document, null, 0, null));//namespaceResolver || null, resultType || 0, result || null));
		}
	}
	
	// Spit out something useful to jQuery
	function jQuerify(x)
	{
		var node, result = [];
		while ( (node = x.iterateNext()) )
		{
			result.push(node);
		}
		// Apparently, passing an array of DOM nodes into jQuery() will make it happy - neat.
		return jQuery(result);
	}
	
	// No document.evaluate, or unusable a or c: pass those along to jQuery() to handle
	//return jQuery(a, c);
	// Um, no: "Don't break the chain!"
	// ...There's no chain to break, really.
	return jQuery(a, c);
};

// Example usage:
// X('//div/p[@class]').slideUp();

