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

Object.subclass('XMLJSONPrettifier', {
});

Object.extend(XMLJSONPrettifier, {
	makePretty: function(input) {
		var output = {};

		ObjectHelper.each(input, function(key, value) {
			if ((key == 'children') && (value instanceof Array)) {
				var subs = output;
				ObjectHelper.each(value, function(ea) {
					var tagName = ea['tagName'];

					var ns = undefined;
					if (tagName.indexOf(':') >= 0) {
						ns = tagName.substring(0, tagName.indexOf(':'));
						tagName = tagName.substring(tagName.indexOf(':') + 1);
					}

					if (tagName && (tagName != 'textNode')) {
						subs[tagName] = subs[tagName] || [];
						subs[tagName].push(XMLJSONPrettifier.makePretty(ea));
					}

					if (ns)
						subs[tagName]._namespace = ns;
				});
			} else if (key.startsWith('xmlns:')) {
				output['_namespaces'] = output['_namespaces'] || {};
				output['_namespaces'][key.substr(6)] = value;
			} else if (key == 'tagName') {
				// do nothing
			} else {
				var ns;
				if (key.indexOf(':') >= 0) {
					ns = key.substring(0, key.indexOf(':'));
					key = key.substring(key.indexOf(':') + 1);
				}

				if (parseInt(value).toString() == value)
					output[key] = parseInt(value);
				else if (value == 'true')
					output[key] = true;
				else if (value == 'false')
					output[key] = false;
				else
					output[key] = value;

				if (ns)
					output[key]._namespace = ns;
			}
		});

		return output;
	}
});

Object.subclass('ObjectHelper', {
});

Object.extend(ObjectHelper, {
	each: function(obj, func) {
		if (obj instanceof Array) {
			obj.each(func);
			return;
		}

		for (var key in obj) {
			if (typeof obj[key] != 'function') {
				func(key, obj[key]);
			}
		}
	},

	select: function(obj, func, asObject) {
		if (obj instanceof Array) {
			return obj.select(func);
		}

		asObject = asObject || false;
		var res;
		if (asObject)
			res = {};
		else
			res = [];
		for (var key in obj) {
			if ((typeof obj[key] != 'function') && func(key, obj[key])) {
				if (asObject)
					res[key] = obj[key];
				else
					res.push(key);
			}
		}
		return res;
	},

	detect: function(obj, func, asObject) {
		if (obj instanceof Array) {
			return obj.detect(func);
		}

		asObject = asObject || false;
		var res = null;
		for (var key in obj) {
			if ((typeof obj[key] != 'function') && func(key, obj[key])) {
				if (asObject) {
					res = {};
					res[key] = obj[key];
				} else	
					res = key;
				break;
			}
		}
		return res;
	},
});

}) // end of module