// Init cookies. Must be done early.
if(Ext.state.CookieProvider)
{
	COMP.Cookie = new Ext.state.CookieProvider({
		expires: new Date(new Date().getTime()+(1000*60*60*24*366)) // 1 year
	});
}
//Ext.state.Manager.setProvider(COMP.Cookie);

COMP.Config =
{
	dialog:null
	,HandleLanguageMenu : function(id)
	{
		var languageMenu = new Ext.menu.Menu({
		items: [{
				text: 'English'     //NOLS
				,langID: 25856
				,group: 'lang'
				,checked:COMP.Lang.id==25856?true:false
				,handler: function(){COMP.Config.HandleLanguageChange(this)}
		},{
				text: 'Espa&#241;ol'  /*Spanish*/   //NOLS
				,langID: 29440
				,group: 'lang'
				,checked:COMP.Lang.id==29440?true:false
				,handler: function(){COMP.Config.HandleLanguageChange(this)}
			}]
		});
		languageMenu.show(Ext.get(id));
	}

	,HandleConfigMenu : function()
	{
		if (RWS.Patron.current.loggedIn)
		{
			COMP.Config.Show(false, 'configButton');
			return;
		}
		else
		{
			COMP.LoadLibraries(['rws_login'], function(){
				COMP.Login.HandleShowLogin("COMP.Config.Show(!RWS.Patron.current.loggedIn, 'loginWindow')", {configLogin:true}, null, 'configButton');
			});
		}
	}

	,AdminLogin : function()
	{
//		HideWaitDialog();
		Ext.getCmp('loginWindow').close();
		COMP.Config.Show(true);
	}
	
	,GetDefault : function(id,ignorePatron)
	{
		if (!ignorePatron && RWS.Patron)
		{
			var d = RWS.Patron.current.data;
			if (d && d.prefs && d.prefs[id] != undefined)
				return d.prefs[id];
		}
		if(COMP.Cookie)
			return COMP.Cookie.get(id,COMP.Prefs[id]);
		
		return COMP.Prefs[id];
	}
	
	// Not intended to be saved automatically.
	,SetDefault : function(id,newValue,ignorePatron)
	{
		if (!ignorePatron && RWS.Patron)
		{
			var d = RWS.Patron.current.data;
			if (d && d.prefs && d.prefs[id] != undefined)
			{
				d.prefs[id] = newValue;
				return;
			}
		}
		
		COMP.Prefs[id] = newValue;
	}

	,GetCheckBoxes : function(boxes)
	{
		var o=new Array;
		for (var i=0; i<boxes.length; i++)
			o.add({
				boxLabel:boxes[i][1]
				,checked:COMP.Config.GetDefault(boxes[i][0])
				,id:boxes[i][0]
			});
		
		return o;
	}
	
	,GetPopups : function(config)
	{
        var popups;
        if(config)
            popups = COMP.Config.configPopups();
		else popups = COMP.Config.soundPopups();
		var pops=new Array;
		for (var i=0; i<popups.length; i++)
		{
			var o = popups[i][3] || { store:popups[i][2] };
		
			o.fieldLabel=popups[i][1];
			o.id=popups[i][0];
			o.value=COMP.Config.GetDefault(popups[i][0]);
			pops.add(o);
		}
		
		return pops;
	}
	
	,Show : function(machineConfig, sender)
	{
		
		var me=COMP.Config;
		var machineItems=[{
				width:700
				,layout:'column'
				,defaults:{border:false}
				,items:[{
					columnWidth:1
					,layout:'form'
					,defaultType:'checkbox'
					,cls:'checkboxForm'
					,defaults:{hideLabel:true}
					,items:me.GetCheckBoxes(me.configBoxes)
				},{
					width:350
					,layout:'form'
					,labelWidth:150
					,defaultType:'combo'
					,defaults:
					{
						editable:false
						,labelSeparator:''
						,forceSelection:true
						,mode:'local'
						,triggerAction:'all'
					}
					,items:me.GetPopups(true)
				}]
			}];
		
		var patronItems=machineItems; // for now
        
        this.dialog = new Ext.Window({
			modal: true
			,id:'configDialog'
			,width:750
			,height:475
			//,cls: 'patronConfig'
			,closeAction: 'close'
			,layout:'fit'
			,border:false
			,resizable:false
			,defaults:{border:false}
			,items: [{
            xtype: 'tabpanel'
            ,defaults:{hideBorders:true}
            ,activeTab: 0
            ,items: [{
            title: machineConfig ? L(25780) : L(25781) // Machine config / Patron config
            ,items: machineConfig ? machineItems : patronItems
            },{
					title: L(5418)//ls_Sounds
                    ,items: [{
                    xtype: 'checkbox'
                    ,id:'enableSounds'
                    ,checked:COMP.Config.GetDefault('enableSounds')
                    ,boxLabel: L(27396)//ls_Enable_Sounds
                    },{
                    xtype: 'label'
                    ,html: '<br>'
                    },{
                        width:350
                        ,layout:'form'
                        ,labelWidth:150
                        ,defaultType:'combo'
                        ,defaults:
                        {
                            editable:false
                            ,labelSeparator:''
                            ,forceSelection:true
                            ,mode:'local'
                            ,triggerAction:'all'
                        }
                        ,items:me.GetPopups(false)
				}]
			}]
				}]
			,buttonAlign:'center'
			,bbar:[{
				xtype:'button'
				,text:L(5442) //'Reset'
				,handler:function() { COMP.Config.Reset(machineConfig); }
			},'->',{
				xtype:'button'
				,text:L(17140) //'Cancel' 
				,handler:function() { Ext.getCmp('configDialog').close(); }
			},{
				xtype:'button'
				,text:L(17432) //'Save' 
				,handler:function() {
					COMP.Config.Save(machineConfig);
					var self = this;
					var text = this.text;
					this.setText(L(14895)+'...'); //ls_Saving
					// this.disable();
					this.setText.defer(1000, this, [L(17432)]); //ls_Save
					//Ext.getCmp('configDialog').destroy();
					//COMP.Config.Show(machineConfig, sender);//kokoni bug 26033 3/23/10
				}
			}]
		});
		
		/*this.dialog = new Ext.Window({
			title: machineConfig ? L(25780) : L(25781) // Machine config / Patron config
			,modal: true
			,width:700
			,height:COMP.Lang.id == 25856 ? 400 : 425
			,cls: 'patronConfig'
			,closeAction: 'close'
			,layout:'fit'
			,border:false
			,defaults:{border:false}
			,items: machineConfig ? machineItems : patronItems
			,buttonAlign:'center'
			,bbar:[{
				xtype:'button'
				,text:L(5442) //'Reset'
				,handler:function() { COMP.Config.Reset(machineConfig); }
			},'->',{
				xtype:'button'
				,text:L(17140) //'Cancel' 
				,handler:function() { COMP.Config.dialog.close(); }
			},{
				xtype:'button'
				,text:L(17432) //'Save' 
				,handler:function() { COMP.Config.Save(machineConfig); COMP.Config.dialog.close(); }
			}]
		});*/
		this.dialog.show(sender);
		if(this.dialog.y < 0) this.dialog.setPosition(this.dialog.x, 0);
	}

	,Save : function(machineConfig) // If it's not a machine config, then it's a patron config which is saved on the server.
	{
		var me=COMP.Config;
		var o = me.configBoxes.concat(me.configPopups());
        o = o.concat(me.soundPopups()); 
        o = o.concat({0:Ext.getCmp('enableSounds').id,1:Ext.getCmp('enableSounds')});
		
		for (var i=0; i<o.length; i++)
		{
			var id=o[i][0];
			var dlgValue=me.dialog.findById(id).getValue();
			if (machineConfig)
			{
				if (dlgValue==COMP.Prefs[id])
					COMP.Cookie.clear(id);
				else
					COMP.Cookie.set(id, dlgValue);
				COMP.Prefs[id] = dlgValue;
			}
			else
			{
			// dw- Server complications. Just save it all for now to be safe(r).
//				if (dlgValue==COMP.Prefs[id] && dlgValue==COMP.Config.GetDefault(id,true))
//					delete patronPrefs[id];
//				else
				RWS.Patron.current.data.prefs[id]=dlgValue;
			}
			if(id == "timeout") 
			 	COMP.V.session_timeout = dlgValue;
		}
		
		c = Ext.getCmp('prefLibrary');
		var libs = COMP.Prefs.collectionsList[COMP.Config.GetDefault('searchAddressBook')]
		c.replaceMenu(libs);
		setDefaultState(c.id, c.getValue());
		var prefsToSend = deepObjCopy(RWS.Patron.current.data.prefs);
		if(RWS.Patron.current.loggedIn){
			for(var i = 0; i < libs.length; i ++){
				if((libs[i].libID + '') == RWS.Patron.current.data.prefs.localCollection){
					prefsToSend.localCollection = libs[i].text;
					break;
				}	
			}
		}
		
		
		if (!machineConfig)
			COMP.SendAjaxCommand('rws_store_patron_prefs',prefsToSend, function(o){}, this);
        
		RWS.Layout.PreFilters.lexile.resetDefaults(true);
		RWS.Layout.PreFilters.library.clear();
		COMP.Config.SetLanguage();
	}
	
	,Reset : function(machineConfig)
	{
		var me=COMP.Config;
		var o = me.configBoxes.concat(me.configPopups());
            o = o.concat(me.soundPopups());
            o = o.concat({0:Ext.getCmp('enableSounds').id,1:Ext.getCmp('enableSounds')});
		
		for (var i=0; i<o.length; i++)
		{
			var id=o[i][0];
			var c=me.dialog.findById(id);

			if (machineConfig)
			{
				c.setValue(COMP.Prefs[id]);
			}
			else
			{
				c.setValue(me.GetDefault(id,true));
			}
		}
	}
	
	,HandleLanguageChange : function(item) 
	{
		COMP.Config.SetLanguage(item.langID);
		item.setChecked(true);
	}
	
	,SetLanguage : function(langID)
	{
		if (!langID) langID = COMP.Config.GetDefault('defaultLang');
		if (langID)
		{
			COMP.Lang.id=langID;
			COMP.Lang.ReloadAllStrings();
						
			if(RWS.Search.Results){
				RWS.Search.Results.CreateTemplates();
				RWS.Layout.ResultsView.tpl = RWS.Search.Results.templates.full;
			}
		}
	}
	
	,SecurityFail : function()
	{
//		HideWaitDialog();
		alert(L(26057));//'Invalid login or insufficient permissions. Unable to access this dialog.'
	}
	
	,VerifyLocalCollection : function()
	{
		// Ask the server to verify the selected local collection actually exists.
		// Should be rare that this is an issue, but there is some concern.
		var col = COMP.Config.GetDefault('localCollection');
		if (parseInt(col) > 0)
			COMP.SendAjaxCommand('rws_verify_local_collection',{col:col}, this.CollectionVerified, this);
	}
	
	,CollectionVerified : function(o)
	{
		// If something has changed since we sent the request, don't assume our result is accurate.
		if (!o.success)
		{
			if (o.oldCollection == COMP.Config.GetDefault('localCollection'))
				COMP.Config.SetDefault('localCollection', o.newCollection);
			else
				COMP.Config.VerifyLocalCollection();
		}
	}
};

COMP.Config.addressBookList=
{
	store:COMP.Prefs.addressBookList
	,listeners:{
		select:{fn:function(){
			var c = Ext.getCmp('localCollection');
			c.replaceMenu(COMP.Prefs.collectionsList[this.getValue()]);
			c.setSelectedIndex(0);
			c = Ext.getCmp('prefMedium');
			c.replaceMenu(COMP.Prefs.collectionsList[this.getValue()]);
			setDefaultState(c.id, c.getValue());
			
		}}
	}
};

COMP.Config.localCollectionPopup= function()
{    
	var collections = COMP.Prefs.collectionsList[COMP.Config.GetDefault('searchAddressBook')];
	var truncate = function(coll){
		for(var i = 0; i < coll.length; i++){
			coll[i].text =  COMP.fitStringToWidth(coll[i].text,160,'x-btn-text', true);
			if(coll[i].items)
				truncate(coll[i].items);
		}
	}
	truncate(collections);
	return {
		xtype:'comboMenu'
		,text: 'None'
		,defaultID:COMP.Config.GetDefault('localCollection') + ''
		,displayField:'text'
		,valueField:'libID'
		,isRendered:false
		,width:180
		,showDefaultOption:false
		,menuItems: collections
		,listeners:{
			resize:function(c, w, h){
				if(w > 180)
					c.setWidth(180);
				
			}
		}
	};
};

COMP.Config.configBoxes=
[
	['allowViewMarcRecords',L(11518)]
//	,['showMarcDisplay',L(5485)]
	,['showCitationReferences',L(5484)]
	,['soundsLikePrompt',L(5472)]
//	,['hideBrowseButton',L(23717)]
	,['limitCopiesByLibrary',L(21509)]
	,['showAmazonLinks',L(13021)]
	,['showAvailAtLocalLibSavedLists',L(23118)]
	,['dontShowTitleAvail',L(18921)]
	,['displayCopyright',L(24112)]
	,['displayLexile',L(24111)]
	,['displayReadingLevel',L(24110)]
	,['showLexileIndicatorSavedLists',L(23438)]
	,['showItemImages', L(16960)]
];

COMP.Config.configPopups = function(){
	return new Array(
		['showLexileHelp', L(20763), [[false,L(20764)],[true,L(20765)],['hide',L(20766)]]]
		,['timeout', L(1810), [[5,'5'],[10,'10'],[15,'15'],[20,'20'],[30,'30'],[60,'60']]]
		,['defaultLang', L(5464), [[25856,L(5465,25856)],[29440,L(5466,29440)]]]
		,['maximumHits', L(6935), [[50,'50'],[100,'100'],[200,'200'],[300,'300'],[400,'400'],[500,'500'],[1000,'1000']]]
		,['defaultSort', L(25782), [['title',L(4087)],['author',L(4085)],['callnum',L(4081)],['awards',L(12500)],['medium',L(4090)],['series',L(3692)],['year',L(4170)]]]
		,['searchAddressBook', L(12039), [], COMP.Config.addressBookList]
		,['localCollection', L(6192), [], COMP.Config.localCollectionPopup()]
		,['defaultResultsPerPage', L(11509), [[10,'10'],[15,'15'],[30,'30'],[50,'50'],[100,'100']]]
		,['defaultSearchResultsMode', 'Default Search Results Mode', [[1,'Brief'],[2,'Full']]]//newls //bug 26509 4/13/10
		//,['showPrefiltersOnLoad', 'Show Prefilters on Load', [[1,'Available'],[2,'Hidden']]]//newls //bug 22890 4/05/10
//		,['z39AddressBook', L(8587), COMP.Prefs.addressBookList]
	//	,['site', L(25449), COMP.Prefs.siteList]
	);
};

COMP.Config.soundPopups = function(){
    var list = [['',L(3982)],['alert',L(17142)],['check_in',L(5704)],['check_out',L(5705)],['click_sound',L(7779)]
	,['hold_placed',L(5708)],['inventory',L(4759)],['new_patron',L(5372)], ['ping',L(5710)],['report_complete',L(5712)]
	,['reservation_placed',L(5714)],['reserve_placed',L(5713)],['saxes',L(7780)],['search_complete',L(5717)]
	,['serious_alert',L(5719)],['short_ping',L(5720)],['soft_alert',L(7781)],['tiny_bubbles',L(7782)],['try_again',L(7783)]
	,['uh_oh',L(7784)],['very_serious_alert',L(5722)],['welcome',L(5723)], ['whistle_lo',L(7785)]]
	
    /*[[0,'NONE'],[1,'Alert'],[2,'Check In'],[3,'Check Out'],[4,'Click Sound'],[5,'Hold Placed'],[6,'Inventory']
	,[7,'New Patron'], [8,'Ping'],[9,'Report Complete'],[10,'Reservation Placed'],[11,'Reserve Placed'],[12,'Saxes']
	,[13,'Search Complete'],[14,'Serious Alert'],[15,'Short Ping'],[16,'Soft Alert'],[17,'Tiny Bubbles'],[18,'Try Again']
	,[19,'Uh Oh!'],[20,'Very Serious Alert'],[21,'Welcome'], [22,'Whistle Lo']];
		*/

	return new Array(
	
		['holdPlacedByPatronSound', L(26360), list]//ls_Hold_Placed_by_Patron
		,['reservationPlacedByPatronSound', L(26361), list]//ls_Reservation_Placed_by_Patron
		,['searchCompleteSound', L(5717), list]//ls_Search_Complete
		,['searchFailedSound', L(5718), list]//ls_Search_Failed
	);
};


COMP.Lang.id = COMP.Config.GetDefault('defaultLang');
if (window.COMP) COMP.Broadcast('scriptLoaded_rws_config');