(function ($) {
$.fn.LazyDocWrite = function(src, before, after) {
	var LazyScript  = function(elem, src, before, after) {
		this.elem   = elem;
		this.src    = src;
		this.before = before;
		this.after  = after;
		this.html   = [];
		this.next   = function() {
			var objs = $.fn.LazyDocWrite.stash;
			objs.shift();

			if (objs.length) {
				objs[0].lazy();
			}
			else {
				$.fn.LazyDocWrite.start = false;
			}
		};
		this.lazy = function() {
			var me = this;
			document._write = document.write;
			document.write = function(s){
				if(s.match(/(<script[^>]+>\s*<\/script>)/)){
					me.elem.LazyDocWrite2($(RegExp.$1).attr("src"));
				}else{
					me.html.push(s);
				}
			};

			if ('function' == typeof(me.before)) me.before(me.elem);
			me.elem.ajaxError(function(ev, req, ops, err) {
				me.next();
			});
			$.getScript(me.src, function() {
				if ('function' == typeof(me.after)) me.after(me.elem);
				document.write = document._write;
				me.elem.html(me.html.join(''));
				me.next();
			});
		};
	};

	var ours = $(this);
	var objs = $.fn.LazyDocWrite.stash;

	ours.each(function() {
		objs.push(new LazyScript($(this), src, before, after));
	});

	if (objs.length && !$.fn.LazyDocWrite.start) {
		$.fn.LazyDocWrite.start = true;
		objs[0].lazy();
	}
};

$.fn.LazyDocWrite.start = false;
$.fn.LazyDocWrite.stash = [];
}) (jQuery);

(function ($) {
$.fn.LazyDocWrite2 = function(src, before, after) {
	var LazyScript  = function(elem, src, before, after) {
		this.elem   = elem;
		this.src    = src;
		this.before = before;
		this.after  = after;
		this.html   = [];
		this.next   = function() {
			var objs = $.fn.LazyDocWrite.stash;
			objs.shift();

			if (objs.length) {
				objs[0].lazy();
			}
			else {
				$.fn.LazyDocWrite.start = false;
			}
		};
		this.lazy = function() {
			var me = this;
			document._write = document.write;
			document.write = function(s){
				if(s.match(/(<script[^>]+>\s*<\/script>)/)){
					me.elem.LazyDocWrite($(RegExp.$1).attr("src"));
				}
				me.html.push(s);
			};

			if ('function' == typeof(me.before)) me.before(me.elem);
			me.elem.ajaxError(function(ev, req, ops, err) {
				me.next();
			});
			$.getScript(me.src, function() {
				if ('function' == typeof(me.after)) me.after(me.elem);
				document.write = document._write;
				me.elem.html(me.html.join(''));
				me.next();
			});
		};
	};

	var ours = $(this);
	var objs = $.fn.LazyDocWrite.stash;

	ours.each(function() {
		objs.push(new LazyScript($(this), src, before, after));
	});

	if (objs.length && !$.fn.LazyDocWrite.start) {
		$.fn.LazyDocWrite.start = true;
		objs[0].lazy();
	}
};

$.fn.LazyDocWrite2.start = false;
$.fn.LazyDocWrite2.stash = [];
}) (jQuery);
