// Inpsired by and based on Pete Newnham's work. Thanks Pete for writing such a fantastic piece of code.

function convertRates(currency) {
	// create the XMLHTTPRequest object
	http_request = false;
	if (window.XMLHttpRequest) {
		http_request = new XMLHttpRequest();
	}
	else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	// Added in a timestamp to stop caching of the XML feed
	http_request.open('GET', "/scripts/currency.xml?uniq="+new Date().getTime(), true);
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			var xmlDoc = http_request.responseXML;
			var currencies = xmlDoc.documentElement.getElementsByTagName("currency");
			var spans = document.getElementsByTagName("span");	// find all span tags on the page
			for (var i=0;i<spans.length;i++) { // loop through them
				if (spans[i].className == "currency") { // if the span contains a rate
					amount = rates[i]; // get that rate in GBP from the rates array
					for (var j=0;j<currencies.length;j++) { // loop through all currencies
						c_name = currencies[j].getAttribute("name"); // get the currency name
						if (c_name == currency) { // if the currency is the same as the one selected
							var exchange_rate = currencies[j].getAttribute("rate"); // get the exchange rate
							var new_value = formatCurrency(amount * exchange_rate); // calculate the new rate
							// add the correct currency symbol
							switch (currency) {
								case "GBP":
									new_value = "£"+rates[i];
									break;
								case "USD":
									new_value = "$"+new_value;
									break;
								case "EUR":
									new_value = "€"+new_value;
									//"&#8364;"
									break;
								case "DKK":
									new_value = new_value+"DKK";
									break;
							}
							spans[i].firstChild.nodeValue = new_value; // update the rate with the new converted rate
						}
					}
				}
			}
		}
	}
	http_request.send(null);
	return true;
}

function formatCurrency(rate) {
	var rlength = 2; // The number of decimal places to round to
	if (rate > 8191 && rate < 10485) {
		rate = rate-5000;
		var newrate = Math.round(rate*Math.pow(10,rlength))/Math.pow(10,rlength);
	} else {
		var newrate = Math.round(rate*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	newrate = newrate + ""; // conver the number to a string
	if (newrate.indexOf(".") != -1) { // if there is a decimal place in the rate
		if (newrate.split(".")[1].length == 1) { // if there is only 1 digit after the decimal place
			newrate = newrate + 0 // add an extra 0 to the end of it
		}
	}
	return newrate;
}

// store all original rates in GBP in an array to make converting between currencies easier
var rates = new Array();
function prepareRates() {
	var spans = document.getElementsByTagName("span");
	for (var i=0;i<spans.length;i++) {
		if (spans[i].className == "currency") {
			var amount = spans[i].firstChild.nodeValue;
			rates[i] = amount.split("£")[1].replace(/,/,"");
		}
	}
	if (getCookie("currencyrate")!=null) {
		convertRates(getCookie("currencyrate"))
	}
}

function switchCurrency(clicked) {
	clicked_title = clicked.getAttribute("title");
	// change the active currency message
	var cmsg = document.getElementById("currencymsg");
	cmsg.lastChild.nodeValue = "All rates are shown in "+clicked_title
}

function createLink(currency) {
	var new_element = currency.cloneNode(true);
	return new_element
}


// TOOL TIP FUNCTIONS

function tip(msg,myEvent){
	scrollposY=0;
	if (window.pageYOffset){
		scrollposY = window.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop){
		scrollposY = document.documentElement.scrollTop
	}
	else if (document.body.scrollTop){
		scrollposY = document.body.scrollTop;
	}


	document.getElementById("curmessage").innerHTML=msg;

	document.getElementById("tip").style.top = scrollposY + myEvent.clientY + 15+"px";
	document.getElementById("tip").style.left = myEvent.clientX - 25+"px";
	document.getElementById("tip").style.zIndex=9;
	document.getElementById("tip").style.visibility="visible";
}

function hide(){
	document.getElementById("tip").style.visibility="hidden";
}

function addConverter() {
	if (testBrowser()) {
		document.writeln("<p style='font-size:10px;' id='activecurrency'>");
		switch (getCookie("currencyrate")) {
			case "GBP":
				document.writeln("<span class='currencymsg' id='currencymsg'>All rates are shown in British Pounds</span>");
				break;
			case "USD":
				document.writeln("<span class='currencymsg' id='currencymsg'>All rates are shown in US Dollars</span>");
				break;
			case "EUR":
				document.writeln("<span class='currencymsg' id='currencymsg'>All rates are shown in Euros</span>");
				break;
			case "DKK":
				document.writeln("<span class='currencymsg' id='currencymsg'>All rates are shown in Danish Krone</span>");
				break;
			default:
				document.writeln("<span class='currencymsg' id='currencymsg'>All rates are shown in British Pounds</span>");
				break;
		}
		document.writeln("</p>");
		document.writeln("<div id='inactivecurrencies'>");
			document.writeln("<a href='#' onmousemove=\"tip('Show rates in '+this.getAttribute('title'),event)\" onmouseout=\"hide();\" onclick='currencyConverter(this.className);switchCurrency(this);return false;' class='GBP' title='British Pounds'><img src='images/flag-gbp.gif' /></a>");
			document.writeln("<a href='#' onmousemove=\"tip('Show rates in '+this.getAttribute('title'),event)\" onmouseout=\"hide();\" onclick='currencyConverter(this.className);switchCurrency(this);return false;' class='USD' title='US Dollars'><img src='images/flag-usd.gif' /></a>");
			document.writeln("<a href='#' onmousemove=\"tip('Show rates in '+this.getAttribute('title'),event)\" onmouseout=\"hide();\" onclick='currencyConverter(this.className);switchCurrency(this);return false;' class='EUR' title='Euros'><img src='images/flag-euro.gif' /></a>");
			document.writeln("<a href='#' onmousemove=\"tip('Show rates in '+this.getAttribute('title'),event)\" onmouseout=\"hide();\" onclick='currencyConverter(this.className);switchCurrency(this);return false;' class='DKK' title='Danish Krone'><img src='images/flag-denmark.gif' /></a>");
		document.writeln("</div>");
		document.writeln("<div id='tip' style='position:absolute;top:250px;left:250px;visibility:hidden;color:#000000;z-index:60;'><table border='0'><tr><td style='background-color:white;color:black;border:1px solid black;font-size:10px;white-space:nowrap' id='curmessage'><br/></td></tr></table></div>");
	}
}

function currencyConverter(currency) {
	document.cookie = "currencyrate="+escape(currency);
	convertRates(currency);
}

function getCookie(c_name)
{
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=")
  if (c_start!=-1)
    {
    c_start=c_start + c_name.length+1
    c_end=document.cookie.indexOf(";",c_start)
    if (c_end==-1) c_end=document.cookie.length
    return unescape(document.cookie.substring(c_start,c_end))
    }
  }
return null
}

// test that the broswer can handle all objects in the script
function testBrowser() {
	if ((window.XMLHttpRequest || window.ActiveXObject) && document.getElementsByTagName && document.getElementById) {
		return true;
	}
	else {
		return false;
	}
}
