$package('itsm.tools');

/**
 * @Copyright email
 * @version 1.0
 * @author Tan
 * for tools/email.jsp
 */

$import('itsm.request.requestEmailHistory');
$import("itsm.config.categoryManage.eventCategoryTree");
$import("itsm.security.userUtil");
$import("itsm.cm.configureItemUtil");
$import("itsm.config.dataDictionary.dataDictionaryUtil");


itsm.tools.email=function() 
{
	
	

	this.replyState = false;	// 弹出窗口的状态. true为回复窗口，false为新邮件窗口
	
	return {
		
		
		contentFormatter:function(cellvalue,options){	 		
			//正则表达式
			var reg = new RegExp( '<[^>]+>' , 'g' );
			//字符串中所有的html标签替换成空
			var tstr = cellvalue.replace(reg, '');	   		
		    
			return tstr;
		},
		
		
		contentUnFormatter:function ( cellvalue, options){
			
		   return cellvalue;
		},

		/**
		 * 邮箱后缀格式化.
		 */
		sinaFrm:function(cellvalue, options){
			var cellvalue1=cellvalue.replace('.sina','')
			return cellvalue;
		},
		
		/**
		 * @description 类型格式化.
		 */
		folderNameFormat:function(cellvalue, options){
			if(cellvalue=="INBOX"){
				return i18n['common_receive'];
			}
				
			else{
				return i18n['common_sent'];
			}
				
		},
		 /**
         * @description 标题格式化
         */
        emailGridTitleFormatter: function (cell, opt, data) {
            return "<a href=javascript:itsm.request.requestEmailHistory.showEmailDetail('" + data.emailMessageId + "')>" + cell + "</a>";
        },
		
        /**
         * @description 标题格式化
         */
        isToRequestFormatter: function (cell, opt, data) {
        	if(cell)
        		return "<span style='color:red'>"+i18n['label_basicConfig_deafultCurrencyYes']+"</span>"
        	else
        		return i18n['label_basicConfig_deafultCurrencyNo']
           
        },
        
        /**
         * @description 发件人格式化
         */
        FromUserFormatter:function(cellvalue,options){
        	var newCellValue=(cellvalue.replace('<',' ')).replace('>',' ');
        	return newCellValue;
        },
        
        
        /**
         * @description 收件人格式化
         */
        ToUserFormatter:function(cellvalue,options){
        	var newCellValue=(cellvalue.replace('<',' ')).replace('>',' ');
        	return newCellValue;
        },
        
        /**
         * @description 回复发件人格式化
         */
        FromUserByReplyFormatter:function(cellvalue){
        	var newCellValue=cellvalue.substring(cellvalue.lastIndexOf("(")+1,cellvalue.lastIndexOf(")"));
        	return newCellValue;
        },
        
		/**
		 * 加载邮件列表.
		 */
		showEmailGrid:function(){
			
			var params = $.extend({},jqGridParams, {
				url:'email!findEmail.action',
				caption:i18n['caption_emailGrid'],
				colNames:[i18n['number'],i18n['title_mailTitle'],'','',i18n['title_mailType'],i18n['title_mailFromUser'],i18n['title_mailToUser'],i18n['title_sendTime'],i18n['title_receviceTime'],i18n['isToRequest'],''],
				colModel:[
			   		{name:'emailMessageId',width:60,sortable:true},
			   		{name:'subject',width:150,formatter:this.emailGridTitleFormatter},
			   		{name:'subject',width:150,hidden:true},
			   		{name:'content',width:150,hidden:true,formatter:this.contentFormatter},
			   		{name:'folderName',width:100,formatter:this.folderNameFormat},
			   		{name:'fromUser',width:200,formatter:this.FromUserFormatter},
			   		{name:'toUser',width:200,formatter:this.ToUserFormatter},
			   		{name:'sendDate',width:180,formatter:timeFormatter},
			   		{name:'receiveDate',width:180,formatter:timeFormatter},
			   		{name:'toRequest',width:120,formatter:this.isToRequestFormatter},
			   		{name:'toRequest',hidden:true}
			   	],
				toolbar: [true,"top"],	
				jsonReader: $.extend(jqGridJsonReader, {id: "emailMessageId"}),
				sortname:'emailMessageId',
				ondblClickRow:function(rowId){itsm.request.requestEmailHistory.showEmailDetail(rowId)},
				pager:'#emailPager'
			});
			$("#emailGrid").jqGrid(params);
			$("#emailGrid").navGrid('#emailPager',navGridParams);
			//列表操作项
			$("#t_emailGrid").css(jqGridTopStyles);
			$("#t_emailGrid").append($('#emailGridToolbar').html());
			//自适应大小
			setGridWidth("#emailGrid","regCenter",10);
			
		},
		
		
		/**
		 * 清理值.
		 */
		clearElement:function(){
				$('#addEmail [name="emailDto.to"]').val("");
				$('#addEmail [name="emailDto.subject"]').val("");
				$('#addEmail [name="emailDto.remarks"]').val("");
				$('#addEmail [name="emailDto.description"]').val("");
				$('#addEmail [name="affachment"]').val("");
				$('#addEmail [name="emailDto.affachmentPath"]').val("");
		},
		
		/**
		 * 引用原文.
		 */
		appendOldSubject:function(){
			var tb = $('#addEmail > form > table');
			$('<tr class="temp"><td colspan="2"><div id = "separatorLine" style="border-bottom:#CCC 1px dashed; margin-top:10px; margin-bottom:10px"></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td>'+i18n['title_sendTime']+'</td><td><div id="oldSentDate"  style="width:100%" ></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td>'+i18n['details']+'</td><td><div id="oldContents" style="width:100%"></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td>'+i18n['title']+'</td><td><div id="oldSubject"></div></td></tr>').prependTo(tb);
			$('<tr class="temp"><td width="100px">发件箱</td><td><div id="oldFrom"></div></td></tr>').prependTo(tb);
			replyState = true;
		},
		
		removeOldSubject:function(){
			$('.temp').remove();
			replyState = false;
		},
		
		/**
		 * 创建邮件.
		 */
		toolbar_addEmail:function(){
			
			itsm.tools.email.clearElement();
			if (replyState){
				itsm.tools.email.removeOldSubject();
			}
			//attr拿到ID为"#addEmail"的title属性。并赋值
			$("#addEmail").attr("title","发送邮件");
			itsm.tools.email.add_email_openwindow();
		},
		
		
		/**
		 * 回复邮件.
		 */
		toolbar_replyEmail:function(){
			checkBeforeEditGrid("#emailGrid",itsm.tools.email.toolbar_replyEmailMethod);
		},
		toolbar_replyEmailMethod:function(rowData){
			
			if(!replyState){
				itsm.tools.email.appendOldSubject();
			}
			$("#addEmail").attr("title",i18n["label_replay"]);
			$("#oldFrom").text(itsm.tools.email.FromUserByReplyFormatter(rowData.fromUser));
			$("#oldSubject").text(rowData.subject);
			$("#oldContents").html(rowData.content);
			$("#oldSentDate").text(rowData.sendDate);
			$("#to").val(itsm.tools.email.FromUserByReplyFormatter(rowData.fromUser));
			$("#subject").val(i18n["label_im_reply"]+":"+rowData.subject);
			$("#emailContent").val("");
			itsm.tools.email.add_email_openwindow();
			
		},
		
		/**
		 * 打开新增邮件窗口.
		 */
		add_email_openwindow:function(){
			lazyInitEditor('#emailContent');
			$('#addEmail').window('open');
		},
		
		/**
		 * 关闭新增邮件窗口.
		 */
		add_closewindow:function(){
				$('#addEmail').window('close');
		},
		
		/**
		 * add Eamil
		 */
		add_email:function(){
			
			var _param = $('#addEmail form').serialize();
			_param = _param + '&emailDto.affachment='+ $("#affachment").val();
			startProcess();
			var _url='email!toEmail.action';
			$.post(_url,_param,function(result){
				endProcess();
				if(result){
					$('#addEmail').window('close');
					resetForm("#addEmailForm");
					msgShow(i18n['msg_sendSuccessful'],'show');
				}else{
					msgShow(i18n['sendFailure'],'show');
				}
					
			});
			
			
		},
		
		/**
		 * 选择请求者.
		 */
		selectRequestCreator:function(){
			itsm.security.userUtil.selectUser('#email_selectCreator','#email_addRequestUserId','','loginName');
		},
		
		
		emailToRequest_aff:function(){
			checkBeforeEditGrid('#emailGrid',itsm.tools.email.emailToRequest);
		},
		
		/**
		 * 转成可编辑请求
		 */
		emailToRequest:function(rowData){

			if(rowData.toRequest=='true'){
				$.messager.alert(i18n['msg_msg'],'<br/>'+i18n['alreadyToRequestSuccess'],'error');
			}else{
				//加载数据字典
				itsm.config.dataDictionary.dataDictionaryUtil.loadOptionsByCode('effectRange','#email_request_effectRange');
				itsm.config.dataDictionary.dataDictionaryUtil.loadOptionsByCode('seriousness','#email_request_seriousness');
				itsm.config.dataDictionary.dataDictionaryUtil.loadOptionsByCode('imode','#email_request_imode');
				itsm.config.dataDictionary.dataDictionaryUtil.loadOptionsByCode('level','#email_request_level');
				itsm.config.dataDictionary.dataDictionaryUtil.loadOptionsByCode('priority','#email_request_priority');
				
				$('#logCall_win').window('open');
				
				$("#email_emailMessageId").val(rowData.emailMessageId);
				
				$('#email_request_etitle').val(rowData.subject);
				
				$('#email_request_edesc').val(itsm.tools.email.contentFormatter(rowData.content));

			}
			
		},
		
		emailToRequest_opt:function(){
			if($('#mailTrqForm').form('validate')){
				startProcess();
				$('#link_addcall_ok').attr('disabled','true');
				var frm = $('#logCall_win form').serialize();
				var url = 'request!saveRequest.action';
				$.post(url,frm, function()
				{
					endProcess();
					$('#link_addcall_ok').removeAttr('disabled');	
					$('#logCall_win').window('close');
					$('#email_request_etitle').val('');
					$('#email_request_edesc').val('');
					$('#email_selectCreator').val('');
					$('#mailToRequestCategoryName').val('');
					$('#emailGrid').trigger('reloadGrid');
					msgShow(i18n['msg_addRequestSuccessful'],'show');	
					
				});
			}
		},


		/**
		 * @description 打开搜索窗口
		 */
		openEmailMessageSearchWin:function(){
			$('#emailMessageSearch_win').window('open');
		},
		emailMessageSearch:function(){
			var _url = 'email!findEmail.action';	
			var sdata = $('#emailMessageSearch_win form').getForm();
			var postData = $("#emailGrid").jqGrid("getGridParam", "postData");     
			$.extend(postData, sdata);
			$('#emailGrid').jqGrid('setGridParam',{page:1,url:_url}).trigger('reloadGrid');
		},
		/**
		 * @description 判断是否选择要删除的邮件
		 */
		deleteEmailMessage_aff:function(){
			checkBeforeDeleteGrid('#emailGrid', this.deleteEmailMessageOpt);
		},
		/**
		 * @description 删除邮件操作
		 */
		deleteEmailMessageOpt:function(rowsId){
			var url="email!deleteEmailMessage.action";
			var param = $.param({'ids':rowsId},true);
			$.post(url, param, function()
			{
				$('#emailGrid').trigger('reloadGrid');
				msgShow(i18n['msg_deleteSuccessful'],'show');
				
			});	
		},
		/**
		 * @description 邮件扫描
		 * @author mars
		 */
		scanEmailServer:function(){
			startProcess();
			$.post('email!scanEmailMessagesByUser.action',"",function(result){
				endProcess();
				if(result){
					$('#emailGrid').trigger('reloadGrid');
					msgShow(i18n['msg_company_scansucess'],'show');
				}
				else{
					msgShow(i18n['ERROR_SCANEMAILMESSAGE'],'show');
				}
			})
			
		},
		
		
		//载入
		init:function(){
		  	//加载发送邮件配置信息
			//itsm.tools.email.getSendEmailConfigure();
			itsm.tools.email.showEmailGrid();
			$('#email_selectCIName').click(function(){
				itsm.cm.configureItemUtil.selectCIS('#email_selectCIName','#email_addRequestCIId');
			});	
			
			$('#mailToRequestCategoryName').click(function(){
				itsm.config.categoryManage.eventCategoryTree.showSelectTree('#email_to_request_select_category_panel','#email_to_request_select_category_tree','request','#mailToRequestCategoryName','#mailToRequestCategoryNo');
			});
			
			
		}
		
	};
	
	
}();

$(document).ready(itsm.tools.email.init);
