// ==============================================================================================
//
//  RBTT Exchange Rates Processing v1.0
//		- written by Rob Robichaud / April 20th 2010
//		- detects current country
//		- detects if output is required (looks for right nav id or full table id)
//		- processes appropriate output for right nav or full table
//
//  RBTT Exchange Rates Processing v1.1
//		- Updated by Rob Robichaud /July 29th 2010
//		- added logic to swap '$' with 'Afl.' for Aruba, 'ANG' for Curacao and Bonaire, 
//		  'SRD' for Suriname, 'ANG' for St. Maarten/Saba on Full Rates Table.
//		  for the right nav we simply remove the '$' symbol.
//
//	Dependencies:
//		- jQuery v1.4.1
//		- correct XML source paths and country association (array)
//		- correct output IDs
//
// ==============================================================================================

	var exchRateXMLSource;
	var exchRateOutputID;
	var exchRateRightNavID = "#exchange_rates_rn";
	var exchRateFullTableID = "#exchange_rates_full";
	var exchRateCurCountry;

	var erCountryXML=new Array(8);
	
	for (i = 0; i < erCountryXML.length; ++ i) {
		erCountryXML[i] = new Array(1)
	}
	
	erCountryXML[0][0]="ar"; 	// Aruba
	erCountryXML[0][1]="/ar/file-503965.xml";
	erCountryXML[1][0]="bb";	// Barbados
	erCountryXML[1][1]="/bb/file-503968.xml";
	erCountryXML[2][0]="an";	// Curacoa and Bonaire
	erCountryXML[2][1]="/an/file-503969.xml";
	erCountryXML[3][0]="jm";	// Jamaica
	erCountryXML[3][1]="/jm/file-504052.xml";
	erCountryXML[4][0]="sxm";	// St. Martaan and Saba
	erCountryXML[4][1]="/sxm/file-503971.xml";
	erCountryXML[5][0]="sr";	// Suriname
	erCountryXML[5][1]="/sr/file-503972.xml";
	erCountryXML[6][0]="tt";	// Trinidad and Tobago
	erCountryXML[6][1]="/tt/file-503735.xml";
	erCountryXML[7][0]="ec";	// Eastern Caribbean
	erCountryXML[7][1]="/ec/file-503970.xml";


// ==============================================================================================
//
//  Browser Console / Log Function - So error is not thrown if not console not present
//
// ==============================================================================================

	function devConsole(msg) {
		if (typeof(console) !== 'undefined' && console != null) {
			console.log(msg);
		}	
	}


// ==============================================================================================
//
//  Grab Country Code from URL
//
// ==============================================================================================

	function getURLCountryCode() {
		var urlPath = document.location.pathname.toLowerCase(); // grab the URL
		var urlPathArray = urlPath.split('/'); // split URL into an array
		var urlCountryCode = urlPathArray[1];
		
		return urlCountryCode;
	}


// ==============================================================================================
//
//  Document Ready
//
// ==============================================================================================

	$(document).ready(function() {
			
		// process xml only if right nav or full table id exists
		if ( ($(exchRateRightNavID).length) || ($(exchRateFullTableID).length) ) {
			
			// determine output ID (right nav or full table)
			($(exchRateRightNavID).length) ? exchRateOutputID = exchRateRightNavID : exchRateOutputID = exchRateFullTableID;
			// devConsole('Output ID: ' + exchRateOutputID);
			
			exchRateCurCountry = getURLCountryCode();
			
			// determine what XML file to process
			for (var i in erCountryXML) {
				if (exchRateCurCountry == erCountryXML[i][0]) {
					exchRateXMLSource = erCountryXML[i][1];
					// devConsole('CountryMatch: ' + erCountryXML[i][0] + ' | ' + erCountryXML[i][1]);
					break;
				}
			}			
			
			// this method of doing the ajax call is a little beefier than required.  
			//	- allows us to test local XML files as well with IE
			//	- allows us to pass addtional arguments with the success / error functions.
			$.ajax({
				type: "GET",
				url: exchRateXMLSource,
				cache: true,
				dataType: ($.browser.msie) ? "text/xml" : "xml",
				success: function(data) {
							var xml;
							if (typeof data == "string") {
								xml = new ActiveXObject("Microsoft.XMLDOM");
								xml.async = false;
								xml.loadXML(data);
							} else {
								xml = data;
							}
							exchangeXmlToTable(xml, exchRateOutputID);
				},
				error: function(xhr, textStatus, errorThrown) {
							// devConsole('Problem Occured: \n' + xhr.statusText + " | " + textStatus + " | " + errorThrown);
							XMLErrorMsg(exchRateOutputID);
				}
			});
		
		} 
		
	});
	
	
// ==============================================================================================
//
//  Exchange Rate XML to Right-Nav Table
//
// ==============================================================================================
	
	
	function exchangeXmlToTable(xmlData, targetID) {
			
		var counter = 0;
		var countLimit = 0;
		var updatedOn = $(xmlData).find("rbtt_exchange_rates").attr("createdon");
		var updatedOnColSpan;
		var countryCode = $(xmlData).find("rbtt_exchange_rates").attr("countrycode");
		var tableHTML;
		var trRowClass = "";
		var rightNavOutput = false;
		var curSymbol = "$";
		
		// Check if this is for RightNav output or not.
		if($(exchRateRightNavID).length) {
			rightNavOutput = true;
			countLimit = $(xmlData).find("rbtt_exchange_rates").attr("displaytopqty");
			// devConsole("Right Nav Qty: " + countLimit);
		} 
		
		switch (exchRateCurCountry) {
			case 'ar':	// Aruba
				if (rightNavOutput) {
					curSymbol = "";
				} else {
					curSymbol = "AFL ";
				}
				break;
			case 'an':	// Curacao and Bonaire
				if (rightNavOutput) {
					curSymbol = "";
				} else {
					curSymbol = "ANG ";
				}
				break;
			case 'sr':	// Suriname
				if (rightNavOutput) {
					curSymbol = "";
				} else {
					curSymbol = "SRD ";
				}
				break;	
			case 'sxm':	// St. Maarten/Saba
				if (rightNavOutput) {
					curSymbol = "";
				} else {
					curSymbol = "ANG ";
				}
				break;				
			default:
				curSymbol = "$";
		}
			
		
		tableHTML = "<tbody class='contentframework-stripedtable'>";
					
		if (rightNavOutput) {
			
			updatedOnColSpan = "3"
			
			tableHTML += "<tr>"
						+ "<th class='contentframework-dataheadertop'>Code</th>"
						+ "<th class='contentframework-dataheadertop'>Buying</th>"
						+ "<th class='contentframework-dataheadertop'>Selling</th>"
						+ "</tr>";			
		} else {
			
			updatedOnColSpan = "5"
			
			tableHTML += "<tr>"
						+ "<th class='contentframework-dataheadertop'>Currency</th>"
						+ "<th class='contentframework-dataheadertop'>Code</th>"
						+ "<th class='contentframework-dataheadertop'>Buying<br/>Cash</th>"
						+ "<th class='contentframework-dataheadertop'>Buying<br/>Cheques &amp; Drafts</th>"
						+ "<th class='contentframework-dataheadertop'>Selling</th>"
						+ "</tr>";	
		}
		
		// loop through each listitem in the xml and grab the defined attributes
		$(xmlData).find("currency").each(function()
		{
			var curType = $(this).attr('type');
			var curCode = $(this).attr('code');
			var buyCash = $(this).find("cash").text();
			var buyCheque = $(this).find("cheque").text();
			var sell = $(this).find("sell").text();
			var noVal = "******";
			
			// determine if values need to be replaced by '******'
			((buyCash == "0.0000") || (buyCash == "")) ? buyCash = noVal : buyCash = curSymbol + buyCash;
			((buyCheque == "0.0000") || (buyCheque == "")) ? buyCheque = noVal : buyCheque = curSymbol + buyCheque;
			((sell == "0.0000") || (sell == "0.0000")) ? sell = noVal : sell = curSymbol + sell;
						
			// define CSS class for alternate rows
			(trRowClass == "contentframework-altrow") ? trRowClass = "" : trRowClass = "contentframework-altrow";		

			
			if (rightNavOutput) {
				tableHTML += "<tr class='" + trRowClass + "'>"
				tableHTML += "<td>" + curCode + "</td>";
				tableHTML += "<td>" + buyCash + "</td>";
				tableHTML += "<td>" + sell + "</td>";				
				tableHTML += "</tr>"

				counter++;
				// continues to loop if resolves to true, otherwise break.
				return (countLimit != counter);					
			
			} else {
				tableHTML += "<tr class='" + trRowClass + "'>"
				tableHTML += "<td>" + curType + "</td>";
				tableHTML += "<td>" + curCode + "</td>";
				tableHTML += "<td>" + buyCash + "</td>";
				tableHTML += "<td>" + buyCheque + "</td>";		
				tableHTML += "<td>" + sell + "</td>";				
				tableHTML += "</tr>"
			}

		});
		
		tableHTML += "<tr><td colspan='" + updatedOnColSpan + "' class='exch_updated'><strong>Updated: </strong>" + updatedOn + "</td></tr>";
		
		tableHTML += "</tbody>";
		
		$(targetID).html(tableHTML);
			
	}
	

// ==============================================================================================
//
//  Exchange Rate XML to Right-Nav Table
//
// ==============================================================================================

	// Problem occured with XML or data Connection
	function  XMLErrorMsg(targetID) {
		
		var colspan;
		
		if($(exchRateRightNavID).length) {
			colspan = "3";
		} else {
			colspan = "5"
		}
	
		// define error message
		errorMsg = "<tr><td class='xmlerrormsg' style='text-align:center;' colspan='" + colspan + "'>Error retrieving exchange rates</td></tr>";
		
		// append the target div with the error msg
		$(targetID).append(errorMsg);
	}	
