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/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();
		});
		driverNameTip();
		showDriverJobNumber();
		formValidate();
		//错误验证信息
		var orginLoginName=$("#loginName").val();
		var orginMobile=$("#mobile").val();
		var loginNameHtml = "<a href='#' id ='loginNameHtml'>"+orginLoginName+"</a>";
		var mobileHtml = "<a href='#' id='mobileHtml'>"+orginMobile+"</a>";
		unique($("#uniqueSelfUrl").val().trim(),'uniqueLoginName',i18ns("User.Role.uniqueLoginName")+loginNameHtml,"loginName");
		unique($("#uniqueSelfUrl").val().trim(),'uniqueMobile',i18ns("User.Role.uniqueMobile")+mobileHtml,"mobile");
		$("#loginNameHtml").live("click",function(){
			$("#loginName").val(orginLoginName);
			$("#userForm").validate().element("#loginName");
		});
		$("#mobileHtml").live("click",function(){
			$("#mobile").val(orginMobile);
			$("#userForm").validate().element("#mobile");
		});
	});
	//验证用户是否选择已角色
	function validRole(){
		 var roleCount=$("#selected_role option").length;
		 if(roleCount>0){
			 return true;
			 }else{
				 $.msg.alert(i18ns("Page.Dialog.title"),i18ns("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(i18ns("Page.Dialog.title"),i18ns("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(i18ns("Page.Dialog.title"),i18ns("User.Role.UnAvailable.SelectAtleastOne"));
			 }
	}
 function formSerializeFun(){
	 return $('#userForm').serialize();
 }
    initializeSearchDate();
	initializeSex();
	initializeDepartment();
	var formSerialize=formSerializeFun();
	//保存数据
function formSave(){
   if(formSerialize!=formSerializeFun()){
	if($('#userForm').valid()){
		$.msg.confirm(i18ns("Page.Dialog.title"),i18ns("User.Role.updateUser"),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(i18ns("Page.Dialog.title"),i18ns("User.Role.updateUserSuccess"),function(){
						 location.href=jumpUrl;
					 });
				}else{
					$.msg.alert(i18ns("Page.Dialog.title"),i18ns("User.Role.Available.SelectAtleastOne"));
					}
				},
				error:function(response){
				 $.msg.alert(i18ns("Page.Dialog.title"),i18ns("User.Role.systemBusy"));
				}
			});
			}
			});
		}
	 else{
		$(".error:first").parent().parent().find("input").focus();
	}
	}else{
		$.msg.alert(i18ns("User.Role.noSave"));
	}
	}
	//验证表单
	function formValidate(){
		$("#userForm").validate({
			rules:{
				loginName:{
			       required:true,
			       maxlength:30,
			       uniqueLoginName:true
		        },
				loginPassword:{
		           required:true,
		           maxlength:50
		        },
				name:{
		        	required:true,
		        	maxlength:20
		        },
				mobile:{
					required:true,
					maxlength:20,
					regex:/^[-\+]*[0-9][0-9-\+]*$/,
				    uniqueMobile:true
				},
				/*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:{
					maxlength:100
				}
		    },
			errorPlacement:function(error,element){
				var elementObj=element.parent().find("span");
				elementObj.empty();
				elementObj.html(error);
			},
			focusInvalid: false,   
		    onkeyup: false
		});
	}
	//初始化生日
	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+"'";
			var objStrs="obj.id ='"+$("#id").val().trim()+"'";
			eval(objStr+";"+objStrs);
			var flag="";
			$.ajax({
				type:"POST",
				url:url,
				async:false,
				data:obj,
				timeout:3000,
				success:function(response,ioArgs){
				  flag=response.status;
					}
			});
			return flag;
			},message);
	}
	function initializeSex(){
		$("#sexRadio").val().trim()==1?$("#sex2").attr("checked",true):$("#sex1").attr("checked",true);
		}
	function initializeDepartment(){
		$("#department").val($("#departmentHidden").val().trim());
	}

	//新增字段peopleId的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"],
						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);
					});
		}
		});
	}
	//显示与该用户关联的司机工号
	function showDriverJobNumber(){
		   var peopleId = $('#peopleId').val();
		   if(peopleId){
	            param={"peopleId":peopleId};
	            $.ajax({
	            	type:"POST",
	            	data:param,
	    			url:$("#queryDriver").val()+'.json',
	    			success:function(response){
	    				$('#peopleCName').val(response.driver.jobNumber);
	    			}
	            });
	        }
	}


});

