var Zone = require("can-zone");
var xhrZone = require("can-zone/xhr");

var noop = function(){};

module.exports = function(data){

	var oldSend;

	var send = function(){
		var req = global.doneSsr.request;
		var cookie = req.headers && req.headers.cookie || "";

		var waitingFunction = Zone.waitFor(noop);

		var self = this;
		this.addEventListener("load", function(){
			var setcookies = self.getResponseHeader( "Set-Cookie" );
			if ( !setcookies ) {
				waitingFunction();
				return;
			}
			if ( !Array.isArray( setcookies ) ) {
				setcookies = [ setcookies ];
			}
			for ( var i = 0; i < setcookies.length; i++ ) {
				document.cookie = setcookies[ i ];
			}
			waitingFunction();
		});

		this.addEventListener("error", function(){
			waitingFunction();
		});

		// TODO:
		// don't attach the cookies if the xhr url isn't the
		// same domain as the express req domain unless CORS

		if (cookie.length) {
			this.setDisableHeaderCheck( true );
			this.setRequestHeader( "cookie", cookie );
		}

		return oldSend.apply(this, arguments);
	};

	return {
		plugins: [xhrZone],

		beforeTask: function(){
			oldSend = XMLHttpRequest.prototype.send;
			XMLHttpRequest.prototype.send = send;
		},

		afterTask: function(){
			XMLHttpRequest.prototype.send = oldSend;
		},

		// Attach the xhr content to the end of the body
		ended: function(){
			var doc = data.document;

			if(doc) {
				var body = doc.body.getElementsByTagName("body")[0] || doc.body;
				if(data.xhr) {
					var xhrScript = doc.createElement("script");
					var xhrTN = doc.createTextNode(data.xhr.toString());
					xhrScript.appendChild(xhrTN);
					body.insertBefore(xhrScript, body.lastChild);
				}
			}
		}
	};
};

@@ -1,36 +1,4 @@
-var Zone = require(%22can-zone%22);%0A
 var 
@@ -37,34 +37,8 @@
 );%0A%0A
-var noop = function()%7B%7D;%0A%0A
 modu
@@ -209,64 +209,47 @@
 var 
-waitingFunction = Zone.waitFor(noop)
+self = this
 ;%0A
-%0A
 %09%09var 
-self
+onload
  = this
+.onload
 ;%0A%09%09
@@ -257,32 +257,16 @@
 his.
-addEventListener(%22
+on
 load
-%22,
+ =
  fun
@@ -362,34 +362,77 @@
 ) %7B%0A%09%09%09%09
-waitingFunction();
+if(onload) %7B%0A%09%09%09%09%09return onload.apply(this, arguments);%0A%09%09%09%09%7D
 %0A%09%09%09%09ret
@@ -622,105 +622,71 @@
 %0A%09%09%09
-waitingFunction();%0A%09%09%7D);%0A%0A%09%09this.addEventListener(%22error%22, function()%7B%0A%09%09%09waitingFunction();
+if(onload) %7B%0A%09%09%09%09return onload.apply(this, arguments);%0A%09%09%09%7D
 %0A%09%09%7D
-)
 ;%0A%0A%09

Use onload wrapping rather than the eventlistener