Ext.namespace('EquipmentRental.Customers');
    	
    	/* `id` int(10) unsigned NOT NULL auto_increment,
  `first_name` varchar(255) default NULL,
  `last_name` varchar(255) default NULL,
  `address_1` varchar(255) default NULL,
  `address_2` varchar(255) default NULL,
  `city` varchar(255) default NULL,
  `state` varchar(255) default NULL,
  `zip` varchar(255) default NULL,
  `email_address` varchar(255) default NULL,
  `phone_1` varchar(255) default NULL,
  `phone_2` varchar(255) default NULL,
  `comment` text,
  `created` datetime default NULL,
  `modified` datetime default NULL,
  */
  
    	// --------------------------------------------------------
   	//		CUSTOMERS LISTENERS	
   	//---------------------------------------------------------
    	var Customers = function() {
			return {
				selectDataStore:new Ext.data.Store({
						    reader: new Ext.data.JsonReader({
							fields: [
								{name:'id'}
								,{name:'name'}		
								,{name:'first_name'}
								,{name:'last_name'}
								,{name:'address_1'}
								,{name:'address_2'}
								,{name:'city'}
								,{name:'state'}
								,{name:'zip'}
								,{name:'email_address'}
								,{name:'phone_1'}
								,{name:'phone_2'}
								,{name:'comment'}
								,{name:'created', type:'date', dateFormat:'n/j h:ia'}
								,{name:'modified', type:'date', dateFormat:'n/j h:ia'}
							],
							root: 'rows'
						    }),
						    proxy: new Ext.data.HttpProxy({
							url: 'http://'+host+'/customers/listAll'
						    }),
						    autoLoad: true
						})				
			};
		}();

    	
    	// --------------------------------------------------------
   	//		CUSTOMERS FORM 	
   	//---------------------------------------------------------
   	EquipmentRental.Customers.Form = Ext.extend(Ext.form.FormPanel, {	    	
	     	border:false
		,frame:true
		,labelWidth:80
		,url:'http://'+host+'/customers/add'
	 
		,constructor:function(config) {
			config = config || {};
			config.listeners = config.listeners || {};
			Ext.applyIf(config.listeners, {
				actioncomplete:function() {
					if(typeof console!='undefined') {
						console.log('actioncomplete:', arguments);
					}
				}
				,actionfailed:function() {
					if(typeof console!='undefined') {
						console.log('actionfailed:', arguments);
					}
				}
			});
			EquipmentRental.Customers.Form.superclass.constructor.call(this, config);
		}

	    ,initComponent:function() {		
			
			var config = {
				 defaultType:'textfield'
				,defaults:{anchor:'-24'}
				,monitorValid:true
				,autoScroll:true		
				,items:[{
					 name:'first_name'
					,fieldLabel:'First Name'
					,allowBlank:false
				},{
					 name:'last_name'
					,fieldLabel:'Last Name'
					,allowBlank:false
				},{
					 name:'address_1'
					,fieldLabel:'Address 1'
				},{
					 name:'address_2'
					,fieldLabel:'Address 2'
				},{
					 name:'city'
					,fieldLabel:'City'
				},{
					 name:'state'
					,fieldLabel:'State'
				},{
					 name:'zip'
					,fieldLabel:'Zip'
				},{
					 name:'country'
					,fieldLabel:'Country'
				},{
					 name:'email_address'
					,fieldLabel:'E-mail'
					,vtype:'email'					
					,allowBlank:false
				},{
					 name:'phone_1'
					,fieldLabel:'Phone1'
				},{
					 name:'phone_2'
					,fieldLabel:'Phone2'
				},{
					 name:'comment'
					,fieldLabel:'Comment'
					,xtype:'textarea'
				},{
					 name:'id'
					,fieldLabel:''
					,xtype:'hidden'
				}]
				,buttons:[{
					 text:'Submit'
					,formBind:true
					,scope:this
					,handler:this.submit
				}]
			}; 

			
		Ext.apply(this, Ext.apply(this.initialConfig, config));

		// call parent
		EquipmentRental.Customers.Form.superclass.initComponent.apply(this, arguments);
		
		// add custom events
        	this.addEvents('saved');

	 
	    }
	    
	    ,onRender:function() {
	 
		// call parent
		EquipmentRental.Customers.Form.superclass.onRender.apply(this, arguments);

		
		this.getForm().waitMsgTarget = this.getEl();
	 
	    } 

		
		,onLoadClick:function() {
			this.load({
				 url:this.url
				,waitMsg:'Loading...'
				,params:{cmd:'load'}
			});
			
		}	    
		
		,submit:function() {
			this.getForm().submit({
				 url:this.url
				,scope:this
				,success:this.onSuccess
				,failure:this.onFailure
				,params:{cmd:'save'}
				,waitMsg:'Saving...'
			});
		}
		
		,onSuccess:function(form, action) {
			/*Ext.Msg.show({				
				 title:'Success'
				,scope:this 
				,msg:'Form submitted successfully'
				,modal:true
				,fn: this.onSuccessProcessResult
				,icon:Ext.Msg.INFO
				,buttons:Ext.Msg.OK
			});	*/
			var responseObj=Ext.decode(action.response.responseText);
			
			//send the new record id
			this.fireEvent('saved',responseObj.rowId);					
		} 
		
		, onSuccessProcessResult: function(buttonId, text){
			if(buttonId=='ok'){
				this.fireEvent('saved');	
			}
			
		}
		
		,onFailure:function(form, action) {
			var responseObj=Ext.decode(action.response.responseText);
			
			this.showError(action.result.error || responseObj.errormsg);
			
		} 
	
		
		,showError:function(msg, title) {
			title = title || 'Error';
			Ext.Msg.show({
				 title:title
				,msg:msg
				,modal:true
				,icon:Ext.Msg.ERROR
				,buttons:Ext.Msg.OK
			});
		} 
	 
	}); // eo extend
 
	
   
   	// --------------------------------------------------------
   	//		CUSTOMERS GRID PANEL	
   	//---------------------------------------------------------
   	
   	
	EquipmentRental.Customers.Grid = Ext.extend(Ext.grid.GridPanel, {
	initComponent:function() {
		var config = {
			 store:new Ext.data.JsonStore({
				 id:'customers'
				,totalProperty:'totalCount'
				,root:'rows'
				,url:'http://'+host+'/customers/index'
				,fields:[
				    {name:'id'}	
				   ,{name:'first_name'}
				   ,{name:'last_name'}
				   ,{name:'address_1'}
				   ,{name:'address_2'}
				   ,{name:'city'}
				   ,{name:'state'}
				   ,{name:'zip'}
				   ,{name:'email_address'}
				   ,{name:'phone_1'}
				   ,{name:'phone_2'}
				   ,{name:'comment'}
				   ,{name:'created', type:'date', dateFormat:'n/j h:ia'}
				   ,{name:'modified', type:'date', dateFormat:'n/j h:ia'}				  
				]
			})
			,stripeRows:true
			,sm:new Ext.grid.CheckboxSelectionModel()
			,columns:[		
			new Ext.grid.CheckboxSelectionModel()	
			,{
				 id:'customers'
				,header:"First Name"
				,width:40, sortable:true
				,dataIndex:'first_name'
			},{
				 header:"Last Name"
				,width:20
				,sortable:true				
				,dataIndex:'last_name'
			},{
				 header:"City"
				,width:20
				,sortable:true
				,dataIndex:'city'
			},{
				 header:"Email"
				,width:20
				,sortable:true
				,dataIndex:'email_address'
			},{
				 header:"Phone 1"
				,width:20
				,sortable:true
				,dataIndex:'phone_1'
			},{
				header:"Last Updated"
			   	,width:20, sortable:true
			   	,renderer:Ext.util.Format.dateRenderer('m/d/Y')
			   	,dataIndex:'modified'
			}]			
			,tbar:[{
				 text:'Add Record'
				 ,iconCls:'icon-plus'
				 ,scope:this
				 ,handler:function() {										 
					 var win = new Ext.Window({
						 id:'formloadsubmit-win'
						,title:'Customers'
						,layout:'fit'
						,width:350
						,height:450
						,closable:true
						,border:false
						,items:{id:'formloadsubmit-form', xtype:'customersForm'}
					});

					 win.show();
					 
					 //add listener to update grid
					 var formRef = Ext.getCmp('formloadsubmit-form');					 
					 var gridRef=this;
					 
					 formRef.on('saved', function(rowId) {					    
					    	win.close();
					    	
					    	//refresh data				    
						gridRef.getStore().reload({
							params:{start:0, limit:10}
							,callback:function(){
								//hightlight the new row
								var store = gridRef.getStore();
								var dex = store.find('id',rowId);
								var row = gridRef.getView().getRow(dex);
								Ext.fly(row).highlight("AFEF95", {
								    attr: "background-color",
								    easing: 'easeOut',
								    duration: 5
								});
	
							}
						});	
					    				    
					 });	
					 
					 }
				 },'-',{
				 text:'Edit Record'
				 ,scope:this
				 ,iconCls:'icon-edit'
				 ,id: 'edit-record'
				 ,disabled: true
				 ,handler:function() {
					 var record=this.getSelectionModel().getSelected().data;				 
					 
					
					 var win = new Ext.Window({
						 id:'formloadsubmit-win'
						,title:'Customers'
						,layout:'fit'
						,width:350
						,height:450
						,closable:true
						,border:false
						,items:{id:'formloadsubmit-form', xtype:'customersForm'}
					 });

					 win.show();
					 
					 //set form values
					 var formRef = Ext.getCmp('formloadsubmit-form');
					 formRef.url='http://'+host+'/customers/edit/'+record.id;	
					 formRef.getForm().setValues(record);	
										 
					 //add listener to update grid				 
					 var gridRef=this;
					 formRef.on('saved', function() {					   
						win.close();
						
						gridRef.getStore().reload({
							params:{start:0, limit:10}
							,callback:function(){	
								//hightlight the edited row							
								var store = gridRef.getStore();
								var dex = store.find('id',record.id);
								var row = gridRef.getView().getRow(dex);
								Ext.fly(row).highlight("8ECF74", {
								    attr: "background-color",
								    easing: 'easeOut',
								    duration: 5
								});
								
								gridRef.disableBtn(gridRef);
								
							}
						});					    	
						
					 });				 
					 
				 	
					 }
				},'-',{
				 text:'Delete Records'
				 ,scope:this
				 ,id: 'delete-records'
				 ,iconCls:'icon-delete'
				 ,disabled: true
				 ,handler:function() {
						var records=this.getSelectionModel().getSelections();
						
						 
					 	var data = [];
						Ext.each(records, function(r) {
						  data.push(r.get('id'));
						});
						
						Ext.Msg.show({
							scope:this
							,title: 'Remove Records' 
							,buttons: Ext.MessageBox.YESNOCANCEL
							,msg: 'Remove '+data.length+' records? Data cannot be restored.'
							,fn: function(btnMsg){
								if (btnMsg == 'yes'){
									Ext.Ajax.request({
										scope:this
										,url:'http://'+host+'/customers/delete'
										,params: {records: data.join(',')}
										,success: function(response) { 
											//parse json response
											var responseObj=Ext.decode(response.responseText);
											
											if(responseObj.success==true){
												this.getStore().reload({params:{start:0, limit:10}});	
												this.disableBtn(this);
											}else{
												this.onFailure(responseObj.errormsg);
											}
										}
										,failure: function(response) { 
											//parse json response
											var responseObj=Ext.decode(response.responseText);
											
											this.onFailure('Server error');
										}									 
									});
								}										
							}
						});
						
					}
				},' '				 
			
			]
			,loadMask:true
			,viewConfig:{forceFit:true}
		}; // eo config object

		// apply config
        	Ext.apply(this, Ext.apply(this.initialConfig, config));

		this.bbar = new Ext.PagingToolbar({
			 store:this.store
			,displayInfo:true
			,pageSize:10
		});
		
		this.on('rowclick',function(grid, rowIndex, e){
			//enable edit and delete buttons
			if(grid.getSelectionModel().getSelections().length==1){
				grid.getTopToolbar().items.item('delete-records').enable();				
				grid.getTopToolbar().items.item('edit-record').enable();
			}
			else if(grid.getSelectionModel().getSelections().length>1){
				grid.getTopToolbar().items.item('delete-records').enable();	
				grid.getTopToolbar().items.item('edit-record').disable();
			}
			else{
				grid.getTopToolbar().items.item('delete-records').disable();
				grid.getTopToolbar().items.item('edit-record').disable();
			}
		});
		
		this.disableBtn=function(grid){
			grid.getTopToolbar().items.item('delete-records').disable();
			grid.getTopToolbar().items.item('edit-record').disable();
		}
		
		
		this.onSuccess=function(msg, title) {
			Ext.Msg.show({
				 title:'Success'
				,msg:msg
				,modal:true
				,icon:Ext.Msg.INFO
				,buttons:Ext.Msg.OK
			});
		} 

		
		this.onFailure=function(msg, title) {
			Ext.Msg.show({
				 title:'Error'
				,msg:msg
				,modal:true
				,icon:Ext.Msg.ERROR
				,buttons:Ext.Msg.OK
			});
		} 
		 

		// call parent
		EquipmentRental.Customers.Grid.superclass.initComponent.apply(this, arguments);
	} // eo function initComponent

	,onRender:function() {

		// call parent
		EquipmentRental.Customers.Grid.superclass.onRender.apply(this, arguments);

		// load the store
		this.store.load({params:{start:0, limit:10}});

	} // eo function onRender

});

	// --------------------------------------------------------
   	//		CUSTOMERS PANEL 	
   	//---------------------------------------------------------
	 EquipmentRental.Customers.Panel = Ext.extend(Ext.Panel, {		
		layout:'border'		 
		
		,initComponent:function() {			
			var config = {
			items:[{
				 region:'north'
				,xtype:'customersGrid'
				,title:'Customers'
				,border:true
				,height:450
				,split: true
			},{			
				region:'center'
				,border:true			
				,height:150
				,title:'Customer Details'
				,html:'Please select a record to see additional details'
				,bodyStyle:'padding:5px;'
			
			}]
			};
			 
			// apply config
			Ext.apply(this, Ext.apply(this.initialConfig, config));
			 
			// call parent
			EquipmentRental.Customers.Panel.superclass.initComponent.apply(this, arguments);
		
			//add details on record select
			var bookTplMarkup = [
			'<strong>Name:</strong> {first_name} {last_name}<br/>',
			'<strong>Address:</strong> <br/>',
			'{address_1}<br />',
			'{address_2}<br />',
			'{zip} {city}, {state}, {country}<br />',
			'<strong>Email:</strong> {email_address}<br/>',
			'<strong>Phone:</strong> {phone_1},{phone_2}<br/>',
			'<strong>Comment:</strong> {comment}<br/>',
			'<strong>Created:</strong>{created}'
			];
			var bookTpl = new Ext.Template(bookTplMarkup);
			 
			this.gridContent = this.items.itemAt(0);
			this.detailsContent = this.items.itemAt(1);
		
			
			var detailsContentRef=this.detailsContent
			this.gridContent.getSelectionModel().on('rowselect', function(sm, rowIdx, r) {
				bookTpl.overwrite(detailsContentRef.body, r.data);
			});
		} 
		
		 
	}); 
    
    	

// --------------------------------------------------------
//		THE MAIN VIEW	
//---------------------------------------------------------

 
// register xtype
Ext.reg('customersForm', EquipmentRental.Customers.Form); 
Ext.reg('customersGrid', EquipmentRental.Customers.Grid);
Ext.reg('customersPanel', EquipmentRental.Customers.Panel);

    
    
    
/*
panel.el.on('click', function(e, t) {
  	e.stopEvent();
	var target = e.getTarget('a.examplelink');
	if(target) {
	    alert(target.href);
	}
	return false;
}); */



