if (typeof(nri) != "undefined")
{
	if (typeof(nri.gt) == "undefined") nri.gt = {};
	
	/**
	 * "Constants"
	 */
	 
	// weather
	nri.gt.WX_UPDATE_FREQ_MS = (1000*60*15); // how often should we update the weather data?
	nri.gt.WX_UPDATE_TTL_SECS = (60*15); // how long should we trust the page's weather data?
	nri.gt.WX_UPDATE_MAX_RETRIES = 5; // how many times should we try to refresh the weather if an attempt fails?
	nri.gt.WX_RETRY_FREQ_MS = (1000*30); // how long should we wait between attempts?
	
	// Thickbox feedback dialog initialization
	nri.gt.TBFB_INIT_RETRY_FREQ_MS = 100; // if nri.feedback isn't initialized when we first try to use it, how long to wait
										  // before retry?
	nri.gt.TBFB_INIT_MAX_RETRIES = 5; // how many times should we try before we give up?
	 
	
	/**
	 * Update the weather module
	 */
	nri.gt.wxupd = function()
	{
		var $ = jQuery;
		
		var force = (arguments[0]?true:false);
		
		var now = new Date();
		var secs = now.getTime() / 1000;
		var ttl = nri.gt.WX_UPDATE_TTL_SECS; // time to let the cached page's weather stand before update
				   			
		var el = $("#nrcMod_dateWeather ul");
		
		var mtime = el.attr("nri:mtime"); // modification time of the weather on the (cached) page
		var wxloc = el.attr("nri:wxloc"); // NWS station location ID of the weather on the (cached) page
		
		if ( force || (ttl < (secs - mtime)) ) // if the page was generated more than ttl seconds ago, refresh the weather data
		{
			var ts = now.getFullYear()+","+now.getMonth()+","+now.getDate()+","+now.getHours()+","+Math.floor(now.getMinutes() / 15);
			
			// if the data's being requested from another server (e.g., vendor template), do a jsonp request
			var notgt = !( (document.location.hostname.indexOf('localdomain')!=-1) || (document.location.hostname=='www.gotriad.com') ); // "not gotriad"
			var url = (notgt?'http://www.gotriad.com':'') + '/nri/utilities/weather/json/' + wxloc + '/' + ts;

			var errfn = function(xml,stat,err)
			{
				if (nri.gt.wxupd.cnt < nri.gt.WX_UPDATE_MAX_RETRIES)
				{
					setTimeout(nri.gt.wxupd,nri.gt.WX_RETRY_FREQ_MS);
					nri.gt.wxupd.cnt++;
				}
				else
				{
					var mtime = new Date( $("#nrcMod_dateWeather ul").attr("nri:mtime") * 1000 );
					var ts = mtime.getFullYear() + '-' + (mtime.getMonth() + 1) + '-' + mtime.getDate() + ' ' + mtime.getHours() + ':' + mtime.getMinutes() + ':' + mtime.getSeconds(); 
					alert("Temporarily unable to connect to server to refresh weather data. The weather shown on this page may be outdated. It was last updated " + ts);
				}
				
				return false;
			};
			
			var sucfn = function( json, stat )
			{
				var icon = json.data.WxIcon;
				var cond = json.data.WxText;
				var temp = json.data.TempF;
				var high = json.data.Day1HiF;
				var low = json.data.Day1LoF;
				
				if (!(cond||temp||high||low))
				{
					errfn();
					return false;
				}

				$("#gtTxt_WthrCond").attr('class','nrcWx_wcomIcon'+(icon?icon:0));
				$("#gtTxt_WthrCond_Txt").html((cond!=null)?cond:'na');
				$("#gtTxt_WthrToday_Txt").html((temp!=null)?temp:'na');
				$("#gtTxt_WthrHighLow_Hi").html(( (high!=null) && (high>low) )?high:'na');
				$("#gtTxt_WthrHighLow_Lo").html((low!=null)?low:'na');

				// set a timeout to update again in WX_UPDATE_FREQ_MS milliseconds
				// and reset the attempt counter
				setTimeout(nri.gt.wxupd,nri.gt.WX_UPDATE_FREQ_MS);
				nri.gt.wxupd.cnt = 0;
				
				return true;
			};
			
			$.ajax(
				{
					url:url,
					async:true,
					cache:true,
					dataType:notgt?'jsonp':'json',
					error:errfn,
					success:sucfn
				}
			);
		};
	};
	
	// weather update retry counter
	nri.gt.wxupd.cnt = 0;
	
	/**
	 * Switch to the appropriate QuickSearch tab, fetching via AHAH if necessary.
	 */
	 nri.gt.qstab = function( tab )
	 {
	 	var $ = jQuery;
	 	
	 	// change selected tab
	 	$("#gtMod_qsEvents").attr("class","").addClass("gtSec_"+tab);
	 	
	 	// the XHR is referenced by nri.gt.qstab.running. If it's set, call XMLHttpRequest::abort()
	 	if ( nri.gt.qstab.running && nri.gt.qstab.running.readyState)
	 	{
		 	try {
		 		nri.gt.qstab.running.abort();
		 	}
		 	catch(e)
		 	{};
	 	
	 		nri.gt.qstab.running = false;
	 	}
	 	else
	 	{
 			$("#gtBlk_qsTabCnt").append('<div class="nrcWgt_overlay">&nbsp;</div><div class="nrcWgt_progBar"><span class="nrcTxt_label">Content Loading...</span></div>');
	 	}
	 		
	 	var url = (!nri._ours?nri.url_prefix:'') + "/nri/gt/modules/quicksearch/" + tab;
	 	
	 	var errfxn = function(s,e,x)
	 	{
	 		nri.gt.qstab.running = false;
	 		return false;
	 	}
	 	
	 	var sucfxn = function(json,stat)
	 	{
	 		nri.gt.qstab.cache[tab] = json;
	 		$("#gtBlk_qsTabCnt").empty().append( json );
	 		
	 		$("#gtBlk_qsTabCnt").find("iframe").each(
	 			function()
	 			{
	 				var ifr = this;
	 				var win = this.contentWindow;
	 				
	 				// best effort to fit iframe to size of contents
 					$(win).load(
	 					function(e)
						{
			 				var ifrh = null;
			 				var $ifr = $(ifr);
				
		 				    if(ifr.Document) ifrh = ifr.Document.body.scrollHeight;
				        	else if(win){
				                if (win.innerHeight && win.scrollMaxY)
				                {
				                	ifrh = win.scrollMaxY + win.innerHeight;
				                }
				                else if (win.document.height)
				                {
				                        ifrh = win.document.height;
				                }
				                else if (ifr.contentDocument.documentElement.scrollHeight)
				                {
				                	ifrh = ifr.contentDocument.documentElement.scrollHeight;
				                }
				                else
				                {
									ifrh = win.document.body.scrollHeight;
				                }
				        	}

				        	$ifr.css('overflow','hidden');
				        	$ifr.height(ifrh);
						} 					
 					);
	 			}
	 		);
			
			try
			{
	 			nri.gt.calendar_init();
			}
			catch(e)
			{}
	 		
			nri.gt.qstab.running = false;
	 		return false;
	 	}
	 	
	 	// if we have a cached result, use that instead of starting another request.
	 	if ( (typeof(nri.gt.qstab.cache[tab]) != "undefined") && nri.gt.qstab.cache[tab].length)
	 	{
	 		sucfxn(nri.gt.qstab.cache[tab],false);
	 	}
	 	else
	 	{
		 	nri.gt.qstab.running = $.ajax(
			 	{
			 		url:url,
			 		async:true,
			 		cache:true,
			 		dataType:(!nri._ours?"jsonp":"json"),
			 		error:errfxn,
			 		success:sucfxn
			 	}
		 	);
	 	}
	 	
	 	return false;
	 }
	 
	 // reference for XHR created by nri.gt.qstab();
	 nri.gt.qstab.running = false;
	 
	 // cache map for qstab switcher
	 nri.gt.qstab.cache = {};
	 
	nri.gt.scene_date_search = function(form,month,day,year)
	{
		form.action = "http://www.gotriadscene.com/advanced_search/event";
		form.method = "POST";
		form.elements['when'].value = (month<10?'0':'') + month + "/" + (day<10?'0':'') + day + "/" + year;
		form.submit();
	}
	
	/**
	 * Balance main menu submenus into multiple columns
	 */
	jQuery(window).bind('nriMenuAppended',
		function(e,$el)
		{ 
			var $ = jQuery;
			
			if ($el.parents("#nrcMod_MainMenu").length)
			{
				// submenu wrapper <div>
				var $smwrap = $el.children(".nrcNav_subMenuWrapper");
				
				// submenu top-level <ul>
				var $smlist = $smwrap.children("ul");
				
				// top-level list items
				var $smitems_top = $smlist.children("li");
				
				// total list items
				var $smitems_cnt = $smlist.find("li").length;
				
				// calculate # columns and items per column				
				var percol = Math.floor($smitems_top.length / 3);
				var cols = Math.min(($smitems_cnt / percol),3);
				var rmndr = $smitems_cnt % cols;
				var idx = 0; var cnt = 0; var subitms = 0;
				var $newcol = false;
				
				for (var i = 0; i < cols; i++)
				{
					$newcol = $smlist.clone().empty();
					cnt = 0;
					
					for (var j = 0; (j < percol) && (idx < $smitems_top.length); j++)
					{
						$newcol.append($smitems_top[idx]);
						
						cnt += 1 + $($smitems_top[idx]).find("li").length;

						idx++;
						
						if (cnt >= percol)
						{
							break;
						}
					}
						
					// try to front-load remainder to columns
					if (rmndr && (idx < $smitems_top.length)
						&& ( (subitms + cnt + 1) < (percol + 3) )
					)
					{
						$newcol.append($smitems_top[idx]);
						idx++;
						rmndr--;
					}
					
					$smwrap.append($newcol);
				}
				
				// the arithmetic's a little fuzzy, so make sure all
				// top-level menu items have been placed
				while (idx < $smitems_top.length)
				{
					$newcol.append($smitems_top[idx++]);
				}
				
				$smlist.remove();
			}
		}
	);
};

/**
	<article>
	  <NID>{{nid}}</NID>
	  <Headline>{{Headline}}</Headline>
	  <Timesaver>{{Timesaver}}</Timesaver>
	  <Body>{{Body}}</Body>
	  <Images><image>{{ImageURL}}</image></Images>
	  <Thumbnail>{{ThumbnailURL}}</Thumbnail>
	  <sections>{{Category}}</sections>
	  <url>{{URL}}</url>
	</article>	
*/
nri.gt.getSliderXML = function()
{
	var $ = jQuery; var $this = false;
	
	var xmldoctpl = "<articles>{{articles}}</articles>";
	var xmlarttpl = "<article><NID>{{NID}}</NID><Headline>{{Headline}}</Headline><Timesaver>{{Timesaver}}</Timesaver><Body>{{Body}}</Body><Images><image>/files/imagecache/gtcom09_scroller_image/{{Image}}</image></Images><Thumbnail>{{Thumbnail}}</Thumbnail><sections>{{Category}}</sections><url>{{URL}}</url></article>";		
	
	
	var xml = "";
	
	$("#gtMod_homeArtSlide .nrcBlk_art").each(
		function()
		{
			$this = $(this);
			var art = xmlarttpl;
			
			$this.find('*').each(
				function()
				{
					var $tel = $(this);
					var tval = $tel.attr("nri:val");
					
					if (! tval) return true;
					else
					{
						var tvars = tval.split(',');
						var els = false;
						
						for (var k = 0; k < tvars.length; k++)
						{
							els = tvars[k].split('|');
							
							if (els[0].charAt(0) == "'")
							{
								els[0] = els[0].substr(1,els[0].length - 2);
							}
							else if (els[0] == 'src' || els[0] == 'href')
							{
								els[0] = $tel.attr(els[0]);
							}
							else if (els[0] == 'cdata')
							{
								els[0] = $tel.html();
							}
							
							art = art.replace('{{'+els[1]+'}}',escape(els[0]));
						}
					}
					
					return true;
				}
			);
			
			xml += art;
		}
	);

	var xmldoc = xmldoctpl.replace('{{articles}}', xml.replace(/\{\{[^\}]+\}\}/g,' '));
	return xmldoc;
}

// initialize the js popup calendars used on the QuickSearch
nri.gt.calendar_init = function()
{
	Calendar.setup(
		{
			inputField     : 'startDate',
			ifFormat       : '%Y-%m-%d',
			button         : 'start_date_trigger',
			singleClick    : true
		}
	);
	
	Calendar.setup(
		{
			inputField     : 'endDate',
			ifFormat       : '%Y-%m-%d',
			button         : 'end_date_trigger',
			singleClick    : true
		}
	);
}

// thickbox feedback dialog initialization
/** @TODO Either find another way to deal with this, or generalize the process
 * 			so it can be used in a more consistent manner
 */
 // Due to the vagueries of IE's readyState, jQuery sometimes fires onready handlers
 // before scripts in the footer have been initialized. This is a (hopefully temporary)
 // hack to deal with that for our Thickbox feedback dialog
nri.gt.fdbck_init = function()
{
	if (typeof(nri.feedback)=='object')
	{
		if (nri.gt.fdbck_init.timeout) clearTimeout(nri.gt.fdbck_init_to);
		$("a[href='/help/feedback']").click( function() { nri.feedback.init(); return false; } );
		nri.gt.fdbck_init.timeout = false;
	}
	else if (nri.gt.fdbck_init.cnt < nri.gt.TBFB_INIT_MAX_RETRIES)
	{ 
		nri.gt.fdbck_init.cnt++;
		nri.gt.fdbck_init.timeout = setTimeout(nri.gt.fdbck_init,nri.gt.TBFB_INIT_RETRY_FREQ_MS);
	}
}

// feeback init retry counter and timeout id
nri.gt.fdbck_init.cnt = 0;
nri.gt.fdbck_init.timeout = false;

// stuff to do when the page is ready
//Global Killswitch
if (Drupal.jsEnabled) {
	$(document).ready(function() {

		nri.gt.fdbck_init(); // init TB feedback dialog handler
		
		// We don't use fieldset legends because they're too difficult to style
		// consistently across browsers. Need to make fieldset titles (<h3>)
		// the controls for collapsible fieldsets
		$('.collapsible > h3.nrcTxt_fldGrp_title').each(function() {
		  var fieldset = $(this.parentNode);
		  // Expand if there are errors inside
		  if ($('input.error, textarea.error, select.error', fieldset).size() > 0) {
			  fieldset.removeClass('collapsed');
		  }
		
		  // Turn the legend into a clickable link and wrap the contents of the fieldset
		  // in a div for easier animation
		  var text = this.innerHTML;
		  $(this).empty().append($('<a href="javascript:void(0);">'+ text +'</a>').click(function() {
			var fieldset = $(this).parents('.collapsible:first')[0];
			// Don't animate multiple times
		    if (!fieldset.animating) {
		      fieldset.animating = true;
		      Drupal.toggleFieldset(fieldset);
		    }
		    return false;
		  })).after($('<div class="fieldset-wrapper"></div>').append(fieldset.children(':not(.nrcTxt_fldGrp_title,.nrcBlk_flgGrp_footer)')));
		  fieldset.filter('.collapsed').children('.fieldset-wrapper').css({height: 'auto', display: 'inline'});
		});
	});
}

