// utility function for handling classes on elements
/**
 * checks if an element has a specific class
 *
 * @param element element
 * @param name class name
 *
 * @return \c true if the class is present, otherwise \c false
 */
function hasClass( element, name ) {
	return element.className.match( new RegExp("(^|\\s)"+name+"(\\s|$)") ) != null;
}

/**
 * removes a class on an element if present
 *
 * @param element element
 * @param name class name
 */
function removeClass( element, name ) {
	element.className = element.className
		.replace( new RegExp( "\\s" + name + "(\\s)"), "$1" )
		.replace( new RegExp( "^" + name + "(\\s|$)"), "" )
		.replace( new RegExp( "\\s" + name + "$"), "" );
}

/**
 * adds a class to an element if not already present
 *
 * @param element element
 * @param name class name
 */
function addClass( element, name ) {
	if( !hasClass( element, name ) )
		element.className += (element.className == "" ? "" : " ") + name;
}

// for_each helper
/**
 * helper function to iterate over nodelists and other objects that act as arrays
 * 
 * @param actsAsArray an array or an object that acts as an array, i.e. has a .length attribute
 * @param callback function that takes one argument, called for each element in the array
 *
 * example:
 *    var a = [ 1, 2, 3 ];
 *    total = 0;
 *    for_each( a, function(v) { total += v; } );
 *    alert( total ); // total is 6
 */
function for_each( actsAsArray, callback ) {
	for( var i = 0, sz = (actsAsArray ? actsAsArray.length : 0); i < sz; ++i )
		callback( actsAsArray[i] );
}


/**
 * format currency value in Dutch notation
 *
 * @param value value to format
 * @param decimals decimals to display, if undefined it defaults to 2
 *
 * @return formatted value (does not include currency symbol)
 */
function formatCurrency( value, decimals ) {
	if( isNaN( Math.abs(value) ) )
		return value;
	
	var factor = 1;
	var decimals = decimals == undefined ? 2 : decimals; // default to 2
	for( var i = 0; i < decimals; ++i )
		factor *= 10;

	var thousandsSeparator = ".";
	var decimalSeparator = ",";
	
	var isNegative = value < 0;
	
	var v = "" + Math.round( Math.abs(value) * factor );
	while( v.length < decimals + 1 )
		v = "0" + v;
	var left = v.substr( 0, v.length - decimals );
	var right = v.substr( v.length - decimals );
	
	var thousands = "";
	while( left.length > 3 ) {
		thousands = thousandsSeparator + left.substr( left.length - 3 ) + thousands;
		left = left.substr( 0, left.length - 3 );
	}
	thousands = left + thousands;
	
	return (isNegative ? "-" : "") + thousands + (decimals > 0 ? decimalSeparator + right : "");
}
