/*var FindADoctor_loadingImage = new Element("img",{'src':'/nm_core/images/ajax64.gif','alt':'Please Wait.'});
var FindADoctor_resultsLoadingImage = FindADoctor_loadingImage.cloneNode(true);
var FindADoctor_filtersLoadingImage = FindADoctor_loadingImage.cloneNode(true);

FindADoctor_readHash=function(){};
*/

//supress errors
function FindADoctor_delay(){}
function FindADoctor_readHash(){}
function FindADoctor_SpecialtyEvents(){}
function FindADoctor_SpecialtyAJAX(specialty_value){}

Ajax.Request.prototype.abort = function() {
    this.transport.onreadystatechange = Prototype.emptyFunction;
    this.transport.abort();
    Ajax.activeRequestCount--;
    if($$('#content_body .ajax_loading')[0]){$$('#content_body .ajax_loading')[0].remove()}
};
document.observe("dom:loaded", function(){
	if($$('body')[0].hasClassName('FindPhysicianPage')==true){
		//$(FindADoctor_loadingImage).addClassName("ajax_loading");
		Physician.init();
	}
	if($$('body')[0].hasClassName('Profile')==true){
		PhysicianProfile.init();
		var favoriteWrapper = new Element('div',{'id':'favorites_wrapper'}).setStyle({display:'none'});
		favoriteWrapper.insert(new Element('h3').update('Compare'));
		favoriteWrapper.insert(new Element('div',{'id':'favorites'}));
		//favoriteWrapper.insert(new Element('span').addClassName('button_background'));
		favoriteWrapper.insert(new Element('span').addClassName('button_background').insert(new Element('a',{href:'#','id':'compare_this'}).update('Compare')));
		favoriteWrapper.insert(new Element('span').addClassName('button_background').insert(new Element('a',{href:'#','id':'compare_clear'}).update('Clear')));
		//Element.insert($('search_right_toolbar'),{'after':favoriteWrapper});
		$('content_sub').insert(favoriteWrapper);

		if($$("#profile_tools ul .compare a")[0]){
			$$("#profile_tools ul .compare a").each(function(element){
				element.observe('click',function(event){
					Event.stop(event);
					FindADoctor_addToFavorites('result'+$$(".physician_profile")[0].getAttribute('id'));
				})
			});
		}
		$("compare_this").observe('click',function(event){
			Event.stop(event);
			FindADoctor_compareFavorites();
		});
		$("compare_clear").observe('click',function(event){
			Event.stop(event);
			FindADoctor_clearFavorites();
		});
		if(SWFAddress.getValue()=='print'){window.print()}
		if(getCookie("eHA_FindADoctor_Favorites_nm") && (getCookie("eHA_FindADoctor_Favorites_nm")!="-" && getCookie("eHA_FindADoctor_Favorites_nm")!="--")){
			$('favorites_wrapper').show();
			FindADoctor_loadFavorites(getCookie("eHA_FindADoctor_Favorites_nm"));
		}
	}
});
var PhysicianProfile = {
	init:function(){
		if($$('#profile_tab_links li').length>0){$$('#profile_tab_links li')[0].addClassName('on')}
		$$('#physician_profile div.tab').invoke('addClassName','off');
		if($$('#physician_profile div.tab').length>0){$$('#physician_profile div.tab')[0].addClassName('on').removeClassName('off')}
	}
};
var Physician = {
	init:function(){
		//SWFAddress.setTracker(null);
		this.ajax.init(this.uiController);
		this.resultsUI.init();
		this.searchUI.init();
		this.uiController.init(this.resultsUI,this.searchUI);
		this.ajax.controller = this.uiController;
		this.mapUtil.init($('search_forms').select('form')[1]);
		this.typeAhead.load();
		this.urlChangeHandler.init(this.ajax.loadFromURL);
		if(SWFAddress.getValue().length > 1){this.ajax.loadFromURL()}
		//document.observe('physicianEvent:urlChange',this.ajax.loadFromURL.bind(this));
	},
	deepLinkTracker:function(){
		alert('new page');
	},
	uiController:{
		init:function(passResults,passSearch){
			this.results=passResults;
			this.search=passSearch;
			this.isSearchUI=true;
			document.observe('physicianEvent:reset',this.setSearchUI.bind(this));
			document.observe('physicianEvent:xhrCreate',this.showLoading.bind(this));
			document.observe('physicianEvent:xhrComplete',this.appendResults.bind(this));
		},
		setResultsUI:function(){
			this.search.hide();this.results.clear();this.isSearchUI=false;
		},
		setSearchUI:function(){
			this.results.clear();this.search.show();this.isSearchUI=true;$$('body')[0].setStyle({cursor:'auto'});
			if($$('.Quick_Search')[0]){$$('.Quick_Search')[0].setStyle({'display':'none'});}
		},
		appendResults:function(event){
			$$('body')[0].setStyle({cursor:'auto'});
			this.results.appendResults(event.memo.transport.responseText);
			if($$('.Quick_Search')[0]){$$('.Quick_Search')[0].setStyle({'display':'block'});}
		},
		showLoading:function(event){$$('body')[0].setStyle({cursor:'progress'});this.search.clear();}
	},
	searchUI: {
		init:function(){
			this.slider={};
			if($("specialty")){
				//$("specialty").observe('change',Physician.searchUI.updateInterests);
			}
			this.isSliderActive=false;
			this.loadingImage = new Element("img",{'src':ajaxWaitGraphicURL,'alt':'Please Wait.'});
			this.loadingImage.addClassName("ajax_loading");
			this.searchForm=$('search_forms');
			$("advanced_more_options_button").observe('click', function(){
				if(this.value.indexOf("More")!=-1){this.value = "Less";this.removeClassName("More").addClassName("Less");}
				else{this.value = "More";this.removeClassName("Less").addClassName("More");}
				Effect.toggle('advanced_more_options', 'slide',{duration:0.5,afterFinish:Physician.searchUI.startSlider});
			});
			$("quick_search_submit").up('form').observe('submit', function(event){document.fire('physicianEvent:quickMainFormSubmit');Event.stop(event);}.bind(this));
			$("advanced_search_submit").up('form').observe('submit', function(event){Event.stop(event);document.fire('physicianEvent:advancedMainFormSubmit');}.bind(this));
			// replace left nav Search href with Find a Physician href (in bread crumbs)
			if($("quick_search") && $$("#content_navigation .generic_child_page_list ul li.Search a")[0] && $$("#bread_crumbs ul li.last a")[0]){
				$$("#content_navigation .generic_child_page_list ul li.Search a")[0].href = $$("#bread_crumbs ul li.last a")[0].href;
			}
			// add select to "Search" in left nav
			if($("quick_search") && $$("#content_navigation .generic_child_page_list ul li.Search")[0]){
				$$("#content_navigation .generic_child_page_list ul li.Search")[0].addClassName("sel");
			}
			// add "Search" to bread crumbs
			if($("quick_search") && $$("#bread_crumbs ul li.last")[0]){
				var new_last_crumb = new Element('li',{'class':'sel last'}).update("<a href='"+$$("#bread_crumbs ul li.last a")[0].href+"'>Search</a>");
				$$("#bread_crumbs ul li.last")[0].removeClassName("sel").removeClassName("last").insert({'after':new_last_crumb});
			}
			$('advanced_more_options').hide();
		},
		startSlider:function(){
			if($('distance')!=null){
				this.distanceInput=$('distance');
				this.sliderDiv=$('distance_slider');
			}
			if(!this.isSliderActive){
				this.slider = new Control.Slider(this.sliderDiv.down('.handle'), this.sliderDiv, {
					range:  $R(1,50),
					values: $R(1,50),
					sliderValue: 10,
					onSlide: function(value) {this.distanceInput.value=value;}.bind(this),
					onChange: function(value) {this.distanceInput.value=value;}.bind(this)
				});
				this.isSliderActive=true;
				this.sliderDiv.down('.handle').observe('mouseover',function(){this.addClassName('slider_hover')});
				this.sliderDiv.down('.handle').observe('mouseout',function(){this.removeClassName('slider_hover')});
				this.sliderDiv.down('.handle').observe('mousedown',function(){this.up().addClassName('slider_div_hover')});
				this.sliderDiv.down('.handle').observe('mouseup',function(){this.up().removeClassName('slider_div_hover')});
				$('distance').observe('change',function(){this.slider.setValue($('distance').value)}.bind(this))
			}
		},
		updateInterests:function(event){
			new Ajax.Request(physicianSpecialtyAjaxUrl,{
				method:'get',
				asynchronous:true,
				parameters: 'specialty='+Event.element(event)[Event.element(event).selectedIndex].value,
				onCreate: function(){$('clinical_interest').update('<option>Loading...</option>');},
				onSuccess: function(transport){/*this.uiController.appendResults(transport.responseText);displayActions();*/},
				onComplete: function(transport){
					var newOptionsObj = eval(transport.responseText);
					$('clinical_interest').update('');
					newOptionsObj.each(function(obj){
						$('clinical_interest').insert(new Element('option',{value:obj.id}).update(obj.name));
					});
				},
				onFailure: function(){/*alert('Something went wrong...');*/}
			});
		},
		show:function(){
			if(this.searchForm){
				if($('results')){
					$('results').remove();
					$('lat').value='';
					$('lon').value='';
					//$('content_workspace').remove();
				}
				//$('content_body').select('h1.category_title')[0].update('Find a Physician');
				$("content_body").removeClassName('search_results_container');
				if($(this.searchForm)){this.searchForm.show();}
			}
		},
		hide:function(){
			if(this.searchForm){
				if($(this.searchForm)){this.searchForm.hide();}
			}
			$("content_body").addClassName('search_results_container');
		},
		clear:function(){		
			if($("results")) {$("results").update(this.loadingImage);}
			else{$("content_body").insert(this.loadingImage);}
			this.hide();
			
			//if($('bread_crumbs')){$('bread_crumbs').remove();}
		}

	},
	resultsUI: {
		init:function(){
			this.filterForm.init();
		},
		show:function(hashParams){
			this.filterForm.show(hashParams);
		},
		clear:function(){
			this.filterForm.hide();
			//if($('bread_crumbs')){$('bread_crumbs').remove();}
		},
		filterForm:{
			init:function(){
				this.hasSlider=false;
				new Ajax.Request(findADoctorFiltersURL,{
					method:'get',
					onCreate: function(){},
					onSuccess: function(transport){this.assignEvents(transport.responseText);}.bind(this),
					onComplete: function(){},
					onFailure: function(){}
				});
			},
			assignEvents:function(htmlText){
				$("search_right_toolbar").insert({'after':htmlText});
				if($('content_workspace')){
					$('content_workspace').setStyle({display:'none'});
					$('filter_reset').observe('click',function(event){
						Event.stop(event);
						$('filter_startindex').value='1';
						document.fire('physicianEvent:filterFormSubmit');
					});
					if($("filter_form").down("noscript")){
						$("filter_form").down("noscript").remove();
					}
				}
				if($("favorites") && $("favorites").childElements()[0]){
					// do nothing, favorites are already there.
				}else{
					if(getCookie("eHA_FindADoctor_Favorites_nm") && (getCookie("eHA_FindADoctor_Favorites_nm")!="-" && getCookie("eHA_FindADoctor_Favorites_nm")!="--")){
						FindADoctor_loadFavorites(getCookie("eHA_FindADoctor_Favorites_nm"));
					}
				}
				if($("favorites") && $("compare_this")){
					$("compare_this").observe('click',function(event){
						Event.stop(event);
						FindADoctor_compareFavorites();
					});
					$("compare_clear").observe('click',function(event){
						Event.stop(event);
						FindADoctor_clearFavorites();
					})
				}
				if(SWFAddress.getValue().length > 1){Physician.ajax.loadFromURL()}
			},
			show:function(hashParams){
				if($('content_workspace')){$('content_workspace').setStyle({display:'block'});}
				if(this.hasSlider==false){
					this.sliderDiv=$('distance_slider_filter_form');
					this.slider = new Control.Slider(this.sliderDiv.down('.handle'), this.sliderDiv, {
						range:  $R(1,50),
						values: $R(1,50),
						sliderValue: hashParams['distance'],
						onSlide: function(value) {$('distance_filter_form').value=value;}.bind(this),
						onChange: function(value) {$('distance_filter_form').value=value;}.bind(this)
					});
					this.hasSlider=true;
					this.sliderDiv.down('.handle').observe('mouseover',function(){this.addClassName('slider_hover')});
					this.sliderDiv.down('.handle').observe('mouseout',function(){this.removeClassName('slider_hover')});
					this.sliderDiv.down('.handle').observe('mousedown',function(){this.up().addClassName('slider_div_hover')});
					this.sliderDiv.down('.handle').observe('mouseup',function(){this.up().removeClassName('slider_div_hover')});
					$('distance_filter_form').observe('change',function(){this.slider.setValue($('distance_filter_form').value)}.bind(this))
				}
			},
			hide:function(){
				if($('content_workspace')){$('content_workspace').setStyle({display:'none'});}
			}
		},
		appendResults:function(htmlText){
			this.clear();
			var hashParams = SWFAddress.getValue().gsub('/','').toQueryParams();
			this.show(hashParams);
			if(hashParams['search_result_page']){
				if($$("#bread_crumbs ul li").length == 3){
					if($$("#bread_crumbs ul li a")[2].innerHTML == 'Search Results'){
						$$("#bread_crumbs ul li a")[2].href = location.href;
					}
					else{
						$$("#bread_crumbs ul li")[2].remove();
					}
				}
				if(hashParams['search_result_page']=='yes'){
					if($$("#bread_crumbs ul li").length == 2){
						$$("#bread_crumbs ul .last").invoke('removeClassName','last');
						$$("#bread_crumbs ul .sel").invoke('removeClassName','sel');
						$$("#bread_crumbs ul")[0].insert(new Element('li').addClassName('last').addClassName('sel').insert(new Element('a',{href:location.href}).update('Search Results')));
					}
				}
			}
			else if(hashParams['browse_by_specialty']){
				if(hashParams['browse_by_specialty']=='yes'){
					if($$("#bread_crumbs ul li").length == 4){
						//alert($$("#bread_crumbs ul li a")[3].innerHTML+hashParams['specialty_name'].gsub("+"," "));
						if($$("#bread_crumbs ul li a")[3].innerHTML == hashParams['specialty_name'].gsub("+"," ")){
							$$("#bread_crumbs ul li a")[3].href = location.href;
						}
						else{
							$$("#bread_crumbs ul li")[2].remove();
							$$("#bread_crumbs ul li")[3].remove();
						}
					}
					if($$("#bread_crumbs ul li").length == 3){
						$$("#bread_crumbs ul li")[2].remove();
					}
					if($$("#bread_crumbs ul li").length == 2){
						$$("#bread_crumbs ul .last").invoke('removeClassName','last');
						$$("#bread_crumbs ul .sel").invoke('removeClassName','sel');
						$$("#bread_crumbs ul")[0].insert(new Element('li').insert(new Element('a',{href:'/eHA_CHS/Browse+By+Speciality'}).update('Browse By Specialty')));
						$$("#bread_crumbs ul")[0].insert(new Element('li').addClassName('last').addClassName('sel').insert(new Element('a',{href:location.href}).update(hashParams['specialty_name'].gsub("+"," "))));
					}
				}
			}
			if($('filter_form')!=null){
				$('filter_form').select('input').each(function(element){
					if(element.id != 'filter_reset'){element.value='';}
				});
				$('filter_form').select('select').each(function(element){
					var options=element.select('option');
					if(element.down('option')){
						element.selectedIndex=0;
					}
				});
				$('filter_form').select('input').each(function(element){
					if(hashParams[element.name] && element.getAttribute('id') != 'filter_reset'){
						element.value=decodeURI(hashParams[element.name]).gsub('^25', '%');
					}
				});
				$('filter_form').select('select').each(function(element){
					var valueToFind=hashParams[element.name];
					var options=element.select('option');
					for(var i=0;i<options.length;i++){
						if(valueToFind==options[i].value){element.selectedIndex=i}
					}
				});
				if(this.filterForm.slider != null){
					this.filterForm.slider.setValue(parseInt(hashParams['distance']));
				}
			}

			//$('content_body').select('h1.category_title')[0].update('Physician Search Results');
			if($$('#content_body .ajax_loading')[0]){$$('#content_body .ajax_loading')[0].remove()}
			if($('results')){
				$('results').remove();
				$('search_forms').insert({'before':htmlText});
			}
			else{
				$('search_forms').insert({'before':htmlText});
			}
			$$("#results .result .secondary").each(function(element){element.down('div').setStyle({display:"none"})})
			//FindADoctor_addSearchResultsEvents();
			$$("#results .result .secondary input").each(function(element){
				if(element.getAttribute('id').indexOf("extraButton")!=-1){
					element.observe('click',function(event){
						Event.stop(event);
						Effect.toggle($(this).up("div.secondary").down('div'), 'blind', {duration:0.5});
						if($(this).value.indexOf("More Options")!=-1){$(this).value = "Less Options";$(this).removeClassName("More").addClassName("Less");
						}else{$(this).value = "More Options";$(this).removeClassName("Less").addClassName("More");
						}
					});
				}
			});
			$$("#results ul .compare a").each(function(element){
				element.observe('click',function(event){
					Event.stop(event);
					FindADoctor_addToFavorites(Event.element(event).up('.result').getAttribute('id'));
				})
			});
			$$('div.results_per_page_pagination a').each(function(element){element.observe('click',function(event){
				var element=event.element();
				Event.stop(event);
				element.href="javascript:void(0)";
				$('filter_startindex').value='1';
				$('directory_results_per_page').value=element.innerHTML;
				document.fire('physicianEvent:filterFormSubmit')
			});});
			$$('div.pagination_inner li a').each(function(element){element.observe('click',function(event){
				var element=event.element();
				Event.stop(event);
				element.href="javascript:void(0)";
				var paginationAParentElement = element.up('li');
				if(paginationAParentElement.hasClassName('next')==false&&paginationAParentElement.hasClassName('previous')==false&&paginationAParentElement.hasClassName('page_selected')==false){
					$('filter_startindex').value=element.innerHTML;
					document.fire('physicianEvent:filterFormSubmit')
				}
				else if(paginationAParentElement.hasClassName('next')==true){
					if($('filter_form').select('input[name="startindex"]')[0].value==''){$('filter_form').select('input[name="startindex"]')[0].value='1'}
					$('filter_form').select('input[name="startindex"]')[0].value=parseInt($('filter_form').select('input[name="startindex"]')[0].value)+1;
					document.fire('physicianEvent:filterFormSubmit')
				}
				else if(paginationAParentElement.hasClassName('previous')==true){
					if($('filter_form').select('input[name="startindex"]')[0].value==''){$('filter_form').select('input[name="startindex"]')[0].value='1'}
					$('filter_form').select('input[name="startindex"]')[0].value=parseInt($('filter_form').select('input[name="startindex"]')[0].value)-1;
					document.fire('physicianEvent:filterFormSubmit')
				}
			});});
			assignPanelLinks();
		}
	},
	ajax: {
		init:function(controller){
			this.currentXHRObj={};
			this.isLoading=false;
			this.uiController=controller;
			this.serverCall=findADoctorFindADoctorSubTemplateURL;
		},
		loadFromURL:function(){
			if(this.isLoading==true){this.currentXHRObj.abort();}
			//if(this.uiController.isSearchUI==true){
			this.serverCall=findADoctorSearchResultsURL;
			if(SWFAddress.getValue().indexOf('=')!=-1){
				document.fire('physicianEvent:xhrOpen');
				this.isLoading=true;
				this.currentXHRObj = new Ajax.Request(this.serverCall,{
					method:'get',
					asynchronous:true,
					parameters: SWFAddress.getValue().replace('/',''),//.gsub('%2f20',' ')),
					onCreate: function(){document.fire('physicianEvent:xhrCreate');},
					onSuccess: function(transport){/*this.uiController.appendResults(transport.responseText);displayActions();*/},
					onComplete: function(transport){
						document.fire('physicianEvent:xhrComplete',{transport:transport});
						this.isLoading=false;
					}.bind(this),

					onFailure: function(){/*alert('Something went wrong...');*/}
				});
			}
			else{
				document.fire('physicianEvent:reset');
			}
		}
	},
	urlChangeHandler: {
		init:function(func){
			//this.handleChange=func;
			SWFAddress.addEventListener(SWFAddressEvent.INTERNAL_CHANGE, this.handleChange);
			SWFAddress.addEventListener(SWFAddressEvent.EXTERNAL_CHANGE, this.handleChange);
		},
		handleChange:function(event){
			//alert(Object.toQueryString(event));
			this.Physician.ajax.loadFromURL();
			//document.fire('physicianEvent:urlChange');
			//Physician.mapUtil.gecodeAddress();
		}
	},
	typeAhead: {
		load:function(){
			this.loadLastNames();
		},
		loadLastNames:function(){
			new Ajax.Request(findADoctorTypeAheadURL,{
				method:'get',
				parameters: "postName=advanced_search_lastname_text",
				onCreate: function(){},
				onSuccess: function(transport){
					$('advanced_search_lastname_text_typeAhead').setStyle({background:"#fff",border:"1px solid #888"});
					var lastNameAutoCompleter = new Autocompleter.Local("advanced_search_lastname_text","advanced_search_lastname_text_typeAhead",(transport.responseText).evalJSON(true),{fullSearch:false,partialSearch:false,partialChars:2,afterUpdateElement:function(el){document.fire('physicianEvent:advancedMainFormSubmit')}});
					lastNameAutoCompleter.markPrevious = this.markPrevious;
					lastNameAutoCompleter.markNext = this.markNext;
					this.loadConditions();
				}.bind(this),
				onFailure: function(){/*alert('Something went wrong...');*/}
			}); 
		},
		loadConditions:function(){
			new Ajax.Request(findADoctorTypeAheadURL,{
				method:'get',
				parameters: "postName=quick_search_text",
				onCreate: function(){},
				onSuccess: function(transport){
					$('quick_search_text_typeAhead').setStyle({background:"#fff",border:"1px solid #888"});
					var quickSearchAutoCompleter = new Autocompleter.Local("quick_search_text","quick_search_text_typeAhead",(transport.responseText).evalJSON(true),{fullSearch:false,partialSearch:false,partialChars:2,afterUpdateElement:function(input,li){
						document.fire('physicianEvent:quickMainFormSubmit');
					}});
					quickSearchAutoCompleter.markPrevious = this.markPrevious;
					quickSearchAutoCompleter.markNext = this.markNext;
				}.bind(this),
				onFailure: function(){/*alert('Something went wrong...');*/}
			}); 
		},
		markPrevious: function() {
			if(this.index > 0) {this.index--;}
			else {
				this.index = this.entryCount-1;
				this.update.scrollTop = this.update.scrollHeight;
			}
			selection = this.getEntry(this.index);
			selection_top = selection.offsetTop;
			if(selection_top < this.update.scrollTop){
				this.update.scrollTop = this.update.scrollTop-selection.offsetHeight;
			}
		},
		markNext: function() {
			if(this.index < this.entryCount-1) {this.index++;}
			else {
				this.index = 0;
				this.update.scrollTop = 0;
			}
			selection = this.getEntry(this.index);
			selection_bottom = selection.offsetTop+selection.offsetHeight;
			if(selection_bottom > this.update.scrollTop+this.update.offsetHeight){
				this.update.scrollTop = this.update.scrollTop+selection.offsetHeight;
			}
		}
	},
	mapUtil:{
		init:function(form){
			this.geocoder = new GClientGeocoder();
			this.searchForm=form;
			document.observe('physicianEvent:quickMainFormSubmit',function(){
				/*$('quick_search_text').value = $('quick_search_text').value.replace(/^\s+|\s+$/g,"");*/
				SWFAddress.setValue($('search_forms').select('form')[0].serialize().gsub('%25', '^25'));
			}.bind(this))
			document.observe('physicianEvent:advancedMainFormSubmit',function(){
				/*$('advanced_search_lastname_text').value = $('advanced_search_lastname_text').value.replace(/^\s+|\s+$/g,"");*/
				this.gecodeAddress();
			}.bind(this))
			document.observe('physicianEvent:filterFormSubmit',function(){this.gecodeAddressFilter();}.bind(this))
		},
		gecodeAddress:function(){
			if($('street_address').value!='' || $('distance_city').value!='' || $('state').value!='' || $('zipcode').value!=''){
				this.geocoder.getLatLng(($('street_address').value+' '+$('distance_city').value+' '+$('state').value+' '+$('zipcode').value),
				function(point){
					if(point){$('lat').value=point.lat();$('lon').value=point.lng();}
					//var newVal=encodeURI(this.searchForm.serialize());
					SWFAddress.setValue(this.searchForm.serialize().gsub('%25', '^25'));
				}.bind(this));
			}
			else{SWFAddress.setValue(this.searchForm.serialize().gsub('%25', '^25'));}
		},
		gecodeAddressFilter:function(){
			if($('steet_address_filter_form').value!='' || $('distance_city_filter_form').value!=''
														|| $('state_filter_form').value!=''
														|| $('zip_filter_form').value!= '')
			{
				this.geocoder.getLatLng(($('steet_address_filter_form').value+' '+$('distance_city_filter_form').value+' '+$('state_filter_form').value+' '+$('zip_filter_form').value),
				function(point){
					if(point){$('filter_lat').value=point.lat();$('filter_lon').value=point.lng();}
					//$('filter_startindex').value='0';
					SWFAddress.setValue($('filter_form').serialize().gsub('%25', '^25'));
	
				}.bind(this));
			}
			else{SWFAddress.setValue($('filter_form').serialize().gsub('%25', '^25'));}
		}
	}
};

function FindADoctor_addSearchPageEvents(){
try{
	page_toolbar();
	
	if(window.location.hash && $("quick_search") && $("advanced_search") && $("advanced_more_options")){
		var hashArray = window.location.hash.substring(1).toQueryParams();
		FindADoctor_replaceSearchForm(FindADoctor_FindADoctorSubTemplateURL,hashArray)
		return true;
	}
	
	if($("advanced_more_options") && $("advanced_more_options_button") && $("quick_search_text") && $("advanced_search_lastname_text")){
		
		/*$('more_options').childElements().each(function(element){
			element.style.position = 'static';
			element.style.left = 'auto';
		});*/
		
		/*
		$("advanced_search_condition_text").onfocus = function(){
			$("quick_search_text").value = "";
			$("advanced_search_lastname_text").value = "";
			return false;
		}
		*/
		
		if($('specialty_list_link')){
			$('specialty_list_content').hide();
			
			new Ajax.Request(findADoctorTypeAheadURL,
			  {
			    method:'get',
			    parameters: "postName="+"advanced_search_condition_text",
			    onCreate: function(){
					//$(typeAheadDivID).update("<img src='/eHA_files/images/ajax/big.gif' alt='Please Wait.' class='ajax_loading' />");
			    },
			    onSuccess: function(transport){
				    condition_array = (transport.responseText).evalJSON(true);
			    	// begin local autocomplete
					var thisUL = $CE("ul");
					for(i=0;i<condition_array.length;i++){
						var thisLI = $CE("li");
						var thisA = $CE("a",{'href':'#'});
						thisA.update(condition_array[i]);
						thisLI.appendChild(thisA);
						thisUL.appendChild(thisLI);
					}
					$('specialty_list_content').appendChild(thisUL);
					$$('#specialty_list_content a').each(function(element){
						element.onclick = function(){
							$('advanced_search_condition_text').value = this.innerHTML;
							return false;
						}
					});

			    },
			    onFailure: function(){ 
					// alert('Something went wrong...');
				}
			  });

			$('specialty_list_link').onclick=function(){
				$('specialty_list_content').toggle();
				return false;
			};
		}
	}
}catch(err){
	// do nothing
}
}


function randomInt(startInt,endInt){
	// startInt can be positive or negative or zero
	// endInt is incremented so that the range is inclusive
	endInt++;
	var result = Math.floor(Math.random()*endInt);
	result = result + startInt;
	return result;
}



var safe_harbor_text = "Important Legal Notice<br /><br />Physicians in good standing on the medical staff and available to see new patients can choose to join our free referral service. We use a rotational selection process to identify physicians based on your stated needs & preferences.";


function FindADoctor_addSearchResultsEvents(){
	alert("FindADoctor_addSearchResultsEvents");
try{	
	//page_toolbar();
	// replace left nav Search href with Find a Physician href (in bread crumbs)
	if($("results") && $$("#content_navigation .generic_child_page_list ul li.Search a")[0] && $$("#bread_crumbs ul li.last a")[0]){
		$$("#content_navigation .generic_child_page_list ul li.Search a")[0].href = $$("#bread_crumbs ul li.last a")[0].href;
	}

	// add select to "Search" in left nav
	if($("results") && $$("#content_navigation .generic_child_page_list ul li.Search")[0]){
		$$("#content_navigation .generic_child_page_list ul li.Search")[0].addClassName("sel");
	}
	
	// add "Search" to bread crumbs
	if($("results") && $$("#bread_crumbs ul li.last")[0] && $$("#bread_crumbs ul li.last a")[0].innerHTML.indexOf("Search")==-1){
		var new_last_crumb = new Element('li',{'class':'sel last'}).update("<a href='"+$$("#bread_crumbs ul li.last a")[0].href+"'>Search</a>");
		$$("#bread_crumbs ul li.last")[0].removeClassName("sel").removeClassName("last").insert({'after':new_last_crumb});
	}
	
	if($$("#results .actions .share a")[0]){
		$$("#results .actions .share a").each(function(element){
			var thisTitle = $(element).up("div").next("div").down("h4 a").innerHTML.replace(/(<([^>]+)>)/ig,"");
			var thisLink = $(element).up("div").next("div").down("h4 a").href;
			if(thisLink.indexOf("http://")==-1){
				thisLink = "http://"+document.domain+thisLink;
			}
			//console.log("assigning "+thisTitle+" as a title for ShareThis");
			//console.log("assigning "+thisLink+" as a link for ShareThis");
			var sharethis_object = SHARETHIS.addEntry(
				{
					title:encode_utf8(thisTitle),
					url:encode_utf8(thisLink)
				},{
					button:false,
					embeds:true
				}
			);
			sharethis_object.attachButton(element);
		});
	}
	
	if($('results') && window.location.hash){
		// add hash to physician profile link for breadcrumbs
		if($$("#results ul li h4 a")){
			$$("#results ul li h4 a").each(function(element){
				element.href = element.href+window.location.hash;
			});
		}
		// add hash to "view complete profile" link
		if($$("#results ul li .view_profile a.detail_button")){
			$$("#results ul li .view_profile a.detail_button").each(function(element){
				element.href = element.href+window.location.hash;
			});
		}

		// no link on thumbnail so this IF doesn't happen
		if($$("#results ul li .thumbnail a")){
			$$("#results ul li .thumbnail a").each(function(element){
				element.href = element.href+window.location.hash;
			});
		}
		// add hash to this selected breadcrumb
		if($$("#bread_crumbs .sel a")){
			$$("#bread_crumbs .sel a").each(function(element){
				element.href = element.href+window.location.hash;
			});
		}
	}
	
	if($$("#results .back_link a")){
		$$("#results .back_link a").each(function(element){
			element.onclick=function(){
				//FindADoctor_back();
				return false;
			}
		});
	}
	if($("favorites") && $("compare_this")){
		$("compare_this").onclick = function(){
			FindADoctor_compareFavorites();
			return false;
		}
	}
	if($("favorites") && $("compare_clear")){
		$("compare_clear").onclick = function(){
			FindADoctor_clearFavorites();
			return false;
		}
	}
	// load cookie and populate favorites if cookie has value and favorites isn't already there
	if($("favorites") && $("favorites").childElements()[0]){
		// do nothing, favorites are already there.
	}else{
		if(getCookie("eHA_FindADoctor_Favorites_nm") && (getCookie("eHA_FindADoctor_Favorites_nm")!="-" && getCookie("eHA_FindADoctor_Favorites_nm")!="--")){
			FindADoctor_loadFavorites(getCookie("eHA_FindADoctor_Favorites_nm"));
		}
	}
	assignPanelLinks();
	
	} catch(err) {
		// do nothing
		//alert("error! "+err.msg);
	}	
}



function $CE(tagName, attributes, styles){ //short for create element
	var el = document.createElement(tagName);
	if (attributes)
		$H(attributes).each(function(pair){
		      eval("el." + pair.key + "='" + pair.value + "'");
		});
	if (styles)
		$H(styles).each(function(pair){
		      el.style[pair.key] = pair.value;
		});
		
	return $(el);
}



// this function serves as the Events assigning function for the FaD detail / profile page

function FindADoctor_readDetailHash(){
    /*

	        // add "search results" to bread crumbs with appropriate hash value.
	        if($$("#bread_crumbs .last")[0]){
		        var LI = new Element('li').update(new Element('a',{'href':$$("#bread_crumbs .last")[0].previous("li").down("a").href+window.location.hash}).update("Search Results"));
		        $$("#bread_crumbs .last")[0].insert({'before':LI});
	        }
	        
			if($$("#bread_crumbs .sel a")){
				$$("#bread_crumbs .sel a").each(function(element){
					element.href = element.href+window.location.hash;
					element.up("ul").previous("a").href = element.up("ul").previous("a").href+window.location.hash;
				});
			}
	*/
    
}



function FindADoctor_addToFavorites(resultID){
	if($('favorites')){
		//if(){
		//$(resultID).addClassName("favorite");
		$("favorites_wrapper").style.height = "auto";
		Effect.Appear('favorites_wrapper');
		var newDIV = $CE("div",{'id':"favorite_"+resultID},{display:"none"});
		var newH4 = $CE("h4");
		var newA = $CE("a",{href:"#",className:"delete",title:"Remove this from Favorites"});
		newA.observe('click',function(event){
			Event.stop(event);
			FindADoctor_removeFavorite($(this).up("div"));
		});
		newA.appendChild(document.createTextNode("Remove this from Favorites"));
		if($(resultID)){
			if(!$("favorite_"+resultID)){
				if($("results")){
					var newH4_A = $$("#"+resultID+" h4 a")[0].cloneNode(true);
					newH4.appendChild(newH4_A);
				}
				newDIV.appendChild(newH4);
				newDIV.appendChild(newA);
				$('favorites').appendChild(newDIV);
				Effect.Appear("favorite_"+resultID,{duration:0.5});
				FindADoctor_updateCookie(resultID);
			}else{
				// this is already a favorite (maybe it has been hidden)
				Effect.Appear("favorite_"+resultID,{duration:0.5});
			}
		}
		else if($$(".physician_profile")[0]){
			if($$(".physician_biography_name")[0]) var drName = $$(".physician_biography_name")[0].innerHTML;
			var newH4_A = new Element('a',{href:location.href});
			newH4_A.update(drName);
			newH4.appendChild(newH4_A);
			newDIV.appendChild(newH4);
			newDIV.appendChild(newA);
			$('favorites').appendChild(newDIV);
			Effect.Appear("favorite_"+resultID,{duration:0.5});
			FindADoctor_updateCookie(resultID);
		}
	}
	//FindADoctor_addFavoriteEvents();
	return false;
}
function FindADoctor_updateCookie(resultID){
	var currentFavoritesCookie = getCookie("eHA_FindADoctor_Favorites_nm");
	if(currentFavoritesCookie){
		if(currentFavoritesCookie.length>0){
			if(currentFavoritesCookie.indexOf(resultID)!=-1){
				// cookie already contains this ID
				return false;
			}else{
				currentFavoritesCookie = currentFavoritesCookie+"-"+resultID;
			}
		}else{
			// happens to be there but empty -- probably because favorites were removed
			currentFavoritesCookie = resultID;
		}
		setCookie("eHA_FindADoctor_Favorites_nm",currentFavoritesCookie);
		return true;
	}else{
		// not there at all, create and set with this ID
		setCookie("eHA_FindADoctor_Favorites_nm",resultID);
		return true;
	}
}

function FindADoctor_loadFavorites(cookie_value){
	// cookie is being populated and depopulated correctly.  must load cookie and initiate AJAX request to load favorites values
	if($('favorites')){
		var favoriteIDs = cookie_value.gsub("result","").split("-");
		for(var i=0;i<favoriteIDs.length;i++){
			if(favoriteIDs[i]!=""){
				if($("result"+favoriteIDs[i])){
					$("result"+favoriteIDs[i]).addClassName("favorite");
				}
				FindADoctor_populateFavorites(favoriteIDs[i]);
			}
		}
		$("favorites_wrapper").style.height = "auto";
		Effect.Appear('favorites_wrapper');
	}
}

function FindADoctor_populateFavorites(asset_id){
	if(findADoctorFavoriteTemplateName){
		// FindADoctor_favoriteTemplateName (equivalent to pagename in fatwire's long URL) MUST be found in the page
		// nm/eHA_Dir_C/nm/SubTemplate/favorite (sample FindADoctor_compareTemplateName value)
		//var URL = "/cs/Satellite";
		var parameters = {
			site: 'eHA_CHS',
			physician_id: asset_id
		};
		new Ajax.Request(findADoctorFavoriteTemplateName,
		{
		    method:'get',
		    parameters: parameters,
		    onCreate: function(){
			    /*var this_loading_image = FindADoctor_loadingImage.cloneNode(true);
			    this_loading_image.id = "favorite"+asset_id;
				$("favorites").insert({'bottom':this_loading_image});*/
		    },
		    onSuccess: function(transport){
		    	//$('results').update(transport.responseText);
		    },
		    onComplete: function(transport){
				//alert(transport.responseText);
				$('favorites').insert(new Element('div',{id:"favorite_result"+asset_id}));
				$("favorite_result"+asset_id).replace(transport.responseText);
				if($("favorite_result"+asset_id)){
					$("favorite_result"+asset_id).select('a.delete').each(function(element){
						element.observe('click',function(event){
							Event.stop(event);
							FindADoctor_removeFavorite($(this).up("div"));
						});
					});
				}
		    },
		    onFailure: function(){
				// alert('Something went wrong...');
			}
		  });
	}else{
		// error, can't find FindADoctor_compareTemplateName
	}
}

function FindADoctor_addFavoriteEvents(){
	if($('favorites')){
		$$("#favorites a.delete").each(function(element){
			element.href = 'javascript:void(0)';
			element.observe('click',function(event){
				Event.stop(event);
				FindADoctor_removeFavorite($(this).up("div"));
			});
		});
	}
}

function FindADoctor_checkFavorites(){
	if($("favorites").down()==undefined){
		// has no children
		Effect.BlindUp("favorites_wrapper",{duration:0.2});
	}
}

function FindADoctor_clearFavorites(){
	if($$("#favorites>div")[0]){
		$$("#favorites>div").each(function(element){
			FindADoctor_removeFavorite(element);
		});
	}
}

function FindADoctor_compareFavorites(){
	// if comparison is already there, do nothing
	if($$("#results div.compare span.done")[0] || $("content_body").select("div.compare span.done")[0]){
		// do nothing
	}else{
		if($("favorites")){
			$("compare_this").up("span").addClassName("sel");
			var DIV = new Element('div',{'class':'compare'}).update(new Element('ul'));
			var doneButton = new Element('span',{'class':'done'}).update(new Element('a',{'href':'#'}).update("Return to Previous Page"));
			if($("results")){
				$("results").childElements().each(function(element){
					if(Prototype.Browser.IE){element.hide();}
					else{element.fade({duration:0.2});}
				});
				$("results").insert({'bottom':DIV});
				$$("#results div.compare")[0].insert({'bottom':doneButton});

				$$("#results div.compare span.done a")[0].onclick = function(){
					FindADoctor_clearCompare();
					return false;
				};
			}
			else if($$(".physician_profile")[0]){
				$$(".physician_profile")[0].fade({duration:0.2});
				if($('results')==null){$("content_body").insert(new Element('div',{id:'results'}));}
				$("results").insert(DIV);
				$("content_body").select("div.compare")[0].insert({'bottom':doneButton});
				$("content_body").select("div.compare span.done a")[0].onclick = function(){
					FindADoctor_clearCompare();
					return false;
				};
			}
			$$('body')[0].setStyle({cursor:'progress'});
			var loadingImage = new Element("img",{'src':ajaxWaitGraphicURL,'alt':'Please Wait.'});
			loadingImage.addClassName("ajax_loading");
			var LI = new Element('li').insert(loadingImage);
			$$("#results div.compare ul")[0].insert({'bottom':LI});
			// populate array of IDs to use (don't use cookie in case user agent refuses cookies)
			var compareIDs = new Array();
			var listOfIds ="";
			$$("#favorites div").each(function(element){
				listOfIds+=element.id.replace("favorite_result","")+",";
				compareIDs.push(element.id.replace("favorite_result",""));
			});
			
			// populate the UL, one LI at a time, with the IDs from array
			/*for(var i=0;i<compareIDs.length;i++){
				var LIclass = "result";
				if(i%2==1){
					LIclass = "result alt";
				}
				FindADoctor_populateCompare(compareIDs[i],LIclass);
				*/
			var parameters = {
				//physician_id: asset_id.gsub("favorite_",""),
				physician_id_list:listOfIds
			};
			//new Ajax.Request(findADoctorCompareTemplateName,
			if(findADoctorCompareListURL){
			new Ajax.Request(findADoctorCompareListURL,
			{
				method:'get',
				parameters: parameters,
				onCreate: function(){
				},
				onSuccess: function(transport){
					//$('results').update(transport.responseText);
				},
				onComplete: function(transport){
					//var compareResults = new Element('ul').update(transport.responseText);
					$$("#results div.compare ul")[0].update(transport.responseText);
					$$("#results div.compare div.actions li.compare").invoke("hide");
					emailEvents();
					$$("#results .result .secondary input").each(function(element){
					if(element.getAttribute('id').indexOf("extraButton")!=-1){
						$$('body')[0].setStyle({cursor:'auto'});
						$$('ajax_loading').invoke('remove');
						this.loadingImage = new Element("img",{'src':ajaxWaitGraphicURL,'alt':'Please Wait.'});
						this.loadingImage.addClassName("ajax_loading");
						element.up("div.secondary").down('div').hide();
						assignPanelLinks();
						element.observe('click',function(event){
							Event.stop(event);
							Effect.toggle($(this).up("div.secondary").down('div'), 'blind', {duration:0.5});
							if($(this).value.indexOf("More Options")!=-1){$(this).value = "Less Options";$(this).removeClassName("More").addClassName("Less");
							}else{$(this).value = "More Options";$(this).removeClassName("Less").addClassName("More");
							}
						});
					}
				});
				}
			});
			}
		}
	}
}

function FindADoctor_clearCompare(){
	if($("results")){
		$$("#results div.compare")[0].remove();
		$("results").childElements().each(function(element){
			if(Prototype.Browser.IE){element.show();}
			else{element.appear({duration:0.2});}
		});
		//$("results").appear({duration:0.2});
	}
	if($$(".physician_profile").length>0){
		if($('results')){$('results').remove()}
		$$(".physician_profile")[0].appear({duration:0.2});
	}
	$("compare_this").up("span").removeClassName("sel");
}

function FindADoctor_populateCompare(asset_id,LIclass){
	if(findADoctorCompareTemplateName){
		// FindADoctor_compareTemplateName (equivalent to pagename in fatwire's long URL) MUST be found in the page
		// nm/eHA_Dir_C/nm/SubTemplate/result (sample FindADoctor_compareTemplateName value)
		var parameters = {
			physician_id: asset_id.gsub("favorite_","")
		};
		new Ajax.Request(findADoctorCompareTemplateName,
		{
		    method:'get',
		    parameters: parameters,
		    onCreate: function(){
			    //var this_loading_image = FindADoctor_loadingImage.cloneNode(true);
			    //this_loading_image.id = "compare"+asset_id;
			    //var LI = new Element('li',{'class':LIclass}).update(this_loading_image);
				//$$("#results div.compare ul")[0].insert({'bottom':LI});
		    },
		    onSuccess: function(transport){
		    	//$('results').update(transport.responseText);
		    },
		    onComplete: function(transport){
			    var LI = new Element('li',{'class':LIclass}).update(transport.responseText);
				if($("results")){
					$$("#results div.compare ul")[0].insert({'bottom':LI});
					$$("#results div.compare div.actions li.compare").invoke("hide");
					//alert($$("#results div.compare ul")[0].select("li:last .secondary").length);
					$$("#results div.compare ul")[0].select("li:last .secondary").each(function(element){element.down('div').setStyle({display:"none"})})
				}
				else if($$(".physician_profile").length>0){
					$$("div.compare ul")[0].insert({'bottom':LI});
					$$("div.compare ul li:last").invoke("hide");
				}
				//alert($$("div.compare ul").length);
				//$$("div.compare ul li:last").select(".secondary").each(function(element){element.down('div').setStyle({display:"none"})})
				//FindADoctor_addSearchResultsEvents();
				$$("div.compare ul li:last").select(".secondary input").each(function(element){
					if(element.id.indexOf("extraButton")!=-1){
						element.observe('click',function(event){
							Event.stop(event);
							Effect.toggle($(this).up("div.secondary").down('div'), 'blind', {duration:0.5});
							if($(this).value.indexOf("More Options")!=-1){$(this).value = "Less Options";$(this).removeClassName("More").addClassName("Less");
							}else{$(this).value = "More Options";$(this).removeClassName("Less").addClassName("More");
							}
						});
					}
				});
				//FindADoctor_addSearchResultsEvents();
		    },
		    onFailure: function(){ 
				// alert('Something went wrong...');
			}
		  });
	}else{
		// error, can't find FindADoctor_compareTemplateName
	}
}

function FindADoctor_removeFavorite(thisFavorite){
	Effect.Fade(thisFavorite.id,{duration:0.2});
	setTimeout("$('"+thisFavorite.id+"').up().removeChild($('"+thisFavorite.id+"'))",200);
	setTimeout("FindADoctor_checkFavorites()",220);
	if($(thisFavorite.id.replace("favorite_result",""))){
		$(thisFavorite.id.replace("favorite_result","")).removeClassName("favorite");
	}
	var currentFavoritesCookie = getCookie("eHA_FindADoctor_Favorites_nm");
	if(currentFavoritesCookie){
		var resultID = thisFavorite.id.replace("favorite_result","");		
		// this string manipulation may leave a trailing hyphen. that is acceptable
		currentFavoritesCookie = currentFavoritesCookie.replace("result"+resultID,"").replace(/--/g,"-");
		setCookie("eHA_FindADoctor_Favorites_nm",currentFavoritesCookie);
	}else{
		// an error has occured.  if there is a favorite, there should be a cookie
		// unless user agent will not allow cookies
	}
	return false;
}


function FindADoctor_changeFilters(){

}

function getCookie(c_name){
	if(document.cookie.length>0){
		c_start=document.cookie.indexOf(c_name + "=");
		if(c_start!=-1){
			c_start=c_start + c_name.length+1; 
			c_end=document.cookie.indexOf(";",c_start);
			if(c_end==-1){
				c_end=document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start,c_end));
		}else{
			//this cookie name not found
			return false;
		}
	}
	//no cookies
	return false;
}
		
function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value) + ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

//addLoadEvent(FindADoctor_switchToTab);

function FindADoctor_switchToTab(tab_id,tab_link_id){
	if($$("#physician_profile .tab")[0] && $$("#profile_tab_links li")[0]){
		try{
			$$("#physician_profile .on").invoke("addClassName","off").invoke("removeClassName","on");
			$$("#profile_tab_links li.on").invoke("addClassName","off").invoke("removeClassName","on");
			if((typeof tab_id!=="undefined" && typeof tab_link_id!=="undefined") && ($(tab_id) && $(tab_link_id))){
				$(tab_id).addClassName("on").removeClassName('off');
				$(tab_link_id).addClassName("on").removeClassName('off');
			}else{
				// requested tab not found, open first tab by default
				//$$("#physician_profile .tab")[0].addClassName("on");
				//$$("#profile_tab_links li")[0].addClassName("on");
			}
		}catch(err){
			console.log("ERROR: "+err.description);
		}
	}
	return false;
}

function FindADoctor_megaDropDownEvents(){
	if($("primary_nav_physician_finder_search_field")){
		FindADoctor_typeAheadJSON(findADoctorTypeAheadURL,"primary_nav_physician_finder_search_field","primary_nav_physician_finder_search_field_typeAhead");
	}
	
	if($("primary_nav_physician_finder_search_button")){
		$("primary_nav_physician_finder_search_button").onclick = function(){
			FindADoctor_megaDropDownExecute($("primary_nav_physician_finder_search_button"));
			return false;
		}
		$("primary_nav_physician_finder_search_button").onsubmit = function(){
			FindADoctor_megaDropDownExecute($("primary_nav_physician_finder_search_button"));
			return false;
		}
		$("primary_nav_physician_finder_search_button").up("form").onsubmit = function(){
			FindADoctor_megaDropDownExecute($("primary_nav_physician_finder_search_button"));
			return false;
		}
	}

}



function FindADoctor_replaceSearchForm(FindADoctor_FindADoctorSubTemplateURL,hash){

}


/*
begin section for video "popup"
*/
var panel_duration = 0.6;
var morph_duration = 0.6;
var panel_close_handler;


function assignPanelLinks(){
	try{
		var videoLinks = new Array();
		$$(".safe_harbor a").each(function(element){
			element.onclick = function(){
				messageString = safe_harbor_text;
				systemMessage(messageString,15000);
				return false;
			}
		});
		if($$("#physician_video a")[0]){
			videoLinks = videoLinks.concat($$("#physician_video a"));
		}
		if($$("#results .actions .video a")[0]){
			videoLinks = videoLinks.concat($$("#results .actions .video a"));
		}
		if($$("#results .physician_media .video a")[0]){
			videoLinks = videoLinks.concat($$("#results .physician_media .video a"));
		}
		if($$(".physician_profile_inner .video a")[0]){
			videoLinks = videoLinks.concat($$(".physician_profile_inner .video a"));
		}
		if(videoLinks.length>0){
			videoLinks.invoke("observe","click",function(event){
				event.stop();
				displayPanel(this,"video");
			});
		}
		emailEvents();
	}catch(err){
		alert(err.message);
	}
}

//addLoadEvent(assignPanelLinks);

function constructPanel(){
	// there are actually 2 panels.  One to provide the transparent black ("backdrop_panel"), another ("media_panel") that is exactly the same
	// shape and size to hold the components (prevents use of transparent PNGs)
	var media_panel = new Element('div',{'id':"media_panel"});
	var backdrop_panel = new Element('div',{'id':"backdrop_panel"});
	$$("body")[0].insert({'bottom':media_panel});
	$$("body")[0].insert({'bottom':backdrop_panel});
	// create the close button
	var panelCloseButton = new Element('a',{'href':'javascript:void(0)','id':'physician_close_btn'}).update("close").observe('click',closePanel);
	var panelCloseDiv = new Element('div',{'id':'close_media_panel'});
	$("media_panel").insert({'bottom':panelCloseDiv});
	$('close_media_panel').insert(panelCloseButton);
	//$("close_media_panel").onclick=closePanel;
	if(Prototype.Browser.IE6){
		$("backdrop_panel").setStyle({
			backgroundColor: '#000',
			position: "absolute",
			top: document.viewport.getScrollOffsets()[1]+"px",
			left: document.viewport.getScrollOffsets()[0]+"px",
			width: document.viewport.getWidth()+"px",
			height: document.viewport.getHeight()+"px",
			zIndex: "10000",
			display: "none"
		});
		$("media_panel").setStyle({
			position: "absolute",
			top: document.viewport.getScrollOffsets()[1]+"px",
			left: document.viewport.getScrollOffsets()[0]+"px",
			width: document.viewport.getWidth()+"px",
			height: document.viewport.getHeight()+"px",
			zIndex: "10001",
			display: "none"
		});
		$$("body select").each(function(element){
			element.setStyle({
				visibility: "hidden"
			});
		});
	}else{
		$("backdrop_panel").setStyle({
			backgroundColor: '#000',
			position: "fixed",
			top: "0px",
			left: "0px",
			width: document.viewport.getWidth()+"px",
			height: document.viewport.getHeight()+"px",
			zIndex: "10000",
			display: "none"
		});
		$("media_panel").setStyle({
			position: "fixed",
			top: "0px",
			left: "0px",
			width: document.viewport.getWidth()+"px",
			height: document.viewport.getHeight()+"px",
			zIndex: "10001",
			display: "none"
		});
	}
	//$("close_media_panel").hide();
	appearPanels();
}

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6;

function appearPanels(){
	if(Prototype.Browser.IE6){
		$$("body select").each(function(element){
			element.setStyle({
				visibility: "hidden"
			});
		});
	}
	$$("body")[0].setStyle({
		position: "relative"
	});
	//$("backdrop_panel").show();
	//$("media_panel").show();
	$("backdrop_panel").appear({duration:panel_duration,from:0.0,to:0.7,afterFinish:function(){
		$("media_panel").show();
		/*$("media_panel").appear({duration:panel_duration,afterFinish:function(){
			if (Prototype.Browser.IE){
				$("media_panel").style.filter='alpha(opacity=100)';
			}
		}});*/
	}});
	$("close_media_panel").show();
}


function closePanel(){
	if(playerObjectExists){
		try{
			playerObject.sendEvent("PLAY","false");
		}
		catch(e){
		}
	}
	
	clearTimeout(panel_close_handler);
	$("backdrop_panel").fade({duration:panel_duration});
	$("media_panel").fade({duration:panel_duration,afterFinish:function(){
		if($$("#close_media_panel a").length==0){
			$("close_media_panel").update();
			$("close_media_panel").insert($("physician_close_btn"));
		}
		$$("#media_panel .big_media").invoke('remove');
		if($("media_panel").hasClassName('email_form')){$("media_panel").removeClassName("email_form")};
	}})	
	Event.stopObserving($$("body")[0],'keypress',keyPressHandler);
	//Event.stopObserving(window,'scroll',scrollHandler);
	$$("body")[0].setStyle({
		position: "static"
	});
	$$("body select").each(function(element){
		element.setStyle({
			visibility: "visible"
		});
	});
}

function keyPressHandler(e){
	var kC = (window.event)?event.keyCode:e.keyCode;
	var Esc = (window.event)?27:e.DOM_VK_ESCAPE;
	if(kC==Esc) closePanel();
}


function scrollHandler(){
	if(Prototype.Browser.IE6){
		$("backdrop_panel").setStyle({
			top: document.viewport.getScrollOffsets()[1]+"px",
			left: document.viewport.getScrollOffsets()[0]+"px"
		});
		
		$("media_panel").setStyle({
			top: document.viewport.getScrollOffsets()[1]+"px",
			left: document.viewport.getScrollOffsets()[0]+"px"
		});
	}else{
		// nothing necessary
	}

}

function checkPanel(){
	// if panels already exist, just show them.
	if($("media_panel") && $("backdrop_panel")){
		// should reassign sizes to panels
		$("backdrop_panel").setStyle({
			width: document.viewport.getWidth()+"px",
			height: document.viewport.getHeight()+"px"
		});
		$("media_panel").setStyle({
			width: document.viewport.getWidth()+"px",
			height: document.viewport.getHeight()+"px"
		});
		appearPanels();
	}else{
		constructPanel();
	}
}

function displayPanel(el,mediaType){
	var mediaPath = el.href;	
	var mediaID = "panel_media";
	checkPanel();
	Event.observe($$("body")[0],'keypress',keyPressHandler);
	Event.observe(window,'scroll',scrollHandler);
	// if unique media has been used before, it should not be replaced
	if($(mediaID+"_wrapper")){
		$(mediaID+"_wrapper").show();
	}else{
		// no media, create wrapper with "big_media_content" inside.  place at top so that close button is always at bottom.
		createPanelMedia(mediaPath,mediaType,mediaID);
	}	
}

function createPanelMedia(mediaPath,mediaType,mediaID){
	var video_width = "400";
	var video_height = "359";
	var mediaDiv = new Element('div',{'id':mediaID+"_wrapper",className:'big_media'}).update(new Element('div',{'id':mediaID,className:'big_media_content'}));
	$("media_panel").insert({'top':mediaDiv});
	jwPlayer(mediaType,escape(mediaPath),"true","","",video_width,video_height,mediaID,'big_media_content');
}


function jwPlayer(mediaType,mediaPath,autostart_value,thumbnailPath,skinpath,jwWidth,jwHeight,mediaID,mediaClass){
	
	var flashvars = {};
	flashvars.file = mediaPath;
	flashvars.autostart = autostart_value;
	flashvars.stretching = 'uniform';
	flashvars.shuffle = 'false';
	flashvars.image = thumbnailPath;
	flashvars.skin = '/eha_chs_v1/swf/nmh-skin.swf';
	flashvars.width = jwWidth;
	flashvars.height = jwHeight;
	flashvars.type = mediaType;
	
	var params = {};
	params.wmode = 'transparent';
	params.allowfullscreen = 'true';
	
	var attributes = {};
	attributes.id = mediaID;
	attributes.styleclass = mediaClass;
	attributes.name = mediaID;
	
	swfobject.embedSWF('/eha_chs_v1/swf/player.swf',mediaID,jwWidth,jwHeight,'9.0.0',false,flashvars,params,attributes);
}

var playerObject = null;
var playerObjectExists = false;
function playerReady(obj){
	playerObject = $(obj.id);
	playerObjectExists = true;
}


function emailEvents(){
	if($$("#profile_tools .email a")[0]){
		$$("#profile_tools .email a")[0].onclick = function(){
			var assetid = $$('.physician_profile')[0].id;
			displayForm(assetid);
			return false;
		}
	}
	if($$("#results .actions .email a")[0]){
		$$("#results .actions .email a").each(function(element){
			element.onclick = function(){
				var assetid = $(this).up("li.result").id;
				assetid = assetid.replace("result","");
				displayForm(assetid);
				return false;
			};
		});
	}
}

function systemMessage(messageString,milliseconds_int){
	checkPanel();
	$$('.big_media').invoke('remove');
	if($("panel_system_message")){
		$("panel_system_message").down("p").update(messageString);
		$("panel_system_message").appear({duration:panel_duration});
	}else{
		var panel_system_message = new Element('div',{'id':'panel_system_message'}).update(new Element('p').update(messageString)).addClassName("big_media");
		$("media_panel").insert({'top':panel_system_message});
	}
	panel_close_handler = setTimeout("closePanel()",milliseconds_int);
}

function displayForm(assetid){
	checkPanel();
	$$('.big_media').invoke('remove');
	
	if($("physician_email_form"+assetid)){
		//$("physician_email_form"+assetid).show();
		$("physician_email_form"+assetid).remove();
	}else{
		
		try{
		
			var parameters = {
				"sitepfx":"Core2",
				"eHA_page_description":assetid,
				"mode":"email"
			};
			/*if(assetid && assetid!==""){
				
			}else{
				assetid = getMetaContents("eHA_Index_Id");
			}*/
			parameters.physician_id = assetid;
			var actionPath = findADoctorSendEmail+"&"+$H(parameters).toQueryString();
			//console.log(actionPath);
			var formDiv = new Element("div",{"id":"physician_email_form"+assetid}).addClassName("physician_email_form").addClassName("big_media");
			var fieldsetElement = new Element("fieldset");
			var legendElement = new Element("legend").update("Email this Profile");
			var formElement = new Element("form",{"action":actionPath,"method":"get"});
			formElement.onsubmit = function(){
				return submitPhysicianEmailForm(this);
			};
			var labelTo = new Element("label",{"for":"email_to"+assetid}).update("To:");
			var inputTo = new Element("input",{"type":"text","value":"","name":"email_to","id":"email_to"+assetid}).addClassName("email_to");
			var errorTo = new Element("span",{"style":"display:none;"}).addClassName("email_to_error").update("Please enter a valid email address.");
			inputTo.onkeypress = function(){
				physicianEmailKeyPress(this);
			};
			var labelFrom = new Element("label",{"for":"email_from"+assetid}).update("From:");
			var inputFrom = new Element("input",{"type":"text","value":"","name":"email_from","id":"email_from"+assetid}).addClassName("email_from");
			var errorFrom = new Element("span",{"style":"display:none;"}).addClassName("email_from_error").update("Please enter a valid email address.");
			inputFrom.onkeypress = function(){
				physicianEmailKeyPress(this);
			};
			var responseSpan = new Element("span",{"style":"display:none;"}).addClassName("physician_email_response");
			var inputSubmit = new Element("input",{"type":"submit","value":"Send","id":"physician_email_submit"}).addClassName("physician_email_submit");
			var inputCancel = new Element("input",{"type":"button","value":"Cancel","id":"physician_email_cancel"}).addClassName("physician_email_submit").observe('click',closePanel);
			var ulElement = new Element("ul");
			var liFrom = new Element("li");
			var liTo = new Element("li");
			var termsLink = new Element("a",{href:"/listing/classListing/emailterms",target:"_blank"}).update("Terms of E-mail Communication.");
			var liTerms = new Element("li");
			liTerms.insert(new Element('input',{type:'checkbox',name:'acceptTerms','id':'acceptTerms'}));
			liTerms.insert(new Element("label",{'for':'acceptTerms','id':'acceptTermsLabel'}).update("I Accept the "));
			liTerms.insert(termsLink);
			liTerms.insert(new Element("span",{"style":"display:none;"}).addClassName("checkbox_error").update("You must accept the terms"));
			var liSubmit = new Element("li");
			liTo.insert({"bottom":labelTo});
			liTo.insert({"bottom":inputTo});
			liTo.insert({"bottom":errorTo});
			liFrom.insert({"bottom":labelFrom});
			liFrom.insert({"bottom":inputFrom});
			liFrom.insert({"bottom":errorFrom})
			
			liSubmit.insert({"bottom":responseSpan});
			liSubmit.insert({"bottom":$("physician_close_btn")});
			
			liSubmit.insert(new Element('span',{'id':'submit_span'}).insert(new Element('span').insert(inputSubmit)));
			liSubmit.insert(new Element('span',{'id':'cancel_span'}).insert(new Element('span').insert(inputCancel)));
			//liSubmit.insert({"bottom":inputSubmit});
			//liSubmit.insert({"bottom":inputCancel});
			
			ulElement.insert({"bottom":liTo});
			ulElement.insert({"bottom":liFrom});
			ulElement.insert({"bottom":liTerms});
			ulElement.insert({"bottom":liSubmit});
			
			formElement.update(ulElement);
			
			fieldsetElement.insert({"bottom":legendElement});
			fieldsetElement.insert({"bottom":formElement});
			
			formDiv.update(fieldsetElement);
			
			$("close_media_panel").update("Email this page");
			$("media_panel").addClassName("email_form");
			$("media_panel").insert({'bottom':formDiv});
			
		}catch(err){
			console.log(err);
		}
	}
	Event.observe($$("body")[0],'keypress',keyPressHandler);
	Event.observe(window,'scroll',scrollHandler);
}

function physicianEmailAction(thisForm){
	var URL = $(thisForm).action+"&"+$(thisForm).serialize();
	new Ajax.Request(URL,
	{
	    method:'get',
	    onCreate: function(){
		    $(thisForm).down(".physician_email_response").update("Sending Email . . .");
		    $(thisForm).down(".physician_email_response").appear({duration:panel_duration});
	    },
	    onSuccess: function(transport){
	    },
	    onComplete: function(transport){
		    if(transport.responseText.indexOf("success")!=-1){
			    // success text has been returned
			    $(thisForm).down(".physician_email_response").update("Email sent!");
			    PhysicianToEmailAddress = $(thisForm).down(".email_to").value;
			    $(thisForm).down(".physician_email_response").removeClassName("failure").addClassName("success");
			    $(thisForm).down(".physician_email_response").appear({duration:panel_duration});
		    }else{
			    $(thisForm).down(".physician_email_response").update("Failed to send Email!");
			    $(thisForm).down(".physician_email_response").addClassName("failure");
			    $(thisForm).down(".physician_email_response").appear({duration:panel_duration});
		    }
	    },
	    onFailure: function(){
		    $(thisForm).down(".physician_email_response").addClassName("failure");
			$(thisForm).down(".physician_email_response").update("Request failed!");
		}
	});
}
var PhysicianToEmailAddress = "";

function submitPhysicianEmailForm(thisForm){
	if($(thisForm).down(".physician_email_response").innerHTML.indexOf("sent")!=-1 && PhysicianToEmailAddress==$(thisForm).down(".email_to").value){
		// email already sent!
		$(thisForm).down(".physician_email_response").update("Email to this address already sent!");
		return false;
	}else{
		var isValid = true;
		if(checkEmail($(thisForm).down(".email_to"))){
			$(thisForm).down(".email_to_error").setStyle({display:'none'});
			// good email address, check from
		}else{
			// to field is bad
			$(thisForm).down(".email_to_error").blindDown({duration:panel_duration});
			isValid = false;
		}
		if(checkEmail($(thisForm).down(".email_from"))){
			// good email address, proceed with submit
			$(thisForm).down(".email_from_error").setStyle({display:'none'});
		}else{
			// from field is bad
			$(thisForm).down(".email_from_error").blindDown({duration:panel_duration});
			isValid = false;
		}
		if($("acceptTerms").checked==true){
			// submit via AJAX because we don't actually want to leave the page.
			$(thisForm).down(".checkbox_error").setStyle({display:'none'});
		}else{
			// from field is bad
			$(thisForm).down(".checkbox_error").blindDown({duration:panel_duration});
			isValid =  false;
		}
		if(isValid){physicianEmailAction(thisForm);}
		return false;
	}
}

function physicianEmailKeyPress(el){
	if(checkEmail(el)){
		// good email address
		$(el).addClassName("good");
	}else{
		$(el).removeClassName("good");
	}
	$(el).next("span").hide();
}

function test(src) {
	var emailReg = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;
	var regex = new RegExp(emailReg);
	return regex.test(src);
}

function checkEmail(inputEl) {
	var emailValue = inputEl.value;
	if (emailValue!="" && test(emailValue)) {
		return true;
	} else {
		return false;
	}

}


//addLoadEvent(FindADoctor_addSearchPageEvents);

//addLoadEvent(FindADoctor_addSearchResultsEvents);

//addLoadEvent(FindADoctor_readHash);

function clearCookie(){
	setCookie("eHA_FindADoctor_Favorites_nm","");
}


//// Browse By Name, Browse By Speciality JS

var alphabetList = {
	init:function(obj){
		this.ajax.init(obj.serverCall);
		this.alphabetListUI.init(obj);
		this.alphabetListUI.assignEvents();
		SWFAddress.addEventListener(SWFAddressEvent.INTERNAL_CHANGE, alphabetList.letterChange);
		SWFAddress.addEventListener(SWFAddressEvent.EXTERNAL_CHANGE, alphabetList.letterChange);
		if(SWFAddress.getValue().length > 1){this.ajax.loadFromURL()}
	},
	letterChange:function(){
		alphabetList.ajax.loadFromURL();
	},
	alphabetListUI:{
		init:function(obj){
			if(SWFAddress.getValue()=='/'){SWFAddress.setValue("letter=A")}
			this.listSelector=obj.listSelector;
			this.mainSelector=obj.mainSelector;
			document.observe('physicianEvent:xhrComplete',this.onNewLetterLoaded.bind(this));
			document.observe('physicianEvent:xhrCreate',this.showLoading.bind(this));
		},
		assignEvents:function(){
			if($$(this.listSelector+" li a")){
				$$(this.listSelector+" li a").each(function(element){
					element.observe('click',function(event){
						SWFAddress.setValue("letter="+this.innerHTML);
						Event.stop(event);
					});
				});
			}
			if($$('div.bottom div.pagination_inner li a').length>0){
				$$('div.bottom div.pagination_inner li a').each(function(element){
					element.observe('click',function(event){
						var hashParams = {};
						var el=Event.element(event);
						if(el.up('li').hasClassName('next')==true){
							if(hashParams['startindex']){hashParams['startindex']=parseInt(hashParams['startindex'])+1}
							else(hashParams['startindex']=2)
						}
						else if(el.up('li').hasClassName('previous')==true){
							if(hashParams['startindex']){hashParams['startindex']=parseInt(hashParams['startindex'])-1}
							//else(hashParams['startindex']=el.innerHTML)
						}
						else{hashParams['startindex']=el.innerHTML}
						SWFAddress.setValue(Object.toQueryString(hashParams));
						Event.stop(event);
					});
				});
			}
		},
		showLoading:function(){
			this.loadingImage = new Element("img",{'src':ajaxWaitGraphicURL,'alt':'Please Wait.',className:'ajax_loader'});
			$$('body')[0].setStyle({cursor:'progress'});
			$$(this.mainSelector)[0].replace(this.loadingImage);
		},
		onNewLetterLoaded:function(event){
/*
			if(!Prototype.Browser.IE){
				var newSt=SHARETHIS.addEntry(
				{
					title:encode_utf8(document.title),
					url:encode_utf8(document.location.href)
				},{
					button:false,
					embeds:true
				});
				newSt.attachButton($$('.page_toolbar_sharethis a')[0]);
				SHARETHIS.onReady();
			}
*/
			$$('body')[0].setStyle({cursor:'auto'});
			$$("#content_body .ajax_loader")[0].replace(event.memo.transport.responseText);
			$$(this.listSelector+" li.sel").invoke("removeClassName","sel");
			var hashParams = SWFAddress.getValue().replace('/','').toQueryParams();
			$$(this.listSelector+' .'+hashParams['letter']).each(function(element){
				$(element).up("li").addClassName("sel");
			});
			if($$("#content_body .page_title")[0]){
				$$("#content_body .page_title")[0].update(hashParams['letter']);
			}
			if($$('div.bottom div.pagination_inner li a').length>0){
				$$('div.bottom div.pagination_inner li a').each(function(element){
					element.observe('click',function(event){
						var el=Event.element(event);
						if(el.up('li').hasClassName('next')==true){
							if(hashParams['startindex']){hashParams['startindex']=parseInt(hashParams['startindex'])+1}
							else(hashParams['startindex']=2)
						}
						else if(el.up('li').hasClassName('previous')==true){
							if(hashParams['startindex']){hashParams['startindex']=parseInt(hashParams['startindex'])-1}
							//else(hashParams['startindex']=el.innerHTML)
						}
						else{hashParams['startindex']=el.innerHTML}
						SWFAddress.setValue(Object.toQueryString(hashParams));
						Event.stop(event);
					});
				});
			}
		}
	},
	ajax: {
		init:function(url){
			this.currentXHRObj={};
			this.isLoading=false;
			this.serverCall=url;
		},
		loadFromURL:function(){
			if(this.isLoading==true){this.currentXHRObj.abort();}
			document.fire('physicianEvent:xhrOpen');
			this.isLoading=true;
			this.currentXHRObj = new Ajax.Request(this.serverCall,{
				method:'get',
				asynchronous:true,
				parameters: SWFAddress.getValue().replace('/',''),
				onCreate: function(){document.fire('physicianEvent:xhrCreate')},
				onSuccess: function(transport){},
				onComplete: function(transport){
					document.fire('physicianEvent:xhrComplete',{transport:transport});
					this.isLoading=false;
				}.bind(this),
				onFailure: function(){/*alert('Something went wrong...');*/}
			});
		}
	}
}
function Physician_Browse_Specialty_listing_replace(letter){
	alert('Physician_Browse_Specialty_listing_replace');
}
function Physician_Browse_Specialty_alphabet_link_events(){
	alphabetList.init({serverCall:specialtyListURL,listSelector:'.alphabetical_list',mainSelector:'#specialty_list'});
}

function Physician_Browse_Name_listing_replace(letter){
	alert('Physician_Browse_Name_listing_replace');
}


function Physician_Browse_Name_select_letter(el){
	alert('Physician_Browse_Name_select_letter');
}




function Physician_Browse_Name_alphabet_link_events(){
	alphabetList.init({serverCall:subTemplatePhysicianGroupDirectory,listSelector:'.alphabetical_list',mainSelector:'#physician_directory'});
}


					// ##### FUNCTION: addLoadEvent
					// #####  PURPOSE: appends a function to the window.onload event handler 
					function addLoadEvent(func) {
						var oldonload = window.onload;
						if (typeof window.onload != 'function') {
							window.onload = func;
						} else {
							window.onload = function() {
								if (oldonload) {
									oldonload();
								}
								func();
							}
						}
					}

