define(function(require){
	var $ = require('jquery');
	var IFA = require('util');
	require('validation')($);
	require('dialog')($);
	require('uriTemplate')($);
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../styles/cim/validation.css');
	$(function(){	
		 $("#districtLevel").change(function(){showDistrict();});
		 $("#save").click(function(){submitForm();});
		 $("#cancel").click(function(){close();});
	});
	$(function(){
		// 验证用户正确性
	    $("#newDistrict").validate({
		  rules:{
	    	districtName:{
	              required:true,
	             // regex: /^[\u4E00-\u9FA5\uF900-\uFA2D]+|[a-zA-Z0-9]+$/,  // 必须添加转义字符'/'--否则出错	            
	              regex:/^[^\|"'<>:;\?\\\\\/]*$/,//不能输入|"'<>:;?\/
	              rangelength:[0,40],
	              checkDistrictName:true           
	           },
	           districtHotkey:{
	    	      required:true,
	    	      //regex:/^[A-Za-z0-9]{1,20}$/,
	    	      regex:/^[A-Za-z]+$/,
	    	      rangelength:[0,20],
	    	      checkHotkey:true
	    	   },
	    	   districtAddress:{
	    		  rangelength:[0,100],
	    		  //regex: /^(([\u4E00-\u9FA5\uF900-\uFA2D]+|[a-zA-Z]+)|())$/
	    		},
	    		contactPhone:{
	    		  //regex:/^((\d{3,4}(\-| ))?\d{8,9}((\-| )\d{1,4})?|(0)?\d{11})$/,
	    		  rangelength:[0,20]
	    		}
		  },
		  errorPlacement:function (error,element){
				error.insertAfter(element);
		   },
		
		  // 用户自定义的键/值对消息;键为一个表单元素的name属性，值为该表单元素将要显示的消息。该消息覆盖元素的title属性或者默认消息
		  messages:{
			   districtName:{
			     required:i18n["Validation.district.name.notNull"],
			     regex:i18n["Validation.district.name.regex"],
			     rangelength:i18n["Validation.district.name.length"]   
			  },
			  districtHotkey:{
				  required:i18n["Validation.district.hotkey.notNull"] ,
				  regex:i18n["Validation.district.hotkey.regex"],
				  rangelength:i18n["Validation.district.hotkey.length"]   
			  },
			  districtAddress:{
				  regex:i18n["Validation.district.address.regex"],
				  rangelength:i18n["Validation.district.address.length"]
			  },
			  contactPhone:{
				  regex:i18n["Validation.district.phone.regex"],
				  rangelength:i18n["Validation.district.phone.length"]
			  }
		   }
		});
		$.validator.addMethod("checkHotkey",function(value,element,param){
			var districtHotkey = $("#districtHotkey").val();
			var validateUrl = $("#validateUrl").val();
			var urlStr = new $.Template(validateUrl);
			var params = {"districtId":-1,"districtHotkey":districtHotkey};
		    var flag = false;
		    $.ajax({
		    	url:urlStr.expand(params)+".json",
		    	dataType:'json',
				async: false,
			    success: function(data){
		    	   flag = data.flag;
			   	}
		   	});
		   	 return flag;
		},i18n["Validation.district.hotkey.exist"]);
		$.validator.addMethod("checkDistrictName",function(value,element,param){
			var level = $("#districtLevel").val();
			var parentCode = $("#parentCode").val();
			var districtName = value;
			var districtId = $("#rest_empty").val();
			var urlStr = new $.Template($("#checkNameUrl").val());
			var params = {"districtLevel":level,"parentCode":parentCode,"districtName":districtName,"districtId":districtId};
			var url = urlStr.expand(params);
			var flag = false;
			 $.ajax({
			    	url:url,
			    	dataType:'json',
					async: false,
				    success: function(data){
			    	   flag = data.flag;
				   	}
			   	});
			   	 return flag;
		},i18n["Validation.district.name.exist"]);
	});
	
	   // 获取门店信息
	   function getDistrict(params){
		   $("#parentCode").empty(); //清空原数据
		   var getUrl = $("#getUrl").val()+".json";
		   $.ajax({
			   url:getUrl,
			   type:"POST",
			   data:params,
			   dataType:"json",
			   timeout:5000,
			   success:function(response,ioArgs){
			       var list = response.districtList;
			       if(list!=null){
			    	   $.each(list,function(index,item){
						      // 在此处同时保存门店的id和名字,显示门店名称,但保存门店id
						   $("<option></option>").val(item.districtId).text(item.districtName).appendTo($("#parentCode"));
			    		   //$("#parentCode").append("<form:option value="+item.districtId+">"+item.districtName+"</form:option>");
					   });
			       }
		       }
		   });
	   }
	   // 根据用户选择设置门店的直接父节点编号
	   function setParentCode(){
		   var parentCode = $("#parentCode").val();
		   if(parentCode==null || parentCode==undefined){ 
			   $("#parentCode").val(0);
		   }
	   }
	   // 获取城市/门店信息
	   function showDistrict(){
		   var level = $("#districtLevel").val();
		   if(level==0){
			   $("#parentCode").hide();
		   }
		   else if(level==1){
			   $("#parentCode").show();
			   var params ={"districtLevel":level-1,"parentCode":0};
			   getDistrict(params);
		   }
		   else{
			   $("#parentCode").show();
			   var params ={"districtLevel":level-1,"parentCode":0};
			   getDistrict(params);
		   }
	   }

		// 函数,提交表单
		function submitForm(){
			if($("#newDistrict").valid()){  
				setParentCode();
				//$("#save").attr("href","#"); // 改变href的值
				var url = $("#saveUrl").val();
				//$("#newDistrict").attr("action",url);
				//$("#newDistrict").submit();
				$.post(url,$("#newDistrict").serialize(),function(data){
					if(data.error){
						$("#newDistrict").valid();
					}else{
						$.msg.confirm(i18n['Page.Dialog.title'],i18n["Entity.save.succeed"],function(){
						},{buttons:IFA.generateJson(i18n['Page.Dialog.ok'],function(){
							var indexUrl= $("#indexUrl").val();
						    window.location = indexUrl;
						})});
					}
				});
			}
		};
		// 关闭窗口
		function close(){
			// 进入查询页面URL
		      var indexUrl= $("#indexUrl").val();
		      window.location = indexUrl;
		};
});

