define(function(require){
	var $ = require('jquery');
    require('uriTemplate')($);
    require('dialog')($);
    require('form')($); 
    require('multiFile')($);
	var IFA = require('util');  
	require("../../../../styles/cim/jquery-ui-1.8.14.custom.css");
	require('../../../../styles/cim/validation.css');
	var ckData="";
	 $(function(){
		 ckData = CKEDITOR.replace('emailContent',{skin:'v2',language:'zh-cn'});
		 $('#mailForm').validate({
			 rules:{
				 emailTemplateId:{
					 mustchoose:true
				 },
				 sendToAddress:{
					 required:true	 
				 },
				 ccToAddress:{
					 emailCheck:true
				 },
				 subject:{
					 maxlength:200
				 },
				 content:{
					 contentCheck:true
				 }
			 },
			 messages:{
				 sendToAddress:{
					 required:i18n["Validation.sendreceiver.required"]
				 }
			 },
			  errorPlacement:function (error,element){
				  if(element.attr("name")=="sendToAddress"){
					  error.insertAfter("#sendToList");
				  }else{
					  error.insertAfter(element);
				  }
			   }
		 }); 
		 $('#smsForm').validate({
			 rules:{
				 smsTemplateId:{
					 mustchooseSmsTemplate:true
				 },
				 smsSendMobilephone:{
					 required:true	 
				 },
				 smsSendContent:{
					 maxlength:1000
				 }
			 },
			 messages:{
				 smsSendMobilephone:{
					 required:i18n["Validation.sendreceiver.required"]
				 }
			 },
			  errorPlacement:function (error,element){
				  if(element.attr("name")=="smsSendMobilephone"){
					  error.insertAfter("#smsSendToList");
				  }else{
					  error.insertAfter(element);
				  }
			   }
		 }); 
		 
			$.validator.addMethod("mustchoose",function(value,element,param){
				if($("#emailTemplateId").val()!=0){
					return true;
				}else{
				    return false;	
				}
			},i18n["Entity.send.plzchomailtemplate"]);
			
			$.validator.addMethod("mustchooseSmsTemplate",function(value,element,param){
				if($("#smsTemplateId").val()!=0){
					return true;
				}else{
				    return false;	
				}
			},i18n["Entity.send.plzchosmstemplate"]);
			
			$.validator.addMethod("contentCheck",function(value,element,param){
				var contentCk = ckData.getData();
				if(contentCk.length>2010){
					return false;
				}else{
				    return true;	
				}
			},i18n["Validation.template.contentmaxlenth1000"]);
			
			$.validator.addMethod("emailCheck",function(value,element,param){
				var emailAddressString = $("#cc").val();
				if(emailAddressString.trim()==""){
					return true;
				}else{					
					var flag = chkEmail(emailAddressString);
					if(flag){
						return true;
					}else{
						return false;
					}
				}
			},i18ns("Entity.mailsend.ccIncorrect"));
	 });

		$("#emailTemplateId").change(function(){
			if( $("#emailTemplateId").val()!=0){
				var templateId = $("#emailTemplateId option:selected").val();
				var resId = $('#emailResId').val();
				var urlStrtemp = $('#mailTemplateShowUrl').val();
				var urlStrTmp = new $.Template(urlStrtemp);
				var urlParam = {"templateId":templateId,"resId":resId};
				var urlStr = urlStrTmp.expand(urlParam);
				$("#subject").val($("#emailTemplateId option:selected").text());
				 $.ajax({
						url:urlStr+".json",
						type:'POST',
						async: false,
						success :function(data) {
							CKEDITOR.instances.emailContent.setData(data.content);
						}
				});		
			}
		});
		$('[name=sendToAddress]:checkbox').click(function(){
			var strn="";
			var str="";
			$('[name=sendToAddress]:[checked]').each(function(){
				str=$(this).val();
				if(strn==""){
					strn+=str;
				}else{
				strn=strn+";"+str;
				}
				//$('#re').html(strn);
				$('#re').val(strn);
			});
		});
		
		$('[name=smsSendMobilephone]:checkbox').click(function(){
			var strn="";
			var str="";
			$('[name=smsSendMobilephone]:[checked]').each(function(){
				str=$(this).val();
				if(strn==""){
					strn+=str;
				}else{
				strn=strn+";"+str;
				}
				$('#smsre').val(strn);
			});
		});
		
		 $('#previewHref').click(function(){
			 var url = $('#previewUrl').val();
			 var sendToAddress = $('#re').text();
			 var ccToAddress = $('#cc').val();
			 var subject = $('#subject').val();
			 var content = ckData.getData();
			 var attachment =$(".MultiFile-title").text();

			 var data = {"sendToAddress":sendToAddress,"ccToAddress":ccToAddress,"subject":subject,"content":content,"attachmentName":attachment};
			 window.showModalDialog(url,data,"dialogWidth=800px;dialogHeight=900px");
		 });
			$('#smsTemplateId').change(function(){
				if( $("#smsTemplateId").val()!=0){
					var templateId = $("#smsTemplateId option:selected").val();
					var resId = $('#smsResId').val();
					var smUrl = $('#smsTemplateShowUrl').val();
					var urlStrTmp = new $.Template(smUrl);
					var urlParam = {"templateId":templateId,"resId":resId};
					var urlStr = urlStrTmp.expand(urlParam);
					//console.log(urlStr);
					 $.ajax({
							url:urlStr+".json",
							type:'POST',
							async: false,
							success :function(data) {
								$("#smsContent").val(data.content);
//								$("#smsContent").html(data.content);
							}
					});		
				}
			});
			$('#sendSMS').click(function(){
				if($('#smsForm').valid()){	
					var mobileList = parse($('#smsre').val());
					var smsto = regMobilePhone(mobileList);
					var smsContent = $('#smsContent').val();
					var rentalNo = $('#smsRentalNo').text();
					var url= $('#smsSendUrl').val();
					var smsResId=$('#smsResId').val();
					$.ajax({
						url:url+".json",
						type:'post',
						data:{smsSendMobilephone:smsto,smsSendContent:smsContent,rentalNo:rentalNo,smsResId:smsResId},
						success:function(response,ioArgs){
							if(response.responseSuccess){      			
								$.msg.alert(i18n["Validation.send.successfully"]);
								$("#sendSmsTips").text(i18ns("Entity.mailsend.sendSmsSuc"));
							}
						}
					});
				}else{
					$.msg.alert(i18n["Page.Dialog.content.inputError"]);
				}
		        return false;
			});
			
			//去除手机好前面的0，国内手机号加86
			function regMobilePhone(mobilelist){
				var result="";
				var pattern = new RegExp(/^1[0-9]{10}$/);
				var mobileStr = mobilelist.split(";");
				for(var i=0; i<mobileStr.length;i++){
					var mobile = mobileStr[i].trim();
					if(pattern.test(mobile)){
						mobile = "86"+mobile;
					}
					mobile = mobile.replace(/\b(0+)/gi,"");
					if(mobile!=""){						
						result += mobile;
						result += ";";
					}
				}
				return result.substring(0,result.length-1);
			}
			
			//把字符组中的手机号解析出来
			function parse(data){
				var result="";
				var mobile="";
				var dataArray = data.split(";");
				for(var i=0; i<dataArray.length;i++){
					var mobileStr = dataArray[i].trim();
					if(mobileStr.indexOf("<")>0&&mobileStr.indexOf(">")>0){
						mobile = mobileStr.substring(mobileStr.indexOf("<")+1,mobileStr.indexOf(">"));						
					}else{
						mobile = mobileStr;
					}
					if(mobile!=""){						
						result += mobile;
						result += ";";
					}
				}
				return result.substring(0,result.length-1);
			}
			
	$('#mailForm').ajaxForm({success:function(){
		$.msg.alert(i18n["Validation.send.successfully"]);
		$("#sendEmailTips").text(i18n["tips.mailsend.successfully"]);
	}});
	$('#SentEmail').click(function(){
		if($('#mailForm').valid()){
			chosePDFAndSend();
		}else{
			$.msg.alert(i18n["Page.Dialog.content.inputError"]);
		}
	});
	 $('#emailAttachment').MultiFile({
		 max: 7,
		 list:'#emailAttachment_list',
		 STRING: {
				remove:i18n['Entity.Operation.delete'],
				denied:'You cannot select a $ext file.\nTry again...',
				file:'$file',
				selected:'File selected: $file',
				duplicate:'$file'+i18n["Validation.send.hadchoose"]
			}
	 });
		function chosePDFAndSend(){
			var div = $('#template');
	  		$.msg.alert(i18n["Validation.send.plzchoosePdf"],div,{
  			    buttons:
  			    	IFA.generateJson(i18n["Entity.Operation.ok"],function(){
  		            	$(this).dialog("close");
  		            	url=$('#mailsentUrl').val();
  		            	$('#mailForm').attr("action",url);
  		            	chooseCheck();
  		            	$('#mailForm').submit();
                      }
  		        ),
  		        width:350,height:220
  			});
		}
		function chooseCheck(){
			$("#pdfType").val($(":radio[name='pdfTypes']:checked").val());
		}
		function excelChooseCheck(){
			$("#excelType").val($(":radio[name='excelTypes']:checked").val());
		}
		$('#exportBtn').click(function(){
			chooseTypeForExcel();
		});
		
		function chooseTypeForExcel(){
			var div = $('#excelTemplate');
	  		$.msg.alert(i18n["Validation.send.plzchoose"],div,{
  			    buttons:
  			    	IFA.generateJson(i18n["Entity.Operation.ok"],function(){
  		            	$(this).dialog("close");
  		            	url=$('#exportUrl').val();
  		            	$('#exportForm').attr("action",url);
  		            	excelChooseCheck();
  		            	$('#exportForm').submit();
                      }
  		        ),
  		        width:350,height:210
  			});
		}
		$("#cc").bind("keydown",function(e){
			var e = e ? e : window.event;
			if (e.keyCode==32)   
	          {   
				var str =$(this).val();
				if(str.indexOf(";")<0){					
					if(str.indexOf("@")>0){					
						str = str+";";
						$(this).val(str);
						//str = str.substring(str.lastIndexOf(";"));
					}else{
						$(this).val("");
					}
	          }else{
	        	  var i = str.lastIndexOf(";");
	        	  var str1 = str.substring(str.lastIndexOf(";")).trim();
	        	  if(str1.indexOf("@")>0){					
						str1 = str1+";";
						$(this).val(str.substring(0,i)+str1);
						//str = str.substring(str.lastIndexOf(";"));
					}
	          }
				}
		});

		function chkEmail(str){
			var checkflag = true;
			var emailAdds = str.split(";");
			//console.log(emailAdds);
			var i = 0;
			for(i=0;i<emailAdds.length;i++){
				var email = emailAdds[i].trim();	
				//console.log(email);
			    //var pattern=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
			    var pattern=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
			    var flag = pattern.test(email);
			   // alert(flag);
			    if(!flag){
			    	checkflag = false;
			    }
			    }
			return checkflag;
			}
		
});