/// <reference path="../../combo.js" />
/// <reference path="Page.js" />
/// <reference path="Book.js" />
/// <reference path="Search.js" />
/// <reference path="Highlighter.js" />

// Defines utility objects for commonly used values.
var $C = YAHOO.util.Connect;
var $D = YAHOO.util.Dom;
var $E = YAHOO.util.Event;
var $EL = YAHOO.util.Element;
var $H = YAHOO.util.History;
var $L = YAHOO.log;
var $S = YAHOO.util.Selector;
var $ = $D.get;
var $$ = $S.query;

var Global =
{
	ContentVersion: '1.0',
	// Google Analytics page tracking
	TrackPageView: function(url)
	{
		var args = ['_trackPageview'];
		if (url) args.push(url);

		_gaq.push(args);
	},

	Init: function()
	{
		if (!Global.ContentServerPath)
			Global.ContentServerPath = 'http://common.logos.com/' + Global.ContentVersion + '/';

		Page.Init();
		Search.Init();
		Book.Init();
	},

	ShowLogin: function()
	{
		$D.replaceClass('login', 'hide', 'show');
		$D.replaceClass('register', 'show', 'hide');
		$$('#login input', null, true).focus();
	},

	NavigateTo: function(location)
	{
		Page.HideInfoBar();

		var loc = (/.*\.js/).test(location) ? location : location + '.js';

		if (Search.QueryBookOnLoad && (/books\//).test(location))
			loc += '?query=' + encodeURIComponent(Search.QueryBookOnLoad);

		Search.QueryBookOnLoad = null;

		Global.TrackPageView(loc);
		Page.ShowContentLoading();
		$C.asyncRequest('get', loc,
		{
			success: function(o)
			{
				var viewData = YAHOO.lang.JSON.parse(o.responseText);

				var parameters = {};

				for (var i in viewData)
				{
					if (!(/Param_/).test(viewData[i].Key))
						$(viewData[i].Key).innerHTML = viewData[i].Value;
					else
						parameters[viewData[i].Key.replace('Param_', '')] = viewData[i].Value;
				}

				Global.InitContent(parameters);

				if (Logos.Chrome && Logos.Chrome.AdRotator && $('adSpace'))
					Logos.Chrome.AdRotator.StartRotation('adSpace', 30000);
			},
			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
					Logos.Chrome.InfoBar.Show("infoBar", "Sorry, there was an error processing your request.", true, Page.OnResize);
			}
		});
	},

	BrowseTo: function(location, states)
	{
		states = states || {};
		states['content'] = location;

		$H.multiNavigate(states);
	},

	InitContent: function(parameters)
	{
		if (parameters['BookId'])
		{
			Book.ImageTypeOverride = (parseInt(parameters['DefaultImageType']) == 2) ? 2 : null;

			Book.OnInit = function()
			{
				Book.RenderLayout(parseInt(parameters.ImageCount, 10), 'bookContent');
				Book.CurrentBookId = Number(parameters['BookId']);
				if (parseInt(parameters.TitlePageOffset, 10) >= 0)
					Book.TitleImage = parseInt(parameters.TitlePageOffset, 10);
			};

			Book.Init();
			Page.OnResize();

			if (parameters['SearchViewData'])
				Search.ProcessBookViewData(parameters['SearchViewData']);
		}
	},

	GetLocation: function()
	{
		var loc = window.location;
		var link = loc.protocol + '//' + loc.host;
		var contentPath = $H.getCurrentState('content');
		if (contentPath && contentPath != '/home')
			link += contentPath;

		return link;
	},

	ShowLinkToPage: function()
	{
		if (!Global.LinkToPageOverlay)
		{
			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;
		var titleContainer = $$('.simpleHeader', $('titleContainer'), true);
		if (titleContainer)
			linkSurfaceText = '<em>' + titleContainer.innerHTML.trim() + '</em>';
		else
			linkSurfaceText = 'Books.Logos.com';

		var longLink = '<a target="_blank" href="' + link + '">' + linkSurfaceText + '</a>';
		$('linkToPageLongLink').value = longLink;
		Global.LinkToPageOverlay.show();

		return false;
	},

	ShowSearchHelp: function()
	{
		var nWidth = Math.min($D.getViewportWidth() - 30, 600);
		var nHeight = Math.min($D.getViewportHeight() - 30, 600);

		if (typeof (Search.SearchHelpPanel) === 'undefined' || Search.SearchHelpPanel === null)
		{
			Search.SearchHelpPanel = new YAHOO.widget.Panel('searchHelpPanel', { fixedcenter: true,
				constraintoviewport: true,
				draggable: true,
				width: nWidth + 'px',
				height: nHeight + 'px',
				underlay: 'none'
			});
			var success = Search.SearchHelpPanel.render();

			Search.SearchHelpPanel.resizeTo = function(panelWidth, panelHeight)
			{
				$D.setStyle(this.innerElement, 'width', panelWidth);
				$D.setStyle(this.innerElement, 'height', panelHeight);
				this.resizeBody(panelWidth, panelHeight);
			};

			Search.SearchHelpPanel.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();
				}
			};
		}
		Search.SearchHelpPanel.resizeTo(nWidth, nHeight);
		Search.SearchHelpPanel.center();
		Search.SearchHelpPanel.show();
	}
};

String.prototype.HtmlEncode = function()
{
	return this.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;');
};

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g, '');
};