define(function(require) {
	var $ = require('jquery');
	require('grid')($);
	require('sort')($);
	require('validation')($);
	require('uriTemplate')($);
	require('../../../styles/cim/jquery-ui-1.8.14.custom.css');
	require('../../../styles/cim/validation.css');
	require('../../../styles/cim/cim-grid.css'); 
	var IFA = require('util');
	$(function(){
		var checkingUrl = $("#checkingUrl").val();
		$("#save").bind("click",save);
		$("#mainNewPayMethod").validate({
			rules:{
				name:{
					required:true,
					maxlength:50,
					checkExisting:true
				},
				value:{
					required:true,
					digits:true,
					checkExisting:true
				},
				descs:{
					maxlength:200
				}
			},
			messages:{
				name:{
					required:i18ns("Entity.payMethod.required"),
					maxlength:i18ns("Entity.payMethod.maxlength50")
				},
				value:{
					required:i18ns("Entity.payMethod.required"),
					digits:i18ns("Entity.payMethod.digits")
				},
				descs:{
					maxlength:i18ns("Entity.payMethod.maxlength200")
				}
			}
		});
		
		$.validator.addMethod("checkExisting",function(value,element,param){
			var data =$(element).attr("name")+"="+value+"&id=";
			var result = false;
			$.ajax({
				url:checkingUrl,
				data:data,
				type:'post',
				async:false,
				success:function(response){
					if(!response.existing){
						result= true;
					}
				}
			});
			return result;
		},i18ns("Entity.payMethod.beenUsed"));
	});
	
	function save(){
		if(!$("#mainNewPayMethod").valid())
			return;
		var creationUrl = $("#creationUrl").val();
		$.msg.confirm(i18n['Page.Dialog.title'],i18n['Page.title.CreateConfirm'],function(){},{buttons:
			IFA.generateJson(i18n['ConditionMap.ok'],function(){
				$.post(creationUrl,$("#mainNewPayMethod").serialize(),function(){
					$.msg.alert(i18n['Page.Dialog.title'],i18n['Page.title.Create.Success'],function(){},{buttons:IFA.generateJson(i18n['ConditionMap.ok'],
					function(){
						$(this).dialog('close');
						location.href=$("#indexUrl").val();
					}
					)});
				});
				$(this).dialog('close');
			},
			i18n['ConditionMap.cancel'],function(){
				$(this).dialog('close');
			}
			)});
	}
	
});