define(function(require){
	var $ = require('jquery');
	require('uriTemplate')($);
	require('validation')($);
	require('dialog')($);
	var IFA = require('util');
	require("../../../styles/cim/jquery-ui-1.8.14.custom.css"); 
	var oldName = $("#name").val().trim();
	$(document).ready(function(){
		$('#edit').bind('click',editRole);
		$('#index').bind('click',indexRole);
		$("#resultForm").validate({
			rules: {
			name:{
			regex:/^[A-Z0-9\_]{1,20}$/,
			checkName:true
				},
			alias:{
			required:true,
			rangelength:[1,20]
				},
			remark:{
			rangelength:[0,200]
				}	   
		    }
		});
		$.validator.addMethod("checkName", function(value,element,param) {
			var name=value.trim();
		    var flag = true;
		    if(oldName!=name){
		    var hiddenUrl = $('#checkNameUrl').val();
		    var urlStr = new $.Template(hiddenUrl);
		  	var urlParam = {"name":name};
		  	var url = urlStr.expand(urlParam);
		  	$.ajax({
	   			  url: url+".json",
	    		  addidvalue:false,
	    		  async: false,
				  dataType:"json",
				  success:function(response){
					if(response.flag == true){
						flag=false;
					}
				  }
				  });
		    }
	    		return flag;
		}, i18n['System.Role.Code.InUse']);
	});
	function editRole(){
		if($("#resultForm").valid()){
		   var array = tree.getCheckedNodes();
		   var ids = array.join(",");
		   if(ids!=""){
			   if(ids==0){
				   $.msg.alert(i18n['Page.Dialog.title'],i18n['System.Role.Code.ChooseValid']);
				   }
			  else{ 
				  ids=ids.substring(2);
				  $("#nodeIds").val(ids);
		      var url = $('#updateUrl').val();
		      if($("#resultForm").valid()){
		    	  $.ajax( {
			      type:"post",
			      url : url+".json",
			      dataType : "json",
			      data:$("#resultForm").serialize(),
			      success:function(response) {
		    		  $.msg.alert(i18n['Page.Dialog.title'],i18n['Entity.Operation.Save.Success'],indexRole);
			      },
			      error : function() {
			    	  $.msg.alert(i18n['Page.Dialog.title'],i18n['System.Error'],indexRole);
			      }
		      });
		      }}
		   }else{
			   $.msg.alert(i18n['Page.Dialog.title'],i18n['System.Role.Code.ChooseValid']);
			   }
		}
	}
	function indexRole(){
		var indexUrl = $('#indexUrl').val();
		location.replace(indexUrl);
	}

});
