function AttachPopups(StartElem, NoAppend) {
	//popups:
	//	<a class="klick-popup" href="#the_id_of_the_content_node"> click here to open a popup </a>
	//	<div id="the_id_of_the_content_node">
	//		content goes here
	//		<a class="klick-popup-closer"> This is a custom popup closer </a>
	//	</div>
	Element.select(StartElem, "a.klick-popup").each(function(el) {
		var popup = document.createElement("div");
		document.body.appendChild(popup);
		popup = $(popup);
		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'>\
					<h1><a class='modal-closer' href='javascript:;'>X</a><span id='ModalTitle' class='modal-title'></span></h1>\
					<div class='modal-content'></div>\
				</div>\
			</div>\
		";
		var container = popup.down("div.modal-container");
		var title = popup.down("span.modal-title");
		var body = popup.down("div.modal-content");
		var y = window.pageYOffset || document.documentElement.scrollTop;
		var source = $(el.href.substring(el.href.indexOf("#") + 1));
		var width = source.getStyle("width") ? parseInt(source.getStyle("width")) : 0;
		var height = source.style.height ? parseInt(source.style.height) : 0;
		if (!NoAppend) body.appendChild(source);
		source.removeClassName("hidden");
		
		el.observe("click", function(e) {
			source.style.width = "";
			Event.stop(e);
			body.appendChild(source);
			title.innerHTML = el.title + "&nbsp;";
			container.removeClassName("hidden");
			
			popup.select(".modal-mask").invoke("setStyle", {
				height : document.documentElement.scrollHeight + document.documentElement.scrollTop + 40 + "px",
				width : document.body.offsetWidth + "px"
			});
			var scroll = document.body.scrollTop || document.documentElement.scrollTop;
			var top = (document.documentElement.scrollTop || document.body.scrollTop) + 20;
			var centered = ((document.viewport.getHeight() / 2) - ((height ? height : body.offsetHeight) / 2));
			
			var top = parseInt((centered < 0 ? top : centered) + scroll);
			var left = parseInt((document.viewport.getWidth() / 2) - ((width ? width : body.offsetWidth) / 2));
			popup.select(".modal-body").invoke("setStyle", {
				top : top + "px",
				left : left + "px",
				width : (width ? width + "px" : "auto")
			});

			if(window.onPopupOpenAlways && String(typeof(window.onPopupOpenAlways)) == 'function'){
				window.onPopupOpenAlways();
			}
		});
		popup.down("a.modal-closer").observe("click", function(e) {
			Event.stop(e);
			if(window.onPopupClose && String(typeof(window.onPopupClose)) == 'function'){
				window.onPopupClose();
			}
			
			container.addClassName("hidden");
			// reset the function to do nothing
			//window.onPopupClose = null;
		});
	});
	Element.select(StartElem, "a.klick-popup-closer").each(function(el) {
		el.observe("click", function(e) {
			Event.stop(e);
			if(window.onPopupClose && String(typeof(window.onPopupClose)) == 'function'){
				window.onPopupClose();
			}
			
			$(this).up("div.modal-container").addClassName("hidden");
			// reset the function to do nothing
			//window.onPopupClose = null;
		})
	});
	Element.select(StartElem, "a.klick-toggle").each(function(el) {
		var text = el.title.split("/")
		el.observe("click", function() {
			var body = this.up(".showhideheader").next(".l");
			body.toggleClassName("hidden");
			this.innerHTML = body.hasClassName("hidden") ? text[0] : text[1];
			this.toggleClassName("show");
		});
	});
}

Event.observe(window,"load", function () {AttachPopups(document.body); 
	if ($("homepagemodalcontainer") && showNag){
		$("homepagemodalcontainer").removeClassName("hidden");
		var pageDimensions = xDocSize();
		$("homepagemodalmask").setStyle({
			height : pageDimensions["h"] + "px",
			width : pageDimensions["w"] + "px"	
		});
		var width = parseInt($("homepagemodalbody").getStyle("width"))
	
		$("homepagemodalbody").setStyle({
			top:(document.documentElement.scrollTop + 100) + "px",
			left:(document.body.offsetWidth / 2) - (width / 2) + "px"
		});
	}
	
	// look for any elements with class SavedP and highlight them
	$A(document.getElementsByClassName('SavedP')).each(function(elem){
		new Effect.Highlight(elem, {duration: 1, startcolor: '#FDB825' });
	});	
	
});

// PRINT FUNCTION

function printIt(){  
    window.print();  
} 


// load movies
function openWin(page) {
OpenWin = this.open(page, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=auto,resizable=no,height=500,width=600");
}


// external site link
function confirmExit(theLocation, theMessage) {
	if(!theMessage || typeof(theMessage) == 'undefined')
		theMessage = "You are now leaving the lapband.com website.\n\nClick 'OK' to continue or 'Cancel' to remain on this site.";

    if (confirm(theMessage)) {
      window.open(theLocation);
    }
}

function confirmAndTrackExit(theLocation,theMessage, trackingFunction){
	if(!theMessage || typeof(theMessage) == 'undefined')
		theMessage = "You are now leaving the lapband.com website.\n\nClick 'OK' to continue or 'Cancel' to remain on this site.";

    if (confirm(theMessage)) {
		trackingFunction(theLocation);
		window.open(theLocation);
    }
}

function confirmExit2(theLocation){
	var theMessage = "You are now leaving the lapband.com website.\n\nClick 'OK' to continue or 'Cancel' to remain on this site.";

    if (confirm(theMessage)) {
		/*
		var s=s_gi(s_account);
		s.linkTrackVars='events,event17';
		s.linkTrackEvents='event17';
		s.tl(true,'o','WebMD');			
		*/
		track_link('17', 'WebMD');
	    window.open(theLocation);
    }
}

function Set_Cookie( name, value, expires ) 
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" );
}


function Get_Cookie(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 "";
}




function openCommercial(page)
{
	window.open(page,"commercial","toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,height=240,width=320");
}




// DEVICE IN DETAIL
function ShowDevice(ElementName)
	{
		//this turns them all to the off state first when one of the items is selected
		//must list the entire array of items as I have with the item_NUMBER

		var a=new Array("deviceText0","deviceText1","deviceText2","deviceText3","deviceText4")
		for (var i=0;i<a.length;i++)
		{	document.getElementById(a[i]).style.display="none"
		}

		//this let you toggle the display of an element
		//it will flip the state each time it is called

		var es = document.getElementById(ElementName).style;
		es.display = (es.display == 'none') ? 'block' : 'none';
	}
// END DEVICE IN DETAIL



// PLAY VIDEO

var currVideo = null;

function playVideo(fileName,id, targetDiv) {
 	var so = new SWFObject(siteRoot() + "local/flash/testimonials/LapbandVideoPlayer_454x333.swf", id, "454", "333", "9");
 	so.addVariable("videoSource",siteRoot() + "local/flash/testimonials/" + fileName);
 	so.addParam("allowScriptAccess", "always");
 	currVideo = id;
 	so.write(targetDiv);
}


function playMovie(fileName,id, targetDiv) {
 	var so = new SWFObject(siteRoot() + "local/flash/infuse/LapbandVideoPlayer_535x383.swf", id, "535", "383", "9");
 	so.addVariable("videoSource",siteRoot() + "local/flash/infuse/" + fileName);
 	so.addParam("allowScriptAccess", "always");
 	currVideo = id;
 	so.write(targetDiv);
}


function stopPlayback(id) {
	var moviename =	getMovieName(id);
	if(moviename)
		moviename.callASfunction(); 
}


var onPopupClose = function(){
	stopPlayback(currVideo);
}

function videoComplete() {

}

function playRotator() {
	//alert(id);
	getMovieName("rotator").callASfunction(); 
}

function getMovieName(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName]
	}
	else {
		return document[movieName]
	}
}



// FLASH NAVIGATION
function flashNavRedirect(urlFragment)
{
	document.location = siteRoot() + urlFragment;
}

function n2()
{ flashNavRedirect('get_informed/');
}
function n21()
{ flashNavRedirect('get_informed/about_lapband/');
}
function n211()
{ flashNavRedirect('get_informed/about_lapband/how_it_works/');
}
function n212()
{ flashNavRedirect('get_informed/about_lapband/right_for_me/');
}
function n213()
{ flashNavRedirect('get_informed/about_lapband/risk_information/');
}
function n214()
{ flashNavRedirect('get_informed/about_lapband/total_care/');
}
function n215()
{ flashNavRedirect('get_informed/about_lapband/faqs/');
}
function n216()
{ flashNavRedirect('get_informed/about_lapband/request_info/');
}
function n22()
{ flashNavRedirect('get_informed/obesity_weight_loss/');
}
function n221()
{ flashNavRedirect('get_informed/obesity_weight_loss/obesity_and_your_health/');
}
function n222()
{ flashNavRedirect('get_informed/obesity_weight_loss/options/');
}
function n223()
{ flashNavRedirect('get_informed/obesity_weight_loss/comparison/');
}
function n224()
{ flashNavRedirect('get_informed/obesity_weight_loss/supporting/');
}
function n225()
{ flashNavRedirect('get_informed/obesity_weight_loss/lapband_realizeband/');
}
function n23()
{ flashNavRedirect('get_informed/costs_payment/');
}
function n231()
{ flashNavRedirect('get_informed/costs_payment/costs/');
}
function n232()
{ flashNavRedirect('get_informed/costs_payment/payment_options/');
}
function n233()
{ flashNavRedirect('get_informed/costs_payment/surgery_outside/');
}
function n24()
{ flashNavRedirect('get_informed/attend_seminar/');
}
function n241()
{ flashNavRedirect('get_informed/attend_seminar/find_seminar/');
}
function n25()
{ flashNavRedirect('get_informed/consult/');
}
function n251()
{ flashNavRedirect('get_informed/consult/discussing/');
}
function n252()
{ flashNavRedirect('get_informed/consult/what_to_look_for/');
}
function n253()
{ flashNavRedirect('get_informed/consult/questions_to_ask/');
}
function n254()
{ flashNavRedirect('get_informed/consult/find/');
}
function n3()
{ flashNavRedirect('prepare_for_surgery/');
}
function n31()
{ flashNavRedirect('prepare_for_surgery/about_the_surgery/');
}
function n311()
{ flashNavRedirect('prepare_for_surgery/about_the_surgery/lapband_system_procedure/');
}
function n312()
{ flashNavRedirect('prepare_for_surgery/about_the_surgery/surgery_faqs/');
}
function n313()
{ flashNavRedirect('prepare_for_surgery/about_the_surgery/prep_checklist/');
}
function n32()
{ flashNavRedirect('prepare_for_surgery/prep_checklist/');
}
function n33()
{ flashNavRedirect('prepare_for_surgery/on_surgery_day/');
}
function n34()
{ flashNavRedirect('prepare_for_surgery/what_to_expect_after_surgery/');
}
function n4()
{ flashNavRedirect('life_after_surgery/');
}
function n41()
{ flashNavRedirect('life_after_surgery/life_after_surgery/');
}
function n411()
{ flashNavRedirect('life_after_surgery/life_after_surgery/first_few_weeks_after_surgery/');
}
function n412()
{ flashNavRedirect('life_after_surgery/life_after_surgery/first_year_after_surgery/');
}
function n413()
{ flashNavRedirect('life_after_surgery/life_after_surgery/post_surgery_faqs/');
}
function n42()
{ flashNavRedirect('life_after_surgery/optimizing_your_weight_loss/');
}
function n43()
{ flashNavRedirect('life_after_surgery/continued_well_being/');
}
function n44()
{ flashNavRedirect('life_after_surgery/complications_who_to_call/');
}
function n45()
{ flashNavRedirect('life_after_surgery/supporting_a_loved_one/');
}
function n451()
{ flashNavRedirect('life_after_surgery/supporting_a_loved_one/getting_support/');
}
function n452()
{ flashNavRedirect('life_after_surgery/supporting_a_loved_one/partners/');
}
function n46()
{ flashNavRedirect('life_after_surgery/healthy_recipes/');
}
function n461()
{ flashNavRedirect('life_after_surgery/healthy_recipes/overview/');
}
function n462()
{ flashNavRedirect('life_after_surgery/healthy_recipes/browse/');
}
function n463()
{ flashNavRedirect('my_lapband/my_recipe_box/submit_a_recipe/');
}
function n464()
{ flashNavRedirect('my_lapband/my_recipe_box/my_recipes/');
}
function n47()
{ flashNavRedirect('life_after_surgery/supporting_a_loved_one/partners/');
}
function n5()
{ flashNavRedirect('success_stories/');
}
function n51()
{ flashNavRedirect('success_stories/');
}
function n52()
{ flashNavRedirect('success_stories/edit/');
}
function n6()
{ flashNavRedirect('news_resources/');
}
function n61()
{ flashNavRedirect('news_resources/news/');
}
function n62()
{ flashNavRedirect('news_resources/newsletter/');
}
function n621()
{ flashNavRedirect('news_resources/newsletter/');
}
function n63()
{ flashNavRedirect('news_resources/internet_resources/');
}

function momentLearn()
{ flashNavRedirect('news_resources/moment_is_now/caitlin_barbara_story/');
}
function momentWatch()
{ flashNavRedirect('news_resources/moment_is_now/caitlin_barbara_story/caitlin_video/');
}
function gretchenRead()
{ //flashNavRedirect('news_resources/news/news_release_grammy_award/');
}
function hollyStory()
{ flashNavRedirect('success_stories/holly/');
}
function seeAll()
{ flashNavRedirect('success_stories/');
}
function momentIsNow()
{flashNavRedirect('life_after_surgery/supporting_a_loved_one/partners/');	
}



//-- Recipe ---------------------------
var LoadRecipeWidget = function (WidgetName, QueryStringParams) {
	var QueryStringParamsString = "";
	for (var i in QueryStringParams) {
		QueryStringParamsString += "&" + i + "=" + escape(QueryStringParams[i]);
	}
	QueryStringParamsString = QueryStringParamsString.length > 0 ? "?" + QueryStringParamsString.substr(1) : "";

	document.getElementById("WidgetsRecipeDiv").innerHTML = "";
	new Ajax.Updater("WidgetsRecipeDiv", siteRoot() + "elements/widgets/recipe/" + WidgetName + "/index" + QueryStringParamsString, { method:"get" });
	
}

var RatingMouseOutTimeoutID;
var RatingMouseOver = function (Rating) {
	clearTimeout(RatingMouseOutTimeoutID);
	for (var i=1; i<=Rating; i++) {
		var StarElem = document.getElementById("WidgetsRecipeRate" + i);
		StarElem.style.backgroundImage = "url(" + siteRoot() + "local/images/recipe/star.gif)";
	}
	for (var i=Rating+1; i<=5; i++) {
		var StarElem = document.getElementById("WidgetsRecipeRate" + i);
		StarElem.style.backgroundImage = "url(" + siteRoot() + "local/images/recipe/star_fade.gif)";
	}
}

var RatingMouseOut = function () {
	var CurrentSelectedRating = Number(document.getElementById("SelectedRating").value);
	CurrentSelectedRating = CurrentSelectedRating >= 1 && CurrentSelectedRating <= 5 ? CurrentSelectedRating : 0;
	RatingMouseOutTimeoutID = setTimeout(function () { SelectRating(CurrentSelectedRating); }, 200);
}

var SelectRating = function (Rating) {
	for (var i=1; i<=5; i++) {
		var StarElem = document.getElementById("WidgetsRecipeRate" + i);
		if (i <= Rating) {
			StarElem.style.backgroundImage = "url(" + siteRoot() + "local/images/recipe/star.gif)";
		} else {
			StarElem.style.backgroundImage = "url(" + siteRoot() + "local/images/recipe/star_fade.gif)";
		}
	}
	document.getElementById("SelectedRating").value = String(Rating);
}

var UpdateMyRecipeBoxCount = function () {
	if (document.getElementById("MyRecipeBoxCountSpan")) new Ajax.Updater("MyRecipeBoxCountSpan", siteRoot() + "elements/widgets/recipe/my_recipe_box_count/index");
}
//-------------------------------------
function browserIndependentFireEvent(element, event){
    if (document.createEventObject){
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        // dispatch for firefox + others
        var evt = document.createEvent("MouseEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

// xDocSize r1, Copyright 2007 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
function xDocSize(){
var b=document.body, e=document.documentElement;var esw=0, eow=0, bsw=0, bow=0, esh=0, eoh=0, bsh=0, boh=0;
if (e) {esw = e.scrollWidth;eow = e.offsetWidth;esh = e.scrollHeight;eoh = e.offsetHeight;}
if (b) {bsw = b.scrollWidth;bow = b.offsetWidth;bsh = b.scrollHeight;boh = b.offsetHeight;}
return {w:Math.max(esw,eow,bsw,bow),h:Math.max(esh,eoh,bsh,boh)};
}


var toggleMomentOfTruthQuestion = function(answeredYes){
	if (answeredYes){
		$("momentoftruthquestion").removeClassName("hidden");	
	} else {
		$("momentoftruthquestion").addClassName("hidden");	
	}
}

var flagMOTcompletion = function(isEmpty){
	if (!isEmpty){
		$("doneindicator").removeClassName("hidden")	
	} else {
		$("doneindicator").addClassName("hidden")			
	}
}

var toggleSweepstakesForm = function(elem){
	if(elem.checked){
		$("surveysweepstakescontainer").removeClassName("hidden");	
	}else{
		$("surveysweepstakescontainer").addClassName("hidden");	
	}
}

var surveyToggleMore = function(el){
	var moreContainer = $(el).up("tr").down(".surveymore");	
	if (el.checked == true) moreContainer.removeClassName("hidden");
	else moreContainer.addClassName("hidden");	
}

var surveyShowMore = function(el){
	//hide all
	$$("div.surveymore").invoke("addClassName","hidden");
	//show one
		
	var moreContainer = $(el).up("tr").down(".surveymore");	
	if (moreContainer){
		if (el.checked == true) moreContainer.removeClassName("hidden");
		else moreContainer.addClassName("hidden");
	}
	
}


var hideInsideLabel = function(el,label){
	if (el.value == label) el.value="";	
	el.addClassName("insidelabelfocused");
}

var showInsideLabel = function(el,label){
	if (el.value == ""){
		el.value=label;	
		el.removeClassName("insidelabelfocused")
	}
}
