/**
 * Code from www.kbbanki.is
 */
var lastInput;
function strip(n,s)
{
	var pos=0;
	var len=n.length;
	var res='';
	while (pos<len)
	{
		if (s.indexOf(n.charAt(pos))!=-1)
			res+=n.charAt(pos);

		pos++;
	}
	return(res);
}

function fixfloat(n)
{
	var pos;
	var inp;
	var flp;
	var res;

	pos=n.indexOf(',');

	if (pos==-1)
		pos=n.indexOf('.');

	// comma in string
	if (pos!=-1)
	{
		inp=strip(n.substring(0,pos),'0123456789');
		flp=strip(n.substring(pos+1),'0123456789');

		if (inp && flp) //num, commanum
			return eval(inp)+flp/Math.pow(10,flp.length);
		else
		{
			if (!inp && flp) //commanum
				return flp/Math.pow(10,flp.length);
			else
			{
				if (!inp && !flp) //not num, not commanum
					return '';
				else if (inp && !flp) //num
					return eval(inp);
			}
		}
	}
	return(strip(n,'0123456789'));
}

function init( code )
{
	if ( code != '')
		calcCurrency(code,1);
}

function calcCurrency(mynt, calc)
{
	lastInput = mynt;
	if (calc == 1)
		calcCurrency2();
}


function calcCurrency2()
{
	var mynt = lastInput;
	var theForm = document.currencyForm;

	//var userin = fixfloat(eval('theForm.'+mynt+'.value'));
	//var equivalent = arrCurrency[mynt].zfactor;

	var userInput = fixfloat(eval('theForm.'+mynt+'.value'));
	var equivalent = arrCurrency[mynt][1];

	if (userInput == '' || userInput == 0 || isNaN(userInput) )
	{
		ClearForm();
		return false;
	}

	var v;
	for (var mynt in arrCurrency)
	{
		if( mynt != lastInput )
		{
			v = FormatMoney(equivalent/parseFloat(arrCurrency[mynt][1])*userInput);
			eval('theForm[mynt].value ='+"v");
		}

	}

	return true;
}

function ClearForm()
{
	var theForm = document.currencyForm;
	for( var mynt in arrCurrency)
		theForm[mynt].value = "";

	return true;
}

function FormatMoney(amt)
{
    var tmpn=0;
    var tmps="";
    tmpn=Math.round(amt*100);

    //Add comma and 2 numbers to the end
    if (tmpn < 0 || tmpn > 99999999999999)
		return "*********";
    else if (tmpn < 10)
		tmps="00"+tmpn;
    else if (tmpn < 100)
		tmps="0"+tmpn;
    else tmps=""+tmpn;

    var before = formatThousand(tmps.substring(0,(tmps.length-2)));
    return before+","+ tmps.substring((tmps.length-2),tmps.length);
}

function formatThousand(szIn)
{
    var sz = szIn;
    var szNew = '';
    while (sz.length > 3)
        {
        if (szNew != '') szNew = '.' + szNew;
        szNew = sz.slice((sz.length-3),sz.length) + szNew;
        sz = sz.slice(0,(sz.length-3));
        }
    if (szNew != '') szNew = '.' + szNew;
    szNew = sz + szNew;
    return(szNew);
}
