module('apps.OData').requires('cop.Layers').toRun(function() {

var initializeOData = function() {
	setupODataPath();
	temporaryFixLK(); // TODO: find fix and remove!
	addLibraries();
};

var setupODataPath = function() {
	Sys.loader.basePath = URL.codeBase.withFilename('odata').toString();
};

var temporaryFixLK = function() {
	delete Function.prototype.remove;
	delete lively.lang.Namespace.remove;
};

var addLibraries = function() {
	Sys.require([Sys.components.dataView, Sys.components.openDataContext, Sys.components.openDataServiceProxy]);

	// connect to loading
	connect(Sys.loader, "_loading", Global, "doODataLayering");
};

doODataLayering = function() {
	var args = $A(arguments);
	if (!args[0] || args[0] == 0) { 
		console.log('Finished loading OData dependencies... ');

		cop.create('Microsoft2LKLayer')
		.refineClass(Sys.Net.XMLHttpExecutor, {
			executeRequest: function() {
		        if (arguments.length !== 0) throw Error.parameterCount();
				var request = this.get_webRequest();
				this._webRequest = request;

				if (this._started) {
					throw Error.invalidOperation(String.format(Sys.Res.cannotCallOnceStarted, 'executeRequest'));
				}
				if (!this._webRequest) {
					throw Error.invalidOperation(Sys.Res.nullWebRequest);
				}

				var body = request.get_body();
				var headers = request.get_headers();
				var verb = request.get_httpVerb();
				var req = new WebResource(new URL(request.getResolvedUrl())); //.beAsync();

				if (headers) {
					req.setRequestHeaders(headers);
				}

				if (verb.toLowerCase() === "post") {
					if ((headers === null) || !headers['Content-Type']) {
						req.setRequestHeaders({'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'});
					}

					if (!body) {
						body = "";
					}
				}

				var timeout = request.get_timeout();
				if (timeout > 0) {
					this._timer = window.setTimeout(Function.createDelegate(this, this._onTimeout), timeout);
				}
				if (verb.toLowerCase() === "post" || verb.toLowerCase() === "put")
					req[verb.toLowerCase()](body);
				else
					req[verb.toLowerCase()]();

		        this._started = true;

				// fake XMLHttpRequest object
				this._xmlHttpRequest = { readyState: 4, status: 200, getResponseHeader: function(header) { return req.responseHeaders[header] || req.responseHeaders[header.toLowerCase()]; }, responseText: req.content, responseXML: req.contentDocument };

				this._onReadyStateChange();
			},
		});

		disconnect(Sys.loader, "_loading", Global, "doODataLayering");
	}
};

// evil but easy
(function loadODataLib() {
	JSLoader.loadJs(URL.codeBase + 'odata/Start.debug.js', initializeOData);
})();

Object.subclass('OData.Metadata', {

});

}) // end of module