/// <reference path="jquery-1.3.2-vsdoc2.js" />
// CONTENTS ====================================================================
/*
- 
*/

// ======================================================================

// CSS for Javascript Disabled Features
(function() {
	var head = document.getElementsByTagName("head")[0];
	if (head) {
		var scriptStyles = document.createElement("link");
		scriptStyles.rel = "stylesheet";
		scriptStyles.type = "text/css";
		scriptStyles.href = "/css/javascript.css";
		scriptStyles.media = "screen,print";
		head.appendChild(scriptStyles);
	}
} ());

/***** Cookie Manager **********************************************************/
var CookieManager = {
	create: function(name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";

	},
	read: function(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return '';
	},
	erase: function(name) {
		CookieManager.create(name, "", -1);
	}
}




/***** Page Controls ie. Print etc *********************************************/
var PageControls = {
	Init: function() {
		var printHtml = '<a title="Print page" class="tool-print" href="#">Print</a>';
		if ($("#content .cont-section").find(".download").length == 0) 
			$("#content .cont-section").prepend(printHtml);
			$("#content .cont-section .download").after(printHtml);
		$("#content .cont-section .tool-print").click(Frontend.PageControls.PrintPage);
	},
	PrintPage: function() {
		window.print();
		return false;
	}
}

/***** / Page Controls *********************************************************/

/***** Table of Contents *******************************************************/
var TableOfContents = {
	Init: function() {
		var ItemNum = 1;
		var ItemsHtml = '';
		var ItemRegExp = new RegExp("[^a-z0-9]", "g");
		$("#content .cont-table").each(function() {
			if ($(this).children("h1").length == 1) { // Only add table of contents if there is only one h1
				$(this).find("h2").each(function() { // Find all of the h2 headers and use text
					var ItemTitle = $(this).text();
					var ItemLink = (ItemTitle.toLowerCase().replace(ItemRegExp, '-').substr(0, 15)) + "-" + ItemNum;
					$(this).attr("id", ItemLink); // Insert ID into h2
					ItemsHtml = ItemsHtml + '<li><a href="#' + ItemLink + '">' + ItemTitle + '</a></li>'; // Add item to ItemHtml
					ItemNum++;
				});
				if (ItemsHtml != '') {
					var ListHtml = '<ul class="cont-list">' + ItemsHtml + '</ul>';
					if ($(this).find(".cont-abs").length == "0")
						$(this).children("h1").after(ListHtml);
					$(this).find(".cont-abs").after(ListHtml);
				}
			}
		});
	}
}

/***** Table Alternate Row *****************************************************/
var TableAlternateRow = {
	Init: function() {
		$("#content table").each(function() {
			if ($(this).hasClass("table-gold")) $(this).find("tr:even").css("background-color", "#f6f2e9");
			if ($(this).hasClass("table-grey")) $(this).find("tr:even").css("background-color", "#e5e5e5");
		});
	}
}

/***** / Equalise Decision Tree Two ***************************************/
var DecisionTreeTwo = {
	Init: function() {
		$(".cols-two .pri .decision-tree-two li").each(function() {
			$(this).find(".product").each(function() {
				var prodHeight = $(this).height();
			});
		});
	}
}

/***** / Tabbed Content ***************************************/
var TabbedContent = {
	//Setting up the tab menu
	Init: function($elem) {
		$elem.each(function() {
			var $tabHolder = $(this),
			//tab buttons
                $thisMenu = $tabHolder.find(".tab-menu"),
			//collapse/show all link at footer of tab
                $tabFooterLink = $elem.find('.mod-listing-bot').find('a'),
			//collapse/show all link text
                linkText = $tabFooterLink.text();
			$thisMenu.find("li a").click(function() {
				if (!$tabFooterLink.is(":visible")) { $tabFooterLink.show(); }
				var $thisMenuLink = $(this);
				//only need to initiate the event if we aren't clicking the currently selected tab
				if (!$thisMenuLink.is(".selected")) {
					//Work out what the number of the current clicked item is. This enables us to display it's relevant content
				    var clickedItem = $thisMenuLink.parent().attr("id").match(new RegExp("\\d+"));
					/** First change the menu to the selected item **/
					$tabHolder.find(".tab-menu .selected")
                            .removeClass("selected")
                            .end()
                        .find('#tab-menu-' + clickedItem)
                            .addClass("selected")
                            .end()
					/** Then change the 'last' selected content **/
                        .find(".tab-content .selected")
                            .removeClass("selected")
                            .end()
                        .find('#tab-item-' + clickedItem)
                            .addClass("selected");

					//Depending on whether the tab we are moving to is 'opened' or 'closed' set it's footer link accordingly       
					var $clickedTabItem = $tabHolder.find('#tab-item-' + clickedItem);
					if ($clickedTabItem.find('.featured').size() === 0) {
						$tabFooterLink.hide(); // .html("") doesn't work in IE
					}
					else if ($tabHolder.find('#tab-item-' + clickedItem).is('.closed')) {
					    $tabFooterLink.html("Show all " + $thisMenuLink.text() + "")
						    .removeClass('collapse');
					} else {
					    $tabFooterLink.html("Collapse " + $thisMenuLink.text() + "")
						    .addClass('collapse');
					}
				}
				return false;

			});
		});
	}
}

/***** / Expanding Content ***************************************/
var Expanders = {
    Init: function() {
        $('.mod-expander .toggler').append('<a class="ind"></a>');

        $('.mod-expander .toggler a.ind').click(function() {
            Frontend.Expanders.Toggle($(this));
            return false;
        });

        $('.mod-expander .decision-tree-one li.point-6 a,.mod-expander .decision-tree-two .decision-three a').click(function() {
            Frontend.Expanders.CloseAll($(this));
            Frontend.Expanders.ShowNext($(this));
            Frontend.Expanders.OpenTarget($(this));
        });
    },

    ListingInit: function() {
        $('.download-listing .content, .video-listing .content').each(function() {
            var thisElem = $(this);
            if (thisElem.find('.bodyText').text() != '') {
                thisElem.append('<a class="ind"></a>');
                thisElem.find('a.ind').click(function() {
                    Frontend.Expanders.Toggle(thisElem.find('.bodyText'));
                    return false;
                }).parents('li')
	            .removeClass('opened').addClass('closed');
            }
        });
    },

    Toggle: function(elm) {
        var holderElm = elm.parents(".mod-expander");
        if (holderElm.hasClass('opened')) {
            holderElm.removeClass('opened').addClass('closed');
            holderElm.find('.content').slideUp(150);
        } else if (elm.parents(".download-listing, .video-listing").size() > 0) {
            elm.parents("li").toggleClass("closed").toggleClass("opened");
        } else {
            if (holderElm.hasClass("mod-decision")) Frontend.Expanders.CloseAll(elm); // Only Close all other expanding modules on the decision tree
            holderElm.removeClass('closed').addClass('opened');
            holderElm.find('.content').slideDown(150);
        }
    },

    ShowNext: function(elm) {
        var holderElm = elm.parents(".mod-expander");
        holderElm.next(".mod-expander").removeClass("mod-expander-hide");
    },

    CloseAll: function(elm) {
        var holderElm = elm.parents(".mod-expander");
        holderElm.removeClass('opened').addClass('closed');
        holderElm.siblings(".mod-expander").each(function() {
            $(this).removeClass('opened').addClass('closed');
        });
    },

    OpenTarget: function(elm) {
        var target = elm.attr("href");
        var holderElm = elm.parents(".mod-expander");
        holderElm.siblings(target).removeClass('closed').addClass('opened');
    },

    ToggleModules: function(elm) {
        elm.each(function() {
            var $thisElm = $(this);
            //Find link at footer of module
            $thisElm.next().find('a').click(function(e) {

                var $thisLink = $(this),
                //Content of link
                    linkText = $thisLink.text(),
                //Item we are toggling. Either the tab module or a normal module
                    $toToggle = $thisElm.is('.tab-content') ? $thisElm.find('.selected') : $thisElm;

                //Change the state of the module
                $toToggle.toggleClass('opened').toggleClass('closed');

                //Here we change the footer link to be "Show all..." or "Collapse..." depending on the change of state i.e. opened or closed
                var sectionName = linkText.indexOf('Show all') != -1 ? linkText.substring(linkText.indexOf('all ') + 4, linkText.length) : linkText.substring(linkText.indexOf('Collapse ') + 8, linkText.length);
                if (linkText.indexOf('Show all') != -1) {
                    $thisLink.html("Collapse " + sectionName + "");
                    $thisLink.addClass('collapse');
                } else {
                    $thisLink.html("Show all " + sectionName + "");
                    $thisLink.removeClass('collapse');
                }

                //If we are closing the module we move the offset of the page back to the first item
                if ($toToggle.is('.closed')) {
                    $('html, body').scrollTop($thisElm.offset().top);
                }

                return false;
            });
        });
    }
}

//Email a friend

var EmailFriend = {
	Init: function () {
		$('.mod-send-friend').each(function () {
			var self = $(this),
			placeholder = self.find('.email-a-friend-placeholder');
			self.find('h2').click(function () {
				placeholder.find('> *').css("opacity", "0")
					.end()
				.slideDown('fast', function () {
					var thisHolder = $(this);
					thisHolder.find('> *').animate({ "opacity": 1 }, 200, function () {
						this.style.filter = '';
					});
					if (thisHolder.parent().find('.success-text'))
						thisHolder.parent().find('.success-text').css('padding-top', '20px');
				});
			});

			self.find('.close,.cancel').click(function () {
				var slideUpFired = false;
				placeholder.find('> *').animate({ "opacity": "0" }, 200, function () {
					this.style.filter = '';
					if (!slideUpFired) {
						slideUpFired = true;
						placeholder.slideUp('fast');
						if (placeholder.parent().find('.success-text'))
							placeholder.parent().find('.success-text').css('padding-top', '190px');
					}

				})

			});
		});
	}
}



//Homepage login
var HomepageLogin = {
	Init: function () {
		$('.login-password').prepend('<a class="show-forgotten" href="#">Forgotten password?</a>');
		$('.forgotten-password').prepend('<a class="show-login" href="#">&lt; Go Back</a>');
		$('.show-forgotten').click(function () {
			$('.login-input').fadeOut(100, function () { $('.forgotten-input').fadeIn(350); });
			return false;
		});

		$('.show-login').click(function () {
			$('.forgotten-input').fadeOut(100, function () { $('.login-input').fadeIn(350); });
			return false;
		});
		Disclaimer.CreateCookie();
		HomepageLogin.IntroVideo();
	},
	IntroVideo: function () {
		var $vid_btn = $('.intro-vid a.inline-cbox');
		var $target = $($vid_btn.attr('href'));

		var $intro_disclaimer = $('#intro-disclaimer');
		var $video_holder = $('#video-holder');
		$video_holder.hide();

		$intro_disclaimer.find('.accept').click(function () {

			var passed = true;

			var $confirm = $intro_disclaimer.find('input[type=checkbox]');

			if ($confirm.is(':checked')) {
				$confirm.parent().removeClass('error');
			} else {
				$confirm.parent().addClass('error');
				passed = false;
			}

			var $prof = $intro_disclaimer.find('select')

			if ($prof.val() != '') {
				$prof.parent().removeClass('error');
			} else {
				$prof.parent().addClass('error');
				passed = false;
			}

			if (passed) {
				$intro_disclaimer.hide();
				$video_holder.show();
				Tracking.GoogleAnalytics.TrackAsEvent('Homepage Video', 'Terms Accepted', $prof.val());
			}
			return false;
		});
		$intro_disclaimer.find('.cancel').click(function () {
			$.fn.colorbox.close();
			return false;
		});

		$vid_btn.colorbox({ innerWidth: '800', height: '730', inline: true, href: $vid_btn.attr('href') });
	}
}

//Disclaimer
var Disclaimer = {
	Open: function(currentNodeTypeAlias) {
		var disclaimerUrl = '/disclaimer';
		if (currentNodeTypeAlias == 'Product Page') disclaimerUrl = '/disclaimer/product-disclaimer';
		var productSection = new RegExp('/products-available', 'g');
		var fromProductSection;
		var showDisclaimerCookie = CookieManager.read("showDisclaimer"); //Get cookies value, 1 = set, '' = not set

		if (showDisclaimerCookie == null || showDisclaimerCookie == "") { 
			//if cookie not set, check if last URL was a product URL, if not then show disclaimer
			var fromProductSection = document.referrer.match(productSection);
		} else { 
			//if cookie set, user was redirected to login page before, so although their URL was 
			//looks like a product page, they didn't see the disclaimer, so show it to them.
			fromProductSection = null;
		}
		var inProductSection = location.href.match(productSection);
		//alert(" from product section = " + fromProductSection + "\r\n" + "in product section = " + inProductSection );
		if ((fromProductSection == null) || (inProductSection == null)) {
			var controls = '<div class="disclaimer-buttons"><a class="accept" href="#">Accept</a><a class="cancel" href="#">Cancel</a></div>';
			$('#cboxContent').css({ 'position': 'relative' });
			$('#cboxContent').append(controls);
			$('#cboxControls').css({ 'height': '0' });
			var delayAmount = $.browser.msie ? 150 : 0;
			var timeout = window.setTimeout("$('head').colorbox({ iframe: true, href: '" + disclaimerUrl + "?altTemplate=AjaxDetail', open: true, overlayClose: false, width: '75%', height: '75%' });", delayAmount);

			$().bind('cbox_open', function() {
				$().unbind("keydown.cbox_close");
			});

			$('#cboxClose, .disclaimer-buttons a.cancel').click(function() {
				history.back(1);
				return false;
			});
			$('.disclaimer-buttons a.accept').click(function() {
				$.fn.colorbox.close();
				$('.disclaimer-buttons').remove();
				$('#cboxControls').css({ 'height': 'auto' });
				$('#cboxClose').unbind('click');
				$('#cboxClose').click(function() {
					$.fn.colorbox.close();
				});
				return false;
			});
		}
	},
	External: function() {
		$('.disclaimer-ext').each(function() {
			var browser = navigator.userAgent,
            safariBrowser = (browser.indexOf("Chrome") === -1 && browser.indexOf("Safari") !== -1) ? true : false;
			$(this).click(function() {

				var $this = $(this),
                thisName = this.name,
                questionnaireURL = thisName.substring(thisName.indexOf('at ') + 3, thisName.length),
                urlString = safariBrowser && $this.is('.safari-redirect') ? questionnaireURL : $(this).attr('href'), controls = '<div class="disclaimer-buttons"><a class="accept" href="#">Accept</a><a class="cancel" href="#">Cancel</a></div>',
                hrefString = (browser.indexOf("Chrome") === -1 && browser.indexOf("Safari") !== -1) && $this.is('.view-questionaire') && $this.is('.safari-redirect') ? "/disclaimer/safari-message?altTemplate=AjaxDetail" :
                        "/disclaimer/external-links?altTemplate=AjaxDetail";
				$('#cboxContent').css({ 'position': 'relative' }).append(controls);
				$('.disclaimer-buttons .accept').attr('href', urlString);
				$('#cboxControls').css({ 'height': '0' });
				$().bind('cbox_open', function() {
					$().unbind("keydown.cbox_close");
				});

				$('.disclaimer-buttons a.cancel, #cboxClose').click(function() {
					$.fn.colorbox.close();
					$('.disclaimer-buttons').remove();
					return false;
				});

				$('.disclaimer-buttons a.accept').click(function() {
					$.fn.colorbox.close();
					$('.disclaimer-buttons').remove();
					$('#cboxControls').css({ 'height': 'auto' });
					window.open(this.href);
					return false;
				});

				$this.colorbox({ iframe: true, href: hrefString, open: true, overlayClose: false, width: '75%', height: '75%%' });

				return false;
			});
		});
	},
	Breast: function() {
		$('.mod-breast-best a').click(function() {
			$('head').colorbox({ iframe: true, href: '/disclaimer/breast-feeding?altTemplate=AjaxDetail', open: true, width: '75%', height: '75%' });
			return false;
		});
	},

	//The disclaimer cookie is used to ensure the user gets disclaimer popup if they were previously
	//redirected to the login page (but retained the /products-available URL)

	//This function is called only from HomePage (with login form), if URL is product URL, create cookie
	//to show we were redirected.
	CreateCookie: function() {
		if (document.location.href.match("products-available")) {
			CookieManager.create("showDisclaimer", "1", "1");
			//Sets flag so cookie isn't deleted after being created on homepage
			$(".home-public-login").data("delete", true);
		}
	},
	
	//This function is called on every page except homepage, (at the end of all JS), unset cookie if it's sets
	DeleteCookie: function() {
		if (CookieManager.read("showDisclaimer") && $(".home-public-login").data("delete") != true) {
			CookieManager.erase("showDisclaimer");
		}
	}

}

//Colorbox galleries
var Colorbox = {
	Init: function() {
		$('.colorbox').colorbox();
		$().bind('cbox_complete', function() {
			Frontend.Colorbox.Adjust();
		});

		$().bind('cbox_load', function() {
			$('#cboxTitle, #cboxControls').hide();
		});
	},
	Adjust: function() {
		var padding = 10;

		if ($('#cboxTitle').height() == 0) padding = 0;

		var newHeight = $('#cboxContent').height() + $('#cboxControls').height() + $('#cboxTitle').height() + padding;
		var deltaWhy = newHeight - $('#cboxContent').height() + padding;

		//console.log('[content height:' + $('#cboxContent').height() + '][controls height:' + $('#cboxControls').height() + '][title height:' + $('#cboxTitle').height() + ']' + 'change in height is:' + deltaWhy);

		$('#colorbox').css({ 'height': $('#colorbox').height() + deltaWhy });
		$('#cboxMiddleLeft').css({ 'height': $('#cboxMiddleLeft').height() + deltaWhy });
		$('#cboxMiddleRight').css({ 'height': $('#cboxMiddleRight').height() + deltaWhy });
		$('#cboxWrapper').css({ 'height': $('#cboxWrapper').height() + deltaWhy });
		$('#cboxContent').css({ 'height': newHeight + padding });

		if ($('#cboxTitle').text() != '') { $('#cboxTitle').fadeIn(900); }
		if ($('#cboxControls').text() != '') { $('#cboxControls').fadeIn(900); }
	}
}

//biggerclick
var BiggerClick = {
    Init: function() {

        $('.clickable').each(function() {
            $(this).hover(function() {
                $(this).addClass('hover');

            }, function() {
                $(this).removeClass('hover');
            });
        });

        $('.clickable').click(function() {
            if ($(this).find('a:first').attr('rel') == 'external') {
                window.open($(this).find('a').eq(0).attr('href')); return false;
            } else {
                if ($(this).find('a').eq(0).hasClass('disclaimer-ext')) {
                    $(this).find('a').eq(0).trigger('click');
                } else {
                    window.location = $(this).find('a').eq(0).attr('href'); return false;
                }
            }
        });

        $('.clickable a').each(function() {
            if ($(this).hasClass('download')) {
                $(this).unbind('click');
                $(this).click(function() {
                    window.open($(this).attr('href')); return false;
                });
            }
        });

        $('.clickable.download-listing a.ind, .clickable.video-listing a.ind').each(function() {
            $(this).unbind('click');
            alert('here');
        });

    }
}

//footnotes
var Footnotes = {
	Init: function(type) {
		$('form').append('<div style="display:none;" class="ref-holder"><div class="wrapper"></div></div>');

		var indexRegExp = new RegExp("[^0-9$]", "g");
		var list = type != 'glossary' ? $('body').find('.reference-list ol:first') : $(this).parent().parent().find('.reference-list ol:first');

		$('sup').each(function() {
			if (!$(this).parent().hasClass('reference')) {
				var addRef = false;
				//check if it should be a reference
				var indexes = $(this).text();
				var indexArray = indexes.split(indexRegExp);
				for (var i = 0; i < indexArray.length; i++) {
					if (indexArray[i] != '') {
						var index = indexArray[i] - 1;
						if (list.find('li').eq(index).length > 0) {
							addRef = true;
						}
					}
				}
				if (addRef) {
					$(this).wrap('<span class="reference"></span>');
				}
			}
		});

		$('.reference').each(function() {
			$(this).hover(
				function() {
					var show = false;
					var refOffset = $(this).offset();
					var indexes = $(this).find('sup').text();
					var indexArray = indexes.split(indexRegExp);
					var newHtml = '';

					//console.log($(this).find('sup').text());
					for (var i = 0; i < indexArray.length; i++) {
						if (indexArray[i] != '') {
							var index = indexArray[i] - 1;
							if (list.find('li').eq(index).length > 0) {
								newHtml += '<strong class="ref-title">REFERENCE ' + (index + 1) + ':</strong>';
								newHtml += list.find('li').eq(index).html();
								show = true;
							}
						}
					}

					if (show) {
						$('.ref-holder .wrapper').html(newHtml);
						var leftAdjust = ($('.ref-holder').width() * -1) / 2 + 20;
						var topAdjust = $('.ref-holder').height() + $(this).height();
						$('.ref-holder').css({ 'top': Math.floor(refOffset.top - topAdjust) + 'px', 'left': Math.floor(refOffset.left + leftAdjust) + 'px' });
						if (jQuery.browser.msie && jQuery.browser.version.substr(0, 1) == "7") {
							$('.ref-holder').show();
						} else {
							$('.ref-holder').fadeIn(150);
						}
					}
				}, function() {
					$('.ref-holder').hide();
				}
			);
		});
	}
}

/***** List filtering ***********************************/
function Querystring(qs) { // optionally pass a querystring to parse
	this.params = {};

	if (qs == null) qs = location.search.substring(1, location.search.length);
	if (qs.length == 0) return;

	// Turn <plus> back to <space>
	// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ');
	var args = qs.split('&'); // parse out name/value pairs separated via &

	// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var name = decodeURIComponent(pair[0]);
		var value = (pair.length == 2) ? decodeURIComponent(pair[1]) : name;
		this.params[name] = value;
	}
}

Querystring.prototype.Get = function(key, default_) {
	var value = this.params[key];
	return (value != null) ? value : default_;
}

Querystring.prototype.Contains = function(key) {
	var value = this.params[key];
	return (value != null);
}


var FilterList = {
	Init: function(niceurl) {
		// Parse the current page's querystring
		var qs = new Querystring();
		var currentFilter = qs.Contains('filter') ? qs.Get('filter') : '';

		if (currentFilter.length > 0) {
			$('.list-filter option').each(function() {
				if ($(this).val() == currentFilter)
					$(this).attr('selected', 'selected');
			});
		}

		$('.list-filter').change(function() {
			var newfilter = $('.list-filter option:selected').val();
			var redirectUrl = newfilter.length > 0 ? niceurl + "?filter=" + newfilter : niceurl;
			//console.log(redirectUrl);
			window.location = redirectUrl;
		});
	}
}
/***** / List filtering *********************************/

var Comparison = {
	Init: function() {
		$('.mod-promo-comparison .link-btn').click(function() {
			var url = $(this).attr('href');
			var name = 'window' + (Math.random() * 99);
			var maxWidth = $(window).width();
			var maxHeight = $(window).height();
			var optns = 'toolbar=0, scrollbars=yes, location=0, statusbar=0, menubar=0, resizable=yes, width=900, height=500, left=' + (maxWidth - 900) / 2 + ', top=' + (maxHeight - 500) / 2;
			optns = optns.substring(0, optns.length - 1);
			newpopup = window.open(url, 'name', optns);
			return false;
		});
	},
	DecisionTreeInit: function() {
		$('.mod-decision .view').click(function() {
			var url = $(this).attr('href');
			var name = 'window' + (Math.random() * 99);
			var maxWidth = $(window).width();
			var maxHeight = $(window).height();
			var optns = 'toolbar=0, scrollbars=yes, location=0, statusbar=0, menubar=0, resizable=yes, width=900, height=500, left=' + (maxWidth - 900) / 2 + ', top=' + (maxHeight - 500) / 2;
			optns = optns.substring(0, optns.length - 1);
			newpopup = window.open(url, 'name', optns);
			return false;
		});
	}
}

var NutritionTable = {
	Init: function() {
		var OpenChar = '[';
		var EndChar = ']';
		$('.nutrition-table td').each(function() {
			var copy = $(this).html();
			if (copy.indexOf(OpenChar) > 0 && copy.indexOf(EndChar) > 0) {
				copy = copy.replace(OpenChar, '<sub>').replace(EndChar, '</sub>');
			}
			$(this).html(copy);
		});
	}
}


/****** search enter click ******************************/
var Search = {
	Init: function() {
		$('.site-search .input-field').keydown(function(ev) {
			if (ev.keyCode == 13) {
				ev.preventDefault();
				ev.stopPropagation();
				$(this).parent("fieldset").children(".input-btn").trigger('click');
				return false;
			}
		});
	}
}


var Frontend = {
	PageControls: PageControls,
	TableOfContents: TableOfContents,
	TableAlternateRow: TableAlternateRow,
	TabbedContent : TabbedContent,
	Expanders: Expanders,
	DecisionTreeTwo: DecisionTreeTwo,
	HomepageLogin: HomepageLogin,
	Disclaimer: Disclaimer,
	Colorbox: Colorbox,
	BiggerClick: BiggerClick,
	Footnotes: Footnotes,
	FilterList: FilterList,
	Comparison: Comparison,
	NutritionTable: NutritionTable,
	Search: Search,
	EmailFriend: EmailFriend
};

/****** google analytics ******************************/
Tracking = {

	GoogleAnalytics: (function () {

		function TrackAsEvent(category, action, label) {
			if (typeof _gaq != 'undefined') {
				_gaq.push(['_trackEvent', category, action, label]);
			}
		}

		return {
			TrackAsEvent: TrackAsEvent
		}
	})()
}
