Event.observe(window, "load", function() {
	$$("a.klick-toggle").each(function(el) {
		var text = el.title.split("/")
		el.observe("click", function() {
			var body = el.up(".showhideheader").next(".l");
			body.toggleClassName("hidden");
			el.innerHTML = body.hasClassName("hidden") ? text[0] : text[1];
			el.toggleClassName("show");
		});
	})

	// dropdown menu functions
	var lis = document.getElementById("navmenu-h").getElementsByTagName("LI");
	for (var i=0; i<lis.length; i++) {
		lis[i].onmouseover=function() {
			Element.addClassName(this, "iehover");
		}
		lis[i].onmouseout=function() {
			Element.removeClassName(this, "iehover");
		}
	}
	
	
	if($('topMenuBoxes')) {
		$('topMenuBoxes').select('.topMenuBox').invoke('observe','mouseout',function(event){
			var element = $(this.id);
			var relatedTarget = $(event.relatedTarget || event.fromElement);
			var target = Event.element(event);
			
			if ((target == element || Element.descendantOf(target, element)) && !((relatedTarget == element) || Element.descendantOf(relatedTarget, element))){
				//document.getElementById(this.id).style.display='none';
				//sasasas = 12121212;
				$(this.id).addClassName('hidden');
			}
		})
		
	}
	
	if($('riskinfo')){
		$('riskinfo').select('a[target="_blank"]').invoke('observe','click',function(ev){
			if(this.href.indexOf(window.location.hostname) == -1){
				Event.stop(ev);
				var exitmsg = 'You are now leaving the lapbandcentral.com website.\n\nClick "OK" to continue or "Cancel" to remain on this site.';
				confirmExit(this.href,exitmsg);
			}
		})
	}
	
});

// external site link
function confirmExit(theLocation, theMessage) {
	if(!theMessage || typeof(theMessage) == 'undefined')
		theMessage = "You are now leaving the lapbandcentral.com website.\n\nClick \"OK\" to continue or \"Cancel\" to remain on this site.";

    if (confirm(theMessage)) {
      window.open(theLocation);
    }
}

// show and hide the login and search boxes
	function showSearch(boxLauncher)
	{
		document.getElementById(boxLauncher).style.display="block";
	}

	function hideSearch(boxKiller)
	{
		document.getElementById(boxKiller).style.display="none";
	}


// un-signed home page document region
	function ShowElement(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 r6_NUMBER
			var a=new Array("document_1","document_2","document_3","document_4")
			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';
		}
	
	
	function ShowTab(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 r6_NUMBER
			var a=new Array("homeDetailsTab1","homeDetailsTab2","homeDetailsTab3","homeDetailsTab4")
			for (var i=0;i<a.length;i++)
			{	document.getElementById(a[i]).className="none"
			}
		}



// background cache

try {document.execCommand("backgroundimagecache", false, true);} catch (e) {}



// tutorial opener

function openTutorial(page) {
OpenWin = this.open(page, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=no,resizable=no,height=434,width=704");
}

// emmi show me opener
function openEmmi(page) {
OpenWin = this.open(page, "CtrlWindow", "toolbar=no,menubar=no,location=no,scrollbars=auto,resizable=no,height=500,width=600");
}

// 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)};
}

//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")		
		if (modalcontainer.hasClassName("hidden")) modalcontainer.removeClassName("hidden");		
		modalmask.className = "modalmask";
		modalcontainer.setStyle({top : "0", left: "0"})
		modalmask.addClassName(maskStyle);
		this.resizeHandler();
	},
	close : function() {		
		var modalcontainer = $("modalcontainer");
		var modalcontent = $("modalcontent")
		if (!modalcontainer.hasClassName("hidden")) modalcontainer.addClassName("hidden");
		if (modalcontent.hasClassName("hasFlashVideo")){
			modalcontent.innerHTML = "";
			modalcontent.removeClassName("hasFlashVideo");
		} 
	},
	resizeHandler : function(){
		var modalmask = $("modalmask")
		var pageDimensions = xDocSize();
		modalmask.setStyle ({ 	
			height : pageDimensions["h"] + "px",
			width : pageDimensions["w"] + "px"
		})
	},
	open :function(options){
		$("modalcontent").innerHTML ="<img src='"+ fullsiteroot() +"local/images/icons/loading.gif' />";
		var width, url, contentEl, hasMask, movieID, hasFlashVideo;
		var modalbody = $("modalbody");
		if (options){
			width = options.width || 400;
			url = options.url || "";	
			contentEl = options.contentEl || "";			
			hasMask = options.hasMask;
			movieID = options.movieID || "";
			hasFlashVideo = options.hasFlashVideo;
		}
		
		//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});
		modalbody.setStyle({
			width: width + "px",
			top:(100 + safariOffset) + "px",
			left:(document.body.offsetWidth / 2) - (width / 2) + "px"
		});	
		
		
		
		if (url != ""){
			new Ajax.Updater("modalcontent",options.url,{evalScripts:true})	
			if (hasFlashVideo){
				$("modalcontent").addClassName("hasFlashVideo");
			}
		} 
		else if (contentEl != ""){
			$("modalcontent").innerHTML = $(contentEl).innerHTML;
			setTimeout(function(){
				$("modalcontent").innerHTML = $("modalcontent").innerHTML
			}, 50);
			//if(Element.hasClassName(contentEl, "hidden")) Element.removeClassName(contentEl, "hidden");
		}
		if (movieID != ""){
			if (!Element.hasClassName("modalcloser","hasMovie")) Element.addClassName("modalcloser","hasMovie");			
		} else {
			if (Element.hasClassName("modalcloser","hasMovie")) Element.removeClassName("modalcloser","hasMovie");
		}
	}
}

Event.observe (window,"resize",Modal.resizeHandler);
Event.observe(window,"load",function(){									 
	if ($("modalcloser"))Event.observe ("modalcloser","click",function(evnt){
		Modal.close()
		if (Element.hasClassName("modalcloser", "hasMovie")) {
			stopPlayback("tlcWalk");
			Element.removeClassName("modalcloser","hasMovie")
		}
		Event.stop(evnt);
	});
});



// modal video stuff

function getMovieName(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName]
	}
	else {
		return document[movieName]
	}
}



// 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


// EXPAND-COLLAPSE TOOL FOR HOSPITAL MARKETING PAGE
// location: /en/total_care/origination/hospital_marketing/
var hospitalMarketingExpand = function(divID){
	$("bigcontainer01").addClassName("hospitalMarketingCollapsed");
	$("bigcontainer02").addClassName("hospitalMarketingCollapsed");
	$("bigcontainer03").addClassName("hospitalMarketingCollapsed");
	
	$(divID).removeClassName("hospitalMarketingCollapsed")
}
// END EXPAND-COLLAPSE TOOL FOR HOSPITAL MARKETING PAGE




function stopPlayback(id) {
	var moviename =	getMovieName(id);
	if(moviename)
		moviename.callASfunction(); 
}

function playVideo(fileName,id, targetDiv) {
	$("videomask").setStyle({
		height : document.documentElement.scrollHeight + document.documentElement.scrollTop + 40 + "px",
		width : document.body.offsetWidth + "px"
	});
	
	var width = 347;
	$("videobody").setStyle({
		top:(document.documentElement.scrollTop + 50) + "px",
		left:(document.body.offsetWidth / 2) - (width / 2) + "px"
	});
	
	$("videocontainer").removeClassName("hidden");
 	var so = new SWFObject(siteRoot() + "local/flash/video/LapbandVideoPlayer_347x333.swf", id, "347", "333", "9");
 	so.addVariable("videoSource",siteRoot() + "local/flash/video/" + fileName);
 	so.addParam("allowScriptAccess", "always");
 	currVideo = id;
 	so.write(targetDiv);
}

function closevidpopup() {
	$("videocontainer").addClassName("hidden");
	$("videocontent").up().innerHTML = "<div id='videocontent'></div>";

}

var forceShowTab = function(id) {
	showPoPupTab($('tab-' + id), '.content' + id);
}

var showPoPupTab = function(ele, ebody){
	el = $(ele).up('li');
	hidealltabsPopup(el.up("ul"));
	el.up("ul").up('.fulltabcontent').getElementsBySelector(ebody).invoke("removeClassName", "hidden");
	el.addClassName('selected');
};

var hidealltabsPopup = function(container) {
	//hide tabs
	$A(container.childNodes).each(function(el,index){
		if(el.nodeName.toLowerCase() == 'li')
			Element.removeClassName(el,'selected');
	});
	container.up('.fulltabcontent').getElementsBySelector('.contenttab').invoke('addClassName','hidden');//bodies
};

// functions to expand and collapse details on the change history page.
var changehistory_collapse_all = function(){
	var tbodies = $$('.expandabledetails');
	// Go though all of them and only look at ones with an ID set
	for (var i = 0; i < tbodies.length; i++) {
		if (tbodies[i].id != '') {
			changehistory_collapse_one(tbodies[i].id);
		}
	}
};

var changehistory_expand_all = function(){
	var tbodies = $$('.expandabledetails');
	// Go though all of them and only look at ones with an ID set
	for (var i = 0; i < tbodies.length; i++) {
		if (tbodies[i].id != '') {
			changehistory_expand_one(tbodies[i].id);
		}
	}
};

function changehistory_expand_one(id){
	var line=$(id);
	var vcollapse=$("C_" + id);
	var vexpand=$("E_" + id);
	if(!vexpand || !vcollapse || !line){
		return true;
	}
	line.removeClassName("hidden");
	vexpand.addClassName("hidden");
	vcollapse.removeClassName("hidden");
	return true;	
};

function changehistory_collapse_one(id){
	var line=$(id);
	var vcollapse=$("C_" + id);
	var vexpand=$("E_" + id);
	if(!vexpand || !vcollapse || !line){
		return true;
	}
	line.addClassName("hidden");
	vexpand.removeClassName("hidden");
	vcollapse.addClassName("hidden");
	return true;	
};

// We're overriding the implementation of Autocompleter with Scriptaculous version 1.8.2
// because earlier versions of Autocompleter are too buggy
Autocompleter = { };
Autocompleter.Base = Class.create({
  baseInitialize: function(element, update, options) {
    element          = $(element);
    this.element     = element;
    this.update      = $(update);
    this.hasFocus    = false;
    this.changed     = false;
    this.active      = false;
    this.index       = 0;
    this.entryCount  = 0;
    this.oldElementValue = this.element.value;

    if(this.setOptions)
      this.setOptions(options);
    else
      this.options = options || { };

    this.options.paramName    = this.options.paramName || this.element.name;
    this.options.tokens       = this.options.tokens || [];
    this.options.frequency    = this.options.frequency || 0.4;
    this.options.minChars     = this.options.minChars || 1;
    this.options.onShow       = this.options.onShow ||
      function(element, update){
        if(!update.style.position || update.style.position=='absolute') {
          update.style.position = 'absolute';
          Position.clone(element, update, {
            setHeight: false,
            offsetTop: element.offsetHeight
          });
        }
        Effect.Appear(update,{duration:0.15});
      };
    this.options.onHide = this.options.onHide ||
      function(element, update){ new Effect.Fade(update,{duration:0.15}) };

    if(typeof(this.options.tokens) == 'string')
      this.options.tokens = new Array(this.options.tokens);
    // Force carriage returns as token delimiters anyway
    if (!this.options.tokens.include('\n'))
      this.options.tokens.push('\n');

    this.observer = null;

    this.element.setAttribute('autocomplete','off');

    Element.hide(this.update);

    Event.observe(this.element, 'blur', this.onBlur.bindAsEventListener(this));
    Event.observe(this.element, 'keydown', this.onKeyPress.bindAsEventListener(this));
  },

  show: function() {
    if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update);
    if(!this.iefix &&
      (Prototype.Browser.IE) &&
      (Element.getStyle(this.update, 'position')=='absolute')) {
      new Insertion.After(this.update,
       '<iframe id="' + this.update.id + '_iefix" '+
       'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' +
       'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');
      this.iefix = $(this.update.id+'_iefix');
    }
    if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50);
  },

  fixIEOverlapping: function() {
    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    this.iefix.style.zIndex = 1;
    this.update.style.zIndex = 2;
    Element.show(this.iefix);
  },

  hide: function() {
    this.stopIndicator();
    if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update);
    if(this.iefix) Element.hide(this.iefix);
  },

  startIndicator: function() {
    if(this.options.indicator) Element.show(this.options.indicator);
  },

  stopIndicator: function() {
    if(this.options.indicator) Element.hide(this.options.indicator);
  },

  onKeyPress: function(event) {
    if(this.active)
      switch(event.keyCode) {
       case Event.KEY_TAB:
       case Event.KEY_RETURN:
         this.selectEntry();
         Event.stop(event);
       case Event.KEY_ESC:
         this.hide();
         this.active = false;
         Event.stop(event);
         return;
       case Event.KEY_LEFT:
       case Event.KEY_RIGHT:
         return;
       case Event.KEY_UP:
         this.markPrevious();
         this.render();
         Event.stop(event);
         return;
       case Event.KEY_DOWN:
         this.markNext();
         this.render();
         Event.stop(event);
         return;
      }
     else
       if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN ||
         (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return;

    this.changed = true;
    this.hasFocus = true;

    if(this.observer) clearTimeout(this.observer);
      this.observer =
        setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000);
  },

  activate: function() {
    this.changed = false;
    this.hasFocus = true;
    this.getUpdatedChoices();
  },

  onHover: function(event) {
    var element = Event.findElement(event, 'LI');
    if(this.index != element.autocompleteIndex)
    {
        this.index = element.autocompleteIndex;
        this.render();
    }
    Event.stop(event);
  },

  onClick: function(event) {
    var element = Event.findElement(event, 'LI');
    this.index = element.autocompleteIndex;
    this.selectEntry();
    this.hide();
  },

  onBlur: function(event) {
    // needed to make click events working
    setTimeout(this.hide.bind(this), 250);
    this.hasFocus = false;
    this.active = false;
  },

  render: function() {
    if(this.entryCount > 0) {
      for (var i = 0; i < this.entryCount; i++)
        this.index==i ?
          Element.addClassName(this.getEntry(i),"selected") :
          Element.removeClassName(this.getEntry(i),"selected");
      if(this.hasFocus) {
        this.show();
        this.active = true;
      }
    } else {
      this.active = false;
      this.hide();
    }
  },

  markPrevious: function() {
    if(this.index > 0) this.index--;
      else this.index = this.entryCount-1;
    this.getEntry(this.index).scrollIntoView(true);
  },

  markNext: function() {
    if(this.index < this.entryCount-1) this.index++;
      else this.index = 0;
    this.getEntry(this.index).scrollIntoView(false);
  },

  getEntry: function(index) {
    return this.update.firstChild.childNodes[index];
  },

  getCurrentEntry: function() {
    return this.getEntry(this.index);
  },

  selectEntry: function() {
    this.active = false;
    this.updateElement(this.getCurrentEntry());
  },

  updateElement: function(selectedElement) {
    if (this.options.updateElement) {
      this.options.updateElement(selectedElement);
      return;
    }
    var value = '';
    if (this.options.select) {
      var nodes = $(selectedElement).select('.' + this.options.select) || [];
      if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select);
    } else
      value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal');

    var bounds = this.getTokenBounds();
    if (bounds[0] != -1) {
      var newValue = this.element.value.substr(0, bounds[0]);
      var whitespace = this.element.value.substr(bounds[0]).match(/^\s+/);
      if (whitespace)
        newValue += whitespace[0];
      this.element.value = newValue + value + this.element.value.substr(bounds[1]);
    } else {
      this.element.value = value;
    }
    this.oldElementValue = this.element.value;
    this.element.focus();

    if (this.options.afterUpdateElement)
      this.options.afterUpdateElement(this.element, selectedElement);
  },

  updateChoices: function(choices) {
    if(!this.changed && this.hasFocus) {
      this.update.innerHTML = choices;
      Element.cleanWhitespace(this.update);
      Element.cleanWhitespace(this.update.down());

      if(this.update.firstChild && this.update.down().childNodes) {
        this.entryCount =
          this.update.down().childNodes.length;
        for (var i = 0; i < this.entryCount; i++) {
          var entry = this.getEntry(i);
          entry.autocompleteIndex = i;
          this.addObservers(entry);
        }
      } else {
        this.entryCount = 0;
      }

      this.stopIndicator();
      this.index = 0;

      if(this.entryCount==1 && this.options.autoSelect) {
        this.selectEntry();
        this.hide();
      } else {
        this.render();
      }
    }
  },

  addObservers: function(element) {
    Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this));
    Event.observe(element, "click", this.onClick.bindAsEventListener(this));
  },

  onObserverEvent: function() {
    this.changed = false;
    this.tokenBounds = null;
    if(this.getToken().length>=this.options.minChars) {
      this.getUpdatedChoices();
    } else {
      this.active = false;
      this.hide();
    }
    this.oldElementValue = this.element.value;
  },

  getToken: function() {
    var bounds = this.getTokenBounds();
    return this.element.value.substring(bounds[0], bounds[1]).strip();
  },

  getTokenBounds: function() {
    if (null != this.tokenBounds) return this.tokenBounds;
    var value = this.element.value;
    if (value.strip().empty()) return [-1, 0];
    var diff = arguments.callee.getFirstDifferencePos(value, this.oldElementValue);
    var offset = (diff == this.oldElementValue.length ? 1 : 0);
    var prevTokenPos = -1, nextTokenPos = value.length;
    var tp;
    for (var index = 0, l = this.options.tokens.length; index < l; ++index) {
      tp = value.lastIndexOf(this.options.tokens[index], diff + offset - 1);
      if (tp > prevTokenPos) prevTokenPos = tp;
      tp = value.indexOf(this.options.tokens[index], diff + offset);
      if (-1 != tp && tp < nextTokenPos) nextTokenPos = tp;
    }
    return (this.tokenBounds = [prevTokenPos + 1, nextTokenPos]);
  }
});

Autocompleter.Base.prototype.getTokenBounds.getFirstDifferencePos = function(newS, oldS) {
  var boundary = Math.min(newS.length, oldS.length);
  for (var index = 0; index < boundary; ++index)
    if (newS[index] != oldS[index])
      return index;
  return boundary;
};

Ajax.Autocompleter = Class.create(Autocompleter.Base, {
  initialize: function(element, update, url, options) {
    this.baseInitialize(element, update, options);
    this.options.asynchronous  = true;
    this.options.onComplete    = this.onComplete.bind(this);
    this.options.defaultParams = this.options.parameters || null;
    this.url                   = url;
  },

  getUpdatedChoices: function() {
    this.startIndicator();

    var entry = encodeURIComponent(this.options.paramName) + '=' +
      encodeURIComponent(this.getToken());

    this.options.parameters = this.options.callback ?
      this.options.callback(this.element, entry) : entry;

    if(this.options.defaultParams)
      this.options.parameters += '&' + this.options.defaultParams;

    new Ajax.Request(this.url, this.options);
  },

  onComplete: function(request) {
    this.updateChoices(request.responseText);
  }
});


var showtip = function(el){
	$(el).up("td").down(".emmitooltip").removeClassName("hidden")
}

var hidetip = function(el){
	$(el).up("td").down(".emmitooltip").addClassName("hidden")
}
