if (!Ext.ModelManager.isRegistered('EditRestaurant')){
Ext.define('EditRestaurant', {
	extend : 'Ext.tab.Panel',
	alias  : 'widget.EditRestaurant',
	dish_id : null,// 餐品的ID
	dishImgPath : null, // 向后台提交餐品的图片地址
	imgWindow : null,
	restaurant : null,
	
	initComponent : function() {
		Ext.apply(this, {
			id : 'widget.EditRestaurant_' + this.restaurant.id,
			title : '　'+this.restaurant.name+'　',
			closable : true,
			layout: 'fit',
			items: [
				this.creasteBasePanel(),
				this.createSectionGrid(),
				this.createDishGrid()
			]
		});
		this.callParent(arguments);
		// 把dishStore复制给全局变量
		dish_store = this.dishStore;
		this.imgWindow = this.createWin();
		restId = this.restaurant.id;// 餐馆Id
	},
	
	creasteBasePanel : function () {
		return {
			title: '基本信息及位置',
			id : 'edit_restaurant_form_' + this.restaurant.id,
			xtype: 'form',
			baseParams : {id: this.restaurant.id},
			layout: {
				type: 'hbox',
				align: 'stretch'
			},
			dockedItems: [{
				xtype: 'toolbar',
				dock: 'bottom',
			    items: [{ 
			        xtype: 'button',
					text: '保存基本信息',
					iconCls: 'database_go',
					handler: this.submitForm,
					scope: this
				}]
			}],
            items:[this.createBaseInfoPanel(),{xtype: 'panel', width: 1}, this.createMapFormPanel()]
			
		};
	},
	createWin : function() {// 创建一个窗体
		this.imgWindow = Ext.create('Ext.window.Window', {
					title : '上传图片',
					height : 200,
					width : 400,
					closeAction : 'hide',
					layout : 'fit',
					items : this.createFormPanel(),
					listeners : {
						beforeclose : function(obj, e) {
							obj.hide();
							return false;
						}
					}
				});
		return this.imgWindow;
	},
	createFormPanel : function() {// 创建一个表单
		this.imgUploadPanel = Ext.create('Ext.form.Panel', {
			title : '请上传该餐品的图片',
			bodyPadding : 5,
			fileUpload : true,
			width : 350,
			layout : 'anchor',
			defaults : {
				anchor : '100%'
			},

			// The fields

			items : [{
						scope : this,
						xtype : 'textfield',
						name : 'my_dish_img',
						fieldLabel : '餐品图片文件',
						inputType : 'file',
						buttonText : '浏览',
						width : 258,
						// 错误提示文本
						blankText : '请输入登录名称!'
					}],

			// Reset and Submit buttons
			buttons : [{
						scope : this,
						text : '重置',
						handler : function(btn) {
							this.imgUploadPanel.getForm().reset();
						}
					}, {
						scope : this,
						text : '提交',
						formBind : true, // only
						// enabled
						// once
						// the
						id : 'btn_btn', // form
						// is
						// valid
						disabled : true,
						handler : function(btn, e, parent) {
							var form = this.imgUploadPanel.getForm();
							if (form.isValid()) {
								form.submit({
											clientValidation : true,
											url : 'upload_img.php',
											params : {
												dishId : this.dish_id,
												dishImgPath : this.dishImgPath
											},

											success : function(vform,
													action) {
												var path = action.result.path;// 图片的解读路径
												dish_store.load();
												Ext.Msg.alert('上传成功',
														'图片已经上传成功！');
												vform.reset();
												vform.owner.ownerCt.hide();
											},
											failure : function(vform,
													action) {
												Ext.Msg
														.alert(
																'上传失败',
																action.result.errors);
												vform.reset();
											}
										});
							}
						}
					}]

		});
		return this.imgUploadPanel;
	},
	createBaseInfoPanel : function() {
		var ratings = Ext.create('Ext.data.Store', {
			fields :["value",  "text"],
			data : [
				{"value": 1, "text": "一星"},
				{"value": 2, "text": "二星"},
				{"value": 3, "text": "三星"}
			]
		});
		
		var cities = Ext.create('Ext.data.Store',{
			storeId: 'editRestaurantCitiesStore',
			autoDestroy: true,
			model: 'City',
			pageSize: 10,
			proxy: {
				type: 'ajax',
				url: 'cities.php',
				reader: {
					type: 'json',
					root: 'cities',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true
		});
		
		var regions = Ext.create('Ext.data.Store',{
			storeId: 'editRestaurantRegionsStore',
			autoDestroy: true,
			model: 'Region',
			pageSize: 30,
			clearOnPageLoad : true,
			proxy: {
				type: 'ajax',
				url: 'regions.php',
				reader: {
					type: 'json',
					root: 'regions',
					totalProperty: 'total',
					id: 'id'
				}
			}
		});

		var agents = Ext.create('Ext.data.Store',{
			storeId: 'editRestaurantAgentsStore',
			autoDestroy: true,
			model: 'Agent',
			pageSize: 10,
			proxy: {
				type: 'ajax',
				url: 'agents.php',
				reader: {
					type: 'json',
					root: 'agents',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true
		});
		
		this.baseInfoPanel = Ext.create('Ext.form.Panel', {
			title: '基本信息',
			flex: 1,
    		bodyPadding: 10,
			autoScroll : true,
			border : false,
			frame: false,
	        fieldDefaults : {
	            msgTarget: 'side',
	            labelWidth: 150,
	            labelAlign: 'right'
	        },
    		defaultType: 'textfield',
    		items: [{
            	xtype: 'fieldset',
            	title: '总体信息',
    			defaultType: 'textfield',
    			padding: 10,
            	items: [{
					fieldLabel: '名称',
					width: 350,
					name: 'name',
					value: this.restaurant.name,
					allowBlank: false,
					blankText : '餐馆名称不能为空',
					enforceMaxLength : true,
					maxLength : 80,
					maxLengthText : '餐馆名称不能超过40个汉字（80个字符）'
	    		},{
	    			fieldLabel: '营业时间(XX:XX-YY:YY)',
					name: 'businesshour',
					value: this.restaurant.businesshour,
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 80,
					maxLengthText : '外卖时间不能超过80个字符'
	    		},{
					fieldLabel: '所属代理',
					name: 'agentid',
					value: this.restaurant.agentid,
					xtype: 'combo',
					editable: false,
					pageSize: 10,
	    			width: 430,
					store: agents,
					queryMode: 'local',
					displayField: 'name',
					valueField: 'id',
					listeners: {
						scope: this,
						'select' : function(combobox, value){
							var nameField = Ext.getCmp("edit_restaurant_agent_name_hiddenfield_" + this.restaurant.id);
							nameField.setValue(value[0].data.name);
						}
					}
	    		},{
					id: 'edit_restaurant_agent_name_hiddenfield_' + this.restaurant.id,
					xtype: 'hiddenfield',
					value: this.restaurant.agent,
					name: 'agent'
				},{
					fieldLabel: '所属城市',
					name: 'cityid',
					value: this.restaurant.cityid,
					xtype: 'combo',
					editable: false,
					queryMode: 'local',
					store: cities,
					pageSize: 10,
					width: 430,
					displayField: 'name',
					valueField: 'id',
					listeners: {
						scope: this,
						'select' : function(combobox, value){
							var nameField = Ext.getCmp("edit_restaurant_city_name_hiddenfield_" + this.restaurant.id);
							nameField.setValue(value[0].data.name);
							
							var lat = value[0].data.latitude;
							var lng = value[0].data.longitude;
							var zoom = value[0].data.zoomlevel;
	
							this.mapPanel.map.setCenter( new google.maps.LatLng(lat, lng) );
							this.mapPanel.map.setZoom( zoom );
										
							regions.getProxy().extraParams.cityid = value[0].data.id;
							regions.loadPage(1);
							var regionIdField =  Ext.getCmp("edit_restaurant_regions_id_combo");
							regionIdField.clearValue();
							var regionField =  Ext.getCmp("edit_restaurant_region_name_hiddenfield");
							regionField.setValue('');
						}
					}
	    		},{
	    			id: 'edit_restaurant_city_name_hiddenfield_' + this.restaurant.id,
					xtype: 'hiddenfield',
					value: this.restaurant.city,
					name: 'city'
				},{
					id: 'edit_restaurant_regions_id_combo',
	    			fieldLabel: '所属区域',
					name: 'regionid',
					xtype: 'combo',
					editable: false,
					queryMode: 'local',
					store: regions,
					pageSize: 30,
	    			width: 430,
					displayField: 'name',
					valueField: 'id',
					listeners: {
						scope: this,
						'select' : function(combobox, value){
							var nameField = Ext.getCmp("edit_restaurant_region_name_hiddenfield");
							nameField.setValue(value[0].data.name);
							
							var lat = value[0].data.latitude;
							var lng = value[0].data.longitude;
							var zoom = value[0].data.zoomlevel;
							
							this.mapPanel.map.setCenter( new google.maps.LatLng(lat, lng) );
							this.mapPanel.map.setZoom( zoom );
						}
					}
	    		},{
	    			id: 'edit_restaurant_region_name_hiddenfield',
					xtype: 'hiddenfield',
					name: 'region'
				},{
					fieldLabel: '电话',
					name: 'telephone',
					value: this.restaurant.telephone,
					allowBlank: false,
					blankText : '餐馆电话不能为空',
					enforceMaxLength : true,
					maxLength : 20,
					maxLengthText : '餐馆电话不能超过20个字符'
	    		},{
	    			fieldLabel: '短信手机号码',
					name: 'mobile',
					value: this.restaurant.mobile,
					allowBlank: false,
					blankText : '短信手机号码用于接收短信，不能为空',
					enforceMaxLength : true,
					maxLength : 11,
					maxLengthText : '短信手机号码不能超过11个字符'
	    		},{
	    			xtype: 'fieldcontainer',
	    			fieldLabel: '是否城市默认餐馆',
					defaultType: 'radiofield',
					layout: 'hbox',
					items: [{
						boxLabel  : '是',
						name: 'citydefault',
						inputValue: '1',
						checked: this.restaurant.citydefault
	                }, {
						boxLabel: '否',
						name: 'citydefault',
						inputValue: '0',
						checked: !this.restaurant.citydefault
	                }]
				},{
	    			fieldLabel: '佣金比例（%）',
					name: 'commission',
					value: this.restaurant.commission,
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 100,
					allowDecimals: false
	    		},{
	    			fieldLabel: '评级',
					name: 'rating',
					value: this.restaurant.rating,
					xtype: 'combo',
					editable: false,
					store: ratings,
					queryMode: 'local',
					displayField: 'text',
					valueField: 'value'
	    		}]
    		},{
            	xtype: 'fieldset',
            	title: '外卖相关',
    			defaultType: 'textfield',
    			padding: 10,
            	items: [{
	    			fieldLabel: '外卖说明',
					name: 'businessmemo',
					value: this.restaurant.businessmemo,
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '外卖时间不能超过255个字符'
	    		},{
	    			fieldLabel: '送餐费用（元）',
					name: 'fee',
					value: this.restaurant.fee,
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 999.99,
					maxText: '送餐费用最大为999.99，如需修改此规则，请找开发人员。'
	    		},{
	    			fieldLabel: '起送金额（元）',
					name: 'minmoney',
					value: this.restaurant.minmoney,
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 999.99,
					maxText: '起送金额最大为999.99，如需修改此规则，请找开发人员。'
	    		},{
	    			fieldLabel: '送餐范围（米）',
					name: 'scope',
					value: this.restaurant.scope,
					xtype: 'numberfield',
					minValue: 0,
					allowDecimals: false
	    		},{
	    			fieldLabel: '折扣（X.x）',
					name: 'discount',
					value: this.restaurant.discount,
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 10,
					allowDecimals: true,
					decimalPrecision: 1
	    		},{
	    			fieldLabel: '公告',
					name: 'notice',
					value: this.restaurant.notice,
					xtype: 'textareafield',
	    			width: 430,
	    			height: 50,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '公告不能超过255个字符'
	    		},{
	    			xtype: 'fieldcontainer',
	    			fieldLabel: '是否支持送餐上门',
					defaultType: 'radiofield',
					layout: 'hbox',
					items: [{
						boxLabel  : '是',
						name: 'takeout',
						inputValue: '1',
						checked: this.restaurant.takeout
	                }, {
						boxLabel: '否',
						name: 'takeout',
						inputValue: '0',
						checked: !this.restaurant.takeout
	                }]
				},{
	    			fieldLabel: '到店消费折扣（X.x）',
					name: 'discountin',
					xtype: 'numberfield',
					value: this.restaurant.discountin,
					minValue: 0,
					maxValue: 10,
					allowDecimals: true,
					decimalPrecision: 1
	    		},{
	    			fieldLabel: '优惠信息',
					name: 'salead',
					value: this.restaurant.salead,
					xtype: 'textareafield',
	    			width: 430,
	    			height: 50
	    		},{
	    			fieldLabel: '主食类',
					name: 'staple',
					value: this.restaurant.staple,
					xtype: 'textfield',
					width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '不能超过255个字符'
	    		}]
    		},{
            	xtype: 'fieldset',
            	title: '内部信息',
    			defaultType: 'textfield',
    			padding: 10,
            	items: [{
	    			fieldLabel: '地址',
					name: 'address',
					value: this.restaurant.address,
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '地址不能超过255个字符'
	    		},{
	    			fieldLabel: '联系人',
					name: 'linkman',
					value: this.restaurant.linkman,
					enforceMaxLength : true,
					maxLength : 50,
					maxLengthText : '联系人不能超过50个字符'
	    		},{
	    			fieldLabel: '联系电话',
					name: 'linkphone',
					value: this.restaurant.linkphone,
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '联系电话不能超过255个字符'
	    		},{
	    			fieldLabel: '关键字（SEO）',
					name: 'keyword',
					value: this.restaurant.keyword,
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '关键字不能超过255个字符'
	    		}]
    		},{
				xtype : 'fieldset',
				title : '打印设备管理',
				defaultType : 'textfield',
				padding : 10,
				items : [{
					fieldLabel : '是否使用打印机',
					name : 'isprint',
					xtype : 'checkbox',//jingyifei,
					checked:this.restaurant.isprint,
					width : 430,
					height : 50
				},{
					fieldLabel : 'MEMBER_CODE',
					name : 'membercode',
					value : this.restaurant.membercode,
					allowBlank : true
				} ,{
					fieldLabel : 'FEIYIN_KEY',
					name : 'feyinkey',
					value : this.restaurant.feyinkey,
					allowBlank : true
				} ,{
					fieldLabel : 'DEVICE_NO',
					name : 'deviceno',
					value : this.restaurant.deviceno,
					allowBlank : true
				} ]
			},{
            	xtype: 'fieldset',
            	title: '登录信息',
    			defaultType: 'textfield',
    			padding: 10,
            	items: [{
	    			fieldLabel: '登录用户名',
					name: 'username',
					value: this.restaurant.username,
					allowBlank: false,
					blankText : '登录用户名不能为空',
					enforceMaxLength : true,
					maxLength : 20,
					maxLengthText : '登录用户名不能超过20个字符（10个汉字）'
	    		},{
	    			fieldLabel: '登录密码',
					name: 'password',
					inputType : 'password',
					enforceMaxLength : true,
					maxLength : 32,
					maxLengthText : '登录密码不能超过32个字符'
	    		},{
	    			fieldLabel: '加入日期',
					name: 'addtime',
					value: this.restaurant.addtime,
					readOnly: true
	    		}]
    		}]
		});
		
		return this.baseInfoPanel;
	},
	
	createMapFormPanel : function() {
		this.mapFormPanel = Ext.create('Ext.panel.Panel', {
			title: '位置信息',
    		bodyPadding: 10,
			flex: 1,
			autoScroll : true,
			border: false,
			frame: false,
    		items: [ this.createMapPanel(),
    		{
				layout:'hbox',
				margin: '10px,0,0,0',
				border: false,
    			items: [{
	    			id: 'edit_restaurant_longitude_hiddenfield_' + this.restaurant.id,
	    			fieldLabel: '经度',
	    			labelWidth: 30,
	    			labelAlign: 'right',
	    			width: 150,
	    			readOnly: true,
					allowBlank: false,
					blankText : '坐标经度不能为空，请移动地图提取经度数据。',
					xtype: 'textfield',
					name: 'longitude'
				},{
	    			id: 'edit_restaurant_latitude_hiddenfield_' + this.restaurant.id,
	    			fieldLabel: '纬度',
	    			labelWidth: 40,
	    			labelAlign: 'right',
	    			width: 150,
	    			readOnly: true,
					allowBlank: false,
					blankText : '坐标纬度不能为空，请移动地图提取纬度数据。',
					xtype: 'textfield',
					name: 'latitude'
				},{
	    			id: 'edit_restaurant_zoomlevel_hiddenfield_' + this.restaurant.id,
	    			fieldLabel: '缩放',
	    			labelWidth: 40,
	    			labelAlign: 'right',
	    			width: 80,
	    			readOnly: true,
					allowBlank: false,
					blankText : '城市缩放倍数不能为空，请缩放地图获取缩放倍数',
					xtype: 'textfield',
					name: 'zoomlevel'
				}]
    		}]
		});
		return this.mapFormPanel;
	},
	
	createMapPanel : function() {
		this.mapId = 'edit_restaurant_map_canvas_'+this.restaurant.id;
		var map_id = this.mapId;
		var mapCanvasHtml = '<div id="'+this.mapId+'" style="height:100%; width: 100%;">' +
				'</div><img src="images/center.png" style="left: 183px; top: 171px; position: absolute;">';
		
		var lat = this.restaurant.latitude;
		var lng = this.restaurant.longitude;
		var zoom = 16;
		var restaurantId = this.restaurant.id;
		
		EditRestaurantMap = Ext.extend(Ext.panel.Panel,{
			title: '通过缩放和移动地图，使餐馆位于地图中心（建议缩放大于16）。',
			layout: 'auto',
			height: 400,
			width: 400,
			html: mapCanvasHtml,
			afterRender : function (){
				EditRestaurantMap.superclass.afterRender.apply(this, arguments);
				
				this.map = makeMapInDiv(map_id, lat, lng, zoom);
				
				var latF = Ext.getCmp("edit_restaurant_latitude_hiddenfield_"+restaurantId);
				var lngF = Ext.getCmp("edit_restaurant_longitude_hiddenfield_"+restaurantId);
				var zoomF = Ext.getCmp("edit_restaurant_zoomlevel_hiddenfield_"+restaurantId);
				latF.setValue(toPrecision(lat,9));
				lngF.setValue(toPrecision(lng,9));
				zoomF.setValue(zoom);
				
				var theMap = this.map;
				google.maps.event.addListener(theMap, 'dragend', function() {
					var center = theMap.getCenter();
					latF.setValue(toPrecision(center.lat(),9));
					lngF.setValue(toPrecision(center.lng(),9));
					zoomF.setValue(theMap.getZoom());
			    });
				google.maps.event.addListener(theMap, 'zoom_changed', function() {
					var center = theMap.getCenter();
					latF.setValue(toPrecision(center.lat(),9));
					lngF.setValue(toPrecision(center.lng(),9));
					zoomF.setValue(theMap.getZoom());
			    });
			}
		});
		
		this.mapPanel = new EditRestaurantMap();
		this.map = this.mapPanel.map;
		return this.mapPanel;
	},
	
	submitForm : function () {
		var form = Ext.getCmp('edit_restaurant_form_' + this.restaurant.id).getForm();
		if (form.isValid()) {
			var pswField = form.findField('password');
			this.lastPassword = pswField.getValue();
			if(this.lastPassword.length!=0) {
				var password = md5(this.lastPassword);
				pswField.setValue(password);
			}
			form.submit({
				url:'update_restaurant.php',
				waitTitle : '请稍候',
				waitMsg : '正在保存餐馆数据...',
				method : 'POST',
		        success: this.editRestaurantSuccess,
		        failure: this.editRestaurantFailure,
		        scope: this
		    });
		}
		else {
			showErrorMsg( '某些输入项不符合规定，请检查各字段的输入。', '输入有误。' );
		}
	},
	
	editRestaurantSuccess : function (form, action) {
		this.resetPassword( form );
		showSuccessMsg( '保存餐馆信息到数据成功。' );
	},
	
	editRestaurantFailure : function (form, action) {
		this.resetPassword( form );
		showFormFailureMsg( action, '保存餐馆信息到数据失败');
	},
	
	resetPassword : function( form ){
		var pswField = form.findField('password');
		pswField.setValue(this.lastPassword);
	},
	
	createSectionGrid : function() {
		this.sectionStore = Ext.create('Ext.data.Store', {
			storeId: 'editRestaurantSectionStore_' + this.restaurant.id,
			autoDestroy: true,
			model: 'Section',
			pageSize: 50,
			proxy: {
				type: 'ajax',
				url: 'sections.php',
				extraParams: {restaurantid : this.restaurant.id},
				reader: {
					type: 'json',
					root: 'sections',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true
		});
		
		this.sectionRowEditing = Ext.create('Ext.ux.grid.plugin.RowEditing', {
			clicksToEdit : 2,		//双击进入编辑
			clicksToMoveEditor: 1,	//编辑过程中单击其他行开始编辑其他行
			autoCancel: true,		//编辑过程中单击其他行是否自动取消本行的数据保存，否
			errorSummary : false
		});

		this.sectionGrid = Ext.create("Ext.grid.Panel", {
			title : '餐品分类列表',
			autoScroll : true,
	        viewConfig: {
	            stripeRows: true,
	            plugins: {
		            ptype: 'gridviewdragdrop',
		            dragText: '拖动以重新排列餐品分类顺序'
			    },
		        listeners: {
		        	scope: this,
					'drop': this.onSectionDrop
				}
	        },
	        store : this.sectionStore,
			columns: [
	            {
	                text     : '分类名称',
	                width    : 300,
	                sortable : true,
	                dataIndex: 'name',
	                editor: {
						allowBlank: false,
						blankText : '分类名称不能为空'
					}
	            },
	            {
					xtype: 'checkcolumn',
	                text     : '不接受订餐',
	                editable : true, //由我扩展，哈哈。
	                sortable : true,
	                width    : 80,
	                dataIndex: 'denyorder',
					editor: {
						xtype: 'checkbox',
						cls: 'x-grid-checkheader-editor'
					}
	            },
	            {
	                text     : '次序',
	                sortable : true,
	                width    : 60,
	                dataIndex: 'sequence',
	                align	 : 'center'
	            },
	            {
	                text     : '上次更新时间',
	                sortable : true,
	                width    : 140,
	                dataIndex: 'lastupdate'
	            },
	            {
	                xtype: 'actioncolumn',
	                flex: 1,
	                items: [{
	                    icon   : 'images/delete.png',
	                    altText: '删除分类',
	                    tooltip: '删除分类',
	                    handler: this.deleteSection,
	                    scope: this
	                }, {
	                    icon   : 'images/edit.png',
	                    altText: '修改分类信息',
	                    tooltip: '修改分类信息',
	                    handler: this.editSection,
	                    scope: this
	                }]
	            }
	        ],
	        dockedItems: [{
				xtype: 'pagingtoolbar',
				store: this.sectionStore,   // same store GridPanel is using
				dock: 'bottom',
				displayInfo: true
			},{
				xtype: 'toolbar',
				items: [{
					id : 'edit_restaurant_'+this.restaurant.id+'_toolbar_add_section',
					text: '添加分类',
					tooltip: '添加一个分类',
					iconCls: 'add',
					scope: this,
					handler: this.addSection
				}, '-', {
					id : 'edit_restaurant_'+this.restaurant.id+'_toolbar_edit_section',
					text:'修改分类',
					tooltip:'修改所选的分类的信息',
					disabled : true,
					iconCls:'edit',
					scope: this,
					handler: this.editSelectedSection
				},'-',{
					id : 'edit_restaurant_'+this.restaurant.id+'_toolbar_delete_section',
					text:'删除分类',
					tooltip:'批量删除所选的分类',
					disabled : true,
					iconCls:'delete',
					scope: this,
					handler: this.deleteSelectedSection
				}]
			}],
			selType: 'rowmodel',
			plugins: [this.sectionRowEditing],
			listeners: {
				scope: this,
				'edit' : this.afterSectionEdit,
				'canceledit' : this.cancelSectionEdit,
				'beforeedit' : this.beforeSectionEdit,
				'selectionchange' : this.sectionSelectionChange
			}
		});
		
		this.pendingSectionRequest = new Ext.util.MixedCollection();
		
		return this.sectionGrid;
	},
	
	onSectionDrop : function(node, data, overModel, dropPosition, eOpts ) {
		var bad = new Array();
		var i = 0;
		this.sectionStore.each(function(record){
			i++;
			if(record.data.sequence!=i){
				bad.push(record.data.id +":" + record.data.sequence + ":" + i); //ID:旧:新
				record.set('sequence',i); //本地更新数据
			}
		});
		if(bad.length>0){
	   		Ext.Ajax.request({
				url: 'sequence_section.php',
				params: {data: bad.join(",")}, //POST数据：data=ID:旧:新,ID:旧:新,ID:旧:新,....
				method: 'POST',
				success: this.sequenceSectionSuccess,
				failure: this.sequenceSectionFailure,
				scope: this
			});
		}

//		console.log(bad.join(","));//ID:旧:新,ID:旧:新,ID:旧:新,....
	},
        
    sequenceSectionSuccess : function(response, opts) {
    	this.sectionStore.each(function(record){
    		record.commit();
    	});
    	showAjaxResponseMsg( response, '重新调整次序', true );
    },
    
    sequenceSectionFailure : function(response, opts) {
    	this.sectionStore.each(function(record){
    		record.reject();
    	});
    	showAjaxResponseMsg( response, '重新调整次序' );
    },
	
	sectionSelectionChange : function ( model, selected, eOpts ) {
		var noSelection = (selected.length==0);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_section').setDisabled(noSelection);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_section').setDisabled(noSelection);
	},
	
		
	beforeSectionEdit : function (editor, e) {
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_add_section').setDisabled(true);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_section').setDisabled(true);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_section').setDisabled(true);
	},
	
	cancelSectionEdit :  function(grid, eOpts) {
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_add_section').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_section').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_section').setDisabled(false);
	},
	
	afterSectionEdit : function(editor) {
		if(this.addingSection){ //添加记录
			var request = Ext.Ajax.request({
    			url: 'add_section.php',
    			params: editor.record.data,
    			method: 'POST',
    			success: this.addSectionSuccess,
    			failure: this.addSectionFailure,
    			scope: this
    		});
    		this.pendingSectionRequest.add(request.id,editor.record);
		}
		else if(editor.record.dirty){ //编辑记录，并且数据已经变更
			var request = Ext.Ajax.request({
    			url: 'update_section.php',
    			params: editor.record.data,
    			method: 'POST',
    			success: this.updateSectionSuccess,
    			failure: this.updateSectionFailure,
    			scope: this
    		});
    		this.pendingSectionRequest.add(request.id,editor.record);
		}
		
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_add_section').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_section').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_section').setDisabled(false);
	},
	
	addSection : function () {
		this.addingSection = true;
		var addInPlace = true;	//在当前位置
		var addPosition = 1;	//之后添加
		var count = this.sectionStore.getTotalCount();
		var seq = count+1;
		var selected = this.sectionGrid.getSelectionModel().selected.first();
		if(selected) {
			seq = selected.data.sequence + 1;
		}
		else {					//没有选择任何项
			addInPlace = false;	//在第一行添加，但最终结果是添加到最后
			addPosition = 0;
		}
		var r = this.createNewSection(seq);
		this.sectionRowEditing.startAdd(r, {addInPlace:addInPlace, addPosition:addPosition});
	},
	
    addSectionSuccess : function(response, opts) {
    	var json = showAjaxResponseMsg( response, "添加分类", true);
//    	var record = this.pendingSectionRequest.getByKey(response.requestId);
//    	if (record) {
//    		if(json){ //成功返回json，应该有我们想要的ID
//    			record.data.id = json.id;
//    			record.data.lastupdate = Ext.Date.format(new Date(), 'Y-m-d H:i:s');
//    			record.commit();
//    		}
//    		else {
//    			this.sectionStore.remove(record);
//    		}
//    	}
    	this.pendingSectionRequest.removeAtKey(response.requestId);
    	this.addingSection = false;
    	this.sectionStore.load();
    },
    
    addSectionFailure : function(response, opts) {
    	showAjaxResponseMsg( response, "添加分类");
    	
//    	var record = this.pendingSectionRequest.getByKey(response.requestId);
//    	if (record) {
//    		this.sectionStore.remove(record);
//    	}
    	this.pendingSectionRequest.removeAtKey(response.requestId);
    	this.addingSection = false;
    	this.sectionStore.load();
    },
    	
    updateSectionSuccess : function(response, opts) {
    	var success = showAjaxResponseMsg( response, "修改分类信息", true);
    	var record = this.pendingSectionRequest.getByKey(response.requestId);
    	if (record) {
    		if(success){
    			record.data.lastupdate = Ext.Date.format(new Date(), 'Y-m-d H:i:s');
    			record.commit();
    		}
    		else {
    			record.reject();
    		}
    	}
    	this.pendingSectionRequest.removeAtKey(response.requestId);
    },
    
    updateSectionFailure : function(response, opts) {
    	showAjaxResponseMsg( response, "修改分类信息");
    	
    	var record = this.pendingSectionRequest.getByKey(response.requestId);
    	if (record) {
    		record.reject();
    	}
    	this.pendingSectionRequest.removeAtKey(response.requestId);
    },
    
	createNewSection : function (seq) {
		var r = Ext.create('Section', {
			name: '新分类',
			restaurantid: this.restaurant.id,
			restaurant: this.restaurant.name,
			denyorder: false,
			lastupdate: Ext.Date.format(new Date(), 'Y-m-d H:i:s'),
			sequence: seq
		});
		return r;
	},
	
	editSelectedSection : function () {
		if(this.sectionRowEditing.editing) return;
		var item = this.sectionGrid.getSelectionModel().selected.first();
		if(item){
			var rowIndex = this.sectionStore.indexOf(item);
			this.sectionRowEditing.startEdit(rowIndex, 0);
		}
	},
	
	deleteSelectedSection : function () {
		if(this.sectionRowEditing.editing) return;
		var item = this.sectionGrid.getSelectionModel().selected.first(); //注意只删除第一个（其实本来就是单选模式）
		if(item){
			var id = item.data.id;
			var name = item.data.name;
			var sequence = item.data.sequence;
			var restaurantid = item.data.restaurantid;
			Ext.MessageBox.confirm("删除确认",
				"确认要删除以下分类吗？<br><b style='color: #ff0000'>"+name+"</b>",
				function ( btn ) {
					if ( btn == 'yes' ) {
			    		Ext.Ajax.request({
			    			url: 'delete_section.php',
			    			params: {id: id, name: name, sequence: sequence, restaurantid: restaurantid},
			    			method: 'POST',
			    			success: this.deleteSectionSuccess,
			    			failure: this.deleteSectionFailure,
			    			scope: this
			    		});
					}
				},
				this
			);
		}
	},
	
	deleteSection : function(grid, rowIndex, colIndex) {
		if(this.sectionRowEditing.editing) return;
		if(grid.store.data.items[rowIndex].data.id && grid.store.data.items[rowIndex].data.name){
			var id = grid.store.data.items[rowIndex].data.id;
			var name = grid.store.data.items[rowIndex].data.name;
			var sequence = grid.store.data.items[rowIndex].data.sequence;
			var restaurantid = grid.store.data.items[rowIndex].data.restaurantid;
			Ext.MessageBox.confirm("删除确认",
				"确认要删除这个分类吗？<br><b style='color: #ff0000'>"+name+"</b>",
				function ( btn ){
					if( btn == 'yes' ){
			    		Ext.Ajax.request({
			    			url: 'delete_section.php',
			    			params: {id: id, name: name, sequence: sequence, restaurantid: restaurantid},
			    			method: 'POST',
			    			success: this.deleteSectionSuccess,
			    			failure: this.deleteSectionFailure,
			    			scope: this
			    		});
					}
				},
				this
			);
		}
    },
	
    deleteSectionSuccess : function(response, opts) {
    	this.sectionGrid.store.load();
    	showAjaxResponseMsg( response, "删除餐品分类");
    },
    
    deleteSectionFailure : function(response, opts) {
    	this.sectionGrid.store.load();
    	showAjaxResponseMsg( response, "删除餐品分类");
    },
    
	///TODO
	editSection : function(grid, rowIndex, colIndex) {
		if(this.sectionRowEditing.editing) return;
		this.sectionRowEditing.startEdit(rowIndex, 0);
	},
	
	createDishGrid : function () {
		this.dishStore = Ext.create('Ext.data.Store',{
			storeId: 'editRestaurantDishStore_' + this.restaurant.id,
			autoDestroy: true,
			model: 'Dish',
			pageSize: 1000,
			groupField: 'section',
			proxy: {
				type: 'ajax',
				url: 'dishes.php',
				extraParams: {restaurantid : this.restaurant.id},
				reader: {
					type: 'json',
					root: 'dishes',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true
		});

		this.dishRowEditing = Ext.create('Ext.ux.grid.plugin.RowEditing', {
			clicksToEdit : 2,		//双击进入编辑
			clicksToMoveEditor: 1,	//编辑过程中单击其他行开始编辑其他行
			autoCancel: true,		//编辑过程中单击其他行是否自动取消本行的数据保存，否
			errorSummary : false
		});
		
		this.groupingFeature = Ext.create('Ext.grid.feature.Grouping',{
	        groupHeaderTpl: '{name} (共 {rows.length} 个)',
	        enableNoGroups: false
	    });

		this.dishGrid = Ext.create("Ext.grid.Panel", {
			title : '餐品列表',
			autoScroll : true,
	        viewConfig: {
	            stripeRows: true,
	            plugins: {
		            ptype: 'gridviewdragdrop',
		            dragText: '拖动以重新排列餐品顺序'
			    },
		        listeners: {
		        	scope: this,
					'drop': this.onDishDrop,
					'beforedrop' : this.onBeforeDrop
				}
	        },
	        store : this.dishStore,
	        features: [this.groupingFeature],
			columns: [
	            {
	                text     : '餐品名称',
	                width    : 200,
	                sortable : true,
	                dataIndex: 'name',
	                editor: {
						allowBlank: false,
						blankText : '餐品名称不能为空'
					}
	            },
	            {
	                text     : '分类',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'section',
					editor: {
						xtype: 'combobox',
						typeAhead: true,
						triggerAction: 'all',
						selectOnTab: true,
						store: this.sectionStore,
						valueField : 'name',
						displayField : 'name',
						queryMode : 'local',
						lazyRender: true,
						listClass: 'x-combo-list-small',
						listeners: {
							scope: this,//TODO COMBO LISTENER
							'select' : function(combobox, value){//在选择变化时变更本记录对应的sectionid
								var sectionid = value[0].data.id;
								var rowIdx = this.dishRowEditing.context.rowIdx;
								var row = this.dishRowEditing.context.store.getAt(rowIdx);
								row.data.sectionid = sectionid;
								this.lastSection = value[0].data.name;
								this.lastSectionId = value[0].data.id;
							}
						}
					}
	            },
	            {
	                text     : '餐馆名称',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'restaurant'
	            },
	            {
	                text     : '注释',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'annotation',
	                editor: {
						allowBlank: true
					}
	            },
				{
					text : '数量',
					width : 100,
					sortable : false,
					dataIndex : 'dishCount',
					editor : {
						xtype : 'numberfield',
						allowBlank : true
					}
				},
	            {
					xtype: 'numbercolumn',
	                text     : '单价',
	                width    : 100,
	                sortable : true,
	                dataIndex: 'price',
	                decimalSeparator : '.',
					format: '￥0.00',
					editor: {
						xtype: 'numberfield',
						allowBlank: false,
						blankText : '餐品单价不能为空',
						minValue: 0,
						maxValue: 999999.99
					}
	            },
	            {
					xtype: 'numbercolumn',
	                text     : '折扣价',
	                sortable : true,
	                width    : 100,
	                dataIndex: 'discountprice',
					format: '￥0.00',
					editor: {
						xtype: 'numberfield',
						minValue: 0,
						maxValue: 999999.99
					}
	            },
	            {
					xtype: 'checkcolumn',
	                text     : '餐品下架',
	                editable : true, //由我扩展，哈哈。
	                sortable : true,
	                width    : 80,
	                dataIndex: 'denyorder',
	                hidden : false,
	                editor: {
						xtype: 'checkbox',
						cls: 'x-grid-checkheader-editor'
					}
	            },
	            {
	                text     : '次序',
	                sortable : true,
	                width    : 60,
	                dataIndex: 'sequence',
	                align	 : 'center'
	            },
	            {
	                text     : '上次更新时间',
	                sortable : true,
	                width    : 140,
	                dataIndex: 'lastupdate'
	            },
	            {
	                xtype: 'actioncolumn',
	                flex: 1,
	                items: [{
	                    icon   : 'images/delete.png',
	                    altText: '删除餐品',
	                    tooltip: '删除餐品',
	                    handler: this.deleteDish,
	                    scope: this
	                }, {
	                    icon   : 'images/edit.png',
	                    altText: '修改餐品信息',
	                    tooltip: '修改餐品信息',
	                    handler: this.editDish,
	                    scope: this
	                }, {
						icon : 'images/database_go.png',
						altText : '上传图片',
						tooltip : '点击上传该餐品的图片',
						handler : this.update_dishImg,
						scope : this
					}, {
						icon : 'images/key.png',
						altText : '上面下架',
						tooltip : '点击下架该商品',
						handler : function(grid,rowIndex){
							var dish_id =grid.store.data.items[rowIndex].data.id;// 获得餐品的Id
							if(dish_id){
								Ext.MessageBox.confirm("提示",
										"确认要下架该餐品吗？<br><b style='color: #ff0000'>" + name
												+ "</b>", function(btn) {
											if (btn == 'yes') {
												
												Ext.Ajax.request({
															url : 'xiajia.php',
															params : {
																dishId : dish_id,
																action:'xiajia'
															},
															method : 'POST',
															success :function (response){
																 var text = response.responseText;
																 var json=Ext.decode(text);
																 //jingyifei
																 if(json.success=='true'){
																		Ext.Msg.alert('提示',
																		'下架成功');
																 }else{
																		Ext.Msg.alert('提示',
																		'下架失败');
																 }
																 dish_store.load();
															},
															failure : function(){
																Ext.Msg.alert('提示',
																'下架失败');
															},
															scope : this
														});
											}
										}, this);
							}else{
								Ext.Msg.alert('提示',
								'请选择一列');
							}
							
						},
						scope : this
					}]
	            }
	        ],
	        dockedItems: [{
				xtype: 'pagingtoolbar',
				store: this.dishStore,   // same store GridPanel is using
				dock: 'bottom',
				displayInfo: true
			},{
				xtype: 'toolbar',
				items: [{
					id : 'edit_restaurant_'+this.restaurant.id+'_toolbar_add_dish',
					text: '添加餐品',
					tooltip: '添加一个餐品',
					iconCls: 'add',
					scope: this,
					handler: this.addDish
				}, '-', {
					id : 'edit_restaurant_'+this.restaurant.id+'_toolbar_edit_dish',
					text:'修改餐品',
					tooltip:'修改所选的餐品的信息',
					iconCls:'edit',
					disabled : true,
					scope: this,
					handler: this.editSelected
				},'-',{
					id : 'edit_restaurant_'+this.restaurant.id+'_toolbar_delete_dish',
					text:'删除餐品',
					tooltip:'批量删除所选的餐品',
					iconCls:'delete',
					disabled : true,
					scope: this,
					handler: this.deleteSelected
				}]
			}],
			selType: 'rowmodel',
			plugins: [this.dishRowEditing],
			listeners: {
				scope: this,
				'edit' : this.afterDishEdit,
				'canceledit' : this.cancelDishEdit,
				'beforeedit' : this.beforeDishEdit,
				'selectionchange' : this.dishSelectionChange
			}
		});
		
		this.pendingDishRequest = new Ext.util.MixedCollection();
		
		return this.dishGrid;
	},
	
	
	onBeforeDrop : function(node, data, overModel, dropPosition, dropFunction, eOpts ) {
		if(data.records[0].data.sectionid!=overModel.data.sectionid) return false;
	},
	
	
	onDishDrop : function(node, data, overModel, dropPosition, eOpts ) {
		var bad = new Array();
		var i = 0;
		var sectionId = data.records[0].data.sectionid;
		this.dishStore.each(function(record){
			if(record.data.sectionid == sectionId){
				i++;
				if(record.data.sequence!=i){
					bad.push(record.data.id +":" + record.data.sequence + ":" + i); //ID:旧:新
					record.set('sequence',i); //本地更新数据
				}
			}
		});
		if(bad.length>0){
	   		Ext.Ajax.request({
				url: 'sequence_dish.php',
				params: {data: bad.join(",")}, //POST数据：data=ID:旧:新,ID:旧:新,ID:旧:新,....
				method: 'POST',
				success: this.sequenceDishSuccess,
				failure: this.sequenceDishFailure,
				scope: this
			});
		}

//		console.log(bad.join(","));//ID:旧:新,ID:旧:新,ID:旧:新,....
	},
        
    sequenceDishSuccess : function(response, opts) {
    	this.dishStore.each(function(record){
    		record.commit();
    	});
    	showAjaxResponseMsg( response, '重新调整次序', true );
    },
    
    sequenceDishFailure : function(response, opts) {
    	this.dishStore.each(function(record){
    		record.reject();
    	});
    	showAjaxResponseMsg( response, '重新调整次序' );
    },
	
	dishSelectionChange : function ( model, selected, eOpts ) {
		var noSelection = (selected.length==0);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_dish').setDisabled(noSelection);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_dish').setDisabled(noSelection);
	},
	
	beforeDishEdit : function (editor, e) {
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_add_dish').setDisabled(true);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_dish').setDisabled(true);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_dish').setDisabled(true);
	},
	
	cancelDishEdit :  function(grid, eOpts) {
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_add_dish').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_dish').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_dish').setDisabled(false);
	},
	
	afterDishEdit : function(editor) {
		if(this.addingDish){ //添加记录
			var request = Ext.Ajax.request({
    			url: 'add_dish.php',
    			params: editor.record.data,
    			method: 'POST',
    			success: this.addDishSuccess,
    			failure: this.addDishFailure,
    			scope: this
    		});
    		this.pendingDishRequest.add(request.id,editor.record);
		}
		else if(editor.record.dirty){ //编辑记录，并且数据已经变更
			var request = Ext.Ajax.request({
    			url: 'update_dish.php',
    			params: editor.record.data,
    			method: 'POST',
    			success: this.updateDishSuccess,
    			failure: this.updateDishFailure,
    			scope: this
    		});
    		this.pendingDishRequest.add(request.id,editor.record);
		}
		
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_add_dish').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_edit_dish').setDisabled(false);
		Ext.getCmp('edit_restaurant_'+this.restaurant.id+'_toolbar_delete_dish').setDisabled(false);
	},
	
	addDish : function () {
		this.addingDish = true;
		var addInPlace = true;	//在当前位置
		var addPosition = 1;	//之后添加
		var selected = this.dishGrid.getSelectionModel().selected.first();
		if(!selected) {			//没有选择任何项
			addInPlace = false;	//在开头添加
			addPosition = 0;
		}
		var r = this.createNewDish(selected); //根据当前的选择创建新餐品
		this.dishRowEditing.startAdd(r, {addInPlace:addInPlace, addPosition:addPosition});
	},
	
    addDishSuccess : function(response, opts) {
    	var json = showAjaxResponseMsg( response, "添加餐品", true);
//    	var record = this.pendingDishRequest.getByKey(response.requestId);
//    	if (record) {
//    		if(json){ //成功返回json，应该有我们想要的ID
//    			record.data.id = json.id;
//    			record.data.lastupdate = Ext.Date.format(new Date(), 'Y-m-d H:i:s');
//    			record.commit();
//    			this.dishStore.group("section"); //让其重新进行分组。
//    		}
//    		else {
//    			this.dishStore.remove(record);
//    		}
//    	}
    	this.pendingDishRequest.removeAtKey(response.requestId);
    	this.addingDish = false;
    	this.dishStore.load();
    },
    
    addDishFailure : function(response, opts) {
    	showAjaxResponseMsg( response, "添加餐品");
    	
//    	var record = this.pendingDishRequest.getByKey(response.requestId);
//    	if (record) {
//    		this.dishStore.remove(record);
//    	}
    	this.pendingDishRequest.removeAtKey(response.requestId);
    	this.addingDish = false;
    	this.dishStore.load();
    },
    	
    updateDishSuccess : function(response, opts) {
    	var success = showAjaxResponseMsg( response, "修改餐品信息", true);
    	var record = this.pendingDishRequest.getByKey(response.requestId);
    	if (record) {
    		if(success){
    			record.data.lastupdate = Ext.Date.format(new Date(), 'Y-m-d H:i:s');
    			record.commit();
    			this.dishStore.group("section"); //让其重新进行分组。
    		}
    		else {
    			record.reject();
    		}
    	}
    	this.pendingDishRequest.removeAtKey(response.requestId);
    },
    
    updateDishFailure : function(response, opts) {
    	showAjaxResponseMsg( response, "修改餐品信息");
    	
    	var record = this.pendingDishRequest.getByKey(response.requestId);
    	if (record) {
    		record.reject();
    	}
    	this.pendingDishRequest.removeAtKey(response.requestId);
    },
    
	createNewDish : function(selected) {
		var seq = 0;
		if(selected){
			this.lastSection = selected.data.section;
			this.lastSectionId = selected.data.sectionid;
			seq = selected.data.sequence+1;
		}
		var r = Ext.create('Dish', {
			name: '新菜',
			section: this.lastSection || '未分类',
			sectionid: this.lastSectionId || null,
			restaurantid: this.restaurant.id,
			restaurant: this.restaurant.name,
			annotation: '',
			price: '10',
			discountprice: '',
			denyorder: false,
			lastupdate: Ext.Date.format(new Date(), 'Y-m-d H:i:s'),
			sequence: seq
		});
		return r;
	},
	
	editSelected : function () {
		if(this.dishRowEditing.editing) return;
		var item = this.dishGrid.getSelectionModel().selected.first();
		if(item){
			var rowIndex = this.dishStore.indexOf(item);
			this.dishRowEditing.startEdit(rowIndex, 0);
		}
	},
	
	deleteDish : function(grid, rowIndex, colIndex) {
		if(grid.store.data.items[rowIndex].data.id && grid.store.data.items[rowIndex].data.name){
			var id = grid.store.data.items[rowIndex].data.id;
			var name = grid.store.data.items[rowIndex].data.name;
			var sectionid = grid.store.data.items[rowIndex].data.sectionid;
			var restaurantid = grid.store.data.items[rowIndex].data.restaurantid;
			var sequence = grid.store.data.items[rowIndex].data.sequence;
			Ext.MessageBox.confirm("删除确认",
				"确认要删除以下餐品吗？<br><b style='color: #ff0000'>"+name+"</b>",
				function ( btn ){
					if( btn == 'yes' ){
			    		Ext.Ajax.request({
			    			url: 'delete_dish.php',
			    			params: {id: id, name: name, sequence:sequence, restaurantid:restaurantid, sectionid:sectionid},
			    			method: 'POST',
			    			success: this.deleteDishSuccess,
			    			failure: this.deleteDishFailure,
			    			scope: this
			    		});
					}
				},
				this
			);
		}
    },
    
	deleteSelected : function () {
		if(this.dishRowEditing.editing) return;
		var item = this.dishGrid.getSelectionModel().selected.first(); //注意只删除第一个（其实本来就是单选模式）
		if(item){
			var id = item.data.id;
			var name = item.data.name;
			var sequence = item.data.sequence;
			var restaurantid = item.data.restaurantid;
			var sectionid = item.data.sectionid;
			Ext.MessageBox.confirm("删除确认",
				"确认要删除以下餐品吗？<br><b style='color: #ff0000'>"+name+"</b>",
				function ( btn ) {
					if ( btn == 'yes' ) {
			    		Ext.Ajax.request({
			    			url: 'delete_dish.php',
			    			params: {id: id, name: name, sequence:sequence, restaurantid:restaurantid, sectionid:sectionid},
			    			method: 'POST',
			    			success: this.deleteDishSuccess,
			    			failure: this.deleteDishFailure,
			    			scope: this
			    		});
					}
				},
				this
			);
		}
	},
    
	editDish : function(grid, rowIndex, colIndex) {
		if(this.dishRowEditing.editing) return;
		this.dishRowEditing.startEdit(rowIndex, 0);
	},
	
    deleteDishSuccess : function(response, opts) {
    	this.dishGrid.store.load();
    	showAjaxResponseMsg( response, "删除餐品");
    },
    
    deleteDishFailure : function(response, opts) {
    	this.dishGrid.store.load();
    	showAjaxResponseMsg( response, "删除餐品");
    },
	update_dishImg : function(grid, rowIndex) {//添加上传图片
		if (grid.store.data.items[rowIndex].data.id
				&& grid.store.data.items[rowIndex].data.name) {
			this.dish_id = grid.store.data.items[rowIndex].data.id;// 获得餐品的Id
			this.dishImgPath = grid.store.data.items[rowIndex].data.imagePath;// 获得餐品的图片地址
			// var name =
			// grid.store.data.items[rowIndex].data.name;
			// var sectionid =
			// grid.store.data.items[rowIndex].data.sectionid;
			// var restaurantid =
			// grid.store.data.items[rowIndex].data.restaurantid;
			// var sequence =
			// grid.store.data.items[rowIndex].data.sequence;

			// 弹出窗体开始选择
			this.imgWindow.show();

		}
	}
});
}
var dish_store = null;
var restId = 0;// 餐馆Id