var exchangeDataExpiry = 300000; // In milliseconds

/** Stores currency exchange data in a cookie
 */
function storeCurrencyExchangeData(amount, convData, country) {
	var name = getCurrencyExchangeDataName(amount, country);
	var expiryDate = new Date();
	expiryDate.setTime(expiryDate.getTime() + exchangeDataExpiry);
	jQuery.cookie(name, JSON.stringify(convData), { expires: expiryDate });
}

/** Gets currency exchange data from a cookie
 */
function getCurrencyExchangeData(amount, country) {
	var name = getCurrencyExchangeDataName(amount, country);
	var cookie = jQuery.cookie(name);
	if(cookie) {
		try {
			return JSON.parse(cookie);
		} catch(e) {
			return null;
		}
	}
	
	return null; // No cookie
} 	 

/** Returns the currency exchange data cookie name for the given amount and country.
 */
function getCurrencyExchangeDataName(amount, country) {
	return 'exchangedata-' + country + '-' + amount;
}

jQuery(document).ready(function(){
		jQuery('body').append('<div class="dialog-form" title="Choose your currency"><div class="LoadingCurrencies" style="display: none;"><img src="currency_converter/images/ajax-loader.gif" /> Loading Currencies...</div><form><fieldset><label for="country">Currencies: </label><select  name="country" class="CurrencyConvertCountries text ui-widget-content ui-corner-all"><option value="">choose a currency</option></select></fieldset></form></div>');
	
	var currencies = null;
	var disclaimerCloseTimer = null;
	
	jQuery(".dialog-form").dialog({
		autoOpen: false,
		modal: true, 
		width:500,
		buttons: {
			"Save": function() {
				var selectedCurrency = jQuery('.CurrencyConvertCountries :selected').val();
				if(selectedCurrency) {
					jQuery.cookie('selectedcurrency', selectedCurrency, { path: '/' });
				}
				jQuery(this).dialog("close");
				location.reload();
			},
			Cancel: function() {
				jQuery(this).dialog("close");
			}
		}
	});

	jQuery('.lnk-choose-currency').click(function(){
		jQuery("div.dialog-form").dialog('open');
		
		// Load the currencies
		if(!currencies){
			jQuery('.LoadingCurrencies').css('display', 'block');
			jQuery('div.dialog-form form').css('display', 'none');
			jQuery.getJSON('PPCurrencyConvert/getCurrencies', function(items){
				jQuery.each(items, function(i, item){
					jQuery('.CurrencyConvertCountries').append(jQuery('<option>', {
						value: item,
						text: i
					}));
				});
				currencies = items;
			})
			
			// Display
			jQuery('.LoadingCurrencies').css('display', 'none');
			jQuery('div.dialog-form form').css('display', 'block');
		}
		
		return false;
	});
	
	jQuery('.CurrencyConvertDisclaimerIcon').mouseover(function(event){
		if(jQuery('.CurrencyConvertFullDisclaimer')[0]) {
			if(disclaimerCloseTimer) {
				window.clearTimeout(disclaimerCloseTimer);
			}
			return true; 
		}
				
		jQuery('body').append('<div class="CurrencyConvertFullDisclaimer">IMPORTANT: Currency conversions are estimates only. The exchange rate may differ at transaction time.</div>');
		var disclaimer = jQuery('div.CurrencyConvertFullDisclaimer');
		var tPosX = event.pageX - 235;
		var tPosY = event.pageY + 20;
		disclaimer.css({'position': 'absolute', 'top': tPosY, 'left': tPosX});
		
		return true;
	}).mouseout(function(){
		disclaimerCloseTimer = window.setTimeout(function() {
			jQuery('.CurrencyConvertFullDisclaimer').remove();
		}, 500);
		
		return false;
	});
	
	jQuery(document).ready(function(){
		jQuery('body').bind('EcomCartUpdated UpdateCartCurrencyConversion', function(){ 
			if(jQuery.cookie('selectedcurrency') == 'NZD') {
				jQuery('.CartCurrencyConvert img').css('display', 'none');
				jQuery('.CartCurrencyConvert').css('display', 'none');
				return;
			}
			
			jQuery('CartCurrencyConvert img').css('display', 'inline');
			jQuery('CartCurrencyConvertDisplay').css('display', 'none');
			jQuery.ajax({
				type: 'POST',
				url: 'PPCurrencyConvert/getupdatedcartestimate/',
				data: {cookie: jQuery.cookie('selectedcurrency')},
				dataType: 'json',
				success: function(data) {
					jQuery('.CartCurrencyConvert img').css('display', 'none');
					if(data.success) {
						if(!jQuery.cookie('selectedcurrency')) { jQuery.cookie('selectedcurrency', data.countrycode, { path: '/' }); }
						if(data.countrycode != 'NZD') {
							jQuery('.CartCurrencyConvert img').css('display', 'none');
							jQuery('.CartCurrencyConvertDisplay').css('display', 'inline');
							jQuery('.CartCurrencyConvertSymbol').text(data.currencysymbol);
							jQuery('.CartCurrencyConvertSubTotal').text(data.subtotal);
							jQuery('.CartCurrencyConvertCode').text(data.countrycode);
							jQuery('.CartCurrencyConvertTotal').text(data.total);
						} else {
							jQuery('.CartCurrencyConvert img').css('display', 'none');
							jQuery('.CartCurrencyConvert').css('display', 'none');
						}
					} else {
						jQuery('.CartCurrencyConvert img').css('display', 'none');
						jQuery('.CartCurrencyConvertDisplay').css('display', 'inline');
						jQuery('.CartCurrencyConvertSymbol').text("N/A");
					}
				},
				error: function(data){
					jQuery('.CartCurrencyConvert img').css('display', 'none');
					jQuery('.CartCurrencyConvertDisplay').css('display', 'inline');
					jQuery('.CartCurrencyConvertSymbol').text("N/A");
				}
			});
		});			
		
		if(jQuery('.ajaxQuantityField')[0]){
			jQuery('body').trigger('UpdateCartCurrencyConversion');
		}
	});
});