//----------------------------------------------------------------------------
// Names of FileCabinet application preferences
//----------------------------------------------------------------------------
var FileCabinetPref_LibraryOpenTOCAtStart = "Library_OpenTOCAtStart";
var FileCabinetPref_LibraryOnePageMode = "Library_OnePageMode";
var FileCabinetPref_SearchResOpenTOCAtStart = "SearchRes_OpenTOCAtStart";
var FileCabinetPref_SearchResOnePageMode = "SearchRes_OnePageMode";
//----------------------------------------------------------------------------
// page constants:
var FileCabinetPage_Home = 0;
var FileCabinetPage_Library = 1;
var FileCabinetPage_Viewer = 2;
var FileCabinetPage_SearchRes = 3;

//----------------------------------------------------------------------------
// Names of FileCabinet application commands
//----------------------------------------------------------------------------
var OwcCmd_SendByEMail = "sendbyemail";
var OwcCmd_ShowMetadata = "showmetadata";

//#############################################################################
//#                                                                           #
//#                    FileCabinetApp class implementation                    #
//#                                                                           #
//#############################################################################
function FileCabinetApp_ApplyPrototype(rObject)
{
	rObject.onSettingsLoaded = FileCabinetApp_onSettingsLoaded;

	// Operations on frames
	rObject.m_sFrameHeader = "FC_HeaderFrame"; // name of the frame that contains tabs
	rObject.m_sFrameContent = "FC_ContentFrame"; // name of the frame that contains application pages
	rObject.m_sAdvSearchWinId = "pageAdvSearch"; // pageId of the advanced search popup window
	rObject.m_iActivePage = FileCabinetPage_Home;
	rObject.m_bContentPageLoaded  = false;
	rObject.m_bViewerPageLoaded = false;
	rObject.m_sDocUid = null;
	rObject.m_sDocHRef = null;
	rObject.m_bAdvSearchMayBeClosed = true;//false for Safari

	rObject.getActivePageIndex = FileCabinetApp_getActivePageIndex;
	rObject.ActivatePage = FileCabinetApp_ActivatePage;
	rObject.getControlFromPage = FileCabinetApp_getControlFromPage;
	rObject.getHtmlElemFromPage = FileCabinetApp_getHtmlElemFromPage;
	rObject.getPageDocument = FileCabinetApp_getPageDocument;
	rObject.getPageObject = FileCabinetApp_getPageObject;
	rObject.onPageLoaded = FileCabinetApp_onPageLoaded;
	rObject.parseURL = FileCabinetApp_parseURL; //replace function from base class
	rObject.buildURL = FileCabinetApp_buildURL; //replace function of base class
	rObject.onPrint = FileCabinetApp_onPrint;	//printing event handler

	// Command handlers
	rObject.ShowHome = FileCabinetApp_ShowHome;
	rObject.ShowLibrary = FileCabinetApp_ShowLibrary;
	rObject.ShowViewer = FileCabinetApp_ShowViewer;
	rObject.ShowSearchRes = FileCabinetApp_ShowSearchRes;
	rObject.ShowAdvancedSearch = FileCabinetApp_ShowAdvancedSearch;
	rObject.SendItemByMail = FileCabinetApp_sendItemByMail;
	rObject.ShowItemMetadata = FileCabinetApp_showItemMetadata;
	rObject.updateCommandUiState = FileCabinetApp_updateCommandUiState;
	
	rObject.Search = FileCabinetApp_Search;
	rObject.Print = FileCabinetApp_Print;
	rObject.ViewDocument = FileCabinetApp_ViewDocument;
	rObject.ViewDocumentSearchRes = FileCabinetApp_ViewDocumentSearchRes;
	rObject.ViewDocumentCommon = FileCabinetApp_ViewDocumentCommon;

	// Internal methods (used by pages)
	rObject.lookupDate = FileCabinetApp_lookupDate;
	rObject.lookupFolder = FileCabinetApp_lookupFolder;
	rObject.setLibrarySearchForm = FileCabinetApp_setLibrarySearchForm;
	
	rObject.browserSnifferWinPlatform = FileCabinetApp_browserSnifferWinPlatform;//cross-window adv search fails on Mac

	// Commands
	Olive.CmdTarget.RegisterCommand(rObject, "ShowHome", "ShowHome");
	Olive.CmdTarget.RegisterCommand(rObject, "ShowLibrary", "ShowLibrary");
	Olive.CmdTarget.RegisterCommand(rObject, "ShowViewer", "ShowViewer");
	Olive.CmdTarget.RegisterCommand(rObject, "ShowSearchRes", "ShowSearchRes");
	Olive.CmdTarget.RegisterCommand(rObject, "ShowAdvancedSearch", "ShowAdvancedSearch");
	Olive.CmdTarget.RegisterCommand(rObject, OwcCmd_SendByEMail, "SendItemByMail", "updateCommandUiState");
	Olive.CmdTarget.RegisterCommand(rObject, OwcCmd_ShowMetadata, "ShowItemMetadata", "updateCommandUiState");
	Olive.CmdTarget.RegisterCommand(rObject, "Search", "Search");
	Olive.CmdTarget.RegisterCommand(rObject, "ViewDocument", "ViewDocument");
} // FileCabinetApp_ApplyPrototype()

function FileCabinetApp()
{
	this.onSearchRequest = FileCabinetApp_onSearchRequest;
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                              Implementation                               //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////
function FileCabinetApp_onSettingsLoaded()
{
	// Enable debugging features if Debug=true URL parameter is passed
	if (this.m_oQueryString)
	{
		// TODO: Check for debug mode
		var bDebugMode = String_parseBoolean(this.m_oQueryString.getParam("Debug", 0), false);
		if (bDebugMode)
		{
			this.enableDebugMode();
			alert("Debug mode is enabled");
		}
	} // {if} Enable debugging features if Debug=true URL parameter is passed

	// Update window title
	document.title = this.getResString("WindowCaption");
	
	// Update initial frame index (from application preferences)
	this.m_iActivePage = this.getPreferenceNumber("InitialTab", FileCabinetPage_Home);

	// Parse URL parameters
	this.parseURL();

	// Set active page to pageViewer; depends on parseURL() above.
	if (this.m_sDocHRef != null || this.m_sDocUid != null)
		this.m_iActivePage = FileCabinetPage_Viewer;

	if( !this.browserSnifferWinPlatform() )
	{
		this.m_bAdvSearchMayBeClosed = false;
		if( isSafari() )
		{
			DHTML_attachEvent(window.top, "unload", FileCabinetApp_disableOnBeforeUnload);
		}	
	}
} // FileCabinetApp_onSettingsLoaded()

function FileCabinetApp_onPageLoaded(oEvent)
{
	var oPage = oEvent.srcObject;
	var bInitShowDocument = false;
	
	if (oPage.m_sPageId == "pageHeader")
	{
		var oTabControl = oPage.findControlById("tabPages");
		oTabControl.setActiveItem(this.m_iActivePage, false);
		oTabControl.attachOwcEventHandler("itemActivated", FileCabinetApp_onTabClicked, this);
	}
	else if (oPage.m_sPageId == "pageContent")
	{
		var oPageSwitcherControl = oPage.findControlById("ctrlPageSwitcher");
		oPageSwitcherControl.setActiveItem(this.m_iActivePage, false);

		this.m_bContentPageLoaded  = true;
		bInitShowDocument = this.m_bViewerPageLoaded;
	}
	else if (oPage.m_sPageId == "pageViewer")
	{
		this.m_bViewerPageLoaded = true;
		bInitShowDocument = this.m_bContentPageLoaded;
	}

	if (bInitShowDocument && ((this.m_sDocHRef != null) || (this.m_sDocUid!=null)))
		this.ViewDocumentCommon(this.oCmdParams, false, false);
}

function FileCabinetApp_onSearchRequest(oEvent)
{
	this.Search(oEvent.SearchParams);
} // FileCabinetApp_onSearchRequest()

function FileCabinetApp_setLibrarySearchForm(oSrcSeQuery)
{
	// Copy search query from advanced search form to regular search form
	var oSearchForm = this.getControlFromPage(FileCabinetPage_Library, "ctrlSearchForm");
	//Copy only common parameters to the search form
	oSearchForm.updateData();
	var oSearchQuery = oSearchForm.getValue();
	oSearchQuery.copySearchInField("Text", oSrcSeQuery);
	oSearchForm.updateControl();
}

function FileCabinetApp_onTabClicked(oEvent)
{
	this.ActivatePage(oEvent.activeItemIndex, true);
}

//-----------------------------------------------------------------------------
// Internal methods (used by pages)
//-----------------------------------------------------------------------------
function FileCabinetApp_lookupDate(oUpdateControl)
{
	var oPage = oUpdateControl.getOwnerPage();
	var oArguments = { controlLookup : oUpdateControl, initValue : oUpdateControl.getHtmlValue() };
	oPage.openPopup("Calendar.htm", "LookupDate", oArguments);
} // FileCabinetApp_lookupDate()

function FileCabinetApp_lookupFolder(oUpdateControl, oInitValue)
{
	var oPage = oUpdateControl.getOwnerPage();
	var oArguments = { controlLookup : oUpdateControl, initValue : oInitValue };
	oPage.openPopup("ChooseFolder.htm", "LookupFolder", oArguments);
}

//-----------------------------------------------------------------------------
// Application commands
//-----------------------------------------------------------------------------
function FileCabinetApp_Search(oSearchQuery)
{
	var oSearchRes = this.getControlFromPage(FileCabinetPage_SearchRes, "divSearchRes");
	oSearchRes.loadSearchResults(oSearchQuery);
	this.ShowSearchRes();
} // FileCabinetApp_Search()

function FileCabinetApp_Print(sDocHRef, sPagesArr, sPageFormat, sPrintScale)
{
	var oPage = Olive.Page.GetPageForWindow(window);

	// TODO: Move creation of data items to SDK
	var oPrintData = new Olive.ContentItem.Print();
	oPrintData.m_sDocHRef = sDocHRef;
	oPrintData.m_sPagesToPrint = sPagesArr;
	oPrintData.m_sPageFormat = sPageFormat;
	oPrintData.m_sPrintScale = sPrintScale;

	var oArguments = { contentItem : oPrintData };
	oPage.openPopup("Print.htm", "PrintView", oArguments);
} // FileCabinetApp_Print()

function FileCabinetApp_ViewDocument(oCmdParams) 
{
	var bTOCAtStart = this.getPreferenceBoolean(FileCabinetPref_LibraryOpenTOCAtStart, false);
	var bOnePageMode = this.getPreferenceBoolean(FileCabinetPref_LibraryOnePageMode, false);
	this.ViewDocumentCommon(oCmdParams, bTOCAtStart, bOnePageMode);
} // FileCabinetApp_ViewDocument()

function FileCabinetApp_ViewDocumentSearchRes(oCmdParams) 
{
	var bTOCAtStart = this.getPreferenceBoolean(FileCabinetPref_SearchResOpenTOCAtStart, false);
	var bOnePageMode = this.getPreferenceBoolean(FileCabinetPref_SearchResOnePageMode, false);
	this.ViewDocumentCommon( oCmdParams, bTOCAtStart, bOnePageMode);
} // FileCabinetApp_ViewDocumentSearchRes()

function FileCabinetApp_ViewDocumentCommon( oCmdParams, bTOCAtStart, bOnePageMode )
{
	// Delegate call to the Viewer page
	var oViewerWebPage = this.getPageObject(FileCabinetPage_Viewer);
	oViewerWebPage.viewDocument( oCmdParams, bTOCAtStart, bOnePageMode );
	// Switch to viewer page
	this.ShowViewer();
} // FileCabinetApp_ViewDocumentCommon()

function FileCabinetApp_ShowHome()
{
	this.ActivatePage(FileCabinetPage_Home);
} // ShowHome()

function FileCabinetApp_ShowLibrary()
{
	this.ActivatePage(FileCabinetPage_Library);
} // ShowLibrary()

function FileCabinetApp_ShowViewer()
{
	this.ActivatePage(FileCabinetPage_Viewer);
} // ShowViewer()

function FileCabinetApp_ShowSearchRes()
{
	this.ActivatePage(FileCabinetPage_SearchRes);
} // ShowSearchRes()

function FileCabinetApp_ShowAdvancedSearch(sCommandParams)
{
	var oInitSearchQuery = null;
	// Copy initial search query from the regular search form
	var oSearchForm = this.getControlFromPage(FileCabinetPage_Library, "ctrlSearchForm");
	oSearchForm.updateData();
	oInitSearchQuery = oSearchForm.getValue();
	var oNewSearchQuery = new Olive.Data.SearchQuery();
	oNewSearchQuery.copySearchInField("Text", oInitSearchQuery);
	var bOkToOpen = true;

	// Open advanced search popup window
	if( !this.m_bAdvSearchMayBeClosed )//Safari will show the onbeforeunload warning if we reopen it - so we will focus it
	{
		var oTopPage = Olive.Page.GetPageForWindow( window.top );
		if( oTopPage )
		{
			var oAdvSearchWin = oTopPage.getPopupByPageId( this.m_sAdvSearchWinId );
			if( oAdvSearchWin && oAdvSearchWin.windowObject && oAdvSearchWin.windowObject.focus )
			{
				oAdvSearchWin.windowObject.focus();//TODO: put oNewSearchQuery into the adv.search HTML
				bOkToOpen = false;
			}
		}
	}
	if( bOkToOpen )
	{
		var oPage = Olive.Page.GetPageForWindow(window);
		oPage.openPopup("AdvSearch.htm", "AdvancedSearch", oNewSearchQuery);
	}
} // FileCabinetApp_ShowAdvancedSearch()
function FileCabinetApp_onPrint(oEvent)
{
	var oPage = null;
	if (oEvent && oEvent.srcObject)
		oPage = oEvent.srcObject.getOwnerPage();
	if(!oPage)
		return;
		
	// build query string for print:
	oQueryString = new QueryString();
	oQueryString.addParam("sBaseHref", oEvent.sBaseHref);
	oQueryString.addParam("bMultilayer", oEvent.bMultilayer);	
	oQueryString.addParam("PageHeight", oEvent.PageHeight);
	oQueryString.addParam("PageWidth", oEvent.PageWidth);
	oQueryString.addParam("defaultImgExt", oEvent.defaultImgExt);
	oQueryString.addParam("textImgExt", oEvent.textImgExt);	
	oQueryString.addParam("graphicImgExt", oEvent.graphicImgExt);
	oQueryString.addParam("Resolution", oEvent.Resolution);
	oQueryString.addParam("BookLength", oEvent.BookLength);
	oQueryString.addParam("LeftPage", oEvent.LeftPage);
	oQueryString.addParam("RightPage", oEvent.RightPage);
	oQueryString.addParam("sDataProto", oEvent.sDataProto);
	var sURL = "PrintForm.htm?" + oQueryString.getQueryString();
	oPage.openPopup(sURL, "PrintForm");	
}

// Handler for the "Send by e-mail" command
function FileCabinetApp_sendItemByMail(oSrc)
{
	var oPage = oSrc.getOwnerPage();
	var oContentItem = Olive.Controls.IDataBound.getContentItem(oSrc);
	var oArguments = this.prepareItemMailParams(oContentItem);
	oPage.openPopup("SendMail.htm", "SendMail", oArguments);
} // FileCabinetApp_sendItemByMail()

// Handler for the "Show metadata" command
function FileCabinetApp_showItemMetadata(oSrc)
{
	var oPage = oSrc.getOwnerPage();
	var oContentItem = Olive.Controls.IDataBound.getContentItem(oSrc);
	var oArguments = { contentItem : oContentItem };
	oPage.openPopup("ShowMetadata.htm", "Metadata", oArguments);
} // FileCabinetApp_showItemMetadata()

function FileCabinetApp_updateCommandUiState(oCmdUiState)
{
	var bEnableCommand = false;
	if (oCmdUiState.commandParams)
	{
		var oSrcContentItem = Olive.Controls.IDataBound.getContentItem(oCmdUiState.commandParams);
		if (oSrcContentItem)
		{
			var sDataObjectType = oSrcContentItem.DataObjectType;
			bEnableCommand = ((sDataObjectType == OwcContentItem_Document) || 
								(sDataObjectType == OwcContentItem_Entity) || 
								(sDataObjectType == OwcContentItem_TocEntry) || 
								(sDataObjectType == OwcContentItem_Page) || 
								(sDataObjectType == OwcContentItem_SearchResult));
			if (bEnableCommand && 
				(oCmdUiState.commandName.toLowerCase() == OwcCmd_ShowMetadata) &&
				(sDataObjectType == OwcContentItem_TocEntry))
			{
				if (!oSrcContentItem.m_bIsInformationComponent)
					bEnableCommand = false;
			}
		}
	} // {if} Command 

	oCmdUiState.enableCommand(bEnableCommand);
} // FileCabinetApp_updateCommandUiState()

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                            Operations on frames                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////
function FileCabinetApp_getActivePageIndex()
{
	return this.m_iActivePage;
}

function FileCabinetApp_getControlFromPage(iPage, sControlId)
{
	return OwcGetControlFromHtmlElem(this.getHtmlElemFromPage(iPage, sControlId));
}

function FileCabinetApp_getHtmlElemFromPage(iPage, sControlId)
{
	var oPageDoc = this.getPageDocument(iPage);
	return (oPageDoc ? getObjFromDoc(oPageDoc, sControlId) : null);
}

function FileCabinetApp_getPageDocument(iPage)
{
	var oContentFrame = eval("window.top." + this.m_sFrameContent);
	if (!oContentFrame)
		return null;
	var oContentPage = Olive.Page.GetPageForWindow(oContentFrame);
	var oPageSwitcherControl = oContentPage.findControlById("ctrlPageSwitcher");
	if (!oPageSwitcherControl)
		return null;

	var oPageFrame = oPageSwitcherControl.getItem(iPage);
	if (!oPageFrame || !oPageFrame.HtmlElement)
		return null;
	var oPageDoc = DHTML_GetIFrameDocument(oPageFrame.HtmlElement);
	return (oPageDoc ? oPageDoc : null);
}

function FileCabinetApp_getPageObject(iPage)
{
	var oPageDocument = this.getPageDocument(iPage);
	if (!oPageDocument)
		return null;
	var oWebPage = Olive.Page.GetPageForDocument(oPageDocument);
	return oWebPage;
}

/******************************************************************************
 * Function : ActivatePage()
 * Overview : Switches to the page specified by index
******************************************************************************/
function FileCabinetApp_ActivatePage(iPageIndex, bIgnoreEmptyContent)
{
	if (this.m_iActivePage == iPageIndex)
		return false;

	// Select correct tab in header
	var oHeaderFrame = eval("window.top." + this.m_sFrameHeader);
	var oHeaderPage = Olive.Page.GetPageForWindow(oHeaderFrame);
	var oTabControl = oHeaderPage.findControlById("tabPages");
	oTabControl.setActiveItem(iPageIndex);

	// Retrieve previous and next page IFRAME elements
	var oContentFrame = eval("window.top." + this.m_sFrameContent);
	var oContentPage = Olive.Page.GetPageForWindow(oContentFrame);
	if (oContentPage)
	{
		// Content page is loaded
		var oPageSwitcherControl = oContentPage.findControlById("ctrlPageSwitcher");
		oPageSwitcherControl.setActiveItem(iPageIndex);
	}

	this.m_iActivePage = iPageIndex;
	return true;
} // ActivatePage()

function FileCabinetApp_parseURL()
{
	if (!this.m_oQueryString)
		return;

	// Read query string parameters
	var nDocUid = parseInt(this.m_oQueryString.getParam("DocUid", 0), 10);
	if (!isNaN(nDocUid))
		this.m_sDocUid = nDocUid.toString();
	
	var sDocHRef = this.m_oQueryString.getParam("DocHRef", 0);
	if (sDocHRef)
		this.m_sDocHRef = sDocHRef.replace(/\\/g, "/");

	if  (this.m_sDocHRef != null || this.m_sDocUid != null)
	{
		var oCmdParams = new Olive.ContentItem.Document();
		oCmdParams.m_sDocHRef = this.m_sDocHRef;
		oCmdParams.m_sDocUid = this.m_sDocUid;
		
		var sEntityId = this.m_oQueryString.getParam("EntityId", 0);
		if (sEntityId && sEntityId != "") oCmdParams.m_sEntityId = sEntityId;
		
		var nPageNo = parseInt(this.m_oQueryString.getParam("PageNo", 0), 10);
		if (!isNaN(nPageNo))  oCmdParams.m_nPageNo = nPageNo;

		var sPageLabel = this.m_oQueryString.getParam("PageLabel", 0);
		if (sPageLabel && sPageLabel!= "")  oCmdParams.m_sPageLabel = sPageLabel;

		var sPrimId = this.m_oQueryString.getParam("PrimId", 0);
		if (sPrimId && sPrimId != "") oCmdParams.m_sPrimId = sPrimId;
		
		this.oCmdParams = oCmdParams;
		this.m_iActivePage = FileCabinetPage_Viewer;
	}
	
	// Read inital tab 
	var sInitialTab = this.m_oQueryString.getParam("Tab", 0);
	if (sInitialTab)
	{
		switch (sInitialTab.toLowerCase())
		{
			case "home":		this.m_iActivePage = FileCabinetPage_Home; break;
			case "library":		this.m_iActivePage = FileCabinetPage_Library; break;
			case "viewer":		this.m_iActivePage = FileCabinetPage_Viewer; break;
			case "searchres":	this.m_iActivePage = FileCabinetPage_SearchRes; break;
			default: Debug.assert(false, "Inavlid URL parameter: '" + sInitialTab + "' is not a valid tab name");
		}
	} // {if} Initial tab was specified in 
} // FileCabinetApp_parseURL()

// function building URL to open application at specified content item
// replace base class function.
function FileCabinetApp_buildURL(oContentItem)	
{
	var sItemLink = this.getAppUrl();
	if (oContentItem && oContentItem.buildQueryString)
		sItemLink += oContentItem.buildQueryString();
	return sItemLink;
} // FileCabinetApp::buildURL()

//---------------- The one and only instance of the application ----------------
JScript_DeriveClass(FileCabinetApp, Olive.WebAppBase);
FileCabinetApp_ApplyPrototype(FileCabinetApp.prototype);

var g_appFileCabinet = new FileCabinetApp();
g_appFileCabinet.initialize();

function OwcGetApplication()
{
	return g_appFileCabinet;
}

function FileCabinetApp_disableOnBeforeUnload()
{
	var oApp = OwcGetApplication();
	if( oApp )
	{
		oApp.m_bAdvSearchMayBeClosed = true;//disable the onbeforeunload warning when closing the app
	}
}
function FileCabinetApp_browserSnifferWinPlatform()//adv.search window can be closed on windows-IE/FF
{
	return navigator.userAgent.toLowerCase().indexOf( "win" ) !=-1;
}