Ext.ns('COMP.Controls');

// linebreak - A simple line break
Ext.ux.linebreak = Ext.extend(Ext.BoxComponent, {
	autoEl:{
		tag:'div'
		,html:'&nbsp;'
	}
});
Ext.reg('linebreak', Ext.ux.linebreak);

COMP.Controls.AjaxCombo = Ext.extend(Ext.form.ComboBox, {
	initComponent:function() {
		Ext.apply(this,{
			mode:'remote'
			,editable:false
			,valueField:'value'			
			,displayField:'display'
			,winEvents: this.winEvents?Ext.apply(this.winEvents, {'select':'changed'}):{'select':'changed'}
			,store:{
				autoLoad:true
				,url:this.storeUrl
				,reader:new Ext.data.JsonReader({
					root:'records'
					,idProperty:'value'
				}, [{name:'display'}, {name:'value'}])
			}
		});
		COMP.Controls.AjaxCombo.superclass.initComponent.call(this);
	}	
});
Ext.reg('ajaxcombo', COMP.Controls.AjaxCombo);

COMP.Controls.AdminChangePassword = Ext.extend(Ext.Window, {
	initComponent:function() {
		Ext.apply(this,{
			title:L(26110)
			,layout: 'form'
			,width: 600
			,resizable: false
			,plain: true
			,cls:'dialog600'
			,border: false
			,modal: true
			,buttonAlign: 'center'
			,labelWidth:150
			,items: [{
				xtype:'label'
				,html:L(26117)+'</br></br>'
			},{
				xtype:'checkbox'
				,fieldLabel:L(26118)	//Hide Password
				,listeners:{
					'check':{fn:function(checkbox, checked){
						this.findParentByType('adminchangepassword').hidePassword(checked);
					}}
				}
			},{
				xtype:'textfield'
				,fieldLabel:L(6500)	//New Password
				,id:'newPassword'
				,name:'newPassword'
				,allowBlank:false
				
			},{
				xtype:'textfield'
				,fieldLabel:L(26120)	//Confirm New Password
				,id:'confirmPassword'
				,name:'confirmPassword'
				,initialPassField:'newPassword'
				,allowBlank:false
				,validationEvent:'keyup'
				,validateOnBlur:false
			}]
			,bbar:['->',{
				text:L(17140)	//ls_Cancel
				,handler:function(){this.ownerCt.ownerCt.close()}
			},{
				text:'OK'
				,formBind:true
				,handler:function(){
					var newPass = EncryptB64_MD5(Ext.getCmp('newPassword').getValue());
					var newConfirm = EncryptB64_MD5(Ext.getCmp('confirmPassword').getValue());
					
					COMP.SendAjaxCommand('all_admin_change_patron_password',
					{
						patronBarcode:Ext.get('patronBarcode').getValue()
						,'new':myUrlEncode(newPass, newPass)
						,newConfirm:myUrlEncode(newConfirm, newConfirm)
					},LWS.PatronPasswordChanged,LWS);
					this.ownerCt.ownerCt.close();
				}
			}]
		});
		COMP.Controls.AdminChangePassword.superclass.initComponent.call(this);
	}
	,hidePassword:function(hide)
	{
		var inputType = hide?'password':'text';
		var newPwd = Ext.getCmp('newPassword');
		var confPwd = Ext.getCmp('confirmPassword');
		
		var nNewPwd = newPwd.initialConfig;
		nNewPwd.inputType = inputType;
		var nConfPwd = confPwd.initialConfig;
		nConfPwd.inputType = inputType;
		
		Ext.removeNode(newPwd.el.dom.parentNode.parentNode);
		Ext.removeNode(confPwd.el.dom.parentNode.parentNode);
		this.add(nNewPwd);
		this.add(nConfPwd)
		this.doLayout();
		
	}
});
Ext.reg('adminchangepassword', COMP.Controls.AdminChangePassword);

COMP.Controls.ResetPassword = Ext.extend(Ext.Window, {
	initComponent:function() {
		Ext.apply(this,{
			title:L(26110)
			,layout: 'form'
			,width: 500
			,cls:'resetDialog'
			,resizable: false
			,plain: true
			,border: false
			,modal: true
			,buttonAlign: 'center'
			,items: [{
				xtype:'label'
				,html:L(26128)+'</br></br>'	//If you have forgotten your password...
			},{
				xtype:'textfield'
				,id:'resetPwdUsername'
				,fieldLabel:L(26127)	//Enter Username
			}]
			,bbar:['->',{
				text:L(26126)
				,handler:function(){
					var username = Ext.getCmp('resetPwdUsername').getValue();
					var o = {username:username};
					COMP.SendAjaxCommand('all_patron_password_reset', o,
						function(o)
						{
							alert(o.alert);
						});
					this.ownerCt.ownerCt.close();
				}
			},{
				text:L(17140)	//ls_Cancel
				,handler:function(){this.ownerCt.ownerCt.close()}
			}]
		});
		COMP.Controls.ResetPassword.superclass.initComponent.call(this);
	}
});
Ext.reg('resetpassword', COMP.Controls.ResetPassword);

COMP.Controls.PatronChangePassword = Ext.extend(Ext.Window, {
	initComponent:function(){
		Ext.apply(this, {
			title:L(6498)	//Change Password
			,layout:'form'
			,width:500
			,resizable:false
			,plain:true
			,border:false
			,modal:true
			,cls:'resetDialog'
			,buttonAlign:'center'
			,defaults:{inputType:'password'}
			,defaultType:'textfield'
			,items:[{
				xtype:'label'
				,html:L(27395)+'</br></br>'	//ls_You_can_change_your_password
			},{
				fieldLabel:L(6499)	//Old Password
				,id:'oldPassword'
			},{
				fieldLabel:L(6500)	//New Password
				,id:'newPassword'
				,name:'newPassword'
				,allowBlank:false
			},{
				fieldLabel:L(6501)	//Verify Password
				,id:'verifyPassword'
				,name:'verifyPassword'
				,initialPassField:'newPassword'
				,allowBlank:false
				,validationEvent:'keyup'
				,validateOnBlur:false
			}]
			,buttons:[{
				text:L(6498)	//Change Password
				,formBind:true
				,handler:function(){
					var oldPass = Ext.getCmp('oldPassword').getValue();
					var newPass = Ext.getCmp('newPassword').getValue();
					var newConfirm = Ext.getCmp('verifyPassword').getValue();

					COMP.SendAjaxCommand('all_patron_change_password',
					{
						rsn:RWS.Patron.current.data.rsn
						,old:myUrlEncode(oldPass,oldPass)
						,'new':myUrlEncode(newPass, newPass)
						,newConfirm:myUrlEncode(newConfirm, newConfirm)
					},RWS.Patron.PasswordChanged,RWS.Patron);
					this.findParentByType('patronchangepassword').close();
				}
			},{
				text:'Cancel'
				,handler:function(){this.findParentByType('patronchangepassword').close()}
			}]
			
		});
		COMP.Controls.PatronChangePassword.superclass.initComponent.call(this);
	}
});
Ext.reg('patronchangepassword', COMP.Controls.PatronChangePassword);

COMP.Controls.COMPedit = Ext.extend(Ext.form.TextField, {
	initComponent:function() {
		Ext.apply(this,{
			enableKeyEvents:true
			,isLockable:true
			,winEvents:{'keypress':'changed' ,'changed':'changed'}
		});
		COMP.Controls.COMPedit.superclass.initComponent.call(this); 
	}	
///*
   ,afterRender : function() {            
         if(this.qtipText){
                 Ext.QuickTips.register({
                 target:  this.getEl(),
                 title: '',
                 text: this.qtipText,
                 enabled: true
             });
             var label = findLabel(this);
             if (label){
                 Ext.QuickTips.register({
                     target:  label,
                     title: '',
                     text: this.qtipText,
                     enabled: true
                });
             }
           }
           Ext.form.Field.superclass.afterRender.call(this);
            this.initEvents();
            this.initValue();
   }
 //*/
});
Ext.reg('COMPedit', COMP.Controls.COMPedit);

COMP.Controls.COMPtextArea = Ext.extend(Ext.form.TextArea, {
	initComponent:function() {
		Ext.apply(this,{
			enableKeyEvents:true
			,isLockable: true
			,winEvents:{
					'keypress':'changed'
					,'changed':'changed'
			}
		});
		COMP.Controls.COMPtextArea.superclass.initComponent.call(this);
	}	
///*
   ,afterRender : function() {            
         if(this.qtipText){
                 Ext.QuickTips.register({
                 target:  this.getEl(),
                 title: '',
                 text: this.qtipText,
                 enabled: true
             });
             var label = findLabel(this);
             if(label){
                 Ext.QuickTips.register({
                     target:  label,
                    title: '',
                     text: this.qtipText,
                     enabled: true
                });
             }
           }
           Ext.form.Field.superclass.afterRender.call(this);
            this.initEvents();
            this.initValue();
   }
 //*/
});
Ext.reg('COMPtextArea', COMP.Controls.COMPtextArea);


COMP.Controls.COMPcheckBox = Ext.extend(Ext.form.Checkbox, {
	initComponent:function() {
		Ext.apply(this,{
			enableKeyEvents:true
			,isLockable: true
			,winEvents:Ext.apply({
					'check':'changed'
			}, this.winEvents)
		});
		COMP.Controls.COMPcheckBox.superclass.initComponent.call(this);
	}
///*
   ,afterRender : function() {            
         if(this.qtipText){
                 Ext.QuickTips.register({
                 target:  this.getEl(),
                 title: '',
                 text: this.qtipText,
                 enabled: true
             });
             var label = findLabel(this);
             if(label){
                 Ext.QuickTips.register({
                     target:  label,
                    title: '',
                     text: this.qtipText,
                     enabled: true
                });
             }
           }
           Ext.form.Field.superclass.afterRender.call(this);
            this.initEvents();
            this.initValue();
   }
 //*/	
	,setInitValue:function(v)
	{
        var checked = this.checked ;
        this.checked = (v === true || v === 'true' || v == '1' || String(v).toLowerCase() == 'on');
        if(this.rendered){
            this.el.dom.checked = this.checked;
            this.el.dom.defaultChecked = this.checked;
        }
        return this;
    }
});
Ext.reg('COMPcheckBox', COMP.Controls.COMPcheckBox);

// Nothing overriden at this time.
var COMPbutton = COMP.Controls.COMPbutton = Ext.extend(Ext.Button, {
	initComponent:function() {
		Ext.apply(this, {
			isLockable: true
		});
		this.refreshTooltip();
		COMPbutton.superclass.initComponent.apply(this, arguments);
	},
	refreshTooltip: function(){
		if (this.tooltip && this.tooltip.isLang) {
			this.setTooltip(this.tooltip.toString());
		}
	},
	setToolTip: function(tip){
		if (tip && tip.isLang) {
			arguments[0] = tip.toString();
		}
		COMPbutton.superclass.setToolTip.apply(this, arguments);
	}
});
Ext.reg('COMPbutton', COMP.Controls.COMPbutton);


COMP.Controls.COMPdateField = Ext.extend(Ext.form.DateField, {
	initComponent:function() {
		Ext.apply(this,{
			enableKeyEvents:true
			,isLockable: true
			,winEvents:{
					'keypress':'changed'
					,'changed':'changed'
					,'select':'changed'
			}
		});
		COMP.Controls.COMPdateField.superclass.initComponent.call(this);
	}	
    ///*
   ,afterRender : function() {            
         if(this.qtipText){
                 Ext.QuickTips.register({
                 target:  this.getEl(),
                 title: '',
                 text: this.qtipText,
                 enabled: true
             });
             var label = findLabel(this);
             if(label){
                 Ext.QuickTips.register({
                     target:  label,
                    title: '',
                     text: this.qtipText,
                     enabled: true
                });
             }
           }
           Ext.form.Field.superclass.afterRender.call(this);
           this.initEvents();
            this.initValue();
   }
 //*/
});
Ext.reg('COMPdateField', COMP.Controls.COMPdateField);

// This is a near 100% copy of the comboMenu class which is currently RWS only.
// This file should be shared so comboMeu will go away and stick with the
// new name due to historical C++ reasons. For now, I just don't want to
// break the rws.
// opt is an array which can be used by the parent of this object to activate/deactivate items.
COMP.Controls.COMPpopupMenu = Ext.extend(COMP.Controls.COMPbutton, {
	defaultText: ''
	,defaultID: ''
	,cls: 'comboMenu'
	,style:'text-align: left;'
	,selectedID: -1
	,valueField:'value'
	,displayField:'display'
	,showDefaultOption:true
	,parentWid:0
	,width:150
	,preKeystrokeCallback:0
	,isLockable: true
	,xtype:'COMPpopupMenu'
	,listeners:{
		'click':{fn:function(m, i, e){
		if (this.preKeystrokeCallback && this.parentWid)
		{
			COMP.WinExec(this.parentWid, this.preKeystrokeCallback, m);
		}
		}}
	}
	,initComponent: function(){
		if(this.storeUrl){
			var store = new Ext.data.JsonStore({
				autoLoad:true
				,url:this.storeUrl
				,root:'records'
				,idProperty:this.valueField
				,fields:[this.displayField, this.valueField]
			});
			store.on('load', this.onLoad, this);
			store.load();
			Ext.apply(this, {store:store});
		}
		Ext.apply(this, {titles:[],opt:[]});
		Ext.apply(this, {
			maxWidth: this.width - 10
			,menu: new Ext.menu.Menu({uid:this.uid + 'Menu', allowOtherMenus:true})
			,winEvents: this.winEvents?Ext.applyIf(this.winEvents, {'select':'changed'}):{'select':'changed'}
		});
		COMP.Controls.COMPpopupMenu.superclass.initComponent.apply(this, arguments);
		if (this.menuItems && this.menuItems.length) {
			this.replaceMenu(this.menuItems);
		}
	}
///*
   ,afterRender : function() {
		if(this.qtipText){
			Ext.QuickTips.register({
				target:  this.getEl(),
				title: '',
				text: this.qtipText,
				enabled: true
			});
			var label = findLabel(this);
			if(label){
				Ext.QuickTips.register({
					target:  label,
					title: '',
					text: this.qtipText,
					enabled: true
				});
			}
		}
		COMP.Controls.COMPpopupMenu.superclass.afterRender.call(this);
   }
 //*/
	,setLabel: function(text)
	{
		var el = this.getEl();
		if (el && el.up)
		{
			var r = el.up('div.x-form-item');
			if (r && r.dom && r.dom.firstChild) {
				r.dom.firstChild.innerHTML = text;
				return;
			}
		}
		this.fieldLabel = text;
	}
	,onRender:function(){
		
		if(this.menuItems && this.menuItems.length)
			this.menu = this.createMenu(this.menuItems);
		if(this.replaceOnRender){
			this.titles = [];
			this.opt = [];
			this.menu.removeAll();
			this.addItems(this.menu, this.replaceOnRender);
		}
		if(this.selectOnRender) {
			this.setValue(this.selectOnRender);
		}
		this.isRendered = true;
		
		COMP.Controls.COMPpopupMenu.superclass.onRender.apply(this, arguments);
	}
	,onLoad:function(){
		if(this.store){
			var data = [];
			var records = this.store.getRange();
			for(var i = 0; i < records.length; i ++){
				data.add(records[i].data);
			}
		}
		this.menu = this.createMenu(data);
	}
	,createMenu:function(data){
		// Create the menu.
		var menu = new Ext.menu.Menu({uid:this.uid + 'Menu', allowOtherMenus:true});

		// Add the items to the new menu.
		this.addItems(menu, data);

		// Set the default.
		if(typeof(this.defaultID) != undefined)
			this.setSelectedID(this.defaultID);
		return menu;
	}
	,replaceMenu:function(data, opt)
	{
		if (!this.menu)	return;
		else if (!data) return;
		else if ((!this.menuItems || this.menuItems.length == 0) && !this.store && !this.isRendered){
			this.replaceOnRender = data;
			return;
		}	
		// Clear any existing titles and menu items.
		this.titles = [];
		this.opt = opt;
		this.menu.removeAll();
		
		// Add the items to the existing menu.
		this.addItems(this.menu, data);
	}
	,addItems:function(menu, data)
	{
		if(this.showDefaultOption && this.defaultText != ''){
			var defaultItem = menu.addMenuItem({uid:'', text: this.defaultText});
			defaultItem.on('click', function(c){
				this.clickedItem(c);
			}, this);
			this.titles[this.defaultID] = this.defaultText;
			this.setSelectedID(this.defaultID);
		}
		for(var i = 0; i < data.length; i++){
			var item = data[i];
			
			function onClick(menuItem)	{this.clickedItem(menuItem)};
			
			if(item.menuItems)
				item.items = item.menuItems;
			if (item=='-')
			{
				menu.addSeparator();
			}
			else if (item.items){
				var menuItem = menu.addMenuItem({text: item[this.displayField], menu: item.items});
				for(var j = 0; j < menuItem.menu.items.items.length; j ++){
					var currentItem = menuItem.menu.items.items[j]
					this.titles[currentItem[this.valueField]] = currentItem[this.displayField];
					currentItem.uid = currentItem[this.valueField];
					var delegate = onClick.createDelegate(this, [item], 0);
					currentItem.on('click', delegate,  this);
				};
			}
			else{
				var menuItem = menu.addMenuItem({text: item[this.displayField], menu: item.items});
				this.titles[item[this.valueField]] = item[this.displayField];
				item.uid = item[this.valueField];
				var delegate = onClick.createDelegate(this, [item], 0);
				menuItem.on('click', delegate, this);
			}
		}
		
	}
	,clickedItem:function(c){
		this.setSelectedID(c.uid);
		this.fireEvent('select', this);
	}
	,setSelectedID:function(uid){
		if (!uid && uid !== 0) return;
		
		this.selectedID = uid;
		var title = this.titles[uid];
		if(!title) title = this.defaultText;
		
		if (this.menuItems && this.menuItems.length > 0 && !this.isRendered)
		{
			var valField = this.valueField || 'value';
			var disp = this.displayField || 'display';
			
			for (var i=0; i<this.menuItems.length; i++) {
				if (this.menuItems[i][valField] == uid) {
					title = this.menuItems[i][disp];
					break;
				}
			}
		}
		else {
			this.selectOnRender = uid;
		}
		
		
		if (this.displayAsHTML)
		{
			if (this.btnEl)
			{
				this.btnEl.update(title);
			}
			else
			{
				this.on('afterrender', function(){
					this.btnEl.update(title);
					
				},this);			
			}
		}
		else
		{	
			var abbr = COMP.fitStringToWidth(title, this.maxWidth - 22, 'size12Font');
			this.setText(abbr);
		}
		
	}
	,isValidUID:function(uid)
	{
	  var title = this.titles[uid];
	  return title;
	}
	,getValue:function(){
		return this.titles.length || this.titles[this.selectedID] ? this.selectedID : this.defaultID; //This conditional was reversed, I think. I changed it. (so it's now correct)
	}
	,setValue:function(val){
		if ((typeof(val) == 'number' && val >= 0) || val)
			this.setSelectedID(val);
	}
});
Ext.reg('COMPpopupMenu', COMP.Controls.COMPpopupMenu);

COMP.Controls.SubTabPanel = Ext.extend(Ext.TabPanel, {
	activeTab:0
	,initComponent:function(){
		Ext.apply(this, {
			plain:true
			,baseCls:'x-subtab-panel'
		});
	COMP.Controls.SubTabPanel.superclass.initComponent.call(this);
	}
});
Ext.reg('subtabpanel', COMP.Controls.SubTabPanel);

//A DisableMenu will disable all of it's items automatically when it is clicked so a 
//function needs to be tied to its enableitems event
COMP.Controls.DisableMenu = Ext.extend(Ext.SplitButton, {
	initComponent:function(){
		COMP.Controls.DisableMenu.superclass.initComponent.call(this);
		this.addEvents('enableitems');
	}
	,disableAllItems:function(){
		for( var i = 0; i < this.menu.items.length; i++)
		{
			var item = this.menu.items.items[i];
			item.disable();	
		};
	}
   	,onClick : function(e, t){
   	    e.preventDefault();
   	    if(!this.disabled){
   	        if(this.menu && !this.menu.isVisible() && !this.ignoreNextClick){
			this.showMenu();
   	        }
			this.disableAllItems();
   	        this.fireEvent("click", this, e);
   	        if(this.handler){
   	            	this.handler.call(this.scope || this, this, e);
   	        }
			this.fireEvent("enableitems", this, e);
			if(this.enableItems){
				this.enableItems.call(this.scope || this, this, e);
			}
   	    }
   	}
	//Enable a menu item based on it's click winEvent.
	,enableItem:function(eventName){
		for(var i=0; i<this.menu.items.length; i++)
		{
			var item = this.menu.items.items[i];
			if(item.winEvents && item.winEvents['click'] == eventName)
			{
				item.enable();
				return;
			}
		}
	}
});
Ext.reg('disablemenu', COMP.Controls.DisableMenu);


COMP.Controls.GearMenu = Ext.extend(COMP.Controls.DisableMenu, {
	initComponent:function(){
		COMP.Controls.GearMenu.superclass.initComponent.call(this);
		Ext.apply(this, {
			iconCls:'actions'
		});
	}
});
Ext.reg('gearmenu', COMP.Controls.GearMenu);

COMP.Controls.COMPradioButtonGroup = Ext.extend(Ext.form.RadioGroup, {
	initComponent:function(){
		Ext.apply(this, {
			isLockable: true
		});
		if (this.winEvents) Ext.apply(this.winEvents, {'change':'changed'});
		else this.winEvents = {'change':'changed'};
		COMP.Controls.COMPradioButtonGroup.superclass.initComponent.call(this);
	}
///*
   ,afterRender : function() {            
         if(this.qtipText){
                 Ext.QuickTips.register({
                 target:  this.getEl(),
                 title: '',
                 text: this.qtipText,
                 enabled: true
             });
             var label = findLabel(this);
             if(label){
                 Ext.QuickTips.register({
                     target:  label,
                    title: '',
                     text: this.qtipText,
                     enabled: true
                });
             }
           }
           Ext.form.Field.superclass.afterRender.call(this);
           this.initEvents();
           this.initValue();
   }
 //*/
	,getValue:function()
	{
		return COMP.Controls.COMPradioButtonGroup.superclass.getValue.call(this).inputValue;
		// return this.initialConfig.inputValue;
	}
});
Ext.reg('COMPradioButtonGroup', COMP.Controls.COMPradioButtonGroup);

COMP.Controls.MenuTextArea = Ext.extend(Ext.Container, {
	height:60
	,width:100
	,initComponent:function(){
		Ext.apply(this,{
			items:[{
				xtype:'textarea'
				,height:this.height
			},{
				xtype:'button'
				,iconCls:'actions'
				,menu:this.menu
				,style:'position:absolute;bottom:-10;'
			}]
		});
		COMP.Controls.MenuTextArea.superclass.initComponent.call(this);
	}
});
Ext.reg('menutextarea', COMP.Controls.MenuTextArea);

///*
 Ext.override(Ext.form.Field, {
   afterRender : function() {            
         if(this.qtipText){
                 Ext.QuickTips.register({
                 target:  this.getEl(),
                 title: '',
                 text: this.qtipText,
                 enabled: true
             });
             var label = findLabel(this);
             if(label){
                 Ext.QuickTips.register({
                     target:  label,
                    title: '',
                     text: this.qtipText,
                     enabled: true
                });
             }
           }
           Ext.form.Field.superclass.afterRender.call(this);
            this.initEvents();
            this.initValue();
   }
 });
// */

var findLabel = function(field) {
    
    var wrapDiv = null;
    var label = null
    //find form-element and label?
    wrapDiv = field.getEl().up('div.x-form-element');
    if(wrapDiv) 
    {
        label = wrapDiv.child('label');        
    }
    if(label) {
        return label;
    }
    
    //find form-item and label
    wrapDiv = field.getEl().up('div.x-form-item');
    if(wrapDiv) 
    {
        label = wrapDiv.child('label');        
    }
    if(label) {
        return label;
    }   
    
     wrapDiv = field.getEl().up('div.x-form-cb');
    if(wrapDiv) 
    {
        label = wrapDiv.child('label');        
    }
    if(label) {
        return label;
    } 
} 

COMP.Controls.CalendarDay = Ext.extend(Ext.BoxComponent, {
	constructor:function(config){
		Ext.apply(this,{
			autoEl:{
				cls:'calDay'
				,tag:'div'
				,cn:[{
					tag:'div'
					,id:'day-text'
					,cls:'calDay-text'
				}
				,{
					tag:'div'
					,cls:'midDay-text'
				}
				,{
					tag:'div'
					,cls:'botDay-text'
				}
				]
			}
			,listeners:{'render':this.initDD,'beforedestroy':this.beforeDestroy}
		});
		this.addEvents(['mouseover', 'click']);
		COMP.Controls.CalendarDay.superclass.constructor.call(this,config);
	}
	,inUse:0
	,middleText:''
	,bottomText:''
	,color:''
	,initComponent:function(){
		COMP.Controls.CalendarDay.superclass.initComponent.apply(this, arguments);
	}
	,initDD:function(cmp){
		cmp.dragZone = new Ext.dd.DragZone(cmp.getEl(),{
			getDragData:function(e){
				var sourceEl = e.getTarget();
				if(sourceEl){
					var d  = Ext.DomHelper.createDom({
						tag:'div'
						,html:'Drag to select days'
						,cls:'calDrag'
						,id:Ext.id()
					});
					return {
						ddel:d
						,ddcmp:cmp
						,sourceEl:sourceEl
						,repairXY:Ext.fly(sourceEl).getXY()
					}
				}
			}
			,getRepairXY:function(){
				return this.dragData.repairXY;
			}
		});
		cmp.dropTarget = new Ext.dd.DropTarget(cmp.getEl(),{
			parent:cmp
			, notifyEnter:function(dragSrc, e, data){
				var cal = this.parent.findParentByType(this.parent.parentType);
				cal.highlightDays(data.ddcmp, cmp);
			}
			,notifyDrop:function(dragSrc, e, data){
				var parent = this.parent.findParentByType(this.parent.parentType);
				if (parent && parent.daysDragged && typeof(parent.daysDragged) == 'function')
					parent.daysDragged(data.ddcmp.date, cmp.date);
			}
		});
	}
	,onRender:function(){
		COMP.Controls.CalendarDay.superclass.onRender.apply(this, arguments);
		this.el.on('mouseover', this.onMouseOver, this);
		this.el.on('click', this.onClick, this);
		this.el.addClassOnOver('calDay-over');
		
		this.updateMiddleText();
		this.updateBottomText();
		this.updateTextColor();
	}
	,beforeDestroy: function(cmp)
	{
		if (cmp)
		{
			Ext.dd.Registry.unregister(cmp.dropTarget);
			Ext.dd.Registry.unregister(cmp.dragZone);
		}
	}
	,updateDayText: function(selMonth){
		if(this.date)
		{
			this.removeClass('calDay-current');
			var dayTxt = this.getDayOfMonth();
			this.getEl().first().update(dayTxt);
			if(this.date.getMonth() != selMonth)
				this.addClass('calDay-notCurrentMonth');
			else
				this.removeClass('calDay-notCurrentMonth');
		}
	}
	,updateMiddleText: function(str){
		this.middleText = str === '' ? '' : str || this.middleText;
		var ele = this.getEl();
		if (ele) ele.first().next().update(this.middleText);
	}
	,updateBottomText: function(str){
		this.bottomText = str === '' ? '' : str || this.bottomText;
		var ele = this.getEl();
		if (ele) ele.first().next().next().update(this.bottomText);
	}
	,updateTextColor: function(color){
		this.color = color;
		var ele = this.getEl();
		if (ele) ele.first().next().next().setStyle('color', this.color);
	}
	,getDayOfMonth:function(){
		return this.date.getDate();
	}
	,onMouseOver:function(e){
		this.fireEvent('mouseover', this, e);	
	}
	,onClick:function(e){
		var parent = this.findParentByType(this.parentType);
		if (parent && parent.dayClick && typeof(parent.dayClick) == 'function')
			parent.dayClick(this.date.toDateString());
	}
	,setAsCurrent:function(){
		if(!this.rendered)
			this.on('afterrender',function(){this.addClass('calDay-current');}, this);
		else
			this.addClass('calDay-current');
		this.current = true;
	}
	,highlight:function(available){
		if(available && !this.inUse)
		{
			this.addClass('calDay-over');
			this.available = true;
		}
		else
		{
			this.addClass('calDay-unavailable');
			this.available = false;
		}
	}
	,removeHighlight:function(){
		this.removeClass('calDay-over');	
		if (this.available) this.removeClass('calDay-unavailable');
	}
	,getCalPosition:function(){
		if(this.rowNum)
			return this.rowNum.toString()+this.day.toString();
	}
});
Ext.reg('calendarday', COMP.Controls.CalendarDay);

COMP.Controls.CalendarRow = Ext.extend(Ext.Container, {
	constructor:function(config){
		Ext.apply(this,{
			layout:'hbox'
			,layoutConfig:{align:'stretch'}
			,defaults:{flex:1,parentType:config.parentType,row:config.row}
			,items:[{
				xtype:'calendarday'	
				,text:'1'
				,day:0
			},{
				xtype:'calendarday'	
				,text:'2'
				,day:1
			},{
				xtype:'calendarday'	
				,text:'3'
				,day:2
			},{
				xtype:'calendarday'	
				,text:'4'
				,day:3
			},{
				xtype:'calendarday'	
				,text:'5'
				,day:4
			},{
				xtype:'calendarday'	
				,text:'6'
				,day:5
			},{
				xtype:'calendarday'	
				,text:'7'
				,day:6
			}]
		});
		COMP.Controls.CalendarRow.superclass.constructor.call(this,config);
	}
	,setDays:function(days, selMonth){
		for(var d=0; d < 7; d++)
		{
			var day = this.find('day', d)[0];
			day.date = days[d];
			day.rowNum = this.row;
			
			if(!this.rendered)
				day.on('afterrender',function(){
					this.updateDayText(selMonth)
				}, day);
			else
				day.updateDayText(selMonth);
		}
	}
	,getDay:function(num){
		return this.find('day', num)[0];
	}
	,getDayDate:function(num)
	{
		var day = this.find('day', num)[0];
		day = '';
	}

});
Ext.reg('calendarrow', COMP.Controls.CalendarRow);

COMP.Controls.Calendar = Ext.extend(Ext.Container, {
	constructor:function(config){
		this.currDate = new Date();
		this.selectedDays = new Array();
		this.config = config;
		this.parentType = config.myType;
		this.calItems = [{
			id:'calContainer'
			,flex:1
			,layout:'vbox'
			,layoutConfig:{align:'stretch'}
			,tbar:{
				cls:'resCal-toolbar'
				,items:[
					{
						xtype:'COMPpopupMenu'
						,id:'calMonth'
						,defaultID:this.currDate.getMonth()
						,parentType:this.parentType
						,listeners:{
							select:function(combo, record, index){
								var cal = combo.findParentByType(this.parentType);
								cal.selMonth = combo.getValue();
								cal.setDays();
								if (cal.changeListener)
									cal.changeListener();
							}
						}
						//The Month values are 0 - 11 to reflect the values returned by the javascript getMonth() function
						,menuItems:[
							{
								display:L(17061)	//January
								,value:0
							},{
								display:L(17062)	//Feberuary
								,value:1
							},{
								display:L(17063)	//March
								,value:2
							},{
								display:L(17064)	//April
								,value:3
							},{
								display:L(17065)	//May
								,value:4
							},{
								display:L(17066)	//June
								,value:5
							},{
								display:L(17067)	//July
								,value:6
							},{
								display:L(17068)	//August
								,value:7
							},{
								display:L(17069)	//September
								,value:8
							},{
								display:L(17070)	//October
								,value:9
							},{
								display:L(17071)	//November
								,value:10
							},{
								display:L(17072)	//December
								,value:11
							}
						]
					}
					,{
						xtype:'COMPpopupMenu'
						,id:'calYear'
						,defaultID:this.currDate.getFullYear()
						,parentType:this.parentType
						,listeners:{
							select:function(combo, record, index){
								var cal = combo.findParentByType(this.parentType);
								cal.selYear = combo.getValue();
								if (cal.changeListener)
									cal.changeListener();
								cal.setDays();
								}
							}
						,menuItems:[{
								display:(this.currDate.getFullYear()-1).toString()
								,value:this.currDate.getFullYear()-1
							}
							,{
								display:this.currDate.getFullYear().toString()
								,value:this.currDate.getFullYear()
							}
							,{
								display:(this.currDate.getFullYear()+1).toString()
								,value:this.currDate.getFullYear()+1
							}
							,{
								display:(this.currDate.getFullYear()+2).toString()
								,value:this.currDate.getFullYear()+2
							}
							,{
								display:(this.currDate.getFullYear()+3).toString()
								,value:this.currDate.getFullYear()+3
							}]
					}
					,'->'
					,{
						xtype:'button'
						,text:L(4626)	//Previous
						,parentType:this.parentType
						,handler:function(b, e){
							var cal = b.findParentByType(this.parentType)
							if (cal)
							{
								cal.previousMonth();
								if (cal.changeListener)
									cal.changeListener();
								
							}
						}
					}
					,{
						xtype:'button'
						,text:'Current'	//NLS
						,parentType:this.parentType
						,handler:function(b, e){
							var cal = b.findParentByType(this.parentType);
							if (cal)
							{
								cal.currentMonth();
								if (cal.changeListener)
									cal.changeListener();
							}
						}
					}
					,{
						xtype:'button'
						,text:L(4625)	//Next
						,parentType:this.parentType
						,handler:function(b, e){
							var cal = b.findParentByType(this.parentType);
							if (cal)
							{
								cal.nextMonth();
								if (cal.changeListener)
									cal.changeListener();
							}
						}
					}
				]
			}
			,items:[{
				height:35
				,layout:'hbox'
				,layoutConfig:{align:'stretch'}
				,defaults:{flex:1}
				,defaultType:'button'
				,style:'padding:5px;'
				,items:[{
					text:'Sun'
					,parentType:this.parentType
					,handler:function(b, e){
//						b.findParentByType(this.parentType).selectColumn(0);
//						alert('Select Sunday column');
					}
				}
				,{
					text:'Mon'	
					,parentType:this.parentType
					,handler:function(b, e){
//						b.findParentByType(this.parentType).selectColumn(1);
//						alert('Select Monday column');
					}
				}
				,{
					text:'Tue'	
					,parentType:this.parentType
					,handler:function(b, e){
//						b.findParentByType(this.parentType).selectColumn(2);
//						alert('Select Tuesday column');
					}
				}
				,{
					text:'Wed'	
					,parentType:this.parentType
					,handler:function(b, e){
//						b.findParentByType(this.parentType).selectColumn(3);
//						alert('Select Wednesday column');
					}
				}
				,{
					text:'Thur'	
					,parentType:this.parentType
					,handler:function(b, e){
//						b.findParentByType(this.parentType).selectColumn(4);
//						alert('Select Thursday column');
					}
				}
				,{
					text:'Fri'	
					,parentType:this.parentType
					,handler:function(b, e){
//						b.findParentByType(this.parentType).selectColumn(5);
//						alert('Select Friday column');
					}
				}
				,{
					text:'Sat'
					,parentType:this.parentType
					,handler:function(b, e){
//						b.findParentByType(this.parentType).selectColumn(6);
//						alert('Select Saturday column');
					}
				}]
			}
			,{
				id:'dateContainer'
				,flex:1
				,layout:'vbox'
				,layoutConfig:{align:'stretch'}
				,defaults:{flex:1,parentType:this.parentType}
				,style:'padding-left:5px; padding-right:5px; padding-bottom:5px;'
				,items:[{
					xtype:'calendarrow'
					,id:'row1'
					,row:1
				}
				,{
					xtype:'calendarrow'
					,id:'row2'
					,row:2
				}
				,{
					xtype:'calendarrow'
					,id:'row3'
					,row:3
				}
				,{
					xtype:'calendarrow'
					,id:'row4'
					,row:4
				}
				,{
					xtype:'calendarrow'
					,id:'row5'
					,row:5
				}
				,{
					xtype:'calendarrow'
					,id:'row6'
					,row:6
				}]
			}]
		}]
		var itms = [];
		if (this.config.topItems)
			itms.add(this.config.topItems);
		itms.add(this.calItems);
		if (config.bottomItems)
			itms.add(config.bottomItems);
		Ext.apply(this,{
			id:'calendar'
			,layout:'vbox'
			,layoutConfig:{align:'stretch'}
			,items:itms
		});
		COMP.Controls.Calendar.superclass.constructor.call(this,config);
	}
	,initComponent:function(){
		COMP.Controls.Calendar.superclass.initComponent.apply(this, arguments);
		this.selMonth = this.currDate.getMonth();
		this.selYear = this.currDate.getFullYear();
		this.on('afterrender', this.setDays, this);
	}
	,setDays:function(){
		var month = this.selMonth;
		var year = this.selYear;

		this.clearDays();
		
		// Need to add 1 day to get the first calendar date.
		var dayDate = this.preCalDate();
		
		var rowDays = new Array();
		var row;
		for(var r=1; r<=6; r++)
		{
			row = this.findById('row'+r);
			if (!row)
				continue;
			for(var d=0; d <= 6; d++)
			{
				dayDate = dayDate.AddDays(1);
				rowDays[d] = new Date(dayDate);
			}
			row.setDays(rowDays, this.selMonth);
		}

		if(this.currDate.getMonth() == month && this.currDate.getFullYear() == year)
 			this.highlightCurrentDate();
	}
	,clearDays:function()
	{
	}
	// Need to add 1 day to get the first calendar date.
	,preCalDate:function()
	{
		var month = this.selMonth;
		var year = this.selYear;
		var lastDayOfPrevMonth = new Date(year, month, 1).AddDays(-1);
		var lastDayOfPrevMonthDOW = lastDayOfPrevMonth.getDay();
		var dayDate = lastDayOfPrevMonth;

		var startDOW = 0;
		//Put the days of the end of the previous month on the first row if needed.
		if(lastDayOfPrevMonthDOW != 6)
			startDOW = lastDayOfPrevMonthDOW;

		if(startDOW != 0 || (startDOW == 0 && lastDayOfPrevMonthDOW == 0))
			dayDate = dayDate.AddDays(-startDOW-1);

		return dayDate;

	}
	// 1 based.
	,findNthDay:function(targetDay){
		var c = 0;
		for(var r = 1; r <= 6; r++)
		{
			var row = this.findById('row'+r);
			if (!row)
				return 0;
			for(var d=0; d<= 6; d++)
			{
				c++;
				if (c == targetDay)
				{
					var day = row.getDay(d);
					return day;
				}
			}
		}
		return 0;
	}
	,getNextDay:function(day){
		var row;
		var dayNum = day.day;
		if(dayNum==6)
		{
			row = this.findById('row'+(day.rowNum+1));
			if(row)
				return	row.getDay(0);
		}
		else
		{
			row = this.findById('row'+day.rowNum);
			if(row)
				return row.getDay(dayNum+1);
		}
	}
	,getPreviousDay:function(day){
		var row;
		var dayNum = day.day;
		if(dayNum==0)
		{
			row = this.findById('row'+(day.rowNum-1));
			if(row)
				return	row.getDay(6);
		}
		else
		{
			row = this.findById('row'+day.rowNum);
			if(row)
				return row.getDay(dayNum-1);
		}
	}
	,removeHighlights:function(){
		for(var r=1; r<=6; r++)
		{
			var row = this.findById('row'+r);
			if (!row)
				continue;
			for(var d=0; d<=6; d++)
			{
				var day = row.getDay(d);
				day.removeHighlight();
			}
		}
	}
	,highlightCurrentDate:function(){
		var currDay;
		for(var r=1; r<=6; r++)
		{
			var row = this.findById('row'+r);
			if (!row)
				continue;
			for(var d=0; d<=6; d++)
			{
				var day = row.getDay(d);
				if (day.date.indexString() == this.currDate.indexString())
				{
					currDay = day;
					break;
				}
			}
		}
		this.currentDay = currDay;
		if (currDay)
			currDay.setAsCurrent();
	}
	,highlightDays:function(startDay, endDay){
		this.removeHighlights();
		//Get positions of the current, start and end days in the calendar
		var currDayPos = this.currentDay.getCalPosition();
		var sDayPos = startDay.getCalPosition();
		var eDayPos = endDay.getCalPosition();
		
		var isCurrMonth, isPrevYear = false;
		var selYear = this.selYear;
		//Determine whether we're showing the current month and year
		if(this.currDate.getMonth() == this.selMonth && this.currDate.getFullYear() == selYear)
			isCurrMonth = true;
		//Determine whether we're showing a previous year
		if(selYear < this.currDate.getFullYear())
			isPrevYear = true;

		this.selectedDays = new Array();
		var cDayPos = sDayPos;
		var day = startDay;
		var avail = true;
		if(isPrevYear || (isCurrMonth && (cDayPos < currDayPos)))
			avail = false;
		day.highlight(avail);
		this.selectedDays.add(day);
		//Check which direction we're highlighting
		if(sDayPos < eDayPos)
			while(cDayPos < eDayPos)
			{
				day = this.getNextDay(day);
				if(day)
				{
					if(isPrevYear || (isCurrMonth && (cDayPos < currDayPos-1)))
						avail = false;
					else
						avail = true;
					day.highlight(avail);
					this.selectedDays.add(day);
				}
				if(cDayPos.toString().substring(1) == 6)
					cDayPos = cDayPos+4;
				else
					cDayPos++;
			}
		else
			while(cDayPos > eDayPos)
			{
				day = this.getPreviousDay(day);
				if(day)
				{
					if(isPrevYear || (isCurrMonth && (cDayPos <= currDayPos)))
						avail = false;
					else
						avail = true;
					day.highlight(avail);
					this.selectedDays.add(day);
				}
				if(cDayPos.toString().substring(1) == 0)
					cDayPos = cDayPos-4;
				else
					cDayPos--;
			}
			
	}
	,currentMonth:function(){
		this.selMonth = this.currDate.getMonth();
		this.selYear = this.currDate.getFullYear();
		var month = this.findById('calContainer').getTopToolbar().findById('calMonth');
		var year = this.findById('calContainer').getTopToolbar().findById('calYear');
		month.setValue(this.selMonth);
		year.setValue(this.selYear);
		this.setDays();
	}
	,previousMonth:function(){
		var month = this.findById('calContainer').getTopToolbar().findById('calMonth');
		if(this.selMonth == 0)
		{
			var year = this.findById('calContainer').getTopToolbar().findById('calYear');
			//Don't let them go less than 1 year in the past
			if(this.selYear == this.currDate.getFullYear()-1)
				return;
			this.selYear--;
			year.setValue(this.selYear);
			this.selMonth = 11;
		}
		else
			this.selMonth--;
		month.setValue(this.selMonth);
		this.setDays();
	}
	,nextMonth:function(){
		var month = this.findById('calContainer').getTopToolbar().findById('calMonth');
		if(this.selMonth == 11)
		{
			var year = this.findById('calContainer').getTopToolbar().findById('calYear');
			//Don't let them go further then 3 years ahead of the current date
			if(this.selYear == this.currDate.getFullYear()+3)
				return;
			this.selYear++
			year.setValue(this.selYear);
			this.selMonth = 0;
		}
		else
			this.selMonth++;
		month.setValue(this.selMonth);
		this.setDays();
	}
});

Ext.reg('calendar', COMP.Controls.Calendar);

/*!
 * Ext JS Library 3.1.0
 * Copyright(c) 2006-2009 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */

/**
 * @class Ext.ux.form.FileUploadField
 * @extends Ext.form.TextField
 * Creates a file upload field.
 * @xtype fileuploadfield
 */
COMP.Controls.FileUploadField = Ext.extend(Ext.form.TextField, {
	constructor:function(config){
		this.config = config;
		COMP.Controls.FileUploadField.superclass.constructor.call(this, config);
	}
	/**
	* @cfg {String} buttonText The button text to display on the upload button (defaults to
	* 'Browse...').  Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
	* value will be used instead if available.
	*/
	,buttonText: 'Submit...'
	/**
	* @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
	* text field (defaults to false).  If true, all inherited TextField members will still be available.
	*/
	,buttonOnly: false
	/**
	* @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
	* (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
	*/
	, buttonOffset: 3
	/**
	* @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
	*/
	// private
	,readOnly: true
	/**
	* @hide
	* @method autoSize
	*/
	,autoSize: Ext.emptyFn
	// private
	,initComponent: function(){
		COMP.Controls.FileUploadField.superclass.initComponent.call(this);

		this.addEvents(
			/**
			* @event fileselected
			* Fires when the underlying file input field's value has changed from the user
			* selecting a new file from the system file selection dialog.
			* @param {Ext.ux.form.FileUploadField} this
			* @param {String} value The file value returned by the underlying file input field
			*/
			'fileselected'
		);
		Ext.applyIf(this, this.config);
	}
	// private
	,onRender : function(ct, position){
		COMP.Controls.FileUploadField.superclass.onRender.call(this, ct, position);

		this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
		this.el.addClass('x-form-file-text');
		this.el.dom.removeAttribute('name');
		this.createFileInput();
		this.bindListeners();
	}
	,bindListeners: function(){
		this.fileInput.on({
			scope: this,
			change: function(){
				var v = this.fileInput.dom.value;
				this.setValue(v);
				this.fireEvent('fileselected', this, v);    
			}
		}); 
	}
	,createFileInput : function() {
		this.fileInput = this.wrap.createChild({
			id: this.getFileInputId(),
			name: this.name||this.getId(),
			cls: 'x-form-file',
			tag: 'input',
			type: 'file',
			size: 1
		});
	}
	,reset : function(){
		this.fileInput.remove();
		this.createFileInput();
		this.bindListeners();
		COMP.Controls.FileUploadField.superclass.reset.call(this);
	}
	// private
	,getFileInputId: function(){
		return this.id + '-file';
	}
	// private
	,onResize : function(w, h){
		COMP.Controls.FileUploadField.superclass.onResize.call(this, w, h);

		this.wrap.setWidth(w);
	}
	// private
	,onDestroy: function(){
		COMP.Controls.FileUploadField.superclass.onDestroy.call(this);
		Ext.destroy(this.fileInput, this.wrap);
	}
	,onDisable: function(){
		COMP.Controls.FileUploadField.superclass.onDisable.call(this);
		this.doDisable(true);
	}
	,onEnable: function(){
		COMP.Controls.FileUploadField.superclass.onEnable.call(this);
		this.doDisable(false);
	}
	// private
	,doDisable: function(disabled){
		this.fileInput.dom.disabled = disabled;
	}
	// private
	,preFocus : Ext.emptyFn
	// private
	,alignErrorIcon : function(){
		this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
	}
});

Ext.reg('FileUploadField', COMP.Controls.FileUploadField);

COMP.Controls.FileUploadCntl = Ext.extend(Ext.FormPanel, {
	constructor:function(config){
		Ext.apply(config, {fileUpload:true});
		this.config = config;
		COMP.Controls.FileUploadCntl.superclass.constructor.call(this, config);
	}
	,initComponent:function(){
		Ext.applyIf(this, {
				title:''
			});
		Ext.apply(this, {
			//For now it needs a fixed width of 212 until further customization
			width:212
			,items:
			[
				{
					xtype:'FileUploadField'
					,hideLabel:true
				}
			]
		});
		Ext.applyIf(this.items[0], this.config);
		COMP.Controls.FileUploadCntl.superclass.initComponent.call(this);
	}
	,setValue:function(v)
	{
		this.items.items[0].setValue(v);
	}
	,getValue:function()
	{
		if (this.items && this.items.items && this.items.items[0])
			return this.items.items[0].getValue();
		return '';
	}
});

Ext.reg('FileUploadCntl', COMP.Controls.FileUploadCntl);

var eNoRecord = -9999;
var eDayClosed=1;
var ePeriod_Due = 2;
var eReserved = 3;
var eBuffered = 4;
var eInUse = 5;
var eOutOfRange = 6;
var ePostProcessing = 7;

COMP.Controls.ResCal = Ext.extend(COMP.Controls.Calendar, {
	id:'ResCal'
	,constructor:function(config){
		this.config = config;
		this.config.myType = 'rescal';
		this.cc = config.cc || '';
		this.config.topItems = [{
			layout:'hbox'
			,height:100
			,layoutConfig:{align:'stretch'}
			,defaults:{flex:1,labelAlign:'right', labelWidth:150}
			,items:[{
				layout:'form'
				,defaultType:'displayfield'
				,valueField:'value'
				,displayField:'display'
				,items:[{
					xtype:'COMPpopupMenu'
					,id:'resCopiesCombo'
//					,fieldLabel:L(13034)	//Copy Barcode/Library
					,fieldLabel:L(5017) // ls_Copy_Barcode
					,width:150
					,defaultID:0
					,forceSelection:true
					,listeners: {
						select:function(combo, record, index) {
							var cal = combo.ownerCt.ownerCt.ownerCt;
							if (cal)
							{
								cal.updateCopyInformation();
								cal.requestDayData();
							}
						}
						,click:function(m, i, e){
							var cal = this.findParentByType('rescal');
							if (cal)
							{
								if (cal.bcList)
								{
									for (var i = 0; i < cal.bcList.length; ++i)
									{
										if (cal.bcList[i].allow)
											m.menu.items.items[i].enable();
										else
											m.menu.items.items[i].disable();
									}
								}
							}
						}
					}
				}
				,{
					id:'calCallNum'
					,fieldLabel:L(4081)	//Call Number
					,value:''
				}
				,{
					id:'calVolume'
					,fieldLabel:L(4082)	//Volume
					,value:''
				}
				]}
				,{
					layout:'form'
					,defaultType:'displayfield'
					,items:[{
						id:'calLoc1'	
						,fieldLabel:L(25934)//Institution term
						,value:''
						}
						,{
							id:'calLoc2'	
							,fieldLabel:L(4758)//Copy Location pref term
							,value:''
						}
						,{
							id:'calLoc3'
							,fieldLabel:L(11113)//Shelving term
							,value:''
					}]
				}]
		}];
       COMP.Controls.ResCal.superclass.constructor.call(this, this.config);
    }
	,initComponent:function(){
		COMP.Controls.ResCal.superclass.initComponent.apply(this, arguments);
		var exp = this.cc? this.cc.Export() : '';
		var useCC = this.cc ? true : false;
		COMP.SendAjaxCommand('all_request_res_barcode_list',{rsn:this.config.rsn,admin:this.config.admin,patBC:this.config.patBC,useCC:useCC,json:exp},this.receivedBarcodeList,this);
	}
	,dayClick:function(date)
	{
		COMP.SendAjaxCommand('all_res_day_selected', {rsn:this.config.rsn, date:date,cpyBC:this.getCurrentBarcode()}, this.requestDayData, this);
	}
	,daysDragged:function(firstDay, lastDay)
	{
		COMP.SendAjaxCommand('all_res_day_selected', {rsn:this.config.rsn, date:firstDay.toDateString(), d2:lastDay.toDateString(), cpyBC:this.getCurrentBarcode()}, this.requestDayData, this);
	}
	,afterRender : function() {            
		COMP.Controls.ResCal.superclass.afterRender.call(this);
	}
	,receivedBarcodeList:function(o)
	{
		this.bcList = '';
		if (o.failed)
		{
			alert(o.failed);
			this.ownerCt.close();
			return;
		}
		
		var c = this.findById('resCopiesCombo')
		if (c)
		{
			c.replaceMenu(o.records);
			c.setValue(0);
			this.bcList = o.records;
			this.updateCopyInformation();
		}
	}
	,updateCopyInformation:function()
	{
		COMP.SendAjaxCommand('all_request_res_copy_info', {cpyBC:this.getCurrentBarcode(),rsn:this.rsn}, function(o){
			if (o.failed)
				return;
					
			this.findById('calCallNum').setValue(o.cnum);
			this.findById('calVolume').setValue(o.cvol);
			this.findById('calLoc1').setValue(o.cloc1);
			this.findById('calLoc2').setValue(o.cloc2);
			this.findById('calLoc3').setValue(o.cloc3);

			 this.requestDayData();

			}, this);
	}
	,requestDayData:function(o){
		if (o && o.ignore)
			return;
		
		if (o && o.failed)
		{
			alert(o.failed);
			return;
		}
		
		var firstDay = this.preCalDate().AddDays(1);
		
		var oo = {
			patBC:this.config.patBC
			,cpyBC:this.getCurrentBarcode()
			,rsn:this.rsn
			,yr:firstDay.getFullYear()
			,mn:firstDay.getMonth()
			,dy:firstDay.getDate()
		}

		COMP.SendAjaxCommand('all_request_res_cal_info', oo, this.handleDayData, this);
	}
	,handleDayData:function(o){
		if(o.failed)
		{
			alert("failed: "+o.failed);
			return;
		}

		this.clearDays();
		this.resInfo = o.resInfo || '';
		this.dayInfo = o.dayInfo || '';
		var bc = this.getCurrentBarcode();
		this.showDayStatus(bc);
	}
	,getCurrentBarcode:function(){
		var bcList = this.findById('resCopiesCombo');
		var bc = 'ANY';
		if (bcList)
		{
			var s = bcList.getValue();
			if (typeof(s) == 'number' && s >= 0)
			{
				bc = bcList.isValidUID(s);
				if (s == 0 && bc == 'Any')
					bc = 'ANY';
			}
		}
		return bc;
	}
	,showDayStatus:function(bc){
		this.clearDays();
		if (this.resInfo)
			for (var i = 0; i < this.resInfo.length; ++i)
				this.markDayStatus(this.resInfo[i]);
		if (this.dayInfo)
			for (var i = 0; i < this.dayInfo.length; ++i)
				this.markDayStatus(this.dayInfo[i]);
	}
	,markDayStatus:function(dayInfo)
	{
		var day = this.findNthDay(dayInfo.day);
		if (day)
		{
			day.useType = dayInfo.stat;
			var cls = '';
			switch (day.useType)
			{
				case eReserved:
					cls = 'calDay-reserved';
				break;

				case eBuffered:
				case ePostProcessing:
					cls = 'calDay-processing';
				break;
				
				case eDayClosed:
				case eInUse:
					cls = 'calDay-unavailable';
				break;
			}
			if (cls)
			{			
				day.addClass(cls);
				day.inUse++;
				day.updateMiddleText(dayInfo.mtxt);
				day.updateBottomText(dayInfo.btxt);
				day.updateTextColor(dayInfo.color);
			}
		}
	}
	,clearDays:function(){
		var row;
		var day;
		for(var r=1; r<=6; r++)
		{
			row = this.findById('row'+r);
			if (!row)
				continue;
			for(var d=0; d <= 6; d++)
			{
				day = row.getDay(d);
				if (day)
				{
					day.inUse = 0;
					var cls = '';
					day.useType = '';
					day.removeClass(['calDay-unavailable', 'calDay-processing', 'calDay-reserved']);
					day.updateMiddleText('');
					day.updateBottomText('');
				}
			}
		}
        COMP.Controls.ResCal.superclass.clearDays.call(this);
	}
	,changeListener:function()
	{
		this.requestDayData();
	}
});

Ext.reg('rescal', COMP.Controls.ResCal);

COMP.ResWindow = Ext.extend(Ext.Window, {
	constructor:function(config)
	{
		this.items = {
			xtype:'rescal'
			,rsn:config.rsn
			,admin:config.admin
			,patBC:config.patBC
			,flex:1
			,cc:config.cc
		};
		Ext.apply(this,{
			title: L(5891) //'Place Reservation' 
			,closeAction: 'close'
			,listeners:{'close':{fn:function() {if (window.RWS && RWS.Circ) {RWS.Circ.clearRSN();}}}}
			,layout:'vbox'
			,layoutConfig:{align:'stretch'}
			,width:700
			,height:500
			//,cls:'dialog'
			,border:false
			,modal:true
			,resizable:false
			,bbar:['->'
			,{
				xtype:'button'
				,text:L(17140) //'Cancel'
				,handler:this.close
				,scope:this
			},'-'
			,{
				xtype:'button'
				,text:L(17141) //'OK' 
				,handler:this.SendRequest
				,scope:this
			}
			]
		});
        COMP.ResWindow.superclass.constructor.call(this, config);
	}
	,SendRequest : function()
	{
		var exp = this.initialConfig.cc? this.initialConfig.cc.Export() : '';

		COMP.SendAjaxCommand('all_place_reservation',{patBC:this.initialConfig.patBC,rsn:this.initialConfig.rsn, cc:exp,x:COMP.GetCurrentTicks()}, this.HandleResult, this);
	}
	,HandleResult : function(o)
	{
		this.close();
		if (this.admin)
		{
			var module = LWS.Desktop.getModuleByWinType('circ');
			if (module && module.win)
				module.win.HandleCircReply(o);
		}
		else
		{
			if (o.error)
				{
					var dialog = new RWS.Dialog({title: 'Error', message:o.error});
					dialog.show();
					return;
				}

			if (o.success){
			    if(COMP.Config.GetDefault('enableSounds')){
					var soundName = COMP.Config.GetDefault('reservationPlacedByPatronSound');
					COMP.PlaySound(soundName);
				}
			}
			alert(o.message)
		}
	}
});
if (window.COMP) COMP.Broadcast('scriptLoaded_controls');