////////////////////////////////////
// Exchange Rate Helpers
////////////////////////////////////

// Variables for chart history graphs.
var flipped = false;
var selectedDaysHistory = 365;

function Convert ()
{
	// Text entry boxs must be called start and finish
	var start = getObjectById('start');
	var finish = getObjectById('finish');

	if (!isNaN(start.value)) {
		finish.value = ConvertTo(start.value);

		getObjectById('FromCurrencySymbol').innerHTML = '&nbsp;' + C2Symbol;
		getObjectById('ToCurrencySymbol').innerHTML = '&nbsp;' + C1Symbol;
	}
	else 
	{
	    ShowNaNAlert(start);
	}
}

function InvConvert ()
{
	// Text entry boxs must be called start and finish
	var start = getObjectById('start');
	var finish = getObjectById('finish');

	if (!isNaN(start.value)) 
	{
		finish.value = ConvertFrom(start.value);

		getObjectById('FromCurrencySymbol').innerHTML = '&nbsp;' + C1Symbol;
		getObjectById('ToCurrencySymbol').innerHTML = '&nbsp;' + C2Symbol;
	}
	else 
	{
	    ShowNaNAlert(start);
	}
}

function ConvertTo (amount)
{
	return Math.round((exchangeRate * amount)*100)/100;
}

function ConvertFrom (amount)
{
	return Math.round((invExchangeRate * amount)*100)/100;
}

function ShowNaNAlert(startTextBox) 
{
	alert('The value entered is not a number, please enter only numeric values. e.g. 34.53');
	startTextBox.focus();
	startTextBox.select();
}

// Calculator History functions.
function getObjectById( id )
{
	if (document.getElementById) 
	{
		return document.getElementById(id);
	}
	else if (document.all) 
	{
		return document.all[id];
	}
	else if (document.layers) 
	{
		return document.layers[id];
	}
	return null;
}

function validateInput(textBox) 
{
	var errorBox = getObjectById("ErrorMessage1");

	if (isNaN(textBox.value)) {
		//alert('The value entered is not a number, please enter only numeric values. e.g. 34.53');
		textBox.style.backgroundColor = "#FF0000";
		errorBox.style.visibility = "visible";
		errorBox.style.display = "block"; 
		errorBox.innerHTML = "The value entered is not a number, please enter only numeric values. e.g. 1234.56";
	} 
	else 
	{
		textBox.style.backgroundColor = "#FFFFFF";
		errorBox.style.display = "none";
		errorBox.innerHTML = "";
	}

	var outputBox = getObjectById("finish");
	outputBox.value="";
}

function setupPermaLink(fromCurrency, toCurrency, fromSymbol, from, toSymbol, to, converterUrl) 
{
    var permaLink = document.getElementById("permalink");

    permaLink.title = "Permalink for the conversion of " + fromCurrency + " " + from + " to " + toCurrency;
    permaLink.href = getPermaLink(fromCurrency, toCurrency, from);

    var permalinkSpan = document.getElementById("permalinkSpan");
    permalinkSpan.style.display = "";
}

function setupTwitterLink(fromCurrency, toCurrency, amount, convertedAmount) {

    var twitterLinkSpan = document.getElementById("tweetAmountLinkSpan");
    twitterLinkSpan.style.display = "";

    var twitterLink = document.getElementById("tweetAmountLink");

    twitterLink.title = "Tweet this";
    // TODO: Replace the short link with a link to twitter.
    var link = "http://twitter.com/home?status=Conversion of ";
    link+= fromCurrency + " " + amount;
    link+= " is about " + toCurrency + " " + convertedAmount 
    link+= " - " + getShortLinkForAmount(fromCurrency, toCurrency, amount);
    twitterLink.href = link;
    twitterLink.target = "_blank";
}

function AddConverstionToTable(currency, toCurrency, fromSymbol, from, toSymbol, to, converterUrl) 
{
    if (isNaN(to) || isNaN(from)) 
    {
        return false;
    }

    // Get the perma link to use.
    var url = getPermaLink(currency, toCurrency, from);

	var fromCell = document.createElement("TD");
	fromCell.innerHTML += '<a href="' + encodeURI(url) + '" class="PopupLink" target="_blank">' + fromSymbol + from + '</a>';

	var middleCell = document.createElement("TD");
	middleCell.innerHTML = '=';
	
	var toCell = document.createElement("TD");
	toCell.innerHTML = toSymbol + to;

	var notes = document.createElement("TD");
	notes.innerHTML = '<input type="text" value="Add notes here." onclick="clearIfDefault(this);return false;" />';

	var row = document.createElement("TR");
	row.appendChild(fromCell);
	row.appendChild(middleCell);
	row.appendChild(toCell);
	row.appendChild(notes);

	var tbody = document.getElementById("historyTable").getElementsByTagName("tbody")[0];
	
	// Append at the bottom
	tbody.appendChild(row);
}

function clearIfDefault(textBox) {
    if (textBox.value == 'Add notes here.') {
        textBox.value = "" 
    }
}

function getPopupLink(converterUrl, fromCurrency, amount) {
    return converterUrl + '?Base=' + fromCurrency + '&amp;Amount=' + amount + '&amp;Source=' + siteName;
}

function getPermaLink(fromCurrency, toCurrency, amount) {
    return '/Convert/' + fromCurrency + '/' + toCurrency + '/' + amount;
}

function getShortLink(fromCurrency, toCurrency) {
    return 'http://d2p.cc/' + fromCurrency + '/' + toCurrency;
}

function getShortLinkForAmount(fromCurrency, toCurrency, amount) {
    return 'http://d2p.cc/' + fromCurrency + '/' + toCurrency + '/' + amount;
}

function ConvertC1toC2() 
{
    try 
	{
	    InvConvert(); 
		
		var startValue = getObjectById('start').value;
		var amount = ConvertFrom(startValue);

		setupPermaLink(C1Currency, C2Currency, C1Symbol, startValue, C2Symbol, amount, ConverterUrl);
		setupTwitterLink(C1Currency, C2Currency, startValue, amount);
		AddConverstionToTable(C1Currency, C2Currency, C1Symbol, startValue, C2Symbol, amount, ConverterUrl);
		
		return false;
	}
	catch (ex)
	{
		alert(ex.description);
	}	
}

function ConvertC2toC1() 
{
    try
	{
	    Convert(); 
		
		var startValue = getObjectById('start').value;
		var amount = ConvertTo(startValue);

		setupPermaLink(C2Currency, C1Currency, C2Symbol, startValue, C1Symbol, amount, ConverterUrl);
		setupTwitterLink(C2Currency, C1Currency, startValue, amount);
		AddConverstionToTable(C2Currency, C1Currency, C2Symbol, startValue, C1Symbol, amount, ConverterUrl);
		
		return false;
	}
	catch (ex)
	{
	    alert(ex.description);
	}
}

function SelectHistoryRow() 
{
	//alert("hello");
	var sourceElement = event.srcElement;
	sourceElement.ClassName="Selected";
}

// Update the exchange rate values shown.
// This is called by a timer update.
function UpdateExchangeRate() {
    // TODO: Update the exchange rate to get the latest rate.

    // Force and update to the current charts so they get refreshed.
    selectChart(selectedDaysHistory);
}

// Get the currency fragment used to generate the image url of the chart.
function getChartCurrencyFragment() {
    if (flipped) {
        return C1Currency + "-" + C2Currency;
    } else {
        return C2Currency + "-" + C1Currency;
    }
}

function getLinkUrl() {
    var currencyFragment;
    if (flipped) {
        currencyFragment = "C1=" + C1Currency + "&C2=" + C2Currency;
    } else {
        currencyFragment = "C1=" + C2Currency + "&C2=" + C1Currency;
    }
    return "./ExchangeRateChart.aspx?" + currencyFragment + "&Days=" + selectedDaysHistory;
}

// select the chart for the daysHistory chosen.
function selectChart(daysHistory) {
    selectedDaysHistory = daysHistory;
    var imageSource = "http://forexcharts.s3.amazonaws.com";
    var chartCurrencies = getChartCurrencyFragment();
    // Append a timestamp to ensure the chart is not cached.
    var imageUrlTimeStampParameter = "?timestamp=" + new Date().getTime();
    var imageUrl = imageSource + "/HistoryChart-" + chartCurrencies + "-" + daysHistory + "-days.png" + imageUrlTimeStampParameter;

    var imageLink = getLinkUrl();

    $('#historyChart')
                .attr('src', imageUrl)
                .attr('alt', 'exchange rate history chart for the last ' + selectedDaysHistory)
                .attr('width', 600)
                .attr('height', 444);

    $('#chartLink')
                .attr('href', imageLink);
}