//smartsite site root: equivalent to ~/
var siteroot = (typeof(fullsiteroot) == "function") && (typeof(sitehost) == "function") ? fullsiteroot().replace(sitehost(), "") : "/";

function appUrl (pn) {
  return siteroot + (siteroot.endsWith("/") ? "" : "/") +(pn.startsWith("/") ? pn.substr(1) : pn);
}

function siteRelativeUrl(url) {
	return url.replace("http://" + window.location.host, "");
}
	
//language
var lang = location.href.indexOf("/en/") > - 1 ? "en" : "fr";

//fixes double slash in URLs
function normalizePath (string) {return string.replace(/(\/+)|\\+/g, "/");}

//escapes <, > & and " into corresponding html entities
var reAmpersand = new RegExp("&", "g");
var reLessthan = new RegExp("<", "g");
var reGreaterthan = new RegExp(">", "g");
var reQuote = new RegExp("\"", "g");

function escapeHTML(string) {return string.replace(reAmpersand, "&amp;").replace(reLessthan, "&lt;").replace(reGreaterthan, "&gt;").replace(reQuote, "&quot;");}
//rounds a number to two decimals places. Returns a string
function toCurrency (number) {return number.toFixed(2);}

//IE background image cache script
//@cc_on document.execCommand("BackgroundImageCache", false, true);

//IE load drawing bug fix
//@cc_on document.documentElement.style.display = "none"
//@cc_on Event.observe(window, "load", function() {document.documentElement.style.display = "block"});

//toggle product sample options according baby's birthday
function toggleproductoption (){
	
	var day = $("birthday");
	var month = $("birthmonth");
	var year = $("birthyear");
	
	var cls = 'none';
	if (day.selectedIndex > 0 && month.selectedIndex > 0 && year.selectedIndex > 0) {
		var d = new Date(year.value,month.value,day.value);
		var today = new Date();
		if (d.getTime() < today.getTime() - 1000*60*60*24*180) {
			cls = 'older';
		} else {
			cls = 'younger';
		}
	}
	
	$$(".productoption,.productquestion").each(function(e) {
		if (e.hasClassName(cls)) {
			e.removeClassName("hidden");
		} else {
			e.addClassName("hidden");
			var input = e.down('input');
			if (input) {
				input.checked = false;
			}
		}
	})
	return false;
}

function hideElement (e) {e.addClassName("hidden");}
function showElement (e) {e.removeClassName("hidden");}

function unhide(divID)
{
   var item = document.getElementById(divID);
   if (item) {
     item.style.display=(item.style.display=='none')?'block':'none';
   }
}

//
function togglefeedingquestion (){
	var i = $('feedby').selectedIndex;
	$("breastfeedq").addClassName("hidden");
	$("suppageq").addClassName("hidden");
	$("formulaq").addClassName("hidden");
	$("breastfeed-exclusive").style.display="none";
	$("breastfeed-total").style.display="none";
	
	if (i == 1)
	{
		$("breastfeed-exclusive").style.display="inline";
		$("breastfeedq").removeClassName("hidden");
	}
	if (i == 2)
	{
		$("breastfeed-total").style.display="inline";
		$("breastfeedq").removeClassName("hidden");
		$("suppageq").removeClassName("hidden");
		$("formulaq").removeClassName("hidden");
	}
	if (i == 3)
	{
		$("formulaq").removeClassName("hidden");
	}
	
	if ($('breastfeedq').hasClassName('hidden')) {
		$('breastfeedperiod').selectedIndex = 0;
	}
	if ($('suppageq').hasClassName('hidden')) {
		$('suppage').selectedIndex = 0;
	}
	if ($('formulaq').hasClassName('hidden')) {
		$('formula').selectedIndex = 0;
	}
	
}

// show hospital options according province that user choosed
function showhospital(){
	provincial_hospital_selectors().each (hideElement);
	var s = current_province_hospital_selector();
	if (s) {s.removeClassName("hidden");}
}

// the selectors for hospitals in each province.  One for each province
function provincial_hospital_selectors () {
	return $("hospital_widget").select("select").reject(function (e) {return e.id=="hprovince";});
}

function current_province_hospital_selector() {
	var province = $("hprovince").options[$("hprovince").options.selectedIndex].value;
	var sl = document.getElementsByName("hospital" + province);
	return sl ? sl[0] : null;
}

function selected_hospital () {
	var s = current_province_hospital_selector();
	return s ? s.options[s.options.selectedIndex].value : null;
}

function focus_next_if_complete (e, nchars, elt) {
	if (e.value.length >= nchars) {
		$(elt).focus();
	}
}


function makePopupWindow() {
	var w = document.createElement("div");
	w.className = "popup";
	document.body.appendChild(w);
	w = $(w);
	w.close = function () {
		// destroy the popup, don't just hide it.  Otherwise if you create a second modal of the same
		// type later on there could be two DOM elements with the same id
		w.remove();
	};
	return w;
}

// true if the element is withi a popup window.
function isWithinPopupWindow(elt) {
	return getPopupContainer(elt) != null;
}

// return the popup up containing elt
function getPopupContainer(elt) {
	return isPopupContainer(elt) ? elt : elt.up("div.popup");
}

// true if elt is popup container
function isPopupContainer(elt) {
	return elt.tagName == "DIV" && elt.hasClassName("popup");
}


// create a (simulated) popup which display the URL
// tracks a page view
function openModal (url, options) {
	var popup = makePopupWindow();
	options = options || {}
	if (options.onClose) {
		popup.close = options.onClose.bind(popup);
	}
	popup.innerHTML = "\
			<div class='hidden modal-container " + options.modalClass + "'>\
				<div class='modal-mask'>" +
					//@cc_on "<iframe frameborder='0' src='javascript:document.write(\"<html><body></body></html>\");document.close();'></iframe>" +
				"</div>\
				<div class='modal-body'>\
					<a class='modal-closer' href='javascript:;'></a>\
					<div class='modal-content'></div>\
				</div>\
			</div>\
		";
	var container = popup.down("div.modal-container");
	new Ajax.Updater(popup.select(".modal-content")[0], url, {
			method:"GET", 
			evalScripts : true, 
			parameters: options.parameters || {},
			onComplete : function() {
				pageTracker._trackPageview(url);
				showModalDialogue(popup);
				if (options.onComplete) {
					options.onComplete.call(popup);
				}
		}});
	popup.down("a.modal-closer").observe("click", function() {
		// the modal close is "non-interaction"
		pageTracker._trackEvent("Popup", "close", url, 0, true);
		popup.close();
	});
}

function showModalDialogue (popup) {
	popup.down(".modal-container").removeClassName("hidden");
	var body = popup.down(".modal-body");
	var scroll = document.body.scrollTop || document.documentElement.scrollTop;
	var centered = ((document.viewport.getHeight() / 2) - (body.offsetHeight / 2));
	popup.select(".modal-body").invoke("setStyle", {
		top : (centered < 0 ? 20 : centered) + scroll + "px",
		left : ((document.viewport.getWidth() / 2) - (body.offsetWidth / 2)) + "px"
	});
	var popupbottom = body.cumulativeOffset().top + body.offsetHeight + 20
	var height = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, popupbottom)
	popup.select(".modal-mask,.modal-mask iframe").invoke("setStyle", {
		height : height + "px",
		width : document.body.offsetWidth + "px"
	});
}

// true if elt is within a modal dialog
function isWithinModalDialog(elt) {
	return elt.up("div.modal-container") != null;
}

function modalPopupContainer(elt) {
	return getPopupContainer(elt);
}

function initialize_club_form () {
  Calendar.setup(
    {
      inputField  : "expect_date",
      ifFormat    : "%d/%m/%Y",
      button      : "expect_date_calendar"
		,range: [ new Date().getFullYear() - 1, new Date().getFullYear() + 1]
		,dateStatusFunc: dateStatusHandler
    }
  );
	$("postalcode-1").observe("keyup", function (evt) {focus_next_if_complete(this, 3, "postalcode-2");});
	$("phone-2").observe("keyup", function (evt) {focus_next_if_complete(this, 3, "phone-3");});
	$("expect_date").observe("change", validateDueDate);
	$("hprovince").observe("change", showhospital);
}


// If due date is valid, show product choices.
// If not, show complaint.
function validateDueDate (evt) {
	var dt = Date.parseExact(this.value, "dd/MM/yyyy");
	if (dt) {
		$("babybirthdayerror").addClassName("hidden");
		if (isPlausibleDueDate(dt)) {
			$('productquestion').removeClassName('hidden');
			$("babybirthdaydateerror").addClassName("hidden");
		} else {
			$('productquestion').addClassName('hidden');
			$("babybirthdaydateerror").removeClassName("hidden");
			$("babybirthdaydateerror").up("div.error").removeClassName("hidden");

		}
	} else {
		$('productquestion').addClassName('hidden');
		$("babybirthdaydateerror").addClassName("hidden");
		$("babybirthdayerror").removeClassName("hidden");
	}
}

//http://www.datejs.com/
function isPlausibleDueDate (dt) {
	return dt >= dueDateRange[0] && dt <= dueDateRange[1];
}

// due date must be from twelve months in the past to 12 months in the future
var dueDateRange = [new Date().add(-12).month(), new Date().add(12).month()];

// See http://www.dynarch.com/static/jscalendar-1.0/doc/html/reference.html#node_sec_5.3.8
function dateStatusHandler(date, y, m, d) {
	// surprisingly, false means no special status, aka enabled.
	return isPlausibleDueDate(date) ? false : "disabled";
}

function autofocus(el, next) {
	if (el.value.length == el.maxLength) $(next).focus()
}

// return true to continue to submit the form
function submit_form(btn) {
	btn.blur();
	var form = $(btn).up("form");
	if (isFormValid	(form)) {
 		if ($("isSubmit")) { $("isSubmit").value = "1";}

		if (form.id == "swac-form") {
			// set the productcode hidden input to the ID of the product choice
			// The VALUE of the product choice is a human visible string and could easily change
			// product code on the other hand, we can trust it.
			var productelt = getSelectedRadioElement("product");
			if (productelt) {
				if ($("productcode")) {
					$("productcode").value = productelt.id;
				}
			}
		}
		
		if (isWithinModalDialog(btn)) {
			// If submit is inside a modal dialog, we do NOT want to submit the form since that
			// would change the outer page.  Instead we just post to the server.
			// Depending on circumstance, we want to either close the dialog (we're done)
			// or do some kind of ajax update to get new contents in the window
			// but in any case we do not want to submit.
			// For now, assuming we always just close it
			var titletext = (lang == 'en') ? 'Send this page to a friend' : 'Envoyer cette page &#224; un ami';
			var thanktext = (lang == 'en') ? 'Thank you' : 'Merci';
			 new Ajax.Request(form.action,
			 {
				 parameters: form.serialize(),
				 onComplete: function () {
					 modalPopupContainer(btn).down("div.modal-content").innerHTML = "<div class='sendtofriend'><h1>" + titletext + "</h1><p>" + thanktext + "</p></div>";
				 }
			 });
		} else {
			form.submit();
		}
	} else {
		showErrorBoxes(form);
	}
	return false;
}


// Run form-specific validation for form with id.
function isFormValid(form) {
	try {
	switch (form.id) {
	case "swac-form":
		return isSwacValid(form);
	case "share-form":
		return isShareValid(form);
	case "frmSendToAFriend":
		return isSendToAFriendValid(form);
	default:
		printfire("using generic validator for form");
		return isGenericValid(form);
	}
	} catch (e) {
		printfire("While validating form: " + e);
		return false;
	}
}


// validate Swac form.  Show error messages if needed
// return true if valid
function isSwacValid (form) {
	var isValid = true;

	$("bfperioderr").style.display="none";
	$("bfexclusiveerr").style.display="none";
	$("breastfeedperiod-err").addClassName("hidden");
	if ($("breastfeedperiod").selectedIndex == 0)
	{
		if($("feedby").selectedIndex == 1)
		{
			$("breastfeedperiod-err").removeClassName("hidden");
			$("bfexclusiveerr").style.display="inline";
		}
		else if($("feedby").selectedIndex == 2)
		{
			$("breastfeedperiod-err").removeClassName("hidden");
			$("bfperioderr").style.display="inline";
		}
	}
	
	isValid = isCommonValid(form);

	var dreamErr = $("dreamerror");
	if (dreamErr) {
		dreamErr.addClassName("hidden");
		if (($('dreamdescription').value||'').trim()=='' && ($('picture').value||'').trim()=='') {
			dreamErr.removeClassName("hidden");
			isValid = false;
		}
	}
	
	var invalidDateErr=$("babybirthdaydateerror");
	if (invalidDateErr) {
		invalidDateErr.addClassName("hidden");
	}
	
	if ($("expect_date").value == "") {
		isValid = false;
		$('babybirthdayerror').removeClassName("hidden");
	} else {
		$('babybirthdayerror').addClassName("hidden");
		if (isValidDateString($("expect_date").value)) {

		} else {
			isValid = false;
			invalidDateErr.removeClassName("hidden");
		}
	}

	// Must choose sample product
	if(!$$(".productquestion")[0].hasClassName("hidden")) {
		if (! hasRadioSelection("product")) {
			isValid = false;
		}
	}
	if (!hasRadioSelection("language")) {
		$("languageerror").removeClassName("hidden");
		isValid = false;
	}
	else {
		$("languageerror").addClassName("hidden");
	}
	
	if (! hasRadioSelection("isfirst")) {
		isValid = false;
	}

	if (! hasRadioSelection("twins")){
		isValid = false;
	}

	$("hospitalerror").addClassName("hidden");

	// relies on fact that the common validation code will have marked
	// the province drop down as in error if no province selected
	if ($("hprovinceerror").hasClassName("hidden")) {
		if (! selected_hospital()) {
			isValid = false;
			$("hospitalerror").removeClassName("hidden");
		}
	}

	// check if confirm email match email
	if($('email').value != $('emailcfm').value){
		$('emailcfmerror2').removeClassName("hidden");
		isValid = false;
	}
	else $('emailcfmerror2').addClassName("hidden");

	if (! isValid) {
		pageTracker._trackEvent("Form", "invalid", document.location.pathname);
	}

	return isValid;
}

// dd/MM/yyyy
var reDateString = new RegExp("[ 0123][0-9]/[ 01][0-9]/[12][0-9]{3}", "g");
function isValidDateString (s) {
	return s.match(reDateString);
}


function isSendToAFriendValid(form) {
	var isValid = true;

	if ($('share_sender').value == "") {
		$('share_sendererror').removeClassName("hidden");
		isValid = false;
	} else {
		 $('share_sendererror').addClassName("hidden");
	}

	if ($('share_receiver').value == "") {
		$('share_receivererror').removeClassName("hidden");
		isValid = false;
	} else {
		$('share_receivererror').addClassName("hidden");
	}

	if ($('share_semail').value == "") {
		$('share_semailerror').removeClassName("hidden");
		isValid = false;
	} else {
		$('share_semailerror').addClassName("hidden");

			if (! $('share_semail').value.match(/[-a-zA-Z0-9\.]+@[-a-zA-Z0-9\.]+.[-a-zA-Z0-9\.]/)) {
					isValid = false;
					$("share_semailvalid").removeClassName("hidden");
			} else {
					$("share_semailvalid").addClassName("hidden");

					// check if confirm email match email
					if($('share_semail').value != $('share_semailcfm').value){
							$('share_semailcfmerror2').removeClassName("hidden");
							isValid = false;
					} else {
							$('share_semailcfmerror2').addClassName("hidden");
					}
			}
	}

	if (! isValid) {
		pageTracker._trackEvent("Form", "invalid", "share");
	}


	return isValid;
}

function isShareValid(form) {
	var isValid = true;

	isValid = isCommonValid(form);

	// check if confirm email match email
	if($('email').value != $('emailcfm').value){
		$('emailcfmerror2').removeClassName("hidden");
		isValid = false;
	}
	else $('emailcfmerror2').addClassName("hidden");

	return isValid;
}



// Apply validations that are "generic"
function isGenericValid(form) {
	var isValid = isCommonValid(form);
	return isValid;
}

// validations that are common to all forms.
// validate form, return true if valid.
// validations are applied only if error message elements exist (otherwise
// we'd be saying the form is invalid, but not telling the user what's wrong.)
// there can be a message for value not provided:
//   it is a DOM element whose id is the id + "error"
// there can be a message for value not in correct format:
//   it is a DOM element whose id is the id + "valid"
function isCommonValid (form) {
	var isValid = true;

	// map from DOM id to a regular expression applied to the value
	// of the TEXT element with that id
	var validatorRe = {};
	// key is the DOM id
	validatorRe["email"] = /[-a-zA-Z0-9\.]+@[-a-zA-Z0-9\.]+.[-a-zA-Z0-9\.]/;
	validatorRe["semail"] = /[-a-zA-Z0-9\.]+@[-a-zA-Z0-9\.]+.[-a-zA-Z0-9\.]/;
	validatorRe["phone-2"] = /[2-9][0-9][0-9]/;
	validatorRe["phone-3"] = /[0-9]{4}/;
	validatorRe["postalcode-1"] = /[a-zA-Z][0-9][a-zA-Z]/;
	validatorRe["postalcode-2"] = /[0-9][a-zA-Z][0-9]/;

	var toHide=["postalcodeerror","postalcodevalid","phoneerror","phonevalid"];

	reFicticiousPhone = /555-01[0-9][0-9]/;

	for (var i=0;i<toHide.length;i++)
	{
		if ($(toHide[i])) $(toHide[i]).addClassName("hidden");
	}

	// validate each text input.
	form.getElementsBySelector("input[type=text]").each(function(fld){
		var errormsg = String(fld.id).replace(/-.*/gi,"") + "error";
		var validmsg = String(fld.id).replace(/-.*/gi,"") + "valid";

		// if there is an error element, and if the field has not value, show the error element
		if($(errormsg)) {
			var hasValue = (fld.value.length > 0);
			if (! hasValue) {
				isValid = false;
			}
			if (validmsg.indexOf("postalcode")<0 && validmsg.indexOf("phone")<0)
			{	$(errormsg)[! hasValue ? "removeClassName" : "addClassName"]("hidden");
			}else if (!hasValue)
			{	$(errormsg)["removeClassName"]("hidden");
			}
		}

		if ($("language")!=null) {
			if (!hasRadioSelection("language")) {
				isValid = false;
				$("languageerror").removeClassName("hidden");
			} else {
				$("languageerror").addClassName("hidden");
			}
		}

		// if there is a validation element, validate the value
		if($(validmsg)){
			if(fld.value.length != 0) {
				var re = validatorRe[fld.id];
				if (re) {
					if (fld.id.indexOf("email") >= 0)
					{
						// email validation has to be exact
						var fvalt = fld.value.trim();
						if (fvalt.match(re) != fvalt)
						{
							isValid = false;
							$(validmsg).removeClassName("hidden");
						}
						else
						{
							$(validmsg).addClassName("hidden");
						}
					}
					else if (fld.value.match(re)) {
						if (validmsg.indexOf("postalcode")<0 && validmsg.indexOf("phone")<0) {
							$(validmsg).addClassName("hidden");
						}
					} else {
						isValid = false;
						$(validmsg).removeClassName("hidden");
					}
				}
			} else if (validmsg.indexOf("postalcode")<0 && validmsg.indexOf("phone")<0) {
				$(validmsg).addClassName("hidden");
			}
			
			if (fld.id == "phone-3") {
				// ad-hoc: do not allow 555-0100 through 555-0199
				var subscriberNumber = $("phone-2").value + "-" + fld.value;
				if ( subscriberNumber.match(reFicticiousPhone)) {	
					isValid= false;
					$(validmsg).removeClassName("hidden");
				}
			}
		}
	});
	
	form.getElementsBySelector("input[type=checkbox]").each(function(fld){
		var errormsg = fld.id + "error";
		if($(errormsg)){
			if (! fld.checked) {
				isValid = false;
			}
			$(errormsg)[fld.checked ? "addClassName" : "removeClassName"]("hidden");
		}
	});

	// every select that is not hidden must have a selection
	form.getElementsBySelector("select").each(function(fld){
		var errormsg = fld.id + "error";
		if($(errormsg)){
			$(errormsg).addClassName("hidden");
			if(!fld.up("div").hasClassName("hidden")) {
				if (fld.selectedIndex == 0) {
					isValid = false;
				}
				$(errormsg)[fld.selectedIndex > 0 ? "addClassName" : "removeClassName"]("hidden");
			}
		}
	});

	return isValid;
}

// this function is called for all kinds of forms.  Most of it is generic
function showErrorBoxes(form) {
	// hide all error boxes
	form.getElementsBySelector("div.error").each(function(e){e.addClassName("hidden");});

	// for each validation message that is shown, show the containing box
	getFormValidationWarnings(form).each(
		function(e){e.up("div.error").removeClassName("hidden");}
	);

	// This is specific to the swac form.
	var bfp=$("breastfeedperiod-err")
	if (bfp != null && !bfp.hasClassName("hidden"))
	{	bfp.up("div.error").removeClassName("hidden");
	}

	if (! isWithinPopupWindow(form)) {
		// Jump page to the first visible error box
		var elements = form.getElementsBySelector("div.error:not(.hidden)");
		var element = elements ? elements[0] : null;
		if(element) element.scrollIntoView();
	}
}

function getFormValidationWarnings (form) {
	return form.getElementsBySelector("li", "span").select(isComplaint);
}

function isComplaint(e) {
	return  isValidationMessage(e) && !e.hasClassName("hidden");
}

function isValidationMessage(e) {
	return e.id.indexOf("error") > -1 || e.id.indexOf("valid") > -1;
}


function hasRadioSelection (radioname){
	var msg = radioname + "error";
	var hasSelection = getSelectedRadioElement(radioname) != null;
	if ($(msg)) {
		if (hasSelection) {
			$(msg).addClassName("hidden");
		} else {
			$(msg).removeClassName("hidden");
		}
	}
	return hasSelection;
}

function getSelectedRadioElement(radioname) {
	var paras = document.getElementsByName(radioname);
	if(paras) {
		for(var i=0;i<paras.length;i++){
			if(paras[i].checked && !paras[i].up("div").hasClassName("hidden")){
				return paras[i];
			}
		}
	}
	return null;
}

function toggleFaqExpansion(e) {
	e.stop();
	var el = Event.element(e);
	if (el.hasClassName("expanded")) {
		el.removeClassName("expanded");
		pageTracker._trackEvent("FAQ", "Collapse", el.innerHTML);
	} else {
		el.addClassName("expanded");
		pageTracker._trackEvent("FAQ", "Expand", el.innerHTML);
	}
	el.next(".a")[el.next(".a").hasClassName('hidden') ? 'removeClassName' : 'addClassName']("hidden");
}

// called on window load, this function is a grab-bag of miscellaneous handlers
function setEventHandlers () {

	// a hyperlink with class klick-popup opens in (simulated) popup
	$$(".klick-popup").each(function(el){
		el.observe("click", function(e){
			Event.stop(e);
			openModal(this);
		})
	});
	
	$$(".klick-expandablemenu").each(function(el){
		if($(el).down("ul.submenu")){
			el.observe("click", function(e){
				e.stop();
				var submenu = $(this).down("ul.submenu");
				if(submenu.hasClassName("hidden")){
					submenu.removeClassName("hidden");
					$(this).addClassName("selected");
					$(this).addClassName("hassubmenu")
				} else {
					submenu.addClassName("hidden");
					$(this).removeClassName("selected");
					$(this).removeClassName("hassubmenu")
				}
			});
		
			$(el).down("ul.submenu").childElements().each(function(lis){
				lis.childElements().each(function(anchor){
					anchor.observe("click", function(link){
						link.stop();
						location.href = anchor.href;
					})
				})
			});
		}
	});

	$$(".tooltipicon a").each(function(el) {
		var ttcontent = el.title;
		var tooltip = document.createElement("div");
		document.body.appendChild(tooltip);
		tooltip = $(tooltip);
		tooltip.addClassName("flashnavtooltip")
		tooltip.addClassName("hidden")
		tooltip.innerHTML = ttcontent;
		el.observe("mouseover", function(){
			var left = el.viewportOffset().left - 55;
			el.title = "";
			tooltip.setStyle({left:left + "px"});
			tooltip.removeClassName("hidden");
		});
		el.observe(/*@cc_on "mouseleave" || @*/"mouseout", function(){
			el.title = ttcontent;
			tooltip.empty();
			tooltip.addClassName("hidden");
		});
	});
	
	$$(".secondarynav a").each(function(el) {										
		if (('/' + el.pathname).replace('//', '/').replace(/\/index$/,'/') == ('/'+location.pathname).replace('//', '/').replace(/\/index$/,'/')) {
			var nearli = $(el).up("li");
			var nearul = nearli.up("ul");
			var farli = nearul.up("li");
			if(nearul && el.pathname.indexOf('articles_advice') < 0) nearul.removeClassName("hidden")
			if(farli){
				farli.addClassName("selected");
				farli.addClassName("hassubmenu");
			}
		}
	});
	
	$$(".tabs a").each(function(el){		
		el.observe("click", function(e){									 	
			var index = el.href.indexOf("#") + 1;
			var tabs = el.up().childElements("a");

			if (index) {
				e.stop();
				var body = document.getElementById(el.href.substring(index));						
				if (body) {
					for (var tab, i = 0; tab = tabs[i]; i++) {
						tab.removeClassName("selected");
						var target = $(tab.href.substring(index));
						if(target) target.addClassName("hidden");						
					}
					Element.addClassName(el, "selected");
					Element.removeClassName(body, "hidden");
				}
			}
		})		
	});

	// This is for the FAQ page
	$$("a.q").each(function(el){
		el.observe("click", toggleFaqExpansion);
	});
	
	$$(".expandall").invoke("observe", "click", function(e){
		e.stop();
		pageTracker._trackEvent("FAQ", "ExpandAll");
		$$("a.q").invoke("addClassName", "expanded");
		$$(".a").invoke("removeClassName", "hidden");
	});
	
	$$(".collapseall").invoke("observe", "click", function(e){
		e.stop();
		pageTracker._trackEvent("FAQ", "CollapseAll");
		$$("a.q").invoke("removeClassName", "expanded");
		$$(".a").invoke("addClassName", "hidden");
	});
}

function setVideoHandlers () {
	if (typeof flowplayer == "function") {
		if (typeof flowplayer() != "undefined") {
			flowplayer().onStart(function(clip) {
				pageTracker._trackEvent("Video", "Start", document.location.pathname + ":" + clip.url + ":" + clip.fullDuration);
			});
			flowplayer().onFinish(function(clip) {
				pageTracker._trackEvent("Video", "Finish",document.location.pathname + ":" + clip.url + ":" + clip.fullDuration);
			});
		}
	}
}


function pregnancy (month) {
	location.href= siteroot + lang + "/articles_advice/pregnancy_month" + month + "/";}

function baby (month) {
	location.href= siteroot + lang + "/articles_advice/first_year_month" + month + "/";
}

function page (number) {
	switch(number){
		case "1" : 
			location.href = siteroot + lang + "/expecting_moms/";
			break;
		case "2" : 
			location.href = siteroot + lang + "/feeding_baby/";
			break;
		case "3" : 
			location.href = siteroot + lang + "/products/";
			break;
		case "4" : 
			location.href = siteroot + lang + "/similac_welcome_addition_club/";
			break;
		case "5" : 
			location.href = siteroot + lang + "/faq/";
			break;
		case "6" : 
			location.href = siteroot + lang + "/articles_advice/";
			break;
		case "7" :
			location.href = siteroot + lang + "/products/similac_mom/";
			break;
	}
}

// the send to friend page has different appearance depending on what is
// being sent.  This is a map from URL to the "mode"

var send_to_friend_mode = [
	{url: "similac_welcome_addition_club", label: "swac"},
	{url: "similac_mom_club", label: "mom"},
	{url: "dreams_come_true", label: "dct"}
];

// handler for Send to a Friend
function send () {
	var mode = send_to_friend_mode.find(function (m) {return location.href.indexOf(m.url) > -1;}) || null;
	pageTracker._trackEvent("Sharing", "email", location.href);
	openModal(siteroot + lang + "/send_to_friend/" + (mode ? "?mode=" + mode.label : ""));
}

// handler for add to Facebook
function facebook () {
	pageTracker._trackEvent("Sharing", "Facebook", location.href);
	window.open('http://www.facebook.com/sharer.php?u='+escape(server + location.pathname), 'sharer', 'toolbar=0,status=0,width=626,height=436');
}


function print_this() {
	pageTracker._trackEvent("Print", "print", location.href);
	window.print();
}


//dream come true
var entCon = function() {location.href = siteroot + lang + "/dreams_come_true/winner/"}
var viewBoard = function() {location.href = siteroot + lang + "/dreams_come_true/"}

// event handlers specific to the dream come true contest.
Event.observe(window, "load", function() {
	if ($("board")) {
		var images = $$(".board img");
		var count = images.length;
		var current = 0;
		$(images[current]).removeClassName("hidden");
		if (images.length > 1) $("next").removeClassName("hidden")
		$("prev").observe("click", function(e) {
			Event.stop(e)
			if (current != 0) current--
			$$(".board img").invoke("addClassName", "hidden")
			if (current < count - 1) $("next").removeClassName("hidden")
			if (current >= 0) $(images[current]).removeClassName("hidden");
			if (current == 0) $("prev").addClassName("hidden")
		})
		$("next").observe("click", function(e) {
			Event.stop(e)
			if (current < count - 1) current++
			$$(".board img").invoke("addClassName", "hidden")
			if (current > 0) $("prev").removeClassName("hidden")
			if (current < count) $(images[current]).removeClassName("hidden");
			if (current == count - 1) $("next").addClassName("hidden")
		})
	}
})



// standard Cookie util
var Cookie={
	set:function(c_name,value, options) {
		var expireDays = options.expires || 1;
		var today = new Date();
		today.setDate(today.getDate() + expireDays);
		document.cookie=c_name + "=" + escape(value) + ";expires=" + today.toUTCString() + ";path=/";
	},
	get:function(c_name) {
		if (document.cookie.length>0) { 
			c_start=document.cookie.indexOf(c_name + "=");
			if (c_start!=-1) { 
				c_start=c_start + c_name.length+1; 
				c_end=document.cookie.indexOf(";",c_start);
				if (c_end==-1) c_end=document.cookie.length;
				return unescape(document.cookie.substring(c_start,c_end));
			} 
		}
		return null;
	},
	remove:function(c_name) {this.set(c_name,"",-1);}
}

// This function is horribly ad-hoc.  If customer ever wants to change
// content of the interstitial we'll have to modify this also
// this function is called with "this" bound to the popup.
function addInterstitialPageTracking () {
	this.down("map").select("area").each(
		function (elt) {
			var action = elt.hasClassName("GOS") ? "GOS" : "Lutein";
			var label =  siteRelativeUrl(elt.href);
			elt.observe("click",
						function (evt) {
							pageTracker._trackEvent("Interstitial", action, label);
						});
		});
}

function showInterstitial () {
	if(Cookie.get("interstitial") == null || Cookie.get("interstitial") == "true"){
		openModal(siteroot + lang + "/_interstitial/",
				  {modalClass: "modal-interstitial"
				   ,onComplete: addInterstitialPageTracking
				  });
		Cookie.set("interstitial", "false", 1);
	}
}

Event.observe(window, "load", setEventHandlers);
Event.observe(window, "load", setVideoHandlers);

