mxFormatN = function (n, l) {
    n = n.toString();
    while (n.length < l) n = '0' + n;
    return n;
}

mxFormatDate = function (d) {
    return mxFormatN(d.getDate(), 2) + '.' + mxFormatN(d.getMonth() + 1, 2) + '.' + mxFormatN(d.getFullYear(), 4);
}

mxFormatDateYMD = function (d) {
    return mxFormatN(d.getFullYear(), 4) + mxFormatN(d.getMonth() + 1, 2) + mxFormatN(d.getDate(), 2);
}

function mxReformatNumber(v, sep, dec) {
    var p = v.split('.'), s = p[0], i = s.length - 3, j = 0;
    if (s[0] == '-')
        j = 1;
    while (i > j) {
        s = s.substr(0, i) + sep + s.substr(i);
        i -= 3;
    }
    return s + (p.length > 1 ? dec + p[1] : '');
}

function mxFormatAmount(v) {
    return mxReformatNumber(v.toFixed(2), ' ', '.');
}

function mxFormatDecimal(v, prec) {
    if (!isNaN(prec)) {
        var p = Math.pow(10, prec);
        v = Math.round(v * p) / p;
    }
    return mxReformatNumber(v + '', ' ', '.');
}

/*
http://stackoverflow.com/questions/4197591/parsing-url-hash-fragment-identifier-with-javascript
http://stackoverflow.com/questions/901115/get-querystring-values-in-javascript/2880929#2880929
*/

function mxDecodeParams(q, def) {
	var p = {};
	var e,
		a = /\+/g, // Regex for replacing addition symbol with a space
		r = /([^&;=]+)=?([^&;]*)/g,
		d = function (s) { return decodeURIComponent(s.replace(a, " ")); };

	while (e = r.exec(q))
		p[d(e[1])] = d(e[2]);

	if (def != undefined)
    {
        for (key in def) {
            if (p[key] == undefined) {
                p[key] = def[key];
            }
        }
    }
    return p;
}

function mxEncodeParams(p, def) {
	var s = '',
        e = function (s) { return encodeURIComponent(s); };

	for (key in p) {
	    if (def == undefined || def[key] != p[key])
	        s += e(key) + '=' + e(p[key]) + '&';
	}
	return s.substr(0, s.length - 1);
}

function mxGetHashParams(def) {
	var q = window.location.hash;
	if (q.length > 0)
		q = q.substr(1, q.length - 1);
	return mxDecodeParams(q, def);
}

function mxSetHashParams(p, def) {
    var loc = window.location;
    var url = loc.toString().split('#')[0];  //loc.protocol + '//' + loc.host + loc.pathname + loc.search;
    var hash = mxEncodeParams(p, def);
    url += '#' + hash;
    if (loc.toString() != url)
        loc.replace(url);
}

