/*
	jQuery Currency Converter Script v1.0.0
	by Matthew Wilkin (clients@cpradio.net)
	
	This script cannot be redistributed or sold without the author's consent/permission.
*/
jQuery.fn.extend(
	{
		convertCurrency:
			function(options)
			{
				var htmlTag = 'span';
				var prefixText = ' convert to ';
				var multiplePricesDropDownLocation = null;
				var acceptedCurrencies = {'USD': {name:'United States',format:'$###,###,###.##'}, 'GBP': {name:'Great Britain',format:'&pound;###.###.###,##'}};
				var roundToNearestDollar = false;
				
				if (options != null)
				{
					if (options['htmlTag'] != null)
					{
						htmlTag = options['htmlTag'];
					}
					
					if (options['prefixText'] != null)
					{
						prefixText = options['prefixText'];
					}
					
					if (options['currencies'] != null)
					{
						acceptedCurrencies = options['currencies'];
					}
					
					if (options['roundToNearestDollar'] != null)
					{
						roundToNearestDollar = options['roundToNearestDollar'];
					}
					
					if (options['multiplePricesDropDownLocation'] != null)
					{
						multiplePricesDropDownLocation = options['multiplePricesDropDownLocation'];
					}
				}
				
				if (multiplePricesDropDownLocation != null
					&& multiplePricesDropDownLocation.length == 1) // Show the drop down once on the page
				{					
					if (multiplePricesDropDownLocation.parent().find('select.currencyConverter').length == 0)
					{
						var primaryCurrency = {code: ($(this).attr('rel')) ? $(this).attr('rel') : '', thousands: ',', decimal: '.'};
						
						if (options != null)
						{
							if (options['primaryCurrency'] != null)
							{
								primaryCurrency = options['primaryCurrency'];
							}
						}
						
						var prefixTextElement = $('<' + htmlTag + '></' + htmlTag + '>');
						prefixTextElement.text($.trim(prefixText) + " ");
						prefixTextElement.addClass('multiplePricesHolder');
						
						var htmlElement = $('<select></select>');
						htmlElement.addClass('currencyConverter');
						htmlElement.attr('rel', primaryCurrency['code'].toUpperCase() + "|" + primaryCurrency['thousands'] + "|" + primaryCurrency['decimal']);
						if (roundToNearestDollar)
						{
							htmlElement.addClass('roundToNearestDollar');
						}
						
						for (currencyType in acceptedCurrencies)
						{
							var selectOption = $('<option></option>');
							selectOption.text(acceptedCurrencies[currencyType]['name']);
							selectOption.val(currencyType.toUpperCase() + "|" + acceptedCurrencies[currencyType]['format']);
							htmlElement.append(selectOption);
						}
						
						prefixTextElement.append(htmlElement);
						prefixTextElement.insertAfter(multiplePricesDropDownLocation);
						
						$(this).each
						(
							function()
							{
								var currentContent = $(this).text();
								if ($.trim(currentContent.replace(/[^0-9]+/g, '')).length != 0)
								{
									$(this).html('');
									
									var moveContent = $('<' + htmlTag + '></' + htmlTag + '>');
									moveContent.addClass('currencyAmount');
									moveContent.html(currentContent);
									$(this).append(moveContent);
									
									var hiddenElement = $('<input />');
									hiddenElement.attr('type', 'hidden');
									hiddenElement.val(currentContent);
									hiddenElement.addClass('currencyHiddenField');
									hiddenElement.insertAfter(moveContent);
								}
							}
						);
						
						htmlElement.bind('change',
							function()
							{
								var currencyInfo = $(this).val().split('|');
								var selectedCurrency = currencyInfo[0].toUpperCase();
								var primaryCurrency = $(this).attr('rel').split('|');
								var roundToNearestDollar = $(this).hasClass('roundToNearestDollar');
								var convertedAmount = $(this).parent().parent().find('.currencyAmount');
								var hiddenAmount = $(this).parent().parent().find('.currencyHiddenField');
								
								var yahooUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20rate,name%20from%20csv%20where%20url%3D'http://download.finance.yahoo.com/d/quotes%3Fs%3D" + primaryCurrency[0].toUpperCase() + selectedCurrency + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate,name'&format=json&callback=?";
								
								$.getJSON
								(
									yahooUrl,
									function(data)
									{
										for (var i = 0; i < convertedAmount.length; i++)
										{
											var originalAmount = hiddenAmount.eq(i).val();
											if (primaryCurrency[0].toUpperCase() != selectedCurrency)
											{
												var currencyValue = originalAmount.replace(/[^\,\.0-9]/g, '');
												currencyValue = currencyValue.replace(primaryCurrency[1], '');
												currencyValue = currencyValue.replace(primaryCurrency[2], '.');
												
												var conversionRate = parseFloat(data.query.results.row.rate, 10);
												var conversionAmount = parseFloat(currencyValue, 10) * conversionRate;
												if (roundToNearestDollar)
												{
													conversionAmount = Math.round(conversionAmount).toString();
												}
												else
												{
													conversionAmount = Math.round(conversionAmount * 100).toString();
												}
												
												var outputFormat = "";
												var currencyInfoPos = currencyInfo[1].length - 1;
												var currencyAmountPos = conversionAmount.length - 1;
												while (currencyInfoPos >= 0)
												{
													if (currencyInfo[1].charAt(currencyInfoPos) == '#'
														&& currencyAmountPos >= 0
														&& conversionAmount.charAt(currencyAmountPos).match(/[0-9]/))
													{
														outputFormat = conversionAmount.charAt(currencyAmountPos) + outputFormat;
														currencyAmountPos--;
													}
													else if (currencyInfo[1].charAt(currencyInfoPos).match(/[^0-9\#]/))
													{
														if (currencyAmountPos >= 0)
														{
															outputFormat = currencyInfo[1].charAt(currencyInfoPos) + outputFormat;
														}
														else if (currencyInfo[1].charAt(currencyInfoPos).match(/[^\.\,]/))
														{
															outputFormat = currencyInfo[1].charAt(currencyInfoPos) + outputFormat;
														}
													}
													
													currencyInfoPos--;
												}
												
												convertedAmount.eq(i).html(outputFormat);
											}
											else
											{
												convertedAmount.eq(i).text(originalAmount);
											}
										}
									}
								);
							}
						);
					}
				}
				else // Show the drop down with each price
				{
					$(this).each
					(
						function ()
						{
							var primaryCurrency = {code: ($(this).attr('rel')) ? $(this).attr('rel') : '', thousands: ',', decimal: '.'};
							
							if (options != null)
							{
								if (options['primaryCurrency'] != null)
								{
									primaryCurrency = options['primaryCurrency'];
								}
							}
							
							if ($(this).find('select.currencyConverter').length == 0)
							{
								var currentContent = $(this).text();
								if ($.trim(currentContent.replace(/[^0-9]+/g, '')).length != 0)
								{
									$(this).html('');
									
									var moveContent = $('<' + htmlTag + '></' + htmlTag + '>');
									moveContent.addClass('currencyAmount');
									moveContent.html(currentContent);
									$(this).append(moveContent);
									
									var prefixTextElement = $('<' + htmlTag + '></' + htmlTag + '>');
									prefixTextElement.text($.trim(prefixText) + " ");
									prefixTextElement.addClass('currencyPrefixText');
									
									var hiddenElement = $('<input />');
									hiddenElement.attr('type', 'hidden');
									hiddenElement.val(currentContent);
									hiddenElement.addClass('currencyHiddenField');
									prefixTextElement.append(hiddenElement);
									
									var htmlElement = $('<select></select>');
									htmlElement.addClass('currencyConverter');
									htmlElement.attr('rel', primaryCurrency['code'].toUpperCase() + "|" + primaryCurrency['thousands'] + "|" + primaryCurrency['decimal']);
									if (roundToNearestDollar)
									{
										htmlElement.addClass('roundToNearestDollar');
									}
									
									for (currencyType in acceptedCurrencies)
									{
										var selectOption = $('<option></option>');
										selectOption.text(acceptedCurrencies[currencyType]['name']);
										selectOption.val(currencyType.toUpperCase() + "|" + acceptedCurrencies[currencyType]['format']);
										htmlElement.append(selectOption);
									}
									
									prefixTextElement.append(htmlElement);
									$(this).append(prefixTextElement);
									
									htmlElement.bind('change',
										function()
										{
											var currencyInfo = $(this).val().split('|');
											var primaryCurrency = $(this).attr('rel').split('|');
											var selectedCurrency = currencyInfo[0].toUpperCase();
											var convertedAmount = $(this).parent().parent().find('.currencyAmount');
											var originalAmount = $(this).parent().find('.currencyHiddenField').val();
											var roundToNearestDollar = $(this).hasClass('roundToNearestDollar');
											
											if (primaryCurrency[0].toUpperCase() != selectedCurrency)
											{
												var yahooUrl = "http://query.yahooapis.com/v1/public/yql?q=select%20rate,name%20from%20csv%20where%20url%3D'http://download.finance.yahoo.com/d/quotes%3Fs%3D" + primaryCurrency[0].toUpperCase() + selectedCurrency + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate,name'&format=json&callback=?";
												var currencyValue = originalAmount.replace(/[^\,\.0-9]/g, '');
												currencyValue = currencyValue.replace(primaryCurrency[1], '');
												currencyValue = currencyValue.replace(primaryCurrency[2], '.');
												
												$.getJSON
												(
													yahooUrl,
													function(data)
													{
														var conversionRate = parseFloat(data.query.results.row.rate, 10);
														var conversionAmount = parseFloat(currencyValue, 10) * conversionRate;
														if (roundToNearestDollar)
														{
															conversionAmount = Math.round(conversionAmount).toString();
														}
														else
														{
															conversionAmount = Math.round(conversionAmount * 100).toString();
														}
														
														var outputFormat = "";
														var currencyInfoPos = currencyInfo[1].length - 1;
														var currencyAmountPos = conversionAmount.length - 1;
														while (currencyInfoPos >= 0)
														{
															if (currencyInfo[1].charAt(currencyInfoPos) == '#'
																&& currencyAmountPos >= 0
																&& conversionAmount.charAt(currencyAmountPos).match(/[0-9]/))
															{
																outputFormat = conversionAmount.charAt(currencyAmountPos) + outputFormat;
																currencyAmountPos--;
															}
															else if (currencyInfo[1].charAt(currencyInfoPos).match(/[^0-9\#]/))
															{
																if (currencyAmountPos >= 0)
																{
																	outputFormat = currencyInfo[1].charAt(currencyInfoPos) + outputFormat;
																}
																else if (currencyInfo[1].charAt(currencyInfoPos).match(/[^\.\,]/))
																{
																	outputFormat = currencyInfo[1].charAt(currencyInfoPos) + outputFormat;
																}
															}
															
															currencyInfoPos--;
														}
														
														convertedAmount.html(outputFormat);
													}
												);
											}
											else
											{
												convertedAmount.text(originalAmount);
											}
										}
									);
								}
							}
						}
					);
				}
			}
	}
);


