<?php
if( !empty($this->viewmessageTabNumber) )
	$messagePanelContextName = 'viewmessageTab' . $this->viewmessageTabNumber;
else
	$messagePanelContextName = $this->resultContext;

$this->messagePanelContextName = $messagePanelContextName;

if( $this->threadsEnabled && !isset($this->thread) ) throw new Exception('no message to render.');
if( !$this->threadsEnabled && !isset($this->message) ) throw new Exception('no message to render!');

    
/**
 * renders the message and the child messages recursively
 * rendered content should have all except last message collapsed (i.e. if has no children then don't collapse)
 */
if( $this->threadsEnabled )
	$this->currentThreadNode = $this->thread;
else 
	$this->currentThreadNode = $this->message;

if( isset($this->inline) && $this->inline == true )
	$this->currentThreadNode = $this->message;
//render message body if found/available, else just render the collapsed preview and message info                             

$folderUTF7Urlencoded = urlencode( $this->folderUTF7 );
$folderUTF7UrlencodedDouble = urlencode( $folderUTF7Urlencoded );
if( isset($this->inline) && $this->inline == true ) 
{
	echo $this->partial('viewmessage/recursivelyrendermessagebody.phtml', array('messageArray' => $this->message['messageArray'], 'moduleBaseUrl' => $this->moduleBaseUrl, 'siteBaseUrl' => $this->siteBaseUrl, 'folderUTF7' => $this->folderUTF7, 'messagePanelContextName' => $this->messagePanelContextName) );
}
else
{

	//set up reply fields for replying to latest message
	if($this->threadsEnabled )
		$latestThreadChild = $this->AtmailMailStorageMain->findLatestThreadChild($this->currentThreadNode);
	else
		$latestThreadChild = $this->currentThreadNode;
	
	$headers = $latestThreadChild['messageArray']['headers'];
	$headers['subject'] = messageHandling::mimeEncodedDecode($headers['subject']);
	
	$reSubject = htmlentities(reReply($headers['subject']), ENT_COMPAT, 'utf-8');

	$this->composeID = 'uid' . substr(md5(microtime()),0,10); //shortened it cos appears jQuery has a limit on the selector length
?> 

<?php if( !isset($this->compact) ) : ?>
<div id="primary_header">
	<h1><?php echo htmlspecialchars( $headers['subject'], ENT_QUOTES, 'UTF-8') ?></h1>
    <div id="back_button">
		<a href="#" id='sendButton'><span class="stronglastword"><?php echo $this->translate('Send my Reply')?></span></a>
		<a href="#" id='toggleThreads'><span class="stronglastword"><?php echo $this->translate('Toggle Threads')?></span></a>
		<a href="#" id='collapseThreads'><span class="stronglastword"><?php echo $this->translate('Collapse Threads')?></span></a>
		<a href="#" id='closeButton'><span class="stronglastword"><?php echo $this->translate('Close')?></span></a>
		<a href="#" id='backToFolder'><span class="stronglastword"><?php echo $this->translate('Back to Folder')?></span></a>
	</div>
</div>

<div id="primary_content" class="">

<?php endif ?>
<form id='composeMessage' class="<?php echo $this->composeID; ?> <?php if($this->hasThreads) { echo "hasThreads"; } else { echo "noThreads"; }  ?> ">
	
	<?php
	    
		if( array_key_exists('reply-to', $headers) )
			$hiddenReplyToSource = htmlspecialchars($headers['reply-to'], ENT_QUOTES, 'UTF-8');
		else
			$hiddenReplyToSource = htmlspecialchars($headers['from'], ENT_QUOTES, 'UTF-8');
		

       	 $ccSender = $headers['cc'];;


$userAccount = $this->UserSettings['Account'];


$ccSender = trim($ccSender);


  $toHtmlspecialcharsCC = str_replace($userAccount, "", $ccSender);

   $toHtmlspecialcharsCC = str_replace('&lt;&gt;', "", $toHtmlspecialcharsCC);
   $toHtmlspecialcharsCC = str_replace('&quot;&quot;', "", $toHtmlspecialcharsCC);
   $toHtmlspecialcharsCC = str_replace('"" <>,', '', $toHtmlspecialcharsCC);
   
		$toHtmlspecialchars = $headers['to'];

$origSender = $this->UserSettings['Account'];
// $origSenderArray = explode('"', $origSender);
// $origSender = $origSenderArray[2];
//print $origSender;
$origSender = trim($origSender);
$firstReplace = '&lt;'.$origSender.'&gt;';

  $toHtmlspecialchars = str_replace($firstReplace, "", $toHtmlspecialchars);
  //print $toHtmlspecialchars;
   $toHtmlspecialchars = str_replace($origSender, "", $toHtmlspecialchars);
   // print $toHtmlspecialchars;
   $toHtmlspecialchars = str_replace('&quot;&quot;', "", $toHtmlspecialchars);
 // print $toHtmlspecialchars;

		
		
		
	    
		//strip out commas for now
		$hiddenReplyToSource = str_replace(',', '', $hiddenReplyToSource);
		
		if( array_key_exists('reply-to', $headers) )
			$hiddenReplyAllToSource = htmlspecialchars( messageHandling::getUniqueAddresses( $headers['reply-to'] . ', ' . $toHtmlspecialchars), ENT_QUOTES, 'UTF-8');
	    else
			$hiddenReplyAllToSource = htmlspecialchars( messageHandling::getUniqueAddresses( $headers['from'] . ', ' . $headers['to']), ENT_QUOTES, 'UTF-8');
		
		if(!isset($headers['cc']))
	    {
		    $headers['cc'] = '';
	    }
	   // $hiddenReplyAllCcSource = htmlspecialchars( messageHandling::getUniqueAddresses( $headers['cc'] ), ENT_QUOTES, 'UTF-8');
	    $hiddenReplyAllCcSource =$toHtmlspecialcharsCC;
		
	?>
	<input type="hidden" name="tabId" value="<?php echo $messagePanelContextName ?>" />
	<input type="hidden" name="composeID" value="<?php echo $messagePanelContextName ?>" />
	<?php //TODO: specify from in composer for future upgrade to altering/selecting fromaddress/Account ?>
	<input type='hidden' name='emailFrom' id='emailFrom' value=''/>
	<input type='hidden' name='hiddenReplyToSource' id='hiddenReplyToSource' value='<?php echo $hiddenReplyToSource ?>'/>
	<input type='hidden' name='hiddenReplyAllToSource' id='hiddenReplyAllToSource' value='<?php echo $hiddenReplyAllToSource ?>'/>
	<input type='hidden' name='hiddenReplyAllCcSource' id='hiddenReplyAllCcSource' value='<?php echo $hiddenReplyAllCcSource ?>'/>
	
	<input type="hidden" name="inlineComposer" id="inlineComposer" value="true" />
	<input type="hidden" name="relatedMessageFolder" id="relatedMessageFolder" value="<?php echo $folderUTF7Urlencoded ?>" /> 
	<input type="hidden" name="relatedMessageUID" id="relatedMessageUID" value="<?php echo $latestThreadChild['messageArray']['headers']['uniqueid'] ?>" />
	<input type="hidden" name="relatedMessageMessageId" id="relatedMessageMessageId" value="<?php echo (isset($headers['message-id']) ? htmlentities($headers['message-id'], ENT_QUOTES, 'UTF-8') : ''); ?>" />
	<input type="hidden" name="relatedMessageResponseType" class="relatedMessageResponseType" value="reply" />
	<input type="hidden" name="relatedDraftUID" class="relatedDraftUID" value="<?php echo $this->relatedDraftUID ?>" />
	<div id="primary_content_inner">
		<div id="message_wrapper">
				<?php echo $this->partial('viewmessage/recursivelyrenderthreads.phtml', $this ); ?> 
			<div class="message reply">
				<div class="message_outer">
			 		<div class="message_inner">
											
			   			<div class="details replyDetails" >
							<h3 class="collapse" style="height: 100%;">
								<div id='recipientsSection' style="display:none;">
									<div id='replyTo'>
										<div class="leftreply">
											<strong><label for="emailTo"><?php print $this->translate('To:')?></label></strong>
										</div>
										<div class="rightreply">
											<div id="form_to">
												<input type="text" name="emailTo" value='' id="emailTo" />
											</div>
										</div>
									</div>
										<div id='reply'>
											<div class="leftreply">
												<strong><label for="emailCc"><?php print $this->translate('Cc:')?></label></strong>
											</div>
											<div class="rightreply">
												<div id="form_cc">
													<input type="text" name="emailCc" value='' id="emailCc" />
												</div>
											</div>
										</div>
										<div id='replyBcc' style="display: none">
											<div class="leftreply">
												<strong><label for="emailBcc"><?php print $this->translate('Bcc:')?></label></strong>
											</div>
											<div class="rightreply">
												<div id="form_bcc">
													<input type="text" name="emailBcc" value='' id="emailBcc" />
												</div>
											</div>
										</div>
										<div id='subject' style="display:none">
										<div class="leftreply">
											<strong><label for="emailSubject"><?php print $this->translate('Subject:')?></label></strong>
										</div>
										<div class="rightreply">
		                                	<div id="subjectHolder">
												<input type="text" id="emailSubject" name="emailSubject" value='<?php echo $reSubject ?>'/>
											</div>
										</div>
									</div>
									<div id='replyAttach'>
										<div class="leftreply">
											<strong><?php print $this->translate('Files:')?></strong>
										</div>
										<div class="rightreply">
		                                	<div id="composerAttachmentsHolder" numberOfAttachmentsCurrentlyIUploading="0"></div>
										</div>
									</div>
								</div>
						
								<div class="YourReply"><strong style="color:#575757;"><label for="replyAll"><?php print $this->translate('Options') ?></label>:</strong>
					    			<input tabindex="0" type="checkbox" id="replyAll" /><?php print $this->translate('Reply To All') ?>
									<span>
										<span id='showRecipientsButton'> | <a tabindex="0" href="#"><?php print $this->translate('Show Recipients')?></a></span>
										<div style="display: inline" id="editSubjectLink"> | <a tabindex="0" id="editSubject" href="#"><?php print $this->translate('Edit Subject')?></a></div>
										<div style="display: inline" id="addBccLink"> | <a tabindex="0" id="addBcc" href="#"><?php print $this->translate('Add Bcc')?></a></div>
									</span>
								</div>
							</h3>
						</div>
			
						<span id='msgReply'></span>
						
			 		</div>
				</div>
			</div> <!-- EO div class message reply -->
		</div> <!-- EO div id message_wrapper -->
	</div> <!-- EO div id primary_content_inner -->
</form>
<?php //echo '<pre>' . print_r($this,1) . '</pre>' ?>	
<?php if(!isset($this->compact)) : ?>
</div> <!-- EO div id primary_content -->
<?php endif ?>
		
<script type="text/javascript" language="JavaScript">

emailTo_handle = null;
emailCc_handle = null;
emailBcc_handle = null;

$( function() 
{	
	$('.buttons a:first-child').focus(function(e){
		$(this).css('outline','1px dotted blue');
	});
	$('.buttons a:first-child').blur(function(e){
		$(this).css('outline','none');
	});
	// move focus to the email body to assist screen readers
	$('iframe.messageIframe', '#<?php echo $messagePanelContextName ?>').focus();
	// does not work to prevent Chrome from entering tab character into RTE
	/*
	$('iframe.messageIframe', '#<?php echo $messagePanelContextName ?>').keydown(function(e){
		console.log(e.target);
		if(e.which == 9){

			e.preventDefault();
			e.stopPropagation();
			$('.buttons div:first-child a:first-child').focus();
			return false;
		}
	});
	*/
	$('div.attachments, a.filename', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) { e.stopPropagation();} );
	var messages = $('.message', '#<?php echo $messagePanelContextName ?>').not('.reply')
	
	messages.bind('click', function(e) { $(this).find('.details, .details-showphoto').trigger('click'); e.stopPropagation();});
	messages.find('.details, .details-showphoto').bind('click', function(e) { toggleThread(this, $(this).parent().parent().parent().attr('msghref')); e.stopPropagation();} );

	$("#sendButton", '#<?php echo $messagePanelContextName ?>').hide();
	
	if('<?php echo $this->UserSettings['DateDisplay'] ?>' != 1)
	{
		$('.received',  '#<?php echo $messagePanelContextName ?>').each( function() { $(this).text(normalDate('<?php echo $this->UserSettings['DateDisplay'] ?>', $(this).attr('title'))) } );
	}
	else
	{
		$('.received',  '#<?php echo $messagePanelContextName ?>').each( function() { $(this).timeago($(this).attr('title')) } );
	}
	function updateTextBoxList( source, dest, autocomplete )
	{
		var $messagePanelContextName = '#<?php echo $messagePanelContextName ?>';
		if( source == null )
		{
			// no source defined, we are most probably clearing the box
			source_values = null;
		}
		else
		{
			source_values = activeSplit($(source, $messagePanelContextName).attr('value'));
		}
		return setTextBoxList( $(dest, $messagePanelContextName), source_values, autocomplete, <?php echo $this->autocompleteCacheSize ?>, <?php echo $this->autocompleteFetchThreshold ?>, <?php echo $this->autocompleteFetchSize; ?>, <?php echo $this->autocompleteMinFetchLength; ?>, '<?php echo $this->moduleBaseUrl ?>' )
	}

	$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('loaded', false);
	var ieReload = $.browser.msie ? {'forceIEReload':<?php echo time() ?>} : null;

	$('#msgReply', '#<?php echo $messagePanelContextName ?>').load(
		'<?php echo $this->moduleBaseUrl ?>viewmessage/reply/messagePanelContextName/<?php echo $messagePanelContextName ?>?v=<?php echo Zend_registry::get('config')->global['version']; ?>',
		ieReload,
		function (responseText, textStatus, XMLHttpRequest) 
		{
	
			$('textarea.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').attr('value', "&nbsp;<div id='replyContainer' style='display:inline;'></div>");
			$('.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').rte(
			{
				focus_after_element: $(".buttons div:first-child a:first-child"),
				<?php if ($this->enableSpellCheck) { ?> content_css_url: '<?php echo $this->siteBaseUrl ?>css/spell.css', <?php } ?>
				content_css_data: 'html { overflow: auto; } ' +
				'.frameBody { font-family: "Helvetica Neue",Helvetica,Arial,sans-serif; font-size: 12px; width: 98%; height: 94%; } ',

				media_url: '<?php echo $this->siteBaseUrl ?>images/rte-light/',
				spellcheck_button: <?php echo $this->enableSpellCheck ? "true" : "false" ; ?>,
				click_callback:function() 
				{ 
					$(this).unbind('click');
					$(this).contents().children("#replyContainer").css('display', 'inline');
					$("#sendButton", '#<?php echo $messagePanelContextName ?>').show();
                                        // perform actions in context of selected tab
					$nodeCheckList = $('#nodeReplyBtnAnchor', '#<?php echo $messagePanelContextName ?>')
					$nodeCheckListLength = $nodeCheckList.length
					var i = $nodeCheckListLength-1;
					while( $($nodeCheckList[i]).parent().parent().parent().parent().parent().parent().children('.body').html().length < 20 && i >= 0  )
						i--
                
					if( $($nodeCheckList[i]).length != 0)
						$($nodeCheckList[i]).trigger('click'); // trigger populating form with correct (last) thread nodes data (in case user had previously clicked reply to other node)
					resizeComposer('<?php echo $messagePanelContextName ?>', true);		
				}
			});
	
			$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('loaded', true);
	
		}
	)
	
	$('.stronglastword', '#<?php echo $messagePanelContextName ?>').each( function() { $(this).stronglastword(); });
	
	$('#editSubject', '#<?php echo $messagePanelContextName ?>').bind('click', function() 
	{
		//only call message body and recipient prep if not done, else will nuke reply test when recalls prep
		if( !$('#recipientsSection', '#<?php echo $messagePanelContextName ?>').is(':visible') )
			$('#showRecipientsButton', '#<?php echo $messagePanelContextName ?>').click()
		$('#subject', '#<?php echo $messagePanelContextName ?>').show()
		$('#editSubjectLink', '#<?php echo $messagePanelContextName ?>').hide()
		resizeComposer('<?php echo $messagePanelContextName ?>', true)
		$('#emailSubject', '#<?php echo $messagePanelContextName ?>').focus();
	})
	
	//set all <a href> links inside messageBody to open in a new window
	$('div.messageBody a', '#<?php echo $messagePanelContextName ?>').each( function() {
		
		//$(this).attr('target', '_blank');
	
	})
	
	$('.showQuotedText').each( function() { $(this).unbind('click').bind('click', function() { return false }) });
	
	// Set the max-width of image attachments for the 2pane & 3pane UI
	resizeImgAttachments('#<?php echo $messagePanelContextName ?>');

	// Find all mailto: links and catch these to open in the message composer tab
	try {

		$('div.messageBody a:mailto', '#<?php echo $messagePanelContextName ?>').each( function() {

			// We are a mailto?
			var href = $(this).attr('href');
			if( !href )
				return;
			
			if( !href.match(/^mailto\:/) )
				return;

			$(this).bind('click', function() 
			{ 
				to = $(this).attr('href').replace('mailto:', '')
				openNewComposerTab( {'to': to } );
				return false;
			
			})

		})
		
	} catch(e) {
		
	}
	
	autocompleteList = new Array();
	emailTo_handle = updateTextBoxList('#hiddenReplyToSource', '#emailTo', autocompleteList);
	emailCc_handle = updateTextBoxList(null, '#emailCc', autocompleteList);
	emailBcc_handle = updateTextBoxList(null, '#emailBcc', autocompleteList);
	
	if( $.jCacher.get('autocomplete') )
	{
		autocompleteList = $.jCacher.get('autocomplete').value
		emailTo_handle.plugins['autocomplete'].setValues(autocompleteList)
		emailCc_handle.plugins['autocomplete'].setValues(autocompleteList)
		emailBcc_handle.plugins['autocomplete'].setValues(autocompleteList)
		
		if(autocompleteList.length >= <?php echo $this->autocompleteFetchThreshold ?>)
		{
			var settings = {
					placeholder: false,
					cacheSize: <?php echo $this->autocompleteCacheSize; ?>,
					minRemoteLength: <?php echo $this->autocompleteMinFetchLength; ?>,
					queryRemote: true,
					remote: {url: '<?php echo $this->moduleBaseUrl ?>/contacts/autocomplete/type/global/limit/<?php echo $this->autocompleteFetchSize; ?>'}
				};
			emailTo_handle.plugins['autocomplete'].setOptions( settings );	
			emailCc_handle.plugins['autocomplete'].setOptions( settings );
			emailBcc_handle.plugins['autocomplete'].setOptions( settings );
		}
		
	}
	else
	{
	
		$.ajax({
			cache:false, 
			url: '<?php echo $this->moduleBaseUrl ?>contacts/autocomplete/limit/<?php echo $this->autocompleteFetchThreshold ?>', 
			dataType: 'json', 
			success: function(r) 
			{
				// above static lookup, enable dynamic lookup
				if(r.length >= <?php echo $this->autocompleteFetchThreshold ?>)
				{
					var settings = {
							placeholder: false,
							cacheSize: <?php echo $this->autocompleteCacheSize; ?>,
							minRemoteLength: <?php echo $this->autocompleteMinFetchLength; ?>,
							queryRemote: true,
							remote: {url: '<?php echo $this->moduleBaseUrl ?>contacts/autocomplete/limit/<?php echo $this->autocompleteFetchSize; ?>'}
						};
					emailTo_handle.plugins['autocomplete'].setOptions( settings );
					emailCc_handle.plugins['autocomplete'].setOptions( settings );
					emailBcc_handle.plugins['autocomplete'].setOptions( settings );
				}
				
				autocompleteList = r
				$.jCacher.add('autocomplete', r, 3600);
				emailTo_handle.plugins['autocomplete'].setValues(r)
				emailCc_handle.plugins['autocomplete'].setValues(r)
				emailBcc_handle.plugins['autocomplete'].setValues(r)
			}

		})
		
	}
	
	
	//hide and bind to show recipients section
	$('#showRecipientsButton', '#<?php echo $messagePanelContextName ?>').bind('click', function() 
	{

		//get last open node
		$nodeCheckList = $('#nodeReplyBtnAnchor', '#<?php echo $messagePanelContextName ?>' )
		$nodeCheckListLength = $nodeCheckList.length
		var i = $nodeCheckListLength-1;
		while( $($nodeCheckList[i]).parent().parent().parent().parent().parent().parent().children('.body').html().length < 20 && i >= 0  )
			i--
		prepResponseFieldsAndContent( $($nodeCheckList[i]).parent().parent() )
		emailTo_handle = updateTextBoxList('#hiddenReplyToSource', '#emailTo', autocompleteList);
		emailCc_handle = updateTextBoxList(null, '#emailCc', autocompleteList);
		emailBcc_handle = updateTextBoxList(null, '#emailBcc', autocompleteList);

		$('#emailBcc', '#<?php echo $messagePanelContextName ?>').hide();
		$('#recipientsSection', '#<?php echo $messagePanelContextName ?>').show();
		$('#showRecipientsButton', '#<?php echo $messagePanelContextName ?>').hide();
		giveInputTitles();
	});

	$('#addBccLink', '#<?php echo $messagePanelContextName ?>').bind('click', function()  
	{ 
		if( !$('#recipientsSection', '#<?php echo $messagePanelContextName ?>').is(':visible') ) 
		{
			$('#showRecipientsButton', '#<?php echo $messagePanelContextName ?>').click()
		}
		$('#replyBcc', '#<?php echo $messagePanelContextName ?>').show(); 
		resizeComposer('<?php echo $messagePanelContextName ?>', true);
		$('#addBccLink', '#<?php echo $messagePanelContextName ?>').hide(); 
		setTimeout('$("#form_bcc INPUT.textboxlist-bit-editable-input:last", "#<?php echo $messagePanelContextName ?>").focus();',100); //appears to be latency issue 
	}); 

	// Support clicking anywhere in the div box to get to the last "bitbox selection"
	$("#form_to", '#<?php echo $messagePanelContextName ?>').bind('click', function() 
	{
		$("#form_to INPUT.textboxlist-bit-editable-input:last", '#<?php echo $messagePanelContextName ?>').focus();
	});

	$("#form_cc", '#<?php echo $messagePanelContextName ?>').bind('click', function() 
	{
		$("#form_cc INPUT.textboxlist-bit-editable-input:last", '#<?php echo $messagePanelContextName ?>').focus();
	});

	$("#form_bcc", '#<?php echo $messagePanelContextName ?>').bind('click', function() 
	{
		$("#form_bcc INPUT.textboxlist-bit-editable-input:last", '#<?php echo $messagePanelContextName ?>').focus();
	});

	//$('#recipientsSection', '#<?php echo $messagePanelContextName ?>').hide()

	//prepare node actions
	$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
	nodeActionsButtonsCloseTimer = null

	$('.arrow, A#nodeReplyAnchor', '.nodeActionsButtons').each( function() {

		$(this).bind('click', function(e) {
			if( nodeActionsButtonsCloseTimer ) {
				clearTimeout(nodeActionsButtonsCloseTimer)
				nodeActionsButtonsCloseTimer = null 
			}
			$('.nodeActionsDropdown', $(this).parent() ).show()
			e.stopPropagation()
		})
	})

	$('.nodeActionsButtons').bind('mouseleave', function() 
	{
	
		nodeActionsButtonsCloseTimer = setTimeout( "$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()", 1000)
	
	})

	$('.nodeActionsButtons').bind('mouseenter', function() 
	{
	
		if( nodeActionsButtonsCloseTimer ) 
		{
		
			clearTimeout(nodeActionsButtonsCloseTimer)
			nodeActionsButtonsCloseTimer = null 
		
		}
		
	})
	
	$('a#nodeImagesAnchor', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		parentDom =  $(this).parent().parent().parent().parent().parent();
		id = parentDom.children('div').attr('id');
		loadImages( parentDom, '<?php echo $this->moduleBaseUrl ?>viewmessage/index/folder/<?php echo $folderUTF7UrlencodedDouble ?>/uniqueId/' + id + '/inline/true/messagePanelContextName/<?php echo $this->messagePanelContextName; ?>' );
		e.stopPropagation();
		$(this).fadeOut('slow');
		return false;
	});
	
	$('a#nodeInfoAnchor', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{

		$(this).parent().parent().parent().parent().parent().each( function() 
		{
		
			if( $('.messageHeadersInfo:first', $(this) ).css('display') == 'none') 
			{
		
				$('.messageHeadersInfo', $(this) ).bind('click', function(e) { e.stopPropagation(); });
				$('.messageHeadersInfo', $(this) ).slideDown('fast');
				$('.messageHeadersRaw', $(this)).hide();
				$('.nodeActionsButtons #viewHeaders a', $(this) ).html('<?php echo $this->translate('View Headers') ?>');
				$('.nodeActionsButtons #viewHeaders a', $(this)).parent().attr('state','hide');
		
			}
			else 
			{
				$('.messageHeadersInfo', $(this) ).unbind('click');
				$('.messageHeadersInfo', $(this)).slideUp('fast');		
				$('.messageHeadersRaw', $(this)).hide();
				$('.nodeActionsButtons #viewHeaders a', $(this)).html('<?php echo $this->translate('View Headers') ?>');
				$('.nodeActionsButtons #viewHeaders a', $(this)).parent().attr('state','hide');
			
			}
		
		})
		
		e.stopPropagation();	
	
	});

	$('.nodeActionsButtons #addToAddressbook a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{	
		$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		emailToString = $('#hiddenReplyAllToSource', '#<?php echo $messagePanelContextName ?>').attr('value');
		emailCcString = $('#hiddenReplyAllCcSource', '#<?php echo $messagePanelContextName ?>').attr('value');
		// Bcc intentionally left out - probably dont want bcc email addresses
		mimeAddresses = emailToString + ', ' + emailCcString
		$.php('<?php echo $this->moduleBaseUrl ?>contacts/addtoaddressbook', $.param({ 'mimeAddresses': emailToString+', '+emailCcString }) )
		$.jCacher.remove('autocomplete')
		$.jCacher.remove('autocomplete_global')
		e.stopPropagation()
	})
	
	$('.nodeActionsButtons #nodeReplyBtnAnchor', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		e.stopPropagation(); 
		if( !$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('loaded') )
		{

			$('#primary_header', '#<?php echo $messagePanelContextName ?>').addClass('loading')
			if( $('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries') == undefined )
				$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries', 0)
			waitingForLoadedRetries = $('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries')
			if( waitingForLoadedRetries < 10 )
			{

				$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries', waitingForLoadedRetries+1 )
				var _this = this
				setTimeout( function() { $(_this).trigger('click') }, 500)
				return                                                                                                            

			}

		}
		$('#primary_header', '#<?php echo $messagePanelContextName ?>').removeClass('loading')
		prepResponseFieldsAndContent( $(this).parent().parent().parent() )
		
		$('.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').rte_focus();
		
		// our emailto/emailcc text boxes are updated in the replyAll checkbox bind below
		$('#replyAll', '#<?php echo $messagePanelContextName ?>').attr('checked', false).change();
<?php if( $this->UserSettings['SaveDrafts'] == '1' ) : ?>
		periodicDraftSaver('<?php echo $messagePanelContextName ?>', '<?php echo $this->composeID; ?>');
<?php endif ?>
		resizeComposer('<?php echo $messagePanelContextName ?>', false, false)
	})
	
	$('.nodeActionsButtons .node-actions .reply-all','#<?php echo $messagePanelContextName ?>').bind('click', function(){
		$('.nodeActionsButtons #replyall a', '#<?php echo $messagePanelContextName ?>').click();
	})

	$('.nodeActionsButtons .node-actions .forward','#<?php echo $messagePanelContextName ?>').bind('click', function(){
		var $context = $(this).parent().parent().parent();
		$('li#forward a', $context).click();
	})

	$('.nodeActionsButtons #replyall a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		e.stopPropagation(); 
		if( !$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('loaded') )
		{

			$('#primary_header', '#<?php echo $messagePanelContextName ?>').addClass('loading')
			if( $('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries') == undefined )
				$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries', 0)
			waitingForLoadedRetries = $('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries')
			if( waitingForLoadedRetries < 10 )
			{

				$('#msgReply', '#<?php echo $messagePanelContextName ?>').data('waitingForLoadedRetries', waitingForLoadedRetries+1 )
				var _this = this
				setTimeout( function() { $(_this).trigger('click') }, 500)
				return                                                                                                            

			}

		}
		$('#primary_header', '#<?php echo $messagePanelContextName ?>').removeClass('loading')
        $('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		prepResponseFieldsAndContent( $(this).parent().parent().parent().parent() )
		$('.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').rte_focus();
		
		// our emailto/emailcc text boxes are updated in the replyAll checkbox bind below
		$('#replyAll', '#<?php echo $messagePanelContextName ?>').attr('checked', true).change();
<?php if( $this->UserSettings['SaveDrafts'] == '1' ) : ?>
		periodicDraftSaver('<?php echo $messagePanelContextName ?>', '<?php echo $this->composeID; ?>');
<?php endif ?>
		resizeComposer('<?php echo $messagePanelContextName ?>')
		
	})

	$('.nodeActionsButtons #forward a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		var uniqueId = $( $(this).parent().parent().parent().parent() ).attr('uniqueId')
		var folder = $('#relatedMessageFolder', '#<?php echo $messagePanelContextName ?>').attr('value')

		forwardMessagesInNewTab( Array(uniqueId), folder )     
		e.stopPropagation()
	
	})
	
	$('.nodeActionsButtons #forwardAsAttachment a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		var uniqueId = $( $(this).parent().parent().parent().parent() ).attr('uniqueId')
		var folder = $('#relatedMessageFolder', '#<?php echo $messagePanelContextName ?>').attr('value')

		forwardMessagesInNewTab( Array(uniqueId), folder, true )     
		e.stopPropagation()
	
	})
	
	$('.nodeActionsButtons #viewHeaders a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		if( $(this).parent().attr('state') == 'hide' )
		{
			$(".messageHeadersInfo", '#<?php echo $messagePanelContextName ?>').hide();
			$(this).parent().attr('state','show')
			$(this).html('<?php echo $this->translate("Hide Headers") ?>')
			$(this).parent().parent().parent().parent().parent().parent().parent().find('.messageHeadersRaw').slideDown('fast')
		}   
		else
		{
			$(this).parent().attr('state','hide')
			$(this).html('<?php echo $this->translate("View Headers") ?>')
			$(this).parent().parent().parent().parent().parent().parent().parent().find('.messageHeadersRaw').slideUp('fast')
		}
		
		e.stopPropagation()
		return false;
	
	})

	$('.nodeActionsButtons #print a, A#nodePrintAnchor', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		printDOMPart( $(this).parent().parent().parent().parent().parent().parent().parent().parent() )
		e.stopPropagation()
		return false;
	
	})

	$('.nodeActionsButtons #markasread a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		icon = $(this).parent().parent().parent().parent().parent().find('#msgIcon')
		$(icon).removeClass('unread')
		if( !$(icon).hasClass('read') )
			$(icon).addClass('read')

		title = $(this).parent().parent().parent().parent().parent().parent().find('h3').not('.showcc');
		if( title.length)
			$(title).removeClass('unread')

		var UID = $(this).parent().parent().parent().parent().attr('uniqueid')
		var folder = $(this).parent().parent().parent().parent().attr('folder')
		var action = moduleBaseUrl + '/mail/flagmessage/flag/seen/appendFlag/true/selectFolder/' + folder + '/mailId/' + UID
		$.php(action)

		updateUIFlags(folder, '#<?php echo $messagePanelContextName ?>');

		e.stopPropagation()
		
	})

	$('.nodeActionsButtons #displayimage a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		var parentDom =  $(this).parent().parent().parent().parent().parent().parent().parent();
		var id = parentDom.children('div').attr('id');
		loadImages( parentDom, '<?php echo $this->moduleBaseUrl ?>viewmessage/index/folder/<?php echo $folderUTF7UrlencodedDouble ?>/uniqueId/' + id + '/inline/true/messagePanelContextName/<?php echo $this->messagePanelContextName; ?>' );
		e.stopPropagation();

		$(this).parent().hide();
	})
	
	$('.nodeActionsButtons #markasunread a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		$('.nodeActionsButtons .nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()

		icon = $(this).parent().parent().parent().parent().parent().find('#msgIcon')

		$(icon).removeClass('read')
		if( !$(icon).hasClass('unread') )
			$(icon).addClass('unread')

		title = $(this).parent().parent().parent().parent().parent().parent().find('h3').not('.showcc');
		if( title.length && !$(title).hasClass('unread') )
			$(title).addClass('unread')

		var UID = $(this).parent().parent().parent().parent().attr('uniqueid')
		var folder = $(this).parent().parent().parent().parent().attr('folder')
		var action = moduleBaseUrl + '/mail/flagmessage/flag/unseen/appendFlag/true/selectFolder/' + folder + '/mailId/' + UID
		$.php(action)

		updateUIFlags(folder, '#<?php echo $messagePanelContextName ?>');

		e.stopPropagation()
		
	})
	
	
	
	function printDOMPart(sourceNode)
	{
		var bodySelector = $(sourceNode).find('.messageBodyOriginal');
		if(!bodySelector.length)
		{
			bodySelector = $(sourceNode).find('.messageBody');
		}
		if ( bodySelector.length > 0 )
		{
	        
			body = bodySelector
			body.find('.showQuotedText').next('blockquote').show();
			body.find('.showQuotedText').remove();
			bodyText = $('<div>').html(html_entity_decode(body.html())).html()
			var headercc = '';
			if( $('#header-cc', '#<?php echo $messagePanelContextName ?>').length > 0 )
				headercc = "<h2><?php echo addslashes($this->translate('Cc')) ?>: " + $('#header-cc', '#<?php echo $messagePanelContextName ?>').html() + "</h2>";
	 		
			var html = "<HTML>\n<HEAD>\n"+
					"<title>" + $('#header-subject', '#<?php echo $messagePanelContextName ?>').html() + "</title>" + 
		            "<link rel=\"stylesheet\" href=\"<?php echo $this->siteBaseUrl; ?>css/reset.css\" type=\"text/css\" media=\"screen, print\" />\n" + 
		            "<link rel=\"stylesheet\" href=\"<?php echo $this->siteBaseUrl; ?>css/printMessage.css\" type=\"text/css\" media=\"screen, print\" />\n" + 
					"</HEAD>\n<BODY style=\"padding:10px; overflow:visible;\">"+ 
		            "<h1><?php echo addslashes($this->translate('Subject')) ?>: " + $('#header-subject', '#<?php echo $messagePanelContextName ?>').html() + "</h1>" +
		            "<h2><?php echo addslashes($this->translate('From')) ?>: " + $('#header-from', '#<?php echo $messagePanelContextName ?>').html() + "</h2>" +
					"<h2><?php echo addslashes($this->translate('To')) ?>: " + $('#header-to', '#<?php echo $messagePanelContextName ?>').html() + "</h2>" + 
					headercc + 
					"<h2>" + $('#header-date', '#<?php echo $messagePanelContextName ?>').html() + "</h2>" +
	                bodyText
			if( $(sourceNode).find('.attachments').length > 0 )
				html = html + $(sourceNode).find('div.attachments').html()
		    html = html + "\n</BODY>\n</HTML>";
			var printWindow = window.open("","printDOMPart");
	        printWindow.document.open();
	        printWindow.document.write(html);
	        printWindow.document.close();
	        printWindow.print();
	    }
	}

	$('.nodeActionsButtons #download a', '#<?php echo $messagePanelContextName ?>').bind('click', function(e) 
	{
		$('.nodeActionsButtonsb.nodeActionsDropdown', '#<?php echo $messagePanelContextName ?>').hide()
		var url = '<?php echo $this->moduleBaseUrl ?>viewmessage/downloadmessage/folder/' + $(this).parent().parent().parent().parent().attr('folder') + '/uniqueId/' + $(this).parent().parent().parent().parent().attr('uniqueid')
		$(this).attr('href',url)
		e.stopPropagation()

	});
	
	// If the reply-all checkbox is ticket on the compose bar
	$('#replyAll', '#<?php echo $messagePanelContextName ?>').bind('change', function() 
	{ 
	
		checked = $(this).is(':checked')
		if( checked ) 
		{
			// Turn the checkbox back on, since the trigger click above set it unchecked
			checked = $(this).attr('checked', true);
			emailTo_handle = updateTextBoxList('#hiddenReplyAllToSource', '#emailTo', autocompleteList);
			emailCc_handle = updateTextBoxList('#hiddenReplyAllCcSource', '#emailCc', autocompleteList);
		}
		else
		{
			emailTo_handle = updateTextBoxList('#hiddenReplyToSource', '#emailTo', autocompleteList);
			emailCc_handle = updateTextBoxList(null, '#emailCc', autocompleteList);
		}
		emailBcc_handle = updateTextBoxList(null, '#emailBcc', autocompleteList);
		giveInputTitles();

		//open recipients section to can see where going to
		$('#recipientsSection', '#<?php echo $messagePanelContextName ?>').show();
		$('#showRecipientsButton', '#<?php echo $messagePanelContextName ?>').hide();
		
		$nodeCheckList = $('#nodeReplyBtnAnchor', '#<?php echo $messagePanelContextName ?>' )
		$nodeCheckListLength = $nodeCheckList.length
		var i = $nodeCheckListLength-1;
		while( $($nodeCheckList[i]).parent().parent().parent().parent().parent().parent().children('.body').html().length < 20 && i >= 0  )
			i--
		prepResponseFieldsAndContent( $($nodeCheckList[i]).parent(), false )
		
		//scroll to bottom
		scrollToComposer(true);
		$('.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').rte_focus();
			
	})

<?php if(!isset($this->currentThreadNode['_children'])) : ?>
	$('#back_button #toggleThreads', '#<?php echo $messagePanelContextName ?>').hide();
	$('#back_button #collapseThreads', '#<?php echo $messagePanelContextName ?>').hide();
<?php elseif(!empty($this->currentThreadNode['_children'])) : ?>
	$('#back_button #toggleThreads', '#<?php echo $messagePanelContextName ?>').show();
	$('#back_button #collapseThreads', '#<?php echo $messagePanelContextName ?>').hide();
<?php else : ?>
	$('#back_button #toggleThreads', '#<?php echo $messagePanelContextName ?>').hide();
	$('#back_button #collapseThreads', '#<?php echo $messagePanelContextName ?>').hide();
<?php endif ?>

	$('#back_button #toggleThreads', '#<?php echo $messagePanelContextName ?>').unbind('click').bind('click', function() 
	{
		$('#back_button #toggleThreads', '#<?php echo $messagePanelContextName ?>').hide();
		$('#back_button #collapseThreads', '#<?php echo $messagePanelContextName ?>').show();

		$('.message_inner .details', '#<?php echo $messagePanelContextName ?>)').each( function() 
		{	
			if($(this).parent().parent().parent().attr('className') == 'message contracted')	
			{
				$(this).trigger('click');
			}
	
		})
	
	})    
	
	$('#back_button #sendButton', '#<?php echo $messagePanelContextName ?>').unbind('click').bind('click', function() {
		$(".sendEmail", '#<?php echo $messagePanelContextName ?>').click();
	})

	$('#back_button #backToFolder', '#<?php echo $messagePanelContextName ?>').bind('click', function() 
	{
		$('#navMessages').tabs('select',0)
		$('#nav').tabs('select',0)
	})

	$('#back_button #closeButton', '#<?php echo $messagePanelContextName ?>').bind('click', function() 
	{
		removeTab( {'name':'#<?php echo $messagePanelContextName ?>'} );
	})

	$('a.ajax').unbind('click').bind('click', function() 
	{
	   	$.php( $(this).attr('href') )
		return false
	
	});

	$('a.ajaxDownload').unbind('click').bind('click', function() 
	{
		$(this).removeAttr('target'); //this eliminates (javascript gragefully disables) the flash when firefox opens a new window then closes it when is gets headers indicating a download			
	
	})

    if($("div.contracted", '#<?php echo $messagePanelContextName ?>').size() > 0)
	{
		$("div.message", '#<?php echo $messagePanelContextName ?>').scrollTop(0);
		
	}
	else
	{
		$("#mail_info", '#<?php echo $messagePanelContextName ?>').scrollTop(0);	
		
	}

	function pretectString(a)
	{
		return a? a : '';
	}

	function prepResponseFieldsAndContent( nodeObj, overwrite ) 
	{
		if(typeof(overwrite) == 'undefined')
			overwrite = true;
		
		if(!overwrite)
		{
			if($('iframe.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').contents().find('body').text().length > 1)
			{
				return;
			}
		}
		
	    //remove click binding
		$('iframe.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').contents().unbind('click');
		
		//pass the nodeOjb which contains the node structure and field attributes
		// N.B. you need this to work around jQuery automagically decoding JSON html entities
		//$('<div/>').text( $( nodeObj ).parent().attr('replyto') ).html()
		//get needed message details for reply 
		var to         		= $('<div/>').text( pretectString( $( nodeObj ).attr('to') )).html()
		var replyto    		= $('<div/>').text( pretectString($( nodeObj ).attr('replyto') )).html()
		var replyallto 		= $('<div/>').text( pretectString($( nodeObj ).attr('replyallto') )).html()
		var replyallcc 		= $('<div/>').text( pretectString($( nodeObj ).attr('replyallcc') )).html()
		var uniqueId   		= $( nodeObj ).attr('uniqueId')
		var sent       		= $('<div/>').text( pretectString( $( nodeObj ).attr('sent')  )).html()
		var subjectOriginal = $('<div/>').text( pretectString($( nodeObj ).attr('subjectOriginal')) ).html()
		var subjectReply    = $('<div/>').text( pretectString($( nodeObj ).attr('subjectReply') )).html()
		var relatedMessageMessageId = $( nodeObj ).attr('relatedMessageMessageId')
        
		$('#emailSubject', '#<?php echo $messagePanelContextName ?>').attr('value', $( nodeObj ).attr('subjectReply') )
		$('#hiddenReplyToSource', '#<?php echo $messagePanelContextName ?>').attr('value', replyto)
		$('#hiddenReplyAllToSource', '#<?php echo $messagePanelContextName ?>').attr('value', replyallto)
		$('#hiddenReplyAllCcSource', '#<?php echo $messagePanelContextName ?>').attr('value', replyallcc)
		$('#relatedMessageUID', '#<?php echo $messagePanelContextName ?>').attr('value', uniqueId)
		$('#relatedMessageMessageId', '#<?php echo $messagePanelContextName ?>').attr('value', relatedMessageMessageId)

		//set body content to body of node (prepared)
		
		nodeHeader = '<br /><?php echo $this->translate('----- Original Message -----') ?><br />' + getReplyHeader('<?php echo htmlspecialchars($headers['from']) ?>', to, sent, subjectOriginal, replyallcc)
		nodeBodySelector = $( nodeObj ).parent().parent().parent().children('.body');
		if(nodeBodySelector.children('.messageBodyOriginal').length)
		{
			nodeBodySelector = nodeBodySelector.children('.messageBodyOriginal');
		}
		else
		{
			nodeBodySelector = nodeBodySelector.children('.messageBody');
		}
		nodeBody = getPreparedReplyBody( nodeBodySelector )
		iframeContentsObject = $('iframe.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').contents()
		iframeContentsObject.find('body').html('&nbsp;<BR/>' + $("#EmailSignature.Signature").html() + '<br /><blockquote>' + nodeHeader + nodeBody + '</blockquote>')

		//open recipients section to can see where going to
		$('#recipientsSection', '#<?php echo $messagePanelContextName ?>').show();
		$('#showRecipientsButton', '#<?php echo $messagePanelContextName ?>').hide();
	}

	function getReplyHeader(from, to, sent, subject, cc) {

		if( cc != undefined)
			ccString = '<div id="origionalMessageSentField" style="display: inline; font-weight:bold;"><?php echo $this->translate('Cc:') ?></div>' + cc + '<br />'
		else
		 	ccString = ''
		return '<div id="origionalMessageFromField" style="width:100%; display: inline; background: rgb(228, 228, 228);"><div style="display: inline; font-weight:bold;"><?php echo $this->translate('From:') ?></div> ' + from + '</div><br />' + 
		'<div id="origionalMessageToField" style="display: inline; font-weight:bold;"><?php echo $this->translate('To:')?></div>' + to + '<br />' + 
		ccString + '<div id="origionalMessageSentField" style="display: inline; font-weight:bold;"><?php echo $this->translate('Sent:') ?></div>' + sent + '<br />' + 
		'<div id="origionalMessageSubjectField" style="display: inline; font-weight:bold;"><?php echo $this->translate('Subject:') ?></div>' + subject + '<br />' + 
		'<br /><br />';

	}

	// On the window resize, make the composer neat for the height position
	$(window).resize(function()
	{
		if( $('iframe.rte-zone-reply', '#<?php echo $messagePanelContextName ?>').hasClass('iframe\\.rte-zone-expand') )
		{
			resizeComposer('<?php echo $messagePanelContextName ?>', true, false);
		}
		else
		{
			// resize image attachments on resize
			resizeImgAttachments('#' + '<?php echo $messagePanelContextName ?>');
		}
		
		//resize any iframes
		$('iframe.messageIframe').each(
			function()
			{
				prepMessageIframeHeight( $(this) );
			}
		)
	});
    
	resizeComposer('<?php echo $messagePanelContextName ?>');
	
	$('#back_button #collapseThreads', '#<?php echo $messagePanelContextName ?>').unbind('click').bind('click', function() 
	{
		$('#back_button #collapseThreads', '#<?php echo $messagePanelContextName ?>').hide();
		$('#back_button #toggleThreads', '#<?php echo $messagePanelContextName ?>').show();

		$('.message_inner .details', '#<?php echo $messagePanelContextName ?>').each( function() 
		{	
			
			if($(this).parent().parent().parent().attr('className') != 'message contracted')	
			{
				$(this).trigger('click');
			}
	
		})
	
	})
	
	$('#attachments_id', '#<?php echo $messagePanelContextName ?>').unbind().bind('click', function(e) 
	{
		// $("div.message", '#<?php echo $messagePanelContextName ?>').scrollTop(0);
		e.stopPropagation();
		location.hash = '#attachments';
	}) 
	
<?php if( isset($headers['x-confirm-reading-to']) && !$this->seen ) : ?>

	if( confirm('<?php echo addslashes($this->translate("A read receipt has been requested, would you like to send the read receipt?")) ?>') )
		$.php('<?php echo $this->moduleBaseUrl ?>viewmessage/sendreadreceipt', $.param({ 'folder': '<?php echo $this->folderUTF7 ?>', 'uniqueId': '<?php echo $latestThreadChild['messageArray']['headers']['uniqueid'] ?>' }) )
		
<?php 	endif ?>

	//now bind a scroll updater to update stored scroll position so we can refer back to it when switching tabs beck to this one
	//2 pane
	$('#primary_content', '#<?php echo $messagePanelContextName ?>').data('OldScrollPos', 0);
	$('#primary_content', '#<?php echo $messagePanelContextName ?>').bind('scroll', function() { $(this).data('OldScrollPos', $(this).scrollTop()) })
	//3 pane
	$('#mail_info', '#<?php echo $messagePanelContextName ?>').each( function() 
	{ 
	
		$(this).data('OldScrollPos', 0);
		$(this).bind('scroll', function() { $(this).data('OldScrollPos', $(this).scrollTop()) })
	
	})

	var folder = $('#relatedMessageFolder', '#<?php echo $messagePanelContextName ?>').attr('value')
	updateUIFlags(folder, '#<?php echo $messagePanelContextName ?>');

})

function giveInputTitles()
{
	$('#form_to').find('li.textboxlist-bit-editable input:first').attr('title','Email recipients');
	$('#form_cc').find('li.textboxlist-bit-editable input:first').attr('title','Carbon copy recipients');
	$('#form_bcc').find('li.textboxlist-bit-editable input:first').attr('title','Blind carbon copy recipients');
}

<?php if ($this->inSpamFolder): ?>
$('#action_junk', "#Email").hide();
$('#action_not_junk', "#Email").show();
<?php endif; ?>
</script>
<?php }



