if (!Ext.ModelManager.isRegistered('AddRestaurant')){
Ext.define('AddRestaurant', {
	extend : 'Ext.form.Panel',
	alias  : 'widget.AddRestaurant',
	
	initComponent : function() {
		Ext.apply(this, {
			id : 'widget.AddRestaurant',
			title : '　添加餐馆　',
			closable : true,
			layout: 'fit',
			items: {
				xtype: 'panel',
				layout: {
					type: 'hbox',
					align: 'stretch'
				},
	
	            items:[this.createBaseInfoPanel(),{xtype: 'panel', width: 1}, this.createMapFormPanel()]
				
			},
			buttonAlign: 'left',
			buttons: [{
	            text: '保存',
	            handler: this.submitForm,
	            scope: this
	        },{
	            text: '重置',
	            handler: function() {this.getForm().reset();},
	            scope: this
	        }]
		});
		this.callParent(arguments);
	},
	
	createBaseInfoPanel : function() {
		var ratings = Ext.create('Ext.data.Store', {
			fields :["value",  "text"],
			data : [
				{"value": 1, "text": "一星"},
				{"value": 2, "text": "二星"},
				{"value": 3, "text": "三星"}
			]
		});
		
		var cityDataInitialization = function (store, records, options){
			var idCombo = Ext.getCmp("add_restaurant_cities_id_combo");
			var nameHiddenField = Ext.getCmp("add_restaurant_city_name_hiddenfield");
			if(records.length){
				idCombo.setValue(records[0].data.id);
				nameHiddenField.setValue(records[0].data.name);
				cities.removeListener('load', cityDataInitialization);
//				if(records.length==1){
//					idCombo.setReadOnly(true);
//				}
				
				regions.getProxy().extraParams.cityid = records[0].data.id;
				regions.loadPage(1);
				
				var lat = records[0].data.latitude;
				var lng = records[0].data.longitude;
				var zoom = records[0].data.zoomlevel;
				
				this.map = makeMapInDiv("add_restaurant_map_canvas", lat, lng, zoom);
				
				var latF = Ext.getCmp("add_restaurant_latitude_hiddenfield");
				var lngF = Ext.getCmp("add_restaurant_longitude_hiddenfield");
				var zoomF = Ext.getCmp("add_restaurant_zoomlevel_hiddenfield");
				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());
			    });
			}
		};
		
		var cities = Ext.create('Ext.data.Store',{
			storeId: 'addRestaurantCitiesStore',
			autoDestroy: true,
			model: 'City',
			pageSize: 10,
			proxy: {
				type: 'ajax',
				url: 'cities.php',
				reader: {
					type: 'json',
					root: 'cities',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true,
			listeners: {
				'load': cityDataInitialization,
				scope: this
			}
		});
		
		var regions = Ext.create('Ext.data.Store',{
			storeId: 'addRestaurantRegionsStore',
			autoDestroy: true,
			model: 'Region',
			pageSize: 30,
			clearOnPageLoad : true,
			proxy: {
				type: 'ajax',
				url: 'regions.php',
				reader: {
					type: 'json',
					root: 'regions',
					totalProperty: 'total',
					id: 'id'
				}
			}
		});
		
		var agentDataInitialization = function (store, records, options){
			var idCombo = Ext.getCmp("add_restaurant_agents_id_combo");
			var nameHiddenField = Ext.getCmp("add_restaurant_agent_name_hiddenfield");
			if(records.length){
				idCombo.setValue(records[0].data.id);
				nameHiddenField.setValue(records[0].data.name);
				agents.removeListener('load', agentDataInitialization);
//				if(records.length==1){
//					idCombo.setReadOnly(true);
//				}
			}
		};
		var agents = Ext.create('Ext.data.Store',{
			storeId: 'addRestaurantAgentsStore',
			autoDestroy: true,
			model: 'Agent',
			pageSize: 10,
			proxy: {
				type: 'ajax',
				url: 'agents.php',
				reader: {
					type: 'json',
					root: 'agents',
					totalProperty: 'total',
					id: 'id'
				}
			},
			autoLoad: true,
			listeners: {
				'load': agentDataInitialization,
				scope: this
			}
		});
		
		this.baseInfoPanel = Ext.create('Ext.form.Panel', {
			title: '基本信息',
			flex: 1,
    		bodyPadding: 10,
			autoScroll : true,
			border : false,
			frame: false,
	        fieldDefaults : {
	            msgTarget: 'side',
	            labelWidth: 130,
	            labelAlign: 'right'
	        },
    		defaultType: 'textfield',
    		items: [{
            	xtype: 'fieldset',
            	title: '总体信息',
    			defaultType: 'textfield',
    			padding: 10,
            	items: [{
	    			fieldLabel: '名称',
	    			width: 350,
					name: 'name',
					allowBlank: false,
					blankText : '餐馆名称不能为空',
					enforceMaxLength : true,
					maxLength : 80,
					maxLengthText : '餐馆名称不能超过40个汉字（80个字符）'
	    		},{
	    			id: 'add_restaurant_agents_id_combo',
	    			fieldLabel: '所属代理',
					name: '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("add_restaurant_agent_name_hiddenfield");
							nameField.setValue(value[0].data.name);
						}
					}
	    		},{
	    			id: 'add_restaurant_agent_name_hiddenfield',
					xtype: 'hiddenfield',
					name: 'agent'
				},{
					id: 'add_restaurant_cities_id_combo',
	    			fieldLabel: '所属城市',
					name: '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("add_restaurant_city_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.map.setCenter( new google.maps.LatLng(lat, lng) );
							this.map.setZoom( zoom );
										
							regions.getProxy().extraParams.cityid = value[0].data.id;
							regions.loadPage(1);
							var regionIdField =  Ext.getCmp("add_restaurant_regions_id_combo");
							regionIdField.clearValue();
							var regionField =  Ext.getCmp("add_restaurant_region_name_hiddenfield");
							regionField.setValue('');
						}
					}
	    		},{
	    			id: 'add_restaurant_city_name_hiddenfield',
					xtype: 'hiddenfield',
					name: 'city'
				},{
					id: 'add_restaurant_regions_id_combo',
	    			fieldLabel: '所属区域',
					name: 'regionid',
					xtype: 'combo',
					editable: false,
					queryMode: 'local',
					store: regions,
					pageSize: 30,
	    			width: 430,
					displayField: 'name',
					valueField: 'id',
					defaultListConfig:{
						loadMask:false
					},
					
					listeners: {
						scope: this,
//						'render':function(obj,options){
//							obj.getEl().unmask();
//						},
//						'beforequery':function(obj){
//							obj.combo.getEl().unmask();
//						},
						'select' : function(combobox, value){
							var nameField = Ext.getCmp("add_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.map.setCenter( new google.maps.LatLng(lat, lng) );
							this.map.setZoom( zoom );
						}
					}
	    		},{
	    			id: 'add_restaurant_region_name_hiddenfield',
					xtype: 'hiddenfield',
					name: 'region'
				},{
	    			fieldLabel: '电话',
					name: 'telephone',
					allowBlank: false,
					blankText : '餐馆电话不能为空',
					enforceMaxLength : true,
					maxLength : 20,
					maxLengthText : '餐馆电话不能超过20个字符'
	    		},{
	    			fieldLabel: '短信手机号码',
					name: 'mobile',
					allowBlank: false,
					blankText : '短信手机号码用于接收短信，不能为空',
					enforceMaxLength : true,
	            	regex : /^((\+86)?|(86)?)(13[0-9]{9}|15[0|1|2|3|5|6|7|8|9]\d{8}|18[0|5|6|7|8|9]\d{8})$/,
	            	regexText : '请填写有效的手机号码',
					maxLength : 11,
					maxLengthText : '短信手机号码不能超过11个字符'
	    		},{
	    			xtype: 'fieldcontainer',
	    			fieldLabel: '是否城市默认餐馆',
					defaultType: 'radiofield',
					layout: 'hbox',
					items: [{
						boxLabel  : '是',
						name: 'citydefault',
						inputValue: '1',
						checked: false
	                }, {
						boxLabel: '否',
						name: 'citydefault',
						inputValue: '0',
						checked: true
	                }]
				},{
	    			fieldLabel: '佣金比例（%）',
					name: 'commission',
					xtype: 'numberfield',
					allowBlank: false,
					blankText : '佣金比例不能为空',
					value: 10,
					minValue: 0,
					maxValue: 100,
					allowDecimals: false
	    		},{
	    			fieldLabel: '评级',
					name: 'rating',
					xtype: 'combo',
					editable: false,
					store: ratings,
					queryMode: 'local',
					displayField: 'text',
					valueField: 'value',
					value: 2
    			}]
    		},{
            	xtype: 'fieldset',
            	title: '外卖相关',
    			defaultType: 'textfield',
    			padding: 10,
            	items: [{
	    			fieldLabel: '外卖时间',
					name: 'businesshour',
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 80,
					maxLengthText : '外卖时间不能超过80个字符'
	    		},{
	    			fieldLabel: '外卖说明',
					name: 'businessmemo',
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '外卖时间不能超过255个字符',
					value : '该餐厅多数情况能送外卖'
	    		},{
	    			fieldLabel: '送餐费用（元）',
					name: 'fee',
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 999.99,
					maxText: '送餐费用最大为999.99，如需修改此规则，请找开发人员。'
	    		},{
	    			fieldLabel: '起送金额（元）',
					name: 'minmoney',
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 999.99,
					maxText: '起送金额最大为999.99，如需修改此规则，请找开发人员。'
	    		},{
	    			fieldLabel: '送餐范围（米）',
					name: 'scope',
					xtype: 'numberfield',
					minValue: 0,
					value: 500,
					allowDecimals: false
	    		},{
	    			fieldLabel: '折扣（X.x）',
					name: 'discount',
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 10,
					allowDecimals: true,
					decimalPrecision: 1,
					value:10,
					allowBlank:false
	    		},{
	    			fieldLabel: '公告',
					name: 'notice',
					xtype: 'textareafield',
	    			width: 430,
	    			height: 50,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '公告不能超过255个字符',
					value: '为了您的准时用餐，请提前20分钟订餐。'
	    		},{
	    			xtype: 'fieldcontainer',
	    			fieldLabel: '是否支持送餐上门',
					defaultType: 'radiofield',
					layout: 'hbox',
					items: [{
						boxLabel  : '是',
						name: 'takeout',
						inputValue: '1',
						checked: true
	                }, {
						boxLabel: '否',
						name: 'takeout',
						inputValue: '0',
						checked: false
	                }]
				},{
	    			fieldLabel: '到店消费折扣（X.x）',
					name: 'discountin',
					xtype: 'numberfield',
					minValue: 0,
					maxValue: 10,
					allowDecimals: true,
					decimalPrecision: 1,
					value:10,
					allowBlank:false
	    		},{
	    			fieldLabel: '优惠信息',
					name: 'salead',
					xtype: 'textareafield',
	    			width: 430,
	    			height: 50,
					value: '到{name}消费可享受 {discount} 折优惠。'
	    		},{
	    			fieldLabel: '主食类',
					name: 'staple',
					xtype: 'textfield',
					width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '不能超过255个字符'
	    		}]
    		},{
            	xtype: 'fieldset',
            	title: '内部信息',
    			defaultType: 'textfield',
    			padding: 10,
            	items: [{
	    			fieldLabel: '地址',
					name: 'address',
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '地址不能超过255个字符'
	    		},{
	    			fieldLabel: '联系人',
					name: 'linkman',
					enforceMaxLength : true,
					maxLength : 50,
					maxLengthText : '联系人不能超过50个字符'
	    		},{
	    			fieldLabel: '联系电话',
					name: 'linkphone',
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '联系电话不能超过255个字符'
	    		},{
	    			fieldLabel: '关键字（SEO）',
					name: 'keyword',
	    			width: 430,
					enforceMaxLength : true,
					maxLength : 255,
					maxLengthText : '关键字不能超过255个字符',
					value: '外卖,菜单,订餐,电话,送餐,外送'
	    		}]
    		},{
				xtype : 'fieldset',
				title : '打印设备管理',
				defaultType : 'textfield',
				padding : 10,
				items : [{
					fieldLabel : '是否使用打印机',
					name : 'isprint',
					xtype : 'checkbox',//jingyifei,
					//checked:this.restaurant.salead,
					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',
					allowBlank: false,
					blankText : '登录用户名不能为空',
					enforceMaxLength : true,
					maxLength : 20,
					maxLengthText : '登录用户名不能超过20个字符（10个汉字）'
	    		},{
	    			fieldLabel: '登录密码',
					name: 'password',
					inputType : 'password',
					allowBlank: false,
					blankText : '登录密码不能为空',
					enforceMaxLength : true,
					maxLength : 32,
					maxLengthText : '登录密码不能超过32个字符'
	    		}]
    		}]
		});
		
		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: 'add_restaurant_longitude_hiddenfield',
	    			fieldLabel: '经度',
	    			labelWidth: 30,
	    			labelAlign: 'right',
	    			width: 150,
	    			readOnly: true,
					allowBlank: false,
					blankText : '坐标经度不能为空，请移动地图提取经度数据。',
					xtype: 'textfield',
					name: 'longitude'
				},{
	    			id: 'add_restaurant_latitude_hiddenfield',
	    			fieldLabel: '纬度',
	    			labelWidth: 40,
	    			labelAlign: 'right',
	    			width: 150,
	    			readOnly: true,
					allowBlank: false,
					blankText : '坐标纬度不能为空，请移动地图提取纬度数据。',
					xtype: 'textfield',
					name: 'latitude'
				},{
	    			id: 'add_restaurant_zoomlevel_hiddenfield',
	    			fieldLabel: '缩放',
	    			labelWidth: 40,
	    			labelAlign: 'right',
	    			width: 80,
	    			readOnly: true,
					allowBlank: false,
					blankText : '城市缩放倍数不能为空，请缩放地图获取缩放倍数',
					xtype: 'textfield',
					name: 'zoomlevel'
				}]
    		}]
		});
		return this.mapFormPanel;
	},
	
	createMapPanel : function() {
		var mapCanvasHtml = '<div id="add_restaurant_map_canvas" style="height:100%; width: 100%;">' +
				'</div><img src="images/center.png" style="left: 183px; top: 171px; position: absolute;">';
		AddRestaurantMap = Ext.extend(Ext.panel.Panel,{
			title: '通过缩放和移动地图，使餐馆位于地图中心（建议缩放大于16）。',
			layout: 'auto',
			height: 400,
			width: 400,
			html: mapCanvasHtml,
			afterRender : function (){
				AddRestaurantMap.superclass.afterRender.apply(this, arguments);
//				this.map = makeMapInDiv("add_restaurant_map_canvas");
//				var theMap = this.map;
//				google.maps.event.addListener(theMap, 'dragend', function() {
//					var lat = Ext.getCmp("add_restaurant_latitude_hiddenfield");
//					var lng = Ext.getCmp("add_restaurant_longitude_hiddenfield");
//					var center = theMap.getCenter();
//					lat.setValue(toPrecision(center.lat(),9));
//					lng.setValue(toPrecision(center.lng(),9));
//			    });
			}
		});
		
		this.mapPanel = new AddRestaurantMap();
		return this.mapPanel;
	},
	
	submitForm : function () {
		var form = this.getForm();
		if (form.isValid()) {
			var pswField = form.findField('password');
			this.lastPassword = pswField.getValue();
			var password = md5(this.lastPassword);
			pswField.setValue(password);
			this.submit({
				url:'add_restaurant.php',
				waitTitle : '请稍候',
				waitMsg : '正在保存餐馆数据...',
				method : 'POST',
		        success: this.addRestaurantSuccess,
		        failure: this.addRestaurantFailure,
		        scope: this
		    });
		}
		else {
			showErrorMsg( '某些输入项不符合规定，请检查各字段的输入。', '输入有误。' );
		}
	},
	
	addRestaurantSuccess : function (form, action) {
		this.resetPassword( form );
		showSuccessMsg( '保存餐馆信息到数据成功。' );
	},
	
	addRestaurantFailure : function (form, action) {
		this.resetPassword( form );
		showFormFailureMsg( action, '保存餐馆信息到数据失败');
	},
	
	resetPassword : function( form ){
		var pswField = form.findField('password');
		pswField.setValue(this.lastPassword);
	}
});
}