﻿/// <reference path="../../combo.js" />
/// <reference path="Profile.js" />
/// <reference path="Search.js" />
/// <reference path="Rating.js" />
/// <reference path="WikiParser.js" />
/// <reference path="Edit.js" />

var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;
var $EL = YAHOO.util.Element;
var $S = YAHOO.util.Selector;
var $C = YAHOO.util.Connect;
var $H = YAHOO.util.History;
var $ = $D.get;
var $$ = $S.query;

var Global =
{
	// Global application state
	ContentVersion: '1.0',
	LastSelectedCommandPane: null,
	PreviousState: null,

	// Google Analytics page tracker object
	GAPageTracker: null,

	Init: function()
	{
		$E.on($('banner'), 'click', function() { document.location = '/'; }, null, true);

		if (Global.ContentServerPath == null)
			Global.ContentServerPath = 'http://common.logos.com/' + Global.ContentVersion;

		// don't scroll the whole window down
		// TODO: get rid of the flicker this method produces
		$E.on(document, 'scroll', function(e)
		{
			$E.stopEvent(e);
			window.scrollTo(document.body.scrollLeft, 0);
		});

		Search.InitHandlers();

		// Set up ajax history
		var initialContentState = $H.getBookmarkedState('content') || '/home';
		var initialTabState = $H.getBookmarkedState('tab') || 'paneTabHome';
		var initialPaneState = $H.getBookmarkedState('pane') || 'homePane';
		var bookmarkedQueryResult = $H.getBookmarkedState('q');

		var queryState = Search.ParseQueryState(bookmarkedQueryResult);
		var bookmarkedQuery = queryState.Query;

		$H.register('content', initialContentState, Global.NavigateTo);
		$H.register('tab', initialTabState, Global.SelectTab);
		$H.register('pane', initialPaneState, Global.SelectPane);

		// Use the Browser History Manager onReady method to setup the initial state
		$H.onReady(function()
		{
			// do this initialization after BHM has been initialized
			if (initialContentState != '/home' && initialContentState != Global.InitialContentState)
				Global.NavigateTo(initialContentState);
			else
				Global.LoadHome();

			if (bookmarkedQuery != null && bookmarkedQuery != '')
				Search.OnQueryStateChange(bookmarkedQueryResult);

			Global.SelectPane(initialPaneState);
			Global.SelectTab(initialTabState);
		});

		// Initialize the browser history management library.
		try
		{
			$H.initialize('yui-history-field', 'yui-history-iframe');
		}
		catch (e)
		{
			// The only exception that gets thrown here is when the browser is
			// not supported (Opera, or not A-grade) Degrade gracefully.
			// Note that we have two options here to degrade gracefully:
			//   1) Call initializeNavigationBar. The page will use Ajax/DHTML,
			//	  but the back/forward buttons will not work.
			//   2) Initialize our module. The page will not use Ajax/DHTML,
			//	  but the back/forward buttons will work. This is what we
			//	  chose to do here:
			//$L('Could not initialize YUI Browser History Manager: ' + e, 'error');
			alert('Could not initialize YUI Browser History Manager: ' + e);
		}

		Logos.Loader.Load("InfoBar", "1.0", function()
		{
			Logos.Chrome.InfoBar.resizeHandler = OnResize;
		});
		Logos.Loader.Load("AdRotator", "1.0", function()
		{
			Logos.Chrome.AdRotator.InsertAd('\
				<div style="background: transparent url(http://www.logos.com/images/homePage/bg_basePackageModule.gif) repeat scroll 0%; -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; width: 239px;">\
					<table width="100%" cellspacing="0" cellpadding="0" border="0">\
						<tbody>\
							<tr>\
								<td width="100%">\
									<table border="0" cellpadding="0" cellspacing="0">\
										<tbody style="text-align: center">\
											<tr>\
												<td colspan="4"><a href="http://www.logos.com/bible"><img src="http://www.logos.com/images/bible.logos.com/experience.gif" alt="Bible study" width="239" border="0" id="" /></a></td>\
											</tr>\
											<tr style="background-image: \'http://www.logos.com/images/bible.logos.com/bg.gif\'; background-repeat: repeat-x;">\
												<td style="background-image: \'http://www.logos.com/images/bible.logos.com/bg.gif\'; background-repeat: repeat-x;">\
													<a href="http://www.logos.com/bible"><img src="http://www.logos.com/images/bible.logos.com/img_bibleStudyThumb.gif" alt="Bible Study Library" width="59" height="60" border="0" onmouseover="swapPackageText(\'bibleStudy\');" onmouseout="restorePackageText();" /></a>\
												</td>\
												<td>\
													<a href="http://www.logos.com/bible"><img src="http://www.logos.com/images/bible.logos.com/img_leadersThumb.gif" alt="Leader\'s Library" width="60" height="60" border="0" onmouseover="swapPackageText(\'leaders\');" onmouseout="restorePackageText();" /></a>\
												</td>\
												<td>\
													<a href="http://www.logos.com/bible"><img src="http://www.logos.com/images/bible.logos.com/img_scholarsThumb.gif" alt="Scholar\'s Library" width="60" height="60" border="0" onmouseover="swapPackageText(\'scholars\');" onmouseout="restorePackageText();" /></a>\
												</td>\
												<td>\
													<a href="http://www.logos.com/bible"><img src="http://www.logos.com/images/bible.logos.com/img_goldThumb.gif" alt="Scholar\'s Library : Gold" width="60" height="60" border="0" onmouseover="swapPackageText(\'gold\');" onmouseout="restorePackageText();" /></a>\
												</td>\
											</tr>\
											<tr>\
												<td colspan="4">\
													<img src="http://www.logos.com/images/bible.logos.com/img_basePackageText.gif" alt="Bible study" width="239" border="0" id="packageImage" />\
												</td>\
											</tr>\
										</tbody>\
									</table>\
								</td>\
							</tr>\
						</tbody>\
					</table>\
				</div>');
			Logos.Chrome.AdRotator.InsertAd('<a href="http://www.reftagger.com" target="_blank"><img src="' + Global.ContentServerPath + 'images/reftaggerbible.logos.com.gif" /></a>');
			Logos.Chrome.AdRotator.InsertAd('<a href="http://www.biblestudymagazine.com/tracking/bible/" target="_blank"><img src="' + Global.ContentServerPath + 'images/bsm239pxwide.gif" alt="Bible Study Magazine ad" /></a>');
			Logos.Chrome.AdRotator.InsertAd('<a href="http://bible.logos.com/content/bible-search-bar" target="_blank"><img src="http://www.logos.com/media/ads/contentsites/biblesearchbar.gif" alt="Bible Search Bar" /></a>');
			Logos.Chrome.AdRotator.StartRotation('adSpace', 30000);
		});

		Rating.Init();
	},

	// Global functionality
	SelectPane: function(id)
	{
		$D.batch($$('#commandsPane div.active'), function(item)
		{
			var elPane = new $EL(item);
			elPane.removeClass('active');
			elPane.addClass('inactive');
		});

		var elSelectedPane = new $EL(id);
		elSelectedPane.removeClass('inactive');
		elSelectedPane.addClass('active');

		if (id == 'editPane')
			Global.SelectHeader('editDetails');
		else
			Global.SelectHeader('searchBox');
	},

	SelectTab: function(id)
	{
		$D.batch($$('ul#paneList li.current'), function(item)
		{
			var elTab = new $EL(item);
			elTab.removeClass('current');
		});

		var elSelectedTab = new $EL(id);
		elSelectedTab.addClass('current');
	},

	SwitchSideBar: function(tab, pane)
	{
		if (tab == null)
			$H.navigate('pane', pane);
		else if (pane == null)
			$H.navigate('tab', tab);
		else if (tab == 'paneTabHome')
			$H.multiNavigate({ 'content': '/home', 'pane': pane, 'tab': tab });
		else
			$H.multiNavigate({ 'pane': pane, 'tab': tab });
	},

	SelectHeader: function(tab)
	{
		$D.batch($$('#sideBarHeader div.active'), function(item)
		{
			var elPane = new $EL(item);
			elPane.removeClass('active');
			elPane.addClass('inactive');
		});

		var elSelectedPane = new $EL(tab);
		elSelectedPane.removeClass('inactive');
		elSelectedPane.addClass('active');
	},

	LastContent: null,
	ShowContentLoading: function(error)
	{
		var container = $('contentBody') || $('body');
		var width = Math.floor(container.clientWidth / 2) - 40;
		var height = Math.floor(container.clientHeight / 3);

		if ($('editSubHeader') != null)
			$D.setStyle('editSubHeader', 'display', 'none');

		$('contentHeader').innerHTML = '';

		if (error)
		{
			container.innerHTML = Global.LastContent;
			Logos.Chrome.InfoBar.Show("infoBar", "Sorry, there was an error processing your request. The development team has been notified of the problem.", true);
		}
		else
		{
			Global.LastContent = container.innerHTML;
			container.innerHTML = '<div id="contentLoading" style="position:relative; left:' + width + 'px; top:' + height + 'px; width:6em"><img src="' + Global.ContentServerPath + 'images/ajax-loader.gif"/>Loading...</div>';
		}
	},

	GetPreviousState: function()
	{
		var state = Global.PreviousState;
		if (state == null)
		{
			if ($('editSermonId') != null)
			{
				state = Number($('editSermonId').value) > 0 ? { 'content': '/submissions/' + $('editSermonId').value, 'pane': 'homePane', 'tab': 'paneTabHome'} : { 'content': '/home', 'pane': 'homePane', 'tab': 'paneTabHome' };
			}
			else
			{
				state = { 'content': '/home' };
			}
		}

		return state;
	},

	ProcessContentChunk: function(o)
	{
		var chunk = YAHOO.lang.JSON.parse(o.responseText);
		var container = $(chunk.ContainerId);
		if (!container)
			return;

		if (document.all)
			container.innerText += chunk.Chunk;
		else
			container.textContent += chunk.Chunk;

		if (chunk.ChunkIndex < chunk.TotalChunks - 1)
		{
			// TODO: Should count requests & give up after X
			$C.asyncRequest('GET', Global.LastRequestedRoute + '?contentChunk=' + (chunk.ChunkIndex + 1),
			{
				success: Global.ProcessContentChunk,
				failure: function(o)
				{
					Logos.Chrome.InfoBar.Show("infoBar", "Sorry, there was an error processing your request.", true, OnResize);
				}
			});
		}
		else
		{
			// Process the content
			Global.InitContentPage();
		}
	},

	InitContentPage: function()
	{
		OnResize();
		Rating.Init();
		Edit.Init();
		Profile.Init();
		Global.LoadHome();

		if ($('sermonTitle') && $('sermonWiki'))
			document.title = '"' + $('sermonTitle').innerHTML + '" - ' + $$('#authorName > a', 'authorNameContainer', true).innerHTML;

		if ($('sermonWiki'))
		{
			var showUpgrade = $('contentIsTruncated') && $('contentIsTruncated').value === 'True';

			Edit.FormatSermon($('sermonWiki').innerHTML);
			if (showUpgrade)
			{
				var upgradeNote = document.createElement('p');
				upgradeNote.innerHTML = '<strong><img style="vertical-align:top; margin:4px 4px 4px 0;" src="/Content/Images/PremiumP16.png" />Premium content!</strong> To contrinue reading, <a href="http://www.logos.com">upgrade now</a> for as little as $2.95/month.';
				$D.addClass(upgradeNote, 'WikiFirstParagraph');
				$('sermonContent').appendChild(document.createElement('hr'));
				$('sermonContent').appendChild(upgradeNote);
			}

			(function()
			{
				var strQuery = Search.QueryToLoad;
				var fnLoadWidget = function()
				{
					Logos.Chrome.PPSWidget.Init('ppsResults', 1000);
					Global.UpdatePPSResults(strQuery);
				};

				if (!Logos.Chrome.PPSWidget)
					Logos.Loader.Load('PowerPointSermonsWidget', '1.0', fnLoadWidget);
				else
					fnLoadWidget();
			})();
		}
		else if ($('txtEditSermon'))
		{
			Edit.FormatSermon(Global.HtmlEncode($('txtEditSermon').value));
		}

		$D.batch($$('div.lbsTooltip'), function(item)
		{
			var elTooltip = new $EL(item);
			elTooltip.setStyle('visibility', 'hidden');
		});

		Search.QueryToLoad = null;

		if (Logos.Chrome && $('adSpace'))
			Logos.Chrome.AdRotator.StartRotation('adSpace', 30000);
	},

	UpdatePPSResults: function(strTerm)
	{
		if (!Logos.Chrome.PPSWidget.initialized)
			return;

		var strQuery = null;
		var bIsBibleReference = false;

		if (strTerm !== null && strTerm != '')
		{
			strQuery = strTerm;
			var reReferenceTest = /<((?:\w|\d)\s?\w{2,}(?:\d|[ .:-])*)>/i;
			var reFieldTest = /\w{3,}:/gi;

			var testResults = reReferenceTest.exec(strQuery);
			if (testResults !== null && testResults.length > 1)
			{
				strQuery = testResults[1];
				bIsBibleReference = true;
			}
			else
			{
				// Strip Logos-specific search fields
				strQuery = strQuery.replace(reFieldTest, '');
			}
		}
		else
		{
			//Fall back to the sermon's passages/topics if there is no search query
			if ($('submissionPassageList'))
			{
				strQuery = $$('#submissionPassageList a')[0].innerHTML;
				bIsBibleReference = true;
			}
			else if ($('submissionTopicList'))
			{
				strQuery = $$('#submissionTopicList a')[0].innerHTML;
			}
		}

		if (strQuery && strQuery.length > 0)
			Logos.Chrome.PPSWidget.Update(strQuery, bIsBibleReference, 2, null);
	},

	LastRequestedRoute: null,

	NavigateTo: function(location, preventDisplayLoading, usePost)
	{
		if (!preventDisplayLoading)
			Global.ShowContentLoading();

		var doInitContent = !preventDisplayLoading;
		var loc = /.*\.js/.test(location) ? location : location + '.js';
		Global.LastRequestedRoute = loc;
		Global.GAPageTracker._trackPageview(loc);
		$C.asyncRequest(usePost ? 'POST' : 'GET', loc,
		{
			success: function(o)
			{
				var viewData = YAHOO.lang.JSON.parse(o.responseText);

				for (var i = 0; i < viewData.length; i++)
				{
					var el = $(viewData[i].Key);
					if (el != null)
						el.innerHTML = viewData[i].Value;
				}

				if (viewData[0].Key == 'ContentChunkCount' && parseInt(viewData[0].Value) > 1 && !usePost)
				{
					if (parseInt(viewData[0].Value) > 4)
					{
						Logos.Chrome.InfoBar.Show("infoBar", "Sorry, the contents of this sermon are too large to display in your browser.", true, OnResize);
						$('sermonContent').innerHTML = '';
					}
					else
					{
						// Need to make additional requests to load the content
						$C.asyncRequest('GET', Global.LastRequestedRoute + '?contentChunk=0',
						{
							success: Global.ProcessContentChunk,
							failure: function(o)
							{
								Logos.Chrome.InfoBar.Show("infoBar", "Sorry, there was an error processing your request.", true, OnResize);
							}
						});

						// The new callback will do the init when content is done loading
						doInitContent = false;
					}
				}

				if (viewData[0].Key == 'CurrentProfile')
				{
					Profile.Current = viewData[0].Value;
				}

				if (doInitContent)
					Global.InitContentPage();
				else
					OnResize();
			},
			failure: function(o)
			{
				// The server returns a nice error page on 404, just treat it as a success & load the content
				if (o.status == 404)
					this.success(o)
				else
					Global.ShowContentLoading('error');
			}
		});
	},

	BrowseTo: function(location, states)
	{
		if (location == $H.getCurrentState('content'))
			return;

		states = states || {};

		if (location == 'previous')
		{
			$H.multiNavigate(Global.GetPreviousState());
		}
		else
		{
			if ($D.hasClass($('editDetails'), 'active') && !states['tab'] && !states['pane'])
			{
				states['tab'] = Global.PreviousState['tab'] || 'paneTabHome';
				states['pane'] = Global.PreviousState['pane'] || 'homePane';
			}

			Global.PreviousState = { 'content': $H.getCurrentState('content'), 'pane': $H.getCurrentState('pane'), 'tab': $H.getCurrentState('tab') };
			states['content'] = location;
			if (/\/edit\/.*|\/create/.test(location))
			{
				states['pane'] = 'editPane';
				$H.multiNavigate(states);
			}
			else
			{
				$H.multiNavigate(states);
			}
		}
	},

	UpdateSermon: function(sermonID, states)
	{
		if (sermonID == null)
			return;

		var sRequestUrl = sermonID == 0 ? '/home' : '/submissions/' + sermonID;
		Global.BrowseTo(sRequestUrl, states);
	},

	LoadHome: function()
	{
		if ($('recentContributions') == null)
			return;

		document.title = 'Sermons.Logos.com';

		$D.batch($$('#recentContributions span.recentPreview'), function(item)
		{
			$(item).innerHTML = Edit.FormatString($(item).innerHTML).replace(/<\/?(?:(?!cite)[^>])*>/ig, ' ').replace(/\s+/, ' ').replace('&amp;nbsp;', '&nbsp;');
		});

		Logos.ReferenceTagging.tag($('recentContributions'));

		$E.on($('contentBody'), 'scroll', Global.OnRecentSubmissionsScroll);

		if (Search.SelectedElement != null)
		{
			Search.SelectedElement.removeClass('selected');
			Search.SelectedElement = null;
		}
	},

	CurrentRequest: null,

	OnRecentSubmissionsScroll: function()
	{
		if (Global.CurrentRequest != null)
			return;

		var aContribElements = $$('#recentContributions .contribContainer');
		var elLastContrib = aContribElements[aContribElements.length - 1];
		var elSecondContrib = aContribElements[aContribElements.length - 2];
		if (elLastContrib == null)
			return;

		var rgLastLink = $D.getRegion(elSecondContrib);
		var rgBody = $D.getRegion('contentBody');

		// Need to have the server pass back the recent contributions count
		var reGetContribId = /contrib(\d+)/;
		var match = reGetContribId.exec(elLastContrib.id);
		var lastResult = parseInt(match[1]);
		if (rgBody.intersect(rgLastLink) != null)
		{
			Global.GAPageTracker._trackPageview('/submissions/recent/' + lastResult + '.js');
			Global.CurrentRequest = $C.asyncRequest('Get', '/submissions/recent/' + lastResult + '.js',
			{
				success: function(o)
				{
					Global.CurrentRequest = null;
					var viewData = YAHOO.lang.JSON.parse(o.responseText);

					// The following code should only be run in the case of infinite scrolling the recent submissions.
					//YAHOO.util.Assert.areEqual("recentContributions", viewData[0].Key);

					var elNewContent = document.createElement("div");
					elNewContent.innerHTML += viewData[0].Value;
					$('recentContributions').appendChild(elNewContent);
					$D.batch($$('#recentContributions .contribContainer'), function(item)
					{
						// Only reftag/edit new contributions.
						var contribId = parseInt(reGetContribId.exec(item.id)[1]);
						if (contribId < lastResult)
						{
							$D.batch($$('span.recentPreview', item), function(preview)
							{
								if (preview.innerHTML != null && preview.innerHTML != '')
								{
									preview.innerHTML = Edit.FormatString(preview.innerHTML).replace(/<\/?(?:(?!cite)[^>])*>/ig, ' ').replace(/\s+/, ' ').replace('&amp;nbsp;', '&nbsp;');
								}
							});
						}
					});

					Logos.ReferenceTagging.tag($('recentContributions').lastChild);

					$D.batch($$('div.lbsTooltip'), function(item)
					{
						var elTooltip = new $EL(item);
						elTooltip.setStyle('visibility', 'hidden');
					});
				},
				failure: function(o)
				{
					Global.CurrentRequest = null;
					Global.ShowContentLoading('error');
				}
			});
		}
	},

	GetLocation: function()
	{
		var loc = window.location;
		var link = loc.protocol + '//' + loc.host;

		var contentState = $H.getCurrentState('content');
		if (/^\/profile\//.test(contentState))
		{
			link += '/profile/' + Profile.Current.ProfileToken;
		}
		else if (/^\/submissions\//.test(contentState))
		{
			link += contentState;
			if ($('sermonTitle') != null)
			{
				link += '-' + $('sermonTitle').innerHTML.trim().replace(/[^\w]+/g, '-');
			}
		}
		else
		{
			link += contentState;
		}

		var states = {};
		if ($H.getCurrentState('q') != '')
			states['q'] = $H.getCurrentState('q');
		if ($H.getCurrentState('tab') != 'paneTabHome')
			states['tab'] = $H.getCurrentState('pane');
		if ($H.getCurrentState('pane') != 'homePane')
			states['tab'] = $H.getCurrentState('tab');
		var statesHash = '#';
		for (var key in states)
		{
			statesHash += key + '=' + escape(states[key]) + '&';
		}
		link += statesHash.slice(0, -1);

		return link;
	},

	ShowLinkToPage: function()
	{
		if (Global.LinkToPageOverlay == null)
		{
			Global.LinkToPageOverlay = new YAHOO.widget.Overlay('linkToPageOverlay', { context: ['linkToPage', 'tr', 'br'],
				width: '350px'
			});
			Global.LinkToPageOverlay.render();
		}

		var link = Global.GetLocation();
		$('linkToPageLink').value = link;

		var linkSurfaceText;
		if ($('sermonTitle') != null)
		{
			var name;
			if ($('authorName') != null)
				name = $('authorName').firstChild.innerHTML;
			else
				name = $('name').innerHTML;
			linkSurfaceText = '<em>' + $('sermonTitle').innerHTML.trim() + '</em> by ' + name.trim();
		}
		else if ($('contributorInfo') != null)
		{
			var elName = $$('#name a', 'contributorInfo', true);
			if (elName == null)
				elName = $$('#name', 'contributorInfo', true);
			linkSurfaceText = elName.innerHTML.trim() + '\'s profile';
		}
		else
		{
			linkSurfaceText = 'Sermons.Logos.com';
		}

		var longLink = '<a target="_blank" href="' + link + '">' + linkSurfaceText + '</a>';
		$('linkToPageLongLink').value = longLink;
		Global.LinkToPageOverlay.show();
	},

	ShowReportPanel: function(id)
	{
		var nWidth = Math.min($D.getViewportWidth() - 30, 500);
		var nHeight = Math.min($D.getViewportHeight() - 30, 250);

		if (Global.ReportPanel == null)
		{
			Global.ReportPanel = new YAHOO.widget.Panel('reportPanel', { fixedcenter: true,
				constraintoviewport: true,
				draggable: false,
				width: nWidth + 'px',
				height: nHeight + 'px',
				underlay: 'none',
				modal: true,
				close: false
			});

			var success = Global.ReportPanel.render();

			Global.ReportPanel.resizeTo = function(panelWidth, panelHeight)
			{
				$D.setStyle(this.innerElement, 'width', panelWidth);
				$D.setStyle(this.innerElement, 'height', panelHeight);
				this.resizeBody(panelWidth, panelHeight);
			};

			Global.ReportPanel.resizeBody = function(panelWidth, panelHeight)
			{
				// QUIRKS FLAG, FOR BOX MODEL
				var IE_QUIRKS = (YAHOO.env.ua.ie && document.compatMode == 'BackCompat');

				// UNDERLAY/IFRAME SYNC REQUIRED
				var IE_SYNC = (YAHOO.env.ua.ie == 6 || (YAHOO.env.ua.ie == 7 && IE_QUIRKS));

				// PADDING USED FOR BODY ELEMENT (Hardcoded for example)
				var PANEL_BODY_PADDING = (10 * 2) // 10px top/bottom padding applied to Panel body element. The top/bottom border width is 0

				// TODO: width?

				var headerHeight = this.header ? this.header.offsetHeight : 0; // Content + Padding + Border
				var footerHeight = this.footer ? this.footer.offsetHeight : 0; // Content + Padding + Border

				var bodyHeight = (panelHeight - headerHeight - footerHeight);
				var bodyContentHeight = (IE_QUIRKS) ? bodyHeight : bodyHeight - PANEL_BODY_PADDING;

				$D.setStyle(this.body, 'height', bodyContentHeight + 'px');

				this.sizeUnderlay();
				if (IE_SYNC)
				{
					// Syncing the iframe can be expensive. Disable iframe if you
					// don't need it.
					this.syncIframe();
				}
			};
		}

		$$('.imgPanelSend', 'reportPanel', true).onclick = function() { Edit.ChangeFlags(id, 1, $('reportContent').value, $('reportUserMessage'), function() { Global.ReportPanel.hide(); }); };

		$('reportContent').value = '';
		var characterLimit = 300;
		$('reportUserMessage').innerHTML = characterLimit + ' characters remaining';
		$('reportContent').onkeyup = function()
		{
			if (this.value.length > characterLimit)
				this.value = this.value.substring(0, characterLimit);

			$('reportUserMessage').innerHTML = (characterLimit - this.value.length) + ' characters remaining';
		}

		Global.ReportPanel.resizeTo(nWidth, nHeight);
		Global.ReportPanel.center();
		Global.ReportPanel.showMask();
		Global.ReportPanel.show();

		$('reportContent').focus();
	},

	ExpandList: function(elLink)
	{
		var extList = $D.getPreviousSibling(elLink);

		if ($D.getStyle(extList, 'display') == 'none')
		{
			$D.setStyle(extList, 'display', 'inline');
			elLink.parentNode.removeChild(elLink);
		}
	},

	HtmlEncode: function(input)
	{
		return input.replace(/&(?!nbsp;|amp;|lt;|gt;|quot;|#39;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\'/g, '&#39;');
	},

	ShowLogin: function()
	{
		$D.replaceClass('login', 'hide', 'show');
		$D.replaceClass('register', 'show', 'hide');
		$D.replaceClass('loginRegister', 'hide', 'show');
		$$('#login input', null, true).focus();
	},

	ShowRegister: function()
	{
		$D.replaceClass('login', 'show', 'hide');
		$D.replaceClass('register', 'hide', 'show');
		$D.replaceClass('loginRegister', 'hide', 'show');
		$$('#register input', null, true).focus();
	}
};

function OnLoad()
{
	OnResize();
}

function OnResize()
{
	var rgInfo = $D.getRegion('infoBar');
	var nInfoHeight = rgInfo ? rgInfo.bottom - rgInfo.top : 0;
	var rgSubHeader = $D.getRegion('editSubHeader');
	var rgTopLevelHeader = $D.getRegion('hd');
	var nTopLevelHeaderHeight = rgTopLevelHeader.bottom - rgTopLevelHeader.top;

	var aElements = new Array('commandsPane', 'contentBody', 'infoPane');
	var aOffset = new Array(0, 8, 0);

	if ($('editSubHeader')) aOffset[2] += $('editSubHeader').clientHeight;

	aOffset[1] += rgSubHeader ? rgSubHeader.bottom - rgSubHeader.top : 0;
	aOffset[1] += rgInfo ? nInfoHeight : 0;
	aOffset[2] += rgInfo ? nInfoHeight : 0;

	var elHeader = $('banner');
	var elNav = $('searchBox');
	if ($D.hasClass(elNav, 'inactive'))
		elNav = $('editDetails');

	for (ixElement in aElements)
	{
		var elBody = document.getElementById(aElements[ixElement]);
		if (elBody != null)
			elBody.style.height = ($D.getViewportHeight() - elHeader.clientHeight - elNav.clientHeight - aOffset[ixElement] - nTopLevelHeaderHeight) + 'px';
	}

	aElements = new Array('sermonText', 'sermonPreview', 'txtEditSermon');
	aOffset = new Array(12, 12, 0);
	elHeader = document.getElementById('banner');
	elNav = document.getElementById('editDetails');
	var elEditHeader = document.getElementById('editSermonTextHeader');

	for (ixElement in aElements)
	{
		var elBody = document.getElementById(aElements[ixElement]);
		if (elBody != null)
			elBody.style.height = ($D.getViewportHeight() - elHeader.clientHeight - elNav.clientHeight - elEditHeader.clientHeight - aOffset[ixElement] - (rgInfo ? nInfoHeight : 0) - nTopLevelHeaderHeight) + 'px';
	}

	var elTxt = document.getElementById('editTextContainer');
	var elPreview = document.getElementById('editPreviewContainer');

	if (elTxt !== null && elPreview !== null)
	{
		var elBody = document.getElementById('body');
		var width = elBody.clientWidth;
		elTxt.style.width = (elBody.clientWidth / 2) - 15 + 'px';
		elPreview.style.width = (elBody.clientWidth / 2) - 1 + 'px';
	}
}

YAHOO.util.Event.onDOMReady(Global.Init);

/** Ad/Additional content script. Not part of site behavior */
function restorePackageText()
{
	swapPackageText("basePackage");
}
function swapPackageText(strImgSrc)
{
	var packageImage = document.getElementById("packageImage");
	packageImage.src = 'http://www.logos.com/images/bible.logos.com/img_' + strImgSrc + 'Text.gif';
}

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g, '');
};