var tools = {};

tools.xhrTimeout = 50000;
tools.uniqId = 0;

tools.generatePassword = function (length)
{
	var chars = new String("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890@!$#+=?()[]{}");
	var pass = "";

	for (x = 0; x < length; x++) {
		i = Math.floor(Math.random() * chars.length);
		pass += chars.charAt(i);
	}

	return pass;
}

tools.toggleButtonText = function (toggleButton)
{	
	var domNode = toggleButton.domNode;
	var value = toggleButton.attr('checked');
	
	dojo.query('.checked', domNode).style({'display' : (value ? 'inline' : 'none')});
	dojo.query('.unchecked', domNode).style({'display' : (!value ? 'inline' : 'none')});
}

tools.createInstance = function (ns)
{
	return ns + tools.uniqId++;
}

tools.disableDijitTree = function (from, disabled)
{
	var nodes = dojo.query('[widgetId]', from);
	nodes = nodes.concat(dojo.query('[widgetId]', from));

	nodes.forEach( function (node)
	{
		var widget = dijit.byNode(node);

		if (widget)
			widget.setAttribute("disabled", disabled);
	});

};

tools.canonicalize = function (name)
{
	var digestName = name;
	digestName = digestName.replace(/([a-z0-9])([A-Z])/g, function (x, g1, g2)
	{
		return g1 + "_" + g2;
	});
	digestName = digestName.replace(/[- ]+$/, " ");
	digestName = digestName.toLowerCase();

	return digestName;
};

tools.addURLParameter = function (url, name, value)
{
	var re = new RegExp("([?&])" + name + "=[^?&]*");

	if (url.search(re) != -1) {
		return url.replace(re, "$1" + name + "=" + value);
	} else if (url.charAt(url.length - 1) == '?')
		return url + name + "=" + value;
	else {
		if (url.search(/\?[^=]+=.*/) != -1)
			return url + "&" + name + "=" + value;
		else
			return url + "?" + name + "=" + value;
	}
};

tools.getHtmlVar = function (id)
{
	var v = dojo.byId(id);

	if (v != null)
		return v.getAttribute("value");
	else {
		console.error("html_var '" + id + "' is not defined");

		return null;
	}
};

tools.destroyDijitWidgets = function (node)
{
	try {
		var nodes = dojo.query('[widgetid]', node);
		nodes = nodes.concat(dojo.query('[widgetId]', node));

		nodes.forEach( function (node)
		{
			var widget = dijit.byNode(node);

			if (widget)
				widget.destroyRecursive();
		});
	} catch (error) {
		console.warn(error);
	}
};

tools.display = function (node, display)
{
	if (display == null)
		display = true;

	var classes = node.className.split(" ");

	for ( var i = 0; i < classes.length; i++) {
		var found = false;
		if (classes[i] == 'display') {
			found = true;
			if (!display)
				classes[i] = 'undisplay';
		} else if (classes[i] == 'undisplay') {
			found = true;
			if (display)
				classes[i] = 'display';
		}
	}

	if (!found) {
		if (display)
			classes.push("display");
		else
			classes.push("undisplay");
	}

	node.className = classes.join(" ");
};

tools.parseJs = function (response)
{
	if (dojo.isIE) {
		var ScriptFragment = '(?:<script.*?>)((\n|.)*?)(?:</script>)';

		var match = new RegExp(ScriptFragment, 'img');
		var scripts = response.match(match);

		if (scripts) {
			var js = '';
			for ( var s = 0; s < scripts.length; s++) {
				var match2 = new RegExp(ScriptFragment, 'im');
				js += scripts[s].match(match2)[1];
			}
			eval(js);
		}
	} else {
		node = document.createElement('div');
		node.innerHTML = response;

		dojo.query("script", node).forEach( function (script)
		{
			eval(script.innerHTML);
		});
	}
};

tools.xhrGet = function (url, options)
{

	dojo.xhrGet( {
		url : url,
		handleAs : "text",
		content : options.parameters,
		timeout : tools.xhrTimeout,
		load : function (response, ioArgs)
		{
			if (options.parseDijit != null)
				tools.destroyDijitWidgets(options.parseDijit);

			if (options.onLoad != null) {
				options.onLoad(response, ioArgs);
			}

			if (options.parseDijit != null)
				dojo.parser.parse(options.parseDijit);

			if (options.parseJs)
				tools.parseJs(response);

			return response;
		},
		error : function (response, ioArgs)
		{
			if (response.status == 500) {
				var errorMessage = ioArgs.xhr.statusText;

				console.error("HTTP status code: " + ioArgs.xhr.status + " " + errorMessage);
			} else
				console.error("HTTP status code: " + ioArgs.xhr.status + " " + response.message);

			if (options.onError != null) {
				options.onError(response, ioArgs);
			}

			return response;
		}
	});
};

tools.xhrPost = function (url, options)
{
	dojo.xhrPost( {
		url : url,
		handleAs : "text",
		form : options.form,
		content : options.parameters,
		timeout : tools.xhrTimeout,
		load : function (response, ioArgs)
		{
			if (options.parseDijit != null)
				tools.destroyDijitWidgets(options.parseDijit);

			if (options.onLoad != null) {
				options.onLoad(response, ioArgs);
			}

			if (options.parseDijit != null)
				dojo.parser.parse(options.parseDijit);

			if (options.parseJs)
				tools.parseJs(response);

			return response;
		},
		error : function (response, ioArgs)
		{
			if (response.status == 500) {
				var errorMessage = ioArgs.xhr.statusText;

				console.error("HTTP status code: " + ioArgs.xhr.status + " " + errorMessage);
			} else
				console.error("HTTP status code: " + ioArgs.xhr.status + " " + response.message);

			if (options.onError != null) {
				options.onError(response, ioArgs);
			}

			return response;
		}
	});
};

tools.mouseOverClass = function (elt)
{
	elt.currentClassName = elt.className;
	elt.className = elt.className + " hover";
};

tools.mouseOutClass = function (elt)
{
	elt.className = elt.currentClassName;
};

/* IE ne gère pas !
tools.registerCss = function (hookId, css)
{
	var styleNode = dojo.byId(hookId);

	if (styleNode != null)
		styleNode.innerHTML = styleNode.innerHTML + '\n' + '@import url("' + css + '");';
	else
		console.warning('Module CSS Hook not found (id=\'' + hookId + '\')');
};

tools.registerInlineCSS = function (hookId, css)
{
//	try {
//	var styleNode = dojo.byId(hookId);
//
//	if (styleNode != null)
//		styleNode.innerHTML = styleNode.innerHTML + '\n' + css;
//	else
//		console.warning('Module CSS Hook not found (id=\'' + hookId + '\')');
//	} catch(err) {
//		alert(err.message);
//	}
	stylesheet = dojo.doc.createStyleSheet();
	stylesheet.cssText = css;

	//
	 // var style = dojo.doc.createElement('STYLE');
	 // document.documentElement.firstChild.appendChild(style);
	 // style.styleSheet.cssText = css;
	 //
};

tools.parseCSS = function (hookId, domNode)
{
	dojo.query("style", domNode).forEach( function (style)
	{
		tools.registerInlineCSS(hookId, style.innerHTML);
	});
};

tools.extractCSS = function (hookId, response)
{
	var hookDiv = document.createElement('div');
	hookDiv.innerHTML = response;

	tools.parseCSS(hookId, hookDiv);
};*/

tools.getParentByClass = function (cnode, parentClass)
{
	while (cnode && !dojo.hasClass(cnode, parentClass)) {
		cnode = cnode.parentNode;
	}
	return cnode;
}

tools.setText = function(node, text) 
{
	dojo.empty(node);
	node.appendChild(document.createTextNode(text));	
}

var root = {

	createNamespace : function (namespace)
	{
		if (window[namespace] == null) {
			window[namespace] = {};
		}
	},

	registerNamespace : function (namespace, name, value)
	{
		root.createNamespace(namespace);
		window[namespace][name] = value;
	}
};

