/**
 * Currency Convert
 * A tweaked jQuery plugin for converting currencies based on Currency plugin
 *
 * on page load call convert
 * $(document).ready(function(){$('.currency').each(function(i,domEle){$(domEle).convertCurrency(false);return true;})});
 *
 **/

;(function(){
	
var $$;

$$ = jQuery.fn.convertCurrency = function(currencycode) {
	var $this = jQuery(this)
	if ($this.attr('rel'))
	{
		var prms = $this.attr('rel').split(':');	/*"USD:EUR:€"*/
		var htmlVal = $this.text();
		var amt = IsNumeric(htmlVal) ? htmlVal : htmlVal.substring(1); //strip currency symbol, if any
		//alert(amt);
		var fAmnt = parseFloat(amt);
		var cCode = currencycode ? ' '+prms[1] : '';
		// check if the exchange rate has been retrieved today
		var cookieVal = jQuery.cookie('currencyrate'+prms[0]+prms[1]);
		if (cookieVal != null)
		{
			//alert(fAmnt+' / '+parseFloat(cookieVal));
			frmtCurrency($this,prms[2],fAmnt*parseFloat(cookieVal),cCode,prms[1]);
		}
		else
		{
			try {
				reqAjax = jQuery.ajax({
					type: "POST",
					url: 'assets/templates/tsp/js/jquery-currency/currency-ajax.php',
					dataType: "json",
					data: "action=rate" + "&currfrom=" + prms[0] + "&currto=" + prms[1],
					success: function(json) {
						switch (json.errcode) {
						case 'ERR-100':
							jQuery.cookie('currencyrate'+prms[0]+prms[1],json.result,{expires: 6, path: '/' });
							frmtCurrency($this,prms[2],fAmnt*parseFloat(json.result),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'
		ele.text(symb+val+code );
		// add the currency code to the element class.
		ele.removeClass();
		ele.addClass('currency ' + cls);
	};
	
	function IsNumeric(sText){
		var ValidChars = "0123456789.";
		var IsNumber=true;
		var Char;
		
		
		for (i = 0; i < sText.length && IsNumber == true; i++) 
		  { 
		  Char = sText.charAt(i); 
		  if (ValidChars.indexOf(Char) == -1) 
			 {
			 IsNumber = false;
			 }
		  }
		return IsNumber;
		}
		
	};

})();

