define(function(require){
	var $ = require('jquery');
    require('validation')($);
    require('datepickerCN')($);
    require('dialog')($);
	var IFA = require('util');
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../styles/cim/cim-grid.css');   
	require('../../../styles/cim/validation.css');
	require('../../../styles/cim/autoComplete.css');
	require('../../../js/seaJsExtends/autoComplete.js')($);	
	$(function(){
		$("#rightButton").bind("click",addSelected);
		$("#leftButton").bind("click",deleteSelected);
		$("#to_select_role").bind("dblclick",addSelected);
		$("#selected_role").bind("dblclick",deleteSelected);
		$("#saveButton").bind("click",formSave);
		$("#cancleButton").bind("click",function(){
			location.href=$("#indexUrl").val().trim();
		});
		initializeSearchDate();
		formValidate();
		unique($("#uniqueUrl").val().trim(),'uniqueLoginName',i18n['Error.LoginName.Exist'],"loginName");
		unique($("#uniqueUrl").val().trim(),'uniqueMobile',i18n['Error.Phone.Exist'],"mobile");
		driverNameTip();
	});
	//验证用户是否选择已角色
	function validRole(){
		 var roleCount=$("#selected_role option").length;
		 if(roleCount>0){
			 return true;
			 }else{
				 $.msg.alert(i18n['Page.Dialog.title'],i18n['User.Role.SelectAtleastOne']);
				 return false;
				 }
	}
	function addSelected() {
		if ($("#to_select_role option:selected").length>0){
			var roles = $("#to_select_role option:selected");
			$.each(roles,function(){
				role = this;
					//从左则框选到右则框
		        $("#selected_role").append("<option value='"+role.value+"' selected>"+role.text+"</option>");		
		       });
		    //将选中的选项删除
			$("#to_select_role option:selected").remove();
		}
		else{
			 $.msg.alert(i18n['Page.Dialog.title'],i18n['User.Role.Available.SelectAtleastOne']);
			 }
	}
	function deleteSelected() {
		if ($("#selected_role option:selected").length>0){
		var roles = $("#selected_role option:selected");
		$.each(roles,function(){
			role = this;
				//从右则框选到左则框	
			$("#to_select_role").append("<option value='"+role.value+"' >"+role.text+"</option>");
	       });
	    //将选中的选项删除
		$("#selected_role option:selected").remove();
		}
		else{
			 $.msg.alert(i18n['Page.Dialog.title'],i18n['User.Role.UnAvailable.SelectAtleastOne']);
			 }
	}
	//保存数据
	function formSave(){
	if($('#userForm').valid()){
		$.msg.confirm(i18n['Page.Dialog.title'],i18n['Page.title.CreateConfirm'],function(result){
			if(result){
			var url=$("#saveFormUrl").val().trim();
			var jumpUrl=$("#indexUrl").val().trim();
			$.ajax({
				type:"post",
				url:url,
				dataType:"json",
				data:$("#userForm").serialize(),
				success:function(response){
				if(response.status){
					 $.msg.alert(i18n['Page.Dialog.title'],i18n['Page.title.Create.Success'],function(){
						 location.href=jumpUrl;
					 });
				}else{
					$.msg.alert(i18n['Page.Dialog.title'],i18n['User.Role.Available.SelectAtleastOne']);
					}
				},
				error:function(response){
				 $.msg.alert(i18n['Page.Dialog.title'],i18n['System.Error']);
				}
			});
			}
			});
		}
	 else{
		$(".error:first").parent().parent().find("input").focus();
	}
	}
	//验证表单
	function formValidate(){
		$("#userForm").validate({
			rules:{
				loginName:{
			       required:true,
			       maxlength:30,
			       uniqueLoginName:true
		        },
				loginPassword:{
		           required:true,
		           maxlength:50,
		           passwordCheck:true
		        },
				name:{
		        	required:true,
		        	maxlength:20
		        },
				mobile:{
					required:true,
					maxlength:20,
					regex:/^[-\+]*[0-9][0-9-\+]*$/,
				},
				/*department:{
					required:true
				},*/
				selectedRoles:{
					required:true
				},
				email:{
					maxlength:50,
					email:true 
				},
				phone:{
					maxlength:20,
					regex:/^\d|-$|^$/
				},
				ext:{
					maxlength:10,
					regex:/^\d|-$|^$/
				},
				education:{
					maxlength:20
				},
				workLimit:{
					digits:true 
				},
				address:{
					maxlength:50
				},
				origin:{
					maxlength:20
				},
				area:{
					maxlength:20
				},
				zipCode:{
					maxlength:10,
					regex:/^\d|^$/
				},
				remark:{
					checkLength:true
				}
		    },
			errorPlacement:function(error,element){
				var elementObj=element.parent().find("span");
				elementObj.empty();
				elementObj.html(error);
			},
		    onkeyup: false
		});
		$.validator.addMethod("checkLength",function(value,element,error){
			if(value.length>100){
				return false;
			}
			return true;
		
		},i18n['User.New.Tips1']);
	}
	//初始化生日
	function initializeSearchDate(){
		$("#birthday").datepicker({readOnly:false}).val();
		$("#outDate").datepicker({readOnly:false}).val();
          }
	//唯一性验证
	function unique(url,method,message,dataParam){
		$.validator.addMethod(method,function(value,element,params){
			value=value.trim();
			var obj={};
			var objStr="obj."+dataParam+"='"+value+"'";
			eval(objStr);
			var flag="";
			$.ajax({
				type:"POST",
				url:url,
				async:false,
				data:obj,
				timeout:3000,
				success:function(response,ioArgs){
				  flag=response.status;
					}
			});
			return flag;
			},message);
	}
	//验证信息
	var message="";
	//密码强度验证
		$.validator.addMethod("passwordCheck",function(value,element,params){
			var status=false;
			value=value.trim();
			$.ajax({
				type:"POST",
				url:$("#checkPswUrl").val(),
				async:false,
				data:{"psw":value},
				timeout:3000,
				success:function(response,ioArgs){
					  if(!response.lengthLess){
						  message=i18n['System.Password.LengthIncorrect1'];
					  }else if(!response.lengthMore){
						  message=i18n['System.Password.LengthIncorrect2'];
					  }else if(!response.lowCase){
						  message=i18n['System.Password.LengthIncorrect3'];
					  }else if(!response.upperCase){
						  message=i18n['System.Password.LengthIncorrect4'];
					  }else if(!response.speChar){
						  message=i18n['System.Password.LengthIncorrect5'];
					  }else if(!response.numberic){
						  message=i18n['System.Password.LengthIncorrect6'];
					  }
					 status=(response.lengthMore)&&(response.lengthLess)&&(response.lowCase)&&(response.upperCase)&&(response.speChar)&&(response.numberic);
					}
			});
			return status;
			},function(){return message;});
		
		//新增people_id字段autocomplete	
		function driverNameTip(){
			$.ajax({
				type:"GET",
				url:$("#queryAllDriver").val(),
				success:function(response){
				var acdata=response.driverList;
				$("#peopleCName").autocomplete(acdata,
					      {
							caption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.PIcaption"],
//							findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
							noFindCaption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.noFindPICaption"]+":&nbsp; ",
							width: 200,
							max: 5,
							formatItem: function(row, i, max) {
								return '<span class="ac_code">{0}</span><span class="ac_Name">{1}</span>'.patchContent(row.jobNumber, row.cnName);
							},
							formatMatch: function(row, i, max) {
								return "{0} {1}".patchContent(row.jobNumber, row.cnName);
							},
							formatResult: function(row) {
								return "{0}".patchContent(row.cnName);
							}
						}).result(function(event, data, formatted) {
							$("#peopleId").val(data.peopleId);
						});
			}
			});
		}

});

