var jQ = null;
var owsCurrencyExchange = function( $ ) {
	jQ = $;
	return this;
}

owsCurrencyExchange.getInstance = function( $ ) {
	if ( !this.prototype.instance ) {
		this.prototype.instance = new this( $ );
	}

	return this.prototype.instance;
}

owsCurrencyExchange.prototype = {

	instance : null,

	currencyFrom : 'EUR',
	currencyRates : {},

	coff : 1,

	init : function() {
		this.searchPriceElements();
		if (this.priceElements.length) {
			this.modifyPriceElementsWhileLoading();
			this.loadCurrency();
		}
	},

	searchPriceElements : function() {
		this.priceElements = jQ('p.priceExch').show();
	},

	modifyPriceElementsWhileLoading : function() {
		this.priceElements.each(function(index, elem){
			elem = jQ(elem);
			elem.attr({'price:init':elem.text()}).empty().addClass('currencyLoad');
		});
	},

	loadCurrency : function() {
		if ( jQ.cookie('owsCEx_' + this.currencyFrom) ) {
			this.currencyRates[ this.currencyFrom ] = parseFloat( jQ.cookie('owsCEx_' + this.currencyFrom) );
			this.updatePriceElementsAfterLoading();
		} else {
			jQ.ajax({
				timeout : 20000,
				url : '/currency-exchange/CurrencyExchange.php',
				data : {
					action : 'getRates',
					'rates[]' : [ this.currencyFrom ]
				},
				dataType : 'json',

				success : function(data, status) {
					var mod = owsCurrencyExchange.getInstance();
					if (data[ mod.currencyFrom ]) {
						mod.currencyRates[ mod.currencyFrom ] = parseFloat( data[ mod.currencyFrom ] );
						mod.setCurrencyToCookie( data[ mod.currencyFrom ] );
						mod.updatePriceElementsAfterLoading();
					} else {
						mod.errorPriceElementsAfterLoading();
					}
				},

				error : function() {
					owsCurrencyExchange.getInstance().errorPriceElementsAfterLoading();
				}
			});
		}
	},

	setCurrencyToCookie : function( exch ) {
		jQ.cookie('owsCEx_' + this.currencyFrom, exch, {expires:1});
	},

	updatePriceElementsAfterLoading : function() {
		this.priceElements.each(function(index, elem){
			var mod = owsCurrencyExchange.getInstance();
			elem = jQ(elem);
			elem.text(
				mod.toFixed( (parseFloat( elem.attr('price:init') ) * mod.coff) * mod.currencyRates[ mod.currencyFrom ], 2)
			).attr({'price:init':0}).removeClass('currencyLoad');
		});
	},

	errorPriceElementsAfterLoading : function() {
		this.priceElements.each(function(index, elem){
			elem = jQ(elem);
			elem.text('error').attr({'price:init':0}).removeClass('currencyLoad');
		});
	},

	toFixed : function(num, n){
		return Math.round( num * Math.pow(10, n) ) / Math.pow(10, n);
		//return Math.floor( num );
	}
}

