
function simpleSearchSettings( form ) {
	var foundLeg = 0;
	for ( var i = 0; i < form.srchWhere.length; i++){
		if (form.srchWhere[i].checked) {
			if ( form.srchWhere[i].value == "Legislation") {
				foundLeg = 1;
				break;
			}
		}
	}
	form.p.value = (foundLeg) ? "legislation_search" : "search";
	return true;
}
function gsaFilter ( form ) {
	var daterange = form.daterange[ form.daterange.selectedIndex ].value;
	form.q.value = form.qMask.value + ( (daterange != "") ? " "+daterange : "");
	return true;
}
function setNewsroomSearchFilter (form) {
	form.p.value = "newsroom_search";
	return true;
}
function setLegislationSearchFilter (form) {
	form.p.value = "legislation_search";
	form.q.value = form.qMask.value;
	return true;
}
function addScript ( url ){
	var headID = document.getElementsByTagName("head")[0]; 

	// Add new JSONP scripts
	var newScript = document.createElement('script');
	newScript.type = 'text/javascript';
	newScript.src = url;
	newScript.className = "jsonp";
	headID.appendChild(newScript);
}
function deleteChildNodes ( el ) {
	// remove any event listeners
	YAHOO.util.Event.purgeElement(el, true);
	while ( el.hasChildNodes() ) 
		el.removeChild( el.lastChild );     
}
function displayThomasResults ( arr ) { 	
	_THOMAS_.set({ root: document.getElementById("thomas_results"), results: arr });
	_THOMAS_.displayPreloader();
	_THOMAS_.displayResults();
}

function thomas(id) {
	this.root = (document.getElementById(id)) ? document.getElementById(id): null;
	this.results = [];
	this.page = 1;
	this.resultsPerPage = 10;
}
thomas.prototype.displayPreloader =  function() {
	if (this.root.children.length > 0)
		deleteChildNodes(this.root);
	
	var p = document.createElement("p");
	var img = document.createElement("img");
	
	img.src = "/images/preloader.gif";
	
	p.style.textAlign = "center";
	p.appendChild(img)
	
	this.root.appendChild(p);
};
thomas.prototype.set = function(obj) {
	for (o in obj) {
		this[o] = obj[o];
	}
};
thomas.prototype.displayResults = function() {
	var arr = this.results;
	var root = this.root;
	var listPosition = "";

	if (this.root.children.length > 0)
		deleteChildNodes(this.root);
		
	if ( arr.length > 0 ) {
		this.displayHead();
		
		var ul = document.createElement("ul");
		ul.className = "list-summaries";
		
		var start = (this.page - 1) * this.resultsPerPage;
		var end = this.page * this.resultsPerPage;
		
		if ( end > arr.length ) { end = arr.length; }
		
		for (var i = start; i < end; i++) {
			var liBody = "";
			var li = document.createElement("li");
			li.className = "list-item list-item-thomas"
						 +  ( (i == start) ? " list-item-first": ( i == (end-1) ) ? " list-item-last": "");
			
			var h3 = document.createElement("h3");
			h3.innerHTML = "<a href='" + arr[i].legislation_url + "'>" + arr[i].title + " - " + arr[i].summary + "</a>"; 
			
			if (arr[i].last_action != "")
				liBody += "<strong>Latest Action:</strong> " + arr[i].last_action;
			
			if (liBody != "")
				liBody += "<br />";
				
			if (arr[i].last_major_action != "")
				liBody +=  "<strong>Latest Major Action:</strong> " + arr[i].last_major_action; 
			
			var div = document.createElement("div");
			div.className = "summary";
			div.innerHTML = "<p>" + liBody + "</p>";
			
			li.appendChild(h3);
			li.appendChild(div);
			
			ul.appendChild(li);
		}
		root.appendChild(ul);
		
		this.displayFoot();
	} else {
		deleteChildNodes (root);
		root.innerHTML = "<p>No Legislation results found.</p>";
	}
};
thomas.prototype.go = function( inc ) {
	this.page = this.page + inc;
	deleteChildNodes ( this.root );
	this.displayResults();
}

thomas.prototype.displayHead = function() {
	this.displayPager({ cName: "list-paging-top" });
}
thomas.prototype.displayFoot = function() {
	this.displayPager({ cName: "list-paging-bottom" });

}
thomas.prototype.displayPager = function(obj) {
	var arr = this.results;
	var root = this.root;

	var div = document.createElement("div");
	div.className = "list-paging " + obj.cName;
	
	var curStart = ( (this.page - 1) * this.resultsPerPage ) + 1;
	var curEnd = curStart + this.resultsPerPage -1;

	var pPage = "Previous Page";
	var nPage = "Next Page";
	
	if ( curEnd > arr.length) {
		curEnd = arr.length;
	}
	if ( curStart > this.resultsPerPage ) {
		pPage = "<a href='#' onClick='_THOMAS_.go(-1); return false;'>"+pPage+"</a>";
	}
	if ( curEnd < arr.length ) {
		nPage = "<a href='#' onClick='_THOMAS_.go(1); return false;'>"+nPage+"</a>";
	}
	
	div.innerHTML = "<span class='list-count'><strong>Legislation</strong> " + curStart + " - " + curEnd + " of " + arr.length + "</span>"
				  + "<span class='list-nav'><span class='pager'>" + pPage + " | " + nPage +"</span></span>";
				  
	root.appendChild(div);
}

var _THOMAS_ = new thomas("thomas_results");

function
createFacebookShare( o ) {
	var tUn = "MarkUdall";
	var url = escape(o.data.url);
	var loc = location.href + "";
	
	// Facebook Like
	var f = document.createElement("IFRAME");
	
	f.setAttribute("class", "btn-share-fb");
	f.setAttribute("scrolling", "no");
	f.setAttribute("frameborder", "0");
	f.setAttribute("allowTransparency", "true");
	f.setAttribute("width", "300");
	f.setAttribute("height", "21");
	f.setAttribute("src", "http://www.facebook.com/plugins/like.php?href=" + url + "&layout=button_count&show_faces=false&width=300&action=like&font=arial&colorscheme=light&height=20" );

	var d = document.getElementById("facebook_like");
	d.appendChild(f);

	// Facebook Share
	var d2 = document.getElementById("facebook_share_btn");
	var arr1 = d2.href.split("?");
	var params = arr1[1] + "";
	var arr2 = arr1[1].split("&");
	var fbUrl = arr1[0];
	for (var i=0; i < arr2.length; i++) {
		fbUrl += ( i > 0 ) ? "&": "?";
		fbUrl += ( i > 0 ) ? arr2[i]: "u=" + url;
	}
	d2.href = fbUrl;
}

VOX = YAHOO.namespace('YAHOO.VOX');


var ServicesBar = {
	root: null,
	curMax: 0,
	itemsPerPage: 5,
	items: [],

	hideAll: function() {
		for(var i=0; i < ServicesBar.items.length; i++) {
			ServicesBar.items[i].style.display = "none";
			// class names set positioning, so remove them
			ServicesBar.items[i].className = "item";
			/*
			for (var j = 0; j < ServicesBar.items.length; j++) {
				YAHOO.util.Dom.removeClass(ServicesBar.items[j], "item"+j);
			}
			*/
		}
	},
	displayPage: function(direction) {
		var j = ServicesBar.curMax;
		var inc = 1;
		var cssNum = 0;

		ServicesBar.hideAll();
		if (direction == "next") {
			for (var i = 0; i < ServicesBar.itemsPerPage; i++) {
				ServicesBar.items[j].style.display = "block";
				
				YAHOO.util.Dom.addClass(ServicesBar.items[j], "item"+cssNum);
				cssNum += inc;
									
				j += inc;
				if ( j >= ServicesBar.items.length ) {
					j = 0;
				} else if ( j < 0 ) {
					j = ServicesBar.items.length -1;
				}
				ServicesBar.curMax = j;
			}
		} else {
			j = ServicesBar.curMax - ServicesBar.itemsPerPage;
			if ( j == 0) {
				j = ServicesBar.items.length -1;
			} else if ( j < 0) {
				j = ServicesBar.items.length -1 + j;
			}
			ServicesBar.curMax = j;
			inc = -1;
			cssNum = ServicesBar.itemsPerPage;
			
			for (var i = 0; i < ServicesBar.itemsPerPage; i++) {
				ServicesBar.items[j].style.display = "block";
				
				YAHOO.util.Dom.addClass(ServicesBar.items[j], "item"+(cssNum-1));
				cssNum += inc;
									
				j += inc;
				if ( j >= ServicesBar.items.length ) {
					j = 0;
				} else if ( j < 0 ) {
					j = ServicesBar.items.length -1;
				}
			}
		}
		
		return false;
	},
	init: function (obj) {
		ServicesBar.root = obj.root;
		ServicesBar.items = YAHOO.util.Dom.getElementsByClassName("item", "li", ServicesBar.root);
		
		ServicesBar.displayPage("next");
	}
};

function setShortener ( url, callback ){
	var fUrl = "http://api.bit.ly/v3/shorten?login=" + BITLY.userId
			 + "&apiKey=" + BITLY.apiKey
			 + "&longUrl=" + escape(url)
			 + "&format=json&callback=" + callback;

	// Add new JSONP scripts
	addScript(fUrl);
}

function setTwitterWidget ( obj ) {
	var el = ( document.getElementById("twitterShare") ) ? document.getElementById("twitterShare"): 0;

	if (el) {
		el.innerHTML = "<a href='http://twitter.com/share' class='twitter-share-button' data-url='" + obj.data.url + "' data-counturl='"+location.href.toString()+"' data-via='"+ TWITTER.userId +"'>Share On Twitter</a>";
		addScript("http://platform.twitter.com/widgets.js");
	}
}

function isExternalLink(a) {
	var site = 'markudall.senate.gov';
	var tsite = 'markudall.testing.senate.gov';
	var arr = [ "mailto:", "javascript:", "http://"+site, "http://www."+site, "http://"+tsite, "http://www."+tsite, "senate.gov", "facebook.com", "twitter.com", "youtube.com", "flickr.com", "thomas.loc.gov", "house.gov", "scribd.com"];
	var str = a.href + "";

	if ( str.substr( str.length-1 , 1) == "#") return -1;
	if ( a.className.indexOf("ygtvlabel") > -1 ) return -1;
	for ( var i=0; i < arr.length; i++) {
		if ( str.toLowerCase().indexOf(arr[i]) > 0 ) {
			return 0;
		}
	}
	return 1;
}

(function() {

	var D = YAHOO.util.Dom,
		E = YAHOO.util.Event,
		L = YAHOO.lang;
		
	E.on(window,"load",function() {
		E.on(document.getElementsByTagName("a"),"click",function(e) {
			var a = this, 
				dest, pos, title,
				exit = 'senate.gov/cgi-bin/exitmsg?url=',
				re = /^https?:\/\/(.*\.)?senate\.gov(.*)/,
				flag = 0;
		
			if (a.tagName.toLowerCase() == 'a' && typeof a['href'] != 'undefined') {
				flag = isExternalLink(a);
				if ( flag == 0 ) {
					location.href = a.href;
					return;
				} else if (flag == -1) {
					return;
				} else {
					VOX.handleExitCancel(e);
					pos = a.href.toLowerCase().indexOf(exit);

					if (pos != -1) {
						pos = pos + exit.length;
						E.preventDefault(e);
						dest = a.href;
						VOX.showExitPanel(dest);
						E.preventDefault(e);
					} else if (a.href.search(re) == -1 && a.href.indexOf('mailto:') == -1
						&& a.href.indexOf('javascript:') == -1 ) {
						VOX.showExitPanel(a.href);
						E.preventDefault(e);
					}
				}
			}
		});
	});		

	if ( document.getElementById("facebook_share") ) {
		var callbacks = {
			// Successful XHR response handler
			success : function (o) {
				var messages = [];

				// Use the JSON Utility to parse the data returned from the server
				try {
					messages = YAHOO.lang.JSON.parse(o.responseText);
				}
				catch (x) {
					return;
				}
				if ( messages.length > 0 ) {
					var f = document.createElement("IFRAME");
					var d = document.getElementById("facebook_share");
					
					f.setAttribute("class", "btn-share-fb");
					f.setAttribute("scrolling", "no");
					f.setAttribute("frameborder", "0");
					f.setAttribute("allowTransparency", "true");
					f.setAttribute("width", "300");
					f.setAttribute("height", "23");
					
					f.setAttribute("src", "http://www.facebook.com/plugins/like.php?href=" + escape(messages.data.url) + "&amp;layout=button_count&amp;show_faces=false&amp;width=450&amp;action=like&amp;font=arial&amp;colorscheme=light&amp;height=21" );

					d.appendChild(f);
				}
			},
			failure : function() {}
		};
					console.log(escape(document.location.href));
		//alert('/vox/utils/bitly.cfm?u=' + escape(document.location.href));
		// Make the call to the server for JSON data
		YAHOO.util.Connect.asyncRequest('GET', '/vox/utils/bitly.cfm?u=' + escape(document.location.href), callbacks);
	}
	
	VOX.getExitPanelContainer = function() {
		if (!('exitPanelContainer' in VOX)) {
			VOX.exitPanelContainer = document.createElement('div');
			document.body.appendChild(VOX.exitPanelContainer);
		}
		return VOX.exitPanelContainer;
	}
	VOX.exitPanel = new YAHOO.widget.Panel("lightbox", { modal: true, visible: false, fixedcenter: true, close: true, focusable: true, width: "375px" });
	VOX.exitPanel.setHeader("<span class='exit-esc'>ESC to cancel</span>Exiting Senate Web Site");	
	VOX.exitPanel.cfg.setProperty("keylisteners", [
		new YAHOO.util.KeyListener(document, { keys:[27] },
            function(types, args, obj) { VOX.exitPanel.hide();
		})
	]); 
	VOX.exitPanel.showEvent.subscribe(function() {
		D.addClass(VOX.exitPanel.element, "exit-panel");
		VOX.handleExitCancel = VOX.exitCancel;
		VOX.exitPanel.setAttribute("role","alert");
		VOX.exitPanel.element.tabIndex = 0;
		VOX.exitPanel.element.focus();
	});
	VOX.exitPanel.beforeHideEvent.subscribe(function() {
		VOX.exitTimeout = clearTimeout(VOX.exitTimeout);
		VOX.handleExitCancel = VOX.exitCancelStub;
	});
	VOX.exitPanel.hideEvent.subscribe(function() {
		VOX.handleExitCancel = VOX.exitCancelStub;
	});
	

	VOX.exitPanel.renderEvent.subscribe(function() {
		VOX.exitPanel.close.appendChild(document.createTextNode(' ESC'));
	});
			
	VOX.exitTimeout = null;

	VOX.exitCancel = function(e) {
		// hide panel and cancel forwarding
		var t = E.getTarget(e);
		if (D.getAncestorByClassName(t, "exit-panel") == null) {
			VOX.exitTimeout = clearTimeout(VOX.exitTimeout);
			VOX.exitPanel.hide();
		}
	};
	VOX.exitCancelStub = function(e) { 
		// do nothing
	};
	VOX.handleExitCancel = VOX.exitCancelStub;
	
	
	
	VOX.exitPanelTemplate = "<div class='exitmsg'>" + 
						"<h1>You are exiting the Senate Web Server</h1>" + 
						"<p><em>Thank you for visiting our site.</em></p>" +
						"<div class='exitdest'><p><strong>You will now access:</strong></p>" + 
						"<a href='{dest}' title='Exit now to {dest}'>{shortdest}</a>" +							
						"</div></div>";
											
	VOX.showExitPanel = function(dest) {
		var shortdest = dest;
		if (shortdest.length > 43) {
			shortdest = shortdest.substr(0,40) + '&hellip;';
		}
		clearTimeout(VOX.exitTimeout);
		VOX.exitTimeout = setTimeout(function() { self.location.href = dest; }, 5000);
		VOX.exitPanel.setBody(YAHOO.lang.substitute(VOX.exitPanelTemplate, { dest: dest, shortdest: shortdest }));
		VOX.exitPanel.render(VOX.getExitPanelContainer());
		VOX.exitPanel.show();			
	};


	VOX.printElement = function(el) {
		var v = new Date();
		var w = window.open('','printel',"width=750,scrollbars=yes");
		/*
		var w = document.getElementById('printframe');		
		if (!w) {
			w = document.createElement('iframe');
			w.id = 'printframe';
			w.src = '/images/spacer.gif';
			w.title = 'This frame used for background printing.';
			w.style.visibility = 'hidden';
			w.style.height = '0px';
			w.style.width = '0px';
			w.style.position = 'absolute';
			document.body.appendChild(w);
		}
		w = (w.contentWindow) ? w.contentWindow : (w.contentDocument.document) ? w.contentDocument.document : w.contentDocument;
		*/
		w.document.open("text/html","replace");
		w.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:wairole="http://www.w3.org/2005/01/wai-rdf/GUIRoleTaxonomy#" xmlns:aaa="http://www.w3.org/2005/07/aaa"><head><title>' + document.title + '</title><meta http-equiv="X-UA-Compatible" content="IE=8"><link rel="shortcut icon" href="/favicon.ico" type="image/x-icon"><link rel="icon" href="/favicon.ico" type="image/x-icon"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><link rel="stylesheet" type="text/css" href="/css/reset.css" /><link rel="stylesheet" type="text/css" href="/css/text.css" /><link rel="stylesheet" type="text/css" href="/css/960.css" /><link rel="stylesheet" type="text/css" href="/css/global.css" /><link rel="stylesheet" type="text/css" href="/js/niftycube/niftyCorners.css" /><link rel="stylesheet" type="text/css" href="/js/yui/build/tabview/assets/skins/sam/tabview.css" /><link rel="stylesheet" type="text/css" href="/css/markudall.css?' + v + '" /><link rel="stylesheet" type="text/css" href="/css/map-base.css?' + v + '" /><link rel="stylesheet" type="text/css" href="/css/backgrounds.css?' + v + '" /><link rel="stylesheet" type="text/css" href="/css/map.css?' + v + '" /><link rel="stylesheet" type="text/css" href="/css/print.css?' + v + '" /><style type="text/css" media="print">body{margin:0 !important} .print-tls{display:none}</style></head><body class="'+document.body.className+'" style="font-size:.85em;background:#fff none;margin:36px;"><div style="text-align:center;"><div style="text-align:left;width:648px;margin:0 auto;">');
		//w.document.write('<div class="print-tls" style="text-align:right;padding-bottom:5px;border-bottom:1px solid #ccc;margin-bottom:1.4em"><a href="javascript:print()"><img src="/images/printbtn.gif" alt=""></a></div>');
		w.document.write(el.innerHTML);
		w.document.write('</div></div></body></html>');
		w.document.close();
		w.print();
	};
	
	VOX.bookmark = function() {
		var title=document.getElementsByTagName("title")[0].text; 
		if(window.sidebar) window.sidebar.addPanel(title,location.href,""); 
		else if(window.external) window.external.AddFavorite(location.href,title); 
		else alert("Your browser does not support automated bookmarks. Please bookmark this site manually.");
	};
	
	
	E.onDOMReady(function (ev) {

		// IE6 always wins :(
		if (document.all && document.getElementById) {
			navRoot = document.getElementById("navtop");
			for (i=0; i<navRoot.childNodes.length; i++) {
				node = navRoot.childNodes[i];
				if (node.nodeName=="LI") {
					node.onmouseover=function() {
						this.className+=" over";
					};
					node.onmouseout=function() {
						this.className=this.className.replace(" over", "");
					};
				}
			}
		}


		// serving coloradans tooltips
		var idx = 0;
		var offsety = 14;
		if (YAHOO.env.ua.ie > 6) {
			offsety = 12;
		} else if (YAHOO.env.ua.ie > 0) {
			offsety = 16;
		}
		
		D.getElementsByClassName('auto-tt','a',document.getElementById('serving_coloradans'), 
			function(el) {
				var tt = new YAHOO.widget.Tooltip('sc-tt'+(idx++),{
					context:el, 
					text: el.title, 
					showDelay: 25, 
					hideDelay: 25,
					effect:{effect:YAHOO.widget.ContainerEffect.FADE,duration:0.15},
					constraintoviewport: false,
					zIndex: 1
				});
				tt.body.className += ' sc-tt';
			
				/*
				E.on(el,'mouseover',function(e) {					
					tt._mouseoverEventY = E.getPageY(e);
				});
				*/
				
				tt.beforeShowEvent.subscribe(function() {
					var reg = D.getRegion(el);
					var offsetx = parseInt(D.getStyle(el, "paddingLeft"));
					var newpos = [reg.left + offsetx,reg.bottom-offsety];
					tt.cfg.setProperty("constraintoviewport",false);
					tt.cfg.setProperty("xy",newpos);
			 	});
			}
		);
		
		// resize fonts
		setDefaultFontSize();
		
		var Y = YAHOO.util;
		
		// Swaps input text
		var els = Y.Dom.getElementsByClassName('swap_value', 'input');
		if (els && els.length) {
			for (var i =0; i < els.length; i++) {
				var _obj = {el: els[i], value: els[i].value};
				
				// add onFocus event
				Y.Event.addFocusListener(els[i], function (ev, o) { 
					if (o.el.value == o.value){
						o.el.value = "";
					}
				}, _obj );
				
				// add onBlur event
				Y.Event.addBlurListener(els[i], function (ev, o) { 
					if (YAHOO.lang.trim(o.el.value) == ""){
						o.el.value = o.value;
					}
				}, _obj );
			}
		}

		// Change serach appliance text
		els = YAHOO.util.Dom.getElementsByClassName('gsKeyMatchText', 'span');
		if (els && els.length) {
			els[0].innerHTML = "Suggested";
		}
		
		// init hot topics news ticker
		if ( document.getElementById("hot_tops-content") ) {
			tickerRun( { div: document.getElementById("hot_tops-content"), interval: 6000} );
		}
		
		if ( document.getElementById("servicesBar") ) {
			ServicesBar.init({ root: document.getElementById("servicesBar") });
		}
		
		var isNifty = 1;
		var form22Config = [
			{ label: "Organization", fields: 7 },
			{ label: "Application Contact", fields: 5 },
			{ label: "Chief Administrative Official <span>(if not application contact)</span>", fields: 5 },
			{ label: "Federal Grant Program", fields: 5 },
			{ label: "Federal Agency Contact", fields: 5 },
			{ label: "Grant Application", fields: 9 }
		];
		if ( document.getElementById("formBuilder") ) {
			if ( document.getElementById("body").className.indexOf("form-22") > -1 ) {
				var fb = document.getElementById("formBuilder");
				var fbRows = YAHOO.util.Dom.getElementsByClassName("clearfix", "div");
				var btns = YAHOO.util.Dom.getElementsByClassName("buttons-bottom", "div");
				var fbBtns = btns[0];
				var nn = document.createElement("div");
				
				nn.className = "grid_11 alpha omega";
				fbBtns.className = "grid_7 prefix_4 alpha omega buttons-bottom";
				
				var secStart = 0
				for ( var i = 0; i < form22Config.length; i++) {
					var secEnd = secStart + form22Config[i].fields;
					var sec = document.createElement("div");
					sec.className = "callout";
					sec.style.margin = "0 0 20px 0";
					
					var secHd = document.createElement("h2");
					secHd.innerHTML = form22Config[i].label;
					sec.appendChild(secHd);
					
					for ( var j = secStart; j < secEnd; j++) {
						var clFix = document.createElement("div");
						clFix.className = "clearfix";
						
						sec.appendChild( fbRows[j] );
						sec.appendChild( clFix );
						secStart = j+1;
					}
					
					nn.appendChild(sec);
				}
				
				nn.appendChild(fbBtns);
				fb.appendChild(nn);
				Nifty("div.callout","transparent");
				
				isNifty = 0;
			}
		}

		if ( isNifty ) {
			Nifty("blockquote","transparent");
			Nifty("div.callout","transparent");
		}
		
		
		var yTabs = YAHOO.util.Dom.getElementsByClassName("yui-navset", "div");
		for (var i=0; i < yTabs.length; i++) {
			var yTabsAct = new YAHOO.widget.TabView(yTabs[i]);
		}
		
		if ( document.getElementById("twitterShare") ) {

			setShortener( location.href.toString(), "setTwitterWidget");
		}
	});

	
		
})();


// Custom subscribable event for youtube video state changes	
VOX.youTubePlayerReady = new YAHOO.util.CustomEvent('youTubePlayerReady',window);

// Pass through to a subscribable event
function onYouTubePlayerReady(playerId) {
	VOX.youTubePlayerReady.fire(playerId);
}
