//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);

document.observe("dom:loaded",function() {
	
	//adds on click event to tabs
	$$('li.buttontab').each(function(el,index){
		Event.observe(el,'click',function(ev) {
			hidealltabs(el.up('.tabs'));
			var bclass = '.content' + el.className.substr(el.className.indexOf(' ') + 8);
			var sclass = bclass.indexOf(' ');
			if (sclass > -1) bclass = bclass.substr(0,sclass);
			el.up('.fulltabcontent').down(bclass).show();
			el.addClassName('selected');
			Event.stop(ev);
		})
	});
	
	//adds event onclick to text fields to delete initial value
	$$('input.textfield').each(function(el,index){
		Event.observe(el,'focus',function(ev) {
			if (el.value.indexOf('Enter ') > -1 || el.value.indexOf('ZIP') > -1) {
				el.value = '';
			}
		})
	});
	
	//toggle button
	if ($('showmoreoptions')) {
		$('showmoreoptions').observe('click',function(ev) {
			el = this;
			if(el.hasClassName('off')) {
				el.removeClassName('off');
				el.addClassName('on');
				el.innerHTML = 'Hide search options';
				el.up('.toggleoptions').down('.togglebox').style.display = '';
			}
			else{
				el.removeClassName('on');
				el.addClassName('off');
				el.innerHTML = 'Show more search options';
				el.up('.toggleoptions').down('.togglebox').style.display = 'none';
			}
			Event.stop(ev);
		});
	}

	//set font size
	if (location.href.indexOf("/home/") == -1) {
		var maincontent = $('content');
		//maincontent.style.fontSize = '100%';
		//Cookie.set('userFontSize','150',100);
		var cookieValue = Cookie.get('userFontSize');
		maincontent.style.fontSize = (cookieValue != null ? maincontent.style.fontSize = cookieValue + '%' : "110%");
		maincontent.removeClassName('hidden');
	}
	if($('navfontsmall')){
		$('navfontsmall').observe('click',decreasefontsize);
		$('navfontbig').observe('click',increasefontsize);
	}
	
	if($('listresults')) {
		$('listresults').observe('click',function(ev){
			$('calnav').addClassName('hidden');
			$('customsearch-calendar').addClassName('hidden');
			$('listnav').removeClassName('hidden');
			$('customsearch-list').removeClassName('hidden');
			$$('div.customsearch-navpages').invoke('removeClassName','hidden');
			Event.stop(ev);
		});
	}
	if($('calresults')) {
		$('calresults').observe('click',function(ev){
			$('calnav').removeClassName('hidden');
			$('customsearch-calendar').removeClassName('hidden');
			$('listnav').addClassName('hidden');
			$('customsearch-list').addClassName('hidden');
			$$('div.customsearch-navpages').invoke('addClassName','hidden');
			Event.stop(ev);
		});
	}

	if ($('mylapbanklink_tabs')) {
		if($('tabrpending')) {
			$('tabrpending').observe('click',function(ev){
				$('tabcontrd').addClassName('hidden');
				$('rdeclined').addClassName('hidden');
				$('tabcontrp').removeClassName('hidden');
				$('rpending').removeClassName('hidden');
				Event.stop(ev);
			});
		}
		if($('tabrdeclined')){
			$('tabrdeclined').observe('click',function(ev){
				$('tabcontrp').addClassName('hidden');
				$('rpending').addClassName('hidden');
				$('tabcontrd').removeClassName('hidden');
				$('rdeclined').removeClassName('hidden');
				Event.stop(ev);
			});
		}
		if($('tabspending')){
			$('tabspending').observe('click',function(ev){
				$('tabcontsd').addClassName('hidden');
				$('sdeclined').addClassName('hidden');
				$('tabcontsp').removeClassName('hidden');
				$('spending').removeClassName('hidden');
				Event.stop(ev);
			});
		}
		if($('tabsdeclined')){
			$('tabsdeclined').observe('click',function(ev){
				$('tabcontsp').addClassName('hidden');
				$('spending').addClassName('hidden');
				$('tabcontsd').removeClassName('hidden');
				$('sdeclined').removeClassName('hidden');
				Event.stop(ev);
			});
		}
	}

	if($('layout')){	
		$('layout').select('a[target="_blank"]').invoke('observe','click',function(ev){
			if(this.href.indexOf(window.location.hostname) == -1){
				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 proceedbtn = new Element('button',{'class':'button','onclick':'openLink("'+this.href+'","")'}).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'});
			}
		})
	}

	if ($("HeightFeet")) {
		$$('input.numeric').invoke('observe','keypress',function(ev){
			if (ev.keyCode != 9 && ev.keyCode != 8 && ( ev.charCode < 48 || ev.charCode > 57)) Event.stop(ev);
		});
	}

	$$("div.secondarynav a", "li.buttontab a").each(function(e){  
		Event.observe(e, 'mouseover', function() {  
			e.up().addClassName('hover');  
		});  
		Event.observe(e, 'mouseout', function() {  
			e.up().removeClassName('hover');  
		});  
	});  

	//hide right side registration widget if on surgeon search page but not results page
	var cpage = location.href;
	if(cpage.indexOf('/find_') > -1 && cpage.indexOf('/searchresults/') <= 0){
		var regelem = $('leftbar').down('.regwidget');
		if(regelem) {
			regelem.addClassName('hidden');
		}
	}

});

var showPoPupTab = function(ele, ebody){
	el = $(ele).up('li');
	hidealltabsPopup(el.up("ul"));
	el.up("ul").up('.fulltabcontent').select(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').select('.contenttab').invoke('addClassName','hidden');//bodies
};

var hidealltabs = function(container) {
	//hide tabs
	container.up('.fulltabcontent').select('.contenttab').invoke('hide');//bodies
	container.select('.selected').invoke('removeClassName','selected');//tabs
};

var increasefontsize = function() {
	var maincontent = $('content');
	if (maincontent.style.fontSize == '')
		maincontent.style.fontSize = '100%';
	var currrentpercentage = eval(maincontent.style.fontSize.replace('%',''));
	if (currrentpercentage < 130) {
		currrentpercentage = currrentpercentage + 10
		maincontent.style.fontSize = currrentpercentage + '%';
		Cookie.set('userFontSize',currrentpercentage,240)
	}
}

var decreasefontsize = function() {
	var maincontent = $('content');
	var currrentpercentage = eval(maincontent.style.fontSize.replace('%',''));
	if (currrentpercentage > 100) {
		currrentpercentage = currrentpercentage - 10
		maincontent.style.fontSize = currrentpercentage + '%';
		Cookie.set('userFontSize',currrentpercentage,240)
	}
}

// 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.quickClose();//close if open	
		var hasMask, maskStyle;
		if (options){
			hasMask = options.hasMask;
		}		
		maskStyle = (hasMask) ? "modalDark" : "modalLight";
		var modalcontainer = $("modalcontainer");
		var modalmask = $("modalmask")
		if (modalcontainer && modalmask)
		{
			if (modalcontainer.hasClassName("hidden")) modalcontainer.removeClassName("hidden");		
			modalcontainer.setStyle({top : "0", left: "0"})
			var pageDimensions = xDocSize();
			modalmask.className = "modalmask";
			modalmask.addClassName(maskStyle);
			
			var maskie6 = 0;
			if (typeof document.body.style.maxHeight == "undefined") //is ie6
				maskie6 = 22;
			
			modalmask.setStyle ({ 	
				height : pageDimensions["h"] + "px",
				width : (pageDimensions["w"] - maskie6) + "px"
			})
		}
	},
	close : function() {
		var modalcontainer = $("modalcontainer");
		if (!modalcontainer.hasClassName("hidden")) modalcontainer.addClassName("hidden");
		if (String(typeof(window.onModalClose)) == 'function') {
			window.onModalClose();
		}
	},
	quickClose : function() {
		var modalcontainer = $("modalcontainer");
		if (!modalcontainer.hasClassName("hidden")) modalcontainer.addClassName("hidden");
	},
	resizeHandler : function(){
		var modalcontainer = $("modalcontainer");
		if (modalcontainer && !modalcontainer.hasClassName("hidden")){
			Modal.close();
			Modal.openMask();
		}
	},
	open :function(options){		
		$("modalcontent").innerHTML ="<img src='"+ fullsiteroot() +"local/images/loading.gif' />";
		var width, url, contentEl, hasMask;
		var modalbody = $("modalbody");
		if (options){
			width = options.width || 400;
			url = options.url || "";	
			contentEl = options.contentEl || "";			
			hasMask = options.hasMask;
			extraClassName = 'alertbox';
		}

		//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"
		});	
		// switch for 2 diff classes on modal box
		if (contentEl.match(/ref/)) $('modalcontainer').removeClassName(extraClassName)
		else $('modalcontainer').addClassName(extraClassName);
		
		if (url != ""){
			new Ajax.Updater("modalcontent",options.url,{evalScripts:true})	
		} 
		else if (contentEl != ""){
			$("modalcontent").innerHTML = '';
			$("modalcontent").insert($(contentEl).innerHTML.replace(/PopupOD/g, "ModalOD"));
			if (contentEl.match(/ref/)) {
				$('modalcontent').select('a[target="_blank"]').invoke('observe','click',function(ev){
					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 proceedbtn = new Element('button',{'class':'button','onclick':'openLink("'+this.href+'","")'}).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'});
				})
			}
			/*
			$("modalcontent").innerHTML = $(contentEl).innerHTML;
			//insanely crappy hack, to appease IE6 and it's refusal to re-render <img>s*/
			setTimeout(function(){
				$("modalcloser").innerHTML = $("modalcloser").innerHTML
			}, 50);
			
			
		}
		if (contentEl.match(/ref/)) $("modalmask").style.display = 'none';
	}
}
Event.observe (window,"resize",Modal.resizeHandler);
Event.observe(window,"load",function(){									 
	if ($("modalcloser"))Event.observe ("modalcloser","click",Modal.close);
})

// external site link
function confirmExit(theLocation, theMessage) {
	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 proceedbtn = new Element('button',{'class':'button','onclick':'openLink("'+theLocation+'","")'}).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'});
}

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 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 checkBMI = function() {
	var inches = 0;
	if (document.getElementById("HeightInches").value != '' && document.getElementById("HeightInches").value != '.')
	{
		inches = parseInt(document.getElementById("HeightInches").value);
	}
	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 classif = ""
	if (isNaN(BMI) || feet == 0 || weight==0 || BMI==0)
	{
		$("bmialert").innerHTML = "Please enter valid values for height and weight.";
		$("BMI").addClassName("hidden");
	}else{
		if(BMI < 18.5) classif = "Underweight";
		else if(BMI < 25) classif = "Normal weight";
		else if(BMI < 30) classif = "Overweight";
		else if(BMI < 35) classif = "Obese (Class I)";
		else if(BMI < 40) classif = "Obese (Class II)";
		else classif = "Severely Obese (Class III)";

		$("BMI").innerHTML  = "Your patient's BMI is <input type='text' class='text resultbmi' onFocus='this.blur()' value='" + StrBMI + "' /> and is classified as <input type='text' class='text resultclassif' onFocus='this.blur()' value='" + classif + "' />"
		$("BMI").removeClassName("hidden");
		if(BMI < 25) {
			$("bmialert").innerHTML = "Based on this BMI, your patient is not eligible for bariatric surgery."
		} else if(BMI < 35) {
			$("bmialert").innerHTML = "Based on this BMI, your patient might not be eligible for bariatric surgery. Please see <a href='" + siteroot + "en/bariatric_surgery/nonsurgical_options/'>Non-Surgical Treatment Options</a>."
		} else if(BMI < 40) {
			$("bmialert").innerHTML = "Based on this BMI, <a href='" + siteroot + "en/bariatric_practice/finding/'>your patient may be eligible for bariatric surgery</a> if they have an obesity-related comorbidity."
		} else {
			$("bmialert").innerHTML = "Based on this BMI, <a href='" + siteroot + "en/bariatric_practice/finding/'>your patient may be eligible for bariatric surgery</a>."
		}
	}
	$("bmialert").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/sign_in/register/";
}

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 flashRef = function(refno) {
	Modal.open({contentEl: refno})
}

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 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;
}

	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);
			}
		}
	}
 
}

// 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 gotosite = function(url) {
	window.open(url, "");
	Modal.close();
}

var openLink = function(href){
	Modal.close();
	window.open(href,'');
}

var playTutorial = function(file) {
	Modal.open({contentEl: '',width:800});
	$('modalcontent').update('<div id="tutorial"></div>');
	var filepath = siteroot + "local/flash/tutorials/" + file;
	var targetdiv = "tutorial";
	var flashvars = {autoplay:"true"};
	var params = {allowScriptAccess:"always",wmode:"transparent"};
	var attributes = {};
	swfobject.embedSWF(filepath,targetdiv,"755", "502", "8","expressInstall.swf", flashvars, params, attributes);
	$('modalcloser').observe('click',function(ev){
		Modal.close();
		$('modalcontent').update('');
		if($('listtutorial')) $('listtutorial').hide();
	});
}

var showTutorialList = function() {
	var loc = location.href;
	var newcontent = '';
	if($('listtutorial')){
		var list = $('listtutorial');
		if ($('listtutorial').visible()) Effect.BlindUp('listtutorial');
		else Effect.BlindDown('listtutorial');
	}else{
		if(loc.indexOf('find_a_surgeon/detail') > -1)
			newcontent = '<ul><li><a href="javascript:void(0)" onclick="playTutorial(\'h6_755x502.swf\')">Request Call back to Surgeon</a></li><li><a href="javascript:void(0)" onclick="playTutorial(\'h7_755x502.swf\')">Surgeon connections on the patient care network</a></li></ul>';
		if(loc.indexOf('/dashboard/profile/') > -1) 
			newcontent = '<ul><li><a href="javascript:void(0)" onclick="playTutorial(\'h8_755x502.swf\')">Edit Personal Profile</a></li><li><a href="javascript:void(0)" onclick="playTutorial(\'h9_755x502.swf\')">Hospital affiliations</a></li><li><a href="javascript:void(0)" onclick="playTutorial(\'h10_755x502.swf\')">Site Preferences</a></li></ul>';
		
		var newdiv = new Element('div', { 'class': 'listtutorial', 'id' : 'listtutorial', 'style':'display:none'});
		newdiv.update(newcontent);
		$('content').insert(newdiv);
		$('listtutorial').addClassName('listtutorial'); //ie8 was not adding this class when using new element
		Effect.BlindDown('listtutorial');
	}
}