
<div id="Flash" class="flash_notice" aria-live="polite"></div>
<?php

//we need this higher up for uniquely addressing the header subject line as well so check it it has already been set first
if( !isset($this->composeID) )
{
	
	$this->composeID = 'uid' . substr(md5(microtime()),0,10); //shortened it cos appears jQuery has a limit on the selector length
	
}

$toHtmlspecialchars = '';

if( isset( $this->to ) && $this->to == "unknown")
{
	unset($this->to);
}

if( isset( $this->messageArray['headers']['to'] ) && $this->messageArray['headers']['to'] == "unknown")
{
	unset($this->messageArray['headers']['to']);
}

if( isset( $this->to ) )
{
	
	$toHtmlspecialchars = htmlspecialchars($this->to, ENT_QUOTES, 'UTF-8');
    
}

if( isset( $this->messageArray['headers']['to'] ))
{
    
   	$toHtmlspecialchars = htmlspecialchars( $this->messageArray['headers']['to'], ENT_QUOTES, 'UTF-8');
	
$origSender = $this->messageArray['headers']['from'];
$origSenderArray = explode('"', $origSender);
$origSender = $origSenderArray[2];
//print $origSender;
$origSender = trim($origSender);
$firstReplace = '&lt;'.$origSender.'&gt;';
//print $origSender .'<br />';

//print $firstReplace .'<br />';

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

 $ccSender = $this->messageArray['headers']['cc'];


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

//print '1. ' .$ccSender;

 //$ccSenderArray = explode('"', $ccSender);
 //$ccSender = $ccSenderArray[2];


$ccSender = trim($ccSender);



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

   $toHtmlspecialcharsCC = str_replace('&lt;&gt;', "", $toHtmlspecialcharsCC);
   $toHtmlspecialcharsCC = str_replace('&quot;&quot;', "", $toHtmlspecialcharsCC);
   $toHtmlspecialcharsCC = str_replace('"" <>,', '', $toHtmlspecialcharsCC);

 //  print '4. ' .$toHtmlspecialcharsCC;

}

?>

<form id="composeMessage" class="<?php echo $this->composeID; ?> <?php if($this->hasThreads) { echo "hasThreads"; } else { echo "noThreads"; }  ?> ">
	<?php if( $this->standalone == true ) : ?>
	<input type="hidden" name="standalone" value="true" />
	<?php endif; ?>		
	<input type="hidden" name="tabId" value="<?php echo $this->tabId ?>" />
	<input type="hidden" name="composeID" value="<?php echo $this->composeID ?>" />
	<input type="hidden" name="relatedMessageFolder" class="relatedMessageFolder" value="<?php echo $this->relatedMessageFolder ?>" />
	<input type="hidden" name="relatedMessageUIDs" class="relatedMessageUIDs" value="<?php echo $this->relatedMessageUIDs ?>" />
	<input type="hidden" name="relatedMessageMessageId" class="relatedMessageMessageId" value="<?php echo  $this->relatedMessageMessageId ?>" />
	<input type="hidden" name="relatedMessageResponseType" class="relatedMessageResponseType" value="<?php echo $this->relatedMessageResponseType ?>" />
	<input type="hidden" name="relatedDraftUID" class="relatedDraftUID" value="<?php echo $this->relatedDraftUID ?>" />
	<input type="hidden" name="readReceiptRequested" class="readReceiptRequested" value="false" />
	<?php $this->pluginCall('composerGetCustomHeaders', $this); if( isset($this->pluginCustomHeaders) ) echo $this->pluginCustomHeaders; ?>
	
	
	<div id="message_wrapper">
	<div class="message reply expanded">
	  	<div class="message_outer">
			<div class="message_inner">
				<div class="composedetails">
				<div class="details">
					
					<h3 class="collapse">
						<div class="leftcompose">
					  <strong><label for="emailTo"><?php print $this->translate('To')?></label>:</strong>
						</div>
						<div class="rightcompose">
					  	<div id="form_to">
							<!-- <input tabindex="0" type="text" name="emailTo" value="<?php echo $toHtmlspecialchars ?>" id="emailTo" /> -->
						<input type="text" name="emailTo" value="<?php echo $toHtmlspecialchars ?>" id="emailTo" />
						</div>
						
					</div>
					<div class="leftcompose">
			<strong><label for="emailSubject"><?php print $this->translate('Subject')?></label>:</strong>
			</div>
			<div class="rightcompose">
				<div id="form_subject" class="focus_subject">
					<?php if( isset($this->messageArray['headers']['subject']) ) : ?>
					<input tabindex="0" id="emailSubject" class="subject es<?php echo $this->composeID ?>" type="text" name="emailSubject" modified="true" value="<?php echo htmlspecialchars($this->messageArray['headers']['subject'], ENT_QUOTES, 'UTF-8') ?>" />
					<?php else : ?>
					<input tabindex="0" id="emailSubject" class="subject es<?php echo $this->composeID ?> default" type="text" name="emailSubject" modified="false" value="<?php echo addslashes($this->translate('No Subject')) ?>" />
					<?php endif; ?>
				</div>
			</div>
		<div id="leftcompose-more" tabindex="0">
			<div class="compose-more-txt"><strong><?php print $this->translate('More')?>:</strong></div>
			<div class="compose-more"></div>
		</div>
		
		<div id="show-more"<?php if( !isset($this->type) || $this->type != 'replyall' ) : ?> display="none"<?php endif; ?>>
			<div class="leftcompose">
				<strong><label for="emailCc"><?php print $this->translate('Cc:')?></label></strong>
			</div>
			<div class="rightcompose">
  					<div id="form_cc">
						<input type="text" tabindex="0" name="emailCc" value='<?php echo $toHtmlspecialcharsCC ?>' id="emailCc" />
					</div>
			</div>
			<div class="leftcompose">
				<strong><label for="emailBcc"><?php print $this->translate('Bcc:')?></label></strong>
			</div>
			<div class="rightcompose">
  				<div id="form_bcc">
					<input type="text" name="emailBcc" value='<?php echo htmlspecialchars(!empty($this->messageArray['headers']['x-atmail-bcc'])?$this->messageArray['headers']['x-atmail-bcc']:'', ENT_QUOTES, 'UTF-8') ?>' id="emailBcc" />
				</div>
			</div>
			
			<div class="leftcompose" id='composeAttachleft'>
				<strong><?php print $this->translate('Files:')?></strong>
			</div>
			<div id="composeAttachrightOuter">
			<div class="rightcompose" id='composeAttachright'>
               	<ul id="composerAttachmentsHolder" numberOfAttachmentsCurrentlyIUploading="0">
<?php
						
//render existing attachments if editing existing draft

if( count($this->messageArray['attachmentsList']) > 0 ) 
{
	
	$attachments = $this->messageArray['attachmentsList'];

	$attachmentArrayId = 0;

	foreach( $attachments as $attachment )
	{ 

		$fileUniqueId = preg_replace('/[^a-zA-Z0-9]*/','', $attachment['filenameFS']);
		$attachmentFilenameOriginal = $attachment['filenameOriginal'];
		$attachmentFilenameOriginalUrlEncoded = urlencode( $attachmentFilenameOriginal );
		$attachmentFilenameFS = $attachment['filenameFS'];
		$attachmentFilenameFSUrlencoded = urlencode( $attachmentFilenameFS );

		$attachmentMimeType = $attachment['mimeType'];
		$sizeHuman = bytesToHumanReadable($attachment['sizeRaw']);
		$icon = $attachment['iconClass'];
		$attachmentHTML = '
					<li class="attachment" id="' . $fileUniqueId .'">
						<div>
							<input type="hidden" name="attachments[' . $attachmentArrayId . '][filenameFS]" value="' . $attachmentFilenameFSUrlencoded . '" />
							<input type="hidden" name="attachments[' . $attachmentArrayId . '][filenameOriginal]" value="' . $attachmentFilenameOriginalUrlEncoded . '" />
							<input type="hidden" name="attachments[' . $attachmentArrayId . '][mimeType]" value="' . $attachmentMimeType . '" />
							<img class="type" src="' . $this->siteBaseUrl . 'images/icons/file-type-' . $icon . '.png" width="16" height="16" />
							<span>' . htmlentities( $attachmentFilenameOriginal, ENT_QUOTES, 'UTF-8' ) . ' ' . $sizeHuman . '</span>
							<a class="attach-btn" href="#" onClick="removeAttachment(\'' . addslashes($attachmentFilenameOriginal) . '\', \'' . $attachmentFilenameFSUrlencoded . '\', $(this).parent().parent()); return false;">
								<img class="attach" src="' . $this->siteBaseUrl . 'images/remove-attachment-trans.png" width="12" height="12" alt="'. addslashes($this->translate("remove attachment")) . '" />
							</a>
						</div>
					</li>';

   		echo $attachmentHTML;
        $attachmentArrayId++;

	}

}

?>               		
               	</ul>
			</div>
			</div>
		   
		</div>
				</h3>
				</div>
				
				<div class="body">
					<textarea name="emailBodyHtml" id="id_description_<?php echo $this->composeID ?>" class="rte-zone" height="150" style="display:none"><?php echo htmlentities($this->messageArray['bodyPreparedHtml'], ENT_QUOTES | ENT_IGNORE, 'UTF-8'); ?></textarea>
				</div>

				<div class="buttons draftsSavedMessageSlot"><?php echo $this->translate('Saved to drafts at') ?> <abbr class="timeago"></abbr></div>
				<div class="buttons">
						
					<div id="back_button" class="sendEmail" style="filter: 0;">
						<a tabindex="0" href="#">
							<span class="stronglastword"><?php print $this->translate('Send Email')?></span>
						</a>
					</div>
					
					<div id="back_button" class="readReceipt" style="filter: 0;">
						<a tabindex="0" id="topRightReadReceipt" href="#">
							<span class="stronglastword"><?php print $this->translate('Read Receipt') ?></span>
						</a>
					</div>
					
					<div id="back_button" class="saveAsDraft" style="filter: 0;">
						<a tabindex="0" href="#">
							<span class="stronglastword"><?php print $this->translate('Save as Draft')?></span>
						</a>
					</div>
					
					<div id="back_button" class="addAttachment" style="filter: 0;">
						<a href="#">
							<span class="stronglastword"><?php print $this->translate('Attach from Computer')?></span>
						</a>
					</div>
<?php if( $this->group['WebDavEnabled'] == '1' && $this->group['StorageTabEnabled'] == '1' ) : ?>
					<div id="back_button" class="addStorageAttachment" style="filter: 0;">

						<div id="fileUploadStorage" class='fileUpload'>
							<input type="text" class="fileupload-input" value="<?php echo $this->translate('Search') ?>">
							<div class="chat fileupload">
								<div class="row hidden"><img class=""/><span class='name'></span></div>
							</div>                       
						</div>
						<a href="#">
							<span class="stronglastword"><?php print $this->translate('Attach from Storage')?></span>
						</a>
					</div>
<?php endif ?>
				</div>
				
			</div>
		</div>
	</div>
</div>
</form>
<script type="text/javascript" language="JavaScript">
	var tabindex = 1;

	function reassignTabs()
	{
		tabindex = 1;

		$('input,textarea,iframe', '.<?php echo $this->composeID ?>', '#<?php echo $this->tabId ?>').each(function() {
		var $input = $(this);
			if ($input.is(':visible'))
			{ 
				$input.attr('tabindex', tabindex);
				tabindex++;
			}
			else
			{
				$input.attr('tabindex', '-1');
			}
		});

		rtetabindex = tabindex;
		$('.rte-zone', '.<?php echo $this->composeID ?>').attr('tabindex', tabindex);
		tabindex++;

		$('.buttons #back_button a', '.<?php echo $this->composeID ?>', '#<?php echo $this->tabId ?>').each(function() {
			var $input = $(this);
			if ($input.is(':visible'))
			{ 
				$input.attr('tabindex', tabindex);
				tabindex++;
			}
		});
		
		
	}
	$(document).ready( function() 
	{
		
		$.fn.addAttachmentRow = function(fileUniqueId, file) {
		
			$(this).append('<li class="attachment" id="' + fileUniqueId +'"><div><input type="hidden" class="filenamefs" name="attachments[' + fileUniqueId +'][filenameFS]" value="aaa" /><input type="hidden" class="filenameoriginal" name="attachments[' + fileUniqueId +'][filenameOriginal]" value="bbb" /><input type="hidden" class="mimetype" name="attachments[' + fileUniqueId +'][mimeType]" value="ccc" /></div><div class="uploading"><div class="upload-spin"></div>Uploading ' + file + '.</div></li>');			
			
		}
		
		$.fn.changeAttachmentRow = function(fileUniqueId, responseHTML) {
		
			$('#' + fileUniqueId + ' div.uploading', '.<?php echo $this->composeID ?>').remove();
			$('#' + fileUniqueId + ' div', '.<?php echo $this->composeID ?>').append( responseHTML );
			
			//transpose values across (fixes IE7 bug with dynamically adding form fields)
			var filenamefs =  $('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').attr('filenamefs');
			var filenameoriginal =  $('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').attr('filenameoriginal');
			var mimetype =  $('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').attr('mimetype');

			$('#' + fileUniqueId + ' div input.filenamefs', '.<?php echo $this->composeID ?>').val( filenamefs );
			$('#' + fileUniqueId + ' div input.filenameoriginal', '.<?php echo $this->composeID ?>').val( filenameoriginal );
			$('#' + fileUniqueId + ' div input.mimetype', '.<?php echo $this->composeID ?>').val( mimetype )
			
			$('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').remove();	
		}
		
		$.fn.loadComposeFiles = function(folder, func) {

			var params;
			
			// First, check we have not called this already
			if( $("DIV.jspContainer", '.<?php echo $this->composeID ?>').size() == 1 )
				return $("DIV#fileUploadStorage", '.<?php echo $this->composeID ?>').show();
			
			// Launch the JSON to load selected files
			$.getJSON('<?php echo $this->appBaseUrl ?>/api/webdav/list/recursive/true/folder/', params, function(json) {

				if( json ) {

					// First, hide all others
					$("DIV.row.activeFile", '.<?php echo $this->composeID ?>').remove();
					files = json;

					// if there are no files, alert and close the box
					// TODO: add translation
					if(files == '')
					{
						$("DIV.addStorageAttachment A").removeClass('add_from_storage_currently_open');
						$("DIV.addStorageAttachment A").addClass('no_files_in_storage');
						$("DIV#fileUploadStorage").hide();
						$.simpleFlash('<?php echo addslashes($this->translate('There are no files in storage')) ?>', 'notice');
					}
					
					$.each(files, function(i, n) 
					{

						var item = files[i];

						var file = $("DIV.row.hidden", '.<?php echo $this->composeID ?>').clone();
						//if(item.iconName == 'img' && gd_enabled == 1) 
						//	$('img', file).addClass('photoSmall');
						$(file).data('fileName', item.fileName);
						$(file).removeClass('hidden');
						$(file).addClass('activeFile');

						// Attach to the events of the ajax loaded "files" tab, for each row clicked
						$(file).bind('click', function(e) 
						{

							// Live handler called.
							var file = $(this).find('SPAN.name').text();
							fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');

							$("DIV.addStorageAttachment A", '.<?php echo $this->composeID ?>').removeClass('add_from_storage_currently_open');
							$("DIV#fileUploadStorage", '.<?php echo $this->composeID ?>').hide();

							if( moreOptions() ) 
							{

								$('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').addAttachmentRow(fileUniqueId, file);

							}			

							// Next, fire the event to the server to append the webfiles > attachment
							$.ajax(
							{
								type: "POST",
								dataType: 'html',
								url: "<?php echo $this->moduleBaseUrl ?>/composemessage/addattachment/composeID/<?php echo $this->composeID ?>",
								data: {
								fileUpload: file,
								fileUniqueId: fileUniqueId
								},
								complete: function(XMLHttpRequest, textStatus) 
								{
									fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');
									$('#' + fileUniqueId, '.<?php echo $this->composeID ?>').changeAttachmentRow(fileUniqueId, XMLHttpRequest.responseText);
								}

							});

						});

						$(file).show();

						$("SPAN.name", file).text(item.path);
					
						$("IMG", file).attr('src', siteBaseUrl + "images/icons/file-type-" + item.iconName + "-large.png");
						$("IMG", file).css('padding-left', '0px');
						$("IMG", file).css('padding-right', '8px');
						$('IMG', file).css('margin', '0');
						if(/^image\//.test(item.contentType)) 
						{
							$("IMG", file).addClass(item.iconName);
							var dir = item.path.replace(item.fileName, '');
							//$("IMG", file).attr('src', "<?php echo $this->siteBaseUrl ?>index.php/mail/webdav/open?Directory=" + encodeURIComponent(dir) + "&Filename=" + urlencode(item.fileName));					
						} 
						else if (item.iconName != '' ) 
						{
							$("IMG", file).addClass(item.iconName);
						} 
						else 
						{
							//$("IMG", file).attr('src', ""); //disabled because was causing hits to /
						}

						$("DIV.fileupload", '.<?php echo $this->composeID ?>').append(file);

					});
					//if(!files[0])	{
					//	$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
					//	$("DIV#webdav_files").append('<div style="margin:10px;" id="noMessageDisplay">&nbsp;No files in folder.</div>');
					//} else {
					//	$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
					//}
										
					var qtipFiles = $('DIV.fileupload', '.<?php echo $this->composeID ?>');
					try {
						qtipFiles.jScrollPane();
					} catch(e) {
						
					}
					
				}

				func();
			});

		};

		// Search for files in the DOM, matching by the filename
		$.fn.searchComposeFiles = function()
		{
			var search = $(this).val();

			// Unhighlight any previous selections, please!
			$("DIV.activeFile SPAN.name", '.<?php echo $this->composeID ?>').each(function() {
				$(this).html( $(this).text() );			
			});

			// Require less then 3 characters to perform the search
			if(search.length < 3) {
				$("DIV.activeFile").show();
				$("DIV#noMessageDisplay", '.<?php echo $this->composeID ?>').remove();
				return false;		
			}

			// Hide all other rows
			$("DIV.activeFile", '.<?php echo $this->composeID ?>').hide();

			var searchMatch = 0;
			// Loop thro each file and see if it matches
			$("DIV.activeFile").each(function() {
				var row = $(this);
				var file = $(this).find("SPAN.name").text();

				//alert(file + ":" + search);
				var reg = new RegExp( search, 'i' );

				if(reg.test(file)) {
					row.show();
					row.highlight(search);

					if(searchMatch == 0) {
						//row.viewFile();
						//$("INPUT[name=id]", row).attr('checked', true);					
					}

					searchMatch++;

				}

			});

			// Display the no files DIV if search results null
			if(searchMatch == 0) {
				//$(this).showNoFiles('No search results. Try again.');		
			} else {
				//$("DIV#noMessageDisplay", "DIV#webdav_files").remove();
			}

			return false;
		}
		
		$("#back_button a", '.<?php echo $this->composeID ?>').each(
			function() { 
				$(this).focus(
					function() {
						$(this).addClass('activated');
						$(this).parent().addClass('activated');
						$(this).find('span').addClass('activated');
						$(this).css('outline','1px dotted blue');
						}
					)
				$(this).blur(
					function() {
						$(this).removeClass('activated');
						$(this).parent().removeClass('activated');
						$(this).find('span').removeClass('activated');
						$(this).css('outline','none');
						}
					)
				}
			);


		// Add the email signature to the email
		var orig = $("#id_description_<?php echo $this->composeID ?>").val();
		<?php if( !$this->editingDraft ): ?>
		var signature = $("#EmailSignature.Signature").html();
		if(signature != '')
		{
			$("#id_description_<?php echo $this->composeID ?>").val("<BR/>" + $("#EmailSignature.Signature").html() + "<BR/>" + orig);
		}
		<?php endif; ?>
		
		//var composeID = '<?php echo $this->composeID ?>'; //commented out cos no context - fix if needed
		$('#leftcompose-more').keydown(function(e){
			if(e.which == ENTER_KEY){
				moreOptions();
				setEmailContextTabOrder();
				// setFocusableElements();
				$('#emailCc').focus();
				$('#form_bcc').keydown(function(e){
						if(e.which==9){
							 $('.rte-zone', '.<?php echo $this->composeID ?>').focus();
						}
				});
			}
		});


		//moved higher up in js to prevent FOUC
		function lessOptions() {

			$('#show-more', '.<?php echo $this->composeID ?>').hide()
			$('#leftcompose-more', '.<?php echo $this->composeID ?>').show()
			$('.details', '.<?php echo $this->composeID ?>').css({ height:"105px" })

			$('#topRightMoreOptionButton', '.<?php echo $this->composeID ?>').unbind('click')
			$('#topRightMoreOptionButton', '.<?php echo $this->composeID ?>').bind('click', function() { moreOptions() } )
			$('#topRightMoreOptionButton', '.<?php echo $this->composeID ?>').children('span').html("<?php print $this->translate('More Options')?>").stronglastword()

			resizeNewComposer('.<?php echo $this->composeID ?>', '#<?php echo $this->tabId ?>');
		}

		function moreOptions() {

			$('#show-more', '.<?php echo $this->composeID ?>').show()
			$('#leftcompose-more', '.<?php echo $this->composeID ?>').hide()
			$('.details', '.<?php echo $this->composeID ?>').css({ height:"100%" })

			$('#topRightMoreOptionButton', '.<?php echo $this->composeID ?>').unbind('click')
			$('#topRightMoreOptionButton', '.<?php echo $this->composeID ?>').bind('click', function() { lessOptions() } )
			$('#topRightMoreOptionButton', '.<?php echo $this->composeID ?>').children('span').html("<?php print $this->translate('Less Options')?>").stronglastword();

			resizeNewComposer('.<?php echo $this->composeID ?>', '#<?php echo $this->tabId ?>');
			// reassignTabs();
            return true
		}

		$('#topRightMoreOptionButton', '.<?php echo $this->composeID ?>').bind('click', function() { moreOptions() } )
		$('#leftcompose-more', '.<?php echo $this->composeID ?>').bind('click', function(){ moreOptions() })
		//hide the show more pane ready for events
		$('#show-more', '.<?php echo $this->composeID ?>').hide()

<?php if( isset($this->type) && $this->type == 'replyall' ) : ?>
		//expanding the more pane cos replying so need to see where it is going to go
		$('#leftcompose-more', '.<?php echo $this->composeID ?>').click();             
<?php endif; ?>

<?php if($this->UserSettings['enableExtraAddressFields'] == '1') : ?>
		// user want the cc and bcc to show by default
		$('#leftcompose-more', '.<?php echo $this->composeID ?>').click();
<?php endif; ?>
		
		$('#emailSubject', '.<?php echo $this->composeID ?>').bind('focus', function() 
		{
			if( $(this).attr('modified') == 'false' )
			{

				$(this).attr('modified', 'true')
				$(this).attr('value', '');
				$(this).removeClass('default');
				
			}
		})
		
		$('.es<?php echo $this->composeID ?>').bind('keyup', function() {
			$('.esh<?php echo $this->composeID ?>').text($(this).attr('value'));   
		})
		
		//set initial value
		$('.esh<?php echo $this->composeID ?>').text( $('.es<?php echo $this->composeID ?>').attr('value'));
		
		$('a.ajax').bind('click', function() 
		{
		
			$.php( $(this).attr('href') );
			return false;

		});
		
		$('a.ajaxDownload').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			
		
		});
		
		// Send email hooks
		$('.sendEmail, #topRightSendButton', '.<?php echo $this->composeID ?>').bind('click', function() 
		{
			
			if( $(this).hasClass('disabled') )
				return false
			
			<?php if ($this->enableConfirmOnSend == 1): ?>
			if(!confirm( '<?php print $this->translate("Are you sure you want to send this email?") ?>'))
				return false;
			<?php endif; ?>
			
			if( parseInt($('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').attr('numberOfAttachmentsCurrentlyIUploading')) > 0)
			{

				if( !confirm('<?php echo addslashes($this->translate("Are you sure you want to send while attachments are still being uploaded?")) ?>') )
				{

					return false

				}

			}

			//$('.sendEmail, #topRightSendButton, #topRightMoreOptionButton, .saveAsDraft, .addAttachment, #topRightReadReceipt, .addStorageAttachment', '.<?php echo $this->composeID ?>').disableActionSimpler();
			$('.sendEmail, .saveAsDraft, .addAttachment, .addStorageAttachment, #topRightReadReceipt, #topRightSendButton, #topRightMoreOptionButton').disableActionSimpler();
			
			// Get the HTML message
			var html = $('.rte-zone', '.<?php echo $this->composeID ?>').rte_html();
			$("#id_description_<?php echo $this->composeID ?>").attr('value', html)
			$.php('<?php echo $this->moduleBaseUrl ?>/composemessage/send/tabId/<?php echo $this->tabId ?>', $('.<?php echo $this->composeID; ?>').serializeArray() ) 
			return false 

		})
		
		// Read receipt hook
		$('#topRightReadReceipt', '.<?php echo $this->composeID ?>').bind('click', function() 
		{
			
			//if active then set form var and remove activeState
			if( $(this).hasClass('activeState') )
			{
				$(this).removeClass('activeState')
				$('.readReceiptRequested', 'form#composeMessage.<?php echo $this->composeID ?>').attr('value', 'false');
				$.simpleFlash('<?php echo addslashes($this->translate("A Read Receipt will not be requested for this email.")) ?>','error');
			}
			else
			{
				
				$(this).addClass('activeState')
				$('.readReceiptRequested', 'form#composeMessage.<?php echo $this->composeID ?>').attr('value', 'true');
				$.simpleFlash('<?php echo addslashes($this->translate("A Read Receipt will be requested for this email.")) ?>','notice');
			}
			return false

		}) 

		// Save as draft
		$('.saveAsDraft', '.<?php echo $this->composeID; ?>').bind('click', function() { 
					
			if( $(this).hasClass('disabled')  )
				return false
				
			
			if( parseInt($('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').attr('numberOfAttachmentsCurrentlyIUploading')) > 0)
				if( !confirm('<?php echo addslashes($this->translate("Are you sure you want to save a draft while attachments are still being uploaded?")) ?>') )
					return false

			//$('.sendEmail, #topRightSendButton, #topRightMoreOptionButton, .saveAsDraft, .addAttachment, .addStorageAttachment', '.<?php echo $this->composeID ?>').disableActionSimpler();
			$('.sendEmail, .saveAsDraft, .addAttachment, .addStorageAttachment, #topRightReadReceipt, #topRightSendButton, #topRightMoreOptionButton').disableActionSimpler();
            
			var html = $('.rte-zone', '.<?php echo $this->composeID ?>').rte_html()
			
			
			
			$("#id_description_<?php echo $this->composeID ?>").attr('value', html)
			$.php('<?php echo $this->moduleBaseUrl ?>/composemessage/savedraft', $('.<?php echo $this->composeID; ?>').serializeArray() ) 
					   
			return false  

		})
		
		
<?php if( $this->UserSettings['SaveDrafts'] == '1' ) : ?>

		periodicDraftSaver('<?php echo $this->tabId ?>', '<?php echo $this->composeID; ?>');

<?php endif ?>
		// Configure Ajax uploader
		$('.addAttachment, #topRightNewAttachment', '.<?php echo $this->composeID ?>').each( function() 
		{
			
			new AjaxUpload( $(this), {
				// Location of the server-side upload script
				action: "<?php echo $this->moduleBaseUrl ?>/composemessage/addattachment/composeID/<?php echo $this->composeID ?>",
				// File upload name
				name: 'newAttachment',
				addClass: 'mail-attachment',
				// Submit file after selection
				autoSubmit: true,
				onSubmit: function(file, extension) 
				{ 
					
					if( moreOptions() ) 
					{	
					  	fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');
						if( $('#' + fileUniqueId, '.<?php echo $this->composeID ?>').length > 0 ) 
						{

							alert('<?php echo addslashes($this->translate("Error: Attachment by that name has already exists.")) ?>')
							return false

						}
					    //add dumy fields at this point to work around IE7 bug (doesnt properly handle dynamically adding form inputs)
						$('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').append('<li class="attachment" id="' + fileUniqueId +'"><div><input type="hidden" class="filenamefs" name="attachments[' + fileUniqueId +'][filenameFS]" value="aaa" /><input type="hidden" class="filenameoriginal" name="attachments[' + fileUniqueId +'][filenameOriginal]" value="bbb" /><input type="hidden" class="mimetype" name="attachments[' + fileUniqueId +'][mimeType]" value="ccc" /></div><div class="uploading"><div class="upload-spin"></div>Uploading ' + file + '.</div></li>')
	                    $('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').attr('numberOfAttachmentsCurrentlyIUploading', parseInt($('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').attr('numberOfAttachmentsCurrentlyIUploading'))+1 );
	                
					}

				},
				onChange: function(file, ext) {
					
				}, 
				onComplete: function(file, responseHTML) 
				{
					fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');
					if( responseHTML.length > 100 )
					{                    
						$('#' + fileUniqueId + ' div.uploading', '.<?php echo $this->composeID ?>').remove();
						$('#' + fileUniqueId + ' div', '.<?php echo $this->composeID ?>').append( responseHTML );
						
						//transpose values across (fixes IE7 bug with dynamically adding form fields)
						var filenamefs =  $('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').attr('filenamefs');
						var filenameoriginal =  $('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').attr('filenameoriginal');
						var mimetype =  $('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').attr('mimetype');
						
						
						$('#' + fileUniqueId + ' div input.filenamefs', '.<?php echo $this->composeID ?>').attr('value', filenamefs );
						$('#' + fileUniqueId + ' div input.filenameoriginal', '.<?php echo $this->composeID ?>').attr('value', filenameoriginal );
						$('#' + fileUniqueId + ' div input.mimetype', '.<?php echo $this->composeID ?>').attr('value', mimetype )
						
						$('#' + fileUniqueId + ' div div.attachment', '.<?php echo $this->composeID ?>').remove();
						
					}
					else 
					{
						//error case with singe char error code                                   
						$('#' + fileUniqueId, '.<?php echo $this->composeID ?>').remove()
						alert('Error occurred uploading attachment: ' + responseHTML)
					}
					$('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').attr('numberOfAttachmentsCurrentlyIUploading', parseInt($('#composerAttachmentsHolder', '.<?php echo $this->composeID ?>').attr('numberOfAttachmentsCurrentlyIUploading'))-1 );
					
				}

			});

			$('a', $(this)).click(function(e){
				e.preventDefault();
				e.stopPropagation();

				$('.mail-attachment input').click();
				return false;
			})

		})          
		// TextboxList and Autocomplete initialization prepopulated with any saved-draft addresses
		emailToArray = activeSplit( $('#emailTo', '.<?php echo $this->composeID ?>').attr('value') );
		$('#emailTo', '.<?php echo $this->composeID ?>').attr('value', '');
		
		emailCcArray = activeSplit( $('#emailCc', '.<?php echo $this->composeID ?>').attr('value') );
		$('#emailCc', '.<?php echo $this->composeID ?>').attr('value','')
		
		emailBccArray = activeSplit( $('#emailBcc', '.<?php echo $this->composeID ?>').attr('value') );
		$('#emailBcc', '.<?php echo $this->composeID ?>').attr('value','')
		
		
		var emailToTextBoxListHandle = new TextboxList(  $('#emailTo', '.<?php echo $this->composeID ?>'), {bitsOptions:{editable:{addOnBlur:true }}, unique: true, plugins: {autocomplete: {placeholder:false,cacheSize: <?php echo $this->autocompleteCacheSize; ?>}}});	
		var emailCcTextBoxListHandle = new TextboxList(  $('#emailCc', '.<?php echo $this->composeID ?>'), {bitsOptions:{editable:{addOnBlur:true }}, unique: true, plugins: {autocomplete: {placeholder:false,cacheSize: <?php echo $this->autocompleteCacheSize; ?>}}});		
		var emailBccTextBoxListHandle = new TextboxList( $('#emailBcc', '.<?php echo $this->composeID ?>'), {bitsOptions:{editable:{addOnBlur:true }}, unique: true, plugins: {autocomplete: {placeholder:false,cacheSize: <?php echo $this->autocompleteCacheSize; ?>}}});
        
		
		// Support clicking anywhere in the div box to get to the last "bitbox selection"
		$("#form_to", '.<?php echo $this->composeID ?>').bind('click', function() {
			$("#form_to INPUT.textboxlist-bit-editable-input:last", '.<?php echo $this->composeID ?>').focus();
		});

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

		$("#form_bcc", '.<?php echo $this->composeID ?>').bind('click', function() {
			$("#form_bcc INPUT.textboxlist-bit-editable-input:last", '.<?php echo $this->composeID ?>').focus();
		});
		
		// Bind to the add attachment from storage ( cloud-files )
		$("DIV.addStorageAttachment A", '.<?php echo $this->composeID ?>').bind('click', function(e)
		{
			if( $(this).hasClass('no_files_in_storage') ) {
				$.simpleFlash('<?php echo addslashes($this->translate('There are no files in storage')) ?>', 'notice');
			}
			else {
				if( $(this).hasClass('add_from_storage_currently_open') ) {
					$(this).removeClass('add_from_storage_currently_open');
					$("DIV#fileUploadStorage", '.<?php echo $this->composeID ?>').hide();
				}
				else {
					$(this).addClass('add_from_storage_currently_open');
					$("DIV#fileUploadStorage", '.<?php echo $this->composeID ?>').show();
					
					$("DIV#fileUploadStorage", '.<?php echo $this->composeID ?>').loadComposeFiles('', function() { });
				}
			}
			//e.stopPropagation();
		});
		
		$("INPUT.fileupload-input", '.<?php echo $this->composeID ?>').bind('keyup', function() {
		
			$(this).searchComposeFiles();
			
		});

		$("INPUT.fileupload-input", '.<?php echo $this->composeID ?>').bind('click', function() {
		
			if($(this).val() == '<?php echo $this->translate("Search") ?>')
				$(this).val('');

		});
		
		// If the files DIV is open, and a click to the background, remove the DIV
		$( '.<?php echo $this->composeID ?>').bind('click', function(e) {
			
		    var clicked = $(e.target);
		
			// Don't hide if the button was clicked
			if(clicked.parents().hasClass('addStorageAttachment'))
				return;
				
			// Hide if any clicks are made outside the popup DIV
			if (!clicked.parents().hasClass("fileUpload")) {
				$("DIV.addStorageAttachment A", '.<?php echo $this->composeID ?>').removeClass('add_from_storage_currently_open');
				$("DIV#fileUploadStorage", '.<?php echo $this->composeID ?>').hide();
			}
			

		});

		if( $.jCacher.get('autocomplete') )
		{
			autocomplete_values = $.jCacher.get('autocomplete').value;
			emailToTextBoxListHandle.plugins['autocomplete'].setValues( autocomplete_values )
			emailCcTextBoxListHandle.plugins['autocomplete'].setValues( autocomplete_values )
			emailBccTextBoxListHandle.plugins['autocomplete'].setValues( autocomplete_values )
			
			if(autocomplete_values.length >= <?php echo $this->autocompleteFetchThreshold ?>)
			{
				emailToTextBoxListHandle.plugins['autocomplete'].setOptions( 
				{
					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; ?>'}
				});
				emailCcTextBoxListHandle.plugins['autocomplete'].setOptions( 
				{
					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; ?>'}
				});
				emailBccTextBoxListHandle.plugins['autocomplete'].setOptions( 
				{
					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; ?>'}
				});
			}
		}
		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 ?>)
					{
						emailToTextBoxListHandle.plugins['autocomplete'].setOptions( 
							{
								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; ?>'}
							});
						emailCcTextBoxListHandle.plugins['autocomplete'].setOptions( 
							{
								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; ?>'}
							});
						emailBccTextBoxListHandle.plugins['autocomplete'].setOptions( 
							{
								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; ?>'}
							});
					}
                    emailToTextBoxListHandle.plugins['autocomplete'].setValues(r)
					emailCcTextBoxListHandle.plugins['autocomplete'].setValues(r)
					emailBccTextBoxListHandle.plugins['autocomplete'].setValues(r)
					$.jCacher.add('autocomplete', r, 3600);
				}
			})
		}
		
		//for loaded drafts, load in saved recipients
		for(var rcpt in emailToArray) {
			value = emailToArray[rcpt];
			//value = $('<div/>').text( value ).html()
			if( value.length > 3 )
				emailToTextBoxListHandle.add(value);
		}
		
		for(var rcpt in emailCcArray) {
			value = emailCcArray[rcpt];
			//value = $('<div/>').text( value ).html()
			if( value.length > 3 )
				emailCcTextBoxListHandle.add(value);
		}
		
		for(var rcpt in emailBccArray) {
			value = emailBccArray[rcpt];
			//value = $('<div/>').text( value ).html()
			if( value.length > 3 )
				emailBccTextBoxListHandle.add(value);
		} 
		
		$('.rte-zone', '.<?php echo $this->composeID ?>').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" ; ?>
		});
		$('.rte-zone', '.<?php echo $this->composeID ?>').rte_focus();
		
		// Select the subject field if Abook > Email clicked, else the to field with a timeout delay for JS fix
		<?php if(isset($toHtmlspecialchars) && $toHtmlspecialchars != '') :?>
			if($('#emailSubject', '.<?php echo $this->composeID ?>').val() != '')
			{
				// we timeout here for 1 second to allow the iframe/compose pane settle and execute all included html/rte editor
			 	$('#id_description_<?php echo $this->composeID ?>', '.<?php echo $this->composeID ?>').rte_focus();
			}
			else
			{
				$('#emailSubject', '.<?php echo $this->composeID ?>').select();
			}
		<?php else :?>
			setTimeout( function() { $('.textboxlist-bit-editable-input:first', '.<?php echo $this->composeID ?>').focus() }, 0 )
		<?php endif ?>
	
		// Resize the composer window
		setTimeout("resizeNewComposer('.<?php echo $this->composeID ?>', '#<?php echo $this->tabId ?>')", 100);
	   		
		<?php 
		//if attachments or cc or bcc then automtically expand more
		if( count($this->messageArray['attachmentsList']) > 0 || !empty($this->messageArray['headers']['x-atmail-bcc']) || !empty($this->messageArray['headers']['cc']) ) 
		{
			//echo "$('#leftcompose-more', '." . $this->composeID . "').click();";    
			echo "moreOptions()\n";

		}
		?>
		
		$('.stronglastword').each( function() { $(this).stronglastword(); });
        
		// On the window resize, make the composer neat for the height position
		$(window).resize(function(){
			resizeNewComposer('.<?php echo $this->composeID ?>', '#<?php echo $this->tabId ?>')
		});
		
		var tabindex = 1;
		var validObjects = new Array("textboxlist-bit-editable-input", "emailSubject", "emailBodyHtml");

		// reassignTabs();
		// $('.rte-zone', '.<?php echo $this->composeID ?>').attr('tabindex', rtetabindex);
        
		$("#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');
		$("#form_to").find('li.textboxlist-bit-editable input:first').attr('tabindex','0');
		setEmailContextTabOrder(); 
	})
	
</script>



