COMP.LoadStylesheet('rws_results');
COMP.LoadStylesheet('rws_postfilters');


var DITEM_SERIES = COMP.StringToFourChar('SERW');

RWS.Search =
{
	mediumStore:new Ext.data.SimpleStore({fields:['medium'],id:'medium'})
	,pastItems:[]
	,searchRequests:[]
	,SendListRequest : function(listName, rsns, fade)
	{
		var o={};
		o.listName = listName;
		o.rsns=rsns.toString();
		o.limitCopiesByLibrary = COMP.Config.GetDefault('limitCopiesByLibrary');
		
		RWS.Layout.CenterContent.items.each(function(i){
			if(i.id != 'breadCrumbs')
				i.hide();//i.el.ghost('l', {duration: 2, scope: i, callback: this.hide});
		});                                              
		RWS.Layout.CenterContent.add(RWS.Layout.Results);
		RWS.Layout.CenterContent.doLayout();
		RWS.Layout.Results.reset();
		RWS.Layout.Results.show();
		RWS.Layout.Results.doLayout();
		// if(fade)
			// RWS.Layout.Results.el.fadeIn();

		var nsb = Ext.getCmp('northSerarchBar');
		Ext.apply(nsb, {o: o});

		if (typeof(addCrumb) == 'undefined') 
			addCrumb=true;
		var breadFunction = function() {RWS.Details.CloseAll(); RWS.Search.SendListRequest(listName,rsns, fade);};
		if (addCrumb /*&& !RWS.Bread.MatchesLastCrumb(o)*/)
			RWS.Bread.AddCrumb(L(26060).append(" " + o.listName), breadFunction, null,o, {callback:RWS.Search.RequestList(o), scope:this}); // Searched
		RWS.Layout.PastSearches.add(o.listName, breadFunction);
		Ext.getCmp('north_library').hide();
		Ext.getCmp('northSerarchBar').show();
		Ext.getCmp('northSerarchButton').show();
		Ext.getCmp('northSerarchPadding').show();
		RWS.Layout.NorthBar.doLayout();
		Ext.getCmp('searchAllResultsLink').setText('Search for \'' + o.listName + '\' using SearchAll!');
		RWS.Layout.SearchPostFilters.show();
			
	}
	,RequestList:function(o){
		RWS.Search.curSearchRequest = COMP.SendAjaxCommand('rws_list_request',o, 
			RWS.Search.HandleResults, RWS.Search
			,function() // fail func
			{
				alert(L(7157)); // Search timed out
			}
		);
	}
	,CancelSearch:function()
	{
		Ext.Ajax.abort(RWS.Search.curSearchRequest);
	}
	,SendRequest : function(o,incPreFilters,soundsLike,e, fade)
	{
		if (incPreFilters != false)
			o = COMP.CombineObjects(o,this.PreFilters, {localCollection:COMP.Config.GetDefault('localCollection')});
			
		o.soundsLike = soundsLike || false;
		o.maximumHits = COMP.Config.GetDefault('maximumHits');
		if (o.limitCopiesByLibrary == undefined)
			o.limitCopiesByLibrary = COMP.Config.GetDefault('limitCopiesByLibrary');
		o.ticks = COMP.GetCurrentTicks(); // disable browser-based results caching


		var e = e || window.Event || window.event;
		o.altKey = e ? e.altKey : false;
		o.shiftKey = e ? e.shiftKey : false;
		o.fromLWS = RWS.fromLWS;
		fade = fade == undefined ? true : false;
		RWS.Search.PerformSearch(o);
	}
	,PerformSearch:function(o,addCrumb){
		// Cancel last netTrekker request, just in case.
		Ext.Ajax.abort(lastTrekkerRequest);
		Ext.Ajax.abort(RWS.Search.curSearchRequest);
		
		RWS.Layout.CenterContent.items.each(function(i){
			if(i.id != 'breadCrumbs')
				i.hide();//i.el.ghost('l', {duration: 2, scope: i, callback: this.hide});
		});
		RWS.Layout.CenterContent.add(RWS.Layout.Results);
		RWS.Layout.CenterContent.doLayout();
		RWS.Layout.Results.reset();
		RWS.Layout.Results.show();
		RWS.Layout.Results.doLayout();
		// RWS.Layout.ResultsSearching.doLayout();
		    
		var nsb = Ext.getCmp('northSerarchBar');
		Ext.apply(nsb, {o: o});
		
		if (typeof(addCrumb) == 'undefined') 
			addCrumb=true;
		var breadFunction = function() {RWS.Details.CloseAll(); RWS.Search.PerformSearch(o,false);};
		if (addCrumb /*&& !RWS.Bread.MatchesLastCrumb(o)*/)
			RWS.Bread.AddCrumb(L(26060).append(" " + o.SearchField0), breadFunction, null,o, {callback:RWS.Search.ShowResultsPanel(o), scope:this}); // Searched
		else
			RWS.Search.ShowResultsPanel(o);
		Ext.getCmp('north_library').hide();
		nsb.show();
		nsb.setValue(o.SearchField0);
		Ext.getCmp('northSerarchButton').show();
		Ext.getCmp('northSerarchPadding').show();
		Ext.getCmp('searchAllResultsLink').setText('Search for \'' + COMP.fitStringToWidth(o.SearchField0, 350, 'font14') + '\' using SearchAll!'); // NEWLS
	}
	,ShowResultsPanel:function(o){
		RWS.Search.curSearchRequest = COMP.SendAjaxCommand('rws_search_request', o, RWS.Search.HandleResults, RWS.Search);
		RWS.Search.searchRequests[o.ticks.toString()] = o;
		this.StoreResultsLink(o);
		var pastSearchesStore = Ext.getCmp('id_PastSearches').store;
		var record = new pastSearchesStore.recordType({title:o.SearchField0, rsn:o.ticks, savedListName:'id_PastSearches'});
		pastSearchesStore.add(record);
		this.lastSearch=o;
	}
	,RequestSoundSearch : function()
	{
		if (RWS.Search.noResultsDialog)
			RWS.Search.noResultsDialog.close();
		
		RWS.Search.SendRequest(this.lastSearch,false,true);
	}
	,RequestMoreLexileSearch : function() // lexile show more
	{
		if (RWS.Search.noResultsDialog)
			RWS.Search.noResultsDialog.close();
		
		var o = this.lastSearch;
		o.lexileMore = true;
		RWS.Search.SendRequest(o,false);
	}
	,SendDetailRequest : function(rsn)
	{
		var o = {rsn:rsn};
		o.limitCopiesByLibrary = COMP.Config.GetDefault('limitCopiesByLibrary');
		COMP.LoadLibrary('rws_results');
        COMP.SendAjaxCommand('rws_detail_request', o, RWS.Search.HandleDetails)

	}
	,GetDetailsLink : function(rsn) // No real need to store something this simple
	{
		return COMP.Location().substring(0, COMP.Location().length-2) + COMP.V.serial + '?details=' + rsn;
	}
	// URL that can be used to directly access the results
	,StoreResultsLink : function(o)
	{
		this.mResultsLink = COMP.Location() + '/' + COMP.V.serial + '?results=' + escape(COMP.GetParamString(o,false));
	}
	,mResultsLink : ''
	,DataFromRSN : function(rsn)
	{
		var index = RWS.Search.Results.stores.main.find('rsn',rsn);
		return RWS.Search.Results.stores.main.getAt(index).data;
	}
	,ProcessResults : function(o)
	{
		if (o.processed)
			return;
		if(o.didYouMean && o.seeAlso)
			this.FillSeeSeeAlso(o);
		o.processed = true;
		for (var i=0; i<o.items.length; i++)
		{
			var item = o.items[i];
			if(item)
			{
				if (item.attachments.length>0)
				{
					item.attachment1url = item.attachments[0].url;
					item.attachment1name = item.attachments[0].name;
				}
			
				item.statusString = StatusString(item.status);
				
				if (item.accession.length>0)
				{
					var date = new Date(item.accession);
					item.accessionsort = -date.format('U');
				}
			}
		}
		RWS.Search.mCurrentTitle = o.title;

		
		var text=Ext.getCmp('simpleSearchBar').GetSearchText();

		var stores = RWS.Search.Results.stores;
		RWS.Layout.ResultsTop.doLayout();
		stores.main.removeAll();
		stores.main.loadData(o.items);
		Ext.getCmp('resultsFullCount').setText(stores.main.getCount() + ' results returned');

		stores.original.removeAll();
		stores.original.loadData(o.items);
		
		var resPop = Ext.getCmp('resultsSortPopup');
		
		var defaultSort = COMP.Config.GetDefault('defaultSort');
		switch (o.autoSort)
		{
			case DITEM_SERIES: 	defaultSort = 'series';	break;
		}
		resPop.setValue(defaultSort);
		stores.main.sort(resPop.getValue(),'ASC');//26296
		pageResults('start');
				//RWS.SavedLists.StoreSearch(o);
		
		if(COMP.Config.GetDefault('enableSounds')){
		var soundName = COMP.Config.GetDefault('searchCompleteSound');
			COMP.PlaySound(soundName);
			}
		if(COMP.Prefs.soundsLikePrompt && !RWS.Search.lastSearch.soundsLike){	
			Ext.getCmp('soundsLike').setText(String.format(L(27676).toString(), COMP.fitStringToWidth(o.title, 350, 'font14')));//ls_Perform_a_SoundsLike_search_for 
			Ext.getCmp('soundsLike').show();
		}else
			Ext.getCmp('soundsLike').hide();
		if(RWS.Search.lastSearch.SearchType0 != "Keyword"){
			Ext.getCmp('allWords').show();	
			Ext.getCmp('allWords').setText(String.format(L(27675).toString(), o.title))//ls_Perform_an_All_Words_search 
		}else
			Ext.getCmp('allWords').hide();           
		if (COMP.Config.GetDefault('showNetTrekker'))
			Ext.getCmp('resultsNettrekkerLink').requestNetTrekkerCount(RWS.Search.mCurrentTitle);
		RWS.Layout.Results.resultsLoaded();
		
	}
	,GetLookupTemplate:function(searchParam)
	{
		var template = '<span onclick="RWS.Search.LookupViaSeeSeeAlso(%obj%);" class="textlink">%display%</span>';//style="font-size:12px"
		
		var o= Ext.decode(searchParam);		
		
		var htmlFriedlyParam = Ext.encode(o).replace(/\"/g, '\''); // " for xcode
		template = template.replace(/\%obj\%/g, htmlFriedlyParam);
		
		var displayStr;
		if (o.SearchField0)
			displayStr = o.SearchField0;
		
		return template.replace(/\%display\%/g, displayStr);
	}
	,FillSeeSeeAlso:function(o, isEmptyResults)
	{
		var id = 'didYouMean';
		if(isEmptyResults)
			id += '-none'
					
		if (o.didYouMean && Ext.decode(o.didYouMean).length > 0)
		{
			o.didYouMean = Ext.decode(o.didYouMean);
			
			var fullHtml = '';
			for(var i = 0; i < o.didYouMean.length; i ++)
			{
				if (i == 0)
					fullHtml = L(27377)+':';//ls_Did_you_mean
				else
					fullHtml += ', ';
					
				fullHtml += ' ' + this.GetLookupTemplate(o.didYouMean[i]);
			}
			 
			Ext.getCmp(id).setHtml(fullHtml);
			Ext.getCmp(id).show();
		}
		else
		{
			Ext.getCmp(id).setHtml('');
			Ext.getCmp(id).hide();
			
		}
		id = 'seeAlso';
		if(isEmptyResults)
			id += '-none'
		
		if (o.seeAlso && Ext.decode(o.seeAlso).length > 0)
		{
			o.seeAlso = Ext.decode(o.seeAlso);
			
			var fullHtml = '';
			for(var i = 0; i < o.seeAlso.length; i ++)
			{
				if (i == 0)
					fullHtml = L(27378)+':';//ls_You_might_also_like
				else			
					fullHtml += ', '
				
				fullHtml += ' ' + this.GetLookupTemplate(o.seeAlso[i]);
			}
			
			Ext.getCmp(id).setHtml(fullHtml);			
		}
		else
		{
			Ext.getCmp(id).setHtml('');		
		}
	}
	,LookupViaSeeSeeAlso:function(o, e)
	{
		var e = e || window.event || Event; 		
		COMP.LoadLibrariesSerial(['rws_search'], function(){RWS.Search.SendRequest(o,null,null,e)});
	}
	,HandleResults : function(o,addCrumb)
	{      
		if (!o.items || o.items.length==0)
		{
			RWS.Search.HandleEmptySet(o,false);
			return;
		}
		if(o.seeAlso)
        	RWS.Search.Results.seeAlso = o.seeAlso.length > 2;
		if(o.didYouMean)
        	RWS.Search.Results.didYouMean = o.didYouMean.length > 2;
		RWS.Search.Results.fullCount = o.fullCount || o.items.length;		
		var moreButton = Ext.getCmp('moreResultsButton');
		if (moreButton)
		{
			if(o.showMoreButton){
				moreButton.show();
				moreButton.setText('Click here to view ' + RWS.Search.Results.fullCount + ' more results for \'' + o.title + '\''); 
			} 
			moreButton.hide();
			
		}
        this.ProcessResults(o);
	}
	,HandleWANresults:function(o)
	{
//		HideWaitDialog();
		
		var dlg;
		dlg = new Ext.Window({
			title:L(5861) // Search Results
			,width:400
			,height:300
			,layout:'vbox'
			,modal:true
			,doSearch:function()
			{
				var sel = dlg.findById('wanResultsGrid').getSelectionModel().getSelected();
				if (sel)
				{
					RWS.Search.lastSearch.prefLibrary = sel.get('server');
					RWS.Search.lastSearch.limitCopiesByLibrary = true;
					RWS.Search.SendRequest(RWS.Search.lastSearch,false,false);
					dlg.close();
					return true;
				}
				return false;
			}
			,items:
			[
				{
					xtype:'grid'
					,flex:1
					,id:'wanResultsGrid'
					,stripeRows:true
					,autoExpandColumn:'name'
					,store:new Ext.data.JsonStore({
						root: 'results',
						fields: ['name','server', 'type', 'count']
					})
			        ,columns:
					[
						{header:'Results', dataIndex:'count', width:100}
						,{header:'Server', dataIndex:'name', id:'name'}
					]
					,sm:new Ext.grid.RowSelectionModel({singleSelect:true})
					,listeners:
					{
						rowdblclick:function() {dlg.doSearch();}
					}
					// ,viewConfig: {forceFit:true, scrollOffset: 0}
				}
			]
			,bbar:
			[
				'->'
				,{text:L(17140),handler:function() // Cancel
				{
					dlg.close();
				}}
				,'-'
				,{text:L(3638),handler:function() // Search
				{
					dlg.doSearch();
				}}
			]
		});
		dlg.show();
		
		var grid = dlg.findById('wanResultsGrid');
		var store = grid.getStore();
		store.loadData(o);
	}
	,AddPastItem:function(record)
	{
		var pastItemsStore = Ext.getCmp('id_PastItems').store;
		var record = new pastItemsStore.recordType({title:record.data.title, rsn: record.data.rsn, savedListName:'id_PastItems'});
		pastItemsStore.add(record);
	}
	,HandleDetails : function(o)
	{
		RWS.Details.ShowSingleDetails(new RWS.Search.Results.Record(o));
	}
	,HandleEmptySet : function(o,soundsLike)
	{
		if(COMP.Config.GetDefault('enableSounds')){
		var soundName = COMP.Config.GetDefault('searchFailedSound');
			COMP.PlaySound(soundName);
			}
		// RWS.Layout.ResultsSearching.el.setHeight(0/*, {duration : .5}*/);
		RWS.Layout.ResultsSearching.hide();
		//L(27597).toString().replace("{0}", o.title) 
		Ext.getCmp('failTitle').setHtml(String.format(L(27677).toString(), o.title))//ls_Your_Search_for_0_returned
		if(COMP.Prefs.soundsLikePrompt && !RWS.Search.lastSearch.soundsLike){
			Ext.getCmp('soundsLike-none').setText(String.format(String.format(L(27676).toString(), o.title)))//ls_Perform_a_SoundsLike_search_for
			Ext.getCmp('soundsLike-none').show();
		}	
		else
			Ext.getCmp('soundsLike-none').hide();
			
		if(RWS.Search.lastSearch.SearchType0 != "Keyword"){
			Ext.getCmp('allWords-none').setText(String.format(L(27675).toString(), o.title))//ls_Perform_an_All_Words_search
			Ext.getCmp('allWords-none').show();
		}	
		else
			Ext.getCmp('allWords-none').hide();  
		RWS.Layout.ResultsNone.show();
		RWS.Layout.Results.doLayout();
		this.FillSeeSeeAlso(o, true);
	}
	,SendCopiesRequest : function(titleRsn)
	{
		var o={titleRsn:titleRsn};
		o.limitCopiesByLibrary = COMP.Config.GetDefault('limitCopiesByLibrary');
		o = COMP.CombineObjects(o,this.PreFilters, {localCollection:COMP.Config.GetDefault('localCollection')});
		o.ticks = COMP.GetCurrentTicks(); // because things change
		
		COMP.SendAjaxCommand('rws_request_copies',o,RWS.Search.HandleCopies);
	}
	
	// Returns 
	,HandleCopies : function(o)
	{
		for (var i=0; i<o.length; i++)
		{
			if (o[i].mapExists)
				o[i].mapLink = '<a class="textLink" onClick="RWS.Maps.Show(\'/map/' + o[i].callnum.trim() + '\');">' + L(5119) + '</a>';
		}
		var localArray = [];
		var remoteArray = [];
		
		var currentSites = COMP.Prefs.collectionsList[COMP.Prefs.searchAddressBook];
		var sites = [{display:"All", value:"All"}];
		for(var i = 0; i < currentSites.length; i ++){
			var s = currentSites[i].site;
			if(s)
				sites.add({display:s, value:s});
		}
		var currentSite = "All";
		
		for(var i = 0; i < currentSites.length; i ++){
			if(currentSites[i].libID == RWS.Search.PreFilters.prefLibrary){
				currentSite = currentSites[i].site;
			}
		}
		var copyAtSite = false;
		for(var i = 0; i < o.length; i ++){
			if(o[i].location1 == currentSite){
				copyAtSite = true;
			}
		}
		if(!copyAtSite)
			currentSite = "All";
		
		var copy = Ext.data.Record.create([
			{name:'uid'},
			{name: 'callnum'},
			{name: 'volume'},
			{name: 'barcode'},
			{name: 'location1'},
			{name: 'location2'},
			{name: 'location3'},
			{name: 'status'},
			{name: 'dueDate'},
			{name: 'mapLink'}
		]);
		
		var reader = new Ext.data.JsonReader({
			id:'uid'
		},copy);
		
		var store = new Ext.data.Store({
			reader:reader
		});
		store.on('load', function(store, records){
			store.un('load');
			if(currentSite != "All")
				store.filter('location1', currentSite, false, false);
			var proposedHeight = 110 + (records.length * 23);	
			if (proposedHeight > Ext.lib.Dom.getViewHeight() - 20) proposedHeight = Ext.lib.Dom.getViewHeight() - 20;
			var allLocationsGrid = {
				xtype:'grid'
				,stripeRows:true
				,store:store
				,colModel: new Ext.grid.ColumnModel({
			        defaults: {sortable: true}
			        ,columns:[
						{header: L(4081), dataIndex:'callnum'}
						,{header:L(4082), dataIndex:'volume'}
						,{header:L(4059), dataIndex:'barcode'}
						,{header:L(25449), dataIndex:'location1'}
						,{header:L(4080), dataIndex:'location2'}
						,{header:L(11112), dataIndex:'location3'}
						,{header:L(4121), dataIndex:'status'}
						,{header:L(5021), dataIndex:'dueDate'}
						,{header:L(5119), dataIndex:'mapLink'} // show map
					]
			    })
				,sm:new Ext.grid.RowSelectionModel({singleSelect:true})
				,width:"100%"
				,viewConfig: {forceFit:true, scrollOffset: 0}
				,height:25 + (records.length * 23)
			};
			var siteSelector = new Ext.ux.comboMenu({
				menuItems: sites
				,displayField: 'display'
				,valueField: 'value'
				,isRendered:false
				,fieldLabel:'Site'
				,showDefaultOption:false
				,listeners:{select: function(c){
					if(c.getValue() == "All")
						store.clearFilter();
					else
						store.filter('location1', c.getValue(), false, false);
				}}
			});
			siteSelector.setSelectedID(currentSite);
			var win = new Ext.Window({
				frame:true
				,border:false
				,id:'copyDetails'
				,modal:true
				,layout:'form'
				,height:proposedHeight
				,resizable:false
				,width:800
				,items:[siteSelector, allLocationsGrid]
			});
			win.show('searchResults');
		});
		store.loadData(o);
	}
	,PreFilters:
	{
		prefLibrary:''
		,prefMedium:''
		,prefAwards:''
		,prefPubYear:''
		,prefLexile:''
		,prefStudyProgramName:''
		,prefInterestLevel:''
		,prefReadingLevel:''
		,prefPointCount:''
		,prefHelpFindBook:COMP.Prefs.showLexileHelp == true
	},
	// New search with same collection ID
	StartOver : function()
	{
		resetFunction();
		var results = Ext.getCmp('searchResults');
		if(results) results.hide();
		ResetFocus();
	},
	
	// Check the URL for anything we want to automatically handle.
	// For example, a user may have been sent a links to search results or
	// item details. In both the cases, take the user straight there.
	CheckStartCommands : function(url)
	{
		// var params = COMP.GetSearchParams(url);
		// var results = params.results;
		// var details = params.details;
		if (url.toLowerCase().startsWith('#simplesearch=')) {
			var searchTerm = url.toLowerCase().after("#simplesearch=");
			if (searchTerm.length) {
				url = '#results=SearchType0=Keyword&SearchField0='+escape(searchTerm)+'&Interface=simple';
			}
		}
		
		if (url)
		{
			url = url.substring(9, url.length)
			var o = COMP.GetSearchParams(unescape(url));
			this.SendRequest(o,false);
		}
	}
	
	,HelpFindBook : function()
	{
		var str = Ext.getCmp('helpFindBook_text').getValue();
		if (str.length > 0)
			COMP.SendAjaxCommand('rws_helpfindbook',{lexileStr:str},function(result,request)
			{
				if (result.error)
				{
					alert(result.error);
					return;
				}
				RWS.Search.HandleResults(result.results);
			});
	}
};

function ShowDetailsLink(rsn)
{
	var link = RWS.Search.GetDetailsLink(rsn);
	var dlg = new RWS.Dialog({title:L(26607), msg:link, icon:Ext.MessageBox.Info, buttons:Ext.Msg.OKAY});
	dlg.show();
}

function ShowResLink(rsn, copycount)
{
	var val = rsn.toString().isNumeric() && parseInt(copycount)>0 && COMP.Config.GetDefault('allowReservations');
	return val;
}

function ShowHoldLink(rsn, copycount)
{
	return rsn.toString().isNumeric() && parseInt(copycount)>0 && COMP.Config.GetDefault('allowHolds');
}

function CanAddToList(rsn)
{
	return !rsn.toString().startsWith('z');
}

function CanLinkToItem(rsn)
{
	return !rsn.toString().startsWith('z');
}

function StatusString(status, electronic)
{
	switch (status)
	{
		case 0:	// No copies
		{
			if (electronic)
				return L(25989); // ONLINE
			else
				return L(27379); // ls_UNAVAILABLE
		}
		case 1:	return L(5872); // IN
		case 2: return L(5873); // OUT
		case 3: return L(25966); // OFFSITE
			
		default: return L(25967); //"UNKNOWN STATUS"
	}
}
if (window.COMP) COMP.Broadcast('scriptLoaded_rws_search');