//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
var normalizePath = function(string) {return string.replace(/(\/+)|\\+/g, "/");}
//escapes <, > & and " into corresponding html entities
var escapeHTML = function(string) {return string.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");}
//rounds a number to two decimals places. Returns a string
var toCurrency = function(number) {return number.toFixed(2);}
//IE background image cache script
//@cc_on document.execCommand("BackgroundImageCache", false, true);
var currentLoc = location.href;
var g_PopupIFrame;
var isMyJourney = location.href.indexOf('mylapband') > -1;


function closeModal(withRefresh, parametersOrRedirectUrl) {
	Modal.close();
	//Modal2.close();

	var parameters = null;
	var redirectUrl = null;

	if (typeof parametersOrRedirectUrl == 'string')
		redirectUrl = parametersOrRedirectUrl;
	else if (typeof parametersOrRedirectUrl == 'object')
		parameters = parametersOrRedirectUrl;

	if (withRefresh)
	{
		if (redirectUrl)
		{
			window.location = redirectUrl;
		}
		else
		{
			var refreshUrl = window.location.href;

			if (refreshUrl.endsWith('?'))
				refreshUrl = refreshUrl.substring(0, refreshUrl.length - 1);

			refreshUrl = refreshUrl.replace(/#[\w-]*$/, ''); // remove anchor part

			if (parameters)
			{
				var queryString = '';

				for (var key in parameters)
				{
					if (window.location.search.indexOf(key + '=') != -1) continue;
					queryString += (key + '=' + parameters[key] + '&');
				}

				if (queryString)
				{
					refreshUrl += (((window.location.search == '') ? '?' : '&') +
						queryString.substring(0, queryString.length - 1));
				}
			}

			window.location = refreshUrl;
		}
	}
}

var rotatewidgets;

var Behaviour = {
	//param: Object sheet = {cssRule : callback}
	//	where cssRule is a string and callback is a function that passes a DOM element as its parameter and returns null, i.e. void callback(DOMElement element)
	register : function(sheet) {Behaviour.list.push(sheet);},
	//call apply after ajaxing stuff if you want behaviour rules to apply to ajaxed elements
	apply : function() {
		for (h = 0; sheet = Behaviour.list[h]; h++) {
			for (selector in sheet) {
				list = $$(selector);
				if (!list) continue;
				for (i = 0; element = list[i]; i++) sheet[selector](element);
			}
		}
	},
	//private
	list : new Array()
}

var initToggleButton = function(){
	$('togbtn').observe('click',function(ev) {
		el = $(this);
		var topicbox = $('topicbox');
		if (el.hasClassName('on')) {
			el.removeClassName('on');
			new Effect.BlindUp(topicbox,{duration:.2 });
			el.update('Show');
			$("ShowInfoFilter").value = "OFF";
		}else{
			el.addClassName('on');	
			new Effect.BlindDown(topicbox, {duration:.5 }); 	
			el.update('Hide');
			$("ShowInfoFilter").value = "ON";
		}
		
		ev.stop();
	});
}

	
document.observe("dom:loaded", function() {
	var flashvars = {};	
	var attributes = {};	
	var params = {allowScriptAccess: "always", wmode:"transparent"};
 											
										
	//home flash  
	if($('homeflash')) {
		
		if (!Cookie.get('announcementCookie')) {
			cookieduration = 43200;  //  5 yrs
			Cookie.set('announcementCookie',"1", cookieduration);
			Modal.open({contentEl: 'announcement', width:818, ptype:'typeannouncement'})
			siteCatalystFirePageView("homepage_announcement");

		}
		else {
			homeFlash();
		}
	}
	
	if($('discovermlbjvid')) {
	 	flashvars.videoSource = siteroot + "local/flash/mlbj/LapbandTeaser3.flv"; 	
 		swfobject.embedSWF( siteroot + "local/flash/mlbj/journeyTeaserPlayer662x448.swf", 'discovermlbjvid', "662", "448", "9","", flashvars, params, attributes);
	}
	
	
	if($('metabolicwoman')) {
	 	var flashvars = {};	
		var attributes = {};	
		var params = {wmode:"transparent"};
		swfobject.embedSWF( siteroot + "local/flash/comorbidities_740x750_v12.swf", "metabolicwoman", "740", "750", "8.0.0","", flashvars, params, attributes);
	}
	
	if($('learn_landing')) {
	 	var flashvars = {};	
		var attributes = {};	
		var params = {wmode:"transparent"};
		swfobject.embedSWF( siteroot + "local/flash/inside-Learn_767x740_v3.swf", "learn_landing", "767", "820", "8.0.0","", flashvars, params, attributes);
	}
	
	if($('right_landing')) {
	 	var flashvars = {};	
		var attributes = {};	
		var params = {wmode:"transparent"};
		swfobject.embedSWF( siteroot + "local/flash/inside-right_767x660.swf", "right_landing", "767", "660", "8.0.0","", flashvars, params, attributes);
	}
	
	if($('prepare_landing')) {
	 	var flashvars = {};	
		var attributes = {};	
		var params = {wmode:"transparent"};
		swfobject.embedSWF( siteroot + "local/flash/inside-prepare_767x645.swf", "prepare_landing", "767", "645", "8.0.0","", flashvars, params, attributes);
	}
	
	if($('live_landing')) {
	 	var flashvars = {};	
		var attributes = {};	
		var params = {wmode:"transparent"};
		swfobject.embedSWF( siteroot + "local/flash/inside-Live_767x619.swf", "live_landing", "767", "619", "8.0.0","", flashvars, params, attributes);
	}
	
	//alert(navigator.userAgent);
	//CSS hover script for elements that don't accept css hover class in IE6	
	if (navigator.appName.indexOf('Internet Explorer') > -1) {
		//alert('ie');
		Behaviour.register({
			"li" : function(element) {
				var timeout;
				var oIframe;
				Event.observe(element, "mouseover", function() {
					clearTimeout(timeout);
					Element.addClassName(element, "over");
					if(element.down("iframe") && ! isMyJourney) {
						var oDropdownmenu = element.down("div.dropdownmenu");
						
						oIframe = element.down("iframe");
						if(oIframe){
							oIframe.setStyle({
									height: oDropdownmenu.offsetHeight + "px",
									top: oDropdownmenu.offsetTop + "px",	
									left: (oDropdownmenu.offsetLeft - 5) + "px"	,
									width: (oDropdownmenu.offsetWidth + 10) + "px"	
								})						
							oIframe.removeClassName("hidden");
						}
					}
										
		});
				Event.observe(element, "mouseout", function() {
					timeout = setTimeout(function() {
						Element.removeClassName(element, "over");
						if(oIframe) oIframe.addClassName("hidden");
					}, 10);
				});
			}
		});
		Behaviour.apply();
	
		Behaviour.register({
			".dropdownmenu div" : function(element) {
				var timeout;
				Event.observe(element, "mouseover", function() {
					clearTimeout(timeout);
					Element.addClassName(element, "over");
				});
				Event.observe(element, "mouseout", function() {
					timeout = setTimeout(function() {Element.removeClassName(element, "over");}, 10);
				});
			}
		});
		Behaviour.apply();
	}
	
	
	
	//sign in link
	
	if($('signinlink')){
		$('signinlink').observe('click',function(ev) {
			//el = this;
			$('loginbox').removeClassName('hidden');
			
			$('loginbox').down('.loginbox').setStyle({
				top:"20px",
				right:"20px",
				left:"auto"
		   });
			
			Event.stop(ev);
		});
	}
	
	if($('rowcontainer')) {
		//alert('me');
		$('rowcontainer').select('.rowexpander').invoke('observe','click',function(ev){
			var el = $(this);
			if (el.checked) {
				$('rowcontainer').select('.rowbody').invoke('addClassName','hidden');
				$('rowcontainer').select('.rowitem').invoke('removeClassName','selected');
				var rowitem = el.up('.rowitem');
				rowitem.addClassName('selected');
				rowitem.down('.rowbody').removeClassName('hidden');
			}
		});
		
	}

	if($('source1')){
		$('source1').observe('change',function(){
			var el = this;
			var selected = $F('source1');
			if(selected=='1' || selected == '9') $('source2').removeClassName('hidden');
			else $('source2').addClassName('hidden');
		});
	}

	if($('feet')){
		$('feet').observe('keyup',function(){
			if($F(this).length > 0)
				$('inches').focus();
		});
	}
	
	if($('phone1')){
		$('phone1').observe('keyup',function(){
			if($F(this).length == 3)
				$('phone2').focus();
		});
		
		$('phone2').observe('keyup',function(){
			if($F(this).length == 3)
				$('phone3').focus();
		});
	}
	
	if($('phone4')){
		$('phone3').observe('keyup',function(){
			if($F(this).length == 3)
				$('phone4').focus();
		});
	}
	
	if($('BirthdateYear')){
		ele = $('BirthdateYear');
		if (ele.hasClassName('bmiyear') && $F(ele) == 'Year'){
			ele.addClassName('bmiyearstate');
		}
		ele.observe('keyup',function(){
			if($F(ele) == 'Year') ele.addClassName('bmiyearstate');
			else ele.removeClassName('bmiyearstate');
		});
	}
	
	if($('insurance-yes')){
		$('insurance-yes').observe('click',function(){
			$('insuranceq1expanded').removeClassName('hidden');
		});
		$('insurance-dontknow').observe('click',function(){
			$('insuranceq1expanded').addClassName('hidden');
		});
		$('insurance-no').observe('click',function(){
			$('insuranceq1expanded').addClassName('hidden');
		});
	}

	//step 2 username
	if($('dynamicusername')){
		$('Name').observe('keyup',function(){
			$('dynamicusername').update($('Name').value);
		});
	}

	//share your story stuff
	if($('sharetable')){ 
		$('sh_name').observe('change',sh_chk);
		$('sh_email').observe('change',sh_chk);
		$('YearOfBirth').observe('change',sh_chk);
		$('sh_gender1').observe('change',sh_chk);
		$('sh_gender2').observe('change',sh_chk);
		$('DateBanded').observe('change',sh_chk);
		$('SurgeryPerformedInUS_Yes').observe('change',sh_chk);
		$('SurgeryPerformedInUS_No').observe('change',sh_chk);
		$('HeightFt').observe('change',sh_chk);
		$('HeightIn').observe('change',sh_chk);
		$('PreopWeight').observe('change',sh_chk);
		$('CurrentWeight').observe('change',sh_chk);
		$('StoryTopicID').observe('change',sh_chk);
		$('StoryArea').observe('change',sh_chk);
		$('agree').observe('change',sh_chk);
	}

	//tooltip toggle content
	if($('tooltiptoggle')){

		$('tooltiptoggle').observe('click',function(ev) {															
			var longcontent = $("longcontent");
			var shortcontent = $("shortcontent");
			var tipele = $(this);
			var iconele = $('tipicon');
			
				if (longcontent.hasClassName("hidden")) {							
					longcontent.removeClassName("hidden");
					shortcontent.addClassName("hidden");
					tipele.update("Less<span>&nbsp;</span>");
					tipele.addClassName("toggle");
					iconele.setStyle({bottom:'7px'});
					siteCatalystTipExpand();
				} else {							
					shortcontent.removeClassName("hidden");
					longcontent.addClassName("hidden");
					tipele.update("More<span>&nbsp;</span>");
					tipele.removeClassName("toggle");
					iconele.setStyle({bottom:'6px'});
				}
			Event.stop(ev);
		});
	}

	
	/*topic filter for success stories*/
	if($('togbtn')) {
		initToggleButton()
		if($('topictogglebar')) { //toggleTopics
			$('topictogglebar').observe('click',function(ev) {

				el = $('togbtn');//$(this); //topbtn
				var topicbox = $('topicbox'); //ScrollTopics
				if (el.hasClassName('on')) {
					el.removeClassName('on');
					new Effect.BlindUp(topicbox,{duration:.2 });
					el.update('Show');
				}else{
					el.addClassName('on');
					new Effect.BlindDown(topicbox, {duration:.5 }); 	
					el.update('Hide');
				}
				
				ev.stop();
			});
		}
		
		if ($('toggleTopics')){
			$('toggleTopics').observe('click',function(ev){

				el = $('topbtn');
				var topicbox = $('ScrollTopics');
				if (el.hasClassName('on')) {
					el.removeClassName('on');
					new Effect.BlindUp(topicbox,{duration:.2 });
					el.update('Show');
					$("ShowTopicFilter").value="OFF";
				}else{
					el.addClassName('on');
					new Effect.BlindDown(topicbox, {duration:.5 }); 	
					el.update('Hide');
					$("ShowTopicFilter").value="ON";
				}
				ev.stop();
			});
		}

		if ($('toggleCommo')){
			$('toggleCommo').observe('click',function(ev){
				el = $('combtn');
				var topicbox = $('ScrollComo');
				if (el.hasClassName('on')) {
					el.removeClassName('on');
					new Effect.BlindUp(topicbox,{duration:.2 });
					el.update('Show');
					$("ShowComoFilter").value="OFF";
				}else{
					el.addClassName('on');
					new Effect.BlindDown(topicbox, {duration:.5 }); 	
					el.update('Hide');
					$("ShowComoFilter").value="ON";
				}
				ev.stop();
			});
		}

		
	}
	
	//tabs
	//$$('.tabbutton').invoke('observe','click',function(ev){
	//	var el = $(this);
	var tabbutton = $$('.tabbutton');
	var tabcontent = $$('.contenttab');
	
	tabbutton.each(function(el,index){
		//check if it has selected state and show its proper tab
		if (el.hasClassName('selected')) tabcontent[index].removeClassName('hidden');
		//add onclick event
		el.observe('click', function(ev){
			var tabbox = el.up('.fulltabcontent');
			tabbox.down('.tabheader').select('.tabbutton').invoke('removeClassName','selected');
			tabbox.select('.contenttab').invoke('addClassName','hidden');
			el.addClassName('selected');
			tabcontent[index].removeClassName('hidden');
			ev.stop();
		});
	});
	
	
	// rotating widgets functionality
	rotatewidgets = $$('div.rotatewidget div.widget');
	
	var widgetLength = rotatewidgets.length;
	if(widgetLength > 0){
		var widgetindex = Math.floor(Math.random()*widgetLength); // get a random selection 
		// hide all
		rotatewidgets.invoke('addClassName','hidden');
		// when page loads select a random widget and clickable	
		widgetselection = $(rotatewidgets[widgetindex]);
		widgetselection.removeClassName('hidden');
		//widgetselection.down("div.rotatewidgetclick").down("a",widgetindex).addClassName('selected');
		rotatewidget(widgetindex);
		
	}
	// render sifr stuff
	
	
	// shows faq answers
	var faqClicks = $$('div.faqholder .widgetcontent ul li a');
	var faqAnswers = document.getElementsByClassName("faqanswer");
	var faqClosers = document.getElementsByClassName("faqcloser");
	var faqSelection ;
				
	faqClicks.each(function(el,index){
			el.observe('click', function(ev){
				Event.stop(ev);
				$('faqholder').select("iframe").invoke("remove");
				faqClicks.invoke('removeClassName','selected');
				el.addClassName('selected');
				$A(faqAnswers).invoke("addClassName","hidden");
				faqSelection = index;
				faqAnswers[index].removeClassName('hidden');
				ShowPopupDiv(faqAnswers[index])
				siteCatalystFAQ(el);
			});				
			
		});
	$A(faqClosers).each(function(el,index){
		el.observe('click', function(ev){
			var divID =  $(this).up("div.faqanswer");
			divID.addClassName('hidden');
			faqClicks.invoke('removeClassName','selected');
			HidePopupDiv(divID);
			ev.stop();
		});
	});


function HidePopupDiv(divID)
{

    var divPopup;
    divPopup= divID;
    if (Prototype.Browser.IE)
    {
		//$('faqholder').removeChild(g_PopupIFrame);
		//var iframes  = $$('#faqholder iframe');
		//iframes.invoke("remove");
        //g_PopupIFrame=null;
		$('faqholder').select("iframe").invoke("remove");
		

    }

}

function ShowPopupDiv(divID)
{

    var divPopup=divID ;

   if (!Prototype.Browser.IE) return;
   
    //Increase default zIndex of div by 1, so that DIV appears before IFrame
    divPopup.style.zIndex=divPopup.style.zIndex+1;
  
    var iFrame = document.createElement("IFRAME");
	g_PopupIFrame = iFrame;
    iFrame.setAttribute("src", "");
    //Match IFrame position with divPopup
    iFrame.style.position="absolute";
    iFrame.style.left =divPopup.offsetLeft + 'px';
    iFrame.style.top =divPopup.offsetTop + 'px';
    iFrame.style.width =divPopup.offsetWidth + 'px';
    iFrame.style.height =divPopup.offsetHeight + 'px';
    iFrame.style.background = "black";
    $('faqholder').appendChild(iFrame);


}
	
	if($('explist')) {
		var explist = $('explist');
		var explinks = explist.select('.explink');
		var expcontent = explist.select('.expcontent');
		
		explinks.invoke('observe','click',function(ev){
			el = $(this);
			if (el.hasClassName('on')) {
				el.removeClassName('on');
				el.up().next('.expcontent').addClassName('hidden');
				//new Effect.BlindUp(el.up().next('.expcontent'), {duration:.2 });
			} else {
				explinks.invoke('removeClassName','on');
				expcontent.invoke('addClassName','hidden');
				el.addClassName('on');
				el.up().next('.expcontent').removeClassName('hidden');
				//new Effect.BlindDown(el.up().next('.afaq'), {duration:.5 });
			}
			ev.stop();
		})
		
	}
	
	if($('explistLifestyle')) {
		var explistLS = $('explistLifestyle');
		var explinksLS = explistLS.select('.explink');
		
		explinksLS.invoke('observe','click',function(ev){
			el = $(this);
			if (el.hasClassName('on')) {
				el.removeClassName('on');
				el.up().next('.expcontent').addClassName('hidden');
			} else {
				el.addClassName('on');
				el.up().next('.expcontent').removeClassName('hidden');
			}
			ev.stop();
		})
		
	}	
	
	//external links
	if($('layout')){	
		$('layout').select('a[target="_blank"]').invoke('observe','click',function(ev){
			if($(this).hasClassName('localhreflink') == false) {
				Event.stop(ev);
				var txtmsg = "This link will open an external website";
				var txtok = "Proceed";
				var txtcancel = "Cancel";
				var modalmsg = new Element('div',{'id':'leavemodal','class':'hidden'});
				var modaltxt = new Element('div',{'class':'leavemodal'}).update(txtmsg+'<br><br>');
				var inner = (this.innerHTML != '' ? this.innerHTML : this.title);
				var proceedbtn = new Element('button',{'class':'button','onclick':'openLink("'+this.href+'","'+inner+'")'}).update('<span><span>'+txtok+'</span></span>');
				var cancelbtn = new Element('button',{'class':'button','onclick':'Modal.close()'}).update('<span><span>'+txtcancel+'</span></span>');
				$('layout').insert(modalmsg);
				$('leavemodal').update('');
				$('leavemodal').insert(modaltxt);
				$('leavemodal').down().insert(proceedbtn);
				$('leavemodal').down().insert(cancelbtn);
				Modal.open({contentEl: 'leavemodal'});
			}
		})
	}
	
	//pdf links
	if($('content')){	
		$('content').select('a').invoke('observe','click',function(ev){
			var elem = $(this);
			if(elem.href.toLowerCase().indexOf('.pdf') > -1) {
				var title = stripHTML(elem.innerHTML);
				var url = elem.href;
				var localfile = url.indexOf(window.location.host);
				if (localfile > -1) {
					var localfilelen = window.location.host.length;
					url = url.substr(localfile+localfilelen);
				}
				var filename = getFileName(url);
				//alert(url)
				siteCatalystFiles(title,filename,url)
			}
		})
	}
	
	if($('journalvideo')) {
		var vparams = window.location.search.toQueryParams();
		var flvname = (vparams.video) ? vparams.video : 'Changes_FINAL.flv';
		playJournal(flvname,'video', 'testimonialContent1')
	}
	
	
	if (currentLoc.indexOf('/success_stories/patient') > -1 || currentLoc.indexOf('/success_stories/video') > -1) {
		$('secondnavi').select('li.selected').each(function(el,index){
			if(el.down('a').innerHTML == 'Success Stories Home') el.removeClassName('selected');
		});
	}
	
	
});
	
var openLink = function(href,inner){
	Modal.close();
	window.open(href,'');
	siteCatalystLink(href,inner);
}

	
var rotatewidget = function(i){
	
    // select the radio button
	var rotatewidgetclicks  =  rotatewidgets[i].select("div.rotatewidgetclick a");

	getrotatewidgets = $$('div.rotatewidget div.widget');
	var wgLength = getrotatewidgets.length-1;	
	
	//show and hide back/next buttons
	if (i == 0) {
		rotatewidgetclicks[0].addClassName('hidden');
	} else {
		rotatewidgetclicks[0].removeClassName('hidden');
	}
	if (i == wgLength) {
		rotatewidgetclicks[1].addClassName('hidden');
	} else {
		rotatewidgetclicks[1].removeClassName('hidden');
	}
	
	
	rotatewidgetclicks.each(function(el,j){				
		//add onclick event
		el.observe('click', function(ev){
			//hide all widgets		
			rotatewidgets.invoke('addClassName','hidden');								 
			//show selected widget and click
			if (j == 0){
				widgetselection  = $(rotatewidgets[i-1]);
				widgetselection.removeClassName('hidden');
				
				sifrCalls();
				rotatewidget(i-1);	// call function again
			}
			else if (j == 1){
				widgetselection  = $(rotatewidgets[i+1]);
				widgetselection.removeClassName('hidden');
				
				sifrCalls();
				rotatewidget(i+1);	// call function again
			}	

			ev.stop();		
			
		});
	});
}


	


var hideloginbox = function() {
	if ($('loginbox'))
		$('loginbox').addClassName('hidden');
	else
		location.href = siteroot + 'en/sign_in';
}

//homepage flash functions
var follow = function(){
	location.href = siteroot + 'en/success_stories/patient_stories/detail/michele';
};

var findZip = function(zip){
	location.href = siteroot + 'en/lapband_is_for_you/find_a_surgeon/searchresults/?SelectedTab=SearchByLocationTab&zip=' + zip;
}

var compare = function(){
	location.href = siteroot + 'en/learn_about_lapband/compare_lapband/';
};

var learn = function(){
	location.href = siteroot + 'en/learn_about_lapband/';
};

var find = function(){
	location.href = siteroot + 'en/lapband_is_for_you/find_a_surgeon/';
};

var tour = function(){
	location.href = siteroot + 'en/learn_about_lapband/my_lapband_journey/discover_my_lapband/';
};

var register = function(){
	//alert(6)
};

var safetyInfo = function(){
	location.href = siteroot + 'en/learn_about_lapband/safety_information/';
};

var toggleTips = function(){
 	longcontent = $("longcontent");
	shortcontent = $("shortcontent");

	if (longcontent.hasClassName("hidden")) {
		longcontent.removeClassName("hidden");
		shortcontent.addClassName("hidden")		
	} else {
		shortcontent.removeClassName("hidden");
		longcontent.addClassName("hidden")	
	}
}

function xDocSize(){
var maskie6 = 0;
//is ie6
if (typeof document.body.style.maxHeight == "undefined") maskie6 = 22;

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 = 0;eow = e.offsetWidth;esh = e.scrollHeight;eoh = e.offsetHeight;}
if (b) {bsw = 0;bow = b.offsetWidth;bsh = b.scrollHeight;boh = b.offsetHeight;}
var w = Math.max(esw,eow,bsw,bow) - maskie6;
var minw = $("layout").getWidth();
if(w<minw) w=minw;
return {w:w,h:Math.max(esh,eoh,bsh,boh)};
}

function maxHeight() {
  var h=0;
  if (window.document.innerHeight>h)
   h=window.document.innerHeight;
  if (window.document.documentElement.clientHeight>h)
   h=window.document.documentElement.clientHeight;
  if (window.document.body.clientHeight>h)
   h=window.document.body.clientHeight;
  return h;
 }
function maxWidth() {
  var w=0;
  if (window.document.innerWidth>w)
   w=window.document.innerWidth;
  if (window.document.documentElement.clientWidth>w)
   w=window.document.documentElement.clientWidth;
  if (window.document.body.clientWidth>w)
   w=window.document.body.clientWidth;
  return w;
 }

//Modal mask
/* modal mask */
var Modal = {
	openMask : function(options) {
		this.close();//close if open	
		var hasMask, maskStyle;
		if (options){
			hasMask = options.hasMask;
		}		
		maskStyle = (hasMask) ? "modalDark" : "modalLight";
		var modalcontainer = $("modalcontainer");
		var modalmask = $("modalmask")
		modalcontainer.removeClassName("hidden");		
		modalcontainer.setStyle({top : "0", left: "0"})
		var pageDimensions = xDocSize();
		modalmask.className = "modalmask";
		modalmask.addClassName(maskStyle);
		modalmask.setStyle ({ 	
			height : pageDimensions["h"] + "px",
			width : pageDimensions["w"] + "px"
		})
	},
	close : function(skip_sc) {
		printfire("xxjavascript.js Modal.close ssvars");
		//if(siteCatalystFireServerSideVars && !skip_sc)
		//	siteCatalystFireServerSideVars("Modal Action");
		
		$("modalcontent").innerHTML = "";
		var modalcontainer = $("modalcontainer");
		modalcontainer.addClassName("hidden");
		try
		{	if (this.printwidget != "") $('layout').style.display='block'; 
			// rewind homepage flash
			var modalbody = $('modalbody');
			if(modalbody.hasClassName('typeannouncement')) 	$('homeflash').Rewind();
			
		}	catch (e) { }
	},
	resizeHandler : function(){
		var modalcontainer = $("modalcontainer");
		var modalmask = $("modalmask")
		var modalbody = $("modalbody");
		var pageDimensions = xDocSize();
		var width;
		width = modalbody.getWidth();
		if (!modalcontainer.hasClassName("hidden")){
			modalmask.setStyle ({ 	
				width : pageDimensions["w"] + "px"
			})
			modalbody.setStyle({
				left:(document.body.offsetWidth / 2) - (width/2) + "px"
			});
			
		}
	},
	open :function(options){
		$("modalcontent").update("<center><img src='"+ siteroot +"local/images/loading.gif' /></center>");
		var width, url, contentEl, hasMask, ptype;
		var modalbody = $("modalbody");
		if (options){
			width = options.width || 550;
			url = options.url || "";	
			contentEl = options.contentEl || "";			
			hasMask = options.hasMask;
			ptype = options.ptype || "";
			this.printwidget = options.printwidget || "";
		}
		
		
		
		//if (ptype != "") modalbody.addClassName(ptype);
		if (ptype != "") modalbody.className = "modalbody " + ptype;//not using addClassName because the ptype of the previous popup needs to be removed as well
		else {
			modalbody.removeClassName("typeannouncement");
			modalbody.removeClassName("type2");
			modalbody.removeClassName("type3");
			modalbody.removeClassName("typeflash");
			modalbody.removeClassName("typepartner");
		}

		//safari doesn't like document.documentElement.scrollTop & IE7 doesn't like window.pageYOffset
		var safariOffset = 0;
		if (document.documentElement.scrollTop==0 && !isNaN(window.pageYOffset)) safariOffset = 0 + window.pageYOffset;
		else safariOffset = 0 + document.documentElement.scrollTop;

		Modal.openMask({hasMask: hasMask});
		topval = (options.ptype == 'typeannouncement') ? 10 : 100;  
		modalbody.setStyle({
			//width: width + "px",
			top:  (topval + safariOffset) + "px",
			left:(document.body.offsetWidth / 2) - (width / 2) + "px"
		});	
		
		
		
		if (url != ""){
			printfire("javascript.js Modal.open");
			//siteCatalystFirePageView(url);
			new Ajax.Updater("modalcontent",options.url,{evalScripts:true})	
		} 
		else if (contentEl != ""){
			$("modalcontent").innerHTML = $(contentEl).innerHTML;
			//insanely crappy hack, to appease IE6 and it's refusal to re-render <img>s
			setTimeout(function(){
				$("modalcontent").innerHTML = $("modalcontent").innerHTML
			}, 50);
		}
		
		if (this.printwidget != "") $('layout').style.display='none';
		
	}
}	
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 safariOffset = 0;
			if (document.documentElement.scrollTop==0 && !isNaN(window.pageYOffset)) safariOffset = 0 + window.pageYOffset;
			else safariOffset = 0 + document.documentElement.scrollTop;
			var top = 100 + safariOffset;
			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");
			// empty video container
			//if($$("div[id^=thisVideo]")) $$("div[id^=thisVideo]").invoke("remove");
			if(container.down('div[id^=thisVideo]')) {
				var videle = container.down('div[id^=thisVideo]');
				var videleid = videle.id;
				var vidnumber = videle.id.substr(9);
				videle.update('<div id="testimonialContent'+vidnumber+'"></div>')
			}
			// 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");
		});
	});
}

var currVideo = null;

function playMovie(fileName,id, targetDiv) {
 	var flashvars = {};	
	var attributes = {};	
	var params = {allowScriptAccess: "always", wmode:"transparent"};
 	flashvars.videoSource = siteroot + "local/flash/testimonials/" + fileName; 	
 	swfobject.embedSWF( siteroot + "local/flash/testimonials/LapbandVideoPlayer_454x333.swf", targetDiv, "454", "333", "9","", flashvars, params, attributes);
	currVideo = id;
 	
}

function playTestimonial(fileName,id, targetDiv) {
	var flashvars = {};	
	var attributes = {};	
	var params = {allowScriptAccess: "always", wmode:"transparent"}	
 	flashvars.videoSource = siteroot + "local/flash/testimonials/" + fileName; 	
 	swfobject.embedSWF( siteroot + "local/flash/testimonials/LapbandVideoPlayer_535x383.swf", targetDiv, "535", "383", "9","", flashvars, params, attributes);
// 	swfobject.embedSWF( siteroot + "local/flash/testimonials/LapbandVideoPlayer_454x414.swf", targetDiv, "454", "414", "9","", flashvars, params, attributes);
	//swfobject.embedSWF( siteroot + "local/flash/infuse/LapbandVideoPlayer_535x383.swf", targetDiv, "535", "383", "9","", flashvars, params, attributes);
	currVideo = id;
 	
}

var playTeaser = function(fileName,id, targetDiv) {
 	var flashvars = {};	
	var attributes = {};	
	var params = {allowScriptAccess: "always", wmode:"transparent"};
 	flashvars.videoSource = siteroot + "local/flash/mlbj/" + fileName; 	
 	swfobject.embedSWF( siteroot + "local/flash/mlbj/journeyTeaserPlayer662x448.swf", targetDiv, "662", "448", "9","", flashvars, params, attributes);
	currVideo = id;
 	
}


function playSeminar(fileName,id, targetDiv) {
 	var flashvars = {};	
	var attributes = {};	
	var params = {allowScriptAccess: "always"}	
 	flashvars.videoSource = siteroot + "local/flash/seminar/" + fileName; 	
 	swfobject.embedSWF( siteroot + "local/flash/seminar/SeminarsVideoPlayer_454x333.swf", targetDiv, "454", "333", "9","", flashvars, params, attributes);
	currVideo = id;
 	
}

var playJournal = function(fname,id,targetdiv) {
	var params = {allowScriptAccess: "always", wmode:"transparent"}
	var flashvars = {}
	flashvars.videoSource = siteroot + "local/flash/testimonials/" + fname; 	
	swfobject.embedSWF(siteroot + "local/flash/testimonials/LapbandVideoPlayer_454x414.swf",targetdiv, "454", "414", "9","",flashvars, params,{});
	currVideo = id;
}

Event.observe(window,"load",function(){
	Event.observe(window, "resize", Modal.resizeHandler);
	if ($("modalcloser"))Event.observe ("modalcloser","click",function(){
		Modal.close()
		if ($('modalbody').hasClassName('typeannouncement')) homeFlash();
	});
	// for attach popups
	AttachPopups(document.body); 
})

var confpopup = function(){
	var modalcontainer = $('modalcontainer');
	modalcontainer.removeClassName('hidden');
	modalcontainer.setStyle({top : "0", left: "0"})

	//$('modalbody').addClassName('hidden');
	var pageDimensions = xDocSize();
	var modalmask = $("modalmask")
	modalmask.className = "modalmask";
	modalmask.addClassName("modalDark");
	modalmask.setStyle ({ 	
		height : pageDimensions["h"] + "px",
		width : pageDimensions["w"] + "px"
	})
	
	var modalbody = $('modalbody');
	var width = 493;
	//modalbody.removeClassName('modalbody');
	modalbody.addClassName('confpopup');
	modalbody.update($('confirmation').innerHTML);
	modalbody.setStyle({
		top:(document.documentElement.scrollTop + 100) + "px",
		left:(document.body.offsetWidth / 2) - (width / 2) + "px"
	});	
}

var loadloginpopup = function(e) {
	//$('modalcontent').update($('directionslogin').innerHTML);
	Modal.close(true);
	var width = 400;
	$('loginbox').removeClassName('hidden');
	$('loginbox').down('.loginbox').setStyle({
		top:(document.documentElement.scrollTop + 100) + "px",
		left:(document.body.offsetWidth / 2) - (width / 2) + "px",
		right:"auto"
   });
}

// external site link
function confirmExit(ele,theLocation, theMessage) {
	
	var innerhtml = ele.innerHTML;
	
	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)) {
		siteCatalystLink(theLocation,innerhtml);
      window.open(theLocation);
    }
	
}

var callbackCheck = function(ele) {
	if(ele.checked) 
		$(ele).up().next(".callbackbox").removeClassName("hidden");
	else
		$(ele).up().next(".callbackbox").addClassName("hidden");
		
}

var datetocallCheck =  function(ele) {
	if (ele.options[ele.selectedIndex].value == 3)
		$(ele).next(".calendardate").removeClassName("hidden");
	else
		$(ele).next(".calendardate").addClassName("hidden");
}

var checkattendance = function(ele) {
	ele = $(ele);
	alertmsg = ele.next('div.cancelalert');
	if(ele.value==0)
		alertmsg.removeClassName('hidden');
	else
		alertmsg.addClassName('hidden');
	
}

// Surgeon Search and Seminar Search helper methods
function SearchActivateZipInputFields(prefix) {
	$(prefix + "Zip").disabled = false;
	$(prefix + "WithinMiles").disabled = false;
}

function SearchValidateZipFailure(prefix) {
	if (prefix.indexOf("Widget") == "-1") {
		// non-widget code
		$(prefix + "Zip_SearchButton").className = "button disabled";
	}
	else {
		// widget code
		alert("Please enter a valid ZIP Code");
	}
}

function SearchValidateZipSuccess(prefix) {
	if (prefix.indexOf("Widget") == "-1") {
		// non-widget code
		$(prefix + "Zip_SearchButton").className = "button active";
	}
}

function SearchValidateZip(prefix) {
	// activate input fields
	SearchActivateZipInputFields(prefix);
	if ($(prefix + "Zip").value.length != 5) {
		SearchValidateZipFailure(prefix);
		return false;
	}
	var valid = "0123456789";
	for (var i=0; i < $(prefix + "Zip").value.length; i++) {
		temp = "" + $(prefix + "Zip").value.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			SearchValidateZipFailure(prefix);
			return false;
		}
	}
	SearchValidateZipSuccess(prefix);
	return true;
}

function SearchActivateNameInputFields(prefix) {
	$(prefix + "SurgeonLastName").disabled = false;
}

function SearchValidateName(prefix) {
	SearchActivateNameInputFields(prefix);
	if (($(prefix + "SurgeonLastName").value.length < 2) || ($(prefix + "SurgeonLastName").value == "Enter a Surgeon Last Name")) {
		if (prefix.indexOf("Widget") == "-1") {
			// non-widget code
			$(prefix + "SurgeonLastName_SearchButton").className = "button disabled";
		}
		else {
			// widget code
			alert("Please enter a valid Surgeon Last Name");
		}
		return false;
	}
	if (prefix.indexOf("Widget") == "-1") {
		// non-widget code
		$(prefix + "SurgeonLastName_SearchButton").className = "button active";
	}
	return true;
}

function SearchPrepareFormSubmit(prefix, zipIntervalId, nameIntervalId) {
	clearInterval(zipIntervalId);
	clearInterval(nameIntervalId);
	if (prefix.indexOf("Widget") == "-1") {
		// non-widget code
		$("LoadingImageDiv").style.display = "";
	}
}

function SearchDisableInputFields(prefix) {
	$(prefix + "Zip").disabled = true;
	$(prefix + "WithinMiles").disabled = true;
	$(prefix + "SurgeonLastName").disabled = true;
	if (prefix.indexOf("Widget") == "-1") {
		// non-widget code
		$(prefix + "Zip_SearchButton").className = "button disabled";
		$(prefix + "SurgeonLastName_SearchButton").className = "button disabled";
	}
}

function DoSearchZip(prefix, zipIntervalId, nameIntervalId) {
	if (SearchValidateZip(prefix)) {
		SearchPrepareFormSubmit(prefix, zipIntervalId, nameIntervalId);
		$(prefix + "SelectedTab").value = "SearchByLocationTab";
		$(prefix + "SearchForm").submit();
		SearchDisableInputFields(prefix);
	}
}

function DoSearchName(prefix, zipIntervalId, nameIntervalId) {
	if (SearchValidateName(prefix)) {
		SearchPrepareFormSubmit(prefix, zipIntervalId, nameIntervalId);
		$(prefix + "SelectedTab").value = "SearchBySurgeonTab";
		$(prefix + "SearchForm").submit();
		SearchDisableInputFields(prefix);
	}
}

function validateOneCharacterEntered(prefix) {
	if ($(prefix + "Field").value.length < 1) {
		$(prefix + "Button").className = "button disabled";
		return false;
	}
	$(prefix + "Button").className = "button active";
	return true;
}


function validateZip(zip) {
	if (zip.length < 5) {
		return false;
	}
	var valid = "0123456789-";
	for (var i=0; i < zip.length; i++) {
		temp = "" + zip.substring(i, i+1);
		if (valid.indexOf(temp) == "-1") {
			return false;
		}
	}
	return true;
}

Date.tryParseDate = function(str, fmt) {
	var today = new Date();
	var y = 0;
	var m = -1;
	var d = 0;
	var a = str.split(/\W+/);
	var b = fmt.match(/%./g);
	var i = 0, j = 0;
	var hr = 0;
	var min = 0;
	for (i = 0; i < a.length; ++i) {
		if (!a[i])
			continue;
		switch (b[i]) {
		    case "%d":
		    case "%e":
			d = parseInt(a[i], 10);
			break;

		    case "%m":
			m = parseInt(a[i], 10) - 1;
			break;

		    case "%Y":
		    case "%y":
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
			break;

		    case "%b":
		    case "%B":
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
			}
			break;

		    case "%H":
		    case "%I":
		    case "%k":
		    case "%l":
			hr = parseInt(a[i], 10);
			break;

		    case "%P":
		    case "%p":
			if (/pm/i.test(a[i]) && hr < 12)
				hr += 12;
			else if (/am/i.test(a[i]) && hr >= 12)
				hr -= 12;
			break;

		    case "%M":
			min = parseInt(a[i], 10);
			break;
		}
	}
	if (isNaN(y)) y = today.getFullYear();
	if (isNaN(m)) m = today.getMonth();
	if (isNaN(d)) d = today.getDate();
	if (isNaN(hr)) hr = today.getHours();
	if (isNaN(min)) min = today.getMinutes();
	if (y != 0 && m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	y = 0; m = -1; d = 0;
	for (i = 0; i < a.length; ++i) {
		if (a[i].search(/[a-zA-Z]+/) != -1) {
			var t = -1;
			for (j = 0; j < 12; ++j) {
				if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
			}
			if (t != -1) {
				if (m != -1) {
					d = m+1;
				}
				m = t;
			}
		} else if (parseInt(a[i], 10) <= 12 && m == -1) {
			m = a[i]-1;
		} else if (parseInt(a[i], 10) > 31 && y == 0) {
			y = parseInt(a[i], 10);
			(y < 100) && (y += (y > 29) ? 1900 : 2000);
		} else if (d == 0) {
			d = a[i];
		}
	}
	if (y == 0)
		y = today.getFullYear();
	if (m != -1 && d != 0)
		return new Date(y, m, d, hr, min, 0);
	return null;
};

function validatePastDate(date) {
	var parsedDate = Date.tryParseDate(date, "%m/%d/%Y");
	if (parsedDate == null) {
		return false;
	}
	return (parsedDate < new Date());
}

function validateFutureDate(date) {
	var parsedDate = Date.tryParseDate(date, "%m/%d/%Y");
	if (parsedDate == null) {
		return false;
	}
	return (parsedDate > new Date());
}

function validatePositiveNumber(num) {
	if (isNaN(num)) {
		return false;
	}
	return (num > 0);
}

function validateEmail(email) {
	return (email.match(/^([0-9a-zA-Z]+[-._'+&])*[_0-9a-zA-Z]+@([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$/) != null);
}

var validationEffectMap = {};

var ValidateField = function (row, field, error, condition, options) {
	// console.log('ValidateField() - Field: ' + field + ', Condition: ' + condition);
	if (!options) options = {};
	if ($(error)) {
		var validated = false;
		
		if (condition == "always") {
			validated = true;
		}
		else if (condition == "checked") {
			validated = $(field).checked;
		}
		else if (condition == "required") {
			var value = $(field).value.strip();
			if (value != "") {
				validated = true;
				if (options.minLength && (value.length < options.minLength))
					validated = false;
				if (validated && options.maxLength && (value.length > options.maxLength))
					validated = false;
			}
		}
		else if (condition == "pastdate") {
			validated = validatePastDate($(field).value);
		}
		else if (condition == "futuredate") {
			validated = validateFutureDate($(field).value);
		}
		else if (condition == "positivenumber") {
			validated = validatePositiveNumber($(field).value);
		}
		else if (condition == "optionalpositivenumber") {
			validated = ($(field).value == "" || validatePositiveNumber($(field).value));
		}
		else if (condition == "zipcode") {
			validated = validateZip($(field).value);
		}
		else if (condition == "email") {
			validated = validateEmail($(field).value);
		}
		else if (typeof condition == 'function')
		{
			validated = condition(row, field, error, options);
		}
		
		updateValidatedRow(validated, row);
		
		return validated;
	}
	else {
		return true;
	}
}

function updateValidatedRow(isValid, row)
{
	if (isValid && !$(row).hasClassName('fielderrorresolved')) {
			$(row).setAttribute("class", "fielderrorresolved");
			$(row).setAttribute("className", "fielderrorresolved");
			$(row).setStyle({backgroundColor: 'transparent'});
			validationEffectMap[row] = new Effect.Highlight(row, {duration: 6, endcolor: "#eef7f7", startcolor: "#badadb"});
	}
	else if (!isValid && !$(row).hasClassName('fielderror')) {
		if (validationEffectMap[row])
			validationEffectMap[row].cancel();
		$(row).setAttribute("class", "fielderror");
		$(row).setAttribute("className", "fielderror");
		$(row).setStyle({backgroundColor: '#EF8273'});
	}
}

var fieldsAllFilledIn = function (fields) {
	for (var i = 0; i < fields.length; i++) {
		if ($(fields[i]).value == null || $(fields[i]).value == "") {
			return false;
		}
	}
	return true;
}

var fieldsAtLeastOneChecked = function (fields) {
	for (var i = 0; i < fields.length; i++) {
		if ($(fields[i]).checked) {
			return true;
		}
	}
	return false;
}

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);
    }
}


var hidemonthfilter = function() {
	$('monthfiltercontainer').addClassName('hidden');
	$('searchnav').removeClassName('hidden');
	if($('View'))
		$('View').value='List';
}

var hidesearchnav = function(){
	$('monthfiltercontainer').removeClassName('hidden');
	$('searchnav').addClassName('hidden');
	if($('View'))
		$('View').value='Calendar';
}

var hideseminardetailtabs = function() {
	if ($('tab1btn'))
		$('tab1btn').removeClassName('selected');
	if ($('tab2btn'))
		$('tab2btn').removeClassName('selected');
	if ($('tab3btn'))
		$('tab3btn').removeClassName('selected');
	if ($('tab1bdy'))
		$('tab1bdy').addClassName('hidden');
	if ($('tab2bdy'))
		$('tab2bdy').addClassName('hidden');
	if ($('tab3bdy'))
		$('tab3bdy').addClassName('hidden');
}

var tabsemclick = function(tabn){
	hideseminardetailtabs();
	$('tab'+tabn+'btn').addClassName('selected');
	$('tab'+tabn+'bdy').removeClassName('hidden');
}

var forceShowTab = function(id) {
	showPoPupTab($('tab-' + id), '.content' + id);
}

// load movies
function openWin(page) {
OpenWin = this.open(page, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=auto,resizable=no,height=500,width=600");
}


var showEmailToPatients = function() {
	var el = $('sendtopatients');
	el.style.top = $('modalbody').style.top;
	el.removeClassName('hidden');
}

var showBottomCallout = function(ele) {
	var el = $(ele);
	$("showcalloutcontent").innerHTML = el.innerHTML;
	$("showcallout").removeClassName("hidden");
}
/*
function playMovie(fileName,targetDiv) {

	var maskie6 = 0;
	if (typeof document.body.style.maxHeight == "undefined") //is ie6
		maskie6 = 22;

	var pageDimensions = xDocSize();
	$("moviemask").setStyle ({ 	
		height : pageDimensions["h"] + "px",
		width : (pageDimensions["w"] - maskie6) + "px"
	});
	

	var videobody = $("videomodalbody");
	videobody.setStyle({
			top:(document.documentElement.scrollTop + 100) + "px"
			//left:(document.body.offsetWidth / 2) - (width / 2) + "px"
		});	


	var flashvars = {videoSource:siteroot + "local/flash/" + fileName, autoplay:"true"};
	var params = {allowScriptAccess:"always"};
	var attributes = {};
	$('videopopup').removeClassName('hidden');
	swfobject.embedSWF(siteroot + "local/flash/LapbandVideoPlayer_535x383.swf",targetDiv,"535", "383", "8","expressInstall.swf", flashvars, params, attributes);
	
}*/

function stopMovie(targetDiv) {
	$('videopopup').addClassName('hidden');
	$("testimonialContent").up().innerHTML = "<div id='testimonialContent'></div>";
}

var signIn = function() {
	location.href = siteroot + "en/sign_in/";
}

var register =  function() {
	location.href = siteroot + "en/register/";
}

/*  // think these are from physician site and not needed on lapband.com TODO: delete this if it isn't needed.
var profile = function() {
	location.href = siteroot + "en/dashboard/profile/";
}

var pref = function() {
	location.href = siteroot + "en/dashboard/profile/?ActiveTab=3";
}

var opt = function() {
	location.href = siteroot + "en/dashboard/profile/?ActiveTab=3";
}

var pending = function() {
	location.href = siteroot + "en/dashboard/my_lapbandlink/?Activetab=received";
}
	
var links = function() {
	location.href = siteroot + "en/dashboard/my_lapbandlink/?Activetab=links";
}

var learnMore1 = function() {
	location.href = siteroot + "en/bariatric_surgery/nonsurgical_options/";
}

var learnMore2 = function() {
	location.href = siteroot + "en/about_lapband/safety_and_efficacy/";
}

var learnMore3 = function() {
	location.href = siteroot + "en/bariatric_surgery/eligible_patients/";
}



var checkphone = function(){
	$('optinbutton').disabled = true;
	var t = $('OPhone1').value;
	if ((t-0) == t && t.length==3)
	{
		t = $('OPhone2').value;
		if ((t-0) == t && t.length==3)
		{
			t = $('OPhone3').value;
			if ((t-0) == t && t.length==4)
			{
				$('optinbutton').disabled = false;
				return true;
			}
		}
	}
	return false;
}
*/

var flashRef = function(refno) {
	Modal.open({contentEl: refno})
}

	function fileliststartCallback() {
		// make something useful before submit (onStart)
		if ($("BTNSend"))
			$("BTNSend").disabled=true;
		$("waiting").className = "";
		$("form").className = "hidden";
		$($('todo').value).className="";
		return true;
	}

	function filelistcompleteCallback(response) {
		// make something useful after (onComplete)
		if ($("BTNSend"))
			$("BTNSend").disabled=false;
		$('r').innerHTML = response;
	}

	function filelistfailCallback() {
		if ($("BTNSend"))
			$("BTNSend").disabled=false;
		$("waiting").className = "hidden";
		$("form").className = "";
		$($('todo').value).className="hidden";
		alert ('Unable to upload \n' + $('form[file]').value );
		$('fileupload').reset();
		return true;
	}

/**
*
*  AJAX IFRAME METHOD (AIM)
*  http://www.webtoolkit.info/
*
**/
 
AIM = {
 
	frame : function(c) {
 
		var n = 'f' + Math.floor(Math.random() * 99999);
		var d = document.createElement('DIV');
		d.innerHTML = '<iframe style="display:none" src="about:blank" id="'+n+'" name="'+n+'" onload="AIM.loaded(\''+n+'\')"></iframe>';
		document.body.appendChild(d);
 
		var i = document.getElementById(n);
		if (c && typeof(c.onComplete) == 'function') {
			i.onComplete = c.onComplete;
		}
		if (c && typeof(c.onFail) == 'function') {
			i.onFail = c.onFail;
		}
 
		return n;
	},
 
	form : function(f, name) {
		f.setAttribute('target', name);
	},
 
	submit : function(f, c) {
		AIM.form(f, AIM.frame(c));
		if (c && typeof(c.onStart) == 'function') {
			return c.onStart();
		} else {
			return true;
		}
	},
 
	loaded : function(id) {
		var i = $(id);
		var d = null;
		if (i.contentDocument) {
			d = i.contentDocument;
		} else if (i.contentWindow) {
			try { d = i.contentWindow.document; }
			catch (err) {}
		} 
		if (d == null) {
			try { d = window.frames[id].document; }
			catch (err) {}
		}
		if (d!=null && d.location.href == "about:blank") {
			return;
		}
 
		if (d==null){
			if (typeof(i.onFail) == 'function') {
				i.onFail();
			}		
		} else {
			if (typeof(i.onComplete) == 'function') {
				i.onComplete(d.body.innerHTML);
			}
		}
	}
 
}

var videoComplete = function(){
}
// landing page whats next links from flash calls
var whatsNext = function(){
	loc = location.href;
	if (loc.match(/learn_about_lapband/)) location.href = siteroot + "en/learn_about_lapband/taking_charge_of_your_health/";
	if (loc.match(/lapband_is_for_you/)) location.href = siteroot + "en/lapband_is_for_you/medical_considerations/";	
	if (loc.match(/prepare_for_surgery/)) location.href = siteroot + "en/prepare_for_surgery/working_with_surgeon/";		
	if (loc.match(/live_healthy_lapband/)) location.href = siteroot + "en/live_healthy_lapband/immediately_after_surgery/";	
	
}


//-- 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);
}



//-- Request Call back popup
var SecondaryReferralIDs = [];
var PrimarySourceChange = function (SelectedOption) {
	if (String(SelectedOption.getAttribute("hastext")) == "true") {
		$("PrimaryReferralText").style.display = "";
	} else {
		$("PrimaryReferralText").style.display = "none";
	}

	for (var i=0; i<SecondaryReferralIDs.length; i++) {
		$("SecondarySourceDiv_" + SecondaryReferralIDs[i]).style.display = "none";
	}
	if ($("SecondarySourceDiv_" + SelectedOption.value)) {
		$("SecondarySourceDiv_" + SelectedOption.value).style.display = "";
	}
}

var SecondarySourceChange = function (SelectedParentReferralID, SelectedOption) {
	if (String(SelectedOption.getAttribute("hastext")) == "true") {
		$("SecondaryReferralText_" + SelectedParentReferralID).style.display = "";
	} else {
		$("SecondaryReferralText_" + SelectedParentReferralID).style.display = "none";
	}
}

var phone_field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		phone_field_length=obj.value.length;
	}
	else if (event == "up") {
		if (obj.value.length != phone_field_length) {
			phone_field_length=obj.value.length;
			if (phone_field_length == len) {
				next_field.focus();
			}
		}
	}
}


var ShowDevice = function(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';
}



var popupFlash =  function(filename) {
	var fullpath = siteroot + 'local/flash/' + filename;
	Modal.open({contentEl: 'flashpopup', width:724, ptype:'typeflash'})
	$('modalcontent').update('<div id="flashcontent"></div>');
	swfobject.embedSWF( fullpath, "flashcontent", "724", "440", "8.0.0","", '', {wmode:"transparent"}, '');
	
}

var popupEmmiFlash =  function(filename) {
	var fullpath = siteroot + 'local/flash/' + filename;
	Modal.open({contentEl: 'flashpopup', width:672, ptype:'typeflash'})
	$('modalcontent').update('<div id="flashcontent"></div>');
	swfobject.embedSWF( fullpath, "flashcontent", "672", "440", "8.0.0","", '', {wmode:"transparent"}, '');
	
}


function confirmAndTrackExit(ele,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);
		siteCatalystLink(theLocation,innerhtml);
		window.open(theLocation);
    }

	var innerhtml = ele.innerHTML;
}

var checkBMI = function() {
	var inches = 0;
	if (document.getElementById("HeightInches").value != '' && document.getElementById("HeightInches").value != '.')
	{
		inches = parseInt(document.getElementById("HeightInches").value);
	}
	var month = $F('month');
	var year = $F('year');
	var feet = parseInt(document.getElementById("HeightFeet").value);
	var height = (feet*12) + inches;
	var weight = parseInt(document.getElementById("PreOpWeight").value);
	var BMI = (weight * 703)/(height * height);
	var StrBMI = BMI.toString().substr(0,BMI.toString().indexOf(".")+2)
	var over18 = checkage(month,year);
	var qual = "Do Not Qualify";

	if (isNaN(BMI) || feet == 0 || weight==0 || BMI==0 || month==0 || year==0)
	{
		$("bmialert").innerHTML = "Please enter valid values for height, weight and birthdate.";
		siteCatalystFirePageView(location.pathname + "_validationerror",
					function(s){
						s.pageName = (location.pathname + "_validationerror/").replace(/\/_/, '_');
						s.hier3 = 'validationerror';
						s.channel = 'validationerror';
						s.prop49=s.pageName + ":bmiinfo";
					}
				);
		$("BMI").addClassName("hidden");
	}else{
		if(BMI < 35 || !over18) {
			$("bmialert").update("Your BMI is " + parseInt(BMI) + ". Based on the information you entered you do not qualify as a LAP-BAND<sup>&reg;</sup> System candidate");
			$("BMI").addClassName("hidden");
		}
		else {
			$("bmialert").update("Your BMI is " + parseInt(BMI) + ". Based on the information you entered you may qualify as a LAP-BAND<sup>&reg;</sup> System candidate");
			$('rFt').update(feet);
			$('rIn').update(inches);
			$('rWeight').update(weight);
			$('rBMI').update(BMI.floor());
			$("BMI").removeClassName("hidden");
			qual = "May Qualify";
		}
		//var compH = feet + " feet " + inches + " inches";
		//siteCatalystBMI(parseInt(BMI),qual,height,weight);

		siteCatalystFirePageView(location.pathname + "_complete",
					function(s){
						s.pageName = (location.pathname + "_complete/").replace(/\/_/, '_');
						s.hier3 = s.pageName.replace(/\//g, ',').replace(/^,/, '').replace(/,$/, '');
						s.channel = 'lapband_is_for_you';
						s.prop6 = height;
						s.prop7 = weight;
						s.eVar10 = parseInt(BMI);
						s.eVar11 = filterVar(qual);
						s.events += ",event30";
						s.linkTrackVars += ",prop6,prop7,eVar10,eVar11";
						s.linkTrackEvents += ",event30";
					}
				);

	}
	$("bmialert").removeClassName("hidden");
}

var checkage = function(month,year){
	var over18 = false;
	if(month>0 && year>0 ){
		var currentTime = new Date();
		var yearage = currentTime.getFullYear() - year;
		var monthage = (currentTime.getMonth()+1) - month;
		if(yearage > 17 || (yearage == 17 && monthage >= 0)) over18=true;

	}
	
	return over18;
}


/************* Homepage swf funcs **********************/

var findSeminarZip = function (zipcode){
	if ($("SeminarZipSearchForm") && zipcode!="" && zipcode.length==5)
	{
		$("SeminarZip").value = zipcode;
		$("SeminarZipSearchForm").submit();
	} else {
		window.location = fullsiteroot() + "/en/lapband_is_for_you/attend_a_seminar/";
	}
}

function fireEvent(obj,evt){
	var fireOnThis = obj;
	if( document.createEvent ) {
	  var evObj = document.createEvent('MouseEvents');
	  evObj.initEvent( evt, true, false );
	  fireOnThis.dispatchEvent(evObj);
	} else if( document.createEventObject ) {
	  fireOnThis.fireEvent('on'+evt);
	}
}

var watchVideo = function(){
	playSeminar ('SEMINAR_FINAL_Lapband.flv', 'video1', 'testimonialContent1');
	//$('showvideolink').click(); //doesn't work in FF
	fireEvent($('showvideolink'),'click');
}

var isiLink = function(){
	//window.location = fullsiteroot() + "en/learn_about_lapband/the_procedure_safety/risk_information/";
	window.location = fullsiteroot() + "en/learn_about_lapband/safety_information/";
}

var seminarLink = function (){
	//window.location = fullsiteroot() + "en/lapband_is_for_you/attend_a_seminar/";
	window.location = fullsiteroot() + "en/register/";
}

window.onload = function() {
	//hide "Safety Information"  under "Learn About LB" for bottom menu
	var findSI = $$('.extendednavcontainer table tr td ul li a');
	findSI.each(function(s) {
		if (s.innerHTML == 'Safety Information') {
			s.up('li').style.display = "none";
		}
	});
	
	//add "News" and "Internet Resources" under "Success Story" for bottom menu
	/*
	var addItemsSS = $$('.extendednavcontainer table tr td a');
	addItemsSS.each(function(e) {
		if (e.innerHTML == 'Success Stories ') {
			getUL = e.nextSiblings();
			getUL[0].insert('<li><a href="'+ fullsiteroot() + 'en/news/">News</a></li>');
			getUL[0].insert('<li><a href="'+ fullsiteroot() + 'en/resource_center/">Internet Resources</a></li>');
		}
	});
	*/
	
	//make top menu text clickable
	var getTopMenuURL = $$('.header .navigation .dropdownmenu');
	getTopMenuURL.each(function(s) {
		if(typeof s.down('div') != 'undefined') {
			s.down('div').observe('click',function() {
				window.location = s.previous("a");
			});
		}
	});
};

/*
document.observe("dom:loaded", function() {
	if($('announcement')) {
		if (!Cookie.get('announcementCookie')) {
			
			//s.pagename="Home:Redesigned Lapband.com Announcement"; //analytics code commented out for now.
			cookieduration = 43200;  //  5 yrs
			Cookie.set('announcementCookie',"1", cookieduration);
			// pause flash 			
			//$('homeflash').StopPlay();
			setTimeout("$('homeflash').StopPlay();",500);
			Modal.open({contentEl: 'announcement', width:818, ptype:'typeannouncement'})
		}		
	}
										 
});
*/
/*show all for lifestyle guidelines*/
var showAllLife = function() {
	var content = $$('#explistLifestyle .expcontent');
	content.each(function(s) {
		s.removeClassName('hidden');
		s.previous().down('.explink').addClassName('on');
	})
}
var sh_chk =  function(){
	
	if($F('sh_name') != '' && $F('sh_email') != '' && $F('YearOfBirth') != '' && ($F('sh_gender1') != null || $F('sh_gender2') != null) && $F('DateBanded') != '' && ($F('SurgeryPerformedInUS_Yes') != null  || $F('SurgeryPerformedInUS_No') != null) && $F('HeightFt') != '' && $F('HeightIn') != '' && $F('PreopWeight') != '' && $F('CurrentWeight') != '' && $F('StoryTopicID') != '' && $F('StoryArea') != '' && $F('agree') != null) {
	
		$('sh_preview').removeClassName('buttonactionalt');
		$('sh_preview').addClassName('buttonaction');
		
	} else {
		$('sh_preview').removeClassName('buttonaction');
		$('sh_preview').addClassName('buttonactionalt');
	}
}
	
	
var homeFlash = function(){
	
	var flashvars = {};
	var params = {wmode:"transparent"};
	var attributes = {};
	
	if (!Cookie.get('introCookie')) {
		var randomnumber=Math.floor(Math.random()*2);
		flashvars = {sectionVar:randomnumber, rotatorXML:'carouselxml'};
		Cookie.set('introCookie',"1",720);
	} else {
		flashvars = {rotatorXML:'carouselxml'};
	}
	swfobject.embedSWF( siteroot + "local/flash/Lapband_Homepage_983x486_v11.swf", "homeflash", "983", "486", "8.0.0","", flashvars, params, attributes);	
}


var stripHTML = function(oldString) {

   var newString = "";
   var inTag = false;
   for(var i = 0; i < oldString.length; i++) {
   
        if(oldString.charAt(i) == '<') inTag = true;
        if(oldString.charAt(i) == '>') {
              if(oldString.charAt(i+1)=="<")
              {
              		//dont do anything
			  }
			  else
			  {
				inTag = false;
				newString += " ";
				i++;
			  }
        }
   
        if(!inTag) newString += oldString.charAt(i);

   }

   return newString;
}


var videoStart = function(pathname) {
	siteCatalystVidStart(pathname);
}

var videoComplete = function(pathname) {
	siteCatalystVidEnd(pathname);
}

var getFileName = function(pathname) {
	if (pathname)
	{
		var filename = pathname.substr(pathname.lastIndexOf("/")+1,pathname.length);
		return filename;
	} else
		return '';
}
