/*
*	Methods to allow conversion of currency rates
*/
function currencyConversion()
{
	this.lookupUrl = parent.location.protocol + "//" + document.domain + "/WSCurrencyRate/GetRate.aspx";
	this.helpUrl = null;
	this.helpIcon = "images/icon_info.gif";
	this.convertedClass = "converted";
	this.items = 0;
	this.lastCurrency = null;
	this.cookie = "currency_last";
	this.cookiePath = "";
	this.currencyArray = new Array();
	this.rateCookieExpiration = 30;
	this.currencyWarningStyle = ".currencyWarning"
	this.cookieExpiration = 0;
	this.currencySelector = "span.currency";
	this.Id = "currencyConvertor";
	this.dropDownId = "currencySelector";
	this.dropDownGridId = "currencyDropdown";
	this.dropDownText = "Select Currency";
	this.dropDownColumns = 4;
	this.objectVariable = "currencies";
	this.dropAlign = "right";
	this.controlAlign = null;
	this.controlAlignId = null;
	this.ie6 = $.browser.msie && $.browser.version < 7;
	this.ie7 = $.browser.msie && $.browser.version < 8;
}

/*
*	Class to contain currency items
*/
function currencyItem(code, description, symbol, convertor)
{
	this.convertor = convertor;
	this.code = code;
	this.description = description;
	this.symbol = symbol;
	this.cookie = "currency_" + code;
	this.rate = this.getRateFromCookies();
}

/*
*	Returns whether an alternative currency has been selected
*/
currencyConversion.prototype.currencySelected = function ()
{
}

/*
*	Sets up the default list of currencies
*/
currencyConversion.prototype.defaultCurrencies = function ()
{
	this.addItem('', '', '');
	this.addItem('EUR', 'Euro', '&#128;');
	this.addItem('USD', 'US Dollar', '$');
	this.addItem('CAD', 'Canadian Dollar', '$');
	this.addItem('CNY', 'Chinese Yuan', '&#165;');
	this.addItem('AUD', 'Australian Dollar', '$');
	this.addItem('JPY', 'Japanese Yen', '&#165;');
	this.addItem('INR', 'Indian Rupees', 'INR');
	this.addItem('NZD', 'New Zealand Dollars', '$');
	this.addItem('CHF', 'Swiss Francs', 'CHF');
	this.addItem('ZAR', 'South African Rand', 'R');
	this.addItem('BRL', 'Brasilian Real', 'R$');
 	this.addItem('BGN', 'Bulgarian Leva', '&#1083;&#1074;');
 	this.addItem('HRK', 'Croatian Kuna', 'kn');
 	this.addItem('CZK', 'Czech Koruna', 'K&#269;');
 	this.addItem('DKK', 'Danish Kroner', 'kr');
 	this.addItem('EEK', 'Estonian Krooni', 'kr');
 	this.addItem('HKD', 'Hong Kong Dollar', '$');
 	this.addItem('HUF', 'Hungarian Forint', 'Ft');
 	this.addItem('IDR', 'Indonesian Rupiah', 'Rp');
 	this.addItem('LVL', 'Latvian Lats', 'Ls');
 	this.addItem('LTL', 'Lithuanian Litas', 'Lt');
 	this.addItem('MYR', 'Malaysian Ringgit', 'RM');
 	this.addItem('MXN', 'Mexican Peso', '$');
 	this.addItem('RON', 'New Romanian Lei', 'lei');
 	this.addItem('NOK', 'Norwegian Krone', 'kr');
 	this.addItem('PHP', 'Philippine Peso', 'Php');
 	this.addItem('PLN', 'Polish Zloty', '&#122;&#322;');
 	this.addItem('RUB', 'Russian Rouble', '&#1088;&#1091;&#1073;');
 	this.addItem('SGD', 'Singapore Dollar', '$');
 	this.addItem('KRW', 'South Korean Won', '&#8361;');
 	this.addItem('THB', 'Thai Baht', '&#647;');
 	this.addItem('TRY', 'Turkish Lira', '&#8356;');
}

/*
*	Outputs the html to present a currency dropdown grid
*/
currencyConversion.prototype.outputDropdown = function ()
{
	// Dropdown doesn't work in IE6
	if (this.ie6)
		return;
		
	this.getLastCurrency();
	document.write('<div id="' + this.Id + '">');
	document.write('<div id="' + this.dropDownId + '">');
	document.write('<a href="javascript:' + this.objectVariable + '.dropdown()">');
	document.write('<span class="selected">');
	if (this.lastCurrency == null || this.lastCurrency.description.length == 0)
		document.write(this.dropDownText);
	else
		document.write(this.lastCurrency.description);
	document.write('</span>');

	// Hack for inline-block business in ie
	if (this.ie7)
		document.write('<div class="dropLink" style="width:13px;display:inline; background-position: 4px 0.15em;">&nbsp;&nbsp;&nbsp;</div>');
	else
		document.write('<div class="dropLink">&nbsp;&nbsp;&nbsp;</div>');
	document.write('</a></div>');

	// Help icon
	if (this.helpUrl != null)
	{
		document.write('<a class="popUp" href="' + this.helpUrl + '"><img src="' + this.helpIcon + '" alt="Currency help" /></a>');
	}

	// Container for dropdown table
	document.write('<div id="' + this.dropDownGridId + '"></div>');
	document.write('</div>');

	/* Set up listeners for dropdowns */
	var scope = this
	$(document).click(function(event){
		if ( $(event.target).closest && $(event.target).closest('#' + scope.dropDownGridId).get(0) == null )
		$('#' + scope.dropDownGridId).empty().hide();
	});

	$('#' + this.dropDownGridId).click(function(event){
		event.stopPropagation();
	});
	
	// Update currency display if one saved in cookies
	$(document).ready(function() {
		if (scope.lastCurrency != null)
			scope.updateValues(scope.lastCurrency.code)
			
		scope.positionDropDown();
	});
	
	// Need to monitor client area resizing to reposition
	if (this.controlAlign != null)
	{
		$(window).resize(function() {
			scope.positionDropDown();
		});
	}
	
	// IE7 doesn't handle overlays and relative positions
	if (this.ie7)
	{
		var zIndexNumber = 1000;
		$('div').each(function() {
			$(this).css('zIndex', zIndexNumber);
			zIndexNumber -= 10;
		});
	}
}

/*
*	Positions the dropdown in relation to the configured control
*/
currencyConversion.prototype.positionDropDown = function ()
{
	if (this.controlAlignId == null)
		return;
	
	if (this.controlAlign == 'left')
		$("#" + this.Id).leftAlign($("#" + this.controlAlignId));
	else if (this.controlAlign == 'right')
		$("#" + this.Id).rightAlign($("#" + this.controlAlignId));
	else if (this.controlAlign == 'centre')
		$("#" + this.Id).centreAlign($("#" + this.controlAlignId));
}

/*
*	Drop downs the grid for selection of the currency
*/
currencyConversion.prototype.dropdown = function ()
{
	var html = '<table style="currency dropdown">'
	var rows = Math.round(this.items / this.dropDownColumns);
	for (var row = 0; row < rows; row++)
	{
		html += '<tr>'
		for (var col = 0; col < this.dropDownColumns; col++)
		{
			var position = row * this.dropDownColumns + col;
			if (position < this.items)
			{
				var currency = this.currencyArray[position];
				html += '<td nowrap="nowrap"><a href="javascript:' + this.objectVariable + '.dropdownSelect(\'' + currency.code +'\')">';
				if (currency.description.length == 0)
					html += '<strong>' + this.dropDownText + '</strong>';
				else
					html += currency.description 
				html += '</a></td>';
			}
			else
				html += '<td>&nbsp;</td>'
				
		}
		html += '</tr>'
	}
	html += '</table>'
	
	$('#' + this.dropDownGridId).html(html);
	// Align with the drop down
	var scope = this;
	if (this.dropAlign == "right")
		$('#' + this.dropDownGridId).rightDropAlign($("#" + scope.dropDownId));
	else if (this.dropAlign == "left")
		$('#' + this.dropDownGridId).leftDropAlign($("#" + scope.dropDownId));
	else if (this.dropAlign == "centre")
		$('#' + this.dropDownGridId).centreDropAlign($("#" + scope.dropDownId));
	else
		$('#' + this.dropDownGridId).dropAlign($("#" + scope.dropDownId));
}

/*
*	An item has been selected so update the display and remove the dropdown
*/
currencyConversion.prototype.dropdownSelect = function(code)
{
	var currency = this.getItem(code);
	if (currency.description.length == 0)
		$('#' + this.dropDownId + ' .selected').html(this.dropDownText);
	else
		$('#' + this.dropDownId + ' .selected').html(currency.description);
	$('#' + this.dropDownGridId).empty().hide();
	this.updateValues(code);
}

/*
*	Allows adding of currency items to the array
*/
currencyConversion.prototype.addItem = function (code, description, symbol)
{
	this.currencyArray[this.items++] = new currencyItem(code, description, symbol, this);
}

/*
*	Saves the last selected currency
*/
currencyConversion.prototype.saveLastCurrency = function (currency)
{
	if (this.cookieExpiration == 0)
		$.cookie(this.cookie, currency.code, { path: this.cookiePath });
	else if (this.cookieExpiration == -1)
		$.cookie(this.cookie, currency.code, { expires: 100, path: this.cookiePath });
	else
	{
		var date = new Date();
		date.setTime(date.getTime() + this.cookieExpiration * 60 * 1000);
		$.cookie(this.cookie, currency.code, { expires: date, path: this.cookiePath });
	}
}

/*
*	Loads the last selected currency from
*/
currencyConversion.prototype.getLastCurrency = function ()
{
	if (this.lastCurrency == null)
	{
		var lastCode = $.cookie(this.cookie, { path: this.cookiePath });
		this.lastCurrency = this.getItem(lastCode);
	}
	
	return this.lastCurrency;
}

/*
*	Returns the currency item for the specified currency code
*/
currencyConversion.prototype.getItem = function (code)
{
	for (var i = 0; i < this.items; i++)
	{
		var codeItem = this.currencyArray[i];
		if (codeItem.code == code)
			return codeItem;
	}
	
	return null;
}

/*
*	Updates the currency values of the marked up controls
*/
currencyConversion.prototype.updateValues = function (code)
{
	var currencyItem = this.getItem(code);
	currencyItem.getRateValue(this);
	this.saveLastCurrency(currencyItem);
}

/*
*	Receives the callback of the currency rate retrieval and updates the page values
*/
currencyConversion.prototype.outputValues = function (currencyItem)
{
	var conversion = this;

	$(conversion.currencySelector).each(function() {
		// Remove previous currency selection
		$(this).children("." + conversion.convertedClass).remove();

		if (currencyItem.rate != 0)
		{
			// Get the value of the product
			var value = $(this).html();
			value = value.match(/\d+([.]\d*)?/gi);
			if (value != null)
				$(this).append(currencyItem.convertedHtml(value));
		}
	});
	if (currencyItem.code != '')
		$(this.currencyWarningStyle).show();
	else
		$(this.currencyWarningStyle).hide();
}

/*
*	Gets the conversion rate for the current currency item
*/
currencyItem.prototype.getRateValue = function ()
{
	if (this.rate == 0)
	{
		// Need to get rate from web service
		var item = this;
		$.get(this.convertor.lookupUrl + "?code=" + item.code, function(response) {
			item.rate = parseFloat(response);
			item.storeRateValue();
			item.convertor.outputValues(item);
		});
	}
	else
		this.convertor.outputValues(this);
}

/*
*	Returns the converted currency value
*/
currencyItem.prototype.convert = function (value)
{
	return $().formatPrice(this.rate * value);
}
		
/*
 * Stores the rate value to a cookie
 */
currencyItem.prototype.storeRateValue = function ()
{
	// Expire in configured period
	var date = new Date();
	date.setTime(date.getTime() + this.convertor.rateCookieExpiration * 60 * 1000);
	var rateStore = '' + this.rate;
	$.cookie(this.cookie, rateStore, { expires: date, path: this.convertor.cookiePath } );
}

/*
 *	Retrieve the exchange rate from a cookie value
 */
currencyItem.prototype.getRateFromCookies = function ()
{
	var cookieValue = $.cookie(this.cookie, { path: this.convertor.cookiePath });
	if (cookieValue == null)
		return 0;
	return parseFloat(cookieValue);
}

/*
*	Returns html to output the converted value
*/
currencyItem.prototype.convertedHtml = function (value)
{
	return ' <span class="' + this.convertor.convertedClass + '">('  + this.symbol + this.convert(value) + ')</span>';
}

// Store list of currencies for conversion
var currencies = new currencyConversion();
currencies.defaultCurrencies();

