/**
 * @fileOverview This file contains our main eHA code
 * @author <a href='http://wiki.element115.net/index.php/User:Schopra'>schopra</a>
 * @author <a href='http://wiki.element115.net/index.php/User:Eschleeper'>eschleeper</a> 
 */

document.observe("dom:loaded", function(){
	try{
		if($$(".eHA_LandingPage_C #content_body .HomePageTab")[0]){
			if($$(".eHA_LandingPage_C #content_body .HomePageTab").size()>1){eHA.HomePageTabs.init();}
		}
		
		//if($$(".eHA_LandingPage_C div.vcalendar")[0]){AH_eventsHome.init($$(".eHA_LandingPage_C #content_body div.calendarModule")[0]);	}
		
		if($$('body')[0].hasClassName('SearchPage')===true){
			if($("content_main")){
				pageToolBarFunctions = new PageToolBarFunctions({textDiv:'content_main'});
			}
			// SearchPageExpandCollapse.childrenContainerSelector='.category_result';
			// SearchPageExpandCollapse.childrenSelector='.result';
			// SearchPageExpandCollapse.init('resultsMain');
		}
		else {
			if($("content_body")){
				pageToolBarFunctions = new PageToolBarFunctions({textDiv:'content_body'});
			}
		}
		if(typeof pageToolBarFunctions!=="undefined"){
			if(!$$("body.AH_HomePage_Type8")[0]){
			pageToolBarFunctions.shareThisSelector=' .addthis_button';
			pageToolBarFunctions.registerToolBars('#page_toolbar');
			}
		}
		searchFunctions = new SearchFunctions();
		if($$('#content_main #content_body .tabs')[0]){new TabList($$('#content_main #content_body .tabs ul li ul')[0]);}
		if($('content_navigation')){MoreButtons.createMoreButtons();}
		if($$('body')[0].hasClassName('Press_Release_Archive')===true){TreeTab.init('press_release_detail_page_list')}
		if($('content_main') && $('content_main').hasClassName('provider_search')===true){
			mediaDirectory.usePanels = true;
			Physician.init();
		}
		if($$('body')[0].hasClassName('Profile')===true){
			mediaDirectory.usePanels = true;
			PhysicianProfile.init();
		}
		
		
		if($$("div.vcalendar")[0]){eHA.calendar.init();}
		//if($('featured_news')) Tabular.Initial("featured_news","newsModule","news","h3");//containerId, TabTitleSectionClass,containerSectionClass, TitleElement

		eHA.loadMeta();
		NavigationSelect.setSelectedOpen("div#content_navigation div.page_list",eHA.assetid);
		NavigationSelect.setSelected("div#primary_navigation",eHA.assetid);
		NavigationSelect.setSelected("div#action_toolbar",eHA.assetid);
		NavigationSelect.setSelected("div#global_navigation",eHA.assetid);
		NavigationSelect.setSelected("div#portal_navigation",eHA.assetid);
		NavigationSelect.setParentClasses("#content_navigation>.page_list>ul>li>ul>li","ul>li");
		if(eHA.assetid !== eHA.categoryid){
			NavigationSelect.setSelected("div#primary_navigation",eHA.categoryid);
			NavigationSelect.setSelected("div#action_toolbar",eHA.categoryid);
			NavigationSelect.setSelected("div#global_navigation",eHA.categoryid);
		}
		// googleMaps.register({address:"google_map_address"});
		if($('caurosel')!=null){
			window.AHPromoModules = new SlidingItems({selectors:{item:"#caurosel ul li",groupDiv:"#caurosel ul",controlsParent:"#caurosel"},groupSize:3,offsetDistance:298,duration:0.5});
		}
		if($('HomePage_spotlights')!=null){
			window.AHPromoModules2 = new SlidingItems({selectors:{item:"#HomePage_spotlights ul li",groupDiv:"#HomePage_spotlights ul",controlsParent:"#HomePage_spotlights"},groupSize:1,offsetDistance:322,duration:0.5});
		}

		mediaDirectory.assignMediaEvents();
		if($("bread_crumbs")){
			psBreadcrumbs.register("bread_crumbs",{protect:[1,2,-2,-1]});
		}
		if($$("div.newsModule")[0]){
			if(AH_newsHub.check()){
				AH_newsHub.init(function(){
					eHA.news.init();
				});
			}else{
				eHA.news.init();
			}
		}
		if($$("div.locationsModule")[0]){
			if(AH_locationsHub.check()){
				AH_locationsHub.init(function(){
					eHA.locations.init();
				});
			}else{
				eHA.locations.init();
			}
		}
		if(eHA.assettype && eHA.assettype==="eHA_Location_C"){
			// this is a location page, begin loading map
			eHA.locations.mapID = eHA.assetid;
			eHA.locations.startMap(function(){AH_locationsDetail.init();});
		}
		if($$("a.document")[0]){
			eHA.documents.init();
		}
		if($$("div.graphModule")[0] || $$("div.protochart-wrapper")[0]){
			eHA.graph.init();
		}
		if($$(".ctModule").size()>0){
			eHA.ct.init();
		}
		if($$(".poll")){
			eHA.polls.init();
		}
		if($$('a.iframe-modal').length > 0){
			eHA.iFramePanels.init('a.iframe-modal',{'width':800,'height':530});
		}
		if($$(".eHA_LandingPage_C #content #hero li.first")[0]){
			AH_hero.init();
		}
		
		if($$(".eHA_Content_C.Services #content_body .services").size()>1){
			eHA.services.init();
		}
		
		if($$(".AH_HomePage_Type8 #content_body")) {FadeIn.Initial("content_body")} //when page loaded completely will display selected container  
	}catch(err){
		alert("error! "+err.toString());
	}
});

Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5),10) == 6;
Prototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5),10) == 7;

/**
 * rewrites prototype's String#unescapeHTML so that it further decodes &apos; and &quot;
 * @function
 * @return {String} decoded string
 */
String.prototype.unescapeHTML = function(){
	return this.stripTags().replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&amp;/g,'&').replace(/&apos;/g,'\'').replace(/&quot;/g,"\"");
};





/**
 * Our eHA Object.  Contains necessary javascript variables for our sites.
 * @namespace
 */
var eHA = {
	Version: '3.3.5',
	Site: 'demo',
	requiredFlashVersion: '9.0.0',
	includeScripts: "media,panels,swfobject,qtobject", // possible scripts to include
	/**
	 * Loads certain meta values into eHA object.  eHA.assetid, eHA.categoryid
	 * @function
	 */
	loadMeta: function(){
		if(this.meta("Asset_Id")){
			this.assetid = this.meta("Asset_Id");
		}
		if(this.meta("Asset_Type")){
			this.assettype = this.meta("Asset_Type");
		}
		if(this.meta("eHA_Category_Id")){
			this.categoryid = this.meta("eHA_Category_Id");
		}
	},
	/**
	 * Part of old "scriptaculous-style" inclusion of other libraries.
	 * @deprecated
	 * @function
	 */
	require: function(libraryName) {
		// inserting via DOM fails in Safari 2.0, so brute force approach
		document.write('<script type="text/javascript" src="'+libraryName+'"><\/script>');
	},
	REQUIRED_PROTOTYPE: '1.6.1',
	/**
	 *Part of old "scriptaculous-style" inclusion of other libraries.
	 *@deprecated
	 *@function 
	 */
	load: function() {
		function convertVersionString(versionString){
			var r = versionString.split('.');
			return parseInt(r[0],10)*100000 + parseInt(r[1],10)*1000 + parseInt(r[2],10);
		}
	
		if((typeof Prototype=='undefined') || 
				(typeof Element == 'undefined') || 
				(typeof Element.Methods=='undefined') ||
				(convertVersionString(Prototype.Version) < 
						convertVersionString(eHA.REQUIRED_PROTOTYPE))){
			throw("eHA requires the Prototype JavaScript framework >= " +
					eHA.REQUIRED_PROTOTYPE);
		}
		$A(document.getElementsByTagName("script")).findAll( function(s) {
			return (s.src && s.src.match(/eHA\.js(\?.*)?$/));
		}).each( function(s) {
			var path = s.src.replace(/eHA\.js(\?.*)?$/,'');
			var includes = s.src.match(/\?.*load=([a-z,]*)/);
			(includes ? includes[1] : eHA.includeScripts).split(',').each(
					function(include) { eHA.require(path+include+'.js'); });
		});
	},
	/**
	 * returns "content" attribute of requested meta tag
	 * @function
	 * @param {String} metaName
	 * @example alert(eHA.meta("Asset_Id")); // will output "1264128919400" (or something)
	 * @returns {String} value of meta's "content" or false if metaName can't be found
	 */
	meta: function(metaName){
		if($$("meta[name="+metaName+"]")[0]){
			return $$("meta[name="+metaName+"]")[0].readAttribute("content");
		}else{
			return false;
		}
	},
	/**
	 * eHA.log provides a namespace for managing the output and numbering of JavaScript log messages
	 * that are produced by our various JavaScripts
	 * @namespace
	 */
	log: {
		// there are 4 log levels, 0 = off, 1 = error, 2 = warning, 3 = debug
		verbosity_level: 0,
		messages_total: 0, // number of total messages
		messages_1: 0, // number of error messages
		messages_2: 0, // number of warning messages
		messages_3: 0, // number of debug messages
		_ERROR: 1,
		_WARNING: 2,
		_DEBUG: 3,
		/**
		 * Creates a new log.  This function is invoked in several places throughout our code.  Formats outputString for use with
		 * function eHA.log.output()
		 * @function
		 * @param {String} log_string the log message that you would like to output
		 * @param {Integer} log_level_int the log level integer value for the message you would like to output
		 */
		create: function(log_string,log_level_int){
			if(typeof log_level_int==="undefined" || log_level_int>this._DEBUG || log_level_int<this._ERROR){
				// default to "debug"
				log_level_int = this._DEBUG;
			}
			if(log_level_int<4 && log_level_int>0){
				this.messages_total++;
				eval("this.messages_"+log_level_int+"++;");
				if(this.verbosity_level>=log_level_int){
					// this message should be displayed, prepare outputString
					eval("var message_number = this.messages_"+log_level_int);
					var message_name = "ERROR MESSAGE";
					if(log_level_int==this._WARNING){ message_name = "WARNING MESSAGE"; }
					if(log_level_int==this._DEBUG){ message_name = "DEBUG MESSAGE"; }
					var now = new Date();
					var timeString = now.getHours()+":"+now.getMinutes()+":"+now.getSeconds()+"."+now.getMilliseconds();
					var outputString = message_name+" "+timeString+" "+message_number+": "+log_string;
					this.output(outputString);
				}
			}
		},
		/**
		 * this function does nothing, by design.  Use the eHA.log.output bookmarklet to enable output when debugging.
		 * @function
		 * @param {String} outputString
		 */
		output: function(outputString){
			// placeholder function.  redefine this function in order to see output
		}
	},
	/**
	 * loads a value from the class of an HTML element.  Depends upon the syntax "name-value".
	 * @function
	 * @param {Element} el
	 * @param {String} requestedName
	 * @returns {String} requestedValue
	 */
	loadValuefromClass: function(el, requestedName){
		var requestedValue = false;
		var classNames = el.className.split(" ");
		for(var cni=0;cni<classNames.length;cni++){
			if(classNames[cni].indexOf('-')!=-1){
				classNameSplit = classNames[cni].split('-');
				if(classNameSplit[0]==requestedName){
					requestedValue = classNameSplit[1];
				}
			}
		}
		return requestedValue;
	},
	/**
	 * an array of expected attributes from an HTML element. This is used in converting an HTML element into an Object Literal
	 * @parameter
	 */
	elementAttributeArray: ["class","id","title","style","dir","lang","cite","classid","type","href","src","alt","name","value","for","action","method","target","enctype","accept","accepty-charset","longdesc","height","width","disabled","selected","checked","profile","size","multiple","label","xmlns","maxlength","cols","rows"],
	
	/**
	 * turns an HTML element into a javascript object
	 * uses all attributes of HTML element (from above array)
	 * as well as any name-value pairs in "className" to set properties
	 * NOTE: className property will also continue to contain all
	 * classes
	 * 
	 * @function
	 * @param {Element} el
	 * @returns {Object}
	 */
	elementToObjectLiteral: function(el){
		var objectLiteral = {};
		for (var i=0; i<eHA.elementAttributeArray.length; i++){
			var thisAttrName = eHA.elementAttributeArray[i];
			if(thisAttrName.indexOf("class")!=-1){ thisAttrName = "className"; }// this is necessary for IE
			var thisAttrValue = $(el).readAttribute(thisAttrName);
			if(thisAttrValue!==null){
				try{
					eval("objectLiteral."+thisAttrName+"='"+thisAttrValue+"'");
				}catch(err){
					eHA.log.create(err.name+": "+err.message+" -- objectLiteral."+thisAttrName+"='"+thisAttrValue+"'", 1);
				}
			}
		}
		if(el.className){
			var classNames = el.className.split(" ");
			for(var cni=0;cni<classNames.length;cni++){
				if(classNames[cni].indexOf('-')!=-1){
					classNameSplit = classNames[cni].split('-');
					eval("objectLiteral."+classNameSplit[0]+"='"+classNameSplit[1]+"'");
				}
			}
		}
		return objectLiteral;
	},
	/**
	 * a utility function to add a child to an object and explicitly point the child.parent to the parent
	 * @function
	 * @param {Object} ob the parent object
	 * @param {String} childName the name of the child
	 * @param {Object} childOb the child object
	 */
	addChild: function(ob, childName, childOb){
	   ob[childName] = childOb;
	   childOb.parent = ob;
	}
};


eHA.services = {
		init: function(){
			if($$(".eHA_Content_C #content_body .services").size()>1){
				
				this.tabs = new Array();
				this.links = new Array();
				this.tabToSelect =parseInt(window.location.hash.substring(1)); // reverts hash value into intiger 
				
				var linksUL = new Element("ul");
				var linksDiv = new Element("div",{className:"tab_navigation Navigation"}).update(linksUL);
				
				$$(".eHA_Content_C #content_body .services").each(function(el,i){
					
					var name = el.down("h3").innerHTML;
					var thisA = new Element("a",{href:""}).update(name);
					var thisLI = new Element("li").update(thisA);
					
					if(i!==0){
						el.hide();
					}else{ //select per default first listed 
						el.addClassName("sel");
						thisLI.addClassName("sel");

					}
					
					thisA.observe("click",function(evt){
						evt.stop();
						this.clearSelection();
						this.select(i);
					}.bind(this));
					
					linksUL.insert({bottom:thisLI});
					
					this.tabs.push({name:name,el:el});
					this.links.push({name:name,el:thisLI});
					
				}.bind(this));
				
				$$(".eHA_Content_C #content_body .services")[0].insert({before:linksDiv});
				
				if((this.tabToSelect)) { // if # has been added select element that match # value
					this.clearSelection();
					this.select(this.tabToSelect);	
					//window.location = window.location.href.replace( /#.*/, "");	//clear hash			
					}				
			}
		},
		clearSelection: function(){
			$A(this.tabs).each(function(tab){
				tab.el.removeClassName("sel").hide();
			});
			$A(this.links).each(function(link){
				link.el.removeClassName("sel");
			});
		},
		select: function(i){
			if(this.tabs[i]){
			this.tabs[i].el.addClassName("sel").show();
			this.links[i].el.addClassName("sel");
			}else {alert('Active tab could not be located. Error: TABS_SERVICES')}
		}
	};


eHA.iFramePanels = {
		init:function(selector,options){
			if(options.width!==null){this.width = options.width;}
			else{this.width = 800;}
			if(options.height!==null){this.height = options.height;}
			else{this.height = 400;}
			panels.construct();
			$$(selector).each(function(el,i){
				el.observe('click',function(evt){
					Event.stop(evt);
					var iFrame = new Element('iframe',{'src':evt.element().href,
						'height':this.height+"px",'width':this.width+"px"});
					var panelItem = new panelObject({
						html:iFrame,
						panelid:"panel_media",
						width: this.width
					});
					panelItem.insert();
					panels.appear();
				}.bind(this));
			}.bind(this));
		}
};

/**
 * this namespace manages the functions that are used to assign select classes to certain navigation HTML within a page.
 * @namespace
 */
var NavigationSelect = {
	selectedClass: " sel",
	openClass: "open",
	parentClass: "parent",
	setParentClasses: function(selector,childSelector){
		if($$(selector).size()>0){
			$$(selector).each(function(el){
				if(el.select(childSelector).size()>0){
					el.addClassName(this.parentClass);
				}
			}.bind(this));
		}
	},
	/**
	 * selects the nav appropriately.  Looks at UL-LIs.  if assetid matches values on any of the LIs
	 * then an appropriate class is applied
	 * @function
	 * @param {String} selector CSS selector for DIV of nav
	 * @param {String} assetid 
	 */
	setSelected: function(selector,assetid){
		if(typeof assetid !== "undefined"){
			if($$(selector)[0] && $$(selector)[0].select(".assetid-"+assetid)[0]){
				$$(selector)[0].select(".assetid-"+assetid).each(function(element){
					if($(element).up("li") && !$(element).up("li").hasClassName(this.selectedClass)){
						//$(element).up("li").className += this.selectedClass;
						$(element).up("li").addClassName(this.selectedClass);
					}else{
						if(!$(element).hasClassName(this.selectedClass)){
							//$(element).className += this.selectedClass;
							$(element).addClassName(this.selectedClass);
						}
					}
				}.bind(this));
			}
		}
	},
	/**
	 * selects the nav appropriately.  Looks at UL-LIs.  if assetid matches values on any of the LIs
	 * then an appropriate class is applied
	 * @function
	 * @param {String} selector CSS selector for DIV of nav
	 * @param {String} assetid 
	 */
	setOpen: function(selector,assetid){
		if(typeof assetid !== "undefined"){
			if($$(selector)[0] && $$(selector)[0].select(".assetid-"+assetid)[0]){
				$$(selector)[0].select(".assetid-"+assetid).each(function(element){
					if($(element).up("ul")){
						$(element).up("ul").addClassName(this.openClass);
					}
					if($(element).up("li")){
						$(element).up("li").addClassName(this.openClass);
					}
				}.bind(this));
			}
		}
	},
	/**
	 * selects the nav appropriately.  Looks at UL-LIs.  if assetid matches values on any of the LIs
	 * then an appropriate class is applied
	 * @function
	 * @param {String} selector CSS selector for DIV of nav
	 * @param {String} assetid 
	 */
	setSelectedOpen: function(selector,assetid){
		if(typeof assetid !== "undefined"){
			if($$(selector)[0] && $$(selector)[0].select(".assetid-"+assetid)[0]){
				$$(selector)[0].select(".assetid-"+assetid).each(function(element){
					if($(element).up("ul")){
						$(element).up("ul").addClassName(this.openClass);
					}
					if($(element).up("ul").up("li")){
						$(element).up("ul").up("li").addClassName(this.openClass);
					}
					if($(element).up("li") && !$(element).up("li").hasClassName(this.selectedClass)){
						$(element).up("li").className += this.selectedClass;
						$(element).up("li").addClassName(this.selectedClass);
					}else{
						if(!$(element).hasClassName("sel")){
							$(element).className += this.selectedClass;
							$(element).addClassName(this.selectedClass);
						}
					}
				}.bind(this));
			}
		}
	}
};

/**
 * manages data and functions to provide functionality for the searchpage elements to expand and collapse
 * @namespace
 */
var SearchPageExpandCollapse={
	childrenContainerSelector:'',
	childrenSelector:'',
	init:function(selector){
		$$('#'+selector+' '+this.childrenContainerSelector).each(function(element){
			var elementChildren=element.select(this.childrenSelector);
			elementChildren.each(function(result,i){
				if(i>=3){result.hide();}
			});	
			if(elementChildren.length>3){
				element.setAttribute('aria-expanded','false');
				element.insert(new Element('a',{href:''}).update('More Results from '+element.down('h2').innerHTML).addClassName('see_more').observe('click',this.handleClick.bindAsEventListener(this)));
			}
		}.bind(this));
	},
	handleClick:function(event){
		var parentDiv=Event.element(event).up(this.childrenContainerSelector);
		if(parentDiv.getAttribute('aria-expanded')=='false'){
			Event.element(event).update(Event.element(event).innerHTML.replace('More','Less'));
			Event.element(event).addClassName('open');
			parentDiv.setAttribute('aria-expanded','true');
			parentDiv.select(this.childrenSelector).invoke('show');
		}
		else{
			Event.element(event).update(Event.element(event).innerHTML.replace('Less','More'));
			Event.element(event).removeClassName('open');
			parentDiv.setAttribute('aria-expanded','false');
			parentDiv.select(this.childrenSelector).each(function(result,i){
				if(i>=3){result.hide();}
			});
		}
	}
};

/**
 * manages data and functions for some tab rollovers in navigation
 * @namespace
 */
var TabRollOvers = {
	setRollovers: function(selector){
		this.hoverSelector = selector;
		$$(this.hoverSelector).each(function(element){
			element.observe('mouseover',function(event){
				element.className=element.className+'hover';
				element.addClassName('hover');
			});
			element.observe('mouseout',function(event){
				element.removeClassName('hover');
				element.className=element.className.replace('hover','');
			});
			element.observe('click',function(event){
				window.location=this.down('a').getAttribute('href');
			});
		});
	},
	focusIndex:0,
	setTabFocus: function(selector){
		$$(selector).each(function(element,i){
			this.focusIndex++;
			element.down('a').setAttribute('tabindex',-1);
			element.setAttribute('tabindex',this.focusIndex);
			element.observe('keydown',function(event){if(event.keyCode==Event.KEY_RETURN){window.location=Event.element(event).down('a').href;}});
		}.bind(this));
	}
};

/**
 * manages data and functions to create and handle behavior for extended lists of contextual links on content pages.
 * Used chiefly for smart navigation
 * @namespace
 */
var MoreButtons = {
	relatedDivSelectors:[".smart_navigation","#clinical_trials_smart_navigation","#page_related"],
	divsToHideSelectors:[".media_wrapper",".page_general_body",".content_category_information",".page_title",".service_description",".contact_information",".release_date",".city_state","#media_contacts"],
	createMoreButtons: function(){
		$A(this.relatedDivSelectors).each(function(selector){
			$$(selector).each(function(element){
				var liArray;
			if(element.select('ul.sub li').length > 0){liArray=element.select('ul.sub li');}
			else{liArray=element.select('ul li');}
			liArray.each(function(element,i){if(i>2){ element.hide(); }});
			if(liArray.length>2){
				var moreLink=new Element('a',{href:''}).addClassName('see_more_related').update('more >>');
				element.appendChild(moreLink);
				moreLink.observe('click',function(event){
					var divCounter=0;
					var afterFinishFunction=function(){return false;};
					$A(this.divsToHideSelectors).each(function(divSelect){$$('#content_body '+divSelect).each(function(element,i){
						if(divCounter===0){afterFinishFunction=function(){ MoreButtons.showMore(moreLink.up('div')); }; }
						Effect.Fade(element,{ duration: 0.3,afterFinish:afterFinishFunction});
						divCounter++;
					});});
					if(divCounter===0){MoreButtons.showMore(moreLink.up('div'));}
				}.bind(this));
			}
			else{ if(liArray.length===0){element.hide();} }
			}.bind(this));
		}.bind(this));
	},
	showMore:function(element){
		var newElement=new Element('div').addClassName('more_related').insert(element.clone(true)).setStyle({display:'none'});
		newElement.select('.see_more_related')[0].remove();
		newElement.insert(new Element('a',{href:""}).addClassName('remove').update('Back'));
		newElement.select('.remove')[0].observe('click',function(event){Effect.Fade(newElement,{afterFinish:MoreButtons.showOriginal,duration: 0.3});}.bind(this));
		newElement.select('li').invoke('show');
		if(newElement.down('ul').select('ul').length>0){
			newElement.down('ul').addClassName('no_list_style');
		}
		if($$('#content_body .more_related')[0]){$$('#content_body .more_related')[0].remove();}
		$('content_body').appendChild(newElement);
		Effect.Appear(newElement,{ duration: 0.3});
	},
	showOriginal:function(){
		$$('#content_body .more_related').invoke('remove');
		$A(MoreButtons.divsToHideSelectors).each(function(divSelect,i){$$('#content_body '+divSelect).each(function(element){
			Effect.Appear(element,{ duration: 0.3});
		});});
	}
};
var TreeTab={
	expandableNodeCount:0,
	treeTop:null,//$('press_release_detail_page_list').down('ul'),
	init: function(selector){
		this.treeTop=$(selector).down('ul');
		this.treeTop.setAttribute('tabindex','0');
		this.treeTop.select('a').each(function(element){element.setAttribute('tabindex','-1');});
		this.treeTop.childElements().each(function(element){
			element.setAttribute('tabindex','-1');
			element.down('ul').setStyle({display:'none'});
			if(element.id===''){
				element.setAttribute('id','node_'+this.expandableNodeCount);
				this.expandableNodeCount++;
			}
			element.addClassName('collapsed');
			element.setAttribute('aria-expanded','false');
			element.observe('keydown',TreeTab.onKeypress);
			element.select('li').each(function(element){element.setAttribute('tabindex','-1');});
			element.observe('click',function(){TreeTab.handleClick(element);});
		});
		this.treeTop.observe('focus',function(){TreeTab.startKeyControls();});
	},
	handleClick:function(element){
		if(element.getAttribute('aria-expanded')=='false'){
			TreeTab.expandTreeNode(element);
			//element.siblings().each(function(treeNode){TreeTab.collapseTreeNode(treeNode)})
		}else if(element.getAttribute('aria-expanded')=='true'){
			TreeTab.collapseTreeNode(element);
		}
	},
	startKeyControls:function(){
		this.treeTop.down().focus();
	},
	onKeypress:function(event){
		if(event.keyCode==38){
			Event.stop(event);
			TreeTab.prevChild(Event.element(event));
		}else if(event.keyCode==40){
			Event.stop(event);
			TreeTab.nextChild(Event.element(event));
		}else if(event.keyCode==Event.KEY_RIGHT){
			Event.stop(event);
			TreeTab.expandTreeNode(Event.element(event));
		}else if(event.keyCode==Event.KEY_LEFT){
			Event.stop(event);
			TreeTab.collapseTreeNode(Event.element(event));
		}else if(event.keyCode==Event.KEY_RETURN){
			if(Event.element(event).down().hasClassName('media_entry')===true){
				window.location.href=Event.element(event).down().getAttribute('href');
			}
		}
		
	},
	nextChild:function(element){
		if(element.getAttribute('aria-expanded')=='true'){
			element.down('li').focus();
		}else if(element.next()===null && element.up('li')!==null){
			if(element.up('li').next()!==null){
				element.up('li').next().focus();
			}
		}else if(element.up()&&element.next()!==null){
			element.next().focus();
		}
	},
	prevChild:function(element){
		if(element.previous()!==null){
			if(element.previous().getAttribute('aria-expanded')==='true'){
				var previousChildren=element.previous().down('ul').childElements();
				previousChildren[previousChildren.length-1].focus();
			}else{
				element.previous().focus();
			}
		}else if(element.up()&&element.up('li')!==null){
			element.up('li').focus();
		}
	},
	expandTreeNode:function(element){
		if(element.down('ul')!==null && element.getAttribute('aria-expanded')=='false'){
			element.setAttribute('aria-expanded','true');
			element.removeClassName('collapsed');
			element.addClassName('expanded');
			Effect.BlindDown(element.down('ul'),{duration:0.3});
		}
	},
	collapseTreeNode:function(element){
		if(element.down('ul')!==null){
			element.removeClassName('expanded');
			element.addClassName('collapsed');
			element.setAttribute('aria-expanded','false');
			Effect.BlindUp(element.down('ul'),{duration:0.3});
		}
	}
};
var SearchFunctions=Class.create(
	/** 
	 * @lends SearchFunctions.prototype
	 * 
	 */
	{
	 /**
	  * Creates an instance of SearchFunctions
	  * @author eschleeper
	  * @param {Object} obj
	  * @constructs
	  */
	initialize: function(obj){
		this.textInputSelector = 'div#search_bar input.search_box';
		if($$(this.textInputSelector)[0]){
			$$(this.textInputSelector)[0].value = 'Search ...';
			this.initialValue = $$(this.textInputSelector)[0].value;
			$$(this.textInputSelector).each(function(element){
				element.observe('click',function(event){if(this.initialValue==element.value){element.value='';}}.bindAsEventListener(this));
				element.observe('focus',function(event){Event.element(event).up('form').addClassName('input_focus');});
				element.observe('blur',function(event){Event.element(event).up('form').removeClassName('input_focus');if(element.value===''){element.value=this.initialValue;}}.bindAsEventListener(this));
			}.bind(this));
		}
	}
});
var PageToolBarFunctions = Class.create(
	/** 
	 * @lends PageToolBarFunctions.prototype
	 * 
	 */
	{
	 /**
	  * Creates an instance of PageToolBarFunctions.  Cookie is initialized. 
	  * @author eschleeper
	  * @param {Object} obj
	  * @constructs
	  */
	initialize: function(obj){
		Cookie.init({name: eHA.Site+'_Client', expires: 365,domain:document.domain,path:"/",secure:(document.location.toString().indexOf("https")!=-1)?true:false});
		this.printSelector = ' .page_toolbar_print';
		this.pageToolBarSelector = ' .page_toolbar_text';
		this.defaultTextSizeSelector = ' .default';
		this.decreaseTextSelector = ' .decrease';
		this.increaseTextSelector = ' .increase';
		this.shareThisSelector = ' .page_toolbar_sharethis';
		
		this.saveTextSize = false;
		
		this.sizeLimits={
			minimum:{
				pixels:8,
				points:6,
				em:0.6,
				percent:60
			},
			maximum:{
				pixels:20,
				points:16,
				em:1.6,
				percent:180
			}
		};
		/*this.shareThisObj = SHARETHIS.addEntry({},{button:false});*/
		this.targetDiv = obj.textDiv;
		if(this.saveTextSize && Cookie.getData('fontSize'))
		{
			this.currentTextSize=Cookie.getData('fontSize');
			$(this.targetDiv).setStyle({fontSize:this.currentTextSize,lineHeight:this.currentTextSize});
		}
		else{
			//this.currentTextSize=$(this.targetDiv).getStyle('font-size');
		}
	},
	registerToolBars:function(selector){
		$$(selector + this.printSelector).each(function(element){
			element.observe('click',function(){window.print();});
		});
		$$(selector + this.pageToolBarSelector + this.defaultTextSizeSelector).each(function(element){
			element.observe('click',this.textSizeReset.bindAsEventListener(this));
		}.bind(this));
		$$(selector + this.pageToolBarSelector + this.decreaseTextSelector).each(function(element){
			element.observe('click',this.textSizeSmaller.bindAsEventListener(this));
		}.bind(this));
		$$(selector + this.pageToolBarSelector + this.increaseTextSelector).each(function(element){
			element.observe('click',this.textSizeLarger.bindAsEventListener(this));
		}.bind(this));
		if($$('.page_toolbar_email')[0]){
			$$('.page_toolbar_email')[0].observe('click',function(){addthis_sendto('email');});
		}
	},
	textSizeSmaller:function(){
		this.currentLineHeight = "1.5em";
		if(typeof this.currentTextSize!=="undefined"){
			this.currentTextSize = Math.round((parseInt(this.currentTextSize,10)*(0.9))/10)*10;
		}else{
			this.currentTextSize = "90";
		}
		$(this.targetDiv).setStyle({fontSize:this.currentTextSize+"%",lineHeight:this.currentLineHeight});
		if(this.saveTextSize){
			Cookie.setData('fontSize', this.currentTextSize);
		}
	},
	textSizeLarger:function(){
		this.currentLineHeight = "1.5em";
		if(typeof this.currentTextSize!=="undefined"){
			this.currentTextSize = Math.round((parseInt(this.currentTextSize,10)*(1.1))/10)*10;
		}else{
			this.currentTextSize = "110";
		}
		$(this.targetDiv).setStyle({fontSize:this.currentTextSize+"%",lineHeight:this.currentLineHeight});
		if(this.saveTextSize){
			Cookie.setData('fontSize', this.currentTextSize);
		}
	},
	textSizeReset:function(){
		$(this.targetDiv).setStyle({fontSize:''});
		if(this.saveTextSize){
			Cookie.setData('fontSize', '');
		}
	}
	
});
var TabList = Class.create(
		/** 
		 * @lends TabList.prototype
		 * 
		 */		
		{
		 /**
		  * Creates an instance of TabList. 
		  * @author eschleeper
		  * @param {Object} obj
		  * @constructs
		  */			 
	initialize: function(obj){
		$$('.tabs h4').invoke('hide');
		$$('.tabs ul li a').invoke('hide');
		$$('.tabs ul li ul li a').invoke('show');
		$$('.tabs ul li ul')[0].addClassName('tab_content');
		tabNav=new Element('ul').addClassName('tab_content_menu');
		obj.childElements().each(function(element,i){
			tabNav.insert(new Element('li',{id:'tab_nav_item_'+i}).update(element.down('a')).addClassName('tab_nav'));
			tabNav.childElements()[i].observe('click',function(event){this.setSelected(element,event,tabNav.childElements()[i]);}.bind(this));
			if(i===0){element.addClassName('selected');tabNav.childElements()[0].addClassName('selected');}
			else{element.hide();}
		}.bind(this));
		obj.up('div').insert({'top':tabNav});
		obj.select('li ul li ul').each(function(element){
			element.up('li').setStyle({position:'relative'});
			new Tooltip(element.up('li'), element,'USE_VERTEX',{x:5,y:5});
		});
	},
	setSelected:function(element,evt,caller){
		Event.stop(evt);
		$$('#content_main #content_body .tabs ul .selected').invoke('removeClassName', 'selected');
		element.siblings().each(function(element){element.hide();});
		element.setStyle({display:'block'});
		caller.addClassName('selected');
	}
});


/**
 * manages data and functions for accessing browser cookies
 * @namespace
 */
var Cookie = {
		data: {},
		options: {expires: 1, domain: "", path: "", secure: false},
		/**
		 * Initialization function.  Use if cookie has not already been created.
		 * @function
		 * @param {Object} options
		 * @param {Object} data
		 */
		init: function(options, data) {
			Cookie.options = Object.extend(Cookie.options, options || {});
			var payload = Cookie.retrieve();
			if(payload) {Cookie.data = payload.evalJSON();}
			else{Cookie.data = data || {};}
			Cookie.store();
		},
		/**
		 * Use to retrieve data based on a key
		 * @function
		 * @param {String} key
		 */
		getData: function(key) {return Cookie.data[key];},
		/**
		 * Use to set a value for a key in the Cookie Object
		 * @function
		 * @param {String} key
		 * @param {String} value
		 */
		setData: function(key, value) {
			Cookie.data[key] = value;
			Cookie.store();
		},
		/**
		 * Use to remove a key in the Cookie Object
		 * @function
		 * @param {String} key
		 */
		removeData: function(key) {
			delete Cookie.data[key];
			Cookie.store();
		},
		/**
		 * Use to retrieve the entire cookie, unescaped, as a string
		 * @function
		 * @returns {String} Cookie as unescaped string
		 */
		retrieve: function() {
			var start = document.cookie.indexOf(Cookie.options.name + "=");
			if(start == -1) {return null;}
			if(Cookie.options.name != document.cookie.substr(start, Cookie.options.name.length)) {return null;}
			var len = start + Cookie.options.name.length + 1;   
			var end = document.cookie.indexOf(';', len);
			if(end == -1) {end = document.cookie.length;} 
			return unescape(document.cookie.substring(len, end));
		},
		/**
		 * @function
		 */
		store: function() {
			var expires = '';
			if (Cookie.options.expires) {var today = new Date();expires = Cookie.options.expires * 86400000;expires = ';expires=' + new Date(today.getTime() + expires);}
			document.cookie = Cookie.options.name + '=' + escape(Object.toJSON(Cookie.data)) + Cookie.getOptions() + expires;
		},
		/**
		 * @function
		 */
		erase: function() {document.cookie = Cookie.options.name + '=' + Cookie.getOptions() + ';expires=Thu, 01-Jan-1970 00:00:01 GMT';},
		/**
		 * @function
		 */
		getOptions: function() {return (Cookie.options.path ? ';path=' + Cookie.options.path : '') + (Cookie.options.domain ? ';domain=' + Cookie.options.domain : '') + (Cookie.options.secure ? ';secure' : '');      }
};

/**
 * manages data and functions for embedded Google Maps in Location Detail pages
 * @requires inclusion of google maps js
 * @namespace
 */
var googleMaps = {
	/**
	 * selectors used in the various googleMaps functions
	 * @property
	 */
	selectorIDs: {
		map: "google_map",
		directions: "google_map_directions",
		address: "google_map_address",
		latitude: "google_map_latitude",
		longitude: "google_map_longitude",
		fromAddress: "google_map_from_address",
		info: "map_information",
		generalInfo: "general_information",
		mapInfo: "google_map_information",
		locationNav: "location_navigation"
	},
	/**
	 * @function
	 * @param {Object} selectorObject to overwrite the default selectors
	 */
	register: function(selectorObject){
		if(typeof selectorObject!=="undefined"){
			Object.extend(this.selectorIDs,selectorObject);
		}
		if(typeof GMap2 !=="undefined" && $(this.selectorIDs.mapInfo) && $(this.selectorIDs.address) && GBrowserIsCompatible()){
			var googleMapDiv = new Element("div",{id:this.selectorIDs.map,className:"GoogleMap"}).setStyle({height:"400px"});
			var googleMapDirectionsDiv = new Element("div",{id:this.selectorIDs.directions,className:"GoogleMapDirections"});
			$(this.selectorIDs.mapInfo).insert({'bottom':googleMapDiv}).insert({'bottom':googleMapDirectionsDiv});
			this.map = new GMap2(googleMapDiv,{backgroundColor:"#02254a"});
			this.geocoder = new GClientGeocoder();
			if($F(this.selectorIDs.latitude)!=="" && $F(this.selectorIDs.longitude)!==""){
				this.addMarker(new GLatLng($F(this.selectorIDs.latitude),$F(this.selectorIDs.longitude)));
			}else{
				this.geocoder.getLatLng($F(this.selectorIDs.address),function(point){ this.addMarker(point); }.bind(this));
			}
			//this.selectInfoTab(this.selectorIDs.generalInfo,$(this.selectorIDs.locationNav).select("a[href=#"+this.selectorIDs.generalInfo+"]")[0]);
			this.selectInfoTab(this.selectorIDs.mapInfo,$(this.selectorIDs.locationNav).select("a[href=#"+this.selectorIDs.mapInfo+"]")[0]);
			if($(this.selectorIDs.locationNav).select("a")[0]){
				$(this.selectorIDs.locationNav).select("a").each(function(element){
					element.observe("click",function(event){
						event.stop();
						this.selectInfoTab(event.element().href,event.element());
					}.bind(this));
				}.bind(this));
			}
			$(this.selectorIDs.mapInfo).down("form").observe("submit",function(event){
				event.stop();
				this.getDirections();
			}.bind(this));
			Event.observe(window,"unload", GUnload); 
		}
	},
	/**
	 * adds a marker to the google map
	 * @function
	 * @param {GLatLng} point
	 */
	addMarker: function(point){
		if(typeof point!=="undefined" && point){
			eHA.log.create("Adding marker for this Address", 3);
			this.map.setCenter(point, 13);
			this.map.addControl(new GLargeMapControl());
			var thisMarker = new GMarker(point)
			this.map.addOverlay(thisMarker);
			if($(this.selectorIDs.generalInfo).select("div.vcard")[0]){
				thisMarker.bindInfoWindow($$("div.vcard")[0].cloneNode(true));
			}
		}else{
			eHA.log.create("Google Maps can't add marker for this Address", 1);
		}
	},
	/**
	 * changes tabs in UI
	 * @function
	 * @param {String} tabSelector
	 * @param {Element} el
	 */
	selectInfoTab: function(tabSelector,el){
		eHA.log.create("Selecting tab "+tabSelector, 3);
		$(this.selectorIDs.locationNav).select("li").invoke("removeClassName","sel");
		el.up("li").addClassName("sel");
		$(this.selectorIDs.info).childElements().invoke("hide");
		if(tabSelector.indexOf("#")!=-1){
			if(typeof tabSelector.split("#")[1]!=="undefined"){
				tabSelector = tabSelector.split("#")[1];
			}else{
				tabSelector = tabSelector.split("#")[0];
			}
		}
		$(tabSelector).show();
	},
	/**
	 * Clears overlays on Google Map, selects the "map" info tab (using this.selectorIDs), loads
	 * directions from hidden inputs and computes directions with GDirections, adds to map, populates
	 * directions list.
	 * @function
	 */
	getDirections: function(){
		try{
	      	this.map.clearOverlays();
	      	this.selectInfoTab(this.selectorIDs.mapInfo,$(this.selectorIDs.locationNav).select("a[href=#"+this.selectorIDs.mapInfo+"]")[0]);
			var directionsPanel = $(this.selectorIDs.directions);
			directionsPanel.update();
			var directions = new GDirections(this.map, directionsPanel);
			var directions_string = $F(this.selectorIDs.fromAddress) + " to " + $F(this.selectorIDs.address);
			eHA.log.create("Attempting to get directions for "+directions_string, 3);
			directions.load(directions_string);
		}catch(err){
			eHA.log.create("Directions error: "+err.message, 1);
		}
	}
};

var Tooltip = Class.create();
Tooltip.prototype = {
		/**
		 * Creates an instance of Tooltip. 
		 * @param {Element} element
		 * @param {tooltip} tool_tip
		 * @param {position} position
		 * @param {vertex} vertex
		 * @constructs
		 */
		initialize: function(element, tool_tip,position,vertex) {
	var options = Object.extend({margin: "0px",padding: "5px",backgroundColor: "#d6d6fc",delta_x: 5,delta_y: 5,zindex: 1000}, arguments[1] || {});
	this.element      = $(element);
	this.tool_tip     = $(tool_tip);
	this.options      = options;
	this.position = position;
	//this.tool_tip.hide();
	//this.hideTooltip();
	this.tool_tip.setStyle({marginLeft:'-1000em',position:'absolute'});
	this.absolutePositionVertex=vertex;
	this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
	this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
	this.registerEvents();
},
destroy: function() {
	Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
	Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
},
registerEvents: function() {
	//this.element.setAttribute('tab-index','1');
	Event.observe(this.element, "mouseover", this.eventMouseOver);
	Event.observe(this.element, "mouseout", this.eventMouseOut);
	if(this.element.down('a')!==null){
		Event.observe(this.element.down('a'), "focus",this.eventMouseOver);
		Event.observe(this.element.down('a'), "blur", this.eventMouseOut);
	}
	if(this.element.down('ul')!==null){
		this.element.down('ul').select('li a').invoke('observe','focus',this.eventMouseOver);
		this.element.down('ul').select('li a').invoke('observe','blur',this.eventMouseOut);
	}
},
showTooltip: function(event){
	Event.stop(event);
	var coords = Event.element(event).cumulativeOffset();
	var mouse_x = coords[0];
	var mouse_y = coords[1]-140;
	this.tool_tip.addClassName('active_tip');
	this.setStyles(mouse_x, mouse_y);
},
setStyles: function(x, y){
	if(this.position=='absolute'){
		Element.setStyle(this.tool_tip, { marginLeft:0, position:this.position,top:y + "px",left:x + "px",zindex:this.options.zindex});
	}
	else if(this.position=='USE_VERTEX'){
		Element.setStyle(this.tool_tip,  {marginLeft:0, position:'relative',zindex:this.options.zindex});
	}
	else{
		Element.setStyle(this.tool_tip, { marginLeft:0, position:this.position,zindex:this.options.zindex});
	}
},
hideTooltip: function(event){/*new Element.hide(this.tool_tip);*/this.tool_tip.setStyle({marginLeft:'-1000em',position:'absolute'});this.tool_tip.removeClassName('active_tip');},
getWindowHeight: function(){
	var innerHeight;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerHeight = document.body.clientHeight;
	} else {
		innerHeight = window.innerHeight;
	}
	return innerHeight;	
},
getWindowWidth: function(){
	var innerWidth;
	if (navigator.appVersion.indexOf('MSIE')>0) {
		innerWidth = document.body.clientWidth;
	} else {
		innerWidth = window.innerWidth;
	}
	return innerWidth;	
}
};

Ajax.Request.prototype.abort = function() {
    this.transport.onreadystatechange = Prototype.emptyFunction;
    this.transport.abort();
    Ajax.activeRequestCount--;
};

/* customer code below */

var AH_hero = {
	duration: 0.9,
	intervalMS: 10000,
	current:0,
	init: function(){
		if($$(".eHA_LandingPage_C #content #hero li.first")[0]){
			this.promos = new Array();
			this.current = 0;
			var linksDiv = new Element("div",{className:"heroNavigation"}).hide();
			//add arrows
			this.previousA = new Element("a",{href:""}).update("Previous");
			this.nextA = new Element("a",{href:""}).update("Next");
			var previousLI = new Element("li",{className:"previous_disabled"}).update(this.previousA);
			var nextLI = new Element("li",{className:"next"}).update(this.nextA);
			this.controlsUL = new Element("ul",{className:"controls"})
				.insert({bottom:previousLI})
				.insert({bottom:nextLI})
				.hide();
			$('hero').insert({bottom:this.controlsUL});
			this.controlsUL.appear({duration:this.duration});

		this.current=parseInt(this.current,10);
		this.nextA.observe("click",function(evt){
			evt.stop();
			this.stop();
			eHA.log.create("BUTTON NEXT index:"+this.current);
			this.next(this.current);
		}.bind(this));
		this.previousA.observe("click",function(evt){
			evt.stop();
			this.stop();
			eHA.log.create("BUTTON PREVIOUS index:"+this.current--);
			this.previous(this.current--);
		}.bind(this));


			// create element arrey for promo to be displayed 
			$$(".eHA_LandingPage_C #content #hero li").each(function(el,i){
				if(el.down("img")){
					if(i>0){
						el.addClassName("off");
						el.hide();
					}else{
						el.addClassName("sel");
					}
				if(el.down("div h5")){
				//wristband needs wrapper to accommodate image in the background							
				var wristband = new Element("div",{className:"wristband"}).update(el.down("div h5"));
				el.insert({bottom:wristband});
				}
					this.promos.push(el);
				}
			}.bind(this));
			this.start();
			
		}
	},
	start: function(){
		this.interval = setInterval("AH_hero.next()",this.intervalMS);
	},
	stop: function(){
		clearInterval(this.interval);
	},
	select: function(index){
		try{
				var thisPromo = $(this.promos[index]);
				this.current = index;
				
				//check for value of selected if greater then set to ziro, if less then number of promos from arrey set to 0
				if(this.current <0 ){this.current=0;}
				if(this.current>this.promos.size()){
						this.current=this.current=0;
				}
				var parallelArray = new Array();
				// currently selected must fade
				$$(".eHA_LandingPage_C #content #hero>ul li.sel").each(function(sibling){
					parallelArray.push(new Effect.Fade(sibling,{sync:true}));
				}.bind(this));
				// newly selected must be moved left and appear
				parallelArray.push(new Effect.Appear(thisPromo,{sync:true}));
				new Effect.Parallel(parallelArray,{duration:this.duration,
					beforeStart:function(){
					thisPromo.setStyle({"left":"0"});
				},
				afterFinish: function(){
					$$(".eHA_LandingPage_C #content #hero>ul li.off").each(function(sibling){
						sibling.setStyle({"left":"-9999px"});
					});
				}
				});
				
				$A(this.promos).invoke("removeClassName","sel").invoke("addClassName","off");
				thisPromo.addClassName("sel").removeClassName("off");
				
				this.stop();
				this.start();
		}catch(err){
			eHA.log.create(err.toString(),eHA.log._ERROR);
		}
	},
	next: function(){
		var index=1;
		try{
			var nextIndex = parseInt(this.current,10) + parseInt(1,10);
		//	eHA.log.create("showing promo size:"+this.promos.size());
			eHA.log.create("NEXT current:"+this.current);
			if(nextIndex>=this.promos.size()){
				nextIndex = 0;
			}
			
			eHA.log.create("NEXT FUNCTION:"+nextIndex);
			this.select(nextIndex);

		}catch(err){
			eHA.log.create(err.toString(),eHA.log._ERROR);
		}
	},
	previous: function(index){
		try{
			var previousIndex = parseInt(index);
			eHA.log.create("PREVIOUS FUNCTION IN:"+previousIndex);
			if(previousIndex>=this.promos.size()){
				previousIndex = 0;
			}
			if(previousIndex<0){
				previousIndex = parseInt(this.promos.size())-1;
			}			
			eHA.log.create("PREVIOUS FUNCTION OUT:"+previousIndex);
			this.stop();
			this.start();
			this.current=previousIndex;
			this.select(previousIndex);
			
		}catch(err){
			eHA.log.create(err.toString(),eHA.log._ERROR);
		}
	}
};


var AH_newsHub = {
	/*
	 * if there are 2 news modules on a content category page, this function will attempt
	 * to organize them into tabs
	 */
	init: function(callback){
		if(this.check()){
			var modulesWrapper = new Element("div",{className:"newsModulesWrapper"});
			var moduleNavigation = new Element("div",{className:"moduleNavigation"}).update("<ul></ul>");
			$("content_body").down(".category_general_body").insert({before:modulesWrapper});
			modulesWrapper.insert({top:moduleNavigation});
			this.modules = new Array();
			this.links = new Array();
			$$(this.selectors.modules).each(function(el,i){
				var thisNewsWrapper = new Element("div",{className:"newsWrapper"});
				var thisLink = new Element("a",{href:""}).update(el.down("h3").innerHTML);
				var thisLI = new Element("li").update(thisLink);
				thisNewsWrapper.insert({top:el.next(".news")});
				thisNewsWrapper.insert({top:el});
				modulesWrapper.insert({bottom:thisNewsWrapper});
				moduleNavigation.down("ul").insert({bottom:thisLI});
				
				this.modules.push(thisNewsWrapper);
				this.links.push(thisLI);
				
				thisLink.observe("click",function(evt){
					evt.stop();
					$A(this.modules).invoke("removeClassName","sel").invoke("addClassName","off");
					$A(this.links).invoke("removeClassName","sel").invoke("addClassName","off");
					evt.element().up("li").removeClassName("off").addClassName("sel");
					thisNewsWrapper.removeClassName("off").addClassName("sel");
				}.bind(this));
				if(i>0){
					thisLI.addClassName("off");
					thisNewsWrapper.addClassName("off");
				}else{
					thisLI.addClassName("sel");
					thisNewsWrapper.addClassName("sel");
				}
			}.bind(this));
			callback();
		}
	},
	selectors: {
		modules: ".eHA_Content_P #content_body .category_general_body .newsModule"
	},
	check: function(){
		if($$(this.selectors.modules).size()===2){
			eHA.log.create("found 2 news modules");
			return true;
		}else{
			return false;
		}
	}
};


var AH_CTHub = {
	/*
	 * if there are 3 conditions modules on a content category page, this function will attempt
	 * to organize them into tabs
	 */
	init: function(callback){
		if(this.check()){
			var modulesWrapper = new Element("div",{className:"conditionsModulesWrapper"});
			var moduleNavigation = new Element("div",{className:"moduleNavigation"}).update("<ul></ul>");
			$("content_body").down(".category_general_body").insert({after:modulesWrapper});
			modulesWrapper.insert({top:moduleNavigation});
			this.modules = new Array();
			this.links = new Array();
			$$(this.selectors.modules).each(function(el,i){
				var thisconditionWrapper = new Element("div",{className:"conditionWrapper"});
				var thisLink = new Element("a",{href:""}).update(el.down("h3").innerHTML);
				var thisLI = new Element("li").update(thisLink);
				thisconditionWrapper.insert({top:el.next(".conditions")});
				thisconditionWrapper.insert({top:el});
				modulesWrapper.insert({bottom:thisconditionWrapper});
				moduleNavigation.down("ul").insert({bottom:thisLI});
				
				this.modules.push(thisconditionWrapper);
				this.links.push(thisLI);
				
				thisLink.observe("click",function(evt){
					evt.stop();
					$A(this.modules).invoke("removeClassName","sel").invoke("addClassName","off");
					$A(this.links).invoke("removeClassName","sel").invoke("addClassName","off");
					evt.element().up("li").removeClassName("off").addClassName("sel");
					thisconditionWrapper.removeClassName("off").addClassName("sel");
					try{
						var thisconditionModule = eHA.conditions.conditionsModuleObjects[eHA.elementToObjectLiteral(thisconditionWrapper.down(".conditionsModule")).assetid];
						
						thisconditionModule.currentPageNumber = 1;
						if(thisconditionModule.conditionsDiv.select("ul.page")[0]){
							thisconditionModule.conditionsDiv.select("ul.page").invoke("remove");
						}
						thisconditionModule.createPage(1);
						
					}catch(err){
						eHA.log.create(err.toString(),eHA.log._ERROR);
					}
					
				}.bind(this));
				if(i>0){
					thisLI.addClassName("off");
					thisconditionWrapper.addClassName("off");
				}else{
					thisLI.addClassName("sel");
					thisconditionWrapper.addClassName("sel");
				}
			}.bind(this));
			callback();
		}
	},
	selectors: {
		modules: ".eHA_Content_P #content_body .category_general_body .conditionsModule"
	},
	check: function(){
		if($$(this.selectors.modules).size()===3){
			eHA.log.create("found 3 conditions modules");
			return true;
		}else{
			return false;
		}
	}
};


var AH_locationsHub = {
	/*
	 * if there are 3 locations modules on a content category page, this function will attempt
	 * to organize them into tabs
	 */
	init: function(callback){
		if(this.check()){
			var modulesWrapper = new Element("div",{className:"locationsModulesWrapper"});
			var moduleNavigation = new Element("div",{className:"moduleNavigation"}).update("<ul></ul>");
			$("content_body").down(".category_general_body").insert({after:modulesWrapper});
			modulesWrapper.insert({top:moduleNavigation});
			this.modules = new Array();
			this.links = new Array();
			$$(this.selectors.modules).each(function(el,i){
				var thisLocationWrapper = new Element("div",{className:"locationWrapper"});
				var thisLink = new Element("a",{href:""}).update(el.down("h3").innerHTML);
				var thisLI = new Element("li").update(thisLink);
				thisLocationWrapper.insert({top:el.next(".locations")});
				thisLocationWrapper.insert({top:el});
				modulesWrapper.insert({bottom:thisLocationWrapper});
				moduleNavigation.down("ul").insert({bottom:thisLI});
				
				this.modules.push(thisLocationWrapper);
				this.links.push(thisLI);
				
				thisLink.observe("click",function(evt){
					evt.stop();
					$A(this.modules).invoke("removeClassName","sel").invoke("addClassName","off");
					$A(this.links).invoke("removeClassName","sel").invoke("addClassName","off");
					evt.element().up("li").removeClassName("off").addClassName("sel");
					thisLocationWrapper.removeClassName("off").addClassName("sel");
					try{
						var thisLocationModule = eHA.locations.locationsModuleObjects[eHA.elementToObjectLiteral(thisLocationWrapper.down(".locationsModule")).assetid];
						
						thisLocationModule.currentPageNumber = 1;
						if(thisLocationModule.locationsDiv.select("ul.page")[0]){
							thisLocationModule.locationsDiv.select("ul.page").invoke("remove");
						}
						thisLocationModule.createPage(1);
						
					}catch(err){
						eHA.log.create(err.toString(),eHA.log._ERROR);
					}
					
				}.bind(this));
				if(i>0){
					thisLI.addClassName("off");
					thisLocationWrapper.addClassName("off");
				}else{
					thisLI.addClassName("sel");
					thisLocationWrapper.addClassName("sel");
				}
			}.bind(this));
			callback();
		}
	},
	selectors: {
		modules: ".eHA_Content_P #content_body .category_general_body .locationsModule"
	},
	check: function(){
		if($$(this.selectors.modules).size()){
			eHA.log.create("found  locations modules");
			return true;
		}else{
			return false;
		}
	}
};


var AH_locationsDetail = {
	init: function(){
		this.tabs = new Array();
		this.links = new Array();
		
		if($("content_body").down("#general_information")){
			this.tabs.push($("content_body").down("#general_information"));
		}
		if($("content_body").down(".google_map_container")){
			this.tabs.push($("content_body").down(".google_map_container"));
		}
		if($("content_body").down("#other_information")){
			this.tabs.push($("content_body").down("#other_information"));
		}
		if($("content_body").down("#services_programs")){
			this.tabs.push($("content_body").down("#services_programs"));
		}
		
		var linksDiv = new Element("div",{className:"tabNavigation"});
		var linksUL = new Element("ul");
		
		$A(this.tabs).each(function(el,i){
			var thisLink = new Element("a",{href:""}).update(el.down("h3").innerHTML);
			var thisLI = new Element("li").update(thisLink);
			linksUL.insert({bottom:thisLI});
			
			this.links.push(thisLI);
			
			thisLink.observe("click",function(evt){
				evt.stop();
				$A(this.tabs).invoke("removeClassName","sel").invoke("addClassName","off");
				$A(this.links).invoke("removeClassName","sel").invoke("addClassName","off");
				evt.element().up("li").removeClassName("off").addClassName("sel");
				el.removeClassName("off").addClassName("sel");
			}.bind(this));
			if(i>0){
				thisLI.addClassName("off");
				el.addClassName("off");
			}else{
				thisLI.addClassName("sel");
				el.addClassName("sel");
			}
		}.bind(this));
		
		linksDiv.update(linksUL);
		$("content_body").down("div.location").insert({after:linksDiv});

		//this.tabs[0].insert({before:linksDiv});
	}
};

var SlidingItems = Class.create({
	/*
	 * options:
	 *    selectors: {item,groupDiv,controlsParent}
	 *    groupSize
	 *    offsetDistance
	 *    duration
	 */
		initialize: function(options){
			
			if($$(options.selectors.item)[0] && $$(options.selectors.item).size()>1){
				
				// configuration
				this.modulesDiv = $$(options.selectors.groupDiv)[0];
				this.controlsParent = $$(options.selectors.controlsParent)[0];
				this.groupSize = options.groupSize;
				this.offsetDistance = options.offsetDistance; // pixel value, width of one item + padding / margin
				this.duration = options.duration;
				this.numberOfModules = $$(options.selectors.item).size();
				this.totalModules = new Number(this.numberOfModules);
				this.currentModule=1;
				
				if(this.groupSize>1){
					this.numberOfModules = Math.ceil(this.numberOfModules/this.groupSize);
					this.offsetDistance = parseInt(this.groupSize*this.offsetDistance,10);
				}
				
				this.previousA = new Element("a",{href:""}).update("Previous");
				this.nextA = new Element("a",{href:""}).update("Next");
				var previousLI = new Element("li",{className:"previous_disabled"}).update(this.previousA);
				var nextLI = new Element("li",{className:"next"}).update(this.nextA);
				this.controlsUL = new Element("ul",{className:"controls"})
					.insert({bottom:previousLI})
					.insert({bottom:nextLI})
					.hide();
				
				this.controlsParent.insert({bottom:this.controlsUL});
				if(this.totalModules>this.groupSize){
					this.controlsUL.appear({duration:this.duration});
				}
				
				this.addEvents();
			}
		},
	addEvents: function(){
		this.previousA.observe("click",function(event){
			event.stop();
			this.previous();
		}.bind(this));
		
		this.nextA.observe("click",function(event){
			event.stop();
			this.next();
		}.bind(this));
	},
	adjustDisabled: function(){
		if(this.currentModule===1){
			this.previousA.up("li").removeClassName("previous").addClassName("previous_disabled");
		}else{
			this.previousA.up("li").removeClassName("previous_disabled").addClassName("previous");
		}
		if(this.currentModule===this.numberOfModules){
			this.nextA.up("li").removeClassName("next").addClassName("next_disabled");
		}else{
			this.nextA.up("li").removeClassName("next_disabled").addClassName("next");
		}
	},
	moveModules: function(){
		var newMarginLeft = "-"+((this.currentModule-1)*this.offsetDistance)+"px";
		this.modulesDiv.morph('margin-left:'+newMarginLeft+';',{duration:this.duration});
	},
	previous: function(){
		if(this.currentModule!==1){
			this.currentModule--;
			this.moveModules();
			this.adjustDisabled();
		}
	},
	next: function(){
		if(this.currentModule!==this.numberOfModules){
			this.currentModule++;
			this.moveModules();
			this.adjustDisabled();
		}
	}
});

eHA.HomePageTabs = {
	/*
	 * if there are more then one module assigned to home page under selector '.HomePageTab' , this function will attempt
	 * to organize them into tabs. NOTE: All modules are wrapped with #featured_section
	 */

		init: function(){		
			if($$(".eHA_LandingPage_C #content_body .HomePageTab").size()>1){
				this.tabs = new Array();
				this.links = new Array();
				this.tabToSelect =parseInt(window.location.hash.substring(1)); // reverts hash value into intiger 
				
				var linksUL = new Element("ul");
				var linksDiv = new Element("div",{className:"tab_home_section"}).update(linksUL);
				
				$$(".eHA_LandingPage_C #content_body .HomePageTab").each(function(el,i){
					if(el.down("h3"))	var name = el.down("h3").innerHTML;
					if(el.down("h5"))	var name = el.down("h5").innerHTML;
					var thisA = new Element("a",{href:""}).update(name).addClassName("tab_"+i);
					var thisLI = new Element("li").update(thisA);
					
					if(i!==0){
						el.hide();
					}else{ //select per default first listed 
						el.addClassName("sel");
						thisLI.addClassName("sel");

					}
					
					thisA.observe("click",function(evt){
						evt.stop();
						this.clearSelection();
						this.select(i);
					}.bind(this));
					
					linksUL.insert({bottom:thisLI});
					
					this.tabs.push({name:name,el:el});
					this.links.push({name:name,el:thisLI});
					
				}.bind(this));
				
				$$(".eHA_LandingPage_C #content_body #HomePage_news .HomePageTab")[0].insert({before:linksDiv});
				
				if((this.tabToSelect)) { // if # has been added select element that match # value
					this.clearSelection();
					this.select(this.tabToSelect);	
					//window.location = window.location.href.replace( /#.*/, "");	//clear hash			
					}				
			}
		},
		clearSelection: function(){
			$A(this.tabs).each(function(tab){
				tab.el.removeClassName("sel").hide();
			});
			$A(this.links).each(function(link){
				link.el.removeClassName("sel");
			});
		},
		select: function(i){
			if(this.tabs[i]){
			this.tabs[i].el.addClassName("sel").show();
			this.links[i].el.addClassName("sel");
			}else {alert('Active tab could not be located. Error: TABS_SERVICES')}
		}
	}


var FadeIn ={
	//this function will show up all segments of content body at once when they are created , css loaded and js starts running. If call added to
	// the bottom of onload function, after all js are exicuted it will show after all JS functions are completed
	Initial:function(ContainerID){
		var ContainerSelector= ContainerID;
		if($(ContainerSelector)) {
			$(ContainerSelector).setStyle({display:'block'});
		}
			else{ }
	}
	
}

