<div id="primary_header">
	<table class="messages" >
		<thead>
			<tr>
				<th class="unread">Unread, replied to or flagged</th>
				<th class="checkBox">Checkbox</th>
				<th class="from"><?php

				if( 
					strtolower($this->currentFolder) == strtolower($this->AtmailMailStorageMain->getMainFolderName('Sent')) 
					|| strtolower($this->currentFolder) == strtolower($this->AtmailMailStorageMain->getMainFolderName('Drafts'))
				)
				{
					echo $this->translate('To');
				}
				else
				{
					echo $this->translate('From');
				}
				
				?></th>
				<th class="subject"><?php print $this->translate('Subject') ?></th>
				<th class="date"><?php echo $this->translate('Date') ?></th>
				<th class="attachments"><img src="<?php echo $this->siteBaseUrl; ?>images/icons/attachment.gif" alt="Attachment" height="14" width="7"/></th>
				<th class="size"><?php print $this->translate('Size')?></th>
			</tr>
		</thead>
	</table>
</div>
<div id="primary_content" class="banner-sky-off">
    <div id="primary_content_inner">
		<form id='messagesListForm' class='messagesListForm'>
<?php if( $this->searching ) : ?>
			<input type="hidden" name="searching" id="searching" value="true" />
			<input type="hidden" name="searchQuery" id="searchQuery" value="<?php echo urlencode( urlencode( $this->searchQueryUTF8 ) ) ?>" />
<?php endif; ?>
			<input type="hidden" name="resultContext" id="resultContext" value="<?php echo $this->resultContext ?>" />
			<input type="hidden" name="listFolder" id="listFolder" value="<?php echo $this->currentFolderDoubleURLEncoded ?>" />
			<input type="hidden" name="pageNumber" id="pageNumber" value="<?php echo $this->pageNumber ?>" />
			<table class="messages" id="messageListTable" style="margin-top:-33px">
<thead>
      <tr>
        <th class="unread" style="text-indent:-1000px">Unread, replied to or flagged</th>
        <th class="checkBox"style="text-indent:-1000px">Checkbox</th>
        <th style="text-indent:-10000px;" class="from"><?php

        if(
          strtolower($this->currentFolder) == strtolower($this->AtmailMailStorageMain->getMainFolderName('Sent'))
          || strtolower($this->currentFolder) == strtolower($this->AtmailMailStorageMain->getMainFolderName('Drafts'))
        )
        { 
          echo $this->translate('To');
        }
        else
        {
          echo $this->translate('From');
        }
         ?></th>
        <th style="text-indent:-10000px" class="subject"><?php print $this->translate('Subject') ?></th>
        <th style="text-indent:-10000px" class="date"><?php echo $this->translate('Date') ?></th>
        <th style="text-indent:-10000px;color:white;" class="attachments">Attachment</th>
        <th style="text-indent:-10000px;color:white" class="size"><?php print $this->translate('Size')?></th>
      </tr>
    </thead>

				<tbody>
<?php
				
				$messagesC = count( $this->messages );
				for($a=0 ; $a<$messagesC ; $a++ )
				{   
				
					if( $this->threadsEnabled ) 
					{
						$message = $this->AtmailMailStorageMain->findLatestThreadChild( $this->messages[$a] );
						$totalChildren = $this->messages[$a]['_totalChildren'];
						$flags = $this->AtmailMailStorageMain->combineThreadFlags( $this->messages[$a] );
						$message['unseenCount'] = $totalChildren - (isset($flags[Zend_Mail_Storage::FLAG_SEEN])? $flags[Zend_Mail_Storage::FLAG_SEEN] : 0);
					}
					else
					{
						$message = $this->messages[$a];
						$totalChildren = 0;
						$flags = $message['FLAGS'];
						$message['unseenCount'] = (isset($flags[Zend_Mail_Storage::FLAG_SEEN])?0:1);
					}
									
				    $header = $message['_basicHeaders'];
	
					$msgIconText = '';
					if(isset($flags[Zend_Mail_Storage::FLAG_ANSWERED])){
						$msgIcon = 'reply';
						$msgIconText = 'This message has been replied to';
					} else if(isset($flags[Zend_Mail_Storage::FLAG_SEEN])) {
						$msgIcon = 'read';
						$msgIconText = 'This message has been read';
					} else {
						$msgIcon = 'unread';
						$msgIconText = 'This message is unread';
					}

					if(isset($flags[Zend_Mail_Storage::FLAG_FLAGGED])){
						$msgIcon .= " flagged";
						$msgIconText .= " and is flagged";
					}
					
					if( mb_strpos($this->currentFolder, $this->AtmailMailStorageMain->getMainFolderName('Sent')) !== false 
					||  mb_strpos($this->currentFolder, $this->AtmailMailStorageMain->getMainFolderName('Drafts')) !== false ) 
						$address = htmlentities(mb_convert_encoding($header['to'],"UTF-8"), ENT_COMPAT | ENT_QUOTES | ENT_IGNORE, 'UTF-8'); //ENT_IGNORE only added in 5.3.0 onwards
					else
						$address = htmlentities(mb_convert_encoding($header['from'],"UTF-8"), ENT_COMPAT | ENT_QUOTES | ENT_IGNORE, 'UTF-8'); //ENT_IGNORE only added in 5.3.0 onwards
						
					if( is_array($header['subject']) )
						$header['subject'] = $header['subject'][0];
						
					$subject = htmlspecialchars($header['subject'], ENT_NOQUOTES, 'utf-8');
					
					$timestr = timeago(strtotime($header['date'])); 
					if ($timestr != '')
					{
						$timeAgo = $timestr . ' ' . $this->translate('ago');
					}
					
					// define a title for the checkboxes to make for more descriptive content for screen readers
					$checkboxTitle = ((!isset($flags[Zend_Mail_Storage::FLAG_SEEN]))? "Unread, " : "") . "sent $timeAgo Subject: $subject from $address" . $this->translate("Press enter to open");
?>
<?php 
					$threadUIDsString = '';
					if( $totalChildren < 2 && !$this->searching ) 
					{
						$threadChildrenUIDs = 'false';
						$threadUIDsString = ' threadChildrenUIDs="' . $threadChildrenUIDs . '"';
						//TODO: total up total thread unread count for updating folders on DnD, backend and click handlers ready.
					}
					?>
					<tr class="<?php echo (!isset($flags[Zend_Mail_Storage::FLAG_SEEN]) ? 'unread' : '') ?> messageItem"<?php echo $threadUIDsString ?> id="<?php echo $message['UID'] ?>">
						<td class="unreadImg">
							<span id="msgIcon" class="<?php echo $msgIcon; ?>"></span><span class="offscreen"><?php echo $msgIconText ?></span>
						</td>
						<td class="checkBox">
						  <label for="msg<?php echo $message['UID'] ?>" class="offscreen"><?php echo str_replace('"','',$checkboxTitle) ?></label>
							<input tabindex="0" id="msg<?php echo $message['UID'] ?>" type="checkbox" name="mailId[]" value="<?php echo $message['UID'] ?>"  class="messageCheckbox" />
							<input type="hidden" name="unseen[<?php echo $message['UID'] ?>]" value="<?php echo $message['unseenCount']; ?>" class="unseenStatus" />
						</td>
						<td class="from" title="<?php echo $address ?>">
							<?php echo $address ?>
							<?php if( $totalChildren != null && $totalChildren != 1 ) echo '(' . $totalChildren . ')' ?>
						</td>
<?php if( isset($message['error']) && $message['error'] == true ) : ?>
					     	<td class="subject"><?php echo $this->translate("Error reading message") ?></td>
						 	<td class="date <?php echo 'dateFormat' . $this->UserSettings['DateDisplay']; ?>" id="date"></td>
							<td class="attachments"></td>
							<td class="size"></td>
<?php else : ?>
						<td class="subject">
							<?php
							//render custom message indicators from plugins
							$this->currentMessage = $message;
							$this->pluginCustomMessageListIndicators = '';
							$this->pluginCall('customMessageListIndicators', $this); 
							echo $this->pluginCustomMessageListIndicators;
							
							echo $subject;
						
							if($this->UserSettings['enableMessagePreview'] === '1' && isset($message['_preview']))
								echo "<font class='preview'> - " . strip_unsafe_tags($message['_preview']) . "</font>";
							?>	
						</td>
			<?php
					$timestr = timeago(strtotime($header['date'])); 
					if ($timestr != '')
					{
											$timeAgo = $timestr . ' ' . $this->translate('ago');
									
									$timestrapart = explode(' ',$timestr);
						$timestr = $timestrapart[0];
						$timestr = '-'.$timestr.' hours'; 
						$headerTime = htmlentities($header['date'], null, 'UTF-8');
					$timeDate = date("Y-m-d H:i",strtotime($headerTime));
						//$timeDate = date('Y-m-d  H:i', strtotime($timestr));
						//echo $timeDate;
					}
					?>
			
					
						<td class="date <?php echo 'dateFormat' . $this->UserSettings['DateDisplay']; ?>" id="date" title="<?php echo $timeDate; ?>"><?php echo $timeDate ?></td>
						<td class="attachments">
							<?php if( !isset($message['attachmentCount']) ) echo '?'; elseif( $message['attachmentCount'] > 0) echo $message['attachmentCount'] ?>
							<?php if( !isset($message['attachmentCount']) || $message['attachmentCount'] > 0): ?>
								<img src="<?php echo $this->siteBaseUrl; ?>images/icons/attachment.gif" alt="Attachment" height="14" width="7" />
							<?php endif; ?>
						</td>
						<td class="size"><?php echo htmlentities(bytesToHumanReadable($message['RFC822.SIZE'])) ?></td>
<?php endif; ?>
					</tr>
				<?php } ?>  
				</tbody>
			</table>
		</form>
				
		<?php 
			//prep search vars to append to sort and pagination URLs
			$postAppend = '';
			if( $this->searching )
			{
				$searchQueryUrlEncodedDouble = urlencode( urlencode( $this->searchQueryUTF8 ) );
				$postAppend = '/searching/true/resultContext/' . $this->resultContext . '/searchQuery/' . $searchQueryUrlEncodedDouble;
			}
?>
<?php 	if( $this->totalMessages == 0 ) : ?>
<?php 		if( $this->threadsEnabled ) : ?>
<?php 			$threadLimit = $this->UserSettings['ThreadLimit']; ?>
		<div style="margin:10px;">&nbsp;<?php echo ($threadLimit==0?$this->translate("No messages found."):$this->translate("No threads match the $threadLimit month criteria.")) ?></div> 
<?php 		elseif( isset($this->textSearch) && $this->textSearch == true ) : ?>
		<div style="margin:10px;">
			&nbsp;<?php echo $this->translate('No matches in this folder over the last year') ?><br />
		</div>
<?php 		elseif( $this->searching ) : ?>
		<div style="margin:10px;">
			&nbsp;<?php echo $this->translate($this->noMessageText) ?><br />
		</div> 
<?php 		else : ?>
		<div style="margin:10px;">&nbsp;<?php echo $this->translate('No messages in this folder') ?></div> 
<?php 		endif; ?>
<?php 	endif; ?>
	</div>
	
</div>

	<div id="banner-skyscraper" style="display: none;"></div>

<script type="text/javascript" language="JavaScript">
	$( function() {
<?php 	if( $this->totalMessages > $this->pageVolume ) : ?>
		$('#messagesListForm',  '#<?php echo $this->resultContext; ?>').createPagnation('#<?php echo $this->resultContext; ?>', '<?php echo $this->siteBaseUrl; ?>', '<?php echo $this->moduleBaseUrl; ?>', '<?php echo $this->pageNumber; ?>', '<?php echo $this->totalMessages; ?>', '<?php echo $this->pageVolume ?>', '<?php echo urlencode(urlencode($this->currentFolder)); ?>', '<?php echo $postAppend ?>');
<?php endif; ?>
<?php if( isset($this->sort) && $this->sort != '' && isset($this->order) && $this->order != '' ) : ?>
		// Add the toggle depending on our sort
		$('#primary_header .messages .<?php echo ($this->sort=='to'?'from':($this->sort=='arrival'?'date':$this->sort)) ?>', '#<?php echo $this->resultContext; ?>').addClass('<?php echo $this->order ?>');    
<?php endif; ?>
		if('<?php echo $this->UserSettings['DateDisplay'] ?>' != 1)
		{
			$('#date', '#messageListTable', '#<?php echo $this->resultContext; ?>').each(function () { $(this).text(normalDate('<?php echo $this->UserSettings['DateDisplay'] ?>', $(this).attr('title'))); });
		}
		else
		{
			$('#date', '#messageListTable', '#<?php echo $this->resultContext; ?>').each(function () { $(this).timeago($(this).attr('title')); });
		}	
		// Add the sort handlers
		/*
		$('#primary_header .messages .from', '#<?php echo $this->resultContext; ?>').bind('click', function() 
		{
		
			<?php if( $this->sort != 'from' && $this->sort != 'to' ) : // default sort to desc if not curently sorted col (eliminates situation where clicking on a new column to sort could have nosort) ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/from/order/asc<?php echo $postAppend ?>')
			<?php elseif($this->order == 'desc' ) : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/nosort/1<?php echo $postAppend ?>')
			<?php elseif($this->order == 'asc') : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/from/order/desc<?php echo $postAppend ?>')
			<?php else : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/from/order/asc<?php echo $postAppend ?>')	
			<?php endif ?> 
		
		});
		
		$('#primary_header .messages .subject', '#<?php echo $this->resultContext; ?>').bind('click', function() 
		{
		
			<?php if($this->sort != 'subject') : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/subject/order/asc<?php echo $postAppend ?>')
			<?php elseif($this->order == 'desc') : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/nosort/1<?php echo $postAppend ?>')
			<?php elseif($this->order == 'asc') : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/subject/order/desc<?php echo $postAppend ?>')
			<?php else : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/subject/order/asc<?php echo $postAppend ?>')	
			<?php endif ?>
		
		});
		
		$('#primary_header .messages .date', '#<?php echo $this->resultContext; ?>').bind('click', function() 
		{
		
			<?php if($this->sort != 'date' && $this->sort != 'arrival') : // ARRIVAL = received time, DATE = sent time //first sort click order ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/date/order/desc<?php echo $postAppend ?>')
			<?php elseif($this->order == 'desc') : //subsequent click will reverse sort ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/date/order/asc<?php echo $postAppend ?>')
			<?php elseif($this->order == 'asc') : //subsequent click will remove sort ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/nosort/1<?php echo $postAppend ?>')
			<?php else : //subsequent click will sort by default again ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/date/order/desc<?php echo $postAppend ?>')	
			<?php endif ?> 
		
		});

		// TODO: Find out how to implement IMAP sort for attachments
		//$('#primary_header .messages .attachments').bind('click', function() { $.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/sort/from<?php echo ($this->order == 'desc')?'/order/asc':'/order/desc' ?>') } );

		$('#primary_header .messages .size', '#<?php echo $this->resultContext; ?>').bind('click', function() 
		{
		
			<?php if($this->sort != 'size') : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/size/order/desc<?php echo $postAppend ?>')
			<?php elseif($this->order == 'desc') : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/size/order/asc<?php echo $postAppend ?>')
			<?php elseif($this->order == 'asc') : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/nosort/1<?php echo $postAppend ?>')
			<?php else : ?>
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded ?>/sort/size/order/desc<?php echo $postAppend ?>')	
			<?php endif ?>
		
		});
*/		
		$('tr.messageItem td:not(.checkBox)', '#<?php echo $this->resultContext; ?>').bind('click', function(e) 
		{
			e.stopPropagation();
			e.preventDefault();

		  var chk = $(this).parent().find('input[type=checkbox]')[0];
			viewMessageClicked( $(this).parent() );
			chk.checked = "checked";
		
		})
		
		$('tr.messageItem .messageCheckbox', '#<?php echo $this->resultContext; ?>').bind('click', function() { toggleMail(this, '#<?php echo $this->resultContext; ?>'); });		
		
		
		$('#pageSelect', '#<?php echo $this->resultContext; ?>').bind('change', function() 
		{
		
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/selectFolder/<?php echo $this->currentFolderDoubleURLEncoded . $postAppend ?>/page/' + this.value);
		
		})
				
		// Setup the DnD ability
		$(".messageItem", '#<?php echo $this->resultContext; ?>').draggable({

			helper: function() { return dragMessages( $(this),  '#<?php echo $this->resultContext; ?>') },
			stop: function() { return dragMessagesStop( $(this),  '#<?php echo $this->resultContext; ?>' ) }, 
			appendTo:'#draggableMessagesContainer',
			cursor:'move',
			scroll:false,
			containment: 'body',
			distance:10,
			cursorAt:{top:15,left:48},
			revert: "invalid",
		  	revertDuration: 300
		})
				
		// Prevent the DND selecting the "text" on the page in Safari/Chrome
		$(".messageItem", '#<?php echo $this->resultContext; ?>').each(function() {
			this.onselectstart = function() { return false; };
		});

		// Allow the "Enter" key to open emails, not just mouse click
		$('.messageCheckbox', '#<?php echo $this->resultContext; ?>').keydown(function(e){
			if (e.which == 13) {
				viewMessageClicked($(this).parent().parent());
			}
		});
		
		//CTRL+click modifiers
		var previouslyClickedIndex = 0;
		var justClickedIndex = 0;
		$('.messageCheckbox', '#<?php echo $this->resultContext; ?>').click( function(e) 
		{
			
			var row = $(this).parent('td').parent('tr');
			var index = $(row).parent().children('tr').index($(row));
			
			if(e.shiftKey) 
			{
			    
				//multiselect
				//get previous and current checkbox and select all
				start = index<previouslyClickedIndex?index:previouslyClickedIndex;
				end = index>previouslyClickedIndex?index:previouslyClickedIndex;
				howMany = end-start-1;
				checkedState = true;
				//check all the ones in between
				$(row).parent().children('tr:gt(' + start + '):lt(' + howMany + ')').each( function(i) 
				{				
					$(this).children('.checkBox').children('input.messageCheckbox').attr('checked', checkedState);
					$(this).addClass('selected');					
				})
				
			    //For consistency with other CTRL+click UIs, retun here and dont overite current prev so that further clicks will still work from prev
				//CONSIDER: remember new justClicked so that further clicks will undo selected if clicked in between
				//justClickedIndex = index
				return;  
			}
			
			if(e.ctrlKey)
			{
			    // Ctrl+Click
			}
			
			if(e.altKey) 
			{
				//single select
			    // Alt+Click
			}
			previouslyClickedIndex = index;
			
		})
		
		<?php if( $this->searching && $this->totalMessages > 0) : ?> 
		var queryString = '<?php echo $this->searchQueryUTF8 ?>';
		$.each(queryString.split(" "), function(idx, val) 
		{ 
			
			if( val == 'subject:' || val == 'to:' || val == 'from:' || val == 'body:' || val == 'text:' )
				return
			if( val.substring(0,3) == 'to:' )
				val = val.substring(3);
			if( val.substring(0,5) == 'from:' )
				val = val.substring(5);
			if( val.substring(0,5) == 'body:' )
				val = val.substring(5);
			if( val.substring(0,5) == 'text:' )
				val = val.substring(5);
			if( val.substring(0,8) == 'subject:' )
				val = val.substring(8);
			if(val != '') 
				$('#<?php echo $this->resultContext; ?>').highlight( val ); 
		});
		<?php endif; ?>
		enableMailActions();
		
		$('#primary_content', '#<?php echo $this->resultContext; ?>').data('OldScrollPos', 0);
		$('#primary_content', '#<?php echo $this->resultContext; ?>').bind('scroll', function() { $(this).data('OldScrollPos', $(this).scrollTop()); } );
	
		//check one folder at a time periodically for new messages
<?php if($this->UserSettings['AutoReload'] > 0) : ?>
		checkAutoReload('<?php echo $this->moduleBaseUrl ?>', '<?php echo $this->currentIdsMd5 ?>', '#<?php echo $this->resultContext; ?>' );
<?php endif ?>
	})
$("#skip-link").focus();
</script>

