define(function(require){
	var $ = require('jquery');
    require('validation')($);
    require('datepickerCN')($);
    //require('uriTemplate')($);
    require('dialog')($);
    require('form')($); 
	require('../../../js/seaJsExtends/autoComplete.js')($);
	require('../../../styles/cim/autoComplete.css');
	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');
	$(function(){
		$("#saveButton").bind("click",formSave);
		$("#cancleButton").bind("click",function(){
			location.href=$("#indexUrl").val().trim();
		});
		$("#link").keyup(function(event){
			if(event.keyCode == 8 || event.keyCode == 46){
				$("#link").val('');
			}								
		});
		$("#companyForm").validate({
			rules:{
				cdpNo:{
				    required:true,
				    maxlength:20,
				    uniqueCdpNo:true
				},
				companyName:{
					required:true,
					maxlength:200
				},
				parentCdp:{
					regex:/^\d+$/
				},
				companyHotkey:{
					required:true,
				    maxlength:20,
				    uniqueHotKey:true
				},
				companyAddress:{
					required:true,
					maxlength:200
				},
				companyContact1st:{
					required:true
				},
				contact1stPhoneValid:{
					required:true,
					regex:/^(|(\d+)|(\d+\-\d+\-\d+)|(\d+\-\d+))$/
				},
				contact2ndPhoneValid:{
					regex:/^(|(\d+)|(\d+\-\d+\-\d+)|(\d+\-\d+))$/
				},
				contact3rdPhoneValid:{
					regex:/^(|(\d+)|(\d+\-\d+\-\d+)|(\d+\-\d+))$/
				},
				contact1stEmail:{
					required:true,
					email:true 
				},
				contact2ndEmail:{
					email:true 
				},
				contact3rdEmail:{
					email:true 
				},
				link:{
					fileType:true
				}},
				errorPlacement:function(error,element){
					var elementObj=element.parent().find("span");
					elementObj.empty();
					elementObj.html(error);
				},
				focusInvalid: false,   
			    onkeyup: false
			});
		$.validator.addMethod('uniqueCdpNo',function(value,element,params){
			value=value.trim();
			var obj={};
			var objStr="obj.cdpNo='"+value+"'";
			eval(objStr);
			var flag="";
			$.ajax({
				type:"POST",
				url:$("#uniqueUrl").val().trim(),
				async:false,
				data:obj,
				timeout:3000,
				success:function(response,ioArgs){
				  flag=response.status;
					}
			});
			return flag;
			},i18n['Company.Profile.CpdId.Exist2']);
		$.validator.addMethod('uniqueHotKey',function(value,element,params){
			value=value.trim();
			var obj={};
			var objStr="obj.companyHotkey='"+value+"'";
			eval(objStr);
			var flag="";
			$.ajax({
				type:"POST",
				url:$("#uniqueUrl").val().trim(),
				async:false,
				data:obj,
				timeout:3000,
				success:function(response,ioArgs){
				  flag=response.status;
					}
			});
			return flag;
			},i18n['Company.Profile.HotKey.Exist2']);
		$.validator.addMethod('fileType',function(value,element,params){
			value=value.trim();
			var fileArray=value.split(".");
			var ext=fileArray[fileArray.length-1];
			if(/gif|GIF|jpg|JPG|bmp|BMP|jpeg|JPEG|png|PNG|^$/.test(ext)){
				return true;
			}else{
				return false;
			}
		},i18n['Company.Profile.Image.Only']);
		//unique($("#uniqueUrl").val().trim(),'uniqueCdpNo',i18n['Company.Profile.CpdId.Exist2'],"cdpNo");
		//unique($("#uniqueUrl").val().trim(),'uniqueHotKey',i18n['Company.Profile.HotKey.Exist2'],"companyHotkey");
		//fileType("fileType",/gif|GIF|jpg|JPG|bmp|BMP|jpeg|JPEG|png|PNG|^$/,i18n['Company.Profile.Image.Only']);
		$('#companyForm').ajaxForm({success:function(){
			$.msg.alert(i18n['Company.Profile.Create.Success'],function(){
				location.href=$("#indexUrl").val().trim();
			});
		},
		error:function(){
			$.msg.alert(i18n['Company.Profile.Create.Failed']);
		}});
	});
	//保存数据
	function formSave(){
	if($('#companyForm').valid()){
		$.msg.confirm(i18n['Page.Dialog.title'],i18n['Page.title.CreateConfirm'],function(result){
			if(result){
				$("#companyForm").submit();
			}
		});
	}else{
		$(".error:first").parent().parent().find("input").focus();
	}
	}
	//验证表单
	function formValidate(){
		
	};
//唯一性验证
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);
}
function fileType(method,regex,message){
	$.validator.addMethod(method,function(value,element,params){
		value=value.trim();
		var fileArray=value.split(".");
		var ext=fileArray[fileArray.length-1];
		if(regex.test(ext)){
			return true;
		}else{
			return false;
		}
	},message);
}

function hotKeyCompany(){
  	$.ajax({
		type:"get",
		url:$("#companyUrl").val(),
		success:function(response){
		$("#parentCdpHotKey").autocomplete(response.company,
			      {
					caption: "&nbsp;&nbsp;"+i18n["JS.districtHotKey.caption"],
					findCaption: "&nbsp;,"+i18n["JS.districtHotKey.findCaption"],
					noFindCaption: "&nbsp;&nbsp;"+i18n["JS.companyHotKey.noFindCaption"]+":&nbsp; ",
					width: 200,
					max:10,
					scroll:true,
					scrollHeight:360,
					selectFirst:false,
					formatItem: function(row, i, max) {
			             var cpdNo="cdpNo:"+row.cdpNo+"&#13;";
			             var companyName=i18n["JS.companyHotKey.coName"]+":"+row.companyName+"&#13;";
			             var companyHotkey=i18n["JS.companyHotKey"]+":"+row.companyHotkey+"&#13;";
			             var companyAddress=i18n["JS.companyHotKey.coAddr"]+":"+row.companyAddress+"&#13;";
			             var companyContact1st=i18n["JS.companyHotKey.coContact"]+":"+row.companyContact1st+"&#13;";
			             var title=cpdNo+companyName+companyHotkey+companyAddress+companyContact1st;
			             var companyName=row.companyName+"("+row.companyHotkey+")";
						return '<span title="{2}"><span class="ac_code" >{0}</span><span class="ac_Name">{1}</span></span>'.patchContent(row.cdpNo,companyName,title);
					},
					formatMatch: function(row, i, max) {
						return "{0} {1} {2}".patchContent(row.cdpNo,row.companyHotkey,row.companyName);
					},
					formatResult: function(row) {
						return "{0}".patchContent(row.cdpNo);
					}
				}).result(function(event, data, formatted) {
				//$("#parentCdp").val(data.cdpNo);
				
				});
	}
	});
}
hotKeyCompany();

$("#companyLevel").bind("change",function(){
	var val=$(this).val();
	if(val=='child'){
		$("#parentCdpHotKey").removeAttr("disabled");
		$("#parentCdpBody").show();
		$("#parentCdpHotKeyTitle").show();
	}else{
		$("#parentCdpHotKey").attr("disabled","disabled");
		$("#parentCdpBody").hide();
		$("#parentCdpHotKeyTitle").hide();
	}
});

$(":input[name='isCredibility']").bind("click",function(){
	if(this.value=="Y"){
		$("#creditLimits").show();
		$("#orderCreditLimit").show();
	}else{
		$("#creditLimits").hide();
		$("#creditLimits").val("0.00");
		$("#orderCreditLimit").hide();
		$("#orderCreditLimit").val("0.00");
	}
});

$("#contact1stPhone_country_code,#contact1stPhone_area_code,#contact1stPhone_phone").bind('keyup',function(){
	var tel = $("#contact1stPhone_country_code").val()+'-'+$("#contact1stPhone_area_code").val()+'-'+$("#contact1stPhone_phone").val();
	 while(tel.indexOf("-")==0){
		 tel = tel.substring(1);
	 }
	 if(tel.lastIndexOf("-")==(tel.length-1)){
		 tel = tel.substring(0,tel.length-1);
	 }
	 tel = tel.replace(/\-+/g,'-');
	 if($("#contact1stPhone_phone").val().trim()==""){
		 tel+='-';
	 }
	 $("#contact1stPhoneValid").val(tel);
	 $("#contact1stPhoneValid").valid();
});	

$("#contact2ndPhone_country_code,#contact2ndPhone_area_code,#contact2ndPhone_phone").bind('keyup',function(){
	var tel = $("#contact2ndPhone_country_code").val()+'-'+$("#contact2ndPhone_area_code").val()+'-'+$("#contact2ndPhone_phone").val();
	 while(tel.indexOf("-")==0){
		 tel = tel.substring(1);
	 }
	 if(tel.lastIndexOf("-")==(tel.length-1)){
		 tel = tel.substring(0,tel.length-1);
	 }
	 tel = tel.replace(/\-+/g,'-');
	 if($("#contact2ndPhone_phone").val().trim()==""){
		 tel+='-';
	 }
	 $("#contact2ndPhoneValid").val(tel);
	 $("#contact2ndPhoneValid").valid();
});	

$("#contact3rdPhone_country_code,#contact3rdPhone_area_code,#contact3rdPhone_phone").bind('keyup',function(){
	var tel = $("#contact3rdPhone_country_code").val()+'-'+$("#contact3rdPhone_area_code").val()+'-'+$("#contact3rdPhone_phone").val();
	 while(tel.indexOf("-")==0){
		 tel = tel.substring(1);
	 }
	 if(tel.lastIndexOf("-")==(tel.length-1)){
		 tel = tel.substring(0,tel.length-1);
	 }
	 tel = tel.replace(/\-+/g,'-');
	 if($("#contact3rdPhone_phone").val().trim()==""){
		 tel+='-';
	 }
	 $("#contact3rdPhoneValid").val(tel);
	 $("#contact3rdPhoneValid").valid();
});	

});

