
function trimString(s)
{
	return s.replace(/^(\s)+/, "").replace(/(\s)+$/, "");
}

function verifyOrgId(n)
{
	var re = new RegExp("^([0-9]{6})-([0-9]{4})$", "i");
	var ma = re.exec(n);
	return (ma && (calculateCheckDigit(ma[1] + ma[2].substring(0,3)) == ma[2].charAt(3)));
}

function verifyEmail(e, mandatory)
{
	if(trimString(e) == "") !mandatory;
	var re = /^.+@.+\..+$/i;
	return (re.exec(e) != null);
}

function verifyPhone(p, mandatory)
{
	if(trimString(p) == "") !mandatory;
	var re = /^([0-9]|\s|\/|\+|\-|\(|\))+$/i;	
	return (re.exec(p) != null);
}

function parseFloatEx(f)
{
	return parseFloat(f.toString().replace(",", "."));
}

function formatPrice(p, l, delim)
{
	var b = Math.pow(10, l);

	p = parseFloatEx(p);
	p = Math.round(p * b) / b;

	p = p.toString().split(".");

	var h = "", d = "", j = 0;

	var nil = "0000000000000000000";

	if(p.length == 1)
		d = nil.slice(0, l);
	else if(p[1].length < l)
		d = p[1] + nil.slice(0, l - p[1].length);
	else
		d = p[1];

	for(var i = p[0].length - 1; i >= 0; i--)
	{
		if(j && (j % 3) == 0) h = " " + h;
		h = p[0].charAt(i) + h;
		j++;
	}

	if(l > 0)
	{
		if(!delim) delim = ",";
	}
	else
		delim = "";
	
	return h + delim + d;
}

function formatPriceEx(p, mf)
{
	// due to a bug in regexp for NS4, we need to loop
	for(var d = null; !d; d = /^.*\[([0-9]+)\].*$/ig.exec(mf));
	return mf.replace(/\[[0-9]\]/ig, formatPrice(p, d[1]));
}

function openWindow(url, windowname, width, height)
{
	var w, f = "scrollbars=yes,toolbar=no,directories=no,location=no,status=no,menubar=no,resizable=1,width=" + width + ",height=" + height;
	
	w = window.open(url, windowname, f, true);
	
	if(w == null)
		alert("Fel:\n\nKunde inte skapa fönster!");
	else
		w.focus();

	return w;
}

function list_setSelectedItem(l, v)
{
	for(var i = 0; i < l.options.length && l.options[i].value != v; i++);

	var ok = (i < l.options.length);

	if(ok) l.selectedIndex = i;

	return ok;
}

function calculateCheckDigit(num)
{
    var i, n, sum = 0, l;
    
    num = num.toString();
    l = num.length;

    for(i = l - 1; i >= 0; i--)
    {
        n = parseInt(num.charAt(i)) * (2 - ((l + 3 - i) % 2));
        sum += parseInt(Math.floor(n / 10) + (n % 10));
	}

	return (10 - (sum % 10)) % 10;
}
