//include AFTER presentation.js
var previewPaneName = "previewPaneName";
var previewPaneWindow;
var previewPaneScalingFactor = 0.67;
var previewPaneStateServiceName = "preview.pane.state";
var inPreviewPaneModeKey = "in.preview.pane.mode";
var previewPanePageName = "preview.pane";
var researchTrailPageName = "my.history";
var previewPaneEmptyPageName = "preview.pane.empty";
var inPreviewPaneModeFlag = null;

// Called by handleChildPreviewPaneOnunloadEvent()
function isInPreviewPaneMode()
{
	if (inPreviewPaneModeFlag != null)
		return inPreviewPaneModeFlag;
		
	var element = $("tlrnz_toggle_preview_pane");

	if (element)
	{
		inPreviewPaneModeFlag = element.hasClassName("close");
		return inPreviewPaneModeFlag;
	}
	
	//return true; if we get this far we're still waiting for FetchPreviewPaneMode to finish
	return true;
}

// Called to set initial state of inPreviewPaneModeFlag
// avoid calling the Ajax.Request unless absolutely necessary
function FetchPreviewPaneMode()
{
	//already initialised to something
	if (inPreviewPaneModeFlag != null)
		return;
		
	//if this button exists, server already passed state to UI
	var element = $("tlrnz_toggle_preview_pane");
	if (element)
	{
		inPreviewPaneModeFlag = element.hasClassName("close");
		return;
	}

	//we need to consult the server
	new Ajax.Request(location.pathname + "/" + previewPaneStateServiceName, {method:'get', 
			onSuccess: function(transport){
				var element = transport.responseXML.documentElement;
				if (element)
				{
					var inPreviewPaneMode = element.getAttribute(inPreviewPaneModeKey);
					inPreviewPaneModeFlag = (inPreviewPaneMode == 'true');
				}
				else
					inPreviewPaneModeFlag = false;
			},
			onFailure: function() {inPreviewPaneModeFlag = false;}
		});
}

// Note that some calls are made on the main window and others on either (the calling)
// window. This is to eliminate the need for the preview pane window to make any method calls
// to methods in the opener that make AJAX requests - this is not handled in all
// situations by IE 6 with the default installation.
function togglePreviewPane(button, mainWindow, isContentPage)
{
	// The button object will be undefined if we're on a page that
	// does not have the open/close preview pane button in the document options
	if (!button)
	{
		setClosePreviewPaneState(mainWindow);
		return;
	}

	// toggle the preview pane message
	if (button.className == "close")
	{
		button.className = "open";
		button.title = "Open the Preview Pane";
		button.childNodes[0].nodeValue = "Open Preview Pane";

		setClosePreviewPaneState(mainWindow);
	}
	else if (button.className == "open")
	{
		button.className = "close";
		button.title = "Close the Preview Pane";
		button.childNodes[0].nodeValue = "Close Preview Pane";

		mainWindow.openPreviewPane(isContentPage);
		persistAndSetNavSidebarState(mainWindow);
		persistAndSetClosePreviewPaneState(true, mainWindow);
		mainWindow.resizeTo(screen.availWidth*previewPaneScalingFactor, screen.availHeight);
		mainWindow.moveTo(0,0);
	}
}

function setClosePreviewPaneState(mainWindow)
{
	restoreNavbarState(mainWindow);
	mainWindow.resizeTo(screen.availWidth, screen.availHeight);
	mainWindow.moveTo(0,0);
	persistAndSetClosePreviewPaneState(false, mainWindow);
	mainWindow.closePreviewPane();
}

function persistAndSetClosePreviewPaneState(flag, mainWindow)
{
	state = new Boolean(flag);
	persistPreviewPaneSetting(inPreviewPaneModeKey, state.toString());
	mainWindow.inPreviewPaneModeFlag = state.valueOf();

}

// Toggles the Preview Pane My Selections button state and also
// the main window My Selections Document Options button, if it currently exists.
function togglePreviewPaneMySelections(uri, button)
{
	var uriWithoutPreviewPane = getUriForMainView(uri);

	toggleMySelections(uriWithoutPreviewPane, button);

	// If the preview pane has the same document ID as the main window,
	// toggle the main window My Selections control.
	var documentIdExtractionRegex = /^.*\/([^?]*).*$/;
	var toggleOpenerSelectionElement = opener.document.getElementById('tlrnz_toggle_selection');
	if (uriWithoutPreviewPane.replace(documentIdExtractionRegex, "$1") == opener.location.href.replace(documentIdExtractionRegex, "$1")
		&& toggleOpenerSelectionElement)
	{
		toggleMySelections(uriWithoutPreviewPane, toggleOpenerSelectionElement);
	}
	
	// This code handles when we're on MySelections page.
	// Need to delay the call to reload because the previous requests to toggle the My Selections
	// state must complete on the server before the reload will work correctly.
	if (!toggleOpenerSelectionElement)
		setTimeout("opener.location.reload(true)", 200);
}

function loadPreviewPaneContentInMain(uri)
{
	opener.location = getUriForMainView(uri);
}

// Prepare the URI for Load into the Main Window Pane 
// - Strip Extraneous References from the URI.
function getUriForMainView(uri)
{
    var uriForMainView = uri; // Current URI.

    var stripPreviewPanePageNameRegex = new RegExp("^(.*)\/" + previewPanePageName + "(.*)$");     // RegEx to Remove "Preview Pane" reference from URI.
    var stripResearchTrailPageNameRegex = new RegExp("^(.*)\/" + researchTrailPageName + "(.*)$"); // RegEx to Remove "Research Trail" reference from URI.

    uriForMainView = uriForMainView.replace(stripPreviewPanePageNameRegex, "$1$2");   // URI - "Preview Pane" reference removed!
    uriForMainView = uriForMainView.replace(stripResearchTrailPageNameRegex, "$1$2"); // URI - "Research Trail" reference removed!
    
    return uriForMainView; // URI for Main View - Extraneous references Removed.
}

function openPreviewPane(isContentPage)
{
	var openUrl;
	if (isContentPage)
	{
		// If we're on a content page then load that content into the preview pane.
		openUrl = location.pathname + "/" + previewPanePageName + location.search + location.hash;
	}
	else
	{
		// When we initially open the 'empty' preview pane we can trim off most of the path of the URL
		var pathnameArray = location.pathname.split('/');
		// Keep the first two non-empty path name elements only
		pathnameArray.splice(3);

		openUrl = pathnameArray.join('/') + '/' + previewPaneEmptyPageName + location.search + location.hash;
	}

	previewPaneWindow = window.open(openUrl, previewPaneName, getPreviewPaneOpenFeatures());

	// (Buggy) IE opens the PP window behind the Windows taskbar. So calling resizeTo() readjusts this.
	previewPaneWindow.resizeTo(screen.availWidth*(1-previewPaneScalingFactor), screen.availHeight);

	window.focus();
}

function getPreviewPaneOpenFeatures()
{
	var openFeatures = [];

	openFeatures.push('width='+screen.availWidth*(1-previewPaneScalingFactor-0.01));
	openFeatures.push('height='+screen.availHeight);
	openFeatures.push('left='+(screen.availWidth*previewPaneScalingFactor + 2));
	openFeatures.push('screenX='+(screen.availWidth*previewPaneScalingFactor + 2));
	openFeatures.push('screenY=0');
	openFeatures.push('top=0');
	openFeatures.push('scrollbars=yes');
	openFeatures.push('status=yes');
	openFeatures.push('toolbar=no');
	openFeatures.push('menubar=no');
	openFeatures.push('location=no');
	openFeatures.push('resizable=yes');
	openFeatures.push('dependent=no');

	return openFeatures.join(',');
}

function closePreviewPane()
{
	// Get the handle to the preview pane if the main window has lost it.
	if (!previewPaneWindow)
	{
		previewPaneWindow = window.open('', previewPaneName);
	}

	if (!previewPaneWindow.closed)
	{
		previewPaneWindow.close();
	}
}

function persistAndSetNavSidebarState(mainWindow)
{
	// Collapse navigation pane if it is not already collapsed.
	if (navSidebarIsHidden(mainWindow))
	{
		persistPreviewPaneSetting("leftbar.hidden", "true");
	}
	else
	{
		persistPreviewPaneSetting("leftbar.hidden", "false");
		mainWindow.toggleNavSidebar();
	}
}

function restoreNavbarState(mainWindow)
{
	new Ajax.Request(location.pathname + "/" + previewPaneStateServiceName, {method:'get',
		onSuccess: function(transport){
				var element = transport.responseXML.documentElement;
				if (element)
				{
					var leftNavbarWasInitiallyHidden = element.getAttribute("leftbar.hidden");
		
					// Expand navigation pane if it is not already expanded, and it was initially expanded.
					if (navSidebarIsHidden(mainWindow) && leftNavbarWasInitiallyHidden == "false")
					{
						mainWindow.toggleNavSidebar();
					}
				}
			}
		});
}

function navSidebarIsHidden(mainWindow)
{
	var nav = $(mainWindow.document.getElementById("navSidebar"));
	return nav.hasClassName('tlrnz_leftbar_hidden');
}

function persistPreviewPaneSetting(name, value)
{
	new Ajax.Request(location.pathname + "/" + previewPaneStateServiceName, {method:'put', parameters:{name:value}});
}

// Suppress links in the preview pane content.
function suppressLinks()
{
    // Check to see we're in the preview pane window. This technique is more reliable than checking the name.
    if ($('previewPane') != null)
    {
			suppressLinksWithinElement('Content');
			suppressLinksWithinElement('crumbs');
    }
}

function suppressLinksWithinElement(elementName)
{
	var parentElement = $(elementName);
	if (parentElement)
	{
		var contentLinks = parentElement.getElementsByTagName('a');
		for (var i = 0; i < contentLinks.length; i++)
		{
			contentLinks[i].setAttribute("onclick", "return false");
			contentLinks[i].removeAttribute("href");
		}
	}
}

function previewOnLoad()
{
	suppressLinks();
	FetchPreviewPaneMode();
	window.setInterval("handleChildPreviewPaneOnunloadEvent()", 500);
}

document.observe("dom:loaded",previewOnLoad);

// Correctly manage the state of the preview pane when the user clicks the built-in close
// button on the preview pane browser window.
function handleChildPreviewPaneOnunloadEvent()
{
    //if the flag has not been set, we don't know our state yet
    if (inPreviewPaneModeFlag == null)
        return;

    // Check this is not the preview pane window.
    // Don't need to do anything if not in preview mode
    if ($('previewPane') != null || !window.isInPreviewPaneMode())
        return;

	// Get the handle to the preview pane if the main window has lost it.
	if (!previewPaneWindow)
	{
		previewPaneWindow = window.open('', previewPaneName);

		// The location won't be empty if the window was already open.
		if (previewPaneWindow.location.href == "")
		{
			// It appears the preview pane window was closed by the user. Toggling will close it properly.
			togglePreviewPane($("tlrnz_toggle_preview_pane"), self);
		}
	}
	else if (previewPaneWindow.closed)
	{
		// It appears the preview pane window was closed by the user. Toggling will close it properly.
		togglePreviewPane($("tlrnz_toggle_preview_pane"), self);
	}
}
