// jQuery.include 2.0

(function($) {
	var maxRegression = 20;
	var tagName = 'span';
	var keepIncludeTags = false;
	var parse = function (domNode) {
		if (maxRegression-- < 1) return this;
		if ($(tagName +'[src]').length === 0) {
			if (!keepIncludeTags) $(tagName +'.include-loaded').unwrap();
			else $(tagName +'.include-loaded').show();
			$(document).trigger('includeReady');
			return this;
		}
		$(tagName +'[src]', domNode).each(function () {
			var inc = $(this);
			var src = inc.attr('src');
			if (src) {
				var path = src.split('/').slice(0, -1).join('/') + '/';
				$.get(src, function(data) {
					data = data.replace(/(\b(?:src|href)=")([^"]+")/g, function () {
						var s = arguments;
						if (/^http(s{0,1}):\/{2}|^\//.test(s[2])) {
							return s[1] + s[2];
						}
						return s[1] + path + s[2];
					});
					inc.html(data).addClass('include-loaded').removeAttr('src').hide();
					setTimeout(function () { parse(inc.get(0)); }, 30);
				});	
			}
		});
		return this;
	};
	$.fn.includeReady = function (observerFn) {
		$(document).bind('includeReady', function(event) {
			observerFn(event);
		});
		return this;
	};
	$.fn.unwrap = function () {
		$(this).each(function () {
			var el = $(this);
			el.replaceWith(el.contents());
		});
	};
	$(document).ready(function() {
		parse(document);
	});
})(jQuery);