﻿// Menu Functionality //
//wrapper functions to prevent null references to menus variable
function menus_hideMenu(id){if (menus) menus.hideMenu(id);}
function menus_showMenu(id,element){if (menus) menus.showMenu(id,element);}
// Menu Manager Class//
function MenuManager(id,direction,hidingDelay,useSliding,animationTime,minInterval,positionFixed){
	//properties
	this.activeMenu = null;
	this.animationTime = animationTime;
	this.direction = direction;
	this.directionMod = (direction == "down" || direction == "right") ? "-" : "+";
	this.hidingDelay = hidingDelay;
	this.id = id;
	this.menus = new Array();
	this.menusList = new Array();
	this.minInterval = minInterval;
	this.orientation = (direction == "left" || direction == "right") ? "h" : "v";
	this.positionFixed = positionFixed;
	this.useSliding = useSliding;
	//this.log = new Array();
	//methods
	this.attachMenus = menuManager_attachMenus;
	this.hideAllMenus = menuManager_hideAllMenus;
	this.hideMenu = menuManager_hideMenu;
	this.showLog = menuManager_showLog;
	this.showMenu = menuManager_showMenu;
}
function menuManager_showLog(){alert(this.log.join("\n"));}
function menuManager_attachMenus(){
	var id, left, top;
	//load menus into array
	for (var i=0;i<arguments.length;i++){
		if (i % 3 == 0)	id = arguments[i];
		else if (i % 3 == 1)left = parseInt(arguments[i]);
		else if (i % 3 == 2){
			top = parseInt(arguments[i]);
			var menu = new Menu(this,id,left,top);
			if (menu.init(left,top)){
				this.menus[id] = menu;
				this.menusList[this.menusList.length] = menu;
			}
		}
	}
}
function menuManager_hideAllMenus(id){
	for (var i=0; i < this.menus.length; i++)
		if (this.menus[i]) this.menus[i].hide(true);
}
function menuManager_hideMenu(id,hideImmediately){
	var menu = this.menus[id];
	if (menu)menu.hide(hideImmediately);
}
function menuManager_showMenu(id,element){
	var menu = this.menus[id];
	if (menu)menu.show(element);
}
// Menu Class //
function Menu(manager,id){
	//properties
	this.acceleration = 0;
	this.animationTimer = null;
	this.closedPosition = 0;
	this.container = null;
	this.hideTimer = null;
	this.id = id;
	this.isOpen = false;
	this.manager = manager;
	this.menu = null;
	this.relevantDimension = 0;
	this.slideStartTime;
	//methods
	this.finishSlide = menu_finishSlide;
	this.hide = menu_hide;
	this.init = menu_init;
	this.moveTo = menu_moveTo;
	this.show = menu_show;
	this.slide = menu_slide;
	this.slideIncrement = menu_slideIncrement;
}
function menu_finishSlide(){
	if (this.manager.useSliding){
		this.moveTo(this.isOpen ? 0 : this.closedPosition);
		if (this.animationTimer)window.clearInterval(this.animationTimer);
	}
	//hide container
	if (!this.isOpen)this.container.style.visibility = "hidden";
}
function menu_hide(hideImmediately){
	//this.manager.log[this.manager.log.length] = "menu hide: " + this.id + " immed: " + hideImmediately;
	if (hideImmediately)	{
		if (this.hideTimer)	window.clearTimeout(this.hideTimer);
		if (this.isOpen) this.slide(false);
	}
	else{
		if (this.manager.useSliding && this.hideTimer) window.clearTimeout(this.hideTimer)
		this.hideTimer = window.setTimeout(this.manager.id + ".hideMenu('" + this.id + "',true);", this.manager.hidingDelay);
	}
}
function menu_init(left,top){
	this.container = document.getElementById(this.id + "MenuContainer");
	this.menu = document.getElementById(this.id + "Menu");
	if (this.container && this.menu){
		this.relevantDimension = this.manager.orientation == "v" ? this.menu.offsetHeight : this.menu.offsetWidth;
		this.container.style.left = left + "px";
		this.container.style.top = top + "px";
		this.closedPosition = eval("0" + this.manager.directionMod + this.relevantDimension);
		this.acceleration = (-this.closedPosition) / this.manager.animationTime / this.manager.animationTime;
		this.menu.onmouseover = new Function(this.manager.id + ".showMenu('" + this.id + "');");
		this.menu.onmouseout = new Function(this.manager.id + ".hideMenu('" + this.id + "');");
		if (this.manager.useSliding) this.moveTo(this.closedPosition);
		return true;
	}
	return false;
}
function menu_moveTo(position){
	if (this.manager.orientation == "h") this.menu.style.left = position + "px";
	else this.menu.style.top = position + "px";
}
function menu_show(element){
	//this.manager.log[this.manager.log.length] = "menu show: " + this.id;
	//immediately hide all other menus
	for (var i=0; i<this.manager.menusList.length; i++){
		var menu = this.manager.menusList[i];
		if (menu != this && menu.isOpen) menu.hide(true);
	}
	//cancel hiding action
	if (this.hideTimer) window.clearTimeout(this.hideTimer);

	if (!this.isOpen){
		//reposition menu, if necessary
		if (!this.manager.positionFixed) item_reposition(element,this.container);
		this.slide(true);
	}
}
function menu_slide(isOpening){
	//this.manager.log[this.manager.log.length] = "menu slide: " + this.id + " isOpening: " + isOpening;
	this.isOpen = isOpening;
	if (isOpening) this.container.style.visibility = "visible";

	if (this.manager.useSliding){
		if (this.animationTimer) window.clearInterval(this.animationTimer);
		this.slideStartTime = (new Date()).getTime();
		this.animationTimer = window.setInterval(this.manager.id + ".menus['" + this.id + "'].slideIncrement();", this.manager.minInterval);
	}
	else this.finishSlide();
}
function menu_slideIncrement(){
	var elapsedTime = (new Date()).getTime() - this.slideStartTime;
	if (elapsedTime <= this.manager.animationTime){
		var position = Math.round(Math.pow(this.manager.animationTime - elapsedTime, 2) * this.acceleration)
		if (this.isOpen && this.manager.directionMod == "-") position = -position;
		else if (this.isOpen && this.manager.directionMod == "+") position = -position;
		else if (!this.isOpen && this.manager.directionMod == "-") position = -this.relevantDimension + position;
		else position = this.relevantDimension + position;
		this.moveTo(position);
	}
	else this.finishSlide()
}
/*build actual menus*/
var menus;
function siteMaster_onLoad(){
	menus = new MenuManager("menus","down",500,true,250,10,false);
	menus.attachMenus("About",0,0);
	menus.attachMenus("HearingLoss",0,0);
	menus.attachMenus("HearingAids",0,0);
	menus.attachMenus("Newsletters",0,0);
	menus.attachMenus("ContactUs",0,0);
}


/*common elements*/
var inDebugMode = false;
function debugAlert(message){if (inDebugMode)alert(message);}
//easy window closing function, attemts to refocus on parent
function closeWindow(){
	try {window.opener.focus();}
	catch(ex) {}
	window.close();
}
//generic event bubble cancel function
function cancelEvent(e){
	if (e.cancelBubble) e.cancelBubble = true;
	if (e.stopPropogation) e.stopPropogation();
}
//generic confirm action function
function confirmAction(text){return confirm("Are you sure you would like to perform this " + text + "?");}
//generic confirm delete function
function confirmDelete(){return confirm("Are you sure you would like to delete the selected items?");}
//easy retrieval of event target
function getEventTarget(e){
	var targ;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3)targ = targ.parentNode;// defeat Safari bug
	return targ;
}
function getScrollTop(){
	if (document.documentElement.scrollTop) return document.documentElement.scrollTop;
	if (document.body.scrollTop) return document.body.scrollTop;
	if (window.pageYOffset) return window.pageYOffset;
	return 0;
}
function getWindowHeight(){
	if (window.innerHeight) return window.innerHeight;
	if (document.documentElement.clientHeight) return document.documentElement.clientHeight;
	if (document.body.clientHeight) return document.body.clientHeight;
	return 0;
}
// Common Page / Popup Opening Functions //
//easy function to open page in parent window, if available.  if parent is not available, then open new window
function openInParent(url){
	try	{ window.opener.document.location = url; window.opener.focus();}
	catch(ex){openWindowDefault(url,"NewWindow");}
}
//easy window opening functionality
function openWindow(url,windowName,args){window.open(url,windowName,args);}
//easy window opening with default sizing and setup
function openWindowDefault(url,windowName){openWindow(url,windowName,"height=600,width=700,scrollbars=1,resizable=1");}
function openDialogWindow(url,windowName){openWindow(url,windowName,"height=700,width=775,scrollbars=1,resizable=1");}
function openDialogWindow2(url,windowName,finishAction,cancelAction,callback,callbackPrefix){
	//append params to url
	if (url.indexOf("?") >= 0) url += "&Master=Dialog";
	else url += "?Master=Dialog";
	if (finishAction) url += "&FinishAction=" + finishAction;
	if (cancelAction) url += "&CancelAction=" + cancelAction;
	if (callback) url += "&Callback=" + callback;
	if (callbackPrefix) url += "&CallbackPrefix=" + callbackPrefix;
	openWindow(url,windowName,"height=620,width=700,scrollbars=1,resizable=1");
}
function openPrintWindow(url,windowName,isLandscape){
	var width = isLandscape ? "1000" : "770";
	openWindow(url,windowName,"height=600,width=" + width + ",scrollbars=1,resizable=1,menubar=1");
}
function openWindowLandscape(url,windowName){openWindow(url,windowName,"height=612,width=800,scrollbars=1,resizable=1");}
//execute command in opener window, with built in fail options
function execOpenerCommand(cmd,closeOnComplete){
	try	{eval(cmd); if (closeOnComplete)closeWindow();}
	catch(ex){alert("The original window is no longer open or available.  The command cannot be completed.");}
}
// Common Field Functions//
function field_addClassName(el, className){	field_removeClassName(el, className); el.className = (el.className + " " + className).trim();}
function field_removeClassName(el, className) {el.className = el.className.replace(className, "").trim();}
function field_onFocus(id){
	var field = document.getElementById(id);
	try	{
		if (field){
			if (field.value.length > 0) field.select();
			else field.focus();
		}			
	}
	catch (ex) {/*do nothing*/}		
}
//function will check all checkboxes in provided element
//if postfix provided, function will only check checkboxes with an id that ends with the postfix
function table_selectAllCheckboxes(id,check,postfix){
	var el = document.getElementById(id)
	if (el)	{
		var fields = el.getElementsByTagName("input");
		for (var i=0; i<fields.length; i++){
			var field = fields[i];
			if (field.type.toLowerCase() == "checkbox")
				if (!postfix || (field.id.match(postfix + "$") == postfix)) field.checked = check;
		}
	}
}
// Common Textarea Functions //
function textarea_onInsert(field, value){
	//IE
	if (document.selection)	{
		field.focus();
		sel = document.selection.createRange();
		sel.text = value;
	}
	//MOZILLA/NETSCAPE
	else if (field.selectionStart || field.selectionStart == '0'){
		var startPos = field.selectionStart;
		var endPos = field.selectionEnd;
		field.value = field.value.substring(0, startPos) + value + field.value.substring(endPos, field.value.length);
	}else{field.value += value;}
	field.focus();
}
// Common Select Box Functions //
function select_addOption(field,text,value){if (field) field.options[field.options.length] = new Option(text,value);}
function select_removeSelectedOptions(field){
	if (field){
		for (var i=field.options.length-1; i>=0; i--){
			if (field.options[i].selected) field.removeChild(field.options[i]);
		}
	}
}
// Trim Functions //
function ltrim(str){return str.replace(/^[ ]+/, '');} 
function rtrim(str){return str.replace(/[ ]+$/, '');} 
function trim(str){return ltrim(rtrim(str));} 
// Repositioning Functions //
function item_reposition(field,item,itemOutsideFixedArea){
	//wrap in try as sometimes the offsetLeft and offsetTop fail in IE
	try	{
		var lft = field.offsetLeft;
		var tp = field.offsetTop;
		//determine position of field
		var o = field.offsetParent;
		while (o){
			if (o.style.position != "fixed" && o.style.position != "absolute"){
				lft += o.offsetLeft;
				tp += o.offsetTop;
				o = o.offsetParent;
			}else{
				if (itemOutsideFixedArea){
					lft += o.offsetLeft;
					tp += getScrollTop() + o.offsetTop;
				}
				o = null;
			}
		}
		//adjust top position for field height
		var fieldHeight = field.offsetHeight;
		var itemHeight = parseInt(item.style.height);
		var scrollAmt = getScrollTop();
		if (tp - itemHeight >= scrollAmt && tp + fieldHeight + itemHeight > getWindowHeight() + scrollAmt) tp -= itemHeight;
		else tp += fieldHeight;
		if (item.style.left != lft + "px") item.style.left = lft + "px";
		if (item.style.top != tp + "px") item.style.top = tp + "px";
	}
	catch(ex){;/* do nothing*/}
}
// Custom Validator Functions //
function isDateFieldValid(value){return ((value.length > 0) && (!(isNaN(Date.parse(value)))));}
function isDateValid(sender, args){args.IsValid = ((args.Value.length > 0) && (!(isNaN(Date.parse(args.Value)))));}
function isEmailValid(sender, args){var reEmail = /^([a-zA-Z0-9_\-])+(\.([a-zA-Z0-9_\-])+)*@((\[(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5])))\.(((([0-1])?([0-9])?[0-9])|(2[0-4][0-9])|(2[0-5][0-5]))\]))|((([a-zA-Z0-9])+(([\-])+([a-zA-Z0-9])+)*\.)+([a-zA-Z])+(([\-])+([a-zA-Z0-9])+)*))$/g;
	args.IsValid = (args.Value.search(reEmail) == 0);}
function warnIfDateInPast(value){
	var dt = Date.parse(value);
	var today = new Date();
	if (dt < new Date(today.getFullYear(),today.getMonth(),today.getDate())) alert("You have selected a date in the past.");
}
// Rollover Functionality //
//create global variables to hold info
var oImages = new Array()
//called from pages to preload rollover images
function preloadImages(directory,prefix,extension){
	//preload images for each image name passed
	for (var i=3;i<arguments.length;i++){
		oImages[arguments[i] + "Off"] = new Image();
		oImages[arguments[i] + "Off"].src = directory + prefix + arguments[i] + "Off." + extension;
		oImages[arguments[i] + "On"] = new Image();
		oImages[arguments[i] + "On"].src = directory + prefix + arguments[i] + "On." + extension;
	}
}
function preloadTristateImages(directory,prefix,extension){
	//preload images for each image name passed
	for (var i=3;i<arguments.length;i++){
		oImages[arguments[i] + "Off"] = new Image();
		oImages[arguments[i] + "Off"].src = directory + prefix + arguments[i] + "Off." + extension;
		oImages[arguments[i] + "On"] = new Image();
		oImages[arguments[i] + "On"].src = directory + prefix + arguments[i] + "On." + extension;
		oImages[arguments[i] + "Hover"] = new Image();
		oImages[arguments[i] + "Hover"].src = directory + prefix + arguments[i] + "Hover." + extension;
	}
}
function toggleImage(id){
	var img = document.getElementById(id + "Image");
	var alwaysOn = (img ? img.getAttribute("alwayson") : "");

	if (img && (alwaysOn != "1")){
		try{
			if (img.src == oImages[id + "On"].src) img.src = oImages[id + "Off"].src;
			else img.src = oImages[id + "On"].src;
		} catch(ex) {;}
	}
}
function toggleTristateImage(id){
	var img = document.getElementById(id + "Image");
	var alwaysOn = img.getAttribute("alwayson");
	if (img && (alwaysOn != "1")){
		try{ if (img.src == oImages[id + "Off"].src) img.src = oImages[id + "Hover"].src;
			else if (img.src == oImages[id + "Hover"].src) img.src = oImages[id + "Off"].src;
		} catch(ex) {;}
	}
}
//set attribute on image preventing it from being changed
function setImageAlwaysOn(id){	var img = document.getElementById(id + "Image");
	if (img){ toggleImage(id); img.setAttribute("alwayson","1");}
	//make sure valid reference was given
	//if (oImages[id + "Off"])
	//{
	//	oImages[id + "Off"].src = oImages[id + "On"].src;
	//	toggleImage(id);
	//}
}
// Unique Object //
function UniqueObjectDescriptor(id,name){this.id = id; this.name = name;}
// Activate Objects (workaround for IE change to <object> tag //
function activateObjects(){
	var o = document.getElementsByTagName("object");
	for (var i = 0; i < o.length; i++)
		o[i].outerHTML = o[i].outerHTML;
}
