
for (var cS = 0; cS < CurrencySources.length; cS++)
{
	for (var i = 1; i < CurrencyRate[cS][0].length; i++)
	{
		if (!CurrencyRate[cS][i]) CurrencyRate[cS][i] = [];
		CurrencyRate[cS][i][0] = 1/CurrencyRate[cS][0][i];
		CurrencyRate[cS][i][i] = 1;
		for (var j = i; j < CurrencyRate[cS][0].length; j++)
		{
			if (!CurrencyRate[cS][j]) CurrencyRate[cS][j] = [];
			CurrencyRate[cS][i][j] = CurrencyRate[cS][0][j]/CurrencyRate[cS][0][i];
			CurrencyRate[cS][j][i] = CurrencyRate[cS][0][i]/CurrencyRate[cS][0][j];
		}
	}
}

var defaultValue = 1;
var currentPrecision = 2;
var currentSource = 0;
var oPrecisionContainer;

var aValueTables = [];
var aValueNodes = [];

restoreFromCookie();

function InitCalc()
{
	
	
	
	for (var i = 0; i < CurrencyAbbr.length; i++)
	{
		
		aValueNodes[i] = [];
		
		var cTable = $('values_' + i);
		if (!cTable)
			continue;
		var cRows = cTable.getElementsByTagName('tr');
		var cHead = cRows[0];
		cHead.getElementsByTagName('td')[0].innerHTML = '<div class="currency_value"><div class="headCurrencySelectContainer" style="position: absolute;"><select class="headCurrencySelect" id="selector_' + i + '"></select></div><span></span><span class="currency-name">' + CurrencyNames[i][0] + '</span><br /></div><div class="currency_icon">' + '<img src="i/flag/' + CurrencyAbbr[i] + '.gif" />' + '</div>';
		
		Common.Event.add(cHead.getElementsByTagName('td')[0],'mouseover',hoverRow);
		Common.Event.add(cHead.getElementsByTagName('td')[0],'mouseout',unhoverRow);
		Common.Event.add(cHead.getElementsByTagName('select')[0],'blur',setUnSelectedRow);
		Common.Event.add(cHead.getElementsByTagName('select')[0],'click',handleSelectClick);
		
		for (var j = 0; j < cRows.length; j++)
		{
			//Common.Event.add(cRows[j],'mouseover',hoverRow);
			//Common.Event.add(cRows[j],'mouseout',unhoverRow);
			//Common.Event.add(cRows[j].getElementsByTagName('select')[0],'focus',setSelectedRow);
			//Common.Event.add(cRows[j].getElementsByTagName('select')[0],'blur',setUnSelectedRow);
			//Common.Event.add(cRows[j].getElementsByTagName('select')[0],'mouseout',unhoverRow);
			//Common.Event.add(cRows[j].getElementsByTagName('select')[0],'click',handleSelectClick);
			//cRows[j].getElementsByTagName('td')[1].innerHTML = '';
			
			aValueNodes[i][j] = (i != j) ? new ValueNode(i,j) : null;
			
		}
		aValueTables[i] = new ValueTable(i);
	}		
	
	var oInput = $('ourValue');
	if (!oInput.value.toString().length)
		oInput.value = defaultValue;
		
	
	
	if (Common.Cookie.get('currentInputValue'))
	{
		oInput.value = Common.Cookie.get('currentInputValue');
		
	}
	
	var x = document.location.toString();
	var y = x.match(/[^\?]+\?(\d+)/);
	if (y && y[1] && parseInt(y[1]))
	{
		oInput.value = parseInt(y[1]).toString().substr(0,7);
	}

	
	Recalc();
	RefreshSelects(true);
	Common.Event.add($('ourValue'),'keyup',InitRecalc);
	
	PrecisionInit();
	oInput.focus();
	if (oInput.value != '1')
	{
		if(oInput.createTextRange){
				var t=oInput.createTextRange();
				t.moveStart("character", 0);
				t.moveEnd("character", oInput.value.length);
				t.select();
		}
		else if(oInput.setSelectionRange){
				oInput.setSelectionRange(0, oInput.value.length);
		}
	}
	else
	{
		setCaretPosition(oInput,1);
	}
	
}

var recalcTimeout = null;

function InitRecalc()
{
	window.clearTimeout(recalcTimeout);
	recalcTimeout = window.setTimeout(performRecalc,20);
}

function performRecalc()
{
	Recalc();
	RefreshSelects();
	Common.Cookie.set('currentInputValue',$('ourValue').value ? $('ourValue').value : 1);
	recalcTimeout = null;
}

function handleSelectClick(ev)
{
	var oElem = Common.Event.normalize(ev).target;
	if (getParentByName(oElem,'tr').isSelected)
		handleCurrencySwitch(ev);
	else
		setSelectedRow(ev);
}


function RefreshSelects(bInitFromDefault)
{
	var oSelector, aArr, oOption;
	var oInput = $('ourValue');
	
	var fValue = oInput.value.replace(/[^0-9.,]/g,'');
	fValue = fValue.replace(/([0-9]*)(,|\.)([0-9]*)([^0-9]?.*)/,'$1,$3');
		
	if(fValue.length == 0) {
		fValue = '0';		
	}
	
	if (parseFloat(fValue.replace(/,/,'.')) > 0)
	{
		oInput.value = fValue;
		fValue = parseFloat(fValue.toString().replace(/,/,'.').replace(/^0*/,''));
	}	
	else
	{
		fValue = 0;
	}
	
	for (var i = 0; i < CurrencyAbbr.length; i++)
	{
		if (Common.Class.match(aValueTables[i],'removed'))
		{
			continue;
		}
		oSelector = $('selector_' + i);
		if (oSelector)
		{
			if (oSelector.options.length < CurrencyAbbr.length || bInitFromDefault)
			{
				try
				{oSelector.options.length = 0;}
				catch (exception) {}
				
				oOption = document.createElement('option');
				oOption.id = 'option_' + j;
				oOption.value = -1;
				oOption.innerHTML = CurrencyRate[currentSource][0][i] == 0 ? CurrencyNames[i][1] : (fValue == 0 ? CurrencyNames[i][0] : (fValue + '&nbsp;' + getProperWord(fValue,i,true)));
				oSelector.appendChild(oOption);
				
				for (var j = 0; j < CurrencyAbbr.length; j++)
				{
					if (j == i)
						continue;
					/*if (Common.Class.match($('values_' + i + '_' + j),'hidden'))
					{*/
						oOption = document.createElement('option');
						oOption.id = 'option_' + i + '_' + j;
						oOption.value = j;
						oOption.innerHTML = CurrencyNames[j][1];
						oSelector.appendChild(oOption);
					//}
				}
				Common.Event.add(oSelector,'change',handleCurrencySwitch);
			}
			else
			{
				oOption = oSelector.options[0];
				oOption.innerHTML = CurrencyRate[currentSource][0][i] == 0 ? CurrencyNames[i][1] : (fValue == 0 ? CurrencyNames[i][0] : (fValue + '&nbsp;' + getProperWord(fValue,i,true)));
			}
		}
				
	}
}

function PrecisionInit()
{
	oPrecisionContainer = $('Precision');
	var aImgs = oPrecisionContainer.getElementsByTagName('img');
	for (var i = 0; i < aImgs.length; i++)
	{
		Common.Event.add(aImgs[i],'mouseover',PrecisionHover);
		Common.Event.add(aImgs[i],'mouseout',PrecisionOut);
		Common.Event.add(aImgs[i],'click',PrecisionClick);
	}
	PrecisionRestore();
}
function PrecisionRestore()
{
	var aImgs = oPrecisionContainer.getElementsByTagName('img');
	for (var i = 0; i < aImgs.length; i++)
	{
		if (i <= currentPrecision)
			Common.Class.add(aImgs[i],'active');
		else
			Common.Class.remove(aImgs[i],'active');
	}
}
function PrecisionHover(ev)
{
	var elem = Common.Event.normalize(ev).target;
	var aImgs = oPrecisionContainer.getElementsByTagName('img');
	for (var i = 0, found = false; i < aImgs.length; i++)
	{
		if (!found)
			Common.Class.add(aImgs[i],'active');
		else
			Common.Class.remove(aImgs[i],'active');
		if (aImgs[i] == elem)
			found = true;
	}
}
function PrecisionOut()
{
	PrecisionRestore();
}
function PrecisionClick(ev)
{
	var elem = Common.Event.normalize(ev).target;
	var aImgs = oPrecisionContainer.getElementsByTagName('img');
	for (var i = 0, found = false; i < aImgs.length && found === false; i++)
	{
		if (aImgs[i] == elem)
			found = i;
	}
	currentPrecision = found;
	PrecisionRestore();	
	Recalc();
	RefreshSelects();
}
function PrecisionSet()
{
	
}

function setSelectedRow(ev)
{
	var oElem = getParentByName(Common.Event.normalize(ev).target,'tr');
	oElem.isSelected = true;
}
function setUnSelectedRow(ev)
{
	var oElem = getParentByName(Common.Event.normalize(ev).target,'tr');
	if (oElem.isSelected)
	{
		oElem.isSelected = false;
		unhoverRow(ev);
	}
}
function hoverRow(hlrow)
{
	var e = Common.Event.normalize(hlrow);
	//if (!Common.Class.match(getParentByName(e.target,'table'),'disabled'))
		Common.Class.add(getParentByName(e.target,'tr'),'hovered');
}
function unhoverRow(hlrow)
{
	var e = Common.Event.normalize(hlrow);
	//if (!Common.Class.match(getParentByName(e.target,'table'),'disabled'))
	{
		var oTr = getParentByName(e.target,'tr');
		if (!oTr.isSelected)
			Common.Class.remove(getParentByName(e.target,'tr'),'hovered');
	}
}

function getParentByName(oNode,name)
{
	name = name.toLowerCase();
	while (oNode.parentNode)
	{
		if (oNode.nodeName.toLowerCase() == name)
			return oNode;
		oNode = oNode.parentNode;
	}
	return false;
}

function Recalc()
{
	var oInput = $('ourValue');
	

	var fValue = oInput.value.replace(/[^0-9.,]/g,'');
	fValue = fValue.replace(/([0-9]*)(,|\.)([0-9]*)([^0-9]?.*)/,'$1.$3');
	document.title = parseFloat(fValue);
	
	if (fValue.toString().indexOf('0') == 0)
	{
		if (fValue.toString().indexOf('.') != -1)
		{
			fValue = fValue.replace(/^0+([^0])/,'0$1');
		}
		else
		{
			fValue = fValue.replace(/^0+([^0])/,'$1');
		}
	}
	
	if(fValue.length == 0) {
		fValue = '0';
	}
	
	if (parseFloat(fValue) > 0)
	{
		oInput.value = fValue.replace(/\./,',');
		fValue = parseFloat(fValue.toString());
		processFontSize(fValue);
	}
	else 
	{
		for (var i = 0; i < CurrencyAbbr.length; i++)
		{
			if (Common.Class.match(aValueTables[i].oNode,'removed'))
			{
//				continue;
			}
			aValueTables[i].oLeft.innerHTML = '';
			aValueTables[i].oRight.innerHTML = CurrencyNames[i][0];
			
			
			
			for (var j = 0; j < CurrencyAbbr.length; j++)
			{
				if (i != j)
				{
					if (CurrencyRate[currentSource][0][j] == 0)
					{
						aValueNodes[i][j].oLeft.innerHTML = '&nbsp;';
						Common.Class.add(aValueNodes[i][j].oNode,'disabled');
					}
					else
					{
						aValueNodes[i][j].oLeft.innerHTML = '';
						Common.Class.remove(aValueNodes[i][j].oNode,'disabled');
					}
					
					aValueNodes[i][j].oRight.innerHTML = CurrencyNames[j][1];
				}
			}
		}
		return false;
	}
	
	for (var i = 0; i < CurrencyAbbr.length; i++)
	{
		if (Common.Class.match(aValueTables[i].oNode,'removed'))
		{
			continue;
		}
		aValueTables[i].oLeft.innerHTML = CurrencyRate[currentSource][0][i] == 0 ? /*CurrencyNames[i][0]*/ '' : prettyPrint(fValue,-1,true) + '&nbsp;';
		aValueTables[i].oRight.innerHTML = CurrencyRate[currentSource][0][i] == 0 ? CurrencyNames[i][0] : getProperWord(fValue,i,true);
		
		if (CurrencyRate[currentSource][0][i] == 0)
			Common.Class.add(aValueTables[i].oNode,'disabled');
		else
			Common.Class.remove(aValueTables[i].oNode,'disabled');
		for (var j = 0; j < CurrencyAbbr.length; j++)
		{
			if (i != j)
			{
				if (CurrencyRate[currentSource][0][j] == 0 || CurrencyRate[currentSource][i][j] == Number.POSITIVE_INFINITY)
				{
					Common.Class.add(aValueNodes[i][j].oNode,'disabled');
					aValueNodes[i][j].oLeft.innerHTML = '';
					aValueNodes[i][j].oRight.innerHTML = CurrencyNames[j][1];
				}
				else
				{
					Common.Class.remove(aValueNodes[i][j].oNode,'disabled');
					aValueNodes[i][j].oLeft.innerHTML = prettyPrint(fValue * CurrencyRate[currentSource][i][j],0,true);
					aValueNodes[i][j].oRight.innerHTML = getProperWord(fValue * CurrencyRate[currentSource][i][j],j,1);
				}
				
			}
		}
	}
	
	saveToCookie();
	
}

function getProperWord(iNum,iCurrency,render)
{
	var cIndex;
	if (render)
		iNum = prettyPrint(iNum);
	iNum = String(iNum);
	if (!iNum.match(/[^0-9]/) || iNum.match(/(,|\.)0*$/))
	{
		if (iNum.match(/(,|\.)0*$/))
			iNum = parseInt(iNum).toString();
		if ((iNum > 4 && iNum < 20) || (parseInt(iNum) > 100 && (parseInt(iNum.substr(iNum.length-2)) < 20 && parseInt(iNum.substr(iNum.length-2)) > 4)))
		{
			cIndex = 4;
		}
		else if (iNum.charAt(iNum.length-1) == 1)
		{
			cIndex = 2;
		}
		else if (iNum.charAt(iNum.length-1) == 2 || iNum.charAt(iNum.length-1) == 3 || iNum.charAt(iNum.length-1) == 4)
		{
			cIndex = 3;
		}
		else
		{
			cIndex = 4;
		}
	}
	else
	{
		cIndex = 3;
	}
	return CurrencyNames[iCurrency][cIndex] ? CurrencyNames[iCurrency][cIndex] : CurrencyNames[iCurrency][0];
}

function prettyPrint(fNum,rounds,spacer)
{
	if (rounds != -1)
		fNum = findNonZero(fNum);
	fNum = fNum.toString().replace(/\./,',').replace(/^,([0-9]+)/,'0,$1');
	if (spacer)
		fNum = fNum.replace(/^([0-9]+)/,function (str,mch){return schpatts(mch)});
	return fNum;
}
function findNonZero(fNum)
{
	for (var i = currentPrecision; i <= 4; i++)
		if (fNum.toFixed(i) != 0 || i == 4)
			return fNum.toFixed(i);
}

Common.Event.add(window,'load',InitCalc);

var  m = document.uniqueID /*IE*/
        && document.compatMode  /*>=IE6*/
        && !window.XMLHttpRequest /*<=IE6*/
        && document.execCommand ;

        try{
                if(!!m){
                        m("BackgroundImageCache", false, true) /* = IE6 only */
                }

        }catch(oh){};
		
		
function generateTable(iCId,r)
{
	var str = '';
	str += '<table id="values_' + iCId + '" class="currency-table ' + (r === true? ' removed' : '') + '"';	
	str += '><tr class="values_head"><td colspan="2"><div><span></span><select class="headCurrencySelect" id="selector_' + iCId + '"></select><span class="currency-name"></span></div><div></div></td></tr>';
	for (var i = 0, cc = 0; i < DefaultCurrencies.length; i++)
	{
		if (DefaultCurrencies[i] != iCId)
		{
			cc++;
			str += '<tr class="values_content';
			if (cc > 7)
				str += ' hidden';
			if (CurrencyRate[currentSource][0][DefaultCurrencies[i]] == 0)
				str += ' disabled';
			str += '" id="values_' + iCId + '_' + DefaultCurrencies[i] + '"><td class="values_value"></td><td class="values_sign"><span></span></td></tr>';
		}
	}
	str += '</table>';
	document.write(str);
}

function handleCurrencySwitch(ev)
{
	var elem = getParentByName(Common.Event.normalize(ev).target,'select');
	
	//document.title = elem.id + ' = ' + elem.options[elem.selectedIndex ? elem.selectedIndex : 0].value;
	
	//getParentByName(elem,'tr').isSelected = false;
	unhoverRow(ev);
	$('ourValue').focus();
	elem.blur();
	
	var id1 = elem.id.replace(/^.+?_([0-9]+_)?/,'');
	//document.title = id1;
	var id2 = elem.options[elem.selectedIndex].value;
	if (id2 == -1)
		return false;
	//alert(id1 + ' : ' + id2);
	switchPair(id1,id2);
	RefreshSelects(true);
	Recalc();

}
function switchPair(id1,id2)
{
	var cNode;
	
	var _id1 = 'values_' + id1;
	var _id2 = 'values_' + id2;
	//alert(_id1 + ' : ' + _id2);
	var oParent1 = $(_id1).parentNode;
	var oParent2 = $(_id2).parentNode;
	
	var bVisibilityChanged = Common.Class.match(
		$(_id2),
		'removed'
		);
	
	for (var i = 0; i < CurrencyAbbr.length; i++)
	{		
		if (i != id1 && bVisibilityChanged)
			Common.Class.add($('values_' + i + '_' + id1),'hidden');
		if (i != id2 && bVisibilityChanged)
			Common.Class.remove($('values_' + i + '_' + id2),'hidden');
		if (i != id1 && i != id2)
		{
			//cNode = $('values_' + i + '_' + id2).parentNode.replaceChild($('values_' + i + '_' + id2),$('values_' + i + '_' + id1));
			//$('values_' + i + '_' + id2).parentNode.appendChild(cNode);
		}
	}
		
	oParent1.appendChild($(_id2));
	oParent2.appendChild($(_id1));
	
	if(bVisibilityChanged) {
		
		Common.Class.add($(_id1),'removed');
		Common.Class.remove($(_id2),'removed');
		
	}
	
	for (var i = 0; i < CurrencyAbbr.length; i++)
	{
		if (i == id2)
			continue;
		if (!Common.Class.match($('values_' + i),'removed'))
			Common.Class.remove($('values_' + id2 + '_' + i),'hidden');
		else
			Common.Class.add($('values_' + id2 + '_' + i),'hidden');
	}

}

function saveToCookie() {
	
	var
		sCurrencies = '',
		aCurrencyTables = Common.Dom.getElementsByClassName(document, 'currency-table', 'table')
		;
	
	for(var i = 0, iIndex; i < aCurrencyTables.length; i++) {		
		
		if(Common.Class.match(aCurrencyTables[i], 'removed')) {
			continue;
		}
		
		iIndex = aCurrencyTables[i].id.match(/^values_(\d+)$/)[1];
		
		sCurrencies += (sCurrencies == '')? iIndex : ',' + iIndex;
			
	}
	
	Common.Cookie.set('currencies', sCurrencies);
	Common.Cookie.set('source', currentSource);
	Common.Cookie.set('precision', currentPrecision);
		
}

function restoreFromCookie() {
		
	var sCurrencies = Common.Cookie.get('currencies');
	
	if(!sCurrencies) {
		return;
	}
	
	currentSource = Common.Cookie.get('source');	
	currentPrecision = Common.Cookie.get('precision');
	DefaultCurrencies = sCurrencies.split(',');
	
	for(var i = 0; i < DefaultCurrencies.length; i++) {
		DefaultCurrencies[i] = parseInt(DefaultCurrencies[i]);
	}
	
	for(var i = 0; i < CurrencyAbbr.length; i++) {
		
		if(DefaultCurrencies.contains(i)) {
			continue;
		}
		
		DefaultCurrencies.push(i);
		
	}
	
}


function ValueNode(i,j)
{
	this.oNode = $('values_' + i + '_' + j);
	this.oLeft = this.oNode.getElementsByTagName('td')[0];
	this.oRight = this.oNode.getElementsByTagName('td')[1].getElementsByTagName('span')[0];
}

function ValueTable(i)
{
	this.oNode = $('values_' + i);
	this.oLeft = this.oNode.getElementsByTagName('tr')[0].getElementsByTagName('div')[0].getElementsByTagName('span')[0];
	this.oRight = this.oNode.getElementsByTagName('tr')[0].getElementsByTagName('div')[0].getElementsByTagName('span')[1];
}

function processFontSize(fValue)
{
	/*
	fValue = fValue.toString();
	if (fValue.length == 6)
	{
		setFontSize('0.9em');
	}
	else if (fValue.length == 7)
	{
		setFontSize('0.8em');
	}
	else
	{
		setFontSize('1em');
	}
	*/
}

function setFontSize(val)
{
	for (var i = 0; i < aValueTables.length; i++)
	{
		aValueTables[i].oLeft.parentNode.style.fontSize = val;
	}
}

function schpatts(str,four)
{
	return (str.length >= (four ? 4 : 5)) ? (schpatts(str.substr(0,str.length-3),true) + '&nbsp;' + str.substr(str.length - 3,3)) : str;
}

function setCaretPosition(ctrl, pos)
{

	if(ctrl.setSelectionRange)
	{
		ctrl.focus();
		ctrl.setSelectionRange(pos,pos);
	}
	else if (ctrl.createTextRange) {
		var range = ctrl.createTextRange();
		range.collapse(true);
		range.moveEnd('character', pos);
		range.moveStart('character', pos);
		range.select();
	}
}
