/**
 * Currency (http://www.reality-xp.com)
 * A jQuery plugin for converting currencies
 * 
 * Version 1.0
 * August 27th, 2008
 *
 * Copyright (c) 2008 Reality XP
 * Dual licensed under the MIT and GPL licenses.
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.opensource.org/licenses/gpl-license.php
 * 
 **/ 

;(function(){
	
var $$;

$$ = $.fn.convertCurrency = function(currencycode) {
	var $this = $(this);
	
	if ($this.attr('rel'))
	{
		
		var prms = $this.attr('rel').split(':');	/*"USD:EUR:€"*/
		var fAmnt = parseFloat($this.text());
		var cCode = currencycode ? ' '+prms[1] : '';
		// check if the exchange rate has been retrieved today
		var cookieVal = $.cookie('currencyrate'+prms[0]+prms[1]);
		if (cookieVal != null)
		{
			frmtCurrency($this,prms[2],fAmnt*parseFloat(cookieVal),cCode,prms[1]);
		}
		else
		{
			try {
				$.ajax({
					type: "POST",
					url: 'currency-ajax.php',
					data: "action=rate" + "&currfrom=" + prms[0] + "&currto=" + prms[1],
					success: function(msg) {
						
						var response = msg.split(':');
						
						switch (response[0]) {
						case 'ERR-100':

							$.cookie('currencyrate'+prms[0]+prms[1],response[2],{expires: 6, path: '/' });
							frmtCurrency($this,prms[2],fAmnt*parseFloat(response[2]),cCode,prms[1]);
							break;
						case 'ERR-200':
							break;
						default:
							break
						}
					},
					error: function(xhr, msg, ex) {
						reqAjax = null
					}
				})
			} catch(e) {
			}
		}
	}
	return this;

	function frmtCurrency(ele,symb,val,code,cls) {
		// round the currency to the nearest .05
		
		//val *= 2.0;
		//val = val.toFixed(1) / 2.0;
		//val = val.toFixed(2);
		// build the text in the form: '$' '12.35' 'USD'	
		
		val = number_format(val, 2);
		
		ele.text(symb+val+code );
		// add the currency code to the element class.
		ele.addClass(cls);
	};

	function number_format (number, decimals, dec_point, thousands_sep) {
		number = (number + '').replace(',', '').replace(' ', '');
		var n = !isFinite(+number) ? 0 : +number,
			prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
			sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
			dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
			s = '',
			toFixedFix = function (n, prec) {
				var k = Math.pow(10, prec);
				return '' + Math.round(n * k) / k;
			};
		// Fix for IE parseFloat(0.55).toFixed(0) = 0;
		s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
		if (s[0].length > 3) {
			s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
		}
		if ((s[1] || '').length < prec) {
			s[1] = s[1] || '';
			s[1] += new Array(prec - s[1].length + 1).join('0');
		}
		return s.join(dec);
	}

};

})();

