
//--------------------------------------------------------------

function CurrencyConverter() {
	this.body_element = document.getElementsByTagName("body")[0];
	this.registerEventListeners();
	this.setStartupCurrency();
}

CurrencyConverter.prototype.registerEventListeners = function() {
	var currency_button_container = document.getElementById('currency_icons');
	var currency_buttons = currency_button_container.getElementsByTagName('img');
	
	this.currency_icons = new Array();
	for (var i = 0; i < currency_buttons.length; i++) {
		this.currency_icons[i] = new CurrencyIcon(currency_buttons[i], this);
	}
}

CurrencyConverter.prototype.setStartupCurrency = function() {
	var saved_currency_code = this.loadCurrency();
	
	if (!saved_currency_code) {
		this.setCurrency('GBP');
	} else {
		this.setCurrency(saved_currency_code);
	}
}

CurrencyConverter.prototype.setCurrency = function(currency_code) {
	this.body_element.className = currency_code;
	this.saveCurrency(currency_code);
	for (var i = 0; i < this.currency_icons.length; i++) {
		this.currency_icons[i].onActivateCurrency(currency_code);
	}
}

CurrencyConverter.prototype.loadCurrency = function() {
	return getCookie("last_currency");
}

CurrencyConverter.prototype.saveCurrency = function(currency_code) {
	setCookie("last_currency", currency_code);
}

//-------------------------------------------------

function CurrencyIcon(img_element, currency_converter) {
	this.img_element = img_element;
	this.currency_converter = currency_converter;
	this.currency_code = img_element.id.substring(0, 3);
	this.inactive_image_src = '/templates/images/layout/' + this.currency_code + '.gif'
	this.active_image_src = '/templates/images/layout/' + this.currency_code + '_active.gif'
	this.encloseInLink();
}

CurrencyIcon.prototype.encloseInLink = function() {
	var link_element = document.createElement('a');
	link_element.setAttribute('href', '#');
	link_element.onclick = this.setCurrency;
	link_element.currency_converter = this;
	
	var li_element = this.img_element.parentNode;
	link_element.appendChild(this.img_element);
	li_element.appendChild(link_element);
}

CurrencyIcon.prototype.setCurrency = function() {
	this.currency_converter.setCurrency(this.currency_code);
	return false;
}

CurrencyIcon.prototype.onActivateCurrency = function(currency_code) {
	if (this.currency_code == currency_code) {
		this.img_element.src = this.active_image_src;
	} else {
		this.img_element.src = this.inactive_image_src;
	}
}

//-------------------------------------------------

