$(document).ready(function() {

	// Login
	var $login = $("#login");

	// Toggle account balance.
	$("a#toggle_balance", $login).each(function() {
		var $link = $(this);
		var $img = $("img", $link);
		var $accountMenu = $link.closest(".account_menu");
		var $total = $("#balance .total", $accountMenu);
		var $refresh = $("#refresh_balance a", $accountMenu);
		if (get_cookie("HideBalance") == "yes") {
			$img.attr("src", $img.attr("src").replace(/HideBal.gif$/, "ShowBal.gif"));
			$link.attr("title", $link.attr("title").replace(/^Hide /, "Show "));
		} else {
			$total.show();
			$refresh.show();
		}
		var expires = new Date();
		expires.setFullYear(expires.getFullYear() + 10);
		$link.click(function() {
			if ($total.is(":visible")) {
				$total.fadeOut().queue(function() {
					$img.attr("src", $img.attr("src").replace(/HideBal.gif$/, "ShowBal.gif"));
					$link.attr("title", $link.attr("title").replace(/^Hide /, "Show "));
					$(this).dequeue();
				});
				$refresh.fadeOut();
				set_cookie("HideBalance", "yes", expires);
			} else {
				$total.fadeIn().queue(function() {
					$img.attr("src", $img.attr("src").replace(/ShowBal.gif$/, "HideBal.gif"));
					$link.attr("title", $link.attr("title").replace(/^Show /, "Hide "));
					$(this).dequeue();
				});
				$refresh.fadeIn();
				set_cookie("HideBalance", "no", expires);
			}
			return false;
		});
	});

	// Mega menu
	function addMega() {
		var $mega = $(this);
		$(".panel", $mega).fadeIn(250);
		if (!$mega.hasClass("active")) {
			$mega.addClass("over");
		}
	}

	function removeMega() {
		var $mega = $(this);
		$(".panel", $mega).fadeOut(250);
		$mega.removeClass("over");
	}

	var megaConfig = {
		interval: 100,
		sensitivity: 4,
		over: addMega,
		timeout: 250,
		out: removeMega
	};
	$("#menu .mega").each(function() {
		$(this).hoverIntent(megaConfig);
	});

	// Cache the main content context.
	var $mainContent = $("#mainContent");

	// *** Clone totepool mega menu onto totepool homepage. *** //

	// Locate the component that uniquely identifies the totepool homepage.
	var $totepoolMegaClone = $('#totepool_mega_clone', $mainContent);
	$totepoolMegaClone.each(function() {

		// Locate the totepool mega menu.
		var $totepoolMega = $('#totepool_mega');
		if ($totepoolMega.length > 0) {

			// Clone the lists of main & 'other' links.
			var $megaMain = $('ul.main', $totepoolMega).clone();
			var $megaOthers = $('div.other', $totepoolMega).clone();

			// Sanity check that content is available.
			if ($megaMain.length > 0 && $megaOthers.length > 0) {

				// Create today's totepool component.
				var $todaysTotepool = $('<div id="todaysTotepool"></div>');

				// Create the header and add to today's totepool component.
				var $header = $('<div class="header"></div>');
				$header.append('<h1>Today&rsquo;s totepool Racing</h1>');
				$header.append('<p>Go directly to a totepool bet by clicking a link below&hellip;</p>');
				$todaysTotepool.append($header);

				// Create the content container.
				var $content = $('<div class="content"></div>');

				// Add the main links to the content.
				var $main = $('<div class="main"></div>');
				var $mainHeading = $('h2', $megaMain);
				$main.append($mainHeading.clone());
				$megaMain.removeAttr('class');
				$mainHeading.closest('li').remove();
				$main.append($megaMain);
				$content.append($main);

				// Add the seconday links to the content.
				var $secondaryLinks = $('<div class="secondary"></div>');
				$secondaryLinks.append($megaOthers);
				$content.append($secondaryLinks);

				// Add the content to today's totepool component.
				$todaysTotepool.append($content);

				// Add today's totepool component to the page.
				$totepoolMegaClone.append($todaysTotepool);
			}
		}
	});

	/* Racecard toggler */
	$('.racecard_toggler', $mainContent).live("click", function() {
		var $link = $(this);
		var $img = $("img", $link);
		var $content = $link.parent().next(".racecard_content");
		if ($content.is(":visible")) {
			$content.slideUp().queue(function() {
				$link.attr("title", $link.attr("title").replace(/^Hide /, "Show "));
				$img.attr("src", $img.attr("src").replace(/Up.gif$/, "Down.gif"));
				$(this).dequeue();
			});
		} else {
			$content.slideDown().queue(function() {
				$link.attr("title", $link.attr("title").replace(/^Show /, "Hide "));
				$img.attr("src", $img.attr("src").replace(/Down.gif$/, "Up.gif"));
				$(this).dequeue();
			});
		}
		return false;
	});

	/* All sports A-Z (left navigation) */
	$('#menu_a-z a#all_sports').toggle(
		function() {
			var $link = $(this);
			var $img = $("img", $link);
			$link.next("ul").slideDown().queue(function() {
				$link.attr("title", $link.attr("title").replace(/^Show /, "Hide "));
				$img.attr("src", $img.attr("src").replace(/Down.gif$/, "Up.gif"));
				$(this).dequeue();
			});
		},
		function() {
			var $link = $(this);
			var $img = $("img", $link);
			$link.next("ul").slideUp().queue(function() {
				$link.attr("title", $link.attr("title").replace(/^Hide /, "Show "));
				$img.attr("src", $img.attr("src").replace(/Up.gif$/, "Down.gif"));
				$(this).dequeue();
			});
		}
	);

	// Bet Search focus & blur.
	$("#bet_search").focus(function() {
		$(this).val("");
	}).blur(function() {
		var $search = $(this);
		if ($search.val() == "") {
			$search.val("A-Z bet search:");
		}
	});

	// Popup game controlled by text link.
	$("a.launchGame").live("click", function() {
		var $anchor = $(this);
		var top = (window.screenY ? window.screenY : window.screenTop) + 50;
		var left = (window.screenX ? window.screenX : window.screenLeft) + 50;
		window.open($anchor.attr("href"), $anchor.attr("target"),
			"width=750,height=550" + ",top=" + top + ",left=" + left +
			",scrollbars=no,resizable=yes").focus();
		return false;
	});

	// Popup game controlled by select option.
	$("select.launchGame").bind("change", function() {
		var $select = $(this);
		var top = (window.screenY ? window.screenY : window.screenTop) + 50;
		var left = (window.screenX ? window.screenX : window.screenLeft) + 50;
		window.open($select.attr("value"), "_blank",
			"width=750,height=550" + ",top=" + top + ",left=" + left +
			",scrollbars=no,resizable=yes").focus();
		return false;
	});

	// Popup help controlled by text link.
	$(".launchHelp").live("click", function() {
		var $anchor = $(this);
		var top = (window.screenY ? window.screenY : window.screenTop) + 50;
		var left = (window.screenX ? window.screenX : window.screenLeft) + 50;
		window.open($anchor.attr("href"), $anchor.attr("target"),
			"width=640,height=480" + ",top=" + top + ",left=" + left +
			",scrollbars=yes").focus();
		return false;
	});

	// Popup websites controlled by text link.
	$(".launchSite").live("click", function() {
		var $anchor = $(this);
		var top = (window.screenY ? window.screenY : window.screenTop) + 50;
		var left = (window.screenX ? window.screenX : window.screenLeft) + 50;
		window.open($anchor.attr("href"), $anchor.attr("target"),
			"width=860,height=600" + ",top=" + top + ",left=" + left +
			",scrollbars=yes,resizable=yes").focus();
		return false;
	});

	// Popup wide websites controlled by text link.
	$(".launchWideSite").live("click", function() {
		var $anchor = $(this);
		var top = (window.screenY ? window.screenY : window.screenTop) + 50;
		var left = (window.screenX ? window.screenX : window.screenLeft) + 50;
		window.open($anchor.attr("href"), $anchor.attr("target"),
			"width=1024,height=400" + ",top=" + top + ",left=" + left +
			",scrollbars=yes,resizable=yes").focus();
		return false;
	});

	// Popup live commentary.
	$(".launchCommentary").live("click", function() {
		var $anchor = $(this);
		var top = (window.screenY ? window.screenY : window.screenTop) + 50;
		var left = (window.screenX ? window.screenX : window.screenLeft) + 50;
		window.open($anchor.attr("href"), $anchor.attr("target"),
			"width=400,height=300,top=" + top + ",left=" + left +
			",scrollbars=yes,resizable=yes").focus();
		return false;
	});

	// All Betting A-Z (footer)
	$("#bottom #a-ztoggler a").toggle(
		function() {
			var $img = $("img#bottom_a-z", $(this));
			$("#bottom #a-zsports").slideDown().queue(function() {
				$img.attr("src", $img.attr("src").replace(/Down.gif$/, "Up.gif"));
				$(this).dequeue();
			});
		},
		function() {
			var $img = $("img#bottom_a-z", $(this));
			$("#bottom #a-zsports").slideUp().queue(function() {
				$img.attr("src", $img.attr("src").replace(/Up.gif$/, "Down.gif"));
				$(this).dequeue();
			});
		}
	);

	// Handle bet slip message layer.
	new MsgLayerHandler("betSlipBodyMembrane");
	new MsgLayerHandler("accountWrapper");

	// Popup printer-friendly bet slip receipt.
	$("#receiptPrint").click(function() {
		var $anchor = $(this);
		var top = (window.screenY ? window.screenY : window.screenTop) + 50;
		var left = (window.screenX ? window.screenX : window.screenLeft) + 50;
		window.open($anchor.attr("href"), $anchor.attr("target"),
			"width=270,height=500" + ",top=" + top + ",left=" + left +
			",scrollbars=yes").focus();
		return false;
	});

	if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
		// Fix mega menu burn-through in IE 6.
		$("#menu .mega .panel").each(function() {
			$(this).bgiframe();
		});
		// Encourage upgrade from IE 6.
		var $upgrade = $('<div id="upgrade_ie6"> </div>');
		$upgrade.append('<a href="#"><img src="/totesport/upgrade-browser/images/en/imgIE6Warning.gif" alt="Still using IE 6?" title="Upgrade your browser&hellip;"/></a>');
		$upgrade.append('<script type="text/javascript" src="/totesport/upgrade-browser/scripts/jquery.reject.min.js"><\/script>');
		$('#menu_a-z').after($upgrade);
		$('#upgrade_ie6 a').click(function() {
			$.reject({
				reject:{all:false, msie5:true, msie6:true},
				display:['msie','firefox','chrome','safari','opera'],
				imagePath:'/totesport/upgrade-browser/images/en/'
			});
			return false;
		});
	}

	// Google Analytics event tracking.
	try {
		if (typeof pageTracker != "undefined") {

			// Add tracking to news highlight links.
			function trackNewsHighlight(category) {
				$('div.newsHighlight a', $mainContent).live('click', function() {
					var $anchor = $(this);
					var $highlight = $anchor.closest('.newsHighlight');
					var action = $('div.textGroup h2', $highlight).text();
					var label = $anchor.text();
					if (label == '') {
						var $img = $('img', $anchor);
						if ($img.length > 0) {
							label = $img.attr('alt');
						}
					}
					pageTracker._trackEvent(category, action, label);
				});
			}

			var url = location.href.match(/\/portal(.*)$/);
			if (url != null && url.length == 2 && (url[1] == "" || /^\?action=GoHome/.test(url[1]) == true)) {
				// Track actions from homepage (i.e. url ending in "/portal" or "/portal?action=GoHome...").

				// Track "Featured Races" (e.g. Next 3).
				$("div.quickpick_racecard", $mainContent).each(function() {
					var $quickpick = $(this);
					var category = "Home - Featured Races";
					var section = $("h2 .race", $quickpick).text();
					$("a.odds", $quickpick).live("click", function() {
						var race = $(this).closest("div.runners_table").find("div.meeting_details h3").text();
						var label = section + (race == "" ? "" : (" (" + race + ")"));
						pageTracker._trackEvent(category, "Add to Bet Slip", label);
					});
					$("div.view_full_racecard a.button", $quickpick).live("click", function() {
						var race = $(this).closest("div.runners_table").find("div.meeting_details h3").text();
						var label = section + (race == "" ? "" : (" (" + race + ")"));
						pageTracker._trackEvent(category, "View Race in Full", label);
					});
					var $racecardTitle = $("div.racecard_title", $quickpick);
					$("a.button", $racecardTitle).click(function() {
						pageTracker._trackEvent(category, "All Todays's Races", section);
					});
					$("a.racecard_toggler", $racecardTitle).click(function() {
						pageTracker._trackEvent(category, "Toggle Racecard", section);
					});
				});

				// Track "Event Highlight".
				$("div.event_highlight", $mainContent).each(function() {
					var $event_text = $("div.event_text", this);
					var category = "Home - Event Highlight";
					var eventName = $("h2", $event_text).text();
					$("h3 a", $event_text).click(function() {
						pageTracker._trackEvent(category, "View More Link", eventName);
					});
					var $event_odds = $("div.event_odds", this);
					$("a.odds", $event_odds).live("click", function() {
						pageTracker._trackEvent(category, "Add to Bet Slip", eventName);
					});
					$("div.all_markets a", $event_odds).click(function() {
						pageTracker._trackEvent(category, "View All Button", eventName);
					});
				});

				// Track totepool highlight links.
				trackNewsHighlight("Home - totepool Highlight");

				// Track "Today's Racing & Results".
				$("div.daily_view", $mainContent).each(function() {
					var $dailyView = $(this);
					var category = "Home - Today's Racing & Results";
					$("a.racecard_toggler", $dailyView).live("click", function() {
						pageTracker._trackEvent(category, "Toggle View");
					});
					var $buildCustom = $("#build_custom", $dailyView);
					if ($buildCustom.length > 0) {
						$buildCustom.click(function() {
							pageTracker._trackEvent(category, "Build Racecard");
						});
					} else {
						$("td.name a", $dailyView).live("click", function() {
							pageTracker._trackEvent(category, "View all Full Racecards", $(this).text());
						});
						$("td.quickpicks a", $dailyView).live("click", function() {
							var meeting = $(this).closest("tr").find("td.name").text();
							pageTracker._trackEvent(category, "View all Quickpick Racecards", meeting);
						});
						$("td.time a", $dailyView).live("click", function() {
							var $time = $(this);
							var action = "View " + (/Result$/.test($time.attr("title")) ? "Result" : "Racecard");
							var meeting = $time.closest("tr").find("td.name").text();
							pageTracker._trackEvent(category, action, meeting + " " + $time.text());
						});
					}
				});

				// Track "Hero Promotion".
				$(".hero_promotion", $mainContent).each(function() {
					$("a", this).live("click", function() {
						pageTracker._trackEvent("Home - Hero Banner", $(this).attr("title"));
					});
				});

				// Track mega menus.
				$("#menu a").live("click", function() {
					var action, label;
					var $anchor = $(this);
					if ($anchor.hasClass('tab')) {
						action = $anchor.text();
						label = '[tab]';
					} else {
						action = $anchor.closest('div.panel').prev('a.tab').text();
						label = $anchor.text();
					}
					pageTracker._trackEvent("Home - Mega Menu", action, label);
				});

				// Track 'tote menu'.
				$("#menu_tote a").live("click", function() {
					var title = $(this).attr('title');
					if (title != '') {
						pageTracker._trackEvent("Home - Left Nav (main)", title);
					}
				});

				// Track 'all sports a-z'.
				$("#menu_a-z a").live("click", function() {
					var title = $(this).attr('title');
					if (title != '') {
						pageTracker._trackEvent("Home - Left Nav (a-z)", title);
					}
				});

				// Track "Racing Post Features".
				$("#menu_features a").bind("click", function() {
					var $anchor = $(this);
					var $parent = $anchor.parent();
					var action = ($parent.is("dt") ? $parent.next("dd").find("a").text() : $anchor.text());
					pageTracker._trackEvent("Home - Features", action);
				});

				// Track "Information".
				$("#menu_utilsinfo a").live("click", function() {
					var $anchor = $(this);
					var $parent = $anchor.parent();
					var action = ($parent.is("dt") ? $parent.next("dd").find("a").text() : $anchor.text());
					pageTracker._trackEvent("Home - Information", action);
				});

				// Track "Strip Promotion".
				$(".strip_promotion", $mainContent).each(function() {
					$("a", this).live("click", function() {
						pageTracker._trackEvent("Home - Strip Banner", $(this).attr("title"));
					});
				});

				// Track "Promotion Highlight Banner".
				$("div.promotion_highlights", $mainContent).each(function() {
					$("a", this).live("click", function() {
						pageTracker._trackEvent("Home - Banner", $(this).attr("title"));
					});
				});

				// Track "Instant Games".
				$("#gameLauncher .action a").click(function() {
					pageTracker._trackEvent("Home - Instant Game Launcher", "More Instant Games");
				});

				// Track other header items.
				var headCat = "Home - Header";

				// Track Logo.
				$("#logo a").click(function() {
					pageTracker._trackEvent(headCat, "Logo");
				});

				// Track "Register Now!".
				$("#create").click(function() {
					pageTracker._trackEvent(headCat, "Register Now!");
				});

				// Track Search.
				$("#btnSearch").click(function() {
					pageTracker._trackEvent("Home - Search", $("#bet_search").val());
				});

				// Track Odds preference.
				$("#lstOddsPreference").change(function() {
					var category='';
					switch ($(this).val()) {
						case 'DECIMAL':
							category='Decimal Odds';
						break;
						case 'ODDS':
							category='Fractional Odds';
						break;
					}
					pageTracker._trackEvent("Home - Preferences", category);
				});

				// Track other footer items.
				var footCat = "Home - Footer";

				// Track "All Betting A-Z".
				$("#a-zsports a").live("click", function() {
					pageTracker._trackEvent(footCat, "All Betting A-Z", $(this).text());
				});

				// Track "Footer" links.
				$("#footer a").click(function() {
					var $anchor = $(this);
					var action = $anchor.closest('ul').prevAll('h2').eq(0).text();
					pageTracker._trackEvent(footCat, action, $anchor.text());
				});

				// Track "Bottom Menu" external links.
				$("#b_menu a").click(function() {
					pageTracker._trackEvent(footCat, "External Tote Links", $(this).text());
				});

				// Track "Licence" external links.
				$("#license a").click(function() {
					pageTracker._trackEvent(footCat, "Licence", $(this).text());
				});
			} else if ($totepoolMegaClone.length > 0) {

				// Track Live totepool Information launch.
				$("#liveTotePools a").click(function() {
					pageTracker._trackEvent("totepool - Banner", "Live totepool Information");
				});

				// Track news highlight links.
				trackNewsHighlight("totepool - Highlight");

				// Track today's totepool links.
				var $todaysTotepool = $('#todaysTotepool a').live('click', function() {

					var $anchor = $(this);
					var $anchorParent = $anchor.parent();
					var isHeadingAnchor = $anchorParent.is('h2');
					var $heading = isHeadingAnchor ? $anchorParent : $anchorParent.closest('ul').prev('h2');
					var action = $heading.length > 0 ? $('a', $heading).text() : '[no heading]';
					var label = isHeadingAnchor ? '[heading]' : $anchor.text();
					pageTracker._trackEvent("totepool - Today's totepool Racing", action, label);
				});
			}
		}
	} catch (e) { }

	// Add a 'retry timer' to error pages to retry loading the homepage after 30 seconds.
	if ($("#errorPage").length > 0) {
		setTimeout("location.replace('/portal')", 30000);
	}
});

// Username focus & blur.
function onUsernameClick() {
	$("#login #username").val("");
}
function onUsernameBlur() {
	var $username = $("#login #username");
	if ($username.val() == "") {
		$username.val("Username:");
	}
}

// Password focus & blur.
function onPasswordPromptFocus() {
	var $login = $("#login");
	$("#password_prompt", $login).hide();
	$("#password", $login).show().focus();
}
function onPasswordFocus() {
	$("#login #password").val("");
}
function onPasswordBlur() {
	var $login = $("#login");
	var $password = $("#password", $login);
	if ($password.val() == "") {
		$password.hide();
		$("#password_prompt", $login).show();
	}
}

/* ----- Best slip action animation tests ----- */
function BS_go_bet_test(target) {
	var $trigger = $(target);
	betTriggered($trigger);

	// Bet Slip processing...

	betAdded($trigger);
	return false;
}

function BS_go_bet_test_error(target) {
	var $trigger = $(target);
	betTriggered($trigger);

	// Bet Slip processing...

	betError($trigger);
	return false;
}
/* ----- Best slip action animation tests ----- */

function betTriggered($trigger) {
	try {
		/* Highlight Odds */
		var over_class = null;
		if ($trigger.hasClass("odds")) {
			over_class = "odds_over";
		} else if ($trigger.hasClass("split_odds")) {
			over_class = "split_odds_over";
		} else if ($trigger.hasClass("split_sp")) {
			over_class = "split_sp_over";
		}
		$trigger.addClass(over_class).fadeOut().fadeIn().delay("normal").queue(function() {
			$trigger.removeClass(over_class).dequeue();
		});
	} catch (e) { }
}

function betAdded($trigger) {
	try {
		var position = $trigger.position();
		$('<div class="bubble"><div class="content">Selection added to Bet Slip</div></div>').insertAfter($trigger).css({
			top: position.top,
			left: position.left
		}).fadeIn("fast").delay(1500).fadeOut("fast").queue(function() {
			$(this).remove().dequeue();
		});
	} catch(e) {}
}

function betError($trigger) {
	try {
		var position = $trigger.position();
		$('<div class="bubble"><div class="content error">Error - Check Bet Slip</div></div>').insertAfter($trigger).css({
			top: position.top,
			left: position.left
		}).fadeIn("fast").delay(1500).fadeOut("fast").queue(function() {
			$(this).remove().dequeue();
		});
	} catch (e) { }
}

// Page tracking
function initialiseTracking() {
	var gaJsHost=(("https:"==document.location.protocol)?"https://ssl.":"http://www.");
	document.write(unescape("%3Cscript src='"+gaJsHost+"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
}

function trackPage() {
	pageTracker=_gat._getTracker("UA-6173963-1");

	// Custom analytics tracking...
	try {
		var virtualPage;
		// For registration/account pages, use h1 to generate virtual page names.
		$("#accountMembrane h1").each(function() {
			var heading = $(this).html();
			var step = heading.match(/open account(.*)/i);
			if (step != null && step.length > 1 && step[1].length > 0) virtualPage = "/OpenAccount/" + step[1].replace(/\W/g, "");
			else if (heading.search(/account created$|application received$/i) >= 0) virtualPage = "/OpenAccount/Created";
			else if (heading.search(/^update your telephone account/i) >= 0) virtualPage = "/OpenAccount/ExistingTelephone";
			else if (heading.search(/^your password has been reset/i) >= 0) virtualPage = "/ForgottenDetails/PasswordReset";
			else {
				step = heading.match(/forgotten details(.*)/i);
				if (step != null && step.length > 1 && step[1].length > 0) {
					// Capitalise words then remove non-alphanumeric.
					virtualPage = "/ForgottenDetails/" + step[1].replace(/\b[a-z]/g, function() { return arguments[0].toUpperCase(); }).replace(/\W/g, "");
				}
			}
		});
		if (virtualPage) {
			// Track virtual page and drop out.
			pageTracker._trackPageview(virtualPage);
			return;
		}
	} catch (e) {}

	// Default/fallback option - use standard page tracking.
	pageTracker._trackPageview();
}

function trackRegistration() {

	// Google Casino.
	try {
		google_conversion_id=1012697898;
		google_conversion_language="en";
		google_conversion_format="3";
		google_conversion_color="ffffff";
		google_conversion_label="Q_EGCM6mrAIQqpby4gM";
		google_conversion_value=0;
		document.write('<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"><\/script>');
	} catch (e) {}

	// Google Sportsbook.
	try {
		google_conversion_id=1014062307;
		google_conversion_language="en";
		google_conversion_format="3";
		google_conversion_color="ffffff";
		google_conversion_label="Mt80CJX_qwIQ47nF4wM";
		google_conversion_value=0;
		document.write('<script type="text/javascript" src="//www.googleadservices.com/pagead/conversion.js"><\/script>');
	} catch (e) {}

	// Yahoo
	try {
		ysm_accountid = "1SGRFU7FSPCD98PV9I7PJ18GFIG";
		ysm_customData=new Object();
		ysm_customData.conversion="transId=,currency=,amount=";
		document.write('<script type="text/javascript" src="//srv3.wa.marketingsolutions.yahoo.com/script/ScriptServlet?aid='+ysm_accountid+'"><\/script>');
	} catch (e) {}

	// MSN Sportsbook
	try {
		if (!window.mstag) {
			mstag = {loadTag : function(){},time : (new Date()).getTime()};
		}
		document.write('<script type="text/javascript" src="//flex.atdmt.com/mstag/site/4618d57f-432f-49e7-8be1-7f860a341401/mstag.js"><\/script>');
		mstag.loadTag("conversion", {cp:"5050",dedup:"1"});
	} catch (e) {}
}

/* Common classes and functions */
function cRect() { this.t = 0; this.r = 0; this.b = 0; this.l = 0; }

/* obtain footprint of the specified element */
function fnGetRect(elMain, rect) {
	rect.l = 0;
	rect.t = 0;
	for (var el = elMain; el; el = el.offsetParent) {
		rect.l += el.offsetLeft;
		rect.t += el.offsetTop;
	}
	rect.r = rect.l + elMain.offsetWidth;
	rect.b = rect.t + elMain.offsetHeight;
}

/* check for overlapping rectangles */
function fnOverlap(r1, r2) { return (((r1.t - r2.b) >= 0) != ((r1.b - r2.t) >= 0)) && (((r1.l - r2.r) >= 0) != ((r1.r - r2.l) >= 0)); }

/* hide any <select> elements that would burn through a layer (only affects IE) */
function fnHideSelect(layer, aHidden) {
	var lRect = new cRect();
	fnGetRect(layer, lRect);
	var l = document.getElementsByTagName('select');
	var sRect = new cRect();
	for (var i = 0; i < l.length; i++) {
		fnGetRect(l[i], sRect);
		// Note: Don't attempt to hide a <select> that is already hidden since
		//       it may have already been hidden by another overlapping layer.
		if (fnOverlap(lRect, sRect) && l[i].style.visibility == "") { l[i].style.visibility = "hidden"; aHidden[aHidden.length] = l[i]; }
	}
}

/* show <select> elements that were hidden */
function fnShowSelect(aHidden) {
	for (var i = 0; i < aHidden.length; i++) { aHidden[i].style.visibility = ""; }
	aHidden.length = 0;
}

function MsgLayerHandler(rootId) {
	this.rootId = rootId;
	this.fnScan();
}

/* Scan for message layers, hide <select> where necessary and add handlers */
MsgLayerHandler.prototype.fnScan = function() {
	// Allow option to scan whole document or a specific subset of the document.
	var root = typeof (this.rootId) == 'undefined' ? document : document.getElementById(this.rootId);
	if (root == null) { return; }
	var l = root.getElementsByTagName('div');
	for (var i = 0; i < l.length; i++) {
		if (l[i].className.indexOf('msgLayer') > -1) { new MsgLayer(l[i]); }
	}
}

function MsgLayer(el) {
	this.aHidden = new Array();
	if ($.browser.msie && $.browser.version.substr(0, 1) < 7) {
		this.fnHideSelect(el);
	}
	var ml = this;
	var l = el.getElementsByTagName('a');
	for (var i = 0; i < l.length; i++) {
		if (l[i].className.indexOf('close') > -1) {
			l[i].onclick = function() { ml.fnClose(el); return false; };
		}
	}
}


/* hide any <select> elements that would burn through the layer */
MsgLayer.prototype.fnHideSelect = function(layer) { fnHideSelect(layer, this.aHidden); }

/* show <select> elements that were hidden */
MsgLayer.prototype.fnClose = function(layer) { fnShowSelect(this.aHidden); layer.style.display = "none"; }

// Resize fireguard for element with specified id (legacy).
function resizeFireguard(id) {
}

function AddOnload(fnOnLoad) {
	// Using jQuery 'dom ready event' in place of 'onload event' to allow unobtrusive script to execute as soon as possible.
	$(fnOnLoad);
}


