if (!window.Modalbox) var Modalbox = new Object();
Modalbox.Methods = {
	overrideAlert: false,
	focusableElements: new Array,
	options: {
		title: "ModalBox Window",
		overlayClose: true,
		width: 500,
		height: 90,
		overlayOpacity: .75,
		overlayDuration: .25,
		slideDownDuration: .5,
		slideUpDuration: .15,
		resizeDuration: .2,
		inactiveFade: true,
		transitions: true,
		loadingString: "Please wait. Loading...",
		closeString: "Close window",
		params: {},
		method: 'get'
	},
	_options: new Object,
	
	setOptions: function(options) {
		Object.extend(this.options, options || {});
	},
	
	_init: function(options) {
		
		Object.extend(this._options, this.options);
		this.setOptions(options);
		
		this.MBoverlay = Builder.node("div", { id: "MB_overlay", opacity: "0" });
		
		this.MBwindow = Builder.node("div", {id: "MB_window", style: "display: none"}, [
			this.MBframe = Builder.node("div", {id: "MB_frame"}, [
				this.MBheader = Builder.node("div", {id: "MB_header"}, [
					this.MBcaption = Builder.node("div", {id: "MB_caption"}),
					this.MBclose = Builder.node("a", {id: "MB_close", title: this.options.closeString, href: "#"}, [
						Builder.build("<span>&times;</span>"),
					]),
				]),
				this.MBcontent = Builder.node("div", {id: "MB_content"}, [
					this.MBloading = Builder.node("div", {id: "MB_loading"}, this.options.loadingString),
				]),
			]),
		]);
		
		document.body.insertBefore(this.MBwindow, document.body.childNodes[0]);
		document.body.insertBefore(this.MBoverlay, document.body.childNodes[0]);
		this.initScrollX = window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft;
		this.initScrollY = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		this.hide = this.hide.bindAsEventListener(this);
		this.close = this._hide.bindAsEventListener(this);
		this.kbdHandler = this.kbdHandler.bindAsEventListener(this);
		this._initObservers();

		this.initialized = true;
		this.active = true;
		this.currFocused = 0;
	},
	show: function(content, options) {
		if(!this.initialized) this._init(options);
		this.content = content;
		this.setOptions(options);
		Element.update(this.MBcaption, this.options.title);
		if(this.MBwindow.style.display == "none") {
			this._appear();
			this.event("onShow");
		}
		else {
			this._update();
			this.event("onUpdate");
		}
	},
	
	hide: function(options) {
		if(this.initialized) {
			if(options) Object.extend(this.options, options);
			if(this.options.transitions)
				Effect.SlideUp(this.MBwindow, { duration: this.options.slideUpDuration, afterFinish: this._deinit.bind(this) } );
			else {
				Element.hide(this.MBwindow);
				this._deinit();
			}
		} else throw("Modalbox isn't initialized");
	},
	
	alert: function(message){
		var html = '<div class="MB_alert"><p>' + message + '</p><input type="button" onclick="Modalbox.hide()" value="OK" /></div>';
		Modalbox.show(html, {title: 'Alert: ' + document.title, width: 300});
	},
		
	_hide: function(event) {
		if(event) Event.stop(event);
		this.hide();
	},
	
	_appear: function() {
		if (navigator.appVersion.match(/\bMSIE\b/))
			this._toggleSelects();
		this._setOverlay();
		this._setWidth();
		this._setPosition();
		if(this.options.transitions) {
			Element.setStyle(this.MBoverlay, {opacity: 0});
			new Effect.Fade(this.MBoverlay, {
					from: 0,
					to: this.options.overlayOpacity,
					duration: this.options.overlayDuration,
					afterFinish: function() {
						new Effect.SlideDown(this.MBwindow, {
							duration: this.options.slideDownDuration,
							afterFinish: function(){
								this._setPosition();
								this.loadContent();
							}.bind(this)
						});
					}.bind(this)
			});
		} else {
			Element.setStyle(this.MBoverlay, {opacity: this.options.overlayOpacity});
			Element.show(this.MBwindow);
			this._setPosition();
			this.loadContent();
		}
		this._setWidthAndPosition = this._setWidthAndPosition.bindAsEventListener(this);
		Event.observe(window, "resize", this._setWidthAndPosition);
	},
	
	resize: function(byWidth, byHeight, options) {
		var wHeight = Element.getHeight(this.MBwindow);
		var wWidth = Element.getWidth(this.MBwindow);
		var hHeight = Element.getHeight(this.MBheader);
		var cHeight = Element.getHeight(this.MBcontent);
		var newHeight = ((wHeight - hHeight + byHeight) < cHeight) ? (cHeight + hHeight - wHeight) : byHeight;
		this.setOptions(options);
		if(this.options.transitions) {
			new Effect.ScaleBy(this.MBwindow, byWidth, newHeight, {
					duration: this.options.resizeDuration,
				  	afterFinish: function() {
						this.event("_afterResize");
						this.event("afterResize");
					}.bind(this)
				});
		} else {
			this.MBwindow.setStyle({width: wWidth + byWidth + "px", height: wHeight + newHeight + "px"});
			setTimeout(function() {
				this.event("_afterResize");
				this.event("afterResize");
			}.bind(this), 1);
			
		}
		
	},
	
	_update: function() {
		Element.update(this.MBcontent, "");
		this.MBcontent.appendChild(this.MBloading);
		Element.update(this.MBloading, this.options.loadingString);
		this.currentDims = [this.MBwindow.offsetWidth, this.MBwindow.offsetHeight];
		Modalbox.resize((this.options.width - this.currentDims[0]), (this.options.height - this.currentDims[1]), {_afterResize: this._loadAfterResize.bind(this) });
	},
	
	loadContent: function () {
		if(this.event("beforeLoad") != false) {
			if(typeof this.content == 'string') {
				
				var htmlRegExp = new RegExp(/<\/?[^>]+>/gi);
				if(htmlRegExp.test(this.content)) {
					this._insertContent(this.content);
					this._putContent();
				} else
					new Ajax.Request( this.content, { method: this.options.method.toLowerCase(), parameters: this.options.params,
						onComplete: function(transport) {
							var response = new String(transport.responseText);
							this._insertContent(transport.responseText.stripScripts());
							response.extractScripts().map(function(script) {
								return eval(script.replace("<!--", "").replace("// -->", ""));
							}.bind(window));
							this._putContent();
						}.bind(this)
					});
					
			} else if (typeof this.content == 'object') {
				this._insertContent(this.content);
				this._putContent();
			} else {
				Modalbox.hide();
				throw('Please specify correct URL or HTML element (plain HTML or object)');
			}
		}
	},
	
	_insertContent: function(content){
		Element.extend(this.MBcontent);
		this.MBcontent.update("");
		if(typeof content == 'string')
			this.MBcontent.hide().update(content);
		else if (typeof this.content == 'object') {
			var _htmlObj = content.cloneNode(true);
			
			if(this.content.id) this.content.id = "MB_" + this.content.id;
			/* Add prefix for IDs on all elements inside the DOM node */
			this.content.getElementsBySelector('*[id]').each(function(el){ el.id = "MB_" + el.id });
			this.MBcontent.hide().appendChild(_htmlObj);
			this.MBcontent.down().show();
		}
	},
	
	_putContent: function(){
		
		if(this.options.height == this._options.height)
			Modalbox.resize(0, this.MBcontent.getHeight() - Element.getHeight(this.MBwindow) + Element.getHeight(this.MBheader), {
				afterResize: function(){
					this.MBcontent.show();
					this.focusableElements = this._findFocusableElements();
					this._setFocus();
					this.event("afterLoad");
				}.bind(this)
			});
		else {
			this._setWidth();
			this.MBcontent.setStyle({overflow: 'hidden', height: Element.getHeight(this.MBwindow) - Element.getHeight(this.MBheader) - 13 + 'px'});
			this.MBcontent.show();
			this.focusableElements = this._findFocusableElements();
			this._setFocus();
			this.event("afterLoad");
		}
	},
	
	activate: function(options){
		this.setOptions(options);
		this.active = true;
		Event.observe(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
		Element.show(this.MBclose);
		if(this.options.transitions && this.options.inactiveFade) new Effect.Appear(this.MBwindow, {duration: this.options.slideUpDuration});
	},
	
	deactivate: function(options) {
		this.setOptions(options);
		this.active = false;
		Event.stopObserving(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
		Element.hide(this.MBclose);
		if(this.options.transitions && this.options.inactiveFade) new Effect.Fade(this.MBwindow, {duration: this.options.slideUpDuration, to: .75});
	},
	
	_initObservers: function(){
		Event.observe(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.observe(this.MBoverlay, "click", this.hide);
		Event.observe(document, "keypress", Modalbox.kbdHandler );
	},
	
	_removeObservers: function(){
		Event.stopObserving(this.MBclose, "click", this.close);
		if(this.options.overlayClose) Event.stopObserving(this.MBoverlay, "click", this.hide);
		Event.stopObserving(document, "keypress", Modalbox.kbdHandler );
	},
	
	_loadAfterResize: function() {
		this._setWidth();
		this._setPosition();
		this.loadContent();
	},
	
	_setFocus: function() {
		if(this.focusableElements.length > 0) {
			var i = 0;
			var firstEl = this.focusableElements.find(function findFirst(el){
				i++;
				return el.tabIndex == 1;
			}) || this.focusableElements.first();
			this.currFocused = (i == this.focusableElements.length - 1) ? (i-1) : 0;
			firstEl.focus();
		} else
			$("MB_close").focus();
	},
	
	_findFocusableElements: function(){
		var els = this.MBcontent.getElementsBySelector('input:not([type~=hidden]), select, textarea, button, a[href]');
		els.invoke('addClassName', 'MB_focusable');
		return this.MBcontent.getElementsByClassName('MB_focusable');
	},
	kbdHandler: function(e) {
		var node = Event.element(e);
		switch(e.keyCode) {
			case Event.KEY_TAB:
				Event.stop(e);
				if(!e.shiftKey) {
					if(this.currFocused == this.focusableElements.length - 1) {
						this.focusableElements.first().focus();
						this.currFocused = 0;
					} else {
						this.currFocused++;
						this.focusableElements[this.currFocused].focus();
					}
				} else {
					if(this.currFocused == 0) {
						this.focusableElements.last().focus();
						this.currFocused = this.focusableElements.length - 1;
					} else {
						this.currFocused--;
						this.focusableElements[this.currFocused].focus();
					}
				}
				break;			
			case Event.KEY_ESC:
				if(this.active) this._hide(e);
				break;
			case 32:
				this._preventScroll(e);
				break;
			case 0:
				if(e.which == 32) this._preventScroll(e);
				break;
			case Event.KEY_UP:
			case Event.KEY_DOWN:
			case Event.KEY_PAGEDOWN:
			case Event.KEY_PAGEUP:
			case Event.KEY_HOME:
			case Event.KEY_END:
				
				if(/Safari|KHTML/.test(navigator.userAgent) && !["textarea", "select"].include(node.tagName.toLowerCase()))
					Event.stop(e);
				else if( (node.tagName.toLowerCase() == "input" && ["submit", "button"].include(node.type)) || (node.tagName.toLowerCase() == "a") )
					Event.stop(e);
				break;
		}
	},
	
	_preventScroll: function(event) {
		if(!["input", "textarea", "select", "button"].include(Event.element(event).tagName.toLowerCase()))
			Event.stop(event);
	},
	
	_deinit: function()
	{	
		this._removeObservers();
		Event.stopObserving(window, "resize", this._setWidthAndPosition );
		if(this.options.transitions) {
			Effect.toggle(this.MBoverlay, 'appear', {duration: this.options.overlayDuration, afterFinish: this._removeElements.bind(this) });
		} else {
			this.MBoverlay.hide();
			this._removeElements();
		}
		Element.setStyle(this.MBcontent, {overflow: '', height: ''});
	},
	
	_removeElements: function () {
		if (navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("", "");
			window.scrollTo(this.initScrollX, this.initScrollY);
		}
		Element.remove(this.MBoverlay);
		Element.remove(this.MBwindow);
		
		/* Replacing prefixes 'MB_' in IDs for the original content */
		if(typeof this.content == 'object' && this.content.id && this.content.id.match(/MB_/)) {
			this.content.getElementsBySelector('*[id]').each(function(el){ el.id = el.id.replace(/MB_/, ""); });
			this.content.id = this.content.id.replace(/MB_/, "");
		}
		/* Initialized will be set to false */
		this.initialized = false;
		
		if (navigator.appVersion.match(/\bMSIE\b/))
			this._toggleSelects();
		this.event("afterHide");
		this.setOptions(this._options);
	},
	
	_setOverlay: function () {
		if (navigator.appVersion.match(/\bMSIE\b/)) {
			this._prepareIE("100%", "hidden");
			if (!navigator.appVersion.match(/\b7.0\b/)) window.scrollTo(0,0);
		}
	},
	
	_setWidth: function () {
		Element.setStyle(this.MBwindow, {width: this.options.width + "px", height: this.options.height + "px"});
	},
	
	_setPosition: function () {
		Element.setStyle(this.MBwindow, {left: Math.round((Element.getWidth(document.body) - Element.getWidth(this.MBwindow)) / 2 ) + "px"});
	},
	
	_setWidthAndPosition: function () {
		Element.setStyle(this.MBwindow, {width: this.options.width + "px"});
		this._setPosition();
	},
	
	_getScrollTop: function () {
		var theTop;
		if (document.documentElement && document.documentElement.scrollTop)
			theTop = document.documentElement.scrollTop;
		else if (document.body)
			theTop = document.body.scrollTop;
		return theTop;
	},
	
	_prepareIE: function(height, overflow){
		var body = document.getElementsByTagName('body')[0];
		body.style.height = height;
		body.style.overflow = overflow;
 
		var html = document.getElementsByTagName('html')[0];
		html.style.height = height;
		html.style.overflow = overflow;
	},
	
	_toggleSelects: function() {
		var selects = $$("select");
		if(this.initialized) {
			selects.invoke('setStyle', {'visibility': 'hidden'});
		} else {
			selects.invoke('setStyle', {'visibility': ''});
		}
			
	},
	event: function(eventName) {
		if(this.options[eventName]) {
			var returnValue = this.options[eventName]();
			this.options[eventName] = null;
			if(returnValue != undefined)
				return returnValue;
			else
				return true;
		}
		return true;
	}
}

Object.extend(Modalbox, Modalbox.Methods);

if(Modalbox.overrideAlert) window.alert = Modalbox.alert;

Effect.ScaleBy = Class.create();
Object.extend(Object.extend(Effect.ScaleBy.prototype, Effect.Base.prototype), {
  initialize: function(element, byWidth, byHeight, options) {
    this.element = $(element)
    var options = Object.extend({
	  scaleFromTop: true,
      scaleMode: 'box',       
      scaleByWidth: byWidth,
	  scaleByHeight: byHeight
    }, arguments[3] || {});
    this.start(options);
  },
  setup: function() {
    this.elementPositioning = this.element.getStyle('position');
     
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
	
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
	 if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
	 
	this.deltaY = this.options.scaleByHeight;
	this.deltaX = this.options.scaleByWidth;
  },
  update: function(position) {
    var currentHeight = this.dims[0] + (this.deltaY * position);
	var currentWidth = this.dims[1] + (this.deltaX * position);
	
	currentHeight = (currentHeight > 0) ? currentHeight : 0;
	currentWidth = (currentWidth > 0) ? currentWidth : 0;
	
    this.setDimensions(currentHeight, currentWidth);
  },

  setDimensions: function(height, width) {
    var d = {};
    d.width = width + 'px';
    d.height = height + 'px';
   
	var topd  = Math.round((height - this.dims[0])/2);
	var leftd = Math.round((width  - this.dims[1])/2);
	if(this.elementPositioning == 'absolute' || this.elementPositioning == 'fixed') {
		if(!this.options.scaleFromTop) d.top = this.originalTop-topd + 'px';
		d.left = this.originalLeft-leftd + 'px';
	} else {
		if(!this.options.scaleFromTop) d.top = -topd + 'px';
		d.left = -leftd + 'px';
	}
    this.element.setStyle(d);
  }
});
function check_email(e) {
ok = "1234567890qwertyuiop[]asdfghjklzxcvbnm.@-_QWERTYUIOPASDFGHJKLZXCVBNM";
for(i=0; i < e.length ;i++){
if(ok.indexOf(e.charAt(i))<0){
return (false);
}
}
if (document.images) {
re = /(@.*@)|(\.\.)|(^\.)|(^@)|(@$)|(\.$)|(@\.)/;
re_two = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (!e.match(re) && e.match(re_two)) {
return (-1);		
}
}
}

function ajaxpage(url, sendto, parameters) {
	if (window.XMLHttpRequest) {
		var http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) http_request.overrideMimeType('text/html');
	} else if (window.ActiveXObject) {
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	http_request.onreadystatechange = function() {
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {
				var check=http_request.responseText;
				window[sendto](http_request.responseText);
			}
		}
	}
	http_request.open('POST', url, true);
	http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http_request.setRequestHeader("Content-length", parameters.length);
	http_request.setRequestHeader("Connection", "close");
	http_request.send(parameters);
}
function checkloginform() {
	email=encodeURI(document.forms['lform'].email.value);
	pw=encodeURI(document.forms['lform'].pw.value);
	if (document.forms['lform'].pw.value.length>4){
		if (check_email(document.forms['lform'].email.value)) {
			document.getElementById('loginbut').innerHTML='Logging in...';
			document.forms['lform'].email.disabled = true;
			document.forms['lform'].pw.disabled = true;
			ajaxpage('/shared/checklogin.php','dologin','email='+email+'&pw='+pw);
		}
		else alert('Please enter a valid e-mail address.');
	}
	else alert('Please enter a valid password.');
}
function dologin(response) {
	if (response!='true') {
		alert('Invalid e-mail/password combination.');
		document.forms['lform'].email.disabled = false;
		document.forms['lform'].pw.disabled = false;
		document.getElementById('loginbut').innerHTML='<a href="#" onclick="checkloginform();" class="button">Log In</a>';
	}
	else parent.location.href='/members/';
}
function checksignupform() {
	document.getElementById('submitbutton').innerHTML='Loading...';
	var email=encodeURI(document.forms['mform'].email.value);
	var pw1=document.forms['mform'].pw1.value;
	var phone=document.forms['mform'].phone.value;
	var fullname=document.forms['mform'].fullname.value;
	var specialty=document.forms['mform'].specialty.value;
	
	if (fullname=='') alert('Please enter your full name.');
	else if (phone.length<7) alert('Please enter your phone number.');
	else if (!check_email(email)) alert('Please enter a valid e-mail address.');
	else if (pw1.length<5) alert('The password must be at least 5 characters in length.');
	else if (pw1!=document.forms['mform'].pw2.value) alert('The two passwords must be the same.');
	else if (specialty=='') specialty='Unknown-Physician-Specialty';
	else ajaxpage('/shared/savemembership.php', 'dosignup', 'email='+email+'&fullname='+fullname+'&pw1='+pw1+'&specialty='+specialty+'&phone='+phone+'&getid='+document.forms['mform'].getid.value);
	document.getElementById('submitbutton').innerHTML='<img src="/shared/images/btn_subscribeCC_LG.gif" alt="Secure Payments by PayPal" title="Secure Payments by PayPal" style="cursor: pointer; cursor: hand;" onclick="checksignupform();" />';
}
function dosignup(response) {
	if (isNaN(response)) {
		alert(response);
		document.getElementById('submitbutton').innerHTML='<img src="/shared/images/btn_subscribeCC_LG.gif" alt="Secure Payments by PayPal" title="Secure Payments by PayPal" style="cursor: pointer; cursor: hand;" onclick="checksignupform();" />';
	}
	else {
		document.forms['mform'].custom.value=response;
		document.forms['mform'].submit();
	}
}
function savedata(params) {
	ajaxpage('/members/profile/save/', 'saveddata', params);
}
function saveddata(response) {
	if (response=='true') {
		this.location.reload(true);
	}
	else alert('There was an error saving your settings.');
}
function addtolist(item,obj) {
	document.getElementById('added').innerHTML=document.getElementById('added').innerHTML.replace('No insurace provider/plan selected','');
	document.forms['sform'].addedhidden.value+=','+item;
	var html=document.getElementById('added').innerHTML;
	if (html=='None selected') html='';
	document.getElementById('added').innerHTML='';
	var oList = document.getElementById('added');
	var oImg = document.createElement('img');
	var oSpan = document.createElement('span');
	var oDiv = document.createElement('div');
	if (obj=='lang') oDiv.className='lang';
	oImg.src='/shared/images/delete.png';
	var oText = document.createTextNode(item);
	oImg.setAttribute('onclick', 'removefromlist(\''+item+'\',\''+obj+'\');');
	oDiv.appendChild(oSpan);
	oSpan.appendChild(oImg);
	oSpan.appendChild(oText);
	oList.appendChild(oDiv);
	document.getElementById('added').innerHTML+=html;
}
function removefromlist(item,obj) {
	var newvalue=document.forms['sform'].addedhidden.value;
	document.forms['sform'].addedhidden.value='';
	document.getElementById('added').innerHTML='';
	valuearr=newvalue.split(',');
	for (var i=0; i<valuearr.length; i++) {
		if (valuearr[i]!='' && valuearr[i]!=item) addtolist(valuearr[i],obj);
	}
	if (document.forms['sform'].addedhidden=='') document.getElementById('added').innerHTML='None selected';
}
function doneupdate(response) {
  document.forms['sform'].plan.options.length = 0;
  var option = new Option('Select one...', '');
  document.forms['sform'].plan.options[0]=option;
	var responsearr=response.split(',');
	for (var i=0; i<responsearr.length; i++) {
		if (responsearr[i]!='') {
			var plan=responsearr[i].split(': ');
			var option = new Option(plan[1], responsearr[i]);
			document.forms['sform'].plan.options[i+1]=option;
		}
	}
}
function mapThis(){
	document.getElementById('admap').innerHTML='<img src="http://maps.google.com/maps/api/staticmap?size=200x220&markers=color:red|label:dot|'+escape(document.forms['sform'].address.value+', '+document.forms['sform'].city.value+', '+document.getElementById('statedrop').options[document.getElementById('statedrop').selectedIndex].value)+'&maptype=roadmap&sensor=false&key=ABQIAAAAHhcKgnLK5P9mBpDcYTmdZBShjl9o_xmFm8AtZgtcxzzrEG8QVhSqLhqOSmGz-Br8OTgwnxan2TCKYA" />';
}
Array.prototype.unique =
function() {
  var a = [];
  var l = this.length;
  for(var i=0; i<l; i++) {
    for(var j=i+1; j<l; j++) {
      if (this[i] === this[j])
        j = ++i;
    }
    a.push(this[i]);
  }
  return a;
};
function sentpw(response) {
	if (response=='true') {
		alert('Your account information has been e-mailed to '+document.getElementById('email').value);
		this.location.reload(true);
	}
	else {
		alert(response);
		document.getElementById('spw').innerHTML='Submit';
	}
}