var CurrencySelector = Class.create();

CurrencySelector.prototype =
{
	initialize: function (element)
	{
		this.div = element;
		
		var a = document.createElement('a');
		a.href = 'javascript: void(0)';		
		a.className = 'currency-selector-toggle';
		a.title = 'Click for a popup list of currencies to choose from';
		a.innerHTML = 'Change Currency';		
		this.toggle = a;		
		this.div.appendChild(a);	
		
		var select = document.createElement('select');
		select.className = 'currency-selector-hidden';
		select.size = 4;
		this.select = select;		
		this.div.appendChild(select);

		this.populateCurrencies();	
	},
	populateCurrencies: function ()
	{	
		var url = '/currencies/lookup';
		var ajax = new Ajax.Request(
			url,
			{
				onSuccess : this.doPopulateCurrencies.bindAsEventListener(this),
				onFailure : function () { }
			}
		);
	},
	doPopulateCurrencies: function (resp)
	{		
		Event.observe(this.toggle, 'click', this.toggleSelect.bindAsEventListener(this));	
		var currencies = resp.responseText.split('|');		
		
		var selected = currencies[currencies.length - 1];
		
		for (i = 0; i < currencies.length - 1; i += 2)
		{
			var id = currencies[i];
			var name = currencies[i + 1];
			
			this.select.options[this.select.options.length] = new Option(name, id);
			if (selected == id)
			{
				this.select.options[this.select.options.length - 1].selected = 'SELECTED';
			}
		}				
		
		Event.observe(this.select, 'change', this.setCurrency.bind(this));
		Event.observe(this.select, 'click', this.toggleSelect.bind(this));	
	},
	toggleSelect: function (event)
	{
		this.select.className = this.select.className == 'currency-selector-hidden' ? 'currency-selector' : 'currency-selector-hidden';
	},
	setCurrency: function (event)
	{
		var currency = this.select.options[this.select.selectedIndex].value;
		for (var i = 0; i < price_currencies.length; i ++)
		{
			price_currencies[i].setCurrency(currency);
		}
		for (var j = 0; j < price_values.length; j ++)
		{
			price_values[j].setCurrency(currency);
		}
		var today = new Date();
		var expire = new Date();
		expire.setTime(today.getTime() + 360000*24*100);
		document.cookie = 'CURRENCY_ID='+currency+';expires='+expire.toGMTString();		
	}
}

Event.observe(window, 'load', 
	function () 
	{
		var selectors = $$('div.currency-selector');
		selectors.each(
			function (element)
			{
				new CurrencySelector(element);
			}		
		);	
	}
);
