//smartsite site root: equivalent to ~/
var siteroot = (typeof(fullsiteroot) == "function") && (typeof(sitehost) == "function") ? fullsiteroot().replace(sitehost(), "") : "/";
//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");
	$("neosure").checked=
		$("isomil1").checked=
		$("isomil2").checked=
		$("gogrow").checked=
		$("advance").checked=false;
	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){
			$$(".productoption", ".productquestion").each(function(e){
				e.removeClassName("hidden");
			})
			$$(".younger").each(function(e){
				e.addClassName("hidden");
			})
		}
		else{
			$$(".productoption", ".productquestion").each(function(e){
				e.removeClassName("hidden");
			})
			$$(".older").each(function(e){
				e.addClassName("hidden");
			})
		}
	}
	else{
		$$(".productoption", ".productquestion").each(function(e){
			e.addClassName("hidden");
		})
		return false;
	}
}
function checkDate(fld)
{
	var rtn		= false;
	var day		= $(fld+"day");
	var month	= $(fld+"month");
	var year	= $(fld+"year");
	if (day!=null && month!=null && year!=null)
	{
		if (day.selectedIndex>0 &&
			month.selectedIndex>0 &&
			year.selectedIndex>0)
		{
			var m=new Date(year.value,month.value-1,1);
			var v=new Date(year.value,month.value-1,day.value);
			rtn=(m.getFullYear()==v.getFullYear() && m.getMonth()==v.getMonth());
		}
	}
	return rtn;
}
//
function togglefeedingquestion (e){
	var e = $(e);
	$("breastfeedq").addClassName("hidden");
	$("suppageq").addClassName("hidden");
	$("formulaq").addClassName("hidden");
	$("breastfeed-exclusive").style.display="none";
	$("breastfeed-total").style.display="none";
	$("formula").selectedIndex=$("suppage").selectedIndex=$("breastfeedperiod").selectedIndex=0;
	if(e.selectedIndex == 1)
	{
		$("breastfeed-exclusive").style.display="inline";
		$("breastfeedq").removeClassName("hidden");
	}
	if(e.selectedIndex == 2)
	{
		$("breastfeed-total").style.display="inline";
		$("breastfeedq").removeClassName("hidden");
		$("suppageq").removeClassName("hidden");
		$("formulaq").removeClassName("hidden");
	}
	if(e.selectedIndex == 3)
	{
		$("formulaq").removeClassName("hidden");
	}
}

// show hospital options according province that user choosed
function showhospital(index){
	for(i=1;i<$("hprovince").options.length;i++)
	{	$("hospital" + i).addClassName("hidden");
	}
	$("hospital" + index).removeClassName("hidden");
}

//
function autofocus(e, target){
	var e = $(e);
	var target = $(target);
	if(e.value.length == 3) {
		target.focus();
	}
}

function makePopupWindow() {
	var w = document.createElement("div");
	w.className = "popup";
	document.body.appendChild(w);
	w = $(w);
	w.close = function () {
		printfire("closing popup");
		// 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");
}


function openModal (url) {
	var popup = makePopupWindow();
	popup.innerHTML = "\
			<div class='hidden modal-container'>\
				<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, onComplete : function() {
			container.removeClassName("hidden");
			var body = popup.down(".modal-body");
			var y = window.pageYOffset || document.documentElement.scrollTop;
			popup.select(".modal-mask,.modal-mask iframe").invoke("setStyle", {
				height : (document.documentElement.scrollHeight || y) + "px",
				width : document.body.offsetWidth + "px"
			});
			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"
			});
		}});
	popup.down("a.modal-closer").observe("click", function() {
		popup.close();
	});
}

// true if elt is within a modal dialog
function isWithinModalDialog(elt) {
	return elt.up("div.modal-container") != null;
}

function modalPopupContainer(elt) {
	return getPopupContainer(elt);
}


// 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) {
	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);
	}
}


// 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 invalidDateErr=$("babybirthdaydateerror")
	if (invalidDateErr!=null)
		invalidDateErr.addClassName("hidden");
	if ($('birthday').selectedIndex > 0 &&
			$('birthmonth').selectedIndex > 0 &&
			$('birthyear').selectedIndex > 0 ) {
		if (invalidDateErr!=null && !checkDate("birth"))
		{	invalidDateErr.removeClassName("hidden");
			isValid = false;
		}else
		{	$('babybirthdayerror').addClassName("hidden");
		}
	} else {
		isValid = false;
		$('babybirthdayerror').removeClassName("hidden");
	}


	// Must choose sample product
	if(!$$(".productquestion")[0].hasClassName("hidden")) {
		if (! hasRadioSelection("product")) {
			isValid = false;
		}
	}
	//comment out for ticket 189825 --shen
	/*
	if (! hasRadioSelection("contact")) {
		isValid = false;
	}
	*/

	if (!hasRadioSelection("language")) {
		$("languageerror").removeClassName("hidden");
		isValid = false;
	}else
	{
		$("languageerror").addClassName("hidden");
	}
/*
	if ($("contact_yes").checked) {
		// If choose yes for receiving phone calls, Validate which language user perfer
		if (! hasRadioSelection("language")) {
			$("languageerror").removeClassName("hidden");
			isValid = false;
		}
	} else {
		$("languageerror").addClassName("hidden");
	}
*/
	invalidDateErr=$("mombirthdaydateerror");
	invalidDateErr.addClassName("hidden");
	if ($('momdobday').selectedIndex > 0 &&
		$('momdobmonth').selectedIndex > 0 &&
		$('momdobyear').selectedIndex > 0 )
	{
		if (invalidDateErr!=null && !checkDate("momdob"))
		{	invalidDateErr.removeClassName("hidden");
			isValid = false;
		}else
		{	$('mombirthdayerror').addClassName("hidden");
		}
	} else {
		isValid = false;
		$('mombirthdayerror').removeClassName("hidden");
	}

	if (! hasRadioSelection("isfirst")) {
		isValid = false;
	}

	if ($("isfirst_no").checked) {
		//if it's not the first child, then validate question previous child's age and feeding method
		if($("previousyear").selectedIndex == 0 && $("previousmonth").selectedIndex == 0){
			isValid = false;
			$("previousageerror").removeClassName("hidden");
		}
		else $("previousageerror").addClassName("hidden");
	} else{
		$("previousageerror").addClassName("hidden");
	}


	if (! hasRadioSelection("twins")){
		isValid = false;
	}

	$("hospitalerror").addClassName("hidden");
	if ($("hprovinceerror").hasClassName("hidden"))	//error not shown, so prov selected
	{
		var pro=$("hprovince");
		if ($("hospital"+pro.selectedIndex).selectedIndex==0)
		{
			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");

	return isValid;
}
function hidePrevChild()
{	$('previouschild').addClassName('hidden');
	$("previousyear").selectedIndex=
		$("previousmonth").selectedIndex=
		$("previousformula").selectedIndex=0;
}

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");
					}
			}
	}

	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-1"] = /[0-9]{3}/;
	validatorRe["phone-2"] = /[0-9]{3}/;
	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"];
	for (var i=0;i<toHide.length;i++)
	{
		if ($(toHide[i])) $(toHide[i]).addClassName("hidden");
	}
	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($(errormsg)) {
			var hasValue = (fld.value.length > 0);
			if (! hasValue) {
				printfire("Field " + fld.id + " not provided");
				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($(validmsg)){
			if(fld.value.length != 0) {
						var re = validatorRe[fld.id];
						if (re) {
							if (fld.value.match(re)) {
								if (validmsg.indexOf("postalcode")<0 && validmsg.indexOf("phone")<0)
								{	$(validmsg).addClassName("hidden");
								}
							} else {
								printfire("Field " + fld.id + " failed validation re");
								isValid = false;
								$(validmsg).removeClassName("hidden");
							}
						}
					} else if (validmsg.indexOf("postalcode")<0 && validmsg.indexOf("phone")<0) {
						$(validmsg).addClassName("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;
}

Event.observe(window, "load", function() {
	$$(".klick-popup").each(function(el){
		el.observe("click", function(e){
			Event.stop(e);
			openModal(this);
		})
	})
	
	$$(".klick-expandablemenu").each(function(el){
		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;
				})
			})
		})
	})
	
	$$(".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");
				}
			}
		})		
	})
	
	$$("a.q").each(function(el){
		el.observe("click", function(e) {
			e.stop();
			el[el.hasClassName("expanded") ? 'removeClassName' : 'addClassName']("expanded");
			el.next(".a")[el.next(".a").hasClassName('hidden') ? 'removeClassName' : 'addClassName']("hidden");
			
		})		
	})
	
	$$(".expandall").invoke("observe", "click", function(e){
		e.stop();
		$$("a.q").invoke("addClassName", "expanded");
		$$(".a").invoke("removeClassName", "hidden");
	})
	
	$$(".collapseall").invoke("observe", "click", function(e){
		e.stop();
		$$("a.q").invoke("removeClassName", "expanded");
		$$(".a").invoke("addClassName", "hidden");
	})
});

var pregnancy = function(month){location.href= siteroot + lang + "/articles_advice/pregnancy_month" + month + "/";}
var baby = function(month){location.href= siteroot + lang + "/articles_advice/first_year_month" + month + "/";}
var page = function(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;
	}
}
var send = function() {
	openModal(siteroot + lang + "/send_to_friend/");
}

var facebook = function() {
	window.open('http://www.facebook.com/sharer.php?u='+escape(server + location.pathname), 'sharer', 'toolbar=0,status=0,width=626,height=436');
}
