/* 
See lines 7 and 8 for the pricing XML file references.
Line 7 is for the standard pricing XML file; line 8 is for the special pricing XML file.
*/

(function() {
	var standardPricingInfoURL = "xml/standard-pricing.xml",
		specialPricingInfoURL = "xml/special-pricing.xml",
		standardPricingInfo,
		specialPricingInfo,
		standardPricingProcessed = false,
		specialPricingProcessed = false,
		formatDollar = function (num) {
			if (String(num).indexOf(".") !== -1) {
				if ($("#calculator").hasClass("fr_ca")) {
					return Number(num).toFixed(2).replace(".", "&#44;");
				} else {
					return Number(num).toFixed(2);
				}
			} else {
				return num;
			}
		},
		dollarToNumeric = function (dollars) {
			var symbols = /[\$,]/g;
			
			return 1 * dollars.replace(symbols, ""); // cast to a numeric primitive
		},
		percentToNumeric = function (percent) {
			var symbolPos = percent.indexOf("%");
			return (percent.slice(0, symbolPos) / 100);
		},
		isNumeric = function (x) {
			return (x - 0) == x && x.length > 0;
		},
		isDollar = function (x) {
			var dollar = /^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/;
			
			return !!x.match(dollar);
		},
		getPricingInfo = function () {
			$.ajax({
	            type: "GET",
	            url: standardPricingInfoURL,
	            dataType: "text",
	            success: processStandardXML
	        });
			$.ajax({
	            type: "GET",
	            url: specialPricingInfoURL,
	            dataType: "text",
	            success: processSpecialXML
	        });
		},
		processStandardXML = function (data) {
			var xmlData, xmlParser;
			
			try {
		        xmlData = new ActiveXObject("Microsoft.XMLDOM");
		        xmlData.async = false;
		        xmlData.loadXML(data);
			} catch (e) {
				xmlParser = new DOMParser();
				xmlData = xmlParser.parseFromString(data,"text/xml");
			}
			standardPricingInfo = $(xmlData);
			if (specialPricingProcessed === true) {
				$("div#loading").hide("fast", function () {$("div#calculator form").removeClass("invisible");});
				registerCalculateEvent();
			} else {
				standardPricingProcessed = true;
			}
		},
		processSpecialXML = function (data) {
			var xmlData, xmlParser;
			
			try {
		        xmlData = new ActiveXObject("Microsoft.XMLDOM");
		        xmlData.async = false;
		        xmlData.loadXML(data);
			} catch (e) {
				xmlParser = new DOMParser();
				xmlData = xmlParser.parseFromString(data,"text/xml");
			}
		    specialPricingInfo = $(xmlData);
			if (standardPricingProcessed === true) {
				$("div#loading").hide("fast", function () {$("div#calculator form").removeClass("invisible");});
				registerCalculateEvent();
			} else {
				specialPricingProcessed = true;
			}
		},
		getTier = function (amount) {
			if (amount < 50) return 1;
			else if (amount > 50 && amount <= 100) return 2;
			else if (amount > 100 && amount <= 200) return 3;
			else if (amount > 200 && amount <= 300) return 4;
			else if (amount > 300 && amount <= 400) return 5;
			else if (amount > 400 && amount <= 500) return 6;
			else if (amount > 500 && amount <= 625) return 7;
			else if (amount > 625 && amount <= 750) return 8;
			else if (amount > 750 && amount <= 875) return 9;
			else if (amount > 875 && amount <= 1000) return 10;
			else if (amount > 1000 && amount <= 1250) return 11;
			else if (amount > 1250 && amount <= 1500) return 12;
			else if (amount > 1500 && amount <= 1750) return 13;
			else if (amount > 1750 && amount <= 2000) return 14;
			else if (amount > 2000 && amount <= 2500) return 15;
			else if (amount > 2500 && amount <= 3000) return 16;
			else if (amount > 3000 && amount <= 3500) return 17;
			else if (amount > 3500 && amount <= 4000) return 18;
			else if (amount > 4000 && amount <= 4500) return 19;
			else if (amount > 4500 && amount <= 5000) return 20;
			else if (amount > 5000 && amount <= 5500) return 21;
			else if (amount > 5500 && amount <= 6000) return 22;
			else if (amount > 6000 && amount <= 6500) return 23;
			else if (amount > 6500 && amount <= 7000) return 24;
			else if (amount > 7000 && amount <= 7500) return 25;
			else if (amount > 7500 && amount <= 8000) return 26;
			else if (amount > 8000 && amount <= 8500) return 27;
			else if (amount > 8500 && amount <= 9000) return 28;
			else if (amount > 9000 && amount <= 9500) return 29;
			else if (amount > 9500 && amount <= 10000) return 30;
			else return "";
		},
		calculateOnlineFee = function (amount) {
			return (amount <= 999.99) ? 1 * Number(9 + (0.01 * amount)).toFixed(2) : -1;
		},
		calculateOfflineFee = function (amount, to, from) {
			var tier, fee, price = "", percentRegEx = /\%/, amtPlusPctRegEx = /\+/;

			to = to.toLowerCase();
			from = from.toLowerCase();
			tier = "tier" + getTier(amount);
			if (tier === "tier") return -1;
			else {
				specialPricingInfo.find("special[for='" + from + "'] country[name='" + to + "'] " + tier).each(function() {
					price = $.trim($(this).text());
				});
				if (price === "") {
					standardPricingInfo.find("standard country[name='" + to + "'] " + tier).each(function() {
						price = $.trim($(this).text());
					});
				}
				if (price.match(amtPlusPctRegEx)) {
					price = price.split("+");
					price = (1 * $.trim(price[0])) + (percentToNumeric($.trim(price[1])) * amount);
				} else if (price.match(percentRegEx)) {
					price = percentToNumeric($.trim(price)) * amount;
				} else if (isDollar(price)) {
					price = dollarToNumeric(price);
				} else if (!isNumeric(price)) {
					price = -1;
				} else {
					return 1 * Number(price).toFixed(2);
				}
				return (price === -1) ? price : 1 * Number(price).toFixed(2);
			}
		},
		updateResults = function (online, offline) {
			var diff,
				onlineAvail = $("div#onlineAvail"),
				onlineUnavail = $("p#onlineUnavail");
			
			if (online >= 0 && offline >= 0) {
				diff = offline - online;
				if ($("#calculator").hasClass("fr_ca")) {
					$("p.fee", onlineAvail).html("<strong>" + formatDollar(online) + " $</strong>");
				} else {
					$("p.fee", onlineAvail).html("<strong>$" + formatDollar(online) + "</strong>");
				}
				if (diff > 0) {
					if ($("#calculator").hasClass("fr_ca")) {
						$("p.savings", onlineAvail).html("Économie <strong>" + formatDollar(diff) + " $</strong>");
						$("p.descriptor", onlineAvail).html("Frais Scotia en direct");
					} else {
						$("p.savings", onlineAvail).html("You saved <strong>$" + formatDollar(diff) + "</strong>");
						$("p.descriptor", onlineAvail).html("Scotia OnLine fee");
					}
				} else {
					$("p.savings", onlineAvail).html("&nbsp;");
					if ($("#calculator").hasClass("fr_ca")) {
						$("p.descriptor", onlineAvail).html("Frais Scotia en direct. Obtenez les frais non en ligne à votre	succursale Scotia.");
					} else {
						$("p.descriptor", onlineAvail).html("Scotia OnLine fee. For offline pricing, please contact your local branch.");
					}
				}
				if (onlineAvail.hasClass("hide")) {
					onlineUnavail.addClass("hide");
					onlineAvail.removeClass("hide");
				}
			} else if (online >= 0 && offline === -1) {
				$("p.fee", onlineAvail).html("$<strong>" + formatDollar(online) + "</strong>");
				$("p.savings", onlineAvail).html("&nbsp;");
				$("p.descriptor", onlineAvail).html("Scotia OnLine fee. For offline pricing, please contact your local branch.");
				if (onlineAvail.hasClass("hide")) {
					onlineUnavail.addClass("hide");
					onlineAvail.removeClass("hide");
				}
			} else {
				if (online === -1 && onlineUnavail.hasClass("hide")) {
					onlineAvail.addClass("hide");
					onlineUnavail.removeClass("hide");
				}
			}
		},
		registerCalculateEvent = function () {
			$("button#calculateButton").click(function () {
				var amt = $.trim($("input#sendAmount").val()),
					to = $("select#destCountry").val(),
					from = $("select#originCity").val(),
					loadingGif = $("div#loading img"),
					errorMsg = "",
					onlineFee, offlineFee, timer;

				$("#error-message").html("&nbsp;");
				$("span.error").html("");
				$("div#onlineAvail p.fee").html("<img src=" + loadingGif.attr("src") + " width=" + loadingGif.attr("width") + " height=" + loadingGif.attr("height") + " alt=" + loadingGif.attr("alt") + " />");
				$("div#onlineAvail p.savings").html("&nbsp;");
				if ($("#calculator").hasClass("fr_ca")) {
					$("div#onlineAvail p.descriptor").html("Frais Scotia en direct");
				} else {
					$("div#onlineAvail p.descriptor").html("Scotia OnLine fee");
				}
				if ($("div#onlineAvail").hasClass("hide")) {
					$("p#onlineUnavail").addClass("hide");
					$("div#onlineAvail").removeClass("hide");
				}
				if (amt === "" || amt === "$" || amt === "0" || amt === "$0" || !isDollar(amt) || to === "-1" || from === "-1") {
					timer = setInterval(function () {$("div#onlineAvail p.fee").html("$0");clearInterval(timer);}, 200);
					if (amt === "" || amt === "$" || amt === "0" || amt === "$0" || !isDollar(amt)) {
						$("span#amountError").html("*");
						if (errorMsg === "") {
							if ($("#calculator").hasClass("fr_ca")) {
								errorMsg += "Indiquez un montant";
							} else {
								errorMsg += "Enter an amount";
							}
						} else {
							if ($("#calculator").hasClass("fr_ca")) {
								errorMsg += ", indiquez un montant";
							} else {
								errorMsg += ", enter an amount";
							}
						}
					}
					if (to === "-1") {
						$("span#toError").html("*");
						if (errorMsg === "") {
							if ($("#calculator").hasClass("fr_ca")) {
								errorMsg += "Indiquez un pays";
							} else {
								errorMsg += "Select a country";
							}
						} else {
							if ($("#calculator").hasClass("fr_ca")) {
								errorMsg += ", indiquez un pays";
							} else {
								errorMsg += ", select a country";
							}
						}
					}
					if (from === "-1") {
						$("span#fromError").html("*");
						if (errorMsg === "") {
							if ($("#calculator").hasClass("fr_ca")) {
								errorMsg += "Indiquez une ville";
							} else {
								errorMsg += "Select a city";
							}
						} else {
							if ($("#calculator").hasClass("fr_ca")) {
								errorMsg += ", indiquez une ville";
							} else {
								errorMsg += ", select a city";
							}
						}
					}
					if ($("#calculator").hasClass("fr_ca")) {
						$("#error-message").html("<span>*</span>ERREUR: " + errorMsg + ".");
					} else {
						$("#error-message").html("<span>*</span>ERROR: " + errorMsg + ".");
					}
					return false;
				} else {
					amt = dollarToNumeric(amt);
					onlineFee = calculateOnlineFee(amt);
					offlineFee = calculateOfflineFee(amt, to, from);
					timer = setInterval(function () {updateResults(onlineFee, offlineFee);clearInterval(timer);}, 800);
					return false;
				}
			});
		};

	$(function() {
		// Change the file reference below to point to the XML file that holds the pricing info.
		// NB: The XML file must be accessible in the same domain and port as this JavaScript file.
		getPricingInfo();
		$('#findBranch a').tooltip({
		    track: true,
		    delay: 0,
		    showURL: false,
		    extraClass: "pretty",
		    opacity: 0.95,
			fixPNG: true
		});
	});
})();