/*
 * Functions
 *
 * Global functions not associated with any objects.
 */

function getEventOrigin(ev)
{
	ev = ev || window.event;
	return ev.target || ev.srcElement;
}

function preventDefaultAction(ev)
{
	ev = ev || window.event;
	ev.returnValue = false;
	if (ev.cancelable && ev.preventDefault) ev.preventDefault();
}

var attachEvent = function()
{
	/* usage: attachEvent(o, t, f[, c])
	 * o: object
	 * t: (event) type
	 * f: function
	 * c: capture (boolean)
	 */
	if (window.addEventListener)
	{
		return function(o, t, f, c)
		{
			c = Boolean(c);
			o.addEventListener(t, f, c);
		};
	}
	else if (window.attachEvent)
	{
		return function(o, t, f)
		{
			var f = function()
			{
				f.call(o, window.event);
			};
			o.attachEvent('on' + t, f);
		};
	}
	else
	{
		return function(o, t, f)
		{
			o['on' + t] = f;
		}
	}
}();

var detachEvent = function()
{
}();

function h_getArrayWithClassNames(s)
{
	// Utility function used by removeClassName() and appendClassName(). Prefix letter 'h' stands for 'hidden'.
	var a;
	return (s && (a = s.match(/\S+/g)) ? a : new Array());
}

function removeClassName(oElmnt, sClassName, bReturn)
{
	// Removes a named class from referred element and leaving other classes by, good if you have multiple classes on that element.
	var a = h_getArrayWithClassNames(oElmnt.className), i = a.indexOf(sClassName);
	if (-1 != i) a.splice(i, 1); // Must be cause if you feed splice() with -1 it gets the elements in reverse order
	oElmnt.className = a.join(' ');
	if (Boolean(bReturn)) return a;
}

function appendClassName(oElmnt, sClassName)
{
	// Appends a named class to referred element, better then setting className as it overwrites the whole attribute value and makes it impossible to have multiple classes on an element.
	if (!(sClassName.isString && /([A-Za-z][-0-9A-Z_a-z]+)/.test(sClassName))) return; // Not valid class name
	var a = removeClassName(oElmnt, sClassName, true); // First remove the class name we want to append to avoid duplicates
	a.push(sClassName);
	oElmnt.className = a.join(' ');
}

function replaceClassName(oElmnt, sOldClassName, sNewClassName)
{
	// Removes a named class and appends another named class.
	removeClassName(oElmnt, sOldClassName);
	appendClassName(oElmnt, sNewClassName);
}