COMP.LoadStylesheet('rws_patron.css');

function CopyStatus(type)
{
	switch (parseInt(type))
	{
		case 4:		return L(5524); // In Stock Hold
		case 32:	return L(4751); // Hold
	}
	return L(17158); // Unknown
}

RWS.Patron =
{
	current:{data : {}}
	,dialog:null
	,accountPanel:{}
	,Init:function(){
		RWS.Patron.accountPanel.checkColumn = new Ext.grid.CheckColumn({
			header:L(6688)
			,dataIndex:'renew'
			,width:50
		});
		
		RWS.Patron.accountPanel = {
			id:'accountPanel'
			,xtype:'container'
			,defaults:{border:false}
			,items:[{
				xtype:'container'
				,layout:'column'
				,defaults:{border:false}
				,items:[{
					id:'accountPanel_image'
					,xtype:'icon'
					,maxWidth:155
					,maxHeight:200
					,ground:'fore'
					,center:false
					,image:''
					,style:'padding-right:5px;'
					,listeners:{
						afterrender:function(img){
							 COMP.resizeImage(img.id, img.maxWidth, img.maxHeight)
						}
					}
					
				},{
					width:303
					,xtype:'container'
					,defaults:{border:false}
					,items:[{
						id:'accountPanel_patronName'
						,xtype:'label'
						,html:''
					},{
						id:'accountPanel_barcode'
						,xtype:'label'
						,html:''
					},{
						layout:'column'
						,defaults:{border:false}
						,items:[{
							xtype:'label'
							,cls:'label'
							,text:L(6788).append(': ')
							,style:'margin-right:5px;'
						},{
							id:'accountPanel_expDate'
							,xtype:'label'
							,html:''
						},{
							columnWidth:1
							,xtype:'label'
							,cls:'label textRight'
							,text:L(6491).append(': ')
							,style:'margin-right:5px;'
						},{
							id:'accountPanel_grade'
							,xtype:'label'
							,html:''
						}]
					},{
						xtype:'linebreak'
					},{
						id:'accountPanel_infoPanel'
						//,xtype:'panel'
						,xtype:'form'
						,defaultType:'textfield'
						,items:[{
							fieldLabel:L(4125)
							,value:RWS.Patron.current.data.address1
							,id:'accountPanel_address1'
                            ,disabled:!COMP.Config.GetDefault('allowPatrontoEditPersonalInfo')
							,width:'100%'
						},{
							xtype:'container'
							,layout:'column'
							,border:false
							,defaults:{border:false}
							,items:[{
								columnWidth:.6
								,layout:'form'
								,defaultType:'textfield'
								,items:[{
									fieldLabel:L(4127)
									,id:'accountPanel_city'
                                    ,disabled:!COMP.Config.GetDefault('allowPatrontoEditPersonalInfo')
									,width:'100%'
								}]
							},{
								columnWidth:.4
								,layout:'form'
								,bodyStyle:'padding-left:5px'
								,defaultType:'textfield'
								,labelWidth:60
								,items:[{
									fieldLabel:L(4128)
									,id:'accountPanel_state'
                                    ,disabled:!COMP.Config.GetDefault('allowPatrontoEditPersonalInfo')
									,width:'100%'
								}]
							}]
						},{
							xtype:'container'
							,layout:'column'
							,border:false
							,defaults:{border:false}
							,items:[{
								columnWidth:.5
								,layout:'form'
								,defaultType:'textfield'
								,items:[{
									fieldLabel:L(4129)
									,id:'accountPanel_postal'
                                    ,disabled:!COMP.Config.GetDefault('allowPatrontoEditPersonalInfo')
									,width:'100%'
								}]
							},{
								columnWidth:.5
								,layout:'form'
								,bodyStyle:'padding-left:5px'
								,defaultType:'textfield'
								,labelWidth:60
								,items:[{
									fieldLabel:L(4130)
									,id:'accountPanel_country'
                                    ,disabled:!COMP.Config.GetDefault('allowPatrontoEditPersonalInfo')
									,width:'100%'
								}]
							}]
						},{
							fieldLabel:L(4131)
							,id:'accountPanel_phone'
                            ,disabled:!COMP.Config.GetDefault('allowPatrontoEditPersonalInfo')
							,width:'100%'
						},{
							fieldLabel:L(4133)
							,id:'accountPanel_email'
							,disabled:!COMP.Config.GetDefault('allowPatronToEditEmailAddress')
							,width:'100%'
						},{
							fieldLabel:L(21463) // user ID
							,id:'accountPanel_userID'
							,disabled:!COMP.Config.GetDefault('allowPatronToChangeUsername')
							,width:'100%'
						},{
							xtype:'container'
							,border: false
							,layout: 'hbox'
							,items:[{xtype:'spacer', flex:1},{
								xtype:'button'
								,text:L(17432)
								,width: 50
								,hidden:!(COMP.Config.GetDefault('allowPatrontoEditPersonalInfo') || COMP.Config.GetDefault('allowPatronToEditEmailAddress'))
								,handler:function(){
									var data=['address1','city','state','postal','country','phone','email','userID'];
									var infoPanel = Ext.getCmp('accountPanel_infoPanel');
									var patronInfo = {};
									for (var i=0; i<data.length; i++)
									{
										var x = infoPanel.findById('accountPanel_' + data[i]).getValue()
										//This seems unsafe. What if the server verification fails? Maybe the server should respond with the real data values.
										RWS.Patron.current.data[data[i]] = x; 
										patronInfo[data[i]] = x;
									}
							
									patronInfo.rsn = RWS.Patron.current.data.rsn;
									RWS.Patron.dialog.setActive(false);
									COMP.SendAjaxCommand('all_patron_save_data', patronInfo, RWS.Patron.Saved, RWS.Patron);
								}
							}]
						}]
					}]
				},{
					xtype:'container'
					,width:200
					,defaults:{border:false}
					,items:[{
						xtype:'container'
						,cls:'objectRight'
						,style:'text-align: right;'
						,width:130
						,border:false
						,items:[{	
							xtype:'comboMenu'
							,noStringReload:true
							,showDefaultOption:false
							,id:'accountPanel_language'
							,displayField:'display'
							,valueField:'value'
							,width:100
							,menuItems:[
								{display:L(5465), value:25856} //English
								,{display:L(5466), value:29440} //Spanish
							]
							,value:COMP.Lang.id==25856?25856:29440	
							,listeners:{
								'select':function(){COMP.Config.SetLanguage(this.getValue());
                                               COMP.Config.SetDefault('defaultLang', this.getValue(), false);
											COMP.SendAjaxCommand('rws_save_patron_language', {defaultLang:this.getValue(), ticks:COMP.GetCurrentTicks()}, function(o){}, this);
											COMP.Lang.ReloadAllStrings(Ext.getCmp('accountPanel'));
                                           }
							}		
						},
						COMP.Config.GetDefault('allowPatronToEditPassword') ?
						{
							xtype:'button'
							,id: 'change_password'
							,border:false
							//,cls:'textLink'
							,text:L(6498)	//Change Password
							,handler:function(){RWS.Patron.ChangePassword();}
						}:{border:false}]
					}]	
				},{
					xtype:'linebreak'
				},{
					xtype:'container'
					,layout:'column'
					,defaults:{border:false}
					,width: 200
					,items:[{
						columnWidth:.6
						,xtype:'container'
						,cls:'textRight'
						,items:[
							{xtype:'label', cls:'label', html:L(6789).append(':&nbsp</br>').toString() }
							,{xtype:'label', cls:'label', html:L(6792).append(':&nbsp</br>').toString() }
							,{xtype:'label', cls:'label', html:L(25956).append(':&nbsp').toString() } //'Last Activity'
							,{xtype:'linebreak'}
							,{xtype:'label', cls:'label', html:L(17705).append(':&nbsp').toString() } // lexile
						]
					},{
						columnWidth:.4
						,xtype:'container'
						,bodyStyle:'padding-left:5px;'
						,items:[
							{xtype:'label', id:'accountPanel_finesDue', html:'$0.00</br>'}
							,{xtype:'label', id:'accountPanel_finesPaid', html:'$0.00</br>'}
							,{xtype:'label', id:'accountPanel_lastActivity', html:''}
							,{xtype:'linebreak'}
							,{xtype:'label', id:'accountPanel_lexile', html:''}
						]
					}]   
				}]
			},{
				xtype:'tabpanel'
				,plain:true
				,frame:true
				,height:250
				,activeTab:0
				,items:[{
					id:'accountPanel_loanedItems'
					,title:L(4327)	//Loanded Items
					,xtype:'grid'
					,frame:true
					,stripeRows:true
					,autoExpandColumn:'title'
					,viewConfig:{forceFit:true}
					,plugins:RWS.Patron.accountPanel.checkColumn
					,columns:COMP.Config.GetDefault('allowPatronToRenewItems') ?[
							{header:L(3689), dataIndex:'callnum', width:90}
							,{header:L(3697), dataIndex:'copyBarcode', width:90}
							,{header:L(3688), dataIndex:'title', id:'title'}
							,{header:L(5021), dataIndex:'dueDate', width:90}
							,{header:L(4714), dataIndex:'$0.00', width:90}
							,RWS.Patron.accountPanel.checkColumn
						]:[
							{header:L(3689), dataIndex:'callnum', width:90}
							,{header:L(3697), dataIndex:'copyBarcode', width:90}
							,{header:L(3688), dataIndex:'title', id:'title'}
							,{header:L(5021), dataIndex:'dueDate', width:90}
							,{header:L(4714), dataIndex:'$0.00', width:90}
						]
					,store: new Ext.data.Store({
						reader:new Ext.data.JsonReader({id:'circRSN'}, 
							new Ext.data.Record.create([
								{name:'callnum'}
								,{name:'circRSN'}
								,{name:'copyBarcode'}
								,{name:'created'}
								,{name:'dueDate'}
								,{name:'subtitle'}
								,{name:'tempDesc'}
								,{name:'title'}
								,{name:'type'}
								,{name:'renew', type:'bool'}
							])
						)
					})
					,bbar: COMP.Config.GetDefault('allowPatronToRenewItems')?['->',{
						text:L(6688)
						,handler:function(){
							var grid = Ext.getCmp('accountPanel_loanedItems');
							var store = grid.getStore();
							var circRSNs = new Array();
							for(var i=0; i<store.getTotalCount(); i++)
							{
								var record = store.getAt(i);
								if(record.data.renew)
									circRSNs.add(record.data.circRSN);
							}
							RWS.Patron.RequestRenewals(circRSNs);
						}
					},{
						text:L(7741)
						,handler:function(){
							var grid = Ext.getCmp('accountPanel_loanedItems');
							var store = grid.getStore();
							var circRSNs = new Array();
							for(var i=0; i<store.getTotalCount(); i++)
								circRSNs.add(store.getAt(i).data.circRSN);
								
							RWS.Patron.RequestRenewals(circRSNs);
						}
					}]:[{hidden: true}]
				},{
					id:'accountPanel_holds'
					,title:L(3882)
					,xtype:'grid'
					,frame:true
					,stripeRows:true
					,autoExpandColumn:'title'
					,viewConfig:{forceFit:true}
					,sm:new Ext.grid.RowSelectionModel({singleSelect:true})
					,columns:[
						{header:L(3689), dataIndex:'callnum', width:90}
						,{header:L(3697), dataIndex:'copyBarcode', width:90}
						,{header:L(3688), dataIndex:'title', id:'title'}
						,{header:L(6864), dataIndex:'created', width:90}
						,{header:L(6865), dataIndex:'expired', width:90}
						,{header:L(4879), dataIndex:'type_string', width:90}
					]
					,store: new Ext.data.Store({
						reader:new Ext.data.JsonReader({id:'circRSN'}, 
							new Ext.data.Record.create([
								{name:'callnum'}
								,{name:'circRSN'}
								,{name:'copyBarcode'}
								,{name:'created'}
								,{name:'title'}
								,{name:'expired'}
								,{name:'type'}
								,{name:'type_string'}
							])
						)
					})
					,bbar:COMP.Config.GetDefault('allowPatronToRemoveHolds')?['->',{
						text:L(3767) // Remove (holds)
						,handler:function(){
							var grid = Ext.getCmp('accountPanel_holds');
							var record = grid.getSelectionModel().getSelected();
							var circRSNs = [];
							if (!record)
							{
								alert(L(25957)); //'You must first select a record.');
								return;
							}
							circRSNs.add(record.data.circRSN);
							RWS.Patron.RemoveHolds(circRSNs);
						}
					}]:[{hidden:true}]
				},{
					id:'accountPanel_reservations'
					,title:L(4747)
					,xtype:'grid'
					,frame:true
					,stripeRows:true
					,autoExpandColumn:'title'
					,viewConfig:{forceFit:true}
					,sm:new Ext.grid.RowSelectionModel({singleSelect:true})
					,columns:[
						{header:L(3689), dataIndex:'callnum', width:90}
						,{header:L(3697), dataIndex:'copyBarcode', width:90}
						,{header:L(3688), dataIndex:'title', id:'title'}
						,{header:L(5943), dataIndex:'startDate', width:90}
						,{header:L(4201), dataIndex:'endDate', width:90}
					]
					,store: new Ext.data.Store({
						reader:new Ext.data.JsonReader({id:'circRSN'}, 
							new Ext.data.Record.create([
								{name:'callnum'}
								,{name:'circRSN'}
								,{name:'copyBarcode'}
								,{name:'endDate'}
								,{name:'startDate'}
								,{name:'subtitle'}
								,{name:'title'}
							])
						)
					})
					,bbar:COMP.Config.GetDefault('allowPatronToEditReservations')?['->',{
						text:L(3767) // Remove (reservations)
						,handler:function(){
							var grid = Ext.getCmp('accountPanel_reservations');
							var record = grid.getSelectionModel().getSelected();
							var circRSNs = [];
							if (!record)
							{
								alert(L(25957)); //'You must first select a record.'
								return;
							}
							circRSNs.add(record.data.circRSN);
							RWS.Patron.RemoveReservations(circRSNs);
						}
					}]:[{hidden:true}]
				},{
					id:'accountPanel_charges'
					,title:L(4908) // Charges
					,xtype:'grid'
					,frame:true
					,stripeRows:true
					,autoExpandColumn:'desc'
					,viewConfig:{forceFit:true}
					,sm:new Ext.grid.RowSelectionModel({singleSelect:true})
					,columns:[
						{header:L(4910), dataIndex:'date', width:90} // Date
						,{header:L(4879), dataIndex:'type', width:90}//Type
						,{header:L(4911), dataIndex:'desc', id:'desc'}//Description
						,{header:L(4912), dataIndex:'total', width:90, renderer: Ext.util.Format.usMoney}//Total
						,{header:L(4677), dataIndex:'balance', width:90, renderer: Ext.util.Format.usMoney}//Balance
					]
					,store: new Ext.data.Store({
						reader:new Ext.data.JsonReader({id:'rsn'}, 
							new Ext.data.Record.create([
								{name:'rsn'}
								,{name:'date'}
								,{name:'type'}
								,{name:'desc'}
								,{name:'total'}
								,{name:'balance'}
							])
						)
					})
				},{
					id:'accountPanel_history'
					,title:L(5573) // History
					,bodyCssClass:'patronDetails'
					,listeners:
					{
						activate:function()
						{
							var url = COMP.AssembleURL('/ajax/lws_patron_history', {bc:RWS.Patron.current.data.barcode});
							this.findById('patronHistoryContents').load({url:url});
						}
					}
					,items: {
			   			xtype:'panel'
						,id:'patronHistoryContents'
						,autoScroll:true 
						,bodyStyle:'background-color:white;'
					 }
					,bbar:
					[
						'->',
						{
							text:L(3625) // Print
							,handler:function()
							{
								COMP.OpenWindow(COMP.AssembleURL('/ajax/lws_patron_history', {bc:RWS.Patron.current.data.barcode}));
							}
						}
					]
				}]
			}]
			,listeners:{
				'render':{fn:function(){
					RWS.Patron.loader = this;
					this.loadData();
				}}
			}
			,loadData:function(){
				var pat = RWS.Patron.current.data;
				this.findById('accountPanel_image').setImage(pat.image);
				this.findById('accountPanel_patronName').setHtml(RWS.Patron.current.patName);
				this.findById('accountPanel_barcode').setHtml('&nbsp;&nbsp;&nbsp;&nbsp;('+pat.barcode+')</br>');
				this.findById('accountPanel_expDate').setHtml(pat.expDate);
				this.findById('accountPanel_grade').setHtml(pat.grade);

				this.findById('accountPanel_address1').setValue(pat.address1);
				this.findById('accountPanel_city').setValue(pat.city);
				this.findById('accountPanel_state').setValue(pat.state);
				this.findById('accountPanel_postal').setValue(pat.postal);
				this.findById('accountPanel_country').setValue(pat.country);
				this.findById('accountPanel_phone').setValue(pat.phone);
				this.findById('accountPanel_email').setValue(pat.email);
				this.findById('accountPanel_userID').setValue(pat.userID);
				this.findById('accountPanel_finesDue').setHtml('$' + pat.finesDue + '</br>');
				this.findById('accountPanel_finesPaid').setHtml('$' + pat.finesPaid + '</br>');
				this.findById('accountPanel_lastActivity').setHtml(pat.lastActivity);
				this.findById('accountPanel_lexile').setHtml(pat.lexile);
				Ext.getCmp('accountPanel_language').setValue(COMP.Config.GetDefault('defaultLang'));

				var loanedItems = this.findById('accountPanel_loanedItems');
				loanedItems.getStore().loadData(RWS.Patron.current.checkouts);		

				var holds = this.findById('accountPanel_holds');
				var holdArray=RWS.Patron.current.holds;
				for (var i=0; i<holdArray.length; i++)
					holdArray[i].type_string = CopyStatus(holdArray[i].type);
				holds.getStore().loadData(RWS.Patron.current.holds);	

				var reservations = this.findById('accountPanel_reservations');
				reservations.getStore().loadData(RWS.Patron.current.reservations);

				var charges = this.findById('accountPanel_charges');
				charges.getStore().loadData(RWS.Patron.current.charges);

				this.doLayout();
			}
		}
	}	
	,Show:function(sender){
		if (!COMP.Config.GetDefault('allowPatronToCheckStatusAndDetails'))
			return;
			
		COMP.LoadStylesheet('rws_patron.css');
		RWS.Patron.bid = COMP.GetCurrentTicks();
		this.dialog = new Ext.Window({
			modal: true
			,width:700
			,height:540
			,closeAction: 'close'
			,cls:'patronWindow'
			,layout:'fit'
			,border:false
			,resizable: false
			,defaults:{border:false}
			,items: this.accountPanel
			,listeners:{
				'beforeclose':{fn:function(){/*RWS.Patron.dialog.hide('patronAccountBtn'); */RWS.Patron.bid = null; RWS.Patron.dialog = null;}}
			}
		});
		this.dialog.show(sender);
		if(this.dialog.y < 0) this.dialog.setPosition(this.dialog.x, 0);
		
		// Patron may have added reservations or holds recently. Or maybe something has changed
		// on the server. Reload so we're up to date as possible. This is a bit of a hack tho.
		// A slow server could cause a situation where the user edits something which the reload
		// then overwrites. Ideally, we reload, and let a callback show the window, all while a
		// dialog let's the user know they need to wait a couple seconds. Until then...
		RWS.Patron.Reload();
	}
	
	,Saved : function(o)
	{
		if (o.success)
			alert(L(25958)); //'Your changes have been saved.'
		else
			alert(o.message || L(25959)); //'Unable to save changes. Please check with your local librarian for assistance.'
			
		if (RWS.Patron.dialog)
			RWS.Patron.dialog.setActive(true);
	}
	,ChangePassword:function()
	{
		RWS.Patron.passwordDialog = new RWS.Controls.PatronChangePassword();
		RWS.Patron.passwordDialog.show();
		setTimeout("Ext.getCmp('oldPassword').focus()", 800);
	}
	,PasswordChanged : function(success)
	{
		if (success)
			alert(L(25960));//'Your password was saved successfully.'
		else
			alert(L(25961));//'Unable to save your password change. Please check with your local librarian for assistance.'
	}
	
	// ,ClosePasswordDialog : function()
	// {
	// 	if (RWS.Patron.passwordDialog)
	// 		RWS.Patron.passwordDialog.close();
	// }
	
	,RequestRenewals : function(circRSNs)
	{
		COMP.SendAjaxCommand('all_patron_request_renewals',{rsn_array:circRSNs.toString()}, this.Handled, this);
	}
	
	,RemoveHolds : function(circRSNs)
	{
		COMP.SendAjaxCommand('all_patron_remove_holds',{rsn_array:circRSNs.toString()}, this.Handled, this);
	}
	
	,RemoveReservations : function(circRSNs)
	{
		COMP.SendAjaxCommand('all_patron_remove_reservations',{rsn_array:circRSNs.toString()}, this.Handled, this);
	}
	
	,Handled : function(o)
	{
		if (!o.success)
		{
			alert(L(25962));//'There was an unknown problem handling your request. Try logging out, then back in, and try again.'
			RWS.Patron.Reload();
			return;
		}
		
		alert(o.message,o.title,function() {RWS.Patron.Reload(); });
	}
	
	// Re-request the patron's info from the server and refresh it all.
	,Reload : function(o)
	{
		if (o==undefined)
		{
			COMP.SendAjaxCommand('all_patron_refresh',{bid:RWS.Patron.bid},RWS.Patron.Reload,this);
			return;
		}
		
		if (o.error)
		{
			alert(o.error);
			return;
		}
		
		if (o.bid == RWS.Patron.bid)
		{
			RWS.Patron.current = o;
			RWS.Patron.current.loggedIn = true;
			RWS.Patron.loader.loadData();
		}
	}
};

RWS.Patron.Init();
if (window.COMP) COMP.Broadcast('scriptLoaded_rws_patron');