var currency_symbols = {
	'EUR' : '&#8364;',
	'USD' : '&#36;'
};

var MAX_LOAD_AMOUNT = 3000.0;
var MAX_LOAD_AMOUNT_US = 4000.0;

var DEFAULT_LOAD_AMOUNT = 10.0;

function setInitialCookies(){
	var refcode = getQueryParameter('refcode');
	
	if (refcode && refcode != ''){
		// we have a refcode, set a cookie
		createCookie('refcodecookie',refcode,30);
	}
	
	var offer = getQueryParameter('offer');
	if (offer && offer != ''){
		// we have a refcode, set a cookie
		createCookie('offercookie',offer,30);
	}
}

function getCurrentOffer(){
	var offer = readCookie('offercookie');
	if (offer== null){
		offer = 'MTCSTD';
	}
	
	return offer;
}

function getRefcode(){
	var refcode = '';
	
	refcode = readCookie('refcodecookie');
	if (refcode== null){
		refcode = '';
	}
	
	return refcode;
}

var conversionRate = 1;
var paymentCurrency = "GBP";
var cardCurrency;

function updateRates() {
	cardCurrency = $("#cardcurrency").val();
	
	//cardcurrency can be null for redeem pages
	if(!cardCurrency){
		return;
	}
	var programme = 'MTCERO';

	if (cardCurrency == 'EUR'){
		programme = 'MTCERO';
	}else if (cardCurrency == 'USD'){
		programme = 'MTCUSD';
	}
	$('#programme').val(programme);
	
	$("#to_currency").html(currency_symbols[$('#cardcurrency').val()]);
	$('#buy_currency_symbol').html(currency_symbols[$('#cardcurrency').val()]);
	

	var dataString =  'offer='+ getCurrentOffer()+'&srcCurrency='+ paymentCurrency + '&destCurrency='+ cardCurrency ;
	$.ajax({
		type: "POST",
		//../CPCardWeb/fxconversion.htm?currency=EUR&amount=100
		url: "../CPCardWeb/fxconversion.htm",
		data: dataString,
		success: function(msg) {
			conversionRate = parseFloat($("rate",msg).text());
		
			convRateFixed = conversionRate.toFixed(4);
			$("#exchange_rate").html(convRateFixed);
			// the following is used on new pages
			$("#internet_rate1").html(convRateFixed);
			$("#internet_rate2").html(convRateFixed);
			
			if ($('#quote_spend_amount').val()){
				updateBuyAmount();
			}else if ($('#amount').val()){
				updateSpendAmount();
			}
		}
	});
}

function updateSpendAmount(){
	var from_amount, to_amount;
	
	if(this.value){
		to_amount = parseFloat(this.value.replace(/,/g, ''));
	}else {
		to_amount = parseFloat($('#amount').val().replace(/,/g, ''));
	}
	
	if (isNaN(to_amount)){
			to_amount = 0.0;
	}
	
	var maxAmount = getMaxLoadAmount();
	if(to_amount > maxAmount){
		to_amount = maxAmount;
		$('[name=amount]').val(to_amount.toFixed(2));
	}
	
	from_amount = to_amount / conversionRate;

	if (!from_amount || !to_amount) { return; }

	$("#from_amount").html(from_amount.toFixed(2));
	$("#to_amount").html(to_amount.toFixed(2));
	$('[name=quote_spend_amount]').val(from_amount.toFixed(2));
	$("#total_saving").html("Save &#163;" + (from_amount * 0.0756).toFixed(1));
	
	//this is needed for the landing page
	$("#total_amount").html(from_amount.toFixed(2));
}

function updateBuyAmount(){
	var from_amount, to_amount;

	if(this.value){
		from_amount = parseFloat(this.value.replace(/,/g, ''));
	}else {
		from_amount = parseFloat($('#quote_spend_amount').val().replace(/,/g, ''));
	}
	if (isNaN(from_amount)){
			from_amount = 0.0;
	}
		
	to_amount = from_amount * conversionRate;
	var maxAmount = getMaxLoadAmount();
	
	if(to_amount > maxAmount){
		to_amount = maxAmount;
		from_amount = to_amount / conversionRate;
		$('[name=quote_spend_amount]').val(from_amount.toFixed(2));
	}
	if (!from_amount || !to_amount) { return; }

	$("#from_amount").html(from_amount.toFixed(2));
	$("#to_amount").html(to_amount.toFixed(2));
	$('[name=amount]').val(to_amount.toFixed(2));
	$("#total_saving").html("Save &#163;" + (from_amount * 0.0756).toFixed(1));
	
	//this is needed for the landing page
	$("#total_amount").html(from_amount.toFixed(2));
}

function getMaxLoadAmount()
{
	if (cardCurrency == 'USD'){
		return MAX_LOAD_AMOUNT_US;
	}

	return MAX_LOAD_AMOUNT;
}

/*
	retrieves all fx rates from 
*/
function retrieveRates(sourceCurrencyArray, destCurrencyArray, successFunction){
	var params = {'srcCurrency':sourceCurrencyArray, 'destCurrency':destCurrencyArray};

	var dataString = jQuery.param(params);

	$.ajax({
		type: "POST",
		//../CPCardWeb/fxrates.htm?srcCurrency=EUR&srcCurrency=USD&destCurrency=GBP
		url: "../CPCardWeb/fxrates.htm",
		data: dataString,
		success: function(msg) {
			if(jQuery.isFunction(successFunction)){
				successFunction.call(this,new Rates(msg));
			}
		}
	});
}

// this is used for old rates table
function processRates(rates){
		$("p#lastupdated").html('Rates updated ' + rates.lastUpdated);
		var baseAmount = 1000.0;
		var numOtherRates = 0;
		var eurSavings = 0.0;
		var usdSavings = 0.0;
		
		var crpEurAmountToShow = 0;
		var crpUsdAmountToShow =0;

		for(i = 0; i < rates.providers.length; i++){
			var aProvider = rates.providers[i];
			if (aProvider.name == 'CRP'){
				// this is CP provider

				var crpEURGBPRate = '';
				var crpUSDGBPRate = '';

				for (j = 0 ; j < aProvider.allRates.length ; j++){
					var aRate = aProvider.allRates[j];
					if (aRate.toCurrency == 'EUR'){
						crpEURGBPRate = aRate.rate;
					}else if (aRate.toCurrency == 'USD'){
						crpUSDGBPRate = aRate.rate;
					}
				}
				
				var crpEurAmountToShow = parseFloat(crpEURGBPRate * baseAmount).toFixed(0);
				var crpUsdAmountToShow = parseFloat(crpUSDGBPRate * baseAmount).toFixed(0);
				
				$("#crpgbpeur").html('&#8364; ' + crpEurAmountToShow);
				$("#crpgbpusd").html('&#36; '+ crpUsdAmountToShow);
			}else {
				if(numOtherRates >= 3){
					continue;
				}

				// some other provider
				var otherEURGBPRate = '';
				var otherUSDGBPRate = '';

				for (j = 0 ;j < aProvider.allRates.length ; j++){
					var aRate = aProvider.allRates[j];
					if (aRate.toCurrency == 'EUR'){
						otherEURGBPRate = aRate.rate;
					}else if (aRate.toCurrency == 'USD'){
						otherUSDGBPRate = aRate.rate;
					}
				}
				
				var eurAmountToShow = parseFloat(baseAmount * otherEURGBPRate).toFixed(0);
				var usdAmountToShow = parseFloat(baseAmount * otherUSDGBPRate).toFixed(0);
				
				$("tr#otherrate" + numOtherRates).replaceWith('<tr><td class="provider">' + aProvider.name +
						'</td><td class="gbp_eur_rate">&#8364; ' +
						eurAmountToShow +
						'</td><td class="gbp_usd_rate">&#36; ' +
						usdAmountToShow  +
						'</td></tr>');

				if(eurSavings  < (crpEurAmountToShow - eurAmountToShow)){
					eurSavings = crpEurAmountToShow - eurAmountToShow;
				}
				if(usdSavings  < (crpUsdAmountToShow - usdAmountToShow)){
					usdSavings = crpUsdAmountToShow - usdAmountToShow;
				}
						
				numOtherRates++;
			}
		}
		
		$("#savingseur").html('&#8364; '+ parseFloat(eurSavings).toFixed(0));
		$("#savingsusd").html('&#36; '+parseFloat(usdSavings).toFixed(0));
}


// this is used for new rates graph
function processRates2(rates){

		var baseAmount = 500;
		// display 4 rates 
		var allRates = new Array(4);						

		var minRate = 100;
		for(i = 0; i < rates.providers.length; i++){
			var aProvider = rates.providers[i];
			var aRate = aProvider.allRates[0].rate;
			allRates[i] = {'name':aProvider.name, 'rate': aRate};
			if(aRate < minRate ){
				minRate = aRate;
			}
		}

		// sort the rates now
		for(i = 0; i < allRates.length; i++){
			for ( j = i + 1; j < allRates.length; j++){
				if(allRates[i].rate < allRates[j].rate){
					var temp = allRates[i];
					allRates[i] = allRates[j];
					allRates[j] = temp; 
				}
			}
		}
		
		//  updating comparison graph
		// lose the sign on the last one as value very close to zero could be shown as -0.0
		var comparison = 	{ 	'last_updated':  rates.lastUpdated,
								'mtc': (baseAmount - (baseAmount * minRate)/allRates[0].rate),
								'rate1': (baseAmount - (baseAmount * minRate)/allRates[1].rate),
								'rate2': (baseAmount - (baseAmount * minRate)/allRates[2].rate),
								'rate3': Math.abs(baseAmount - (baseAmount * minRate)/allRates[3].rate)};
			
		var max_bar = 100;
		var mtc_bar = $("#mtc_bar");

		mtc_bar.css('width',max_bar+'px');
		mtc_bar.html('&pound;'+comparison.mtc.toFixed(2));
		
		var po_bar_px = (comparison.rate1* (max_bar/comparison.mtc));
		var po_bar  = $("#po_bar");

		po_bar.css('width',po_bar_px.toFixed(0)+'px');

		if(po_bar_px > 50){
			po_bar.html('&pound;'+comparison.rate1.toFixed(2));
		}else{
			$("#po_figs").html('&pound;'+comparison.rate1.toFixed(2));
		}
		
		
		var tr_bar_px = (comparison.rate2* (max_bar/comparison.mtc));
		var tr_bar = $("#tr_bar");
		
		tr_bar.css('width',tr_bar_px.toFixed(0)+'px');

		if(tr_bar_px > 50){
			tr_bar.html('&pound;'+comparison.rate2.toFixed(2));
		}else{
			$('#tr_figs').html('&pound;'+comparison.rate2.toFixed(2));
		}
		
		var ms_bar_px = (comparison.rate3* (max_bar/comparison.mtc));
		var ms_bar = $("#ms_bar");
		
		ms_bar.css('width',ms_bar_px.toFixed(0)+'px');

		if(ms_bar_px > 50){
			ms_bar.html('&pound;'+comparison.rate3.toFixed(2));
		}else{
			$('#ms_figs').html('&pound;'+comparison.rate3.toFixed(2));
		}

		$("#rate1_label").html(allRates[1].name);
		$("#rate2_label").html(allRates[2].name);
		$("#rate3_label").html(allRates[3].name);
		$("#last_updated").html(comparison.last_updated);
}

/*
Login form display script
*/
$(function(){
	// login form dropdown
	$('#header_log_in_button').click(function(){
		document.location = 'https://www.prepaycardservices.com/CPCardWeb/home.htm?programme=MTCERO&ver2';
	});
	
	$('#header_activate_button').click(function(){
		document.location = 'https://www.prepaycardservices.com/CPCardWeb/activate_card.htm?programme=MTCERO&ver2';
	});

	$('#header_topup_button').click(function(){
		document.location = 'https://www.prepaycardservices.com/CPCardWeb/topup_card.htm?programme=MTCERO&ver2';
	});
	
	
	$('#usp1orderlink,#usp2orderlink,#usp3orderlink,#order_now').click(function(){

		var formAction = "https://www.prepaycardservices.com/CPCardWeb/buycard.htm";	
		if(pageTracker){
			pageTracker._trackPageview('/buy' + location.pathname);
			formAction = pageTracker._getLinkerUrl(formAction,false);
		}
		
		var quoteForm = $("form[name= 'form_fx']");
		quoteForm.attr("action",formAction);
		$("#quote_form").submit();

		return false;
	});

	
	$("select#cardcurrency").change(updateRates);

	$("[name=amount]").keyup(updateSpendAmount);
	$("[name=quote_spend_amount]").keyup(updateBuyAmount);
	
	$("[name=quote_spend_amount], [name=amount]").keypress(function (e)  {
		var ascii_value = (e.which || e.keyCode);
		
		if (ascii_value > 8
		    && (!String.fromCharCode(ascii_value).match(/[0-9.,]/))){
			return false;
		}else {
			return true;	
		}
	});

	setInitialCookies();
	$("[name=quote_spend_amount]").val(DEFAULT_LOAD_AMOUNT);
	updateRates();
	
	$('[name=offer]').val(getCurrentOffer());
	$('[name=refcode]').val(getRefcode());
	
	$("#intro").cycle({
		timeout       : 5000,
		speed         : 500,
		slideExpr     : "img.banner",
		pause         : true,
		cleartype     : false,
		cleartypeNoBg : false
	});


	$("#testimonial_banners").cycle({
		timeout       : 5000,
		pause         : true,
		cleartype     : false,
		cleartypeNoBg : false,
		random  	  : 0
	});

	$('#username_tooltip').tooltip({
		delay       : 0,
		showURL     : false,
		track       : true,
		bodyHandler : function()
		{
			return 'You will have received your username and passcode when you purchased your card.<br /><br />'
			       + 'Please contact us if you need any help.';
		}
	});
	
});


