/// <reference path="WebSdk.js" />
{
	function SearchPanePage()
	{
		/// <summary>Viewer HTML page class</summary>
	}

	SearchPanePage.Commands = 
	{
		ShowICViewer    : "ShowICViewer",		
		SortBy	        : "SortBy",
		HideSearchPane  : "HideSearchPane",
		GoToPage  	: "GoToPage"
	};
	
	SearchPanePage.ElementIDs = 
	{
		SearchInThisIssueID       : "searchthisissue",
		SearchInThisPublicationID : "searchthispublication",
		SearchFormTextFieldID     : "searchformtextfield"
	};
	
	SearchPanePage.ResourceStrings = 
	{
		Command_Search      : "Command_Search",
		Label_SearchIn      : "Label_SearchIn",
		Label_InMagazine    : "Label_InMagazine",
		Label_InLibrary     : "Label_InLibrary",
		Label_SearchShow    : "Label_SearchShow",
		Label_Articles      : "Label_Articles",
		Label_Ads           : "Label_Ads",
		Button_Close        : "Button_Close"
	};	
	
	SearchPanePage.DeclareType = function SearchPanePage_DeclareType()
	{
		/// <summary>
		///		Declares methods and properties of SearchPanePage Web page class
		/// </summary>
		//this.DeclareField("m_searchResults", null);
		this.DeclareField("m_docViewerAgg", null);
		this.DeclareField("m_flashViewer", null);
		this.DeclareField("m_searchForm", null);		
		this.DeclareField("m_oHtmlSearchThisIssue", null);	

		// Overrides
		this.OverrideMethod("postInitialize", SearchPanePage_postInitialize);
        this.DeclareMethod("BindDocViewerParts", SearchPanePage_BindDocViewerParts);

		// Command handlers		
		this.DeclareMethod("_onShowICViewer", SearchPanePage_ShowICViewer);
		this.DeclareMethod("_onSearch", SearchPanePage_onSearchRequest);		
		this.DeclareMethod("_onSortBy", SearchPanePage_onSortBy);
		this.DeclareMethod("_updateSortByState", SearchPanePage_updateSortByState);
		this.DeclareMethod("_GoToPage", SearchPanePage_GoToPage);
		this.DeclareMethod("CheckOkToChangeIssue", SearchPanePage_CheckOkToChangeIssue);
					
		// Helper functions
		this.DeclareMethod("_findControls", SearchPanePage_findControls);
		this.DeclareMethod("_getSelectedSearchResult", SearchPanePage_getSelectedSearchResult);		
		this.DeclareMethod("_updateSearchIn", SearchPanePage_updateSearchIn); 
		this.DeclareMethod("_HideSearchPane", SearchPanePage_HideSearchPane);
	};

	SearchPanePage.ApplyPrototype = function SearchPanePage_ApplyPrototype(classProto)
	{
		/// <summary>
		///		Declares events and commands of SearchPanePage Web page class
		/// </summary>
		/// <param name="classProto" type="object">
		///		Reference to the prototype of <see cref="SearchPanePage" /> class.
		///		You may use it to declare commands and events for the class.
		/// </param>		
		Olive.CmdTarget.RegisterCommand(classProto, SearchPanePage.Commands.ShowICViewer, "_onShowICViewer");
		Olive.CmdTarget.RegisterCommand(classProto, SearchPanePage.Commands.SortBy, "_onSortBy", "_updateSortByState");
		Olive.CmdTarget.RegisterCommand(classProto, SearchPanePage.Commands.HideSearchPane, "_HideSearchPane");	
		Olive.CmdTarget.RegisterCommand(classProto, SearchPanePage.Commands.GoToPage, "_GoToPage");	

		// Events
		classProto.registerOwcEventsClass2("closeSearchPane", "onCloseSearchPane", true);
	};

	function SearchPanePage_postInitialize(popupArguments)
	{
		/// <summary>
		///		Initializes HTML pages after all controls are created.
		/// </summary>
		/// <param name="popupArguments" type="object">
		///		Reference to the arguments passed to this page by opener.
		///		If this page is not loaded in a popup window or opener did not
		///		pass any arguments to this page, <parameter name="popupArguments" />
		///		will be <c>null</c>
		/// </param>
		/// <remarks>
		///		This initialization routine is called after all Web controls on 
		///		this page are created.  This is a good place to binds controls 
		///		to each other, attaches event handlers and perform other 
		///		initialization tasks.
		/// </remarks>
		
		// set resources strings
		for (var res_str in SearchPanePage.ResourceStrings)
		    this.WebApplication.setResString(window.document, res_str);
		    
		// get controls
		this._findControls();
		
		// handle "Search" requests
		if (this.m_searchForm)
		{
		    this.m_searchForm.setFieldValue("text", "");
		    this.m_searchForm.onSearchRequest = Delegate.CreateDelegate(this._onSearch, this);
			this._updateSearchIn();
		}
		
		// set page size for the search results
	   // this.m_searchResults.setPageSize(this.WebApplication.m_nSearchResPageSize, true);
      
        // initialize magnifier control
	    if (this.m_magnifierControl)
	    {
	        this.m_magnifierControl.setMaxWidth(this.WebApplication.m_nMagnifierMaxWidth);
	        this.m_magnifierControl.setMaxHeight(this.WebApplication.m_nMagnifierMaxHeight);
	        this.m_magnifierControl.setMagPercent(this.WebApplication.m_nMagnifierMagPercent);
	    }

		this.m_bInitialized = true;
		this.WebApplication.onSearchPaneLoaded(); 	
		
		//set search form text field focus
        var oSearchFormTextField = document.getElementById( SearchPanePage.ElementIDs.SearchFormTextFieldID );
        if ( oSearchFormTextField )
        {
            oSearchFormTextField.focus();
        }         
	}

	function SearchPanePage_BindDocViewerParts(docViewerAgg)
	{
//	    docViewerAgg.set_SearchResControl(this.m_searchResults);
		docViewerAgg.m_oBindSearchResToDocViewer.setPreEventHandlerAction(this.WebApplication.constructor.CheckOkToChangeIssue);
	}

	function SearchPanePage_GoToPage(oCmdParams)
	{
		alert(oCmdParams);
		alert(this.m_flashViewer);
		//// <summary>Handler for clicking on a page link: go to page</summary>
		///	<param name="nPageNo" type="number">Page number of the link</param>
		
		if (oCmdParams > 0 && this.m_flashViewer)
			this.m_flashViewer.gotoPageWithHighlighting(oCmdParams, "");
	}

	function SearchPanePage_findControls()
	{
		this.m_docViewerAgg = this.findControlByType(Olive.Controls.controlTypeNames.DocViewerAgg);
		if (!this.m_docViewerAgg)
		{
			//alert('help');
			//this.reportError(DHTML.newError(SearchPanePage.ErrorCodes.DocViewerAggAbsence, "Internal error: Cannot find Olive.Controls.DocViewerAgg control on HTML page"));
			return;
		}

		this.m_flashViewer = this.m_docViewerAgg.m_oViewerCtrl;
		if (!this.m_flashViewer)
		{
			//this.reportError(DHTML.newError(MainPage.ErrorCodes.FlashViewerAbsence, "Internal error: Cannot find Olive.Controls.FlashViewer control on HTML page"));
			return;
		}

		/// <summary>Find controls needed by the other methods on the page</summary>
		// get search form object
		//this.m_searchForm = this.findControlByType(Olive.Controls.controlTypeNames.SearchForm);
		//if (!this.m_searchForm)
		//{
		//	this.reportError(DHTML.newError(SearchPanePage.ErrorCodes.SearchFormAbsence, "Internal error: Cannot find Olive.Controls.SearchForm control on HTML page"));
		//	return;
		//}
		//this.m_oHtmlSearchThisIssue = document.getElementById(SearchPanePage.ElementIDs.SearchInThisIssueID);
		//this.m_oHtmlSearchThisPublication = document.getElementById(SearchPanePage.ElementIDs.SearchInThisPublicationID);
 
	    // get search results object
		//this.m_searchResults = this.findControlByType(Olive.Controls.controlTypeNames.SearchRes);
		//if (!this.m_searchResults)
		//{
		//	this.reportError(DHTML.newError(SearchPanePage.ErrorCodes.SearchResAbsence, "Internal error: Cannot find Olive.Controls.SearchRes control on HTML page"));
		//	return;
		//}
		return;
	}

	function SearchPanePage_updateSearchIn()
	{
		/// <summary>Put the current Href and publication name in search form fields</summary>
		var sDocHRef = this.WebApplication.m_sDocHRef;
		if (sDocHRef)
		{
			if (this.m_oHtmlSearchThisIssue)
				this.m_oHtmlSearchThisIssue.value = sDocHRef;
			if (this.m_oHtmlSearchThisPublication)
			{
				this.m_oHtmlSearchThisPublication.value = sDocHRef.substr(0, sDocHRef.indexOf("/"));
			}
		}
	}

	function SearchPanePage_onSearchRequest(eventArgs)
	{
		/// <summary>Handler for clicking on the search button</summary>
		/// <param name="eventArgs" type="Olive.Event">Event arguments object</param>
        
        eventArgs.cancelBubbling = true;	    
	    var oSearchParams = eventArgs.SearchParams;	    
		
		if(this.WebApplication.m_bSearchQueryRestricted)
		{
		    var sUserQueryString = oSearchParams.getSearchInField("text");
		    var regExp = /(.*[^\*\?]+){2,}/g; // two characters what are not special wildcards characters
		    var res = sUserQueryString.match(regExp);
		    if(!res)
		    {
		        this.displayMessage(this.getResString("Message_InsufficientSearchQuery"));//show error message
		        return;
		    }
		    
		}
        
        var oSortOptions = this.WebApplication.getSearchSortOptions(this.WebApplication.m_bSortByDate);		
		if (oSortOptions)
			oSearchParams.setSortBy(oSortOptions);
        
	   // this.m_searchResults.loadSearchResults(oSearchParams);
	}
	
	function SearchPanePage_ShowICViewer()
	{
		/// <summary>Handler for clicking on the "full text" link in search results</summary>
	    var oContentItem = this._getSelectedSearchResult();
	    if (!oContentItem)
		    return;
			
	    // open the ICViewer in viewMode specified in configuration settings
	    oContentItem.expando = true;
	    oContentItem.viewMode = this.WebApplication.m_sICViewMode;
	    // Open component viewer form
	    this.WebApplication.OpenComponent(oContentItem);		
	}
	
	function SearchPanePage_getSelectedSearchResult(bDoNotAlert)
	{
		/// <summary>Get the Content Item of the selected search result</summary>
		/// <param name="bDoNotAlert" type="boolean">Do not display a message if no search result was selected</param>
		/// <returns type="Olive.ContentItem">The content item of the selected search result</returns>
		//var oContentItem = null;
		//var oSelectedItemControl = this.m_searchResults.getSelectedItem();
		//if (oSelectedItemControl && oSelectedItemControl.getContentItem)
		//	oContentItem = oSelectedItemControl.getContentItem();

		//if (!oContentItem && !bDoNotAlert)
		//	this.displayMessage("No search result selected");
		//return oContentItem;
	}
    
    function SearchPanePage_updateSortByState(oCmdUiState)
    {
		/// <summary>Enables a sort-by command if it is different from the current sort order</summary>
		/// <param name="oCmdUiState" type="Olive.CmdUiState">Reference to object storing command's UI state</param>
		var sCommandSortBy = oCmdUiState.commandParams.toLowerCase();
		var bCheckCommand = false;
		if (this.WebApplication.m_bSortByDate === true)
			bCheckCommand = (sCommandSortBy == "date");
		else
			bCheckCommand = (sCommandSortBy != "date");

        oCmdUiState.checkCommand(bCheckCommand);
    }

    function SearchPanePage_onSortBy(oCmdParams)
    {
		/// <summary>Handler for requesting to re-sort the search results</summary>
		///	<param name="oCmdParams" type="string">Command parameter: "date" or "relevance"</param>
		//var bSortByDate = (oCmdParams.toLowerCase() == "date");
		//if (this.WebApplication.m_bSortByDate == bSortByDate)
		//	return; // no change
		//var oSortOptions = this.WebApplication.getSearchSortOptions(bSortByDate);//persist the new value
		//if (this.m_searchForm && this.m_searchResults)
		//{
		//	this.m_searchForm.updateData();
		//	var oSearchParams = this.m_searchForm.getValue();
		//	if (oSearchParams)
		//	{
		//		if (oSortOptions)
		//		{
		//			oSearchParams.setSortBy(oSortOptions);
		//		}
			//	this.m_searchResults.loadSearchResults(oSearchParams);
			//}
		//}  
    }
    
    function SearchPanePage_CheckOkToChangeIssue(oContentItem)
	{
		/// <summary>
		///		This method opens a popup dialog window asking the user if it is OK to open a new issue.
		///		First it looks at a cookie to see if the user has already answered the question
		///	</summary>
		/// <param name="oContentItem" type="Olive.ContentItem">
		///		Content item of the search result for opening the document viewer
		/// </param>
		/// <returns type="boolean">Flag specifying whether it is OK to change.</returns>
		var bIsDocHRefDifferent = this.WebApplication.isDocHRefDifferent(oContentItem);
		if (bIsDocHRefDifferent)
		{
		    this.WebApplication._checkOkToChangeIssue(oContentItem);
		    return false;
		}
		return true;
	}
	
	// Hide search pane when user click on close button
    function SearchPanePage_HideSearchPane()
    {
        var objEvent = this.createOwcEventObject("closeSearchPane");
        this.fireOwcEvent(objEvent);
        Object_Destroy(objEvent);
    }

	JScript.Type.RegisterClass("SearchPanePage", SearchPanePage, Olive.Page, [Olive.Controls.IDataBound]);
}

Olive.WindowBinder.RegisterPageClass(window, SearchPanePage);
