// FLAGS
isIE = !!window.ActiveXObject;
downloadComplete = false;
// GLOBALS
var bodyTag, feedbackEl, indicatorNode, altUrl, mapType, mediaSource, unique;
var searchableMap, floorplan, fadeDeck = new Array();
searchableMap = [ [ 'overlay', 'display',  'block'], ['page', 'overflow',  'hidden'],  ['media', 'display',  'block'] ];
floorplan = [ ['overlay', 'display',  'block'], ['overlay', 'height',  '450px'],  ['video', 'display',  'block'], ['docBox', 'd', '<object type=\"application/x-shockwave-flash\" data=\"Claremont217-floorplan.swf\" width=\"320\" height=\"280\"><param name=\"movie\" value=\"Claremont217-floorplan.swf\" /><p>Alternative content</p></object>'] ];
fadeDeck = [ ['card1'], ['card2'], ['card3'] ];
function $() {
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;

	function get$(el){
		if (typeof el == 'string') el = document.getElementById(el);
		return el;
	}
}
function flashToJs(flashInput) {
	if (flashInput == 'btn-close') { turnOff(); }
	else {
		for (var i in communities) { 
			if ( flashInput == communities[i].acronym ) { 
				urchinTracker('exit-To/comm-site/actionBox-flashMap/' + communities[i].acronym );
				window.location = communities[i].site_uri;
			}
		}
	}
}
function startMedia() {
	var overlay, media, userFeedback, closeBut, closeX;
	$('page').style.overflow = 'hidden';
	window.scrollTo(0, 0);
	bodyTag = document.body;
	if( (this.className.indexOf('mapType') != -1) ) {
		if(this.className.indexOf('-linkOut') != -1) { launchOverlay('0.80'); launchMediaContainer('none', false); }	
		else { launchOverlay(); launchMediaContainer(); }
	} else {
		launchOverlay();
		launchMediaContainer();
	}
	typeof(altUrl) == "string" ? mediaSource = altUrl : mediaSource = this.href;
	track('overlay', this.pathname);
	ahah(mediaSource);
	altUrl = null;
	$('media').style.display = 'block';
}
function track(eventType,obj,genUnique) { // eventType is overlay, obj is pathname of new content loaded into browser, unique is a boolean switch to assign a unique number to the end of the track hit
	var temp = eventType;
	window.location.pathname.length == 1 ? temp += '/index.htm' : temp += (window.location.pathname);
	temp += (obj);
	genUnique ? unique = uniqueID() : unique = null;
	unique != null ? temp += unique : null;
	urchinTracker(temp);
}
function uniqueID() {
	var temp = new Date;
	return temp.valueOf();
}
function launchOverlay(opacLvl) { // if passed, always pass in opacity formatted as a string and in firefox style, i.e. 1.0 or 0.55 or such
	var o = opacLvl;
	if(!$('overlay')) {
		overlay = newEl('div','overPanel','id:overlay');
		overlay.style.height = bodyTag.offsetHeight;
		bodyTag.appendChild(overlay);
		overlay.innerHTML = '&nbsp;';
		if (isIE) {
			if (o != null) { overlay.style.filter = 'alpha(opacity = ' + (o * 100) + ')'; }
		} else if (o != null) { overlay.style.opacity =  o; }
	} else { // if overlay exists still apply custom opacity
		if (isIE) {
			if (o != null) { overlay.style.filter = 'alpha(opacity = ' + (o * 100) + ')'; }
		} else if (o != null) { overlay.style.opacity =  o; }
	}
	$('overlay').style.display = 'block';
}
function launchMediaContainer( buttons, visible ) {
	var btn;
	if(!$('media')) {	
		media = newEl('div','toolPanel','id:media');
		bodyTag.appendChild(media);
		if ( buttons == 'none' ) { media.useButtons = false; }
		if ( visible == false ) { media.className += ' invisible'; }
	} else { // if media exists still apply invisiblity
		if ( visible == false ) { 
			media.className += ' invisible';
		}
		if ( buttons == 'none' ) {
			if ( btn = $('closeBut') ) { btn.style.display = 'none'; btn = null; }
			if ( btn = $('closeBut') ) { btn.style.display = 'none'; btn = null; }
		}
	}
}
function newEl(elType,elClass,elId) {
	var obj = document.createElement(elType); // create el - required
	if (elClass) { obj.className = elClass; } // set class name - optional
	var argsLen = newEl.arguments.length; 
	if ( argsLen > 2 ) { // test for presence of other args - optional
		var args = newEl.arguments; // short name for array
		for ( i=2; i < argsLen; i++) { // 2 = skip el creation and className args
			var curArg = args[i];
			var colonPos = curArg.indexOf(':');
			obj.setAttribute( curArg.substring(0,colonPos), curArg.substring(colonPos+1,curArg.length + 1) ); // parse args at colon with attName:attribute as the format
		}
	}
	return obj;
}
function addControls() {
	var media = $('media');
	if (media.useButtons == false) { return true;}
	userFeedback = newEl('div','','id:userFeedback','title:Click to close this message','alt:Click to close this message'); // user messages
	userFeedback.onmouseup = feedback;
	
	bg1 = newEl('img','abs ufBg','id:interfacePng','src:images/bg-uf-blue.png','width:409','height:64');
	userFeedback.appendChild(bg1);
	
	ufTxt = newEl('p','','id:ufTxt');
	ufTxt.innerHTML = '&nbsp;'
	userFeedback.appendChild(ufTxt);
	
	userFeedback.messageNode = ufTxt;
	
	media.appendChild(userFeedback);
	
	closeBut = newEl('div','','id:closeBut','title:Click to close this form','alt:Click to close this form');
	closeBut.innerHTML = '&nbsp;';
	closeBut.pointer = 'media';
	closeBut.onclick = turnOff;
	media.appendChild(closeBut);
	
	closeX = newEl('div','','id:closeX','title:Click to close this form','alt:Click to close this form');
	closeX.innerHTML = '&nbsp;';
	closeX.onclick = turnOff;
	media.appendChild(closeX);
}

function turnOff( saveContent ) { 
	if (this.pointer) { var el = $( this.pointer ); } else { var el = $( 'media' );} // future setup to point at other objects as the turnOff target with a default to the media overlay
	removeNode($('overlay'));
	removeNode(el);
	$('page').style.overflow = 'auto';
	saveContent == undefined ?  el.innerHTML = '&nbsp;' : null;
}
function removeNode(el) {
	var parentEl = el.parentNode;
	parentEl.removeChild(el);
}

function feedback(msg, handOff, msgType) { // i think handOff was 
	if (feedbackEl) { // if feedbackEl exists; register this el upon load dyn content
		if (typeof(msg) && typeof(msg) == "string") {
			feedbackEl.style.display = 'block'; 
			feedbackEl.messageNode.innerHTML = msg; 
			handOff ? feedbackEl.onmouseup = handOff : null;
			if (msgType == 'err') { feedbackEl.messageNode.className = 'err'; }
			else if (msgType == 'msg') { feedbackEl.messageNode.className = 'msg'; }
		} else {
			 toggle(feedbackEl); 
		}
	}
}
function formBehavior(el) {
	var temp = el;
	if ( temp.className && temp.className.indexOf('trigger') != -1 ) {
		temp.onclick = contextualSwitch;
	}
}
function formStepBehavior(el) {
	var temp = el;
	var stepButton;
	if ( temp.tagName && temp.tagName.toLowerCase() == 'div' && temp.className.indexOf('step ') != -1 ) { // divs are structure markers for steps
		totalFormSteps++; // add to var holding total number of steps
		formStepsArray[totalFormSteps] = el; // add div to array holding references to all steps
		if ( totalFormSteps != 0 ) {  // skipping first run through - we will only create this button dynamically if there is more than one step
			stepButton = newEl('button','btTxt');
			stepButton.innerHTML = 'Next';
			stepButton.onclick = handleFormSubmission;
			formStepsArray[totalFormSteps - 1].appendChild(stepButton); //appending the button to the previous step, skipping appending to the last step in the sequence which contains a submit button from the html source
			formStepsArray[totalFormSteps - 1].nextButton = stepButton;
		}
	}
	if ( temp.className && temp.className.indexOf('trigger') != -1 ) { temp.onclick = contextualSwitch; }
	if ( temp.className && temp.className.indexOf('reqSetContainer') != -1 ) {
		masterReqSetArray[totalFormSteps] = temp; 
		masterReqSetArray[totalFormSteps].isValid = false; 
	} // adding this to our collection of reqSetContainers
}
function contextualSwitch() {
	var trigger = this;
	var target;
	for (i=1; i < 100; i++) {
		target = $(this.id + i);
		if ( target == undefined ) { i=101; break; }
		if ( target.className.indexOf('setRQ') != -1 ) { toggleReq(target); }
		if ( target.className.indexOf('setVIS') != -1 ) { toggle(target); }
	}
}
function toggleReq(el) {
	if ( el.tagName.toLowerCase() == 'label' || el.tagName.toLowerCase() == 'p' ) { 
		alert(el.tagName);
		if ( el.innerHTML.indexOf('required') != -1 ) { el.innerHTML = el.innerHTML.replace(/<em>(required)<\/em>/, ''); } 
		else { el.innerHTML += '<em>(required)</em>'; }
	}
	if ( el.tagName.toLowerCase() == 'input' ) {
		if ( el.className.indexOf('req') != -1) { 
			el.className = el.className.replace(/ req/, ''); 
			if ( el.className.indexOf('err') != -1 ) { el.className = el.className.replace(/err/, ''); } // if this is marked as a current error remove this as well since we are marking input as optional
		} else { el.className += ' req '; }
	}
}
function resetValidState() {
	var callingElement = this; 
	if (callingElement.className.indexOf('reqSet') != -1 ) {
		while ( callingElement.tagName.toLowerCase() != 'form' && callingElement.className.indexOf('reqSetContainer') == -1 )  { //  climb till we hit reqSetContainer with a safety stop at form el
			callingElement = callingElement.parentNode; 
		}
	}
	if (callingElement.className.indexOf('err') != -1) {
		callingElement.className = callingElement.className.replace(/ err/, '');
	}
}
function handleFormSubmission() {
	var formObj = formStepsArray[currentFormStep];
	formIsValid = true;
	crawl(formObj,validateFormElement); // either crawl the whole form or if stepForm crawl a step div
	if ( masterReqSetArray[currentFormStep] ) {
		if ( !masterReqSetArray[currentFormStep].isValid ) {
			formIsValid = false;
			if ( masterReqSetArray[currentFormStep].className.indexOf('err') == -1 ) { 
				masterReqSetArray[currentFormStep].className += ' err';
			}
		} 
		masterReqSetArray[currentFormStep].isValid = false; // make sure this is reading false  in case this step is re-evaluated at a later point, say by another form el making the step invalid
	}
	if (formIsValid) {
		if (formObj.tagName.toLowerCase() == 'div') { // if we are validating a step
			if (totalFormSteps == currentFormStep) { // we are crawling the last step and its been validated
				crawl($('stepForm'),packageFormData);
				track('overlay',whichForm,true); // register a tracking hit with a unique number for a successful submission
				unique != null ? whichForm += ('-' + unique) : null;
				formStr += '&target=' + formTarget + '&form=' + whichForm; // add form specifics
				ahah( '/php/phpmailhtml.php', 'passBack', 'POST', formStr);
				loadFormSuccessMessage();
			} else { // we have more steps to go and this is valid
				advanceForm();
			}
		}
	} else { feedback('Please correct errors in the form',null,'err'); }
	return false;
}
function loadFormSuccessMessage() {
	mediaSource = mediaSource.replace(/.htm/,'-success.htm');
	ahah(mediaSource);
}
function advanceForm() {
	formStepsArray[currentFormStep].style.marginTop = -400 + 'px';
	currentFormStep++;
	$('currentPage').innerHTML = currentFormStep + 1;
	if (currentFormStep == totalFormSteps) { $('formSubmit').value = 'Submit';} // check if we are advancing to last step and, if so, change submit button text to Submit
}
function validateFormElement(el) {
	formEl = el;
	if ( formEl.className && formEl.className.indexOf('req') != -1 ) {
		if ( formEl.className.indexOf('reqSetContainer') != -1 ) { return true; } // handle reqSetContainer elements
		
		if ( formEl.className.indexOf('reqSet') != -1 ) { // handle reqSet elements
			var tempContainer = formEl;
			while ( tempContainer.className.indexOf('reqSetContainer') == -1 )  { tempContainer = tempContainer.parentNode; } //  climb till we hit reqSetContainer with a safety stop at form el
			if ( formEl.checked == false ) { formEl.onfocus = resetValidState; } 
			else { tempContainer.isValid = true; } // check 
			return true;
		}
			
		if ( formEl.value == '' ) { // handle req elements, check for no value entered
			if (formEl.className.indexOf('err') == -1) { formEl.className += ' err'; }
			formEl.onfocus = resetValidState;
			formIsValid = false;
		}
	}
}
function packageFormData(formElm) {
	var passedEl = formElm; 
	if ( ( !passedEl.tagName ) || ( passedEl.tagName.toLowerCase() != 'input' && passedEl.tagName.toLowerCase() != 'select' && passedEl.tagName.toLowerCase() != 'textarea' ) ) { return true; } // skip non important nodes
	
	if ( passedEl.getAttribute('name') == 'form' ) { whichForm = escape(passedEl.getAttribute('value')); return true; } // form name
	if ( passedEl.getAttribute('name') == 'target' ) { formTarget = escape(passedEl.getAttribute('value')); return true; } // target code
	
	if (passedEl.getAttribute('type') &&  (passedEl.getAttribute('type')=='radio' || passedEl.getAttribute('type')=='checkbox') ) { //  checked radio value
		if (!passedEl.checked) { return true; }
	}
	
	if (passedEl.value != '') { formStr = formStr + "<h4>" + passedEl.name + "</h4><p>" + escape(passedEl.value) + "</p>"; } // record value for all else
}

function TMinit() {
	var el; // general use 
	if ( el = $('png')) { fixPng(el); el = null; }
	prepJSLinks();
	if (!!document.getElementById('fadeDeck')) { // set up fadeDeck; in place on index and retirement-communities.htm
		topCard = 0;
		next = topCard + 1;
		lastCard = fadeDeck.length-1;
		iePre = null;
		iePost = null;
		opacStep = .05;
		opaque = 1;
		currentOpacity = 0;
		(isIE) ? setIEOpacity() : styler = 'opacity';
		homeGallery = window.setInterval('switchDeck()', 9000);
	}
	if (!!document.getElementById('contactMap')) {// set up flash map on contact.htm
		var oeTags = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'
		+ 'width="499" height="423"'
		+ 'codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">'
		+ '<param name="movie" value="sitemapusa.swf" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />'
		+ '<embed src="sitemapusa.swf" quality="high" bgcolor="#ffffff" '
		+ 'width="499" height="423" name="siteMapUSA" align="middle"'
		+ 'play="true"'
		+ 'loop="false"'
		+ 'quality="high"'
		+ 'allowScriptAccess="sameDomain"'
		+ 'type="application/x-shockwave-flash"'
		+ 'pluginspage="http://www.macromedia.com/go/getflashplayer">'
		+ '<\/embed>'
		+ '<\/object>';
		document.getElementById('contactMap').innerHTML = oeTags;   
	}
	if (document.body.className && document.body.className.indexOf('autoDL') != -1) { autoDownload(); }
	
	if (el = document.getElementById('iconPrintPage')) { el.onclick = printPage; el = null; }
	if (el = document.getElementById('iconEmailPage')) { el.href += '&body=' + document.location; el = null; }
	if (el = document.getElementById('txtWidget')) { el.onclick = toggleTextSize; el = null; }
	if (el = document.getElementById('iconSizeText')) { el.onclick = toggleTextSize; el = null; }
	if (el = $('jobsContainer')) { ahah('corpAsp/rssJobs.asp', 'jobsContainer'); }
}
function emailPage() {
	this.href += '&amp;body='+document.location;
	return true;
}
function initDynContent(){
	var el;
	if (document.getElementById('hg')) { 
		el = document.getElementById('imageGallery');
		crawl( el, prepHGLinks ); 
		fullSizePhoto = document.getElementById('bigPhoto');
		addEvent( fullSizePhoto, 'click', toggleHG );
	}
	if( $('media')) { addControls(); }
	if ( el = $('dynPng')) { fixPng(el); el=null; }
	if ( el = $('interfacePng')) { fixPng(el); el=null; } //  interfacePng is a js created img element used in the user feedback-error/success messaging
	if ( $('dynForm')) { 
		formStr = 'formData=';
		$('formSubmit').onclick = handleFormSubmission; 
		crawl($('dynForm'), formBehavior ); 
		feedbackEl = $('userFeedback');
	}
	if ( $('stepForm')) { 
		totalFormSteps = -1; // number of steps
		currentFormStep = 0; // users position in step order
		formStepsArray = new Array;
		masterReqSetArray = new Array;
		formStr = 'formData=';
		$('formSubmit').onclick = handleFormSubmission; 
		crawl($('stepForm'), formStepBehavior );
		$('totalPages').innerHTML = totalFormSteps + 1;
		feedbackEl = $('userFeedback'); 
	}
}

function autoDownload() { // at the moment used only to initiate an automatic download of a newsletter from a url with name/value pair 'm=november' or some such
		var urlVars = document.location.search;
		if ( urlVars == "" ) { return; }
		var downloadTags = ['january', 'february',  'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
		for (tagInc=0; tagInc < downloadTags.length-1; tagInc++) {
			if ( urlVars.indexOf(downloadTags[tagInc]) != -1 ) { //found a tag in the url
				try {
					newsletterList = document.getElementById('newsletters');
					crawl(newsletterList,findDownload);
				}
				catch(e) { break; }
			}
		}
		function findDownload(x) {
			if (x.tagName && x.tagName.toLowerCase() == 'a' && x.href.toLowerCase().indexOf(downloadTags[tagInc]) != -1) {
				if ( !downloadComplete ) { 
					document.location = x.href;
					downloadComplete = true;
				}
				return false;
			}
		}
	}
function prepJSLinks() {
		var x = document.links.length;
		for( i=0; i < x; i++ ) {
			if ( document.links[i].className.search(/linktype/) != -1 ) { document.links[i].onclick=handleJSClick;}
		}
	}
function handleJSClick() {
	if ( this.className.search(/overlay/) != -1 ) { startMedia.apply(this); return false; 
	} else if ( this.className.search(/contextual/) != -1 ) { contextLink.apply(this); return false;
	} else { return true; }
	
}
function contextLink() {
	var obj = this;
	do { 
		obj = obj.parentNode; 
	} while ( !obj.className || (!!obj.className && obj.className.indexOf('contextual') == -1) )
	if ( !!this.className || this.className.indexOf('expand') == -1 ) { toggleClass(obj, 'active'); } 
}
function prepHGLinks(e) {
	gallery = document.getElementById('hg');
	gallery.state = 'thumbs';
	if ( e.tagName ) { 
		if ( e.tagName.toLowerCase() == 'a' ) { 
			e  = e.firstChild; // get inside
			if ( e.tagName.toLowerCase = 'img' ) { //check for an image
				imgSrc = e.src;
				imgSrcEnd = imgSrc.slice(-4);
				imgSrc = imgSrc.substring(0, (imgSrc.length-7));
				newSrc = imgSrc + imgSrcEnd;
				e = e.parentNode;
				e.largeVersionURI = newSrc;
				addEvent( e, 'click', showLargeVersion );
			}
		}
	}
	
}//if (popups[i].rel.indexOf("popup")!=-1)
function showLargeVersion() {
	fullSizePhoto.src = 'images/spinLargePhoto.gif';
	fullSizePhoto.src = this.largeVersionURI;
	toggleHG();
	return false;
}
function toggleClass(el, classStr) {
	if (el.className) {
		if (el.className.indexOf(classStr) == -1) { 
			el.className += (' ' + classStr); 
		} else { 
			classStr = new RegExp(classStr,'i'); 
			el.className = el.className.replace(classStr,''); 
		} 
	}
}
function toggleHG() {
	if (gallery.state == 'thumbs') { 
		gallery.style.top = '-408px';
		gallery.state = "large";
		return false;
	} else { 
		gallery.style.top = '0';
		gallery.state = "thumbs";
		return false;
	}
}
function setIEOpacity () {
	iePre = 'alpha(opacity=';
	iePost = ')';
	styler = 'filter';
	opaque = 100;  //fully opaque setting for ie
	opacStep = 5;  // adjust the step size to reflect larger opaque value
}
function fadeIn() {
	if ( currentOpacity < opaque ) { 
		nextCard.style[styler] = (iePre + (currentOpacity += opacStep) + iePost);
		setTimeout("fadeIn()", 10); 
	} 
	else { 
		if ( currentOpacity >= opaque ) {
			nextCard.style[styler] = iePre + opaque + iePost; // correct for any funkiness in the numerals
			currentOpacity = opaque;
			fadeOut(); 
		}
	}
}
function fadeOut() {
	if ( currentOpacity > opacStep ) { 
		curCard.style[styler] = (iePre + (currentOpacity -= opacStep) + iePost);
		setTimeout("fadeOut()", 10); 
	}
	else {
		if ( currentOpacity <= opacStep ) {
			curCard.style[styler] = iePre + 0 + iePost; // correct for any funkiness in the numerals
			topCard = next; //set up markers for next round of transitions
			if ( topCard == lastCard ) { next = 0;} else { next++; } //check to see if we are at the end of the array
		}
			
	}
}
function switchDeck() {
	curCard = document.getElementById(fadeDeck[topCard]);
	nextCard = document.getElementById(fadeDeck[next]);
	fadeIn();
	counter = 0;
}
function runCard(card) {
	var limit = 0;
	var obj;
	limit = (card.length);
	
	for ( i = 0; i != limit; i++) { 
		switch ( card[i][1] ) {
			case 'c':
				obj = document.getElementById(card[i][0]); obj.className= card[i][2];
				break;
			
			case 'f':
				card[i][2](card[i][0]);
				break;
			
			case 'd':
				obj = document.getElementById(card[i][0]); obj.innerHTML= card[i][2];
			 	break;
			 
			default:
				 obj = document.getElementById(card[i][0]); obj.style[card[i][1]]= card[i][2];
		}
	}
}

function ahah(url,target,methodType,dataToPass) {
	if (methodType && methodType.toUpperCase() == "POST") { var meth = "POST"; } else { var meth = "GET"; }
	if (dataToPass) { var dataPackage = dataToPass; } else { var dataPackage = null; }
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        req.onreadystatechange = function() {ahahDone(target);};
        req.open(meth, url, true);
		if (meth=="POST") {req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");}
        req.send(dataPackage);
    } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = function() {ahahDone(target);}
            req.open(meth, url, true);
			if (meth=="POST") {req.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");}
            dataPackage ? req.send(dataPackage) : req.send();
        }
    }
} 
function ahahDone(target) {
   // only if req is "loaded"
   if (req.readyState == 4) {
       // only if "OK"
       if (req.status == 200 || req.status == 304) {
		   	results = req.responseText;
			if (target == 'passBack') { // decide what needs to be done with data
				return results;
			} else {
				if (!target) { target = 'media' } // if no target value is passed then default to media
				var markerStart = results.indexOf('<bod'); // extract data from body tag if this proves to be more than just a html fragment
				if ( markerStart != -1) { 
					var markerEnd = markerStart;
					do { markerEnd++; } while( results.slice(markerEnd, markerEnd + 1) != '>' ); // crawls to end of body tag
					var openingBodyTag = results.substr(markerStart, markerEnd-markerStart);
					if (openingBodyTag.indexOf('class') != -1) { 
						rExp = /\".*\"/; // matches whatever is between double quotes
						extractedClass = openingBodyTag.match(rExp);
						extractedClass = extractedClass[0];
						extractedClass = extractedClass.substr(1,extractedClass.length - 2);
					} else { extractedClass = ""; }
					
					results = results.substring( (markerEnd+2), ((results.indexOf('</bod'))-1) ); 
					document.getElementById(target).className += ' ' + extractedClass;
				}
				document.getElementById(target).innerHTML = results;
				initDynContent(); // check for any js that needs to be run for new content
			}
		} else {
           document.getElementById(target).innerHTML="ahah error:\n" +
               req.statusText;
       }
   }
}

function printPage() { window.print(); return false; }
function toggle(el) { el.style.display == 'block' ? el.style.display = 'none' : el.style.display = 'block'; }
function turnOn(caller) { $('overlay').style.display = 'block'; $( caller ).style.display = 'block' }
function fixPng (el) { // enables PNG transparency for IE 5-6; tag transparent png's with an id of png, then png1, then png2 and so on
	if ( isIE && ((navigator.userAgent.indexOf('MSIE 6') != -1) || (navigator.userAgent.indexOf('MSIE 5') != -1)) ) {
		var origSrc, ref, i;
		ref = el.id;
		i = 0;
		while(el) {
			origSrc = el.src;
			el.src = "images/x.gif";
			el.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + origSrc + "',sizingMethod='scale')";
			if (el.id.indexOf('interfacePng') != -1) { el.style.position = 'absolute'; el.style.top = 0; el.style.left = 0; }
			i++;
			el = document.getElementById(ref + i);
		}
	}
	el = null;
}
function attachSeries(elId, fn) {
	var temp;
	var i = 1;
	if (temp = $(elId)) { 
		do { temp.onclick = fn; } 
		while (temp = $(elId + i++));
	}
}
function crawl(el, fn) {  // takes an element and crawls every element inside and runs a specified function on it
	var level= 0;
	do {
		while ( el.firstChild ) {
			el = el.firstChild;
			fn(el);
			level++;
		}
		if ( el.nextSibling ) {
			el = el.nextSibling;
			fn(el);
		}
		else {
			climb:
			for ( i = level; i > 0; i-- ) {
				el = el.parentNode;
				level--;
				if ( el.nextSibling ) {
					el = el.nextSibling;
					fn(el);
					break climb;
				}
			}
		}
	} while ( level > 0 )
	return false;
}

function LoadMapSearchControl() { // searchable gmap load code
      var options = {
            zoomControl : GSmapSearchControl.ZOOM_CONTROL_ENABLE_ALL,
            title : "Touchmark Central Offices",
            url : "http://Touchmark.com",
            idleMapZoom : GSmapSearchControl.ACTIVE_MAP_ZOOM,
            activeMapZoom : GSmapSearchControl.ACTIVE_MAP_ZOOM
            }

      new GSmapSearchControl(
            document.getElementById("mapsearch"),
            "5150 sw griffith drive, beaverton, oregon",
            options
            );
	// arrange for this function to be called during body.onload
    // event processing
	
    }
function readGACookie(name) { // used with sleuth
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function getRef() { // used with sleuth
	ref = document.referrer;
	re = /(\?|&)(q|p)=([^&]*)/;
	searchq = re.exec(ref);
	if(searchq) {
		__utmSetVar(searchq[3]);
	}
}
function sleuth() {
	// Name: Google Analytics Keyword Sleuth / Author: Michael Harrison  / Grabs exact keywords users hit site from
	if (document.cookie.indexOf("__utmz=") != -1)
	{
		z = readGACookie('__utmz');
		za = z.split('|');
		t = za[0].split('.');
		za[0] = t[t.length - 1];
		for (i = 0; i < za.length; i++)
		{	
			t2 = za[i].split('=');
			if (t2[0] == 'utmgclid' || t2[1] == 'cpc' || t2[1] == 'ppc')	{
				getRef();
			}
		}
	}
}
   
function addEvent( obj, type, fn ) { // addEvent via Dustin Diaz at http://www.dustindiaz.com/rock-solid-addevent/
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}
var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window, 'load', TMinit);
addEvent(window,'unload',EventCache.flush);