// VAR SETUP
var blank = new Image();
blank.src = '/common/images/x.gif';

// WORK
$(document).ready(function() {
// Frame busting
	if(top.location != location) { top.location.href = document.location.href;} 
// Init
	TMinit();
// PNG fix
	fixPNG();
// js links
	prepJSLinks();
	$("#iconPrintPage").bind("click",printPage);
	$("#iconEmailPage").attr("href",$("#iconEmailPage").attr("href")+'&body=' + document.location);
	$("#iconSizeText").bind("click",toggleTextSize);
	
	if ( $("#jobsContainer").length >0 ) { ahah('corpAsp/rssJobs.asp', 'jobsContainer'); }
	if( $("body[class*='autoDL']").length == 1 ) { autoDownload(); }
	if ($('#fadeDeck').length != 0) { prepFadeDeck(); }
	
	
	
	
	
	
	
 });
 
// ## CODE
function fixPNG(scope) {
	var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
	if (badBrowser) {
		if (scope == null){ // fix whole page
			$('img[src$=.png]').each(function() {
				if (!this.complete) { this.onload = function() { applyPNGFix(this) }; } else { applyPNGFix(this); }
			}); 
		}else{
			if (scope.jquery) { applyPNGFix(scope); }// fix specific jquery object holding an img
			else{ // fix an elements child png's
				$('#'+scope+' img[src$=.png]').each(function() {
					if (!this.complete) { this.onload = function() { applyPNGFix(this) }; } else { applyPNGFix(this); }
				}); 
			}
		}
	}
}

function applyPNGFix(png) {
   var src = png.src;
   if (!png.style.width) { png.style.width = $(png).width(); }
   if (!png.style.height) { png.style.height = $(png).height(); }
   png.onload = function() { };
   png.src = blank.src;
   png.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + src + "',sizingMethod='scale')";
 }
 
function initDynContent(){
	var el;
	if ($("#hg").length>0){
		el = document.getElementById('imageGallery');
		crawl( el, prepHGLinks ); 
		fullSizePhoto = document.getElementById('bigPhoto');
		addEvent( fullSizePhoto, 'click', toggleHG );
	}
	if ( $("#media").length > 0 ) { addControls(); fixPNG("media"); }
	if ( $("#interfacePng").length > 0 ) { fixPNG("interfacePng"); }
	if ( $("#dynForm").length > 0 ) { 
		formStr = 'formData='; 
		$("#formSubmit").bind("click",handleFormSubmission);
		$("#dynForm [id*='Trigger']").bind("click",contextualSwitch);
		feedbackEl = $tco('userFeedback');
	}
	if ( $("#stepForm").length > 0 ) { 
		totalFormSteps = -1; // number of steps
		currentFormStep = 0; // users position in step order
		formStr = '';
		formStepsArray = new Array;
		masterReqSetArray = new Array;
		$("#formSubmit").bind("click",handleFormSubmission);
		$("#stepForm [id*='Trigger']").bind("click",contextualSwitch);
		crawl($tco('stepForm'), formStepBehavior );
		$("#totalPages").html(totalFormSteps + 1);
		feedbackEl = userFeedback; 
	}
} 
//## shorten by changing crawl call to $("[id*='Trigger']").bind("click",contextualSwitch)
function formBehavior() {
	if ( this.className && this.className.indexOf('trigger') != -1 ) { this.bind("click",contextualSwitch)}
}
function formStepBehavior() {
	if ( this.tagName && this.tagName.toLowerCase() == 'div' && this.className.indexOf('step ') != -1 ) { // divs are structure markers for steps
		totalFormSteps++; // add to var holding total number of steps
		formStepsArray[totalFormSteps] = this; // 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
			var stepButton = newEl('button','btTxt');
			$(stepButton).html('Next').bind("click",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 ( this.className && this.className.indexOf('reqSetContainer') != -1 ) {
		masterReqSetArray[totalFormSteps] = this; 
		masterReqSetArray[totalFormSteps].isValid = false; 
	} // adding this to our collection of reqSetContainers
}

function validateFormElement() {
	var formEl = this;
	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).attr('value').trim() == '' ) { // handle req elements, check for no value entered
			if (formEl.className.indexOf('err') == -1) { formEl.className += ' err'; }
			formEl.onfocus = resetValidState;
			formIsValid = false;
		}
	}
}

function startMedia() {
	var overlay, media, userFeedback, closeBut, closeX;
	$('#page').css("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').css("display",'block');
}

function autoDownload() { // initiate opening of a newsletter from a url with a get like 'm=november'
	var urlVars = document.location.search;
	if ( urlVars == "" ) { return; }
	var m = ['january', 'february',  'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
	for (i=0,t=m.length-1; i < t; i++) {
		if ( urlVars.indexOf("m="+m[i]) != -1 ) { findDownload(m[i]); }
	}
	function findDownload(x) {
		if ($("ul#newsletters a[href*="+x+"]:first").length!=0) {
			document.location = $("ul#newsletters a[href*="+x+"]:first").attr("href");
		}
	}
}

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;
	if (typeof urchinTracker != "undefined") {urchinTracker(temp);}
}
function uniqueID() {
	var temp = new Date;
	return temp.valueOf();
}

function prepJSLinks() {
	$("a[class*=' linktype']").click(function() {	
		//event.preventDefault();
		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 prepFadeDeck() { // set up fadeDeck; in place on index and retirement-communities
	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);

}

function feedback(msg, handOff, msgType) { 
	if ($(feedbackEl)) { 
		if (typeof(msg) && typeof(msg) == "string") {
			$(feedbackEl.messageNode).html(msg); 
			$(feedbackEl).css("display","block");
			handOff ? feedbackEl.onmouseup = handOff : null;
			if (msgType == 'err') { $(feedbackEl).attr('class','err'); }
			else if (msgType == 'msg') { $(feedbackEl).attr('class','msg'); }
		} else {
			 toggle(feedbackEl); 
		}
	}
}
function crawl(el, fn) { $(el).find("*").each(fn); }

function toggle(el) { $(el).css("display") == 'block' ? $(el).css("display",'none') : $(el).css("display",'block'); }

function printPage() { window.print(); return false; }

function turnOn(caller) { $('#overlay').css("display","block"); caller.css("display","block"); }

function loadAlphaVid(vid) {
	var objCode = $(vid).html().replace(/<(\/)*noscript>/gi,"");
	if (readCookie('tcoVid') == null) { // cookie not found, vid not seen
		createCookie("tcoVid","true",true);
		objCode = objCode.replace(/button/gi,"autoPlay");
	}
	$(vid).html(objCode);// Embedding
}

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();
			}
		}
	}
}