var filterVar = function(varvalue) {
	var newval = "";
	for (var i = 0; i< varvalue.length; i++) {
		var charcode = varvalue.charCodeAt(i);
		if (varvalue.charAt(i) != "\t" && varvalue.charAt(i) != "\n" && varvalue.charAt(i) != "\r\n") {
			if (charcode <= 127) {
				newval += varvalue.charAt(i);	
			}
			else {
				if (charcode >= 192 && charcode <= 197) newval += "A";
				else if (charcode == 198) newval += "AE";
				else if (charcode == 199) newval += "C";
				else if (charcode == 199) newval += "C";
				else if (charcode >= 200 && charcode <= 203) newval += "E";
				else if (charcode >= 204 && charcode <= 207) newval += "I";
				else if (charcode == 208) newval += "D";
				else if (charcode == 209) newval += "N";
				else if (charcode >= 210 && charcode <= 214) newval += "O";
				else if (charcode >= 217 && charcode <= 220) newval += "U";
				else if (charcode >= 224 && charcode <= 229) newval += "a";
				else if (charcode == 230) newval += "ae";
				else if (charcode == 231) newval += "c";
				else if (charcode >= 232 && charcode <= 235) newval += "e";
				else if (charcode >= 236 && charcode <= 239) newval += "i";
				else if (charcode == 240) newval += "o";
				else if (charcode == 241) newval += "n";
				else if (charcode >= 242 && charcode <= 246) newval += "o";
				else if (charcode >= 249 && charcode <= 252) newval += "u";
				else if (charcode == 253) newval += "y";
				else if (charcode == 338) newval += "OE";
				else if (charcode == 339) newval += "oe";
				else if (charcode == 352) newval += "S";
				else if (charcode == 353) newval += "s";
				else if (charcode == 376) newval += "Y";
			}
		}
	}
	// strip tags
	newval = newval.toLowerCase().replace(/(<([^>]+)>)/ig,"").replace(/&#\d+/ig, "").replace(/&amp;/ig,"&");
	return newval;
}
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");
			var expandButton = el.next(".klick-expand").down(".headertitle");
			body.toggleClassName("hidden");
			el.innerHTML = body.hasClassName("hidden") ? text[0] : text[1];
			el.toggleClassName("show");
			expandButton.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")
}

var otheremail = function(){
	var newval = $F('contactemail');
	if(newval == 'otheremail') 
		$('otheremailrow').removeClassName('hidden');
	else
		$('otheremailrow').addClassName('hidden');
}



/********************************************************/
/* start callbackwidgets:                               */
/********************************************************/

	var dontAskOnNavAway = false;

	var navigateAway = function (){
		if (dirty_tabs.indexOf("|" + currenttab +"|")>=0 && !dontAskOnNavAway) {
			return ("You have unsaved changes.");
		} else {
			return;
		}	
	}

	var dirtyfyTab = function(){
		if (currenttab!="" && dirty_tabs.indexOf("|" + currenttab +"|")<0) {
			dirty_tabs += "|" + currenttab +"|";
		}
	}

	var undirtyfyTab = function(thetab){
		if (thetab!="" && dirty_tabs.indexOf("|" + thetab +"|")>=0) {
			dirty_tabs = dirty_tabs.replace("|" + thetab +"|", "");
		}
	}

	var checkdirtyTab = function (newtab){
		if (dirty_tabs.indexOf("|" + currenttab +"|")>=0) {
			if (confirm("You have unsaved changes.\n Press OK to save or Cancel to proceed.")) {
				dontAskOnNavAway = true;
				$(currenttab+"form").submit();
				return false;
			} else {
				if ($("ResetForm") && $("DisplayTab"))
				{
					dontAskOnNavAway = true;
					$("DisplayTab").value=newtab;
					$("ResetForm").submit();
					return false;
				}
			}
		}	
		return true;
	}

	var checkdirtyTabAjax = function (newtab){
		if (dirty_tabs.indexOf("|" + currenttab +"|")>=0) {
			if (confirm("You have unsaved changes.\n Press OK to save or Cancel to proceed.")) {
				dontAskOnNavAway = true;
				$(currenttab+"form").onsubmit();
				return false;
			} else {
				if ($("ResetForm") && $("DisplayTab"))
				{
					dontAskOnNavAway = true;
					$("DisplayTab").value=newtab;
					$("ResetForm").onsubmit();
					return false;
				}
			}
		}
		return true;
	}


	var setCurrentTab = function (tab){
		currenttab = tab
	}

	var getRecipient = function(cbtype) {
		if ($(cbtype+"RecipientID").options[$(cbtype+"RecipientID").selectedIndex].value == "other") {
			$(cbtype+"add_recipient").style.display = "none";
			$(cbtype+"OtherEmailTR").style.display = "";
		}
		else {
			$(cbtype+"add_recipient").style.display = "";
			$(cbtype+"OtherEmailTR").style.display = "none";
		}
	}


	var removeRow = function (node, lookstring, cbtype)
	{
		if ($(cbtype+"RecipientID").disabled == true)
			return false;
		confirmResult = true;
		if ( $(cbtype +"_List").value.replace(lookstring, "") == "" && $("Enable"+ cbtype +"CallBackRequest").checked)
		{
			confirmResult = confirm('If you remove this only recipient, the ' + cbtype + ' request call back feature will be disabled.\n\nAre you sure you want to remove this recipient?');
			if (confirmResult)
			{
				$("Enable"+ cbtype +"CallBackRequest").checked = false;
				$("Enable"+ cbtype +"CallBackRequest").onclick();
			}
		}
		if (confirmResult)
		{
			var tr = node.parentNode;
			while (tr.tagName.toLowerCase() != "tr")
			tr = tr.parentNode;
			tr.parentNode.removeChild(tr);
			$(cbtype +"_List").value = $(cbtype +"_List").value.replace(lookstring, "");
		}
		dirtyfyTab();
	} 
	

	var removeOfficeRow = function (node, lookstring, cbtype, officeID)
	{
		if ($(cbtype+"O"+officeID+"RecipientID").disabled == true)
			return false;
		confirmResult = true;
		if ( $(cbtype+"O"+officeID+"_List").value.replace(lookstring, "") == "" && $("Enable"+cbtype+"O"+officeID+"CallBackRequest").checked)
		{
			confirmResult = confirm('If you remove this only recipient, the ' + cbtype + ' request call back feature will be disabled for this office.\n\nAre you sure you want to remove this recipient?');
			if (confirmResult)
			{
				$("Enable"+ cbtype +"O"+ officeID +"CallBackRequest").checked = false;
				$("Enable"+ cbtype +"O"+ officeID +"CallBackRequest").onclick();
			}
		}
		if (confirmResult)
		{
			var tr = node.parentNode;
			while (tr.tagName.toLowerCase() != "tr")
			tr = tr.parentNode;
			tr.parentNode.removeChild(tr);
			$(cbtype +"O"+ officeID+"_List").value = $(cbtype +"O"+ officeID+"_List").value.replace(lookstring, "");
		}
		dirtyfyTab();
	} 
	
	/* Validation start */

	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);
	}

	var validateEmail = function(address) {
	   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	   if(reg.test(address) == false) {
		  return false;
	   }
	   return true;
	}
	
	var validationEffectMap = {};

	var ValidateField = function (row, field, error, condition, options) {
		// console.log('ValidateField() - Field: ' + field + ', Condition: ' + condition);
		if (!options) options = {};
		if ($(error) || options.preCheck) {
			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") {
				var num = $(field).value;
				validated = validatePositiveNumber(num);
				if (validated) {
					validated = !(options.maxNumber && (Number(num) > options.maxNumber));
					if (validated)
						validated = !(options.isWholeNumber && !(/^\d+$/.match(num)));
				}
			}
			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);
			}
			
			if ($(error)) {
				updateValidatedRow(validated, row);
			}
			else if (options.preCheck) {
				updateValidatedRowPreCheck(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'});
		}
	}

	function updateValidatedRowPreCheck(isValid, row)
	{
		if ($(row))
		{
			if (isValid && !$(row).hasClassName('fielderrorresolved')) {
				$(row).toggleClassName('fielderrorresolved');
			}
			else if (!isValid && $(row).hasClassName('fielderrorresolved')) {
				if (validationEffectMap[row])
					validationEffectMap[row].cancel();
				$(row).toggleClassName('fielderrorresolved');
			}
		}
	}

	/* Validation end */

	var addRecipient = function(cbtype, officeID) {
		var ctlstart = cbtype + (officeID !=null?"O"+officeID:"");
		if ($(ctlstart+"RecipientID").disabled == true)
			return false;
		var IsUserID = ($(ctlstart+"RecipientID").options[$(ctlstart+"RecipientID").selectedIndex].value != "other");
		var lookstring = "";
		if (IsUserID)
		{
			lookstring =  "|L:" +  $(ctlstart+"RecipientID").options[$(ctlstart+"RecipientID").selectedIndex].value + "|";
		} else {
			if ($(ctlstart + "OtherEmail").value == "")
			{
				alert ("Please enter an email address");
				$(ctlstart + "OtherEmail").focus();
				return false;
			}
			if (!validateEmail($(ctlstart + "OtherEmail").value))
			{
			    alert('Please enter a valid email address');
				$(ctlstart + "OtherEmail").focus();
				return false;
			}
			lookstring = "|E:" + $(ctlstart + "OtherEmail").value + "|";
		}
		if ($(ctlstart +"_List").value.indexOf(lookstring)>=0)
		{
			alert ("That recipient has already been added.");
			$(ctlstart + "RecipientID").focus();
			return false;
		}

		var table = $(ctlstart+"CBLIST"); 
		var row = table.insertRow( table.rows.length);  
		var cell1 = row.insertCell(0);
		var element1 = document.createElement("input");  
		element1.type = "hidden";

		var cell2 = row.insertCell(1);
		var element2 = document.createElement("li");
		var cell3 = row.insertCell(2);

		if (!IsUserID) //add a new email
		{
			element1.value = $(ctlstart + "OtherEmail").value;
			$(ctlstart +"_List").value += lookstring;
			element1.name = ctlstart + "RecipientEmail";
			element2.innerHTML = $(ctlstart + "OtherEmail").value;
		} else {
			element1.value = $(ctlstart+"RecipientID").options[$(ctlstart+"RecipientID").selectedIndex].value;
			$(ctlstart +"_List").value += lookstring;
			element1.name = ctlstart + "RecipientLapbandID"
			element2.innerHTML = $(ctlstart+"RecipientID").options[$(ctlstart+"RecipientID").selectedIndex].text;
		}
		if (officeID == null)
			cell3.innerHTML = "<a href='javascript:void(0)' onclick='removeRow(this, \"" + lookstring + "\", \""+ cbtype +"\");return false;' class='"+cbtype+"Link'>[remove]</a>";
		else
			cell3.innerHTML = "<a href='javascript:void(0)' onclick='removeOfficeRow(this, \"" + lookstring + "\", \""+ cbtype +"\", "+officeID+");return false;' class='"+cbtype+"O"+officeID+"Link'>[remove]</a>";
		cell1.appendChild(element1);
		cell2.appendChild(element2);
		dirtyfyTab();
		return false;
	};


	var dirty_tabs = "";
	var currenttab = "";

	
	var greyAllbyClass = function (classname, fade){
		var xx = document.getElementsByClassName(classname);
		for (i=0; i<xx.length; i++){
			greyOne (xx[i], fade);
		}
	}
	var greyOne = function (ctl, fade){
		if (!fade)
		{
			ctl.style.cursor = "pointer";
			ctl.style.color="#548BB4";
		}else{
			ctl.style.cursor="default";
			ctl.style.color="#CCCCCC";
		}
	}



/********************************************************/
/* end callbackwidgets:                                 */
/********************************************************/

var SelectTabAll = function(tabele) {
	var container = $('tabcontainer');
	var tab = $(tabele);
	var tabbtn = $(tabele + 'tab');
	var btns = container.select('.tabbtn');
	var tabs = container.select('.tabcontent');
	
	btns.invoke('removeClassName','selected');
	tabs.invoke('addClassName','hidden');
	
	tab.removeClassName('hidden');
	tabbtn.addClassName('selected');
}

// Sortable Results Table
	
	var SRT_SetSortOrder = function(prefix, newSort) {
		if ($(prefix+'_searchSort').value==newSort+' ASC')
			$(prefix+'_searchSort').value = newSort+' DESC';
		else
			$(prefix+'_searchSort').value = newSort+' ASC';

		SRT_list(prefix, 1);
	}

	function SRT_list(prefix, pageNum)
	{
		var link = window.location.pathname.substring(0,window.location.pathname.indexOf('/manage_seminars/')+17);
		document.body.style.cursor = 'wait';
		//new Ajax.Updater(prefix+'_Result', '~~/_list_registrants/?listtype='+prefix+'&dateID='+$(prefix+'_dateID').value+'&sortBy='+$(prefix+'_searchSort').value+'&pageNum='+pageNum
		var allparams = 'list_seminars/_list_registrants/?listtype='+prefix+'&dateID='+$(prefix+'_dateID').value+'&sortBy='+$(prefix+'_searchSort').value+'&pageNum='+pageNum;
		if ($(prefix+'_return')) //return param not everywhere
		{
			allparams += '&return='+$(prefix+'_return').value;
		}
		new Ajax.Updater(prefix+'_Result', link+allparams, {method:'GET', onSuccess:function(){document.body.style.cursor = '';}});
	}

	var OpenEmails_Attended = function()
	{
		var emails = '';
		  var x=document.getElementsByTagName("input");
		  //alert(x.length);
		  for( var i=0; i<x.length; i++)
		  {
			if (x[i].name.indexOf('email_')==0)
			{
				if (x[i].value != '' && $('attended_yes_'+x[i].name.substring(6)).checked)
				{
					emails = emails + x[i].value + ';';
				}
			}
		  }	
		document.location='mailto:?bcc='+emails;
	};

	var OpenEmails_NotAttended = function()
	{
		var emails = '';
		  var x=document.getElementsByTagName("input");
		  //alert(x.length);
		  for( var i=0; i<x.length; i++)
		  {
			if (x[i].name.indexOf('email_')==0)
			{
				if (x[i].value != '' && $('attended_no_'+x[i].name.substring(6)).checked)
				{
					emails = emails + x[i].value + ';';
				}
			}
		  }	
		document.location='mailto:?bcc='+emails;
	};

	var setupCalendarButton = function(inpID,btnID)
	{
		Calendar.setup(
			{
				inputField : inpID, // ID of the input field
				ifFormat : "%b %e, %Y", // the date format
				button : btnID // ID of the button
			}
		);
	};

	var getSelectDates = function(semID)
	{
		var link = window.location.pathname.substring(0,window.location.pathname.indexOf('/manage_seminars/')+17);
		document.body.style.cursor = 'wait';
		new Ajax.Updater('semDateTimeHold', link+'list_seminars/_select_dates/'+semID+'?sdID='+$('sdID').value
				, {method:'GET', onSuccess:function(){document.body.style.cursor = '';}});
	}
	
	var msgRegistrantDownload = function()
	{
		alert('Please note that seminar registrants are only opted-in to receive email and/or phone communications from the practice in relation to the seminar that they have registered for. If you would like to contact these individuals for reasons outside of this purpose you will need to receive their permission to do so.');
	}


