$.fn.scrollTo = function( target, options, callback ) {
    if(typeof options == 'function' && arguments.length == 2) { callback = options; options = target; }
    var settings = $.extend({
                            scrollTarget  : target,
                            offsetTop     : 0,
                            duration      : 300,
                            easing        : 'swing'
                            }, options);
    return this.each(function(){
                     var scrollPane = $(this);
                     var scrollTarget = (typeof settings.scrollTarget == "number") ? settings.scrollTarget : $(settings.scrollTarget);
                     var scrollY = (typeof scrollTarget == "number") ? scrollTarget : scrollTarget.offset().top;
					 scrollY = scrollY - parseInt(settings.offsetTop);
					 scrollPane.animate({scrollTop : scrollY }, parseInt(settings.duration), settings.easing, function(){
                                        if (typeof callback == 'function') { callback.call(this); }
                                        });
                     });
};

var lastScrollbar = null;
var selectedEmails = [];//选中的联系人{name: xx, email: xxx}对象合集
var selectedAttachments = [];//选中的附件{mailid: xx, itemIndex: xx, attachFileName: xx}对象合集

var g_loadFrameTime = 0;
var g_iframeOnLoadStartTime = 0;
//常量
//var localized_show_quote = "显示引用↓";
//var localized_hide_quote = "隐藏引用↑";
var vertscrollbar_id = 'foxwb_vertscrollbar_id';

var autoResizeDelay = 500;
var g_autoResizeTimer = 0;
function startAutoResize(){
	if (g_autoResizeTimer == 0){
		g_autoResizeTimer = setInterval(autoResize, autoResizeDelay);
	}
}
function endAutoResize(){
	if (g_autoResizeTimer){
		clearInterval(g_autoResizeTimer);
		g_autoResizeTimer = 0;
	}
}
function autoResize(){
	adjustExpandMailContentSize(true);
}

function updateMailFrameLanguage(){
	try{
		$('.desc_phone').text(csPhone);
		$('.desc_mobile').text(csMobile);
		$('.desc_dept').text(csDept);
		$('.desc_compose_mail').text(csComposeMail);
		$('.desc_related_mail').text(csRelatedMail);
		$('.desc_add_to_addressbook').text(csAddToAddressBook);
	}catch(e){
		WriteLog('updateMailFrameLanguage', e.message);
	}
}
function updateMailEntryLanguage(mailid){
	try{
		var entry = $('#mail_session_id_'+mailid);
		$('.desc_attachment', entry).text(csAttachment);
		$('.desc_normal_attachment', entry).text(csNormalAttachment);
		$('.desc_huge_attachment', entry).text(csHugeAttachment);

		$('.desc_sender', entry).text(csSender);
		$('.desc_receipts', entry).text(csReceipts);
		$('.desc_receipts_cc', entry).text(csReceiptsCC);
		$('.desc_to', entry).text(csTo);
		$('.desc_details', entry).text(csDetails);
		$('.desc_size', entry).text(csSize);
		$('.desc_time', entry).text(csTime);

		$('.desc_meeting_time_to', entry).text(csMeetTimeTo);
		$('.desc_meeting_time', entry).text(csMeetTime);
		$('.desc_meeting_address', entry).text(csMeetAddress);
		$('.desc_accept', entry).text(csAccept);
		$('.desc_tentative', entry).text(csTentative);
		$('.desc_refuse', entry).text(csRefuse);

		$('.desc_fast_reply_send', entry).text(csFastReplySend);
		$('.desc_fast_reply_cancel', entry).text(csFastReplyCancel);

		var readReceipt = $('.desc_read_receipt', entry);
		var readReceiptState = parseInt(readReceipt.attr('readReceipt'));
		switch (readReceiptState){
			case 0: {
				readReceipt.text(csSendingReceipt);
				$('.desc_send_text', entry).hide();
				break;
			}
			case 1: {
				readReceipt.text(csReceiptsNotify);
				$('.desc_send_text', entry).show();
				$('.desc_send_text', entry).text(csSendText);
				break;
			}
			case 2: {
				$('.desc_send_text', entry).hide();
				readReceipt.text(csReceiptsNotified);
				break;
			}
		}
		
	}catch(e){
		WriteLog('updateMailEntryLanguage', e.message);
	}
}

function doCheckFastReplyArea(pageX, pageY){
	var element = document.elementFromPoint(pageX, pageY);
	var fastReplyArea = $(element).closest('.mail_fast_reply_textarea');
	return (fastReplyArea.length != 0);
}
function checkFastReplyArea(params){
	var pageX = params.getValue('offsetX');
	var pageY = params.getValue('offsetY');
	return doCheckFastReplyArea(pageX, pageY);
}

//初始化
var g_showMoreButtonTimer = 0;
//对应TMailEntryUpdateAction
var euAddMailEntry = 0;  
var euAddMailEntryAtBegin = 1;
var euAddMailEntryAtEnd = 2;
//TMailEntryLoadAction
var elMailEntryLoadNext = 0;
$(document).ready(function() {

	try{
		updateMailFrameLanguage();

		//注册JSFunction
		registerJSFunction('clearBindEvent', clearBindEvent);
		registerJSFunction('showSelectedConversation', showSelectedConversation);
		registerJSFunction('updateMailEntry', updateMailEntry);
		registerJSFunction('updateMailContent', updateMailContent);
		registerJSFunction('deleteMailEntry', deleteMailEntry);
		registerJSFunction('onSendFastReplyComplete', onSendFastReplyComplete);
		registerJSFunction('getFastReplyState', getFastReplyState);
		registerJSFunction('getFastReplyContent', getFastReplyContent);
		registerJSFunction('selectAllContact', selectAllContact);
		registerJSFunction('updateIFrameContent', updateIFrameContent);
		registerJSFunction('showFastReply', showFastReply);
		registerJSFunction('hideFastReply', hideFastReply);
		registerJSFunction('checkIsHideFastReply', checkIsHideFastReply);
		registerJSFunction('showCommentEditer', showCommentEditer);
		registerJSFunction('hideComment', hideComment);
		
		registerJSFunction('updateHugeAttachments', updateHugeAttachments);
		registerJSFunction('updateHugeAttachmentsInDraftBox', updateHugeAttachmentsInDraftBox);
		registerJSFunction('onCharsetChange', onCharsetChange);
		registerJSFunction('onIFrameRightClick', onIFrameRightClick);
		registerJSFunction('doMailContentZoom', doMailContentZoom);
		registerJSFunction('getCurZoomValue', getCurZoomValue);
		registerJSFunction('updateMailReadMark', updateMailReadMark);
		registerJSFunction('checkFastReplyArea', checkFastReplyArea);
		registerJSFunction('checkIsFocusInEditor', checkIsFocusInEditor);
		registerJSFunction('createHideImage', createHideImage);
		registerJSFunction('removeHideImage', removeHideImage);
		registerJSFunction('addDebugMsg', addDebugMsg);

		//初始化全局事件
		$(window).resize(onWindowSizeChange);
		$(document).delegate('.mail_head_collapse', 'selectstart', function(e){
			e.stopPropagation();
			return false;
		});
		$(document).delegate('.mail_content_container', 'selectstart', function(e){
			e.stopPropagation();
			return false;
		});
		$(document).delegate('#show_more_button', 'click', function(e){
			//显示加载动画
			try{
				var counter = 0;
				var obj = $(this);
				if (g_showMoreButtonTimer == 0){
					g_showMoreButtonTimer = setInterval(function(){
						if (counter == 0){
							counter ++;
							obj.text('加载中.');
						}else if (counter == 1){
							counter ++;
							obj.text('加载中..');
						}else if (counter == 2){
							counter = 0;
							obj.text('加载中...');
						}else{
							counter = 0;
						}
					}, 300);
					//加载剩余的邮件
					var updateAction = euAddMailEntryAtEnd;
					var loadAction = elMailEntryLoadNext;
					invokeAppFunction('LoadMailEntry', {updateAction: updateAction, loadAction: loadAction});
				}
			}catch(e){
				WriteLog('LoadMailEntry', e.message);
			}
		});
		
		$(document).delegate('body', 'mousedown', function(e){
			clearContactSelected();
			clearAttachmentsSelected();
		});
		$(document).delegate('body', 'keydown', function(e){
			if (e.keyCode == 67 && e.ctrlKey){
				//do ctrl+c
				if (hasSelectedContact()){
					doCopyContact();
					return false;
				}else if (hasSelectedAttachments()){
					doCopyAttachments();
					return false;
				}
			}
		});
		$(document).delegate('.mail_attachment_download_button', 'click', function(e){
			var mailid = $(this).attr('mailid');
			DownloadAllAttachments(mailid);
		});
		$(document).delegate('.mail_head', 'click', function(e){
			toggleSession(this);
			e.stopPropagation();
			return false;
		});
		$(document).delegate('.mail_info_sender_avatar', 'click', function(e){
			e.stopPropagation();
		});
		$(document).delegate('.mail_info_general_time', 'click', function(e){
			e.stopPropagation();
		});
		$(document).delegate('.mail_info_general_receiver_wrapper', 'click', function(e){
			e.stopPropagation();
		});
		$(document).delegate('.mail_info_general_sender_wrapper', 'click', function(e){
			e.stopPropagation();
		});
		$(document).delegate('.mail_info_head', 'click', function(e){
			try{
				var str = document.selection.createRange().text;
				if (str.length == 0){
					toggleSession(this);
					e.stopPropagation();
				}
			}catch(e){
				WriteLog(e.message);
			}
		});
		//
		$(document).delegate('.mail_session', 'mouseup', function(e){
			if (e.which == 3){
				var mailid = $(this).attr('mailid');
				if (!doCheckFastReplyArea(e.pageX, e.pageY)){
					onPopupMainMenu(mailid, e.screenX, e.screenY, e.offsetX, e.offsetY, false);
					e.stopPropagation();
				}
			}
		});

		$(document).delegate('.mail_info_expanded_contact_address', 'dblclick', function(e){
			var email = $(this).attr('email');
			doComposeMail(email);
			e.stopPropagation();
			return false;
		});
		$(document).delegate('.mail_info_expanded_contact_address', 'mouseup', function(e){
			if (e.which == 1 || e.which == 3){
				if (e.which == 3){
					var ulElement = $(this).closest('ul');
					var mailid = ulElement.attr('mailid');
					if (!$(this).parent().hasClass('ui-selected')){
						$('.ui-selected', ulElement).removeClass('ui-selected');
						$(this).parent().addClass('ui-selected');
						var name = $(this).attr('uName');
						var email = $(this).attr('email');
						selectedEmails = null;
						selectedEmails = [];
						selectedEmails[selectedEmails.length] = {name: name, email: email};
					}
					popupContactMenu(mailid, selectedEmails, e.screenX, e.screenY);
				}
				e.stopPropagation();
				return false;
			}
		});
		//
		$(document).delegate('.mail_info_general_expand', 'click', function(e){
			var mailid = $(this).parent().attr('mailid');
			toggleMailDetail(mailid);
			e.stopPropagation();
		});
		$(document).delegate('.mail_fast_reply_icon', 'click', function(e){
			var mailid = $(this).parent().attr('mailid');
			toggleFastReply(mailid);
			e.stopPropagation();
		});
		$(document).delegate('.mail_info_attachment_count', 'click', function(e){
			var mailid = $(this).parent().parent().attr('mailid');
			flashArea($('#attachment_area_'+mailid));
			e.stopPropagation();
		});
		$(document).delegate('.mail_entry_info_attachment_span', 'click', function(e){
			var obj = $(this).parent().parent();
			var mailid = obj.attr('mailid');
			flashArea($('#attachment_area_'+mailid));
		});
		//attachments
		$(document).delegate('.mail_huge_attachment_entry', 'click', function(e){
			var url = decodeURI($(this).attr('downloadUrl'));
			if (url != ''){
				invokeAppFunction('OpenNewWindow', {url: url});
			}
		});
		$(document).delegate('.mail_attachment_container_host', 'mouseup', function(e){
			if (e.which == 3){
				var mailid = $(this).attr('mailid');
				popupAttachmentMenu(mailid, e.screenX, e.screenY, true);
				e.stopPropagation();
			}
		});
		$(document).delegate('.mail_huge_attachment', 'mouseup', function(e){
			e.stopPropagation();
		});
		$(document).delegate('.mail_attachment_entry', 'mouseup', function(e){
			if (e.which == 1 || e.which == 3){
				if (e.which == 3){
					var mailid = $(this).attr("mailid");
					var itemIndex = $(this).attr("itemIndex");
					var attachFileName = $(this).attr("attachFileName"); 

					if (!$(this).hasClass('ui-selected')){
						clearAttachmentsSelected();
						$(this).addClass('ui-selected');
						selectAttachment(mailid, itemIndex, attachFileName);
					}
					popupAttachmentMenu(mailid, e.screenX, e.screenY, false);
				}
				e.stopPropagation();
			}
		});
		$(document).delegate('.mail_attachment_entry', 'mousedown', function(e){
			if (e.which == 1 || e.which == 3){
				if (e.which == 1){
					clearContactSelected();
					var mailid = $(this).attr('mailid');
					var itemIndex = $(this).attr("itemIndex");
					var attachFileName = $(this).attr("attachFileName"); 
					if (e.shiftKey || e.ctrlKey) {
						if (!$(this).hasClass('ui-selected')) {
							$(this).addClass('ui-selected');
							selectAttachment(mailid, itemIndex, attachFileName);
						}
					} else {
						clearAttachmentsSelected();
						$(this).addClass('ui-selected');
						selectAttachment(mailid, itemIndex, attachFileName);
					}
				}
				e.stopPropagation();
			}
		});
		$(document).delegate('.mail_attachment_entry', 'dblclick', function(e){
			var mailid = $(this).attr('mailid');
			var itemIndex = $(this).attr('itemIndex');
			var attachFileName = $(this).attr('attachFileName');
			OpenAttachFile(mailid, itemIndex, attachFileName);
			e.stopPropagation();
		});
		//read receipt
		$(document).delegate('.read_receipt_send_button', 'click', function(e){
			var obj = $(this);
			//update
			var readReceipt = obj.closest('.mail_read_receipt');
			var mailid = readReceipt.attr('mailid');
			obj.hide();
			var desc = $('.mail_read_receipt_desc', readReceipt);
			if (desc.attr('readReceipt') === '1'){
				desc.attr('readReceipt', '0');
				$('.mail_read_receipt_desc', readReceipt).text(csSendingReceipt);
				invokeAppFunction('MakeReceiptMesssage', {mailid: mailid});
				
				var doUpdateReadReceiptState = function(){
					var curState = invokeAppFunction('GetCurrentReadReceiptState', {mailid: mailid});
					if (curState != '0' && curState != '1'){
						desc.attr('readReceipt', '0');
						$('.mail_read_receipt_desc', readReceipt).text(csReceiptsNotified);
					}else{
						setTimeout(doUpdateReadReceiptState, 500); 
					}
				};
				setTimeout(doUpdateReadReceiptState, 500); 
			}
		});
		//fast reply
		/*$(document).delegate('.mail_fast_reply_textarea', 'blur', function(e){
			//var obj = $(this).parent().parent().parent();
			//setEditUnfocus(obj);
		});
		$(document).delegate('.mail_fast_reply_textarea', 'focus', function(e){
			try{
				var obj = this;
				var sel = obj.createTextRange();
				var len = obj.innerHTML.length;
				sel.moveStart('character', len);
				sel.select();
				sel.collapse(false);
			}catch(e){
				WriteLog('textarea focus', e.message);
			}
		});*/
		$(document).delegate('.mail_fast_reply_textarea', 'keydown', function(e){
			var textarea = $(this);
			var mailid = textarea.attr('mailid');
			var bNeedReset = false;
			if (textarea.val().length > 0){
				if (e.which == 13 && e.ctrlKey){
					sendFastReply(mailid);
					e.stopPropagation();
				}else{
					var str = textarea.text() + String.fromCharCode(e.which);
					var lines = str.split('\r').length;
					if (lines > 4){
						//if (e.which == 46 || e.which == 8){
						//	//bNeedReset = true;
						//}else{
							var newHeight = 16 * lines;
							textarea.height(newHeight);
							$('#mail_fast_reply_'+mailid).height(newHeight + 60);
							adjustMailContentSize(mailid, true, true);
						//}
					}
				}
			}else{
				bNeedReset = true;
			}
			if (bNeedReset){
				var curHeight = textarea.height();
				if (curHeight > 53){
					textarea.height(53);
					$('#mail_fast_reply_'+mailid).height(116);
					adjustMailContentSize(mailid, true, true);
				}
			}
		});
		$(document).delegate('.mail_fast_reply_textarea', 'keyup', function(e){
			var textarea = $(this);
			var mailid = textarea.attr('mailid');
			if (textarea.val().length > 0){
				enableFastReplySendButton(mailid, true);
			} else {
				enableFastReplySendButton(mailid, false);
			}
			e.stopPropagation();
		});
		$(document).delegate('.mail_fast_reply_toolbar', 'selectstart', function(e){
			return false;
		});
		//联系人资料卡浮窗
		$(document).delegate('.mail_info_sender_avatar', 'mouseenter', function(e){
			var email = $(this).attr('email');
			var name = $(this).attr('uName');
			var x = $(this).offset().left;
			var y = $(this).offset().top + $(this).height() + 5;
			resetShowContactTask();
			prepareShowContactView(name, email, x, y);
		});
		$(document).delegate('.mail_info_sender_avatar', 'mouseleave', function(e){
			resetShowContactTask();
			setHideContactView();
		});
		$(document).delegate('.mail_info_general_sender', 'mouseenter', function(e){
			var email = $(this).attr('email');
			var name = $(this).attr('uName');
			var x = $(this).offset().left;
			var y = $(this).offset().top + $(this).height() + 5;
			resetShowContactTask();
			prepareShowContactView(name, email, x, y);
		});
		$(document).delegate('.mail_info_general_sender', 'mouseleave', function(e){
			resetShowContactTask();
			setHideContactView();
		});
		$(document).delegate('.mail_info_expanded_contact_address', 'mouseenter', function(e){
			var email = $(this).attr('email');
			var name = $(this).attr('uName');
			var x = $(this).offset().left;
			var y = $(this).offset().top + $(this).height() + 5;
			resetShowContactTask();
			prepareShowContactView(name, email, x, y);
		});
		$(document).delegate('.mail_info_expanded_contact_address', 'mouseleave', function(e){
			resetShowContactTask();
			setHideContactView();
		});
		$(document).delegate('.mail_info_general_receiver', 'mouseenter', function(e){
			var email = $(this).attr('email');
			var name = $(this).attr('uName');
			var x = $(this).offset().left;
			var y = $(this).offset().top + $(this).height() + 5;
			resetShowContactTask();
			prepareShowContactView(name, email, x, y);
		});
		$(document).delegate('.mail_info_general_receiver', 'mouseleave', function(e){
			resetShowContactTask();
			setHideContactView();
		});
		registerContactViewDelegate();
		registerMailMeetingDelegate();
		//
		$(document).delegate('.edit_input_focus', 'focus', function(e){
		
		});
		$(document).delegate('.edit_input_focus', 'blur', function(e){
			try{
				var obj = $(this);
				setEditUnfocus(obj);
			}catch(e){
				WriteLog('textrea lostfocus', e.message);
			}
		});
		$(document).delegate('.edit_input_lostfocus', 'focus', function(e){
			try{
				var obj = $(this);
				setEditFocus(obj);
			}catch(e){
				WriteLog('textarea focus', e.message);
			}
		});
		$(document).delegate('.edit_input_lostfocus', 'blur', function(e){
			
		});

		//scrollbar
		setupFoxWBScrollbar({});
		initFoxWBScrollbar();

	}catch(e){
		WriteLog('ready', e.message);
	}

	//
	g_loadFrameTime = invokeAppFunction('DebugGetInitConversationFrameTime', {});
	//doInitDebugMsg();
	doClearDebugMsg();
	doAddDebugMsg('初始化页面框架时间: '+g_loadFrameTime);
});

function onPopupMainMenu(mailid, x, y, offsetX, offsetY, bPopupFromIFrame){
	invokeAppFunction('OnPopupMainMenu', {
		mailid: mailid,
		x: x,
		y: y,
		offsetX: offsetX,
		offsetY: offsetY,
		popupFromIFrame: bPopupFromIFrame
	});
}

var g_loadPageStartTime = 0;
function updateSenderAvatar(mailid){
	try{
		var date = new Date();
		var img_src = invokeAppFunction('GetSenderAvatar', {mailid: mailid});
		if (img_src){
			img_src = img_src +'?hashkey=' + (new Date().getTime());
		}
		$('#sender_avatar_'+mailid).attr('src', img_src);
	}catch(e){
		WriteLog('updateSenderAvatar', e.message);
	}
}

var g_mailFrameContentTimer = 0;
function updateMailFrameContent(mailid){
	try{
		invokeAppFunction('LoadMailContent', {mailid: mailid});
	}catch(e){
		WriteLog('updateMailFrameContent', e.message);
	}
}

//
function iframe_onReadyStateChange(obj){
	try{
		var loadState = $(obj).attr('loadState');
		setTimeout(function(){
			var mailid = $(obj).attr('mailid');
			//var newObj = document.getElementById('iframe_'+mailid);
			//if (newObj == obj){
			if (loadState === 'loading' || loadState === 'complete'){
				//if (newObj.readyState != 'loading'){
				adjustMailContentSize(mailid, true, true);
				setupHorzScrollbar(mailid);
				//}
			}
			//}
		}, 100);
	}catch(e){
		WriteLog('iframe_onReadyStateChange', e.message);
	}
}
function iframe_onload(obj) {
	//var date1=new Date();  //开始时间
	//setTimeout(function(){
		try{
			var loadState = $(obj).attr('loadState');
			var mailid = $(obj).attr("mailid");
			if (loadState === 'unload'){
				var date1 = new Date();
				//document.selection.empty();

				//只有一个会话 一开始设置满页
				var sessionCount = parseInt($('#foxmail_view_body').attr('sessionCount'));
				if (sessionCount == 1){
					var sessionPanel = $('#mail_session_panel_'+mailid);
					if (sessionPanel.length > 0){
						sessionTop = sessionPanel.offset().top;
						var documentHeight = document.documentElement.clientHeight || document.body.clientHeight;
						var currentHeight = sessionPanel.height() + sessionTop;
						var sessionHeight = documentHeight - sessionTop - 20;
						sessionPanel.css('height', sessionHeight+'px');
						$("#mail_content_loading_"+mailid).css('height', sessionHeight+'px');
					}
				}

				//update language
				updateMailEntryLanguage(mailid);
				//附件选择事件
				makeAttachmentSelectable(mailid);
			
				//联系人选择事件
				makeContactSelectable(mailid);
				//联系人头像
				updateSenderAvatar(mailid);

				//更新备注信息 暂时屏蔽
				updateComment(mailid, true);
				var date2 = new Date();
				doAddDebugMsg('InitMailEntry: '+(date2.getTime() - date1.getTime()));
			
				g_iframeOnLoadStartTime = new Date();
				//
				setMailReadMark(mailid, true);

				//更新邮件正文内容
				$(obj).attr('loadState', 'loading');
				startAutoResize();//开启计时器自动刷新页面高度
				updateMailFrameContent(mailid);

			}else if (loadState === 'loading'){
				var startTime = new Date();

				//显示附件
				var attachmentArea = $('#mail_attachment_container_host_'+mailid);
				var attachmentCount = parseInt(attachmentArea.attr('attachmentCount'));
				if (attachmentCount > 0){
					attachmentArea.removeClass('hide_ifzero_0');
				}
				//初始化超大附件
				initHugeAttachments(mailid);
				setTimeout(function(){
					$(obj).attr('loadState', 'complete');
					endAutoResize();//结束调整大小计时器
					//
					adjustExpandMailContentSize(true);
					var id = 'horz_scrollbar_'+mailid;
					var scrollbar = getFoxWBScrollbar(id);
					if (scrollbar){
						scrollbar.HorzScrollHandler(null);
					}else{
						scrollbar = setupHorzScrollbar(mailid);
						scrollbar.HorzScrollHandler(null);
					}
				}, 100);

				endTime = new Date();
				doAddDebugMsg('iframe onload执行耗时: '+(endTime.getTime()-startTime.getTime()));
			}else if (loadState === 'complete'){

			}
		}catch(e){
			WriteLog('iframe_onload', e.message);
		}
	//}, 100);
}

//水平滚动条
function getHorzScrollbar(mailid){
	var key = 'horz_scrollbar_' + mailid;
	return  getFoxWBScrollbar(key);
}
function hideHorzScrollbar(mailid){
	try{
		var id = 'horz_scrollbar_'+mailid;
		var scrollbar = getFoxWBScrollbar(id);
		if (scrollbar){
			scrollbar.showHorzScrollbar(false);
		}
	}catch(e){
		WriteLog('hideHorzScrollbar', e.message);
	}
}
function showHorzScrollbar(mailid){
	try{
		var id = 'horz_scrollbar_'+mailid;
		var scrollbar = getFoxWBScrollbar(id);
		if (scrollbar){
			scrollbar.showHorzScrollbar(true);
		}
	}catch(e){
		WriteLog('showHorzScrollbar', e.message);
	}
}
function updateHorzScrollbar(mailid){
	try{
		var id = 'horz_scrollbar_'+mailid;
		var scrollbar = getFoxWBScrollbar(id);
		if (scrollbar){
			scrollbar.update();
		}
	}catch(e){
		WriteLog('updateHorzScrollbar', e.message);
	}
}
function setupHorzScrollbar(mailid){
	try{
		var id = 'horz_scrollbar_'+mailid;
		var scrollbar = getFoxWBScrollbar(id);
		if (!scrollbar){
			var target = document.getElementById('iframe_'+mailid);
			if (target){
				var iframeTarget = $(target);
				if (iframeTarget.attr('loadState') != 'unload'){
					scrollbar = createFoxWBScrollbar({
						id: id,
						Parent: 'mail_session_id_'+mailid,
						HS: true,
						HSTarget: iframeTarget
					});
					if (!lastScrollbar) lastScrollbar = scrollbar;
					adjustHorzFixScrollbar();
				}
			}
		}
		updateHorzScrollbar(mailid);
		return scrollbar;
	}catch(e){
		WriteLog('setupHorzScrollbar', e.message);
	}
}
function resetHorzScrollbarFixPosition(scrollbar){
	try{
		if (!scrollbar) return;
		if (!scrollbar.horzVisible()) return;
		//if (!scrollbar.horzFixed()) return;

		//恢复状态
		scrollbar.fixedHorzScrollbar(false);
		//更新位置
		setupHorzScrollbarPosition(scrollbar);
	}catch(e){
		WriteLog('resetHorzScrollbarFixPosition', e.message);
	}
}
function setupHorzScrollbarFixPosition(scrollbar){
	try{
		if (!scrollbar) return;
		if (!scrollbar.horzVisible()) return;
		if (scrollbar.horzFixed()) {
			setupHorzScrollbarPosition(scrollbar);
			return;
		}

		if (lastScrollbar){
			//不是自己 恢复
			if (lastScrollbar.getID() != scrollbar.getID()){
				resetHorzScrollbarFixPosition(lastScrollbar);
				lastScrollbar = null;
			}
		}
		//设置Fixed
		scrollbar.fixedHorzScrollbar(true);
		//更新位置
		setupHorzScrollbarPosition(scrollbar);
		//记录最后的滚动条
		lastScrollbar = scrollbar;
	}catch(e){
		WriteLog('setupHorzScrollbarFixPosition', e.message);
	}
}
function setupHorzScrollbarPosition(scrollbar){
	try{
		if (!scrollbar) return;
		if (!scrollbar.horzVisible()) return;
		var nWidthFix = -8;
		var nHeightFix = 0;
		var nXFix = 4;
		var nYFix = 7;
		var vertScrollbar = getFoxWBScrollbar(vertscrollbar_id);
		if (vertScrollbar){
			if (scrollbar.horzFixed()){
				//滚动条浮在窗口底部
				if (vertScrollbar.vertVisible()){
					//有竖直滚动条
					var nVertWidth = vertScrollbar.getVertWidth();
					nXFix = 9;
					nYFix = 0;
					nWidthFix = 0 - nVertWidth - 18;
				}
			}
		}
		scrollbar.setHorzOffset(nXFix, nYFix, nWidthFix, nHeightFix);
		scrollbar.update();
	}catch(e){
		WriteLog('setupHorzScrollbarPosition', e.message);
	}
}
function doAdjustHorzFixScrollbar(px, py, nWidth, nHeight){
	var element = document.elementFromPoint(px, py);
	var elemClsName = $(element).attr('class');
	var bIsScrollbar = false;
	var bReset = false;
	if (elemClsName){
		bIsScrollbar = (elemClsName.indexOf('foxwb_') != -1);
	}
	if (bIsScrollbar){
		//是滚动条
		var session = $(element).closest('.mail_session');
		if (session.length > 0){
			var mailid = session.attr('mailid');
			var top = session.offset().top;
			var height = session.height();
			var pos = top + height - 34;
			var scrollBarTop = $(element).offset().top;
			if (pos >= scrollBarTop){
				if (scrollBarTop + 17 > nHeight){
					var horzScrollbar = getHorzScrollbar(mailid);
					setupHorzScrollbarFixPosition(horzScrollbar);
				}else{
					if (top < (nHeight - 100)){
						var horzScrollbar = getHorzScrollbar(mailid);
						setupHorzScrollbarFixPosition(horzScrollbar);
					}else{
						resetHorzScrollbarFixPosition(lastScrollbar);
						bReset = true;
					}
				}
			}else{
				resetHorzScrollbarFixPosition(lastScrollbar);
				bReset = true;
			}
		}
	}else{
		//不是滚动条
		var mailBody = $(element).closest('.mail_body');
		if (mailBody.length > 0){
			var session = $(element).closest('.mail_session');
			var mailid = session.attr('mailid');
			if (mailid){
				//是展开的邮件
				var offsetTop = $('#mail_session_id_'+mailid).offset().top;
				if (offsetTop < (nHeight - 100)){
					//距离窗口底部300px 设置fixed属性
					var horzScrollbar = getHorzScrollbar(mailid);
					setupHorzScrollbarFixPosition(horzScrollbar);
					return false;
				}
			}
		}
		resetHorzScrollbarFixPosition(lastScrollbar);
		bReset = true;
	}
	return bReset;
}
function adjustHorzFixScrollbar(){
	try{
		var nWidth = document.documentElement.clientWidth || document.body.clientWidth;
		var nHeight = document.documentElement.clientHeight || document.body.clientHeight;
		var scrollbar = getFoxWBScrollbar(vertscrollbar_id);
		if (scrollbar){
			//var viewBody = $('#foxmail_view_body');
			//var sessionCount = parseInt(viewBody.attr('sessionCount'));
			var yFix = -4;
			var px = Math.round(nWidth / 2);
			var py = nHeight + yFix;
			//调整滚动条
			if (doAdjustHorzFixScrollbar(px, py, nWidth, nHeight)){
				//如果是还原滚动条位置，再次调整新的区域的滚动条
				doAdjustHorzFixScrollbar(px, py, nWidth, nHeight);
			}
		}
	}catch(e){
		WriteLog('adjustHorzFixScrollbar', e.message);
	}
}

//垂直滚动条
function setupVertScrollbar(){
	try{
		var scrollbar = getFoxWBScrollbar(vertscrollbar_id);
		if (!scrollbar){
			scrollbar = createFoxWBScrollbar({
				id: vertscrollbar_id,
				Parent: 'mail_frame',
				VS: true,
				VSTarget: $('#mail_session_container')
			});
			scrollbar.VertScrollHandler(function(){
				adjustHorzFixScrollbar();
			});
		}
	}catch(e){
		WriteLog('setupVertScrollbar', e.message);
	}
}

function updateVertScrollbar() {
	var date1 = new Date();
	var scrollbar = getFoxWBScrollbar(vertscrollbar_id);
	if (scrollbar){
		scrollbar.update();
	}
	var date2 = new Date();
	//doAddDebugMsg('更新竖直滚动条耗时: ' + (date2.getTime()-date1.getTime()));
}

function showVerticalScrollbar() {
	var scrollbar = getFoxWBScrollbar(vertscrollbar_id);
	if (scrollbar){
		scrollbar.showVertScrollbar(true);
	}
}
function hideVerticalScrollbar() {
	var scrollbar = getFoxWBScrollbar(vertscrollbar_id);
	if (scrollbar){
		scrollbar.showVertScrollbar(false);
	}
}
//
function onIFrameRightClick(params){
	try{
		var mailid = params.getValue('mailid');
		var x = params.getValue('x');
		var y = params.getValue('y');
		var offsetX = parseInt(params.getValue('offsetX'));
		var offsetY = parseInt(params.getValue('offsetY'));
		var iframeObj = document.getElementById('iframe_'+mailid);
		if (iframeObj){
			var fixheight = 0;
			var scrollbar = getFoxWBScrollbar(vertscrollbar_id);
			if (scrollbar){
				fixheight = scrollbar.vertScrollTop();
			}
			var offsetX = offsetX - iframeObj.offsetLeft - 13;
			var offsetY = offsetY - iframeObj.offsetTop - 45 + fixheight;
			onPopupMainMenu(mailid, x, y, offsetX, offsetY, true);
		}
	}catch(e){
		WriteLog('onIFrameRightClick', e.message);
	}
}
function onCharsetChange(params) {
	var mailid = params.getValue('mailid');
	var iframeSrc = params.getValue('iframeSrc');
	setTimeout(function(){
		try{
			var frm = document.getElementById('iframe_'+mailid);
			if (frm == 'undefined') return;
			frm.src = iframeSrc;
		}catch(e){
			WriteLog('onCharsetChange', e.message);
		}
	}, 100);
}

function findSessionElement(obj) {
    return $($(obj).closest(".mail_session")[0]);
}

function findSessionMailId(obj) {
    return findSessionElement(obj).attr("mailid");
}

function toggleSession(obj) {
	var session = $('.mail_session');
    if (session.length <= 1) {
		if (session.hasClass('mail_session_collapse')){
			expandSession(session);
		}
		return;
	}
    var sessionElement = findSessionElement(obj);
    if (sessionElement.attr('toggling') == 'true') return;
    if (sessionElement.hasClass("mail_session_expand")) {
        collapseSession(sessionElement);
    } else {
        expandSession(sessionElement);
    }
}

function checkMailSessionLoaded(mailid) {
	var sessionElement = $("#mail_content_state_"+mailid);
	if (sessionElement.val() === "complete")
		return true;
	else
		return false;
}

function loadMailSession(mailid) {
	//加载邮件内容
	invokeAppFunction('LoadMailEntryInfo', {mailid: mailid});
	//设置状态
	var sessionElement = $("#mail_content_state_"+mailid);
	sessionElement.val("complete");
}

function doExpandSession(mailid, bScrollTop){
	var sessionElement = $('#mail_session_id_'+mailid);
	sessionElement.attr('toggling', 'true');
	var mailBody = $("#mail_body_"+mailid);
	$(".mail_head", sessionElement).hide();
	//var loading = $('#mail_content_loading_'+mailid);
	//$(".mail_head", sessionElement).fadeOut(100, function(){
		try{
			var curHeight = mailBody.height();
			var minHeight = 120;
			if (curHeight < minHeight){
				mailBody.css('height', minHeight+'px');
			}
			mailBody.animate({height: 'toggle'}, 300, 'swing', function() {
				try{
					sessionElement.attr('toggling', 'false');
					mailBody.css('height', 'auto');
					adjustExpandMailContentSize(true);
					showHorzScrollbar(mailid);
				}catch(e){
					WriteLog('ExpandSessionEnd', e.message);
				}
			});
		}catch(e){
			WriteLog('ExpandSession', e.message);
		}
	//});
}

function expandSession(sessionElement) {
    sessionElement.addClass("mail_session_expand");
    sessionElement.removeClass("mail_session_collapse");
	var mailid = sessionElement.attr('mailid');
	if (!checkMailSessionLoaded(mailid)){
		loadMailSession(mailid); //载入会话邮件
	}
	doExpandSession(mailid, true);
}

function collapseSession(sessionElement) {
	try{
		sessionElement.attr('toggling', 'true');
		sessionElement.addClass("mail_session_collapse");
		sessionElement.removeClass("mail_session_expand");
		//隐藏滚动条
		var mailid = sessionElement.attr('mailid');
		hideHorzScrollbar(mailid);
		doHideFastReply(sessionElement.attr('mailid'), function(){
			var mailBody = $(".mail_body", sessionElement);
			mailBody.animate({height: 'toggle'}, 300, 'swing', function(){
				sessionElement.attr('toggling', 'false');
				$(".mail_head", sessionElement).show();
				//$(".mail_head", sessionElement).fadeIn(100, function(){
					updateVertScrollbar();
				//});
			});
		});
	}catch(e){
		WriteLog('CollapseSession', e.message);
	}
}

function flashArea(obj) {
	var top = obj.offset().top;
	var scrollTop = $(".mail_session_container").scrollTop();
	var mailid = $(obj).attr('mailid');
	var frame = $('#mail_attachment_container_border_'+mailid);
    $(".mail_session_container").scrollTo(top+scrollTop, {offsetTop:20}, function() {
        frame.addClass('mail_attachment_container_flash');
        setTimeout(function(){
            frame.removeClass('mail_attachment_container_flash');
            setTimeout(function(){
                frame.addClass('mail_attachment_container_flash');
                setTimeout(function(){
                    frame.removeClass('mail_attachment_container_flash');
                }, 500);
            }, 500);
        }, 500);
    });
}

function adjustExpandMailContentSize(resizeContent){
	var date1 = new Date();

	try{
		var elements = $(".mail_session_expand");
		for (var i=0; i<elements.length; i++) {
			var item = elements[i];
			var mailid = $(item).attr("mailid");
			updateVertScrollbar();
			adjustMailContentSize(mailid, false, resizeContent);
			if (resizeContent){
				showHorzScrollbar(mailid);
			}else{
				hideHorzScrollbar(mailid);
			}
			updateHorzScrollbar(mailid);
		}
		//调整滚动条
		updateVertScrollbar();
	}catch(e){
		WriteLog('adjustExpandMailContentSize', e.message);
	}

	var date2 = new Date();
	doAddDebugMsg('调整所有展开iframe大小耗时:'+(date2.getTime()-date1.getTime()));
}
var resizeTimer = 0;
var resizeCounter = 0;
function onWindowSizeChange(event) {
	var date1 = new Date();

	try{
		//调整MailFrame大小
		adjustMailFrameSize();
		//频率控制 暂时屏蔽
		//if (resizeCounter > 3){
		//调整每个MailEntry的大小
		adjustExpandMailContentSize(false);
		//	resizeCounter = 0;
		//}else{
		//	resizeCounter ++;
		//}

		if (resizeTimer){
			clearTimeout(resizeTimer);
			resizeTimer = 0;
		}
		resizeTimer = setTimeout(function(){
			//延时做最终调整
			//resizeCounter = 0;
			//调整MailFrame大小
			adjustMailFrameSize();
			//调整每个MailEntry的大小
			adjustExpandMailContentSize(true);
		}, 300);

	}catch(e){
		WriteLog('onWindowSizeChange', e.message);
	}

	var date2 = new Date();
	doAddDebugMsg('调整窗口大小耗时: '+(date2.getTime()-date1.getTime()));
}

function frameMouseEnterHandler(){
	showVerticalScrollbar();
}
function frameMouseLeaveHandler(){
	hideVerticalScrollbar();
}

//Delphi调用函数
function addDebugMsg(params){
	doAddDebugMsg(params.getValue('msg'));
}
function showCommentEditer(params){
	var mailid = params.getValue('mailid');
	var content = params.getValue('content');
	var readOnly = params.getValue('readOnly');
	doShowCommentEditer(mailid, content, readOnly)
}
function hideComment(params){
	setTimeout(function(){
		var mailid = params.getValue('mailid');
		doHideComment(mailid);
	}, 100);
}
function updateMailEntry(params){
	try{
		var updateAction = params.getValue('updateAction');
		var sessionKey = parseInt($('#foxmail_view_body').attr('sessionKey'));
		//更新滚动条
		setupVertScrollbar();
		adjustMailFrameSize();
		adjustExpandMailContentSize(true);
		updateVertScrollbar();
		setTimeout(function(){
			try{
				if ((updateAction == euAddMailEntryAtBegin) ||
					(updateAction == euAddMailEntryAtEnd)){
					var viewBody = $('#foxmail_view_body');
					var sessionCount = parseInt(viewBody.attr('sessionCount')) + 1;
					viewBody.attr('sessionCount', sessionCount);
				}
				//隐藏加载按钮 停止动画计时器
				if (g_showMoreButtonTimer){
					clearInterval(g_showMoreButtonTimer);
					g_showMoreButtonTimer = 0;
					var buttonArea = $('#show_more_button').parent();
					if (!buttonArea.hasClass('hide_ifzero_0')){
						buttonArea.addClass('hide_ifzero_0')
					}
				}
				//更新滚动条
				setupVertScrollbar();
				adjustMailFrameSize();
				adjustExpandMailContentSize(true);
				updateVertScrollbar();
			}catch(e){
				WriteLog('updateMailEntry', e.message);
			}
		}, 100);
	}catch(e){
		WriteLog('updateMailEntry', e.message);
	}
}
function updateMailContent(params){
	try{
		var mailid = params.getValue('mailid');
		setTimeout(function(){
			//adjustMailFrameSize();
			//adjustExpandMailContentSize();
		}, 100);
	}catch(e){
		WriteLog('updateMailContent', e.message);
	}
}
function deleteMailEntry(params){
	try{
		var mailid = params.getValue('mailid');
		var sessionKey = parseInt($('#foxmail_view_body').attr('sessionKey'));
		setTimeout(function(){
			try{
			var sessionContainer = $('#mail_session_container');
			var session = $('#mail_session_id_'+mailid);
			if (session.length > 0){
				var viewBody = $('#foxmail_view_body');
				var sessionCount = parseInt(viewBody.attr('sessionCount')) - 1;
				viewBody.attr('sessionCount', sessionCount);
				session.animate({height: '0px'}, 300, 'swing', function(){
					session.remove();
					if (sessionCount == 0){
						//conversation is empty
						var curSessionKey = parseInt($('#foxmail_view_body').attr('sessionKey'));
						if (sessionKey === curSessionKey){
							$('#body_main').empty();
						}
					}else if(sessionCount == 1){
						//最后一个自动展开
						//var sessionElement = $('.mail_session');
						//if (sessionElement.hasClass('mail_session_collapse')){
						//	expandSession(sessionElement);
						//}
					}
				});
			}
			}catch(e){
				WriteLog('deleteMailEntry', e.message);
			}
		}, 100);
	}catch(e){
		WriteLog('deleteMailEntry', e.message);
	}
}
function updateIFrameContent(params){
	//var date1 = new Date();
	try{
		var mailid = params.getValue('mailid');
		var content = params.getValue('content');
		var iframe = document.getElementById('iframe_'+mailid);
		if (iframe){
			try{
				var iframeWin = iframe.contentWindow;
				if (iframeWin){
					var iframeElement = iframeWin.document;
					hideLoadingAnimate(mailid);
					//iframeElement.write("<!DOCTYPE HTML><style>html{overflow:hidden;}*>img{max-width:100%;height:auto!important;}</style>"+content);
					iframeElement.write(content);
					//iframeWin.attachEvent('onload', function(){
					//	setTimeout(adjustExpandMailContentSize, 10);
					//});
					iframeElement.close();
					//
					//var paddingLeft = iframeElement.body.style.paddingLeft;
					//var paddingRight =  iframeElement.body.style.paddingRight;
					//var marginLeft = iframeElement.body.style.marginLeft;
					//var marginRight = iframeElement.body.style.marginRight;
					//alert([paddingLeft, paddingRight, marginLeft, marginRight]);
				}
			}catch(e){
				WriteLog('updateIFrameContent', e.message);
			}
		}
	}catch(e){
		WriteLog('updateIFrameContent', e.message);
	}
	//var date2 = new Date();
	//var date3 = date2.getTime() - date1.getTime();   
	//doAddDebugMsg('将内容写入到IFrame耗时: '+date3);
}

function selectAllContact(params){
	var mailid = params.getValue('mailid');
	selectedEmails = [];
	var index = 0;
	$('.mail_info_expanded_contact_address', $('#mail_header_receiver_panel_'+mailid)).each(function(){
		$(this).parent().addClass('ui-selected');
		var name = $(this).attr('uName');
		var email = $(this).attr('email');
		selectedEmails[index++] = {name: name, email: email};
	});
}

function getFastReplyContent(params) {
	var mailid = params.getValue('mailid');
	var mailInfo = $('#mail_info_'+mailid);
	var textarea = $('.mail_fast_reply textarea', mailInfo);
	return textarea.val();
}

function getFastReplyState(params) {
	var mailid = params.getValue('mailid');
	return true; // true: replyAll 
}

function onSendFastReplyComplete(params){
	var mailid = params.getValue('mailid');
	var mailInfo = $('#mail_info_'+mailid);
	var textarea = $('.mail_fast_reply textarea', mailInfo);
	setTimeout(function(){
		textarea.val('');
		//$$.reportFastReplyStatus('0');
	}, 300);
}
function clearBindEvent() {
	g_loadPageStartTime = new Date();
	doClearDebugMsg();
	doAddDebugMsg('初始化页面框架时间: '+g_loadFrameTime);
	var date1 = new Date();

	try{
		$('#selected_conversation_info').hide();
		$('#body_main').show();
		endAutoResize();
		lastScrollbar = null;
		//清理滚动条事件
		releaseAllFoxWBScrollbar();
		resetShowContactTask();
		doHideContactView();
		//清理超大附件资源信息
		releaseHugeAttachments();
		//$('.mail_attachment_container').selectable('destroy');
		//$('.mail_header_receiver_panel').selectable('destroy');
	}catch(e){
		WriteLog('clearBindEvent', e.message);
	}

	var date2 = new Date();
	var date3 = date2.getTime()-date1.getTime();
	doAddDebugMsg('清理绑定事件耗时: '+date3);
}

function showSelectedConversation(params){
	try{
		var number = params.getValue('number');
		$('#body_main').hide();
		var info = $('#selected_conversation_info');
		info.show();
		var text = $('#selected_conversation_info_value');
		text.text('当前选择了 ' + number + ' 个会话');
	}catch(e){
		WriteLog('showSelectedConversation', e.message);
	}
}

function editSubject(){
}
