//if (parent.frames.length > 0) top.location.replace(document.location);

document.observe('dom:loaded', function() {
	$$('html').invoke('addClassName', 'JS-active');
});

document.observe('dom:loaded', function() {
	$$('.tipPopup').each(function(el) {
		var tipAnchor = new Element('a', { 'href': '#', 'class': el.className }).update(el.select('.tipLabel')[0].innerHTML);
		var tipPopup = new Element('div', { 'class': 'tip' }).update('<a href="#" class="close" onclick="$(this).up().hide();return false;">Close</a><table border="0" cellpadding="0" cellspacing="0"><tr><td class="topLeftCorner"><!-- blank --></td><td class="topSide" colspan="3"><!-- blank --></td><td class="topRightCorner"><!-- blank --></td></tr><tr><td class="leftSide"><!-- blank --></td><td colspan="3" class="tipContent" style="font-size:10px;">' + el.select('.tipContent')[0].innerHTML + '</td><td class="rightSide"><!-- blank --></td></tr><tr><td class="btmLeftCorner"><!-- blank --></td><td class="btmSide beforePoint"><!-- blank --></td><td class="btmPoint"><!-- blank --></td><td class="btmSide afterPoint"><!-- blank --></td><td class="btmRightCorner"><!-- blank --></td></tr></table></div>').hide();
		tipAnchor.observe('click', function(ev) {
			Event.stop(ev);

				// get tooltip element
				var el = this;
				// get element clicked on
				var obj = Event.element(ev);
				
				// calculate height of tooltip
				var h = el.getHeight();
				
				el.show();
				
				var x = obj.cumulativeOffset()[0];
				var y = obj.cumulativeOffset()[1] + 3;
				var dw = (document.body.getWidth() > 950) ? ((document.body.getWidth() - 950) * 0.5) : 0;
				
				el.setStyle({
					top: y - h + 'px',
					left: x - dw + (obj.getWidth()/2) - 49 + 'px'
				});
				
		}.bind(tipPopup));
		Element.insert(el, { after: tipPopup });
		Element.replace(el, tipAnchor);
	});
});

document.observe('dom:loaded', function() {
	$$('#moreLink').invoke('observe', 'click', function(e) {
		Event.stop(e);
		var el = Event.element(e);
		
		$('section_links').hide();
        if ($('section_1')) {
		    $('section_1').show();
        }
		
		$('content_main').setStyle({
			marginTop: "-30px"						   
		});
		$('content_aside').setStyle({ marginTop: "-30px" });
		
	});
});

document.observe('dom:loaded', function() {
	$$('#ctl00_bdyBody .searchAgain button').each(function(el) {
		el.onmouseenter = function() {
			this.addClassName("hover");
		};
		el.onmouseleave = function() {
			this.removeClassName("hover");
		};
	});	
});

document.observe('dom:loaded', function() {
	$$('#section_links.more').each(function(e) {
		e.show();
	});
    if ($('section_1')) {
	    $('section_1').hide();
    }
});

// Date Format Method
// copyright Stephen Chapman, 20th November 2007, 6th May 2009
// http://javascript.about.com
// permission to use this JavaScript on your web page is granted
// provided that all of the code below in this script (including these
// comments) is used without any alteration

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

document.observe('dom:loaded', function() {
	
	// create new divs for printable pages
	var printstamp = new Element('div', { 'id': 'printstamp' });	
	var printfooter = new Element('div', { 'id': 'printfooter' });
	
	// create contents of new elements
	var now = new Date();
	var thisDate = now.format('longDate');
	var thisTime = now.format('h:MM tt Z');
	var printDateTime = thisDate + " at " + thisTime;
	
    // if breadcrumb get its content, else ""
    var breadCrumbStr = ($$('div.breadcrumb')[0]) ? "This document retrieved from: "+$$('div.breadcrumb')[0].innerHTML : "";

	var printstamp_insert = "<p><span class='printDateTime'>"+printDateTime+"</span><span class='printBreadcrumb'>"+breadCrumbStr+"</span><span class='printUrl'>"+window.location+"</span></p>";
	
	printstamp.update(printstamp_insert);
	
	// insert new footer elements into footer
    if ($('legal')) {
	    Element.insert($('legal'), { 'before': printstamp });
    }
	
	// update printable footer with new footer contents
    if ($('footer')) {
	printfooter.update($('footer').innerHTML);
    }
	
	// insert new footer inside of content_main
	if ($('content_main')) {
		Element.insert('content_main', { 'bottom': printfooter });
	}
});

/*  ****************************************************************************
	To disable sIFR for Internet Explorer 6, uncomment the following line:

if (!(Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))<7)) {

	***************************************************************************/

/*****************************************************************************
scalable Inman Flash Replacement (sIFR) version 3, revision 436.

Copyright 2006 - 2008 Mark Wubben, <http://novemberborn.net/>

Older versions:
* IFR by Shaun Inman
* sIFR 1.0 by Mike Davidson, Shaun Inman and Tomas Jogin
* sIFR 2.0 by Mike Davidson, Shaun Inman, Tomas Jogin and Mark Wubben

See also <http://novemberborn.net/sifr3> and <http://wiki.novemberborn.net/sifr3>.

This software is licensed and provided under the CC-GNU LGPL.
See <http://creativecommons.org/licenses/LGPL/2.1/>
*****************************************************************************/

var sIFR=new function(){var O=this;var E={ACTIVE:"sIFR-active",REPLACED:"sIFR-replaced",IGNORE:"sIFR-ignore",ALTERNATE:"sIFR-alternate",CLASS:"sIFR-class",LAYOUT:"sIFR-layout",FLASH:"sIFR-flash",FIX_FOCUS:"sIFR-fixfocus",DUMMY:"sIFR-dummy"};E.IGNORE_CLASSES=[E.REPLACED,E.IGNORE,E.ALTERNATE];this.MIN_FONT_SIZE=6;this.MAX_FONT_SIZE=126;this.FLASH_PADDING_BOTTOM=5;this.VERSION="436";this.isActive=false;this.isEnabled=true;this.fixHover=true;this.autoInitialize=true;this.setPrefetchCookie=true;this.cookiePath="/";this.domains=[];this.forceWidth=true;this.fitExactly=false;this.forceTextTransform=true;this.useDomLoaded=true;this.useStyleCheck=false;this.hasFlashClassSet=false;this.repaintOnResize=true;this.replacements=[];var L=0;var R=false;function Y(){}function D(c){function d(e){return e.toLocaleUpperCase()}this.normalize=function(e){return e.replace(/\n|\r|\xA0/g,D.SINGLE_WHITESPACE).replace(/\s+/g,D.SINGLE_WHITESPACE)};this.textTransform=function(e,f){switch(e){case"uppercase":return f.toLocaleUpperCase();case"lowercase":return f.toLocaleLowerCase();case"capitalize":return f.replace(/^\w|\s\w/g,d)}return f};this.toHexString=function(e){if(e.charAt(0)!="#"||e.length!=4&&e.length!=7){return e}e=e.substring(1);return"0x"+(e.length==3?e.replace(/(.)(.)(.)/,"$1$1$2$2$3$3"):e)};this.toJson=function(g,f){var e="";switch(typeof(g)){case"string":e='"'+f(g)+'"';break;case"number":case"boolean":e=g.toString();break;case"object":e=[];for(var h in g){if(g[h]==Object.prototype[h]){continue}e.push('"'+h+'":'+this.toJson(g[h]))}e="{"+e.join(",")+"}";break}return e};this.convertCssArg=function(e){if(!e){return{}}if(typeof(e)=="object"){if(e.constructor==Array){e=e.join("")}else{return e}}var l={};var m=e.split("}");for(var h=0;h<m.length;h++){var k=m[h].match(/([^\s{]+)\s*\{(.+)\s*;?\s*/);if(!k||k.length!=3){continue}if(!l[k[1]]){l[k[1]]={}}var g=k[2].split(";");for(var f=0;f<g.length;f++){var n=g[f].match(/\s*([^:\s]+)\s*\:\s*([^;]+)/);if(!n||n.length!=3){continue}l[k[1]][n[1]]=n[2].replace(/\s+$/,"")}}return l};this.extractFromCss=function(g,f,i,e){var h=null;if(g&&g[f]&&g[f][i]){h=g[f][i];if(e){delete g[f][i]}}return h};this.cssToString=function(f){var g=[];for(var e in f){var j=f[e];if(j==Object.prototype[e]){continue}g.push(e,"{");for(var i in j){if(j[i]==Object.prototype[i]){continue}var h=j[i];if(D.UNIT_REMOVAL_PROPERTIES[i]){h=parseInt(h,10)}g.push(i,":",h,";")}g.push("}")}return g.join("")};this.escape=function(e){return escape(e).replace(/\+/g,"%2B")};this.encodeVars=function(e){return e.join("&").replace(/%/g,"%25")};this.copyProperties=function(g,f){for(var e in g){if(f[e]===undefined){f[e]=g[e]}}return f};this.domain=function(){var f="";try{f=document.domain}catch(g){}return f};this.domainMatches=function(h,g){if(g=="*"||g==h){return true}var f=g.lastIndexOf("*");if(f>-1){g=g.substr(f+1);var e=h.lastIndexOf(g);if(e>-1&&(e+g.length)==h.length){return true}}return false};this.uriEncode=function(e){return encodeURI(decodeURIComponent(e))};this.delay=function(f,h,g){var e=Array.prototype.slice.call(arguments,3);setTimeout(function(){h.apply(g,e)},f)}}D.UNIT_REMOVAL_PROPERTIES={leading:true,"margin-left":true,"margin-right":true,"text-indent":true};D.SINGLE_WHITESPACE=" ";function U(e){var d=this;function c(g,j,h){var k=d.getStyleAsInt(g,j,e.ua.ie);if(k==0){k=g[h];for(var f=3;f<arguments.length;f++){k-=d.getStyleAsInt(g,arguments[f],true)}}return k}this.getBody=function(){return document.getElementsByTagName("body")[0]||null};this.querySelectorAll=function(f){return window.parseSelector(f)};this.addClass=function(f,g){if(g){g.className=((g.className||"")==""?"":g.className+" ")+f}};this.removeClass=function(f,g){if(g){g.className=g.className.replace(new RegExp("(^|\\s)"+f+"(\\s|$)"),"").replace(/^\s+|(\s)\s+/g,"$1")}};this.hasClass=function(f,g){return new RegExp("(^|\\s)"+f+"(\\s|$)").test(g.className)};this.hasOneOfClassses=function(h,g){for(var f=0;f<h.length;f++){if(this.hasClass(h[f],g)){return true}}return false};this.ancestorHasClass=function(g,f){g=g.parentNode;while(g&&g.nodeType==1){if(this.hasClass(f,g)){return true}g=g.parentNode}return false};this.create=function(f,g){var h=document.createElementNS?document.createElementNS(U.XHTML_NS,f):document.createElement(f);if(g){h.className=g}return h};this.getComputedStyle=function(h,i){var f;if(document.defaultView&&document.defaultView.getComputedStyle){var g=document.defaultView.getComputedStyle(h,null);f=g?g[i]:null}else{if(h.currentStyle){f=h.currentStyle[i]}}return f||""};this.getStyleAsInt=function(g,i,f){var h=this.getComputedStyle(g,i);if(f&&!/px$/.test(h)){return 0}return parseInt(h)||0};this.getWidthFromStyle=function(f){return c(f,"width","offsetWidth","paddingRight","paddingLeft","borderRightWidth","borderLeftWidth")};this.getHeightFromStyle=function(f){return c(f,"height","offsetHeight","paddingTop","paddingBottom","borderTopWidth","borderBottomWidth")};this.getDimensions=function(j){var h=j.offsetWidth;var f=j.offsetHeight;if(h==0||f==0){for(var g=0;g<j.childNodes.length;g++){var k=j.childNodes[g];if(k.nodeType!=1){continue}h=Math.max(h,k.offsetWidth);f=Math.max(f,k.offsetHeight)}}return{width:h,height:f}};this.getViewport=function(){return{width:window.innerWidth||document.documentElement.clientWidth||this.getBody().clientWidth,height:window.innerHeight||document.documentElement.clientHeight||this.getBody().clientHeight}};this.blurElement=function(g){try{g.blur();return}catch(h){}var f=this.create("input");f.style.width="0px";f.style.height="0px";g.parentNode.appendChild(f);f.focus();f.blur();f.parentNode.removeChild(f)}}U.XHTML_NS="http://www.w3.org/1999/xhtml";function H(r){var g=navigator.userAgent.toLowerCase();var q=(navigator.product||"").toLowerCase();var h=navigator.platform.toLowerCase();this.parseVersion=H.parseVersion;this.macintosh=/^mac/.test(h);this.windows=/^win/.test(h);this.linux=/^linux/.test(h);this.quicktime=false;this.opera=/opera/.test(g);this.konqueror=/konqueror/.test(g);this.ie=false/*@cc_on||true@*/;this.ieSupported=this.ie&&!/ppc|smartphone|iemobile|msie\s5\.5/.test(g)/*@cc_on&&@_jscript_version>=5.5@*/;this.ieWin=this.ie&&this.windows/*@cc_on&&@_jscript_version>=5.1@*/;this.windows=this.windows&&(!this.ie||this.ieWin);this.ieMac=this.ie&&this.macintosh/*@cc_on&&@_jscript_version<5.1@*/;this.macintosh=this.macintosh&&(!this.ie||this.ieMac);this.safari=/safari/.test(g);this.webkit=!this.konqueror&&/applewebkit/.test(g);this.khtml=this.webkit||this.konqueror;this.gecko=!this.khtml&&q=="gecko";this.ieVersion=this.ie&&/.*msie\s(\d\.\d)/.exec(g)?this.parseVersion(RegExp.$1):"0";this.operaVersion=this.opera&&/.*opera(\s|\/)(\d+\.\d+)/.exec(g)?this.parseVersion(RegExp.$2):"0";this.webkitVersion=this.webkit&&/.*applewebkit\/(\d+).*/.exec(g)?this.parseVersion(RegExp.$1):"0";this.geckoVersion=this.gecko&&/.*rv:\s*([^\)]+)\)\s+gecko/.exec(g)?this.parseVersion(RegExp.$1):"0";this.konquerorVersion=this.konqueror&&/.*konqueror\/([\d\.]+).*/.exec(g)?this.parseVersion(RegExp.$1):"0";this.flashVersion=0;if(this.ieWin){var l;var o=false;try{l=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")}catch(m){try{l=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");this.flashVersion=this.parseVersion("6");l.AllowScriptAccess="always"}catch(m){o=this.flashVersion==this.parseVersion("6")}if(!o){try{l=new ActiveXObject("ShockwaveFlash.ShockwaveFlash")}catch(m){}}}if(!o&&l){this.flashVersion=this.parseVersion((l.GetVariable("$version")||"").replace(/^\D+(\d+)\D+(\d+)\D+(\d+).*/g,"$1.$2.$3"))}}else{if(navigator.plugins&&navigator.plugins["Shockwave Flash"]){var n=navigator.plugins["Shockwave Flash"].description.replace(/^.*\s+(\S+\s+\S+$)/,"$1");var p=n.replace(/^\D*(\d+\.\d+).*$/,"$1");if(/r/.test(n)){p+=n.replace(/^.*r(\d*).*$/,".$1")}else{if(/d/.test(n)){p+=".0"}}this.flashVersion=this.parseVersion(p);var j=false;for(var k=0,c=this.flashVersion>=H.MIN_FLASH_VERSION;c&&k<navigator.mimeTypes.length;k++){var f=navigator.mimeTypes[k];if(f.type!="application/x-shockwave-flash"){continue}if(f.enabledPlugin){j=true;if(f.enabledPlugin.description.toLowerCase().indexOf("quicktime")>-1){c=false;this.quicktime=true}}}if(this.quicktime||!j){this.flashVersion=this.parseVersion("0")}}}this.flash=this.flashVersion>=H.MIN_FLASH_VERSION;this.transparencySupport=this.macintosh||this.windows||this.linux&&(this.flashVersion>=this.parseVersion("10")&&(this.gecko&&this.geckoVersion>=this.parseVersion("1.9")||this.opera));this.computedStyleSupport=this.ie||!!document.defaultView.getComputedStyle;this.fixFocus=this.gecko&&this.windows;this.nativeDomLoaded=this.gecko||this.webkit&&this.webkitVersion>=this.parseVersion("525")||this.konqueror&&this.konquerorMajor>this.parseVersion("03")||this.opera;this.mustCheckStyle=this.khtml||this.opera;this.forcePageLoad=this.webkit&&this.webkitVersion<this.parseVersion("523");this.properDocument=typeof(document.location)=="object";this.supported=this.flash&&this.properDocument&&(!this.ie||this.ieSupported)&&this.computedStyleSupport&&(!this.opera||this.operaVersion>=this.parseVersion("9.61"))&&(!this.webkit||this.webkitVersion>=this.parseVersion("412"))&&(!this.gecko||this.geckoVersion>=this.parseVersion("1.8.0.12"))&&(!this.konqueror)}H.parseVersion=function(c){return c.replace(/(^|\D)(\d+)(?=\D|$)/g,function(f,e,g){f=e;for(var d=4-g.length;d>=0;d--){f+="0"}return f+g})};H.MIN_FLASH_VERSION=H.parseVersion("8");function F(c){this.fix=c.ua.ieWin&&window.location.hash!="";var d;this.cache=function(){d=document.title};function e(){document.title=d}this.restore=function(){if(this.fix){setTimeout(e,0)}}}function S(l){var e=null;function c(){try{if(l.ua.ie||document.readyState!="loaded"&&document.readyState!="complete"){document.documentElement.doScroll("left")}}catch(n){return setTimeout(c,10)}i()}function i(){if(l.useStyleCheck){h()}else{if(!l.ua.mustCheckStyle){d(null,true)}}}function h(){e=l.dom.create("div",E.DUMMY);l.dom.getBody().appendChild(e);m()}function m(){if(l.dom.getComputedStyle(e,"marginLeft")=="42px"){g()}else{setTimeout(m,10)}}function g(){if(e&&e.parentNode){e.parentNode.removeChild(e)}e=null;d(null,true)}function d(n,o){l.initialize(o);if(n&&n.type=="load"){if(document.removeEventListener){document.removeEventListener("DOMContentLoaded",d,false)}if(window.removeEventListener){window.removeEventListener("load",d,false)}}}function j(){l.prepareClearReferences();if(document.readyState=="interactive"){document.attachEvent("onstop",f);setTimeout(function(){document.detachEvent("onstop",f)},0)}}function f(){document.detachEvent("onstop",f);k()}function k(){l.clearReferences()}this.attach=function(){if(window.addEventListener){window.addEventListener("load",d,false)}else{window.attachEvent("onload",d)}if(!l.useDomLoaded||l.ua.forcePageLoad||l.ua.ie&&window.top!=window){return}if(l.ua.nativeDomLoaded){document.addEventListener("DOMContentLoaded",i,false)}else{if(l.ua.ie||l.ua.khtml){c()}}};this.attachUnload=function(){if(!l.ua.ie){return}window.attachEvent("onbeforeunload",j);window.attachEvent("onunload",k)}}var Q="sifrFetch";function N(c){var e=false;this.fetchMovies=function(f){if(c.setPrefetchCookie&&new RegExp(";?"+Q+"=true;?").test(document.cookie)){return}try{e=true;d(f)}catch(g){}if(c.setPrefetchCookie){document.cookie=Q+"=true;path="+c.cookiePath}};this.clear=function(){if(!e){return}try{var f=document.getElementsByTagName("script");for(var g=f.length-1;g>=0;g--){var h=f[g];if(h.type=="sifr/prefetch"){h.parentNode.removeChild(h)}}}catch(j){}};function d(f){for(var g=0;g<f.length;g++){document.write('<script defer type="sifr/prefetch" src="'+f[g].src+'"><\/script>')}}}function b(e){var g=e.ua.ie;var f=g&&e.ua.flashVersion<e.ua.parseVersion("9.0.115");var d={};var c={};this.fixFlash=f;this.register=function(h){if(!g){return}var i=h.getAttribute("id");this.cleanup(i,false);c[i]=h;delete d[i];if(f){window[i]=h}};this.reset=function(){if(!g){return false}for(var j=0;j<e.replacements.length;j++){var h=e.replacements[j];var k=c[h.id];if(!d[h.id]&&(!k.parentNode||k.parentNode.nodeType==11)){h.resetMovie();d[h.id]=true}}return true};this.cleanup=function(l,h){var i=c[l];if(!i){return}for(var k in i){if(typeof(i[k])=="function"){i[k]=null}}c[l]=null;if(f){window[l]=null}if(i.parentNode){if(h&&i.parentNode.nodeType==1){var j=document.createElement("div");j.style.width=i.offsetWidth+"px";j.style.height=i.offsetHeight+"px";i.parentNode.replaceChild(j,i)}else{i.parentNode.removeChild(i)}}};this.prepareClearReferences=function(){if(!f){return}__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){}};this.clearReferences=function(){if(f){var j=document.getElementsByTagName("object");for(var h=j.length-1;h>=0;h--){c[j[h].getAttribute("id")]=j[h]}}for(var k in c){if(Object.prototype[k]!=c[k]){this.cleanup(k,true)}}}}function K(d,g,f,c,e){this.sIFR=d;this.id=g;this.vars=f;this.movie=null;this.__forceWidth=c;this.__events=e;this.__resizing=0}K.prototype={getFlashElement:function(){return document.getElementById(this.id)},getAlternate:function(){return document.getElementById(this.id+"_alternate")},getAncestor:function(){var c=this.getFlashElement().parentNode;return !this.sIFR.dom.hasClass(E.FIX_FOCUS,c)?c:c.parentNode},available:function(){var c=this.getFlashElement();return c&&c.parentNode},call:function(c){var d=this.getFlashElement();if(!d[c]){return false}return Function.prototype.apply.call(d[c],d,Array.prototype.slice.call(arguments,1))},attempt:function(){if(!this.available()){return false}try{this.call.apply(this,arguments)}catch(c){if(this.sIFR.debug){throw c}return false}return true},updateVars:function(c,e){for(var d=0;d<this.vars.length;d++){if(this.vars[d].split("=")[0]==c){this.vars[d]=c+"="+e;break}}var f=this.sIFR.util.encodeVars(this.vars);this.movie.injectVars(this.getFlashElement(),f);this.movie.injectVars(this.movie.html,f)},storeSize:function(c,d){this.movie.setSize(c,d);this.updateVars(c,d)},fireEvent:function(c){if(this.available()&&this.__events[c]){this.sIFR.util.delay(0,this.__events[c],this,this)}},resizeFlashElement:function(c,d,e){if(!this.available()){return}this.__resizing++;var f=this.getFlashElement();f.setAttribute("height",c);this.getAncestor().style.minHeight="";this.updateVars("renderheight",c);this.storeSize("height",c);if(d!==null){f.setAttribute("width",d);this.movie.setSize("width",d)}if(this.__events.onReplacement){this.sIFR.util.delay(0,this.__events.onReplacement,this,this);delete this.__events.onReplacement}if(e){this.sIFR.util.delay(0,function(){this.attempt("scaleMovie");this.__resizing--},this)}else{this.__resizing--}},blurFlashElement:function(){if(this.available()){this.sIFR.dom.blurElement(this.getFlashElement())}},resetMovie:function(){this.sIFR.util.delay(0,this.movie.reset,this.movie,this.getFlashElement(),this.getAlternate())},resizeAfterScale:function(){if(this.available()&&this.__resizing==0){this.sIFR.util.delay(0,this.resize,this)}},resize:function(){if(!this.available()){return}this.__resizing++;var g=this.getFlashElement();var f=g.offsetWidth;if(f==0){return}var e=g.getAttribute("width");var l=g.getAttribute("height");var m=this.getAncestor();var o=this.sIFR.dom.getHeightFromStyle(m);g.style.width="1px";g.style.height="1px";m.style.minHeight=o+"px";var c=this.getAlternate().childNodes;var n=[];for(var k=0;k<c.length;k++){var h=c[k].cloneNode(true);n.push(h);m.appendChild(h)}var d=this.sIFR.dom.getWidthFromStyle(m);for(var k=0;k<n.length;k++){m.removeChild(n[k])}g.style.width=g.style.height=m.style.minHeight="";g.setAttribute("width",this.__forceWidth?d:e);g.setAttribute("height",l);if(sIFR.ua.ie){g.style.display="none";var j=g.offsetHeight;g.style.display=""}if(d!=f){if(this.__forceWidth){this.storeSize("width",d)}this.attempt("resize",d)}this.__resizing--},replaceText:function(g,j){var d=this.sIFR.util.escape(g);if(!this.attempt("replaceText",d)){return false}this.updateVars("content",d);var f=this.getAlternate();if(j){while(f.firstChild){f.removeChild(f.firstChild)}for(var c=0;c<j.length;c++){f.appendChild(j[c])}}else{try{f.innerHTML=g}catch(h){}}return true},changeCSS:function(c){c=this.sIFR.util.escape(this.sIFR.util.cssToString(this.sIFR.util.convertCssArg(c)));this.updateVars("css",c);return this.attempt("changeCSS",c)},remove:function(){if(this.movie&&this.available()){this.movie.remove(this.getFlashElement(),this.id)}}};var X=new function(){this.create=function(p,n,j,i,f,e,g,o,l,h,m){var k=p.ua.ie?d:c;return new k(p,n,j,i,f,e,g,o,["flashvars",l,"wmode",h,"bgcolor",m,"allowScriptAccess","always","quality","best"])};function c(s,q,l,h,f,e,g,r,n){var m=s.dom.create("object",E.FLASH);var p=["type","application/x-shockwave-flash","id",f,"name",f,"data",e,"width",g,"height",r];for(var o=0;o<p.length;o+=2){m.setAttribute(p[o],p[o+1])}var j=m;if(h){j=W.create("div",E.FIX_FOCUS);j.appendChild(m)}for(var o=0;o<n.length;o+=2){if(n[o]=="name"){continue}var k=W.create("param");k.setAttribute("name",n[o]);k.setAttribute("value",n[o+1]);m.appendChild(k)}l.style.minHeight=r+"px";while(l.firstChild){l.removeChild(l.firstChild)}l.appendChild(j);this.html=j.cloneNode(true)}c.prototype={reset:function(e,f){e.parentNode.replaceChild(this.html.cloneNode(true),e)},remove:function(e,f){e.parentNode.removeChild(e)},setSize:function(e,f){this.html.setAttribute(e,f)},injectVars:function(e,g){var h=e.getElementsByTagName("param");for(var f=0;f<h.length;f++){if(h[f].getAttribute("name")=="flashvars"){h[f].setAttribute("value",g);break}}}};function d(p,n,j,h,f,e,g,o,k){this.dom=p.dom;this.broken=n;this.html='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="'+f+'" width="'+g+'" height="'+o+'" class="'+E.FLASH+'"><param name="movie" value="'+e+'"></param></object>';var m="";for(var l=0;l<k.length;l+=2){m+='<param name="'+k[l]+'" value="'+k[l+1]+'"></param>'}this.html=this.html.replace(/(<\/object>)/,m+"$1");j.style.minHeight=o+"px";j.innerHTML=this.html;this.broken.register(j.firstChild)}d.prototype={reset:function(f,g){g=g.cloneNode(true);var e=f.parentNode;e.innerHTML=this.html;this.broken.register(e.firstChild);e.appendChild(g)},remove:function(e,f){this.broken.cleanup(f)},setSize:function(e,f){this.html=this.html.replace(e=="height"?/(height)="\d+"/:/(width)="\d+"/,'$1="'+f+'"')},injectVars:function(e,f){if(e!=this.html){return}this.html=this.html.replace(/(flashvars(=|\"\svalue=)\")[^\"]+/,"$1"+f)}}};this.errors=new Y(O);var A=this.util=new D(O);var W=this.dom=new U(O);var T=this.ua=new H(O);var G={fragmentIdentifier:new F(O),pageLoad:new S(O),prefetch:new N(O),brokenFlashIE:new b(O)};this.__resetBrokenMovies=G.brokenFlashIE.reset;var J={kwargs:[],replaceAll:function(d){for(var c=0;c<this.kwargs.length;c++){O.replace(this.kwargs[c])}if(!d){this.kwargs=[]}}};this.activate=function(){if(!T.supported||!this.isEnabled||this.isActive||!C()||a()){return}G.prefetch.fetchMovies(arguments);this.isActive=true;this.setFlashClass();G.fragmentIdentifier.cache();G.pageLoad.attachUnload();if(!this.autoInitialize){return}G.pageLoad.attach()};this.setFlashClass=function(){if(this.hasFlashClassSet){return}W.addClass(E.ACTIVE,W.getBody()||document.documentElement);this.hasFlashClassSet=true};this.removeFlashClass=function(){if(!this.hasFlashClassSet){return}W.removeClass(E.ACTIVE,W.getBody());W.removeClass(E.ACTIVE,document.documentElement);this.hasFlashClassSet=false};this.initialize=function(c){if(!this.isActive||!this.isEnabled){return}if(R){if(!c){J.replaceAll(false)}return}R=true;J.replaceAll(c);if(O.repaintOnResize){if(window.addEventListener){window.addEventListener("resize",Z,false)}else{window.attachEvent("onresize",Z)}}G.prefetch.clear()};this.replace=function(x,u){if(!T.supported){return}if(u){x=A.copyProperties(x,u)}if(!R){return J.kwargs.push(x)}if(this.onReplacementStart){this.onReplacementStart(x)}var AM=x.elements||W.querySelectorAll(x.selector);if(AM.length==0){return}var w=M(x.src);var AR=A.convertCssArg(x.css);var v=B(x.filters);var AN=x.forceSingleLine===true;var AS=x.preventWrap===true&&!AN;var q=AN||(x.fitExactly==null?this.fitExactly:x.fitExactly)===true;var AD=q||(x.forceWidth==null?this.forceWidth:x.forceWidth)===true;var s=x.ratios||[];var AE=x.pixelFont===true;var r=parseInt(x.tuneHeight)||0;var z=!!x.onRelease||!!x.onRollOver||!!x.onRollOut;if(q){A.extractFromCss(AR,".sIFR-root","text-align",true)}var t=A.extractFromCss(AR,".sIFR-root","font-size",true)||"0";var e=A.extractFromCss(AR,".sIFR-root","background-color",true)||"#FFFFFF";var o=A.extractFromCss(AR,".sIFR-root","kerning",true)||"";var AW=A.extractFromCss(AR,".sIFR-root","opacity",true)||"100";var k=A.extractFromCss(AR,".sIFR-root","cursor",true)||"default";var AP=parseInt(A.extractFromCss(AR,".sIFR-root","leading"))||0;var AJ=x.gridFitType||(A.extractFromCss(AR,".sIFR-root","text-align")=="right")?"subpixel":"pixel";var h=this.forceTextTransform===false?"none":A.extractFromCss(AR,".sIFR-root","text-transform",true)||"none";t=/^\d+(px)?$/.test(t)?parseInt(t):0;AW=parseFloat(AW)<1?100*parseFloat(AW):AW;var AC=x.modifyCss?"":A.cssToString(AR);var AG=x.wmode||"";if(!AG){if(x.transparent){AG="transparent"}else{if(x.opaque){AG="opaque"}}}if(AG=="transparent"){if(!T.transparencySupport){AG="opaque"}else{e="transparent"}}else{if(e=="transparent"){e="#FFFFFF"}}for(var AV=0;AV<AM.length;AV++){var AF=AM[AV];if(W.hasOneOfClassses(E.IGNORE_CLASSES,AF)||W.ancestorHasClass(AF,E.ALTERNATE)){continue}var AO=W.getDimensions(AF);var f=AO.height;var c=AO.width;var AA=W.getComputedStyle(AF,"display");if(!f||!c||!AA||AA=="none"){continue}c=W.getWidthFromStyle(AF);var n,AH;if(!t){var AL=I(AF);n=Math.min(this.MAX_FONT_SIZE,Math.max(this.MIN_FONT_SIZE,AL.fontSize));if(AE){n=Math.max(8,8*Math.round(n/8))}AH=AL.lines}else{n=t;AH=1}var d=W.create("span",E.ALTERNATE);var AX=AF.cloneNode(true);AF.parentNode.appendChild(AX);for(var AU=0,AT=AX.childNodes.length;AU<AT;AU++){var m=AX.childNodes[AU];if(!/^(style|script)$/i.test(m.nodeName)){d.appendChild(m.cloneNode(true))}}if(x.modifyContent){x.modifyContent(AX,x.selector)}if(x.modifyCss){AC=x.modifyCss(AR,AX,x.selector)}var p=P(AX,h,x.uriEncode);AX.parentNode.removeChild(AX);if(x.modifyContentString){p.text=x.modifyContentString(p.text,x.selector)}if(p.text==""){continue}var AK=Math.round(AH*V(n,s)*n)+this.FLASH_PADDING_BOTTOM+r;if(AH>1&&AP){AK+=Math.round((AH-1)*AP)}var AB=AD?c:"100%";var AI="sIFR_replacement_"+L++;var AQ=["id="+AI,"content="+A.escape(p.text),"width="+c,"renderheight="+AK,"link="+A.escape(p.primaryLink.href||""),"target="+A.escape(p.primaryLink.target||""),"size="+n,"css="+A.escape(AC),"cursor="+k,"tunewidth="+(x.tuneWidth||0),"tuneheight="+r,"offsetleft="+(x.offsetLeft||""),"offsettop="+(x.offsetTop||""),"fitexactly="+q,"preventwrap="+AS,"forcesingleline="+AN,"antialiastype="+(x.antiAliasType||""),"thickness="+(x.thickness||""),"sharpness="+(x.sharpness||""),"kerning="+o,"gridfittype="+AJ,"flashfilters="+v,"opacity="+AW,"blendmode="+(x.blendMode||""),"selectable="+(x.selectable==null||AG!=""&&!sIFR.ua.macintosh&&sIFR.ua.gecko&&sIFR.ua.geckoVersion>=sIFR.ua.parseVersion("1.9")?"true":x.selectable===true),"fixhover="+(this.fixHover===true),"events="+z,"delayrun="+G.brokenFlashIE.fixFlash,"version="+this.VERSION];var y=A.encodeVars(AQ);var g=new K(O,AI,AQ,AD,{onReplacement:x.onReplacement,onRollOver:x.onRollOver,onRollOut:x.onRollOut,onRelease:x.onRelease});g.movie=X.create(sIFR,G.brokenFlashIE,AF,T.fixFocus&&x.fixFocus,AI,w,AB,AK,y,AG,e);this.replacements.push(g);this.replacements[AI]=g;if(x.selector){if(!this.replacements[x.selector]){this.replacements[x.selector]=[g]}else{this.replacements[x.selector].push(g)}}d.setAttribute("id",AI+"_alternate");AF.appendChild(d);W.addClass(E.REPLACED,AF)}G.fragmentIdentifier.restore()};this.getReplacementByFlashElement=function(d){for(var c=0;c<O.replacements.length;c++){if(O.replacements[c].id==d.getAttribute("id")){return O.replacements[c]}}};this.redraw=function(){for(var c=0;c<O.replacements.length;c++){O.replacements[c].resetMovie()}};this.prepareClearReferences=function(){G.brokenFlashIE.prepareClearReferences()};this.clearReferences=function(){G.brokenFlashIE.clearReferences();G=null;J=null;delete O.replacements};function C(){if(O.domains.length==0){return true}var d=A.domain();for(var c=0;c<O.domains.length;c++){if(A.domainMatches(d,O.domains[c])){return true}}return false}function a(){if(document.location.protocol=="file:"){if(O.debug){O.errors.fire("isFile")}return true}return false}function M(c){if(T.ie&&c.charAt(0)=="/"){c=window.location.toString().replace(/([^:]+)(:\/?\/?)([^\/]+).*/,"$1$2$3")+c}return c}function V(d,e){for(var c=0;c<e.length;c+=2){if(d<=e[c]){return e[c+1]}}return e[e.length-1]||1}function B(g){var e=[];for(var d in g){if(g[d]==Object.prototype[d]){continue}var c=g[d];d=[d.replace(/filter/i,"")+"Filter"];for(var f in c){if(c[f]==Object.prototype[f]){continue}d.push(f+":"+A.escape(A.toJson(c[f],A.toHexString)))}e.push(d.join(","))}return A.escape(e.join(";"))}function Z(d){var e=Z.viewport;var c=W.getViewport();if(e&&c.width==e.width&&c.height==e.height){return}Z.viewport=c;if(O.replacements.length==0){return}if(Z.timer){clearTimeout(Z.timer)}Z.timer=setTimeout(function(){delete Z.timer;for(var f=0;f<O.replacements.length;f++){O.replacements[f].resize()}},200)}function I(f){var g=W.getComputedStyle(f,"fontSize");var d=g.indexOf("px")==-1;var e=f.innerHTML;if(d){f.innerHTML="X"}f.style.paddingTop=f.style.paddingBottom=f.style.borderTopWidth=f.style.borderBottomWidth="0px";f.style.lineHeight="2em";f.style.display="block";g=d?f.offsetHeight/2:parseInt(g,10);if(d){f.innerHTML=e}var c=Math.round(f.offsetHeight/(2*g));f.style.paddingTop=f.style.paddingBottom=f.style.borderTopWidth=f.style.borderBottomWidth=f.style.lineHeight=f.style.display="";if(isNaN(c)||!isFinite(c)||c==0){c=1}return{fontSize:g,lines:c}}function P(c,g,s){s=s||A.uriEncode;var q=[],m=[];var k=null;var e=c.childNodes;var o=false,p=false;var j=0;while(j<e.length){var f=e[j];if(f.nodeType==3){var t=A.textTransform(g,A.normalize(f.nodeValue)).replace(/</g,"&lt;");if(o&&p){t=t.replace(/^\s+/,"")}m.push(t);o=/\s$/.test(t);p=false}if(f.nodeType==1&&!/^(style|script)$/i.test(f.nodeName)){var h=[];var r=f.nodeName.toLowerCase();var n=f.className||"";if(/\s+/.test(n)){if(n.indexOf(E.CLASS)>-1){n=n.match("(\\s|^)"+E.CLASS+"-([^\\s$]*)(\\s|$)")[2]}else{n=n.match(/^([^\s]+)/)[1]}}if(n!=""){h.push('class="'+n+'"')}if(r=="a"){var d=s(f.getAttribute("href")||"");var l=f.getAttribute("target")||"";h.push('href="'+d+'"','target="'+l+'"');if(!k){k={href:d,target:l}}}m.push("<"+r+(h.length>0?" ":"")+h.join(" ")+">");p=true;if(f.hasChildNodes()){q.push(j);j=0;e=f.childNodes;continue}else{if(!/^(br|img)$/i.test(f.nodeName)){m.push("</",f.nodeName.toLowerCase(),">")}}}if(q.length>0&&!f.nextSibling){do{j=q.pop();e=f.parentNode.parentNode.childNodes;f=e[j];if(f){m.push("</",f.nodeName.toLowerCase(),">")}}while(j==e.length-1&&q.length>0)}j++}return{text:m.join("").replace(/^\s+|\s+$|\s*(<br>)\s*/g,"$1"),primaryLink:k||{}}}};
var parseSelector=(function(){var B=/\s*,\s*/;var A=/\s*([\s>+~(),]|^|$)\s*/g;var L=/([\s>+~,]|[^(]\+|^)([#.:@])/g;var F=/(^|\))[^\s>+~]/g;var M=/(\)|^)/;var K=/[\s#.:>+~()@]|[^\s#.:>+~()@]+/g;function H(R,P){P=P||document.documentElement;var S=R.split(B),X=[];for(var U=0;U<S.length;U++){var N=[P],W=G(S[U]);for(var T=0;T<W.length;){var Q=W[T++],O=W[T++],V="";if(W[T]=="("){while(W[T++]!=")"&&T<W.length){V+=W[T]}V=V.slice(0,-1)}N=I(N,Q,O,V)}X=X.concat(N)}return X}function G(N){var O=N.replace(A,"$1").replace(L,"$1*$2").replace(F,D);return O.match(K)||[]}function D(N){return N.replace(M,"$1 ")}function I(N,P,Q,O){return(H.selectors[P])?H.selectors[P](N,Q,O):[]}var E={toArray:function(O){var N=[];for(var P=0;P<O.length;P++){N.push(O[P])}return N}};var C={isTag:function(O,N){return(N=="*")||(N.toLowerCase()==O.nodeName.toLowerCase())},previousSiblingElement:function(N){do{N=N.previousSibling}while(N&&N.nodeType!=1);return N},nextSiblingElement:function(N){do{N=N.nextSibling}while(N&&N.nodeType!=1);return N},hasClass:function(N,O){return(O.className||"").match("(^|\\s)"+N+"(\\s|$)")},getByTag:function(N,O){return O.getElementsByTagName(N)}};var J={"#":function(N,P){for(var O=0;O<N.length;O++){if(N[O].getAttribute("id")==P){return[N[O]]}}return[]}," ":function(O,Q){var N=[];for(var P=0;P<O.length;P++){N=N.concat(E.toArray(C.getByTag(Q,O[P])))}return N},">":function(O,R){var N=[];for(var Q=0,S;Q<O.length;Q++){S=O[Q];for(var P=0,T;P<S.childNodes.length;P++){T=S.childNodes[P];if(T.nodeType==1&&C.isTag(T,R)){N.push(T)}}}return N},".":function(O,Q){var N=[];for(var P=0,R;P<O.length;P++){R=O[P];if(C.hasClass([Q],R)){N.push(R)}}return N},":":function(N,P,O){return(H.pseudoClasses[P])?H.pseudoClasses[P](N,O):[]}};H.selectors=J;H.pseudoClasses={};H.util=E;H.dom=C;return H})();

/*****************************************************************************
It is adviced to place the sIFR JavaScript calls in this file, keeping it
separate from the `sifr.js` file. That way, you can easily swap the `sifr.js`
file for a new version, while keeping the configuration.

You must load this file *after* loading `sifr.js`.

That said, you're of course free to merge the JavaScript files. Just make sure
the copyright statement in `sifr.js` is kept intact.
*****************************************************************************/

// Make an object pointing to the location of the Flash movie on your web server.
// Try using the font name as the variable name, makes it easy to remember which
// object you're using. As an example in this file, we'll use Futura.
var theMixPlain = { src: '/javascripts/flash/TheMix_MixPlain.swf' };
var theMixBoldPlain = { src: '/javascripts/flash/TheMix_Bold_MixPlain.swf' };
var theMixSemiLightPlain = { src: '/javascripts/flash/TheMix_SemiLight_LightPlain.swf' };
// var theMixPlain = { src: '/dev/public/_javascripts/_flash/TheMix_MixPlain.swf' };
// var theMixSemiLightPlain = { src: '/dev/public/_javascripts/_flash/TheMix_SemiLight_LightPlain.swf' };

// Now you can set some configuration settings.
// See also <http://wiki.novemberborn.net/sifr3/JavaScript+Configuration>.
// One setting you probably want to use is `sIFR.useStyleCheck`. Before you do that,
// read <http://wiki.novemberborn.net/sifr3/DetectingCSSLoad>.

// sIFR.useStyleCheck = true;

// Next, activate sIFR:
sIFR.activate(theMixPlain, theMixBoldPlain, theMixSemiLightPlain);

// If you want, you can use multiple movies, like so:
//
//    var futura = { src: '/path/to/futura.swf' };
//    var garamond = { src '/path/to/garamond.swf' };
//    var rockwell = { src: '/path/to/rockwell.swf' };
//    
//    sIFR.activate(futura, garamond, rockwell);
//
// Remember, there must be *only one* `sIFR.activate()`!

// Now we can do the replacements. You can do as many as you like, but just
// as an example, we'll replace all `<h1>` elements with the Futura movie.
// 
// The first argument to `sIFR.replace` is the `futura` object we created earlier.
// The second argument is another object, on which you can specify a number of
// parameters or "keyword arguemnts". For the full list, see "Keyword arguments"
// under `replace(kwargs, mergeKwargs)` at 
// <http://wiki.novemberborn.net/sifr3/JavaScript+Methods>.
// 
// The first argument you see here is `selector`, which is a normal CSS selector.
// That means you can also do things like '#content h1' or 'h1.title'.
//
// The second argument determines what the Flash text looks like. The main text
// is styled via the `.sIFR-root` class. Here we've specified `background-color`
// of the entire Flash movie to be a light grey, and the `color` of the text to
// be red. Read more about styling at <http://wiki.novemberborn.net/sifr3/Styling>.



document.observe('dom:loaded', function() {
	sIFR.replace(theMixSemiLightPlain, {
		selector: '#ctl00_bdyBody #content_home h1',
		css: 
			'.sIFR-root {' +
				'background-color: transparent;' +
				'color: #0033CC;' +
				'leading: 1' +
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixPlain, {
		selector: '#content_home p',
		css: 
			'.sIFR-root {' +
				'background-color: transparent;' +
				'color: #696969;' +
				'leading: 2' +
			'}' + 
			'.sIFR-root a {' +
				'color: #EA7125;' + 
				'text-decoration: none;' +
			'}' +
			'.sIFR-root a:hover {' +
				'color: #EA7125;' +
				'text-decoration: underline;' +
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixSemiLightPlain, {
		selector: '#ctl00_bdyBody #content_main .pressRelease h1',
		css:
			'.sIFR-root {' +
				'color: #0033CC;' +
				'leading: 1' +
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixSemiLightPlain, {
		selector: '#ctl00_bdyBody #content_wrapper h1',
		css: 
			'.sIFR-root {' +
				'background-color: transparent;' +
				'color: #33CC00;' +
				'leading: 1' +
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixSemiLightPlain, {
		selector: '#ctl00_bdyBody #wide_content_wrapper h1',
		css: 
			'.sIFR-root {' +
				'color: #fc0;' +
				'color: #33CC00;' +
				'leading: 1' +
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixPlain, {
		selector: '#ctl00_bdyBody #content_main #content_header h2',
		css: 
			'.sIFR-root {' + 
				'color: #33CC00;' + 
				'leading: 1' + 
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixPlain, {
		selector: '#ctl00_bdyBody .intro_paragraph',
		css: 
			'.sIFR-root {' + 
				'color: #696969;' + 
				'leading: 3;' +
			'}' + 
			'.sIFR-root a {' +
				'color: #EA7125;' + 
				'text-decoration: none;' +
			'}' +
			'.sIFR-root a:hover {' +
				'color: #EA7125;' +
				'text-decoration: underline;' +
			'}',
		wmode: 'transparent' 
	});
	sIFR.replace(theMixPlain, {
		selector: '#ctl00_bdyBody #content_main h2',
		css: 
			'.sIFR-root {' + 
				'background-color: transparent;' + 
				'color: #0033CC;' + 
				'leading: 1' + 
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixPlain, {
		selector: '#ctl00_bdyBody #content_main h4',
		css: 
			'.sIFR-root {' + 
				'color: #777777;' + 
				'leading: 1' + 
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixPlain, {
		selector: '#ctl00_bdyBody #content_main .big_quote blockquote p',
		css: 
			'.sIFR-root {' + 
				'color: #34BC07;' + 
				'leading: 2' + 
			'}' + 
			'.sIFR-root a {' +
				'color: #EA7125;' + 
				'text-decoration: none;' +
			'}' +
			'.sIFR-root a:hover {' +
				'color: #EA7125;' +
				'text-decoration: underline;' +
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixBoldPlain, {
		selector: '#ctl00_bdyBody #content_main .big_quote blockquote h3',
		css: 
			'.sIFR-root {' + 
				'color: #34BC07;' + 
				'leading: 2' + 
			'}' + 
			'.sIFR-root a {' +
				'color: #EA7125;' + 
				'text-decoration: none;' +
			'}' +
			'.sIFR-root a:hover {' +
				'color: #EA7125;' +
				'text-decoration: underline;' +
			'}',
		wmode: 'transparent'
	});
	sIFR.replace(theMixPlain, {
		selector: '#ctl00_bdyBody #content_main .pull_quote strong',
		css: 
			'.sIFR-root {' + 
				'color: #34BC07;' + 
				'leading: 2' + 
			'}' + 
			'.sIFR-root a {' +
				'color: #EA7125;' + 
				'text-decoration: none;' +
			'}' +
			'.sIFR-root a:hover {' +
				'color: #EA7125;' +
				'text-decoration: underline;' +
			'}',
		wmode: 'transparent'
	});
});


/*  ****************************************************************************
	To disable sIFR for Internet Explorer 6, uncomment the following line:

}

	***************************************************************************/

// Looks for inputs and textareas with a class of 'default_value' 
// and clears or resets the default value on focus/blur.
document.observe('dom:loaded', function() {
	$$('input.default_value', 'textarea.default_value')
	.invoke('observe', 'focus', function(e) {
		if (this.hasClassName('default_value')) {
			if (this.value.toLowerCase() == 'search')
			{
				this.value='';
				this.removeClassName('default_value');
			}	
		}
	})
	.invoke('observe', 'blur', function(e) {
		if (this.value=='' && this.defaultValue.toLowerCase() == 'search') {
			this.addClassName('default_value');
			this.value=this.defaultValue;
		}
		else
			this.defaultValue = "";
	})
});

document.observe('dom:loaded', function() {
	$$('#shortcut-search button')
	.invoke('observe', 'mouseover', function(e) {
		Event.element(e).addClassName('hover');
	})
	.invoke('observe', 'mouseout', function(e) {
		Event.element(e).removeClassName('hover');
	})
	
});

document.observe('dom:loaded', function() {
	$$('dl.toggle dt').invoke('observe', 'click', function(e) {
        var el = this;
		if (el.hasClassName('open')) {
			el.removeClassName('open');
			el.next('dd').setStyle({display:'none'});
		}
		else {
			el.addClassName('open');
			el.next('dd').setStyle({display:'block'});
		}
        var h2Els = $(this).next().getElementsBySelector("h2");
        var h4Els = $(this).next().getElementsBySelector("h4");
        var allEls = h2Els.concat(h4Els);
        for (var i=0, j=allEls.length; i<j; i++) {
            var tagName = allEls[i].tagName.toLowerCase();
            var textColor = (tagName === "h2") ? "#0033CC" : "#777777";
            if (!$(allEls[i]).hasClassName("sIFR-replaced")) {
                sIFR_replaceText({ color: textColor, selector: "#ctl00_bdyBody #content_main "+tagName});
            }
        }
	});
});

var sIFR_replaceText = function(options) {
    //console.log("sIFR_replaceText(%o)...",options);
	sIFR.replace(theMixPlain, {
		selector: options.selector,
		css: 
			'.sIFR-root {' + 
				'color: ' + options.color + ';' +
				'leading: 1' + 
			'}',
		wmode: 'transparent'
	});
}

document.observe('dom:loaded', function() {
	var captionEl = $('caption');
	var anchorEl = $('caption-text');
	var arrowEl = $('caption-arrow');
	var defaultValue = '';
	if (captionEl && anchorEl && arrowEl) {
		Element.observe(anchorEl, 'mouseover', function() {
			defaultValue = anchorEl.innerHTML;
			anchorEl.update(captionEl.title);
		});
		Element.observe(anchorEl, 'mouseout', function() {
			anchorEl.update(defaultValue);
		});
		Element.observe(arrowEl, 'mouseover', function() {
			defaultValue = anchorEl.innerHTML;
			anchorEl.update(captionEl.title);
		});
		Element.observe(arrowEl, 'mouseout', function() {
			anchorEl.update(defaultValue);
		});
	}
});

document.observe('dom:loaded', function() {

    if ($('content_wrapper') && $('content_wrapper').getHeight()) {var mainColumn_h = $('content_wrapper').getHeight()};

//	$$('#sub_navigation > div > ul > li:not([class~=open]) ul').invoke('hide');
	$$('#sub_navigation ul li a.toggle').invoke('observe', 'click', function(e) {
		Event.stop(e);
		if (e.target.up('li').hasClassName('open')) {
			e.target.next('ul').hide();
			e.target.up('li').removeClassName('open');
		}
		else {
			e.target.next('ul').show();
			e.target.up('li').addClassName('open');
		}
		
		// get height of .subnav-main-wrapper
		if (document.getElementsByClassName('inline_filter').length) {
			
			var subnav_h = $('sub_navigation').down(0).next(0).getHeight();
			var filter_h = $$('.inline_filter')[0].getHeight();
			var leftColumn_h = filter_h + 368;
			
			if (subnav_h > 308) {
				$('sub_navigation').getElementsByClassName('inline_filter')[0].setStyle({
					top: 'auto',
					position: 'relative'
				});
                $('sub_navigation').setStyle({ height: 'auto' });
			}
			else {
				$('sub_navigation').getElementsByClassName('inline_filter')[0].setStyle({
					top: '468px',
					position: 'absolute'
				});
                $('sub_navigation').setStyle({ height: leftColumn_h + 'px' });
			} 
		}
	});
    
    
	$$('#ctl00_bdyBody.content .inline_filter .filters div a.toggle').invoke('observe', 'click', function(e) {
		Event.stop(e);
		if (e.target.up('div').hasClassName('open')) {
			e.target.next('ul').hide();
			e.target.up('div').removeClassName('open');
		}
		else {
			e.target.next('ul').show();
			e.target.up('div').addClassName('open');
		}	
		
		if ($('sub_navigation').getElementsByClassName('inline_filter')[0].getStyle("position") == "absolute") {
			
			var subnav_h = $('sub_navigation').down(0).next(0).getHeight();
			var filter_h = $$('.inline_filter')[0].getHeight();
			var leftColumn_h = filter_h + 368;
			
			if (leftColumn_h > mainColumn_h) {
				$('sub_navigation').setStyle({ height: leftColumn_h + 'px' });	
			} else {
				$('sub_navigation').setStyle({ height: 'auto' });	
			}
		}
	});
});

var homeTabsIFR = '';

document.observe('dom:loaded', function() {
	if (document.images) {
		imgs = new Array();
		imgs[0] = '/stylesheets/images/default/bd-home-bg.png';
		imgs[1] = '/stylesheets/images/default/main_nav-energy-on.png';
		imgs[2] = '/stylesheets/images/default/main_nav-environment-on.png';
		imgs[3] = '/stylesheets/images/default/main_nav-community-on.png';
		imgs[4] = '/stylesheets/images/default/main_nav-people_and_culture-on.png';
		imgs[5] = '/stylesheets/images/default/main_nav-performance-on.png';
		imgs[6] = '/stylesheets/images/default/main_nav-home-energy.png';
		imgs[7] = '/stylesheets/images/default/main_nav-home-environment.png';
		imgs[8] = '/stylesheets/images/default/main_nav-home-community.png';
		imgs[9] = '/stylesheets/images/default/main_nav-home-people_and_culture.png';
		imgs[10] = '/stylesheets/images/default/main_nav-home-performance.png';
		imgs[11] = '/stylesheets/images/default/main_nav-inner-community.png';
		imgs[12] = '/stylesheets/images/default/main_nav-inner-energy.png';
		imgs[13] = '/stylesheets/images/default/main_nav-inner-environment.png';
		imgs[14] = '/stylesheets/images/default/main_nav-inner-none.png';
		imgs[15] = '/stylesheets/images/default/main_nav-inner-people_and_culture.png';
		imgs[16] = '/stylesheets/images/default/main_nav-inner-performance.png';
		
		for (i=0; i<imgs.length; i++) {
			eval('img' + i + ' = new Image();');
			eval('img' + i + '.src = "' + imgs[i] + '";');
		}
	}
	
	var bodyEl = $('ctl00_bdyBody');
        
	$$('#ctl00_bdyBody.home #main_navigation a').invoke('observe', 'mouseover', function(e) {
// 		$w(bodyEl.className).each(function(item) { bodyEl.removeClassName(item) });
		/*bodyEl.removeClassName('home-energy');
		bodyEl.removeClassName('home-environment');
		bodyEl.removeClassName('home-community');
		bodyEl.removeClassName('home-people_and_culture');
		bodyEl.removeClassName('home-performance');
		bodyEl.addClassName('home');
		bodyEl.addClassName('home-' + e.target.className);*/
        
        $('content_home').setStyle({'display': 'none'});
        $('home-tab-energy').setStyle({'display': 'none'});
        $('home-tab-environment').setStyle({'display': 'none'});
        $('home-tab-community').setStyle({'display': 'none'});
        $('home-tab-people_and_culture').setStyle({'display': 'none'});
        $('home-tab-performance').setStyle({'display': 'none'});
        $('home-tab-' + e.target.className).setStyle({'display': 'block'});
        
        if ((Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))<7)) {
            $('main_navigation').setStyle({'backgroundImage': 'url(/stylesheets/images/default/x.gif)'});
            $('main_navigation').setStyle({'filter': 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="/stylesheets/images/default/main_nav-home-' + e.target.className + '.png", sizingMethod="crop")'});
        } else {
            $('main_navigation').setStyle({'backgroundImage': 'url(/stylesheets/images/default/main_nav-home-' + e.target.className + '.png)'});
        }
        
        if (!homeTabsIFR.include('|' + e.target.className)) {
            homeTabsIFR = homeTabsIFR + '|' + e.target.className;
            sIFR.replace(theMixSemiLightPlain, {
                selector: '#home-tab-' + e.target.className + ' .content_wrapper h2',
                css: 
                    '.sIFR-root {' +
                        'background-color: transparent;' +
                        'color: #7B7B7B;' +
                        'leading: 1;' +
                    '}',
                wmode: 'transparent'
            });
            sIFR.replace(theMixSemiLightPlain, {
                selector: '#home-tab-' + e.target.className + ' .content_wrapper p',
                css: 
                    '.sIFR-root {' +
                        'background-color: transparent;' +
                        'color: #7B7B7B;' +
                        'leading: 2.5;' +
                    '}' +
                    '.sIFR-root a {' +
                        'color: #EA7125;' +
                        'text-decoration: none;' +
                    '}' +
                    '.sIFR-root a:hover {' +
                        'color: #EA7125;' +
                        'text-decoration: underline;' +
                    '}',
                wmode: 'transparent'
            });
        }
        $$('.carousel_home .carousel_rail').each(function(s) {
            var railWidth = (s.select('dl').length * s.down('dl').getWidth()) + 'px';
            var heightArray = new Array;
            s.select('dl').each(function(dl, i) { heightArray[i] = dl.getHeight() });
            var railHeight = (heightArray.max()) + 'px';
            s.setStyle({
                width: railWidth,
                height: railHeight
            });
            s.up().setStyle({
                height: railHeight
            });
        });
       
	});
    
    /*$$('#ctl00_bdyBody.home #main_navigation a').invoke('observe', 'mouseout', function(e) {
		// if the mouse position falls outside the bounds of the drop down, update bg image
		if (!((65 < e.pointerY()) && (e.pointerY() < 495) && (((document.viewport.getWidth()-950)/2) < e.pointerX()) && (e.pointerX() < (((document.viewport.getWidth()-950)/2)+738)))) {
            e.fromElement.style.backgroundImage = 'url(/stylesheets/images/default/main_nav-' + e.target.className + '-off.png)';
		} else {
            e.fromElement.style.backgroundImage = 'url(/stylesheets/images/default/main_nav-' + e.target.className + '-on.png)';
        }
    });GKH*/
    
	$$('#ctl00_bdyBody.home #main_navigation','#ctl00_bdyBody.home .home-tab').invoke('observe', 'mouseout', function(e) {
		// if the mouse position falls outside the bounds of the drop down, hide it
		if (!((65 < e.pointerY()) && (e.pointerY() < 495) && (((document.viewport.getWidth()-950)/2) < e.pointerX()) && (e.pointerX() < (((document.viewport.getWidth()-950)/2)+738)))) {
// 			$w(bodyEl.className).each(function(item) { bodyEl.removeClassName(item) });
			/*bodyEl.removeClassName('home-energy');
			bodyEl.removeClassName('home-environment');
			bodyEl.removeClassName('home-community');
			bodyEl.removeClassName('home-people_and_culture');
			bodyEl.removeClassName('home-performance');
			bodyEl.addClassName('home');
			bodyEl.addClassName('home-default');*/

        $('home-tab-energy').setStyle({'display': 'none'});
        $('home-tab-environment').setStyle({'display': 'none'});
        $('home-tab-community').setStyle({'display': 'none'});
        $('home-tab-people_and_culture').setStyle({'display': 'none'});
        $('home-tab-performance').setStyle({'display': 'none'});
        $('content_home').setStyle({'display': 'block'});
        $('main_navigation').setStyle({'backgroundImage': 'none'});
        if ((Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5))<7)) {
            $('main_navigation').setStyle({'filter': 'none'});
        }
        }
	});
});

document.observe('dom:loaded', function() {
	$$('#feature_1 a img', '#feature_2 a img')
	.invoke('observe', 'mouseover', function(e) {
		Event.element(e).src = Event.element(e).src.replace(/.png/i, '-over.png');
	})
	.invoke('observe', 'mouseout', function(e) {
		Event.element(e).src = Event.element(e).src.replace(/-over.png/i, '.png');
	})
});

document.observe('dom:loaded', function() {
	if ($$('#banner li').length > 1 ) {
		new Protofade('banner', { duration: 2.0, randomize:true });
	}
});

document.observe('dom:loaded', function() {
	/*var plantData = Array();
	plantData.push({ 	type: "Headquarters", 
						name: "<a href='#'>Exelon</a>",
						address: "1234 Main Street", 
						city: "City", 
						state: "State", 
						zip: "88888", phone: "888.888.8888", coords: { lat: 41.882387, lng: -87.630129 }
					});

	plantData.push({ 	type: "Hydro", 
						name: "<a href='#'>Conowingo Hydroelectric<br />Power Plant</a>",
						address: "1234 Main Street", 
						city: "City", 
						state: "State", 
						zip: "88888", phone: "888.888.8888", coords: { lat: 39.3936, lng: -76.1025 }
					});

	plantData.push({ 	type: "Hydro", 
						name: "<a href='#'>Muddy Run Pumped<br />Storage Facility</a>", 
						address: "1234 Main Street", 
						city: "City", 
						state: "State", 
						zip: "88888", phone: "888.888.8888", coords: { lat: 39.846254, lng: -76.293676 }
					});

	plantData.push({ 	type: "Nuclear", 
						name: "<a href='#'>Nuclear Plant</a>", 
						address: "1234 Main Street", 
						city: "City", 
						state: "State", 
						zip: "88888", phone: "888.888.8888", coords: { lat: 39.947648, lng: -76.992187 } 
					});

	plantData.push({ 	type: "Landfill Gas", 
						name: "<a href='#'>Gas Plant</a>", 
						address: "1234 Main Street", 
						city: "City", 
						state: "State", 
						zip: "88888", phone: "888.888.8888", coords: { lat: 39.546254, lng: -77.493676 }
					});

	plantData.push({ 	type: "Fossil", 
						name: "<a href='#'>Fossil Plant</a>", 
						address: "1234 Main Street", 
						city: "City", 
						state: "State", 
						zip: "88888", phone: "888.888.8888", coords: { lat: 39.609563, lng: -76.640625 }
					});

	var canvas = $("map_power_plants");
	if (canvas) {
		GMap_Plants = new GMap_initialize({ containerObj: canvas, markers: plantData });
	}*/


	var coords = [ { lat: "42.506528", lng: "-90.491638" }, 
				   { lat: "42.585444", lng: "-90.42572" }, 
				   { lat: "42.53082", lng: "-89.167786" }, 
				   { lat: "42.500453", lng: "-89.14856" }, 
				   { lat: "42.498428", lng: "-89.096375" }, 
				   { lat: "42.468045", lng: "-89.093628" }, 
				   { lat: "42.496403", lng: "-89.046936" }, 
				   { lat: "42.468045", lng: "-88.992004" }, 
				   { lat: "42.542963", lng: "-88.972778" }, 
				   { lat: "42.544987", lng: "-87.813721" }, 
				   { lat: "42.515639", lng: "-87.812347" }, 
				   { lat: "42.489315", lng: "-87.801361" }, 
				   { lat: "42.454874", lng: "-87.799988" }, 
				   { lat: "42.411291", lng: "-87.805481" }, 
				   { lat: "42.386951", lng: "-87.804108" }, 
				   { lat: "42.364632", lng: "-87.82196" }, 
				   { lat: "42.325047", lng: "-87.831573" }, 
				   { lat: "42.298643", lng: "-87.832947" }, 
				   { lat: "42.270196", lng: "-87.828827" }, 
				   { lat: "42.246819", lng: "-87.819214" }, 
				   { lat: "42.228517", lng: "-87.810974" }, 
				   { lat: "42.196986", lng: "-87.790375" }, 
				   { lat: "42.163403", lng: "-87.764282" }, 
				   { lat: "42.130821", lng: "-87.74231" }, 
				   { lat: "42.098222", lng: "-87.714844" }, 
				   { lat: "42.07682", lng: "-87.684631" }, 
				   { lat: "42.055411", lng: "-87.668152" }, 
				   { lat: "42.038074", lng: "-87.669525" }, 
				   { lat: "42.018692", lng: "-87.664032" }, 
				   { lat: "41.982973", lng: "-87.650299" }, 
				   { lat: "41.960511", lng: "-87.639313" }, 
				   { lat: "41.934977", lng: "-87.632446" }, 
				   { lat: "41.896144", lng: "-87.61322" }, 
				   { lat: "41.867516", lng: "-87.6091" }, 
				   { lat: "41.84092", lng: "-87.606354" }, 
				   { lat: "41.822502", lng: "-87.596741" }, 
				   { lat: "41.802031", lng: "-87.580261" }, 
				   { lat: "41.763117", lng: "-87.561035" }, 
				   { lat: "41.744677", lng: "-87.523956" }, 
				   { lat: "41.744677", lng: "-87.523956" }, 
				   { lat: "41.580525", lng: "-87.52533" }, 
				   { lat: "41.347948", lng: "-87.526703" }, 
				   { lat: "41.122815", lng: "-87.526703" }, 
				   { lat: "40.931153", lng: "-87.52533" }, 
				   { lat: "40.939452", lng: "-88.122711" }, 
				   { lat: "40.884448", lng: "-88.121338" }, 
				   { lat: "40.88341", lng: "-88.224335" }, 
				   { lat: "40.781581", lng: "-88.224335" }, 
				   { lat: "40.777422", lng: "-88.70224" }, 
				   { lat: "40.841866", lng: "-88.732452" }, 
				   { lat: "40.901058", lng: "-88.775024" }, 
				   { lat: "40.906248", lng: "-88.946686" }, 
				   { lat: "40.856409", lng: "-88.949432" }, 
				   { lat: "40.855371", lng: "-88.983765" }, 
				   { lat: "40.807573", lng: "-88.985138" }, 
				   { lat: "40.805494", lng: "-89.193878" }, 
				   { lat: "40.880295", lng: "-89.192505" }, 
				   { lat: "40.92389", lng: "-89.255676" }, 
				   { lat: "41.037931", lng: "-89.25293" }, 
				   { lat: "41.139365", lng: "-89.189758" }, 
				   { lat: "41.341763", lng: "-89.085388" }, 
				   { lat: "41.387113", lng: "-89.13208" }, 
				   { lat: "41.370625", lng: "-89.241943" }, 
				   { lat: "41.405656", lng: "-89.318848" }, 
				   { lat: "41.393294", lng: "-89.502869" }, 
				   { lat: "41.395355", lng: "-89.722595" }, 
				   { lat: "41.424194", lng: "-89.931335" }, 
				   { lat: "41.444785", lng: "-90.203247" }, 
				   { lat: "41.455079", lng: "-90.32135" }, 
				   { lat: "41.613389", lng: "-90.346069" }, 
				   { lat: "41.881831", lng: "-90.343323" }, 
				   { lat: "42.032974", lng: "-90.219727" }, 
				   { lat: "42.073762", lng: "-89.846191" }, 
				   { lat: "42.200038", lng: "-89.769287" }, 
				   { lat: "42.291532", lng: "-89.824219" }, 
				   { lat: "42.287469", lng: "-89.906616" }, 
				   { lat: "42.380865", lng: "-89.928589" }, 
				   { lat: "42.500453", lng: "-89.997253" }, 
				   { lat: "42.506528", lng: "-90.491638" }  ];

	var canvasPeco = $("map_delivery_area_peco");
	var polyOpt = { "coords": coords,
                    "dataService": "http://www.exeloncorp.com/XMLFiles/PecoElectric_Outline.KML",
					"center": { lat: "41.689322", lng: "-89.121094" },
					"zoom": 7 
				  };
	if (canvasPeco) {
		var GMap_Service = new GMap_initialize({ containerObj: canvasPeco, polyOverlays: [ polyOpt ] });
	}

	var canvasComed = $("map_delivery_area_comed");
	var polyOpt = { "coords": coords,
                    "dataService": "http://www.exeloncorp.com/XMLFiles/ComedElectric_Outline.KML",
					"center": { lat: "41.689322", lng: "-89.121094" },
					"zoom": 7 
				  };
	if (canvasComed) {
		var GMap_Service = new GMap_initialize({ containerObj: canvasComed, polyOverlays: [ polyOpt ] });
	}    
});


function GMap_initialize(ArgsObj) {
	/* Argument Defaults */
	var NewArguments = {
		containerObj: false,
		mapObj: false,
		markers: false,
		mapCenter: { lat: "40.912559", lng: "-77.768741" },
		mapZoom: 8,
		polyOverlays: false
	};
	/* Replace Default Args with New Args */
	for (var argName in ArgsObj) {
		NewArguments[argName] = ArgsObj[argName];
	}
	/* Set Properties with Latest Arguments */
	var self = this;
	self.containerObj = NewArguments.containerObj;
	self.mapObj = NewArguments.containerObj;
	self.markers = NewArguments.markers;
	self.mapCenter = NewArguments.mapCenter;
	self.mapZoom = NewArguments.mapZoom;
	self.polyOverlays = NewArguments.polyOverlays;

	/* More Properties */
	self.markerObjs = [ ];

	//console.log("GMap_initialize() running... self.containerObj %o self.markers %o, self.polyOverlays %o",self.containerObj,self.markers,self.polyOverlays);

	self.doClustering = function() {
		var clusterIcon = self.createClusterMarker();
		self.cluster = new ClusterMarker(self.GMapObj, { markers: self.markerObjs, clusterMarkerIcon: clusterIcon } );
		self.cluster.fitMapToMarkers();
		
		self.GMapObj.savePosition(); //  enables the large map control centre button to return the map to initial view
		
		/*
		//  add an HtmlControl to enable toggling of the ClusterMarker cluster function
		//  see http://googlemapsapi.martinpearman.co.uk/htmlcontrol for more info on HtmlControl
		var html='<div class="htmlControl" style="padding:0px 3px 3px 3px">Enable clustering: <input type="checkbox" checked="checked" onclick="toggleClustering()" /></div>';
		var control=new HtmlControl(html);
		map.addControl(control, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7)));
		
		function toggleClustering() {
		cluster.clusteringEnabled=!cluster.clusteringEnabled;
		cluster.refresh(true);	//	true required to force a full update of the markers - otherwise the update would occur next time that the map is zoomed or the active markers change
		}
		*/
	}
	self.addMarkers = function() {
		for (i=0, j=self.markers.length; i<j; i++) {
			var markerObj = self.createMarker(self.markers[i]);
			self.markerObjs.push(markerObj);
		}
	}
	self.createClusterMarker = function() {
		var marker = new GIcon();
		marker.image="/stylesheets/images/default/map/mapPoint-cluster.png";
		marker.transparent = "/stylesheets/images/default/map/mapPoint-trans.png";
		marker.iconSize=new GSize(29, 29);
		marker.iconAnchor=new GPoint(9, 31);
		marker.infoWindowAnchor=new GPoint(9, 31);
		marker.shadow = "http://www.google.com/mapfiles/shadow50.png";
		marker.shadowSize=new GSize(0, 0);
		return marker;
	}
	self.createMarker = function(marker) {
		//console.log("createExtInfoWindow: have map obj as '%o', marker %o",map,marker);
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(53, 63);
		// define click area for standards browsers
		baseIcon.imageMap = [ 13,61, 0,15, 2,7, 4,4, 7,2, 13,0, 20,2, 23,4, 26,8, 27,13, 13,61 ];
		// define click area for IE6
		baseIcon.transparent = "/stylesheets/images/default/map/mapPoint-trans.png";
		// we include our shadow in the icon image
		baseIcon.shadowSize = new GSize(0, 0);
		baseIcon.iconAnchor = new GPoint(15, 63);
		baseIcon.infoWindowAnchor = new GPoint(-120, 80);

		var customIcon = new GIcon(baseIcon);
		switch(marker.type) {
			case "Headquarters":
				customIcon.image = "/stylesheets/images/default/map/mapPoint-HQ.png";
				customIcon.iconSize = new GSize(34, 56);
				break;
			case "Nuclear":
				customIcon.image = "/stylesheets/images/default/map/mapPoint-triangle.png";
				break;
			case "Hydro":
				customIcon.image = "/stylesheets/images/default/map/mapPoint-diamond.png";
				break;
			case "Solar":
				customIcon.image = "/stylesheets/images/default/map/mapPoint-star.png";
				break;
			case "Wind":
				customIcon.image = "/stylesheets/images/default/map/mapPoint-circle.png";
				break;
			case "Landfill Gas":
				customIcon.image = "/stylesheets/images/default/map/mapPoint-square.png";
				break;
			case "Fossil":
				customIcon.image = "/stylesheets/images/default/map/mapPoint-circle.png";
				break;
			default:
				customIcon.image = "/stylesheets/images/default/map/mapPoint-diamond.png";
				break;
		}

		// Set up GLatLong Obj
		var point = new GLatLng(marker.coords.lat,marker.coords.lng);

		// Set up GMarkerOptions object
		var markerOptions = { icon:customIcon };
		var markerObj = new GMarker(point, markerOptions);
		var bubbleHTML = createWindowHTML(marker); 
		self.extInfoWindowEvent(markerObj, bubbleHTML);

		return markerObj;
	}
	self.extInfoWindowEvent = function(markerObj,bubbleHTML) {
		var mapID = "map-1";
		GEvent.addListener(markerObj, 'click', function(){ 
			markerObj.openExtInfoWindow(
				self.GMapObj,
				"extWindow",
				bubbleHTML,
				{ beakOffset: 3, cssClassName: "gmaps_bubble", layoutContextId: mapID, avoidMapControls: true  }
			); 
		});
	}
	self.doPolygons = function() {
		//console.log("GMap: doPolygons()...",this.polyOverlays);
		for (var i=0, j=this.polyOverlays.length; i<j; i++) {
			var overlay = this.polyOverlays[i];
			var transCoords = [ ];
            if (overlay.dataService) {
                self.addGGeoXmlPoly(overlay);
            } else {
			    for (var m=0, n=overlay.coords.length; m<n; m++) {
				    var Gpt = new GLatLng(overlay.coords[m].lat,overlay.coords[m].lng)
				    transCoords.push(Gpt);
                }
			    var poly = new GPolygon(transCoords, "#ff0000", 1, 0.36, "#ee3342", 0.2);

			    /* set center of map based on first overlay */
			    var center = this.polyOverlays[0].center;
			    var zoom = this.polyOverlays[0].zoom;
			    var Gcenter = new GLatLng(center.lat,center.lng);
			    self.GMapObj.setCenter(Gcenter, zoom);
                self.addPoly(poly);
			}
		}
	}
    self.addPoly = function(poly) {
			/* add polygon overlay */
			self.GMapObj.addOverlay(poly);
    }
    self.addGGeoXmlPoly = function(overlay) {
        //console.log("addGeoRSSPoly(): overlay %o...",overlay);
        self.geoXml = new GGeoXml(overlay.dataService,self.addGeoXmlComplete);
    }
    self.addGeoXmlComplete = function() {
    /*DEBUG
        console.log("addGeoXmlComplete, self.geoXml %o...",self.geoXml);
        console.log("self.geoXml.hasLoaded() %o",self.geoXml.hasLoaded());
        console.log("self.geoXml.loadedCorrectly() %o",self.geoXml.loadedCorrectly());
        console.log("self.geoXml.isHidden() %o",self.geoXml.isHidden());
        console.log("self.geoXml.getDefaultCenter() %o",self.geoXml.getDefaultCenter());
        console.log("self.geoXml.getDefaultBounds() %o",self.geoXml.getDefaultBounds());
        */
        self.GMapObj.setCenter(self.geoXml.getDefaultCenter());
        //console.log("self.mapCenter %o, self.mapZoom %o",self.mapCenter,self.mapZoom);
        //var center = new GLatLng(self.mapCenter.lat,self.mapCenter.lng);
        //self.GMapObj.setCenter(center,self.zoom);
        self.geoXml.gotoDefaultViewport(self.GMapObj);
        self.addPoly(self.geoXml);
    }
    self.getPolyDataError = function(transport) {
        //console.log("getPolyDataError()...");
        //console.log("data as \n",transport.responseXML);
    }
	if ((typeof GBrowserIsCompatible === "function") && (GBrowserIsCompatible()) && (self.containerObj)) {
		var mapDOMObj = $(self.mapObj);
		var width = mapDOMObj.offsetWidth;
		var height = mapDOMObj.offsetHeight;
		//console.log("have mapDOMObj as %o",mapDOMObj);
		self.GMapObj = new GMap2(mapDOMObj, { size: new GSize(width,height) });

		// markers 
		if (self.markers) {
			self.addMarkers();
		}
		// polygonal overlays
		//console.log(self.polyOverlays);
		if (self.polyOverlays) {
			self.doPolygons();
		}
		// add standard controls with maps.google.com behaviors
		var customUI = self.GMapObj.getDefaultUI();
		//customUI.controls.scalecontrol = false;
		self.GMapObj.setUI(customUI);

		// add Terrain map type and switch to it
		self.GMapObj.addMapType(G_PHYSICAL_MAP);
  		self.GMapObj.setMapType(G_PHYSICAL_MAP);
		// per Etool 100, client request ability to turn off on satellite view
		self.GMapObj.removeMapType(G_SATELLITE_MAP); 
		self.GMapObj.removeMapType(G_HYBRID_MAP);

		// marker clustering
		if (self.markerObjs.length) {
			self.doClustering();
		}
		// center & zoom map
		//self.GMapObj.setCenter(new GLatLng(self.mapCenter.lat, self.mapCenter.lng), self.mapZoom);
	}
}


function createWindowHTML(marker) {
	var plantType = marker.type.toLowerCase().split(' ')[0];
	var bubbleElements = Array();
	bubbleElements.push('<div class="mapBubble">');
	bubbleElements.push('   <div class="header '+plantType+'">'+marker.type+'</div>');
	bubbleElements.push('   <div class="content">');
	bubbleElements.push('       <p class="title">'+marker.name+'<p>');
	bubbleElements.push('       <p class="address">'+marker.address+'</p>');
	bubbleElements.push('       <p class="citystate">'+marker.city+' '+marker.state+' '+marker.zip+'</p>');
	bubbleElements.push('       <p class="phone">'+marker.phone+'</p>');
	bubbleElements.push('    </div>');
	bubbleElements.push('    <div class="actions">');
    if (marker.directions != ''){ bubbleElements.push('       <a class="directions" href="'+marker.directions+'">directions</a> '); }
    if (marker.directions != '' && marker.email != ''){ bubbleElements.push('       <span>|</span> '); }
    if (marker.email != ''){ bubbleElements.push('       <a class="email" href="'+marker.email+'">email</a>'); }
	bubbleElements.push('    </div>');
	bubbleElements.push('</div>');
	var HTML = bubbleElements.join("\n");

	return HTML;
}

/*
 * ClusterMarker Version 1.3.2
 * A marker manager for the Google Maps API                                                      *
 * http://googlemapsapi.martinpearman.co.uk/clustermarker                                        *
 *                                                                                               *
 * This program is free software: you can redistribute it and/or modify it under the terms of    *
 * the GNU General Public License as published by the Free Software Foundation, either version 3 *
 * of the License, or (at your option) any later version.                                        *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;     *
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     *
 * See the GNU General Public License for more details.                                          */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('f h(a,b){2.5=a;2.k=[];2.C=[];2.F=[];2.S=[];4(D(b)===\'N\'){b={}}2.T=(b.T)?b.T:24;2.1c=(b.1c===o)?o:r;4(b.O){2.O=b.O}4(b.s){2.s=b.s}G{2.s=m 25();2.s.26=\'1z://27.1A.1B/1C/28.1D\';2.s.H=m 1E(1F,1G);2.s.1H=m I(9,1I);2.s.29=m I(9,1I);2.s.2a=\'1z://2b.1A.1B/2c/2d/1C/2e.1D\';2.s.2f=m 1E(1F,1G)}2.U=(b.U)?b.U:\'2g 2h 2i 1J 2j 2k %1K 1d\';4(b.J){2.J=b.J}2.v=(b.v)?b.v:0;4(b.1d){2.1L(b.1d)}K.1e(2.5,\'2l\',2,2.1M);K.1e(2.5,\'2m\',2,2.1N);K.1e(2.5,\'2n\',2,2.1O)}h.l.1L=f(a){n i;4(!a[0]){n b=[];g(i 1J a){b.w(a[i])}a=b}g(i=a.8-1;i>=0;i--){a[i].A=o;a[i].t=o;a[i].z=o}2.k=2.k.2o(a)};h.l.1P=f(d){f $1Q(a,b,c){1f m 2p(a,{2q:b,2r:c})}n e=m 1g(),i,$u,$V=[],$3,$2=2,$6=2.k;g(i=d.8-1;i>=0;i--){$3=$6[d[i]];$3.2s=d[i];e.W($3.B());$V.w($3)}$u=$1Q(e.1R(),2.s,2.U.2t(/%1K/2u,d.8));$u.1S=e;2.S.w(K.2v($u,\'1T\',f(){4(D $2.5.X==="f"){$2.5.X()}$2.O({u:$u,V:$V})}));$u.1h=d;g(i=d.8-1;i>=0;i--){$6[d[i]].1i=$u}1f $u};h.l.O=f(a){2.5.Y(a.u.B(),2.5.1U(a.u.1S))};h.l.1V=f(){n a=2.T,$7=2.5.Z(),$P=2.5.10().1W(),$11,$1j,$1k,$12,$1l,$1m,$E=2.5.2w(),i,$3,$p=[],$1n,$6=2.k,$q=2.C;4(a){$11=$P.1o($E.2x(),$7);$1j=m I($11.x-a,$11.y+a);$1k=$P.13($1j,$7);$12=$P.1o($E.2y(),$7);$1l=m I($12.x+a,$12.y-a);$1m=$P.13($1l,$7);$E.W($1k);$E.W($1m)}2.Q=o;4(D($q[$7])===\'N\'){2.C[$7]=[];2.Q=r;g(i=$6.8-1;i>=0;i--){$3=$6[i];$3.t=$E.1X($3.B())?r:o;$3.z=$3.t;4($3.t){$p.w(i)}}}G{g(i=$6.8-1;i>=0;i--){$3=$6[i];$1n=$3.t;$3.t=$E.1X($3.B())?r:o;$3.z=$3.t;4(!2.Q&&$1n!==$3.t){2.Q=r}4($3.t&&D($q[$7][i])===\'N\'){$p.w(i)}}}1f $p};h.l.1Y=f(){n a,i,j,$7=2.5.Z(),$6=2.k,$q=2.C;g(i=$6.8-1;i>0;i--){4($6[i].z){a=[];g(j=i-1;j>=0;j--){4($6[j].z&&$q[$7][i].1Z($q[$7][j])){a.w(j)}}4(a.8!==0){a.w(i);g(j=a.8-1;j>=0;j--){$6[a[j]].z=o}2.F.w(2.1P(a))}}}};h.l.2z=f(){n a=2.k,$14=m 1g(),i;g(i=a.8-1;i>=0;i--){$14.W(a[i].B())}n b=2.5.1U($14);4(2.J&&b>2.J){b=2.J}2.5.Y($14.1R(),b);2.R()};h.l.1O=f(){2.R(r)};h.l.1M=f(){4(!2.1p){2.R()}G{2.1p=o}};h.l.15=f(a,b){n c=2.5.10().1W(),i,$3,$H,$L,$M,$1q,$1r,$1s,$1t,$v=2.v,$6=2.k;g(i=a.8-1;i>=0;i--){$3=$6[a[i]];$H=$3.20().H;$L=c.1o($3.B(),b);$M=$3.20().1H;$1q=m I($L.x-$M.x-$v,$L.y-$M.y+$H.2A+$v);$1r=m I($L.x-$M.x+$H.2B+$v,$L.y-$M.y-$v);$1s=c.13($1q,b);$1t=c.13($1r,b);2.C[b][a[i]]=m 1g($1s,$1t)}};h.l.R=f(a){n i,$3,$1u=2.5.Z(),$p=2.1V();4(2.Q||a){2.1v();4(2.1c&&$1u<2.5.10().21()){4($p.8>0){2.15($p,$1u)}2.1Y()}g(i=2.F.8-1;i>=0;i--){2.5.22(2.F[i])}g(i=2.k.8-1;i>=0;i--){$3=2.k[i];4(!$3.A&&$3.z){2.5.22($3);$3.A=r}4($3.A&&!$3.z){2.5.1w($3);$3.A=o}}}};h.l.1v=f(){n i,j,$16=2.5,$1x=2.S,$17=2.F,$18,$6=2.k;g(i=$17.8-1;i>=0;i--){$18=$17[i].1h;g(j=$18.8-1;j>=0;j--){19 $6[$18[j]].1i}$16.1w($17[i])}g(i=$1x.8-1;i>=0;i--){K.2C($1x[i])}2.F=[];2.S=[]};h.l.2D=f(){n i,$6=2.k,$16=2.5;g(i=$6.8-1;i>=0;i--){4($6[i].A){$16.1w($6[i])}19 $6[i].A;19 $6[i].t;19 $6[i].z}2.1v();2.k=[];2.C=[]};h.l.1y=f(a){n b=2.k[a];4(b.A){K.2E(b,\'1T\')}G 4(b.t){n c=b.1i.1h,$1a=r,$p,i,$7=2.5.Z(),$1b,$q=2.C,$23=2.5.10().21();2F($1a&&$7<$23){$1a=o;$7++;4(D($q[$7])===\'N\'){$q[$7]=[];2.15(c,$7)}G{$p=[];g(i=c.8-1;i>=0;i--){4(D($q[$7][c[i]])===\'N\'){$p.w(c[i])}}4($p.8>=1){2.15($p,$7)}}g(i=c.8-1;i>=0;i--){$1b=c[i];4($1b!==a&&$q[$7][$1b].1Z($q[$7][a])){$1a=r;2G}}};2.5.Y(b.B(),$7);2.1y(a)}G{2.5.Y(b.B());2.1y(a)}};h.l.1N=f(){4(D 2.5.X==="f"){2.5.X()}2.1p=r;2.R(r)};',62,167,'||this|marker|if|_map|mapMarkers|mapZoomLevel|length|||||||function|for|ClusterMarker|||_mapMarkers|prototype|new|var|false|uncachedIconBoundsIndexes|iconBounds|true|clusterMarkerIcon|_isActive|clusterMarker|intersectPadding|push|||_makeVisible|_isVisible|getLatLng|_iconBounds|typeof|activeAreaBounds|_clusterMarkers|else|iconSize|GPoint|fitMapMaxZoom|GEvent|iconAnchorPoint|iconAnchorPointOffset|undefined|clusterMarkerClick|mapProjection|_activeMarkersChanged|refresh|_eventListeners|borderPadding|clusterMarkerTitle|clusteredMarkers|extend|closeExtInfoWindow|setCenter|getZoom|getCurrentMapType|mapPointSw|mapPointNe|fromPixelToLatLng|markersBounds|_preCacheIconBounds|map|clusterMarkers|childIndexes|delete|intersectDetected|clusteredMarkerIndex|clusteringEnabled|markers|bind|return|GLatLngBounds|_childIndexes|_parentCluster|activeAreaPointSw|activeAreaLatLngSw|activeAreaPointNe|activeAreaLatLngNe|oldState|fromLatLngToPixel|_cancelMoveEnd|iconBoundsPointSw|iconBoundsPointNe|iconBoundsLatLngSw|iconBoundsLatLngNe|zoomLevel|_removeClusterMarkers|removeOverlay|eventListeners|triggerClick|http|google|com|mapfiles|png|GSize|39|34|iconAnchor|31|in|count|addMarkers|_moveEnd|_zoomEnd|_mapTypeChanged|_clusterMarker|newClusterMarker|getCenter|clusterGroupBounds|click|getBoundsZoomLevel|_filterActiveMapMarkers|getProjection|containsLatLng|_filterIntersectingMapMarkers|intersects|getIcon|getMaximumResolution|addOverlay|mapMaxZoomLevel|256|GIcon|image|maps|arrow|infoWindowAnchor|shadow|www|intl|en_us|arrowshadow|shadowSize|Click|to|zoom|and|see|moveend|zoomend|maptypechanged|concat|GMarker|icon|title|index|replace|gi|addListener|getBounds|getSouthWest|getNorthEast|fitMapToMarkers|height|width|removeListener|removeMarkers|trigger|while|break'.split('|'),0,{}))

document.observe('dom:loaded', function() {
	var tabControlSelector = 'dt.tab a';
	var tabSelector = 'dd.tab_body';
	DocumentTabs = new Array();
	$$('.tabbed_content').each(function(tabbed_content){

	var tabSwitcher = new TabSwitcher({	tabArea: tabbed_content,
										controlSelector: tabControlSelector,
										tabSelector: tabSelector,
										tabActiveClass: 'active',
										tabHoverClass: 'active',
                                        equalHeightCols: false
									 	});
		DocumentTabs.push(tabSwitcher);
	});
});

var TabSwitcher = function(ArgumentsObj) {
	/* Argument Defaults */
	var NewArguments = {
		tabAreaDOM: false,
		controlSelector: false,
		tabSelector: false,
		tabActiveClass: 'tabActive',
		tabHoverClass: 'tabHover',
        equalHeightCols: false 
	};
	/* Replace Default Args with New Args */
	for (var argName in ArgumentsObj) {
		NewArguments[argName] = ArgumentsObj[argName];
	}
	/* Set Properties with Latest Arguments */
	this.tabAreaDOM = NewArguments.tabArea;
	this.controlSelector = NewArguments.controlSelector;
	this.tabSelector = NewArguments.tabSelector;
	this.tabActiveClass = NewArguments.tabActiveClass;
	this.tabHoverClass = NewArguments.tabHoverClass;
    /* for layout support, even height columns:  tab controls stacked in one column, with 
       tab body to either side. after switching tabs make the tab controls equal height of tab body */
	this.equalHeightCols = NewArguments.equalHeightCols; 

	/* Other Properties */
	this.tabControls = new Array();

	this.init = function(){
		var controls = $(self.tabAreaDOM).select(self.controlSelector);
		$(controls).each(function(control){
			self.tabControls.push({ DOMObj: control, active: false });
		});
		self.tabs = $(self.tabAreaDOM).select(self.tabSelector);
		self.registerEvents(); 
		self.showTab(0, null);
		//console.log("new instance TabSelector, %o",self);
	}
	this.registerEvents = function() {
		//console.log('registerEvents() for object %o',self);
		$(self.tabControls).each(function(tC,index){
			//console.log('working for tab control this %o, index %o',tC,index);

			// click
			Event.observe(tC.DOMObj, 'click', function(event) { self.showTab(index, event); }, false);

			// mousover
			Event.observe(tC.DOMObj, 'mouseover', function(){ 
				$(this).addClassName(self.tabHoverClass); 
			}, false);

			// mouseout
			Event.observe(tC.DOMObj, 'mouseout', function(){ 
				/* handle edge case where hover and active class are same name */
				if (self.tabActiveClass === self.tabHoverClass){ 
					if (tC.active) {
						 /* don't remove the classname, it's the active state */
					} else {
						$(this).removeClassName(self.tabHoverClass);
					}
				}
			}, false);

		});
	}
	this.showTab = function(tabRef, event) {
		if (event) Event.stop(event);
		var tab = false;
		var tabNumb;
		if (self.isInteger(tabRef)) {
			tabNumb = tabRef;
		} else {
			tabJ = $$('.'+tabRef)[0];
			var allTabs = $(tabJ.parentNode).childElements();
			$(allTabs).each(function(tab,i){
				if ($(tab).hasClass(tabRef)) {
					tabNumb = i;
				}
			});
		}
		tab = self.tabs[tabNumb];
		//console.log('showTab(): selected tab as "%o"',tab);
		/* only switch if new tab body exists */
		if (tab) {
			self.hideTabs();
			self.tabControls[tabNumb].active = true;
			$(self.tabControls[tabNumb].DOMObj).addClassName(self.tabActiveClass);
			$(tab).removeClassName('hidden');
            self.activeTab = tab;
            if (self.equalHeightCols) {
                self.doEqualHeightCols();
            }
		}
	}
    /* for layout support, even height columns:  tab controls stacked in one column, with 
       tab body to either side. after switching tabs make the tab controls equal height of tab body */
    this.doEqualHeightCols = function() {
        //console.log('doEqualHeightCols()...');
        var numTabs = self.tabs.length;
        var tabControlsHeight = 0;
        var tabActiveHeight = $(self.activeTab).getHeight();
        //console.log("tabActiveHeight: %s",tabActiveHeight);
        for (i=0, j=numTabs; i<j; i++) {
            var tabH = $(self.tabControls[i].DOMObj).getHeight();
            var tabCSSH = $(self.tabControls[i].DOMObj).getStyle("height");
            //console.log('tabH: %s, tabCSSH %s',tabH,tabCSSH);
            tabControlsHeight += tabH;
        }
        var heightDelta = tabActiveHeight - tabControlsHeight; 
        //console.log("tabControlsHeight: %s",tabControlsHeight);
        if (!(tabControlsHeight == tabActiveHeight)) {
            //console.log("adjusting tab heights for large tab body with delta %s",heightDelta);
            var heightAdd = 0;
            var heightAddPerfect = 0;
            var numToGetRemain = 0;
            var remainRatio = 0;
            if (heightDelta % numTabs == 0) {
                heightAdd = heightDelta / numTabs; 
                //console.log("perfect height to add division. height to add to each tab control: %s",heightAdd);
            } else {
                heightAddPerfect = heightDelta / numTabs;
                heightAdd = heightAddPerfect.floor(); 
                remainRatio = heightAddPerfect - heightAdd;
                numToGetRemain = remainRatio * numTabs;
                //console.log("remainder components as:\nheightAddPerfect %s\nheightAdd %s\nremainRatio %s\nnumToGetRemain %s",heightAddPerfect,heightAdd,remainRatio,numToGetRemain);
            }
            for (i=0, j=numTabs; i<j; i++) {
                var tabC = self.tabControls[i].DOMObj;
                var heightCSS = $(tabC).getStyle("height");
                controlHeightStr = heightCSS.substring(0,heightCSS.length-2);
                controlHeight = controlHeightStr * 1;
                var newHeight = heightAdd + controlHeight;
                if (i < numToGetRemain) {
                    newHeight += 1;
                }
                //console.log("setting tab height to newHeight %s, based on add %s, controlHeight %s",newHeight,heightAdd,controlHeight);
                $(tabC).setStyle({ "height": newHeight+"px" });
            }
            var isMSIE = /*@cc_on!@*/false;
            /* fix for IE, where last tab body is not repositioned with tab re-size */
            if (isMSIE) {
                var bottomTabs = $(self.activeTab).adjacent(".tab_bottom");
                var container = $(self.activeTab.parentNode);
                if (container) {
                    $(container).setStyle({ "height": tabActiveHeight+4+"px" }); 
                }
                if (bottomTabs[0]) {
                    $(bottomTabs[0]).setStyle({ "bottom": "0px" });
                }
            }
        }
    }
	this.hideTabs = function() {
		$(self.tabControls).each(function(tabC) {
			tabC.active = false;
			$(tabC.DOMObj).removeClassName(self.tabActiveClass);
		});
		$(self.tabs).invoke('addClassName', 'hidden');
	}
	this.isInteger = function(s) {
		return (s.toString().search(/^-?[0-9]+$/) == 0);
	}

	var self = this;
	self.init();
}

document.observe('dom:loaded', function() {
	$$('.carousel_small .carousel_rail').each(function(s) {
        var paneEls = (s.select(".pane").length) ? s.select(".pane") : s.select("dl");
        s.insert(paneEls[0].cloneNode(true));
        //console.log("paneEls as %o",paneEls);
		var railWidth = ((paneEls.length + 1) * paneEls[0].getWidth()) + 'px';
		var heightArray = new Array;
		paneEls.each(function(el, i) { heightArray[i] = el.getHeight() });
		var railHeight = (heightArray.max()) + 'px';
		s.setStyle({
			'width': railWidth,
			'height': railHeight
		});
		s.up().setStyle({
			'height': railHeight
		});
		s.up(1).setStyle({
			'height': railHeight
		});
	});
});

/*
Copyright (c) 2009 Victor Stanciu - http://www.victorstanciu.ro

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

Carousel = Class.create(Abstract, {
	initialize: function (scroller, slides, controls, options) {
		this.scrolling	= false;
		this.scroller	= $(scroller);
		this.slides		= slides;
		this.controls	= controls;

		this.options    = Object.extend({
            duration:           1,
            auto:               false,
            frequency:          3,
            visibleSlides:      1,
            controlClassName:   'carousel-control',
            jumperClassName:    'carousel-jumper',
            disabledClassName:  'carousel-disabled',
            selectedClassName:  'carousel-selected',
            circular:           false,
            wheel:              true,
            effect:             'scroll',
            transition:         'sinoidal'
        }, options || {});
        
        if (this.options.effect == 'fade') {
            this.options.circular = true;
        }

		this.slides.each(function(slide, index) {
			slide._index = index;
        });

		if (this.controls) {
            this.controls.invoke('observe', 'click', this.click.bind(this));
        }
        
        if (this.options.wheel) {            
            this.scroller.observe('mousewheel', this.wheel.bindAsEventListener(this)).observe('DOMMouseScroll', this.wheel.bindAsEventListener(this));;
        }

        if (this.options.auto) {
            this.start();
        }

		if (this.options.initial) {
			var initialIndex = this.slides.indexOf($(this.options.initial));
			if (initialIndex > (this.options.visibleSlides - 1) && this.options.visibleSlides > 1) {               
				if (initialIndex > this.slides.length - (this.options.visibleSlides + 1)) {
					initialIndex = this.slides.length - this.options.visibleSlides;
				}
			}
            this.moveTo(this.slides[initialIndex]);
		}
	},

	click: function (event) {
		this.stop();

		var element = event.findElement('a');

		if (!element.hasClassName(this.options.disabledClassName)) {
			if (element.hasClassName(this.options.controlClassName)) {
				eval("this." + element.rel + "()");
            } else if (element.hasClassName(this.options.jumperClassName)) {
                this.moveTo(element.rel);
                if (this.options.selectedClassName) {
                    this.controls.invoke('removeClassName', this.options.selectedClassName);
                    element.addClassName(this.options.selectedClassName);
                }
            }
        }

		this.deactivateControls();

		event.stop();
    },

	moveTo: function (element) {
		if (this.options.beforeMove && (typeof this.options.beforeMove == 'function')) {
			this.options.beforeMove();
        }

		this.previous = this.current ? this.current : this.slides[0];
		this.current  = $(element);

		var scrollerOffset = this.scroller.cumulativeOffset();
		var elementOffset  = this.current.cumulativeOffset();

		if (this.scrolling) {
			this.scrolling.cancel();
		}

        switch (this.options.effect) {
            case 'fade':               
                this.scrolling = new Effect.Opacity(this.scroller, {
                    from:   1.0,
                    to:     0,
                    duration: this.options.duration,
                    afterFinish: (function () {
                        this.scroller.scrollLeft = elementOffset[0] - scrollerOffset[0];
                        this.scroller.scrollTop  = elementOffset[1] - scrollerOffset[1];

                        new Effect.Opacity(this.scroller, {
                            from: 0,
                            to: 1.0,
                            duration: this.options.duration,
                            afterFinish: (function () {
                                if (this.controls) {
                                    this.activateControls();
                                }
                                if (this.options.afterMove && (typeof this.options.afterMove == 'function')) {
                                    this.options.afterMove();
                                }
                            }).bind(this)
                        });
                    }
                ).bind(this)});
            break;
            case 'scroll':
            default:
                var transition;
                switch (this.options.transition) {
                    case 'spring':
                        transition = Effect.Transitions.spring;
                        break;
                    case 'sinoidal':
                    default:
                        transition = Effect.Transitions.sinoidal;
                        break;
                }

                this.scrolling = new Effect.SmoothScroll(this.scroller, {
                    duration: this.options.duration,
                    x: (elementOffset[0] - scrollerOffset[0]),
                    y: (elementOffset[1] - scrollerOffset[1]),
                    transition: transition,
                    afterFinish: (function () {
                        if (this.controls) {
                            this.activateControls();
                        }
                        if (this.options.afterMove && (typeof this.options.afterMove == 'function')) {
                            this.options.afterMove();
                        }                        
                        this.scrolling = false;
                    }).bind(this)});
            break;
        }

		return false;
	},

	prev: function () {
		if (this.current) {
			var currentIndex = this.current._index;
			var prevIndex = (currentIndex == 0) ? (this.options.circular ? this.slides.length - 1 : 0) : currentIndex - 1;
        } else {
            var prevIndex = (this.options.circular ? this.slides.length - 1 : 0);
        }

		if (prevIndex == (this.slides.length - 1) && this.options.circular && this.options.effect != 'fade') {
			this.scroller.scrollLeft =  (this.slides.length - 1) * this.slides.first().getWidth();
			this.scroller.scrollTop =  (this.slides.length - 1) * this.slides.first().getHeight();
			prevIndex = this.slides.length - 2;
        }

		this.moveTo(this.slides[prevIndex]);
	},

	next: function () {
		if (this.current) {
			var currentIndex = this.current._index;
			var nextIndex = (this.slides.length - 1 == currentIndex) ? (this.options.circular ? 0 : currentIndex) : currentIndex + 1;
        } else {
            var nextIndex = 1;
        }

		if (nextIndex == 0 && this.options.circular && this.options.effect != 'fade') {
			this.scroller.scrollLeft = 0;
			this.scroller.scrollTop  = 0;
			nextIndex = 1;
        }

		if (nextIndex > this.slides.length - (this.options.visibleSlides + 1)) {
			nextIndex = this.slides.length - this.options.visibleSlides;
		}		

		this.moveTo(this.slides[nextIndex]);
	},

	first: function () {
		this.moveTo(this.slides[0]);
    },

	last: function () {
		this.moveTo(this.slides[this.slides.length - 1]);
    },

	toggle: function () {
		if (this.previous) {
			this.moveTo(this.slides[this.previous._index]);
        } else {
            return false;
        }
    },

	stop: function () {
		if (this.timer) {
			clearTimeout(this.timer);
		}
	},

	start: function () { 
        this.periodicallyUpdate();
    },

	pause: function () {
		this.stop();
		this.activateControls();
    },

	resume: function (event) {
		if (event) {
			var related = event.relatedTarget || event.toElement;
			if (!related || (!this.slides.include(related) && !this.slides.any(function (slide) { return related.descendantOf(slide); }))) {
				this.start();
            }
        } else {
            this.start();
        }
    },

	periodicallyUpdate: function () {
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.next();
        }
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency * 1000);
    },
    
    wheel: function (event) {
        event.cancelBubble = true;
        event.stop();
        
		var delta = 0;
		if (!event) {
            event = window.event;
        }
		if (event.wheelDelta) {
			delta = event.wheelDelta / 120; 
		} else if (event.detail) { 
            delta = -event.detail / 3;	
        }        
       
        if (!this.scrolling) {
            this.deactivateControls();
            if (delta > 0) {
                this.prev();
            } else {
                this.next();
            }            
        }
        
		return Math.round(delta); //Safari Round
    },

	deactivateControls: function () {
		this.controls.invoke('addClassName', this.options.disabledClassName);
    },

	activateControls: function () {
		this.controls.invoke('removeClassName', this.options.disabledClassName);
    }
});


Effect.SmoothScroll = Class.create();
Object.extend(Object.extend(Effect.SmoothScroll.prototype, Effect.Base.prototype), {
	initialize: function (element) {
		this.element = $(element);
		var options = Object.extend({ x: 0, y: 0, mode: 'absolute' } , arguments[1] || {});
		this.start(options);
    },

	setup: function () {
		if (this.options.continuous && !this.element._ext) {
			this.element.cleanWhitespace();
			this.element._ext = true;
			this.element.appendChild(this.element.firstChild);
        }

		this.originalLeft = this.element.scrollLeft;
		this.originalTop  = this.element.scrollTop;

		if (this.options.mode == 'absolute') {
			this.options.x -= this.originalLeft;
			this.options.y -= this.originalTop;
        }
    },

	update: function (position) {
		this.element.scrollLeft = this.options.x * position + this.originalLeft;
		this.element.scrollTop  = this.options.y * position + this.originalTop;
    }
});

/*
 *
 *  Ajax Autocomplete for Prototype, version 1.0.3
 *  (c) 2008 Tomas Kirda
 *
 *  Ajax Autocomplete for Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the web site: http://www.devbridge.com/projects/autocomplete/
 *
 */
var globalResultsPage;
var Autocomplete = function(el, options){
  this.hasSearch = false;
  this.qr = null;
  this.el = $(el);
  if (this.el) {
    this.el.setAttribute('autocomplete','off');
    this.currentValue = this.el.value;
  }
  this.submitEl = $("global_search_submit");
  this.fieldsEl = $("global_search_fields");
  this.formWrapRef = "#shortcuts > ul";
  this.positionEl = $("shortcut-search");
  this.formWrapEl = false;
  this.id = (this.el) ? this.el.identify() : false;
  this.query = null;
  this.suggestions = [];
  this.categories = [];
  this.results = [];
  this.data = [];
  this.badQueries = [];
  this.selectedIndex = -1;
  this.intervalId = 0;
  this.cachedResponse = [];
  this.instanceId = null;
  this.onChangeInterval = null;
  this.ignoreValueChange = false;
  this.serviceUrl = options.serviceUrl;
  this.resultsPage = options.resultsPage;
  this.isMSIE = /*@cc_on!@*/false;
  this.options = {
    autoSubmit:false,
    minChars:1,
    //maxHeight:300,
    deferRequestBy:0,
    width:0,
    container:null,
	staticSearch: false
  };
  if (this.el) {
    if(options){ Object.extend(this.options, options); }
    if(Autocomplete.isDomLoaded){
        this.initialize();
    }else{
        Event.observe(document, 'dom:loaded', this.initialize.bind(this), false);
    }
  }
};

Autocomplete.instances = [];
Autocomplete.isDomLoaded = false;

Autocomplete.getInstance = function(id){
  var instances = Autocomplete.instances;
  var i = instances.length;
  while(i--){ if(instances[i].id === id){ return instances[i]; }}
};

Autocomplete.highlight = function(value, re){
  return value.replace(re, function(match){ return '<strong>' + match + '<\/strong>' });
};

Autocomplete.prototype = {

  killerFn: null,

  initialize: function() {
    var me = this;
    this.killerFn = function(e) {
      if (!$(Event.element(e)).up('.autocomplete')) {
        me.killSuggestions();
        me.disableKillerFn();
      }
    }.bindAsEventListener(this);

    if (!this.options.width) { this.options.width = this.el.getWidth(); }
	if(this.resultsPage){ globalResultsPage = this.resultsPage;}

    var wrapEl = $$(this.formWrapRef)[0];
    if (wrapEl) { 
        this.formWrapEl = wrapEl;
    }


	this.qr = $('quickResults');
    if (this.qr) {
	    this.qr.down('div.autocomplete').id = 'Autocomplete_' + this.id;
	    Event.observe($('quickResultsClose'), 'click', function(){this.hide});

        this.container = $('Autocomplete_' + this.id);

        Event.observe(this.el, window.opera ? 'keypress':'keydown', this.onKeyPress.bind(this));
        Event.observe(this.el, 'keyup', this.onKeyUp.bind(this));
        Event.observe(this.el, 'blur', this.enableKillerFn.bind(this));

        /* not using recent searches capability for Exelon */
        //Event.observe(this.el, 'focus', this.recentSearch.bind(this));

        this.instanceId = Autocomplete.instances.push(this) - 1;

        this.positionDropdown();
    }
  },
  positionDropdown: function() {
    /* position dropdown horiz since layout cannot naturally position */
    if (this.positionEl) {
        var ancestors = $(this.positionEl).ancestors();
        var totalOffset = this.positionEl.offsetLeft;
        var newOffset = 0;
        for (var i=0, j=ancestors.length; i<j; i++) {
            newOffset = ancestors[i].offsetLeft;
            //totalOffset += newOffset;
        }
        var staticPad = (this.isMSIE) ? -9 : -9;
        totalOffset += staticPad
        $(this.qr).setStyle({ left: totalOffset+"px" });
    }
  },
  fixPosition: function() {
    var offset = this.el.cumulativeOffset();
    $(this.mainContainerId).setStyle({ top: (offset.top + this.el.getHeight()) + 'px', left: offset.left + 'px' });
  },
  recentSearch: function(){
	if(this.el.value.toLowerCase() == 'search'){this.el.value = ''}

	var recentTerms = this.readCookie('recentSearchCookie');
	
	if((recentTerms) && (this.el.value == '')){

		$(this.fieldsEl).className = "active";
		
		var seachHeight =  $(this.fieldsEl).down('fieldset').getHeight();
		this.qr.show();
        this.formWrapEl.addClassName("quickSearchActive");
		this.container.show();
	
		if($('recentSearchTerms')){return false;}
		var ul = new Element('ul');
		ul.id = "recentSearchTerms";		
		var termArray = recentTerms.split(':');
		 for(var i=0; i<termArray.length; i++){
			var li = new Element('li');
			var a = new Element('a');
			a.innerHTML = termArray[i];
			a.href = '#';
		    Event.observe(a, 'click', function(){
			   var thisTerm = this.innerHTML;
			   Autocomplete.prototype.globalSearch(thisTerm);   
				return false;
			});
			li.appendChild(a);
			ul.appendChild(li);
		}
		this.qr.down('div.autocomplete').update(ul);
	}
  
},
  enableKillerFn: function() {
    if(this.el.value == ''){this.el.value = 'SEARCH'; this.hasSearch = false;} 
    $(this.submitEl).removeClassName('searching');
	
	Event.observe(document.body, 'click', this.killerFn);
  },

  disableKillerFn: function() {
    Event.stopObserving(document.body, 'click', this.killerFn);
  },

  killSuggestions: function() {
    this.stopKillSuggestions();
    this.intervalId = window.setInterval(function() { this.hide(); this.stopKillSuggestions(); } .bind(this), 300);

	this.hasSearch = false;
	$(this.fieldsEl).className = '';
	$('viewAll').hide();
	this.qr.hide();
    this.formWrapEl.removeClassName("quickSearchActive");
	if($('recentSearchTerms')){
	  this.qr.down('div.autocomplete').removeChild($('recentSearchTerms'));
  	}
},

  stopKillSuggestions: function() {
    window.clearInterval(this.intervalId);
  },

  onKeyPress: function(e) {
    if (!this.enabled) { return; }
    // return will exit the function
    // and event will not fire
    switch (e.keyCode) {
      case Event.KEY_ESC:
        this.el.value = this.currentValue;
        this.hide();
        break;
      case Event.KEY_TAB:
      case Event.KEY_RETURN:
        if (this.selectedIndex === -1) {
          this.hide();
          return;
        }
        this.select(this.selectedIndex);
        if (e.keyCode === Event.KEY_TAB) { return; }
        break;
      case Event.KEY_UP:
        this.moveUp();
        break;
      case Event.KEY_DOWN:
        this.moveDown();
        break;
      default:
        return;
    }
    Event.stop(e);
  },

  onKeyUp: function(e) {
    switch (e.keyCode) {
      case Event.KEY_UP:
      case Event.KEY_DOWN:
        return;
    }
    clearInterval(this.onChangeInterval);
    if (this.currentValue !== this.el.value) {
      if (this.options.deferRequestBy > 0) {
        // Defer lookup in case when value changes very quickly:
        this.onChangeInterval = setInterval((function() {
          this.onValueChange();
        }).bind(this), this.options.deferRequestBy);
      } else {
        this.onValueChange();
      }
    }
  },

  onValueChange: function() {
		
    clearInterval(this.onChangeInterval);
    this.currentValue = this.el.value;
    this.selectedIndex = -1;
    if (this.ignoreValueChange) {
      this.ignoreValueChange = false;
      return;
    }
    if (this.currentValue === '' || this.currentValue.length < this.options.minChars) {
      	this.qr.hide();
        this.formWrapEl.removeClassName("quickSearchActive");
		$('viewAll').hide();
		$(this.fieldsEl).className = "";
		this.hide();
    } else {
      this.getSuggestions();
    }
  },

  getSuggestions: function() {
 
 	this.qr.hide();	
    this.formWrapEl.removeClassName("quickSearchActive");
	$('viewAll').hide();
	if((!this.hasSearch) || (this.el.value == '')){
		$(this.fieldsEl).className = '';
	}
	
	if(this.options.staticSearch){
		this.serviceUrl = this.options.serviceUrl+this.currentValue+'.xml';
	}
	var cr = this.cachedResponse[this.currentValue];
    if (cr && Object.isArray(cr.suggestions)) {
	  this.hasSearch = true;
      this.suggestions = cr.suggestions;
      this.data = cr.data;
      this.suggest();
    } else if (!this.isBadQuery(this.currentValue)) {
		new Ajax.Request(this.serviceUrl, {
        parameters: { query: this.currentValue },
		onCreate: this.loading(),
		onComplete: this.processResponse.bind(this),
        method: 'get'
      });
    }
  },
  loading: function(){

	$(this.submitEl).addClassName('searching');
  },
  isBadQuery: function(q) {
    var i = this.badQueries.length;
    $(this.fieldsEl).className = "";
    while (i--) {
      if (q.indexOf(this.badQueries[i]) === 0) { return true; }
    }
    return false;
  },

  hide: function() {
  //console.log("hide()....");
    this.enabled = false;
    this.selectedIndex = -1;
    this.container.hide();
  },

  suggest: function() { 
	this.hasSearch = true;

 if (this.results.length === 0) {
        //console.log("zero results length");
      this.hide();
      return;
    }
    //console.log("suggest(): handling results...");
    var content = [];
	var cats = 	this.categories['category'];
	var resultArray = this.results['result'];
	for(var i=0; i<cats.length; i++){
        var catClass = (i == 0) ? "quickSearchCategory topCat" : "quickSearchCategory";
		content.push('<div id="category_'+ cats[i]["@id"] +'" class="'+catClass+'"><h4>', cats[i]["name"], '</h4><div class="quickSearchResults"></div></div>');
	}
    this.enabled = true;

    this.container.update(content.join(''));
	for(var i=0; i<resultArray.length; i++){
        var div = new Element('div',{ className: 'item' });
		var parentId = 'category_' + resultArray[i]["@category_id"];
	    div.update('<h5 id='+resultArray[i]["relevance"]+'><a href="'+resultArray[i]["url"]+'" title="'+resultArray[i]["title"]+'">'+ resultArray[i]["title"] +'</a></h5>');
	 	$(parentId).down('div.quickSearchResults').appendChild(div);
	}
    //console.log("showing quick search container...");
	//$('searchH3').hide();
	//$('resultH3').show();

    $(this.fieldsEl).className = "active hasResults";

	Event.observe($('viewAll'), 'click',  
		function(){
			Autocomplete.prototype.globalSearch($('search').value);
			return false;
	});
	$('viewAll').show();
	this.container.show();
	this.qr.show();
    this.formWrapEl.addClassName("quickSearchActive");
	$(this.submitEl).removeClassName('searching');
	
  },

  processResponse: function(xhr) {

	var response;
   	try {
     response = fleegix.xml.parse(xhr.responseXML);
    } catch (err) { /*console.log("XHR response error \n",err);*/return; }

    //console.log("have response parsed %o",response);
	this.query = response["data"]["query"];

	this.categories = response["data"]["categories"];
	this.results = response["data"]["results"];
    this.cachedResponse[response["data"]["query"]] = response;
	if (response["data"]["results"].length === 0) { this.badQueries.push(response["data"]["query"]); }
	if (response["data"]["query"].toLowerCase() === this.currentValue.toLowerCase()) { this.suggest(); }

  },

  activate: function(index) {
    var divs = this.container.childNodes;
    var activeItem;
    // Clear previous selection:
    if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
      divs[this.selectedIndex].className = '';
    }
    this.selectedIndex = index;
    if (this.selectedIndex !== -1 && divs.length > this.selectedIndex) {
      activeItem = divs[this.selectedIndex]
      activeItem.className = 'selected';
    }
    return activeItem;
  },

  deactivate: function(div, index) {
    div.className = '';
    if (this.selectedIndex === index) { this.selectedIndex = -1; }
  },

  select: function(i) {
    var selectedValue = this.suggestions[i];
    if (selectedValue) {
      this.el.value = selectedValue;
      if (this.options.autoSubmit && this.el.form) {
        this.el.form.submit();
      }
      this.ignoreValueChange = true;
      this.hide();
      this.onSelect(i);
    }
  },

  moveUp: function() {
    if (this.selectedIndex === -1) { return; }
    if (this.selectedIndex === 0) {
      this.container.childNodes[0].className = '';
      this.selectedIndex = -1;
      this.el.value = this.currentValue;
      return;
    }
    this.adjustScroll(this.selectedIndex - 1);
  },

  moveDown: function() {
    if (this.selectedIndex === (this.suggestions.length - 1)) { return; }
    this.adjustScroll(this.selectedIndex + 1);
  },

  adjustScroll: function(i) {
    var container = this.container;
    var activeItem = this.activate(i);
    var offsetTop = activeItem.offsetTop;
    var upperBound = container.scrollTop;
    var lowerBound = upperBound + this.options.maxHeight - 25;
    if (offsetTop < upperBound) {
      container.scrollTop = offsetTop;
    } else if (offsetTop > lowerBound) {
      container.scrollTop = offsetTop - this.options.maxHeight + 25;
    }
    this.el.value = this.suggestions[i];
  },

  onSelect: function(i) {
    (this.options.onSelect || Prototype.emptyFunction)(this.suggestions[i], this.data[i]);
  },
  globalSearch: function(thisEl){

	var recentTerms = this.readCookie('recentSearchCookie');
	var currentSearch;	
	var newTerm;

	if(thisEl.tagName == 'FORM'){
		currentSearch = $('search').value.trim(); 
	}else{
		currentSearch = thisEl;
	}

	if((currentSearch == '')||(currentSearch.toLowerCase() == 'search')){return false;}
	if(!recentTerms){
		newTerm = currentSearch;
	}
	else{
	    var	termArray = recentTerms.split(':');
		var count = 0;
		newTerm = currentSearch;
		for(var i=0; i<termArray.length; i++){
			if (currentSearch.toLowerCase() != termArray[i].toLowerCase() ){
				newTerm = newTerm + ':'+ termArray[i];
				count++;
			}
			if(count == 4){break;}
		}

	}


	this.createCookie('recentSearchCookie', newTerm, '')
	window.location = globalResultsPage+'?'+currentSearch;
},

createCookie: function (name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
},

readCookie: function (name) {

	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;
},

eraseCookie: function (name) {
	createCookie(name,"",-1);
}


};

//Event.observe(document, 'dom:loaded', function(){ Autocomplete.isDomLoaded = true; }, false);

$(document).observe("dom:loaded",function(){
    Autocomplete.isDomLoaded = true; 
    new Autocomplete('search_input', { 
        serviceUrl:'../../_xml/test/quickSearch', 
        resultsPage:'../../SiteSearch/searchresults/index.html', 
        minChars:1, 
        staticSearch:true 
    });
});


/* fleegix XML plugin 
 * http://js.fleegix.org/plugins/xml 
 * 2009-04-13
 * 
 * Copyright 2009 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
/* Dk-patched fleegix XML module: add support for element attributes */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('5(z A==\'B\'){2 A={}}A.C=v q(){2 o=/^[\\s\\n\\r\\t]+|[\\s\\n\\r\\t]+$/g;2 p=q(a,b){5(a){2 r=w;5(a S T==J){r=[];r.K(a)}6{r=a}r.K(b);9 r}6{9 b}};7.L=q(a,b){2 c=[];2 d={};x(2 i=0,j=a.u;i<j;i++){5(a[i].D){2 e=a[i].U;d[e]=a[i].D}}x(2 f V d){2 g="@"+f;2 h=d[f];2 k;2 l=b.u;5(l){2 m=l-1;2 n=b;k=n[m];k[g]=h}6{k=b;k[g]=h}}};7.E=q(a,b){2 c={};2 d=[];2 k;2 e;2 t;2 f;5(b){d=a.M(b)}6{d=a.F}x(2 i=0;i<d.u;i++){k=d[i];5(k.y==1){e=k.N;5(k.G){5(k.F.u==1){t=k.G.y;5(t==3||t==4||t==8){f=k.G.D.W(o,\'\');c[e]=p(c[e],f)}6 5(t==1){2 g=p(c[e],7.E(k));2 h=7.H(k);c[e]=(h==1)?[g]:g}}6{2 g=p(c[e],7.E(k));2 h=7.H(k);c[e]=(h==1)?[g]:g}}6{c[e]=p(c[e],w)}7.L(k.X,c[e])}}9 c};7.H=q(a){2 b=0;5(a.O.N){2 c=a.O.F;x(2 m=0,n=c.u;m<n;m++){5(c[m].y){2 d=c[m].y;5(!(d==3||d==4||d==8)){b++}}}}9 b};7.Y=q(a){5(z P!="B"){9(v P()).Z(a,"10/C")}6 5(z Q!="B"){2 b=11.12();b.R(a);9 b}6{2 c="13:14/C;15=16-8,"+17(a);2 d=v 18();d.19("1a",c,J);d.1b(w);9 d.1c}};7.1d=q(a,b){2 c=[];2 d=w;5(I.1e){2 e=I.1f(a).1g;d=v Q("1h.1i");d.R(e);d=d.1j}6{c=1k.I.1l.M(b);d=c[0]}9 d}};',62,84,'||var|||if|else|this||return|||||||||||||||||function||||length|new|null|for|nodeType|typeof|fleegix|undefined|xml|nodeValue|parse|childNodes|firstChild|getCountNodesThisLevel|document|false|push|doAttributes|getElementsByTagName|tagName|parentNode|DOMParser|ActiveXObject|loadXML|instanceof|Array|nodeName|in|replace|attributes|createDoc|parseFromString|application|XML|newDocument|data|text|charset|utf|encodeURIComponent|XMLHttpRequest|open|GET|send|responseXML|getXMLDoc|all|getElementById|innerHTML|Microsoft|XMLDOM|documentElement|window|body'.split('|'),0,{}))

/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

var swfobject = function() {
	
	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",
		EXPRESS_INSTALL_ID = "SWFObjectExprInst",
		
		win = window,
		doc = document,
		nav = navigator,
		
		domLoadFnArr = [],
		regObjArr = [],
		objIdArr = [],
		listenersArr = [],
		script,
		timer = null,
		storedAltContent = null,
		storedAltContentId = null,
		isDomLoaded = false,
		isExpressInstallActive = false;
	
	/* Centralized function for browser feature detection
		- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
		- User agent string detection is only used when no alternative is possible
		- Is executed directly for optimal performance
	*/	
	var ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try { 
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";	 // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");	// Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	}();

	/* Cross-browser onDomLoad
		- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
		- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
	*/ 
	var onDomLoad = function() {
		if (!ua.w3cdom) {
			return;
		}
		addDomLoadEvent(main);
		if (ua.ie && ua.win) {
			try {	 // Avoid a possible Operation Aborted error
				doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors 
				script = getElementById("__ie_ondomload");
				if (script) {
					addListener(script, "onreadystatechange", checkReadyState);
				}
			}
			catch(e) {}
		}
		if (ua.webkit && typeof doc.readyState != UNDEF) {
			timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
		}
		if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
		}
		addLoadEvent(callDomLoadFunctions);
	}();
	
	function checkReadyState() {
		if (script.readyState == "complete") {
			script.parentNode.removeChild(script);
			callDomLoadFunctions();
		}
	}
	
	function callDomLoadFunctions() {
		if (isDomLoaded) {
			return;
		}
		if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
			var s = createElement("span");
			try { // Avoid a possible Operation Aborted error
				var t = doc.getElementsByTagName("body")[0].appendChild(s);
				t.parentNode.removeChild(t);
			}
			catch (e) {
				return;
			}
		}
		isDomLoaded = true;
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		var dl = domLoadFnArr.length;
		for (var i = 0; i < dl; i++) {
			domLoadFnArr[i]();
		}
	}
	
	function addDomLoadEvent(fn) {
		if (isDomLoaded) {
			fn();
		}
		else { 
			domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
		}
	}
	
	/* Cross-browser onload
		- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
		- Will fire an event as soon as a web page including all of its assets are loaded 
	 */
	function addLoadEvent(fn) {
		if (typeof win.addEventListener != UNDEF) {
			win.addEventListener("load", fn, false);
		}
		else if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("load", fn, false);
		}
		else if (typeof win.attachEvent != UNDEF) {
			addListener(win, "onload", fn);
		}
		else if (typeof win.onload == "function") {
			var fnOld = win.onload;
			win.onload = function() {
				fnOld();
				fn();
			};
		}
		else {
			win.onload = fn;
		}
	}
	
	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() { // Static publishing only
		var rl = regObjArr.length;
		for (var i = 0; i < rl; i++) { // For each registered object element
			var id = regObjArr[i].id;
			if (ua.pv[0] > 0) {
				var obj = getElementById(id);
				if (obj) {
					regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
					regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
					if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
						if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
							fixParams(obj);
						}
						setVisibility(id, true);
					}
					else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
						showExpressInstall(regObjArr[i]);
					}
					else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
						displayAltContent(obj);
					}
				}
			}
			else {	// If no fp is installed, we let the object element do its job (show alternative content)
				setVisibility(id, true);
			}
		}
	}
	
	/* Fix nested param elements, which are ignored by older webkit engines
		- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
		- Fall back to the proprietary embed element
	*/
	function fixParams(obj) {
		var nestedObj = obj.getElementsByTagName(OBJECT)[0];
		if (nestedObj) {
			var e = createElement("embed"), a = nestedObj.attributes;
			if (a) {
				var al = a.length;
				for (var i = 0; i < al; i++) {
					if (a[i].nodeName == "DATA") {
						e.setAttribute("src", a[i].nodeValue);
					}
					else {
						e.setAttribute(a[i].nodeName, a[i].nodeValue);
					}
				}
			}
			var c = nestedObj.childNodes;
			if (c) {
				var cl = c.length;
				for (var j = 0; j < cl; j++) {
					if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
						e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
					}
				}
			}
			obj.parentNode.replaceChild(e, obj);
		}
	}
	
	/* Show the Adobe Express Install dialog
		- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
	*/
	function showExpressInstall(regObj) {
		isExpressInstallActive = true;
		var obj = getElementById(regObj.id);
		if (obj) {
			if (regObj.altContentId) {
				var ac = getElementById(regObj.altContentId);
				if (ac) {
					storedAltContent = ac;
					storedAltContentId = regObj.altContentId;
				}
			}
			else {
				storedAltContent = abstractAltContent(obj);
			}
			if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
				regObj.width = "310";
			}
			if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
				regObj.height = "137";
			}
			doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
			var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
				dt = doc.title,
				fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
				replaceId = regObj.id;
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			if (ua.ie && ua.win && obj.readyState != 4) {
				var newObj = createElement("div");
				replaceId += "SWFObjectNew";
				newObj.setAttribute("id", replaceId);
				obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
				obj.style.display = "none";
				var fn = function() {
					obj.parentNode.removeChild(obj);
				};
				addListener(win, "onload", fn);
			}
			createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
		}
	}
	
	/* Functions to abstract and display alternative content
	*/
	function displayAltContent(obj) {
		if (ua.ie && ua.win && obj.readyState != 4) {
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			var el = createElement("div");
			obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
			el.parentNode.replaceChild(abstractAltContent(obj), el);
			obj.style.display = "none";
			var fn = function() {
				obj.parentNode.removeChild(obj);
			};
			addListener(win, "onload", fn);
		}
		else {
			obj.parentNode.replaceChild(abstractAltContent(obj), obj);
		}
	} 

	function abstractAltContent(obj) {
		var ac = createElement("div");
		if (ua.win && ua.ie) {
			ac.innerHTML = obj.innerHTML;
		}
		else {
			var nestedObj = obj.getElementsByTagName(OBJECT)[0];
			if (nestedObj) {
				var c = nestedObj.childNodes;
				if (c) {
					var cl = c.length;
					for (var i = 0; i < cl; i++) {
						if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
							ac.appendChild(c[i].cloneNode(true));
						}
					}
				}
			}
		}
		return ac;
	}
	
	/* Cross-browser dynamic SWF creation
	*/
	function createSWF(attObj, parObj, id) {
		var r, el = getElementById(id);
		if (el) {
			if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
				attObj.id = id;
			}
			if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
				var att = "";
				for (var i in attObj) {
					if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
						if (i.toLowerCase() == "data") {
							parObj.movie = attObj[i];
						}
						else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							att += ' class="' + attObj[i] + '"';
						}
						else if (i.toLowerCase() != "classid") {
							att += ' ' + i + '="' + attObj[i] + '"';
						}
					}
				}
				var par = "";
				for (var j in parObj) {
					if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
						par += '<param name="' + j + '" value="' + parObj[j] + '" />';
					}
				}
				el.outerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
				objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
				r = getElementById(attObj.id);	
			}
			else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
				var e = createElement("embed");
				e.setAttribute("type", FLASH_MIME_TYPE);
				for (var k in attObj) {
					if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
						if (k.toLowerCase() == "data") {
							e.setAttribute("src", attObj[k]);
						}
						else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							e.setAttribute("class", attObj[k]);
						}
						else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
							e.setAttribute(k, attObj[k]);
						}
					}
				}
				for (var l in parObj) {
					if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
						if (l.toLowerCase() != "movie") { // Filter out IE specific param element
							e.setAttribute(l, parObj[l]);
						}
					}
				}
				el.parentNode.replaceChild(e, el);
				r = e;
			}
			else { // Well-behaving browsers
				var o = createElement(OBJECT);
				o.setAttribute("type", FLASH_MIME_TYPE);
				for (var m in attObj) {
					if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
						if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							o.setAttribute("class", attObj[m]);
						}
						else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
							o.setAttribute(m, attObj[m]);
						}
					}
				}
				for (var n in parObj) {
					if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
						createObjParam(o, n, parObj[n]);
					}
				}
				el.parentNode.replaceChild(o, el);
				r = o;
			}
		}
		return r;
	}
	
	function createObjParam(el, pName, pValue) {
		var p = createElement("param");
		p.setAttribute("name", pName);	
		p.setAttribute("value", pValue);
		el.appendChild(p);
	}
	
	/* Cross-browser SWF removal
		- Especially needed to safely and completely remove a SWF in Internet Explorer
	*/
	function removeSWF(id) {
		var obj = getElementById(id);
		if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
			if (ua.ie && ua.win) {
				if (obj.readyState == 4) {
					removeObjectInIE(id);
				}
				else {
					win.attachEvent("onload", function() {
						removeObjectInIE(id);
					});
				}
			}
			else {
				obj.parentNode.removeChild(obj);
			}
		}
	}
	
	function removeObjectInIE(id) {
		var obj = getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}
	}
	
	/* Functions to optimize JavaScript compression
	*/
	function getElementById(id) {
		var el = null;
		try {
			el = doc.getElementById(id);
		}
		catch (e) {}
		return el;
	}
	
	function createElement(el) {
		return doc.createElement(el);
	}
	
	/* Updated attachEvent function for Internet Explorer
		- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
	*/	
	function addListener(target, eventType, fn) {
		target.attachEvent(eventType, fn);
		listenersArr[listenersArr.length] = [target, eventType, fn];
	}
	
	/* Flash Player and SWF content version matching
	*/
	function hasPlayerVersion(rv) {
		var pv = ua.pv, v = rv.split(".");
		v[0] = parseInt(v[0], 10);
		v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
		v[2] = parseInt(v[2], 10) || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	}
	
	/* Cross-browser dynamic CSS creation
		- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
	*/	
	function createCSS(sel, decl) {
		if (ua.ie && ua.mac) {
			return;
		}
		var h = doc.getElementsByTagName("head")[0], s = createElement("style");
		s.setAttribute("type", "text/css");
		s.setAttribute("media", "screen");
		if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
			s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
		}
		h.appendChild(s);
		if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
			var ls = doc.styleSheets[doc.styleSheets.length - 1];
			if (typeof ls.addRule == OBJECT) {
				ls.addRule(sel, decl);
			}
		}
	}
	
	function setVisibility(id, isVisible) {
		var v = isVisible ? "visible" : "hidden";
		if (isDomLoaded && getElementById(id)) {
			getElementById(id).style.visibility = v;
		}
		else {
			createCSS("#" + id, "visibility:" + v);
		}
	}

	/* Filter to avoid XSS attacks 
	*/
	function urlEncodeIfNecessary(s) {
		var regex = /[\\\"<>\.;]/;
		var hasBadChars = regex.exec(s) != null;
		return hasBadChars ? encodeURIComponent(s) : s;
	}
	
	/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
	*/
	var cleanup = function() {
		if (ua.ie && ua.win) {
			window.attachEvent("onunload", function() {
				// remove listeners to avoid memory leaks
				var ll = listenersArr.length;
				for (var i = 0; i < ll; i++) {
					listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
				}
				// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
				var il = objIdArr.length;
				for (var j = 0; j < il; j++) {
					removeSWF(objIdArr[j]);
				}
				// cleanup library's main closures to avoid memory leaks
				for (var k in ua) {
					ua[k] = null;
				}
				ua = null;
				for (var l in swfobject) {
					swfobject[l] = null;
				}
				swfobject = null;
			});
		}
	}();
	
	
	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
		*/ 
		registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
			if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
				return;
			}
			var regObj = {};
			regObj.id = objectIdStr;
			regObj.swfVersion = swfVersionStr;
			regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
			regObjArr[regObjArr.length] = regObj;
			setVisibility(objectIdStr, false);
		},
		
		getObjectById: function(objectIdStr) {
			var r = null;
			if (ua.w3cdom) {
				var o = getElementById(objectIdStr);
				if (o) {
					var n = o.getElementsByTagName(OBJECT)[0];
					if (!n || (n && typeof o.SetVariable != UNDEF)) {
							r = o;
					}
					else if (typeof n.SetVariable != UNDEF) {
						r = n;
					}
				}
			}
			return r;
		},
		
		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
			if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
				return;
			}
			widthStr += ""; // Auto-convert to string
			heightStr += "";
			if (hasPlayerVersion(swfVersionStr)) {
				setVisibility(replaceElemIdStr, false);
				var att = {};
				if (attObj && typeof attObj === OBJECT) {
					for (var i in attObj) {
						if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
							att[i] = attObj[i];
						}
					}
				}
				att.data = swfUrlStr;
				att.width = widthStr;
				att.height = heightStr;
				var par = {}; 
				if (parObj && typeof parObj === OBJECT) {
					for (var j in parObj) {
						if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
							par[j] = parObj[j];
						}
					}
				}
				if (flashvarsObj && typeof flashvarsObj === OBJECT) {
					for (var k in flashvarsObj) {
						if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
							if (typeof par.flashvars != UNDEF) {
								par.flashvars += "&" + k + "=" + flashvarsObj[k];
							}
							else {
								par.flashvars = k + "=" + flashvarsObj[k];
							}
						}
					}
				}
				addDomLoadEvent(function() {
					createSWF(att, par, replaceElemIdStr);
					if (att.id == replaceElemIdStr) {
						setVisibility(replaceElemIdStr, true);
					}
				});
			}
			else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
				isExpressInstallActive = true; // deferred execution
				setVisibility(replaceElemIdStr, false);
				addDomLoadEvent(function() {
					var regObj = {};
					regObj.id = regObj.altContentId = replaceElemIdStr;
					regObj.width = widthStr;
					regObj.height = heightStr;
					regObj.expressInstall = xiSwfUrlStr;
					showExpressInstall(regObj);
				});
			}
		},
		
		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},
		
		hasFlashPlayerVersion: hasPlayerVersion,
		
		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3cdom) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},
		
		removeSWF: function(objElemIdStr) {
			if (ua.w3cdom) {
				removeSWF(objElemIdStr);
			}
		},
		
		createCSS: function(sel, decl) {
			if (ua.w3cdom) {
				createCSS(sel, decl);
			}
		},
		
		addDomLoadEvent: addDomLoadEvent,
		
		addLoadEvent: addLoadEvent,
		
		getQueryParamValue: function(param) {
			var q = doc.location.search || doc.location.hash;
			if (param == null) {
				return urlEncodeIfNecessary(q);
			}
			if (q) {
				var pairs = q.substring(1).split("&");
				for (var i = 0; i < pairs.length; i++) {
					if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
						return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
					}
				}
			}
			return "";
		},
		
		// For internal usage only
		expressInstallCallback: function() {
			if (isExpressInstallActive && storedAltContent) {
				var obj = getElementById(EXPRESS_INSTALL_ID);
				if (obj) {
					obj.parentNode.replaceChild(storedAltContent, obj);
					if (storedAltContentId) {
						setVisibility(storedAltContentId, true);
						if (ua.ie && ua.win) {
							storedAltContent.style.display = "block";
						}
					}
					storedAltContent = null;
					storedAltContentId = null;
					isExpressInstallActive = false;
				}
			} 
		}
	};
}();

/**
	Protofade 1.2 18/09/09
	Copyright (c) 2009 Filippo Buratti; info [at] cssrevolt.com [dot] com; http://www.filippoburatti.net/

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

var Protofade = Class.create({

	initialize: function(element, options) {		
		this.options = {
      		duration: 1,
			delay: 4.0,
			randomize: false,
			autostart:true,
			controls:false,
			eSquare:false,
			eRows: 3, 
			eCols: 5,
			eColor: '#FFFFFF'
    	}
		Object.extend(this.options, options || {});

    	this.element        = $(element);
		this.slides			= this.element.childElements();
		this.num_slides		= this.slides.length;		
		this.current_slide 	= (this.options.randomize) ? (Math.floor(Math.random()*this.num_slides)) : 0;
		this.end_slide		= this.num_slides - 1;
		
		this.slides.invoke('hide');
		this.slides[this.current_slide].show();
				
		if (this.options.autostart) { 
			this.startSlideshow();
		}				
		if (this.options.controls) {
			this.addControls();
		}
		if (this.options.eSquare) {
			this.buildEsquare();
		}
	},
	
	addControls: function() {
		this.wrapper 		= this.element.up();
		this.controls		= new Element('div', { 'class': 'controls' });
		this.wrapper.insert(this.controls);
		
		this.btn_next 		= new Element('a', { 'class': 'next', 'title': 'Next', href: '#' }).update('Next');
		this.btn_previous	= new Element('a', { 'class': 'previous', 'title': 'Previous', href: '#' }).update('Previous');
		this.btn_start		= new Element('a', { 'class': 'start', 'title': 'Start', href: '#' }).update('Start');
		this.btn_stop		= new Element('a', { 'class': 'stop', 'title': 'Stop', href: '#' }).update('Stop');
		
		this.btns = [this.btn_previous, this.btn_next, this.btn_start, this.btn_stop];
		this.btns.each(function(el){
			this.controls.insert(el);
		}.bind(this));
		
		this.btn_previous.observe('click', this.moveToPrevious.bindAsEventListener(this));
		this.btn_next.observe('click', this.moveToNext.bindAsEventListener(this));
		this.btn_start.observe('click', this.startSlideshow.bindAsEventListener(this));
		this.btn_stop.observe('click', this.stopSlideshow.bindAsEventListener(this));
	},
	
	buildEsquare: function() {		
		this.eSquares 	= [];
		var elDimension	 	= this.element.getDimensions();
		var elWidth  		= elDimension.width;
		var elHeight 		= elDimension.height;
				
		var sqWidth 		= elWidth / this.options.eCols;
		var sqHeight 		= elHeight / this.options.eRows;
	
		$R(0, this.options.eCols-1).each(function(col) {
			this.eSquares[col] = [];							 	
			$R(0, this.options.eRows-1).each(function(row) {
				var sqLeft = col * sqWidth;
			    var sqTop  = row * sqHeight;
				this.eSquares[col][row] = new Element('div').setStyle({
 														    opacity: 0, backgroundColor: this.options.eColor,
															position: 'absolute', 'z-index': 5,
															left: sqLeft + 'px', top: sqTop + 'px',
															width: sqWidth + 'px', height: sqHeight + 'px'		
														});
				this.element.insert(this.eSquares[col][row]);				 							 										 
			}.bind(this))
		}.bind(this));			
	},

	startSlideshow: function(event) {
		if (event) { Event.stop(event); }
		if (!this.running)	{
			this.executer = new PeriodicalExecuter(function(){
	  			this.updateSlide(this.current_slide+1);
	 		}.bind(this),this.options.delay);
			this.running=true;
		}
	},
	
	stopSlideshow: function(event) {	
		if (event) { Event.stop(event); } 
		if (this.executer) { 
			this.executer.stop();
			this.running=false;
		}	 
	},

	moveToPrevious: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide-1);
	},

	moveToNext: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide+1);
	},
	
	updateSlide: function(next_slide) {		
		if (next_slide > this.end_slide) { 
			next_slide = 0; 
		} 
		else if ( next_slide == -1 ) {
			next_slide = this.end_slide;
		}	
		this.fadeInOut(next_slide, this.current_slide);		
	},

 	fadeInOut: function (next, current) {		
		new Effect.Parallel([
			new Effect.Fade(this.slides[current], { sync: true }),
			new Effect.Appear(this.slides[next], { sync: true }) 
  		], { duration: this.options.duration });
		
		if (this.options.eSquare) {			
			$R(0, this.options.eCols-1).each(function(col) {	 						 	
				$R(0, this.options.eRows-1).each(function(row) {
					var eSquare = this.eSquares[col][row];
					var delay = Math.random() * 150;				
					setTimeout(this.delayedAppear.bind(this, eSquare), delay);
				}.bind(this))
			}.bind(this));	
		}
		
		this.current_slide = next;		
	},
	
	delayedAppear: function(eSquare)	{
		var opacity = Math.random();
		new Effect.Parallel([ 
			new Effect.Appear ( eSquare, { from: 0, to: opacity, duration: this.options.duration/4 } ),
			new Effect.Appear ( eSquare, { from: opacity, to: 0, duration: this.options.duration/1.25} )
		], { sync: false });			
	}
});

/*
	A Subclass of Victor Stanciu's Prototype.Carousel Class
*/

var PhotoSlideshow = Class.create(Carousel, {
	initialize: function($super, el) {
		/* Identify each of the required elements */
		var photoCarousel = $(el)
		if (photoCarousel) var photoCarouselWrapper = $(photoCarousel.down('div.carousel-wrapper'));
		if (photoCarouselWrapper) var photoCarouselContent = $(photoCarouselWrapper.down('div.carousel-content'));
		if (photoCarouselContent) var photoCarouselSlides = $(photoCarouselContent.select('div.slide'));
		if (photoCarouselSlides) var photoCarouselSlidesLength = photoCarouselSlides.length;
		
		/* Create a wrapper for the caption */
		var photoCarouselCaptionStr = '';
		photoCarouselCaptionStr += '<div class="carousel-caption">';
		photoCarouselCaptionStr += 
		photoCarouselCaptionStr += '</div>';
		photoCarousel.insert(photoCarouselCaptionStr);
		
		
		/* Create a wrapper for all the triggers */
		var photoCarouselTriggersStr = '';
		photoCarouselTriggersStr += '<div class="carousel-triggers">';
		
		/* Create previous/next anchors */
		photoCarouselTriggersStr += '<ul class="carousel-controls">';
		photoCarouselTriggersStr += '<li class="carousel-control-prev"><a href="#" class="carousel-control" rel="prev">previous</a></li>';
		photoCarouselTriggersStr += '<li class="carousel-control-next"><a href="#" class="carousel-control" rel="next">next</a></li>';
		photoCarouselTriggersStr += '</ul>';
		
		/* Loop through all the slide elements, and create jumper anchors for each */
		photoCarouselTriggersStr += '<div class="carousel-jumpers"><ul>';
		for (var i=0; i < photoCarouselSlidesLength; i++) {
			var slideIndex = i + 1;
			var slideId = Element.identify(photoCarouselSlides[i]);
			photoCarouselTriggersStr += '<li><a href="#" class="carousel-jumper" rel="' + slideId + '">' + slideIndex + '</a></li>';
		}
		photoCarouselTriggersStr += '</ul></div>';
		
		/* Create the ellipses overflow indicators */
		photoCarouselTriggersStr += '<ul class="carousel-overflow"><li class="carousel-overflow-before"><a>&hellip;</a></li><li class="carousel-overflow-after"><a>&hellip;</a></li></ul>';
		
		photoCarouselTriggersStr += '</div>';
		photoCarousel.insert(photoCarouselTriggersStr);
		
		var photoCarouselTriggers = $(photoCarousel.select('a.carousel-control', 'a.carousel-jumper'));
		
		if (photoCarouselSlides && photoCarouselTriggers) {
			photoCarousel.addClassName('JS-carousel');
			$super(photoCarouselWrapper, photoCarouselSlides, photoCarouselTriggers, {
				'duration': 0.1,
				'circular': true,
				'effect': 'fade',
				'wheel': false,
				'beforeMove': this.before.bindAsEventListener(this),
				'afterMove': this.after.bindAsEventListener(this)
			})
			if (!this.current) {
				this.current = this.slides[0];
				this.after();
			}
		}
	},
	before: function() {
		this.controls.invoke('removeClassName', this.options.selectedClassName);
	},
	after: function() {
		var photoCarouselCaption = this.current.up('.photo-carousel').down('.carousel-caption');
		var photoCarouselCaptionStr = this.current.down('img').title ? this.current.down('img').title : '';
		var photoCarouselCurrentJumper = $$('a[rel="' + this.current.id + '"]')[0];
		var photoCarouselJumpersParent = photoCarouselCurrentJumper.up('ul');
		var photoCarouselJumpers = photoCarouselJumpersParent.childElements();
		var photoCarouselJumperWidth = photoCarouselJumpers[0].getWidth();
		var photoCarouselJumpersWidth = photoCarouselJumperWidth * photoCarouselJumpers.length;
		var photoCarouselJumperWrapper = photoCarouselCurrentJumper.up('.carousel-jumpers');
		var photoCarouselJumperWrapperWidth = photoCarouselJumperWrapper.getWidth();
		
		photoCarouselCaption.innerHTML = '<p>' + photoCarouselCaptionStr + '</p>';
		
		/* First, set the width of the ul element */
		photoCarouselJumpersParent.setStyle({'position': 'absolute', 'width': photoCarouselJumpersWidth + 'px'});
		
		/* If the items don't fill the space, re-center them */
		if (photoCarouselJumpersWidth <= photoCarouselJumperWrapperWidth) {
			photoCarouselJumpersParent.setStyle({'left': (photoCarouselJumperWrapperWidth - photoCarouselJumpersWidth)/2 + 'px'});
			photoCarouselJumperWrapper.up().select('.carousel-overflow li').invoke('hide');
		}
		/* If the items are bigger than the space, check the current id and determine the correct position */
		else {
			var photoCarouselMidPoint = ((photoCarouselJumperWrapperWidth - photoCarouselCurrentJumper.getWidth()) / 2);

			if (photoCarouselCurrentJumper.positionedOffset().left > photoCarouselMidPoint) {
				
				if (-(photoCarouselCurrentJumper.positionedOffset().left - photoCarouselMidPoint) <= photoCarouselJumperWrapperWidth - photoCarouselJumpersParent.getWidth()) {
					photoCarouselJumpersParent.setStyle({'left': photoCarouselJumperWrapperWidth - photoCarouselJumpersParent.getWidth() + 'px'});
					photoCarouselJumperWrapper.up().select('.carousel-overflow-before').invoke('show');
					photoCarouselJumperWrapper.up().select('.carousel-overflow-after').invoke('hide');
				}
				else {
					photoCarouselJumpersParent.setStyle({'left': -(photoCarouselCurrentJumper.positionedOffset().left - photoCarouselMidPoint) + 'px'});
					photoCarouselJumperWrapper.up().select('.carousel-overflow-before').invoke('show');
					photoCarouselJumperWrapper.up().select('.carousel-overflow-after').invoke('show');
				}
			}
			else {
				photoCarouselJumpersParent.setStyle({'left': 0});
				photoCarouselJumperWrapper.up().select('.carousel-overflow-before').invoke('hide');
				photoCarouselJumperWrapper.up().select('.carousel-overflow-after').invoke('show');
			}
		}
		
		this.controls.each(function (el) {if (el.rel == this.current.id) el.addClassName(this.options.selectedClassName)}, this);
	}
});

document.observe('dom:loaded', function() {
	$$('div.photo-carousel').each(function(el) {
		new PhotoSlideshow(el);
	});
});

document.observe('dom:loaded', function() {
	$$('.filterButton input')
		.invoke('observe', 'mouseover', function(e) {
			Event.element(e).src='/stylesheets/images/default/btn-filter-on.png';
		})
		.invoke('observe', 'mouseout', function(e) {
			Event.element(e).src='/stylesheets/images/default/btn-filter.png';
		});
});
