<?php 
	//must be passed in on prequestParams else wont know what context it is in
	if( !isset( $this->requestParams['messagePanelContextName'] ) )
		throw new Exception('need to know messagePanelContextName for reply else will not have valid context');
?>
<div class='body'>
<textarea name="emailBodyHtml" id="id_description_<?php echo $this->requestParams['messagePanelContextName'] ?>" class="rte-zone-reply" height="150" style="display:none"></textarea>
</div>
<div class="buttons draftsSavedMessageSlot">Saved to drafts at <abbr class="timeago"></abbr></div>

<div class='buttons'>
	<div id="back_button" class="sendEmail">
		<a tabindex="0"  href="#"><span class="stronglastword"><?php print $this->translate('Send my Reply')?></span></a>
	</div>
  <div id="back_button" class="readReceipt">
		<a tabindex="0" id="topRightReadReceipt" href="#"><span class="stronglastword"><?php print $this->translate('Read Receipt') ?></span></a>
	</div>
	<div id="back_button" class="saveAsDraft">
		<a tabindex="0" href="#"><span class="stronglastword"><?php print $this->translate('Save as Draft')?></span></a>
	</div>
		
	<div id="back_button" class="addAttachment">
		<a tabindex="0" 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 tabindex="0" href="#">
			<span class="stronglastword"><?php print $this->translate('Attach from Storage')?></span>
		</a>
	</div>
<?php endif ?>

	
	
</div>


<script type="text/javascript" language="JavaScript">
$( function() {
  $(".addAttachment",'#<?php echo $this->requestParams['messagePanelContextName'] ?>').keyup(function(e){
		if(e.which===ENTER_KEY){ $(this).click() }
	});
  // adding read receipt functionality
  var readReceipt   = document.createElement('input');
  readReceipt.type  = 'hidden';
  readReceipt.name  = 'readReceiptRequested';
  readReceipt.value = 'false';
  readReceipt.className = 'readReceiptRequested';

  $('#composeMessage','#<?php echo $this->requestParams['messagePanelContextName'] ?>').append(readReceipt);

	$.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->requestParams['messagePanelContextName'] ?>').remove();
		$('#' + fileUniqueId + ' div', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').append( responseHTML );
		
		//transpose values across (fixes IE7 bug with dynamically adding form fields)
		var filenamefs =  $('#' + fileUniqueId + ' div div.attachment', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').attr('filenamefs');
		var filenameoriginal =  $('#' + fileUniqueId + ' div div.attachment', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').attr('filenameoriginal');
		var mimetype =  $('#' + fileUniqueId + ' div div.attachment', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').attr('mimetype');

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

		var params;
		
		// First, check we have not called this already
		if( $("DIV.jspContainer", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').size() == 1 ) {
			$("DIV.addStorageAttachment A", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').addClass('add_from_storage_currently_open');
			return $("DIV#fileUploadStorage", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>').remove();
				files = json;

				// if there are no files, alert and close the box
				// TODO: add translation
				if(files == '')
				{
					$("DIV.addStorageAttachment A", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').removeClass('add_from_storage_currently_open');
					$("DIV.addStorageAttachment A", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').addClass('no_files_in_storage');
					$("DIV#fileUploadStorage", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>').clone();
					//if(item.iconName == 'img') 
					//	$('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() 
					{

						// Live handler called.
						var file = $(this).find('SPAN.name').text();
						fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');
						//prepResponseFieldsAndContent('#<?php echo $this->requestParams['messagePanelContextName'] ?>',false)
						//$('#replyAttach', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').show();
						//resizeComposer('<?php echo $this->requestParams['messagePanelContextName'] ?>');
						$('#showRecipientsButton:visible', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').click();

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

						//if($('#showRecipientsButton', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').css('display') != 'none')
						//	$('#showRecipientsButton', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').click();
						$('#replyAttach', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').show();
						//resizeComposer('<?php echo $this->requestParams['messagePanelContextName'] ?>');
						$('#composerAttachmentsHolder', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>",
							data: {
							fileUpload: file,
							fileUniqueId: fileUniqueId
							},
							complete: function(XMLHttpRequest, textStatus) 
							{
								fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');
								$('#' + fileUniqueId, '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>');
				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->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>').remove();
			return false;		
		}

		// Hide all other rows
		$("DIV.activeFile", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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;
	}
	
	// Send email hooks
	$('.sendEmail', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').bind('click', function() {
		
		<?php if ($this->enableConfirmOnSend == 1): ?>
			if(!confirmOnSend( '<?php print $this->translate("Are you sure you want to send this email?") ?>')) 
				return false;
		<?php endif; ?>
			
		//$('.sendEmail, .saveAsDraft, .addAttachment, .addStorageAttachment', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').disableActionSimpler();
		$('.sendEmail, .saveAsDraft, .addAttachment, .addStorageAttachment, #topRightReadReceipt, #topRightSendButton, #topRightMoreOptionButton').disableActionSimpler();
		
		var html = $('.rte-zone-reply', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').rte_html()
		$("#id_description_<?php echo $this->requestParams['messagePanelContextName'] ?>").attr('value', html)
		$.php( '<?php echo $this->moduleBaseUrl . 'composemessage/send' ?>', $('#composeMessage', '#<?php echo $this->requestParams['messagePanelContextName'] ?>' ).serializeArray() ) 
		return false 
		
	})

  // Read receipt hook
    $('#topRightReadReceipt','#<?php echo $this->requestParams['messagePanelContextName'] ?>').bind('click', function() 
    {
      
      //if active then set form var and remove activeState
      if( $(this).hasClass('activeState') )
      {
        $(this).removeClass('activeState')
        $('.readReceiptRequested','#<?php echo $this->requestParams['messagePanelContextName'] ?>').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','#<?php echo $this->requestParams['messagePanelContextName'] ?>').attr('value', 'true');
        $.simpleFlash('<?php echo addslashes($this->translate("A Read Receipt will be requested for this email.")) ?>','notice');
      }
      return false

    }) 
	// Save draft
	$('.saveAsDraft', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').bind('click', function() {
		
		
		if( $(this).hasClass('disabled') )
			return false
		
		if( parseInt($('#composerAttachmentsHolder', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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, .saveAsDraft, .addAttachment, .addStorageAttachment', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').disableActionSimpler();
		$('.sendEmail, .saveAsDraft, .addAttachment, .addStorageAttachment, #topRightReadReceipt, #topRightSendButton, #topRightMoreOptionButton').disableActionSimpler();
		
		var html = $('.rte-zone-reply', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').rte_html()
	    $("#id_description_<?php echo $this->requestParams['messagePanelContextName'] ?>").attr('value', html)

		$.php( '<?php echo $this->moduleBaseUrl . 'composemessage/savedraft' ?>', $('#composeMessage', '#<?php echo $this->requestParams['messagePanelContextName'] ?>' ).serializeArray() )
		
		return false 
		
	})
	
	//$("#FilesLeft").hide();
	//$("#FilesRight").hide();

	// Configure Ajax uploader
	$('.addAttachment', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').each( function() {
		//alert("<?php echo $this->moduleBaseUrl ?>composemessage/addattachment/");
		new AjaxUpload( $(this), {
			// Location of the server-side upload script
			action: "<?php echo $this->moduleBaseUrl ?>composemessage/addattachment/composeID/<?php echo $this->requestParams['messagePanelContextName'] ?>",
			// File upload name
			name: 'newAttachment',
			addClass: 'mail-attachment-reply',
			// Submit file after selection
			autoSubmit: true,
			onChange: function(file, extension){ },
			onSubmit: function(file, extension) { 
				$('#replyAttach', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').show();
				resizeComposer('<?php echo $this->requestParams['messagePanelContextName'] ?>');
				fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');
				if( $('#' + fileUniqueId, '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>').attr('numberOfAttachmentsCurrentlyIUploading', parseInt($('#composerAttachmentsHolder', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').attr('numberOfAttachmentsCurrentlyIUploading'))+1 );
				
				if($('#showRecipientsButton', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').css('display') != 'none')
					$('#showRecipientsButton', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').click();
			},
			onComplete: function(file, responseHTML) {                       
				fileUniqueId = file.replace(/[^a-zA-Z0-9]+/g,'');
				context = '#<?php echo $this->requestParams['messagePanelContextName'] ?>'
				if( responseHTML.length > 100 )
				{                    
					
					$('#' + fileUniqueId + ' div.uploading', context).remove();
					$('#' + fileUniqueId + ' div', context).append( responseHTML );
					
					//transpose values across (fixes IE7 bug with dynamically adding form fields)
					var filenamefs =  $('#' + fileUniqueId + ' div div.attachment', context).attr('filenamefs');
					var filenameoriginal =  $('#' + fileUniqueId + ' div div.attachment', context).attr('filenameoriginal');
					var mimetype =  $('#' + fileUniqueId + ' div div.attachment', context).attr('mimetype');
					
					
					$('#' + fileUniqueId + ' div input.filenamefs', context).attr('value', filenamefs );
					$('#' + fileUniqueId + ' div input.filenameoriginal', context).attr('value', filenameoriginal );
					$('#' + fileUniqueId + ' div input.mimetype', context).attr('value', mimetype )
					
					$('#' + fileUniqueId + ' div div.attachment', context).remove();
					
				}
				else 
				{
					
					//error case with singe char error code                                   
					$('#' + fileUniqueId, context).remove()
					alert('Error occurred uploading attachment: ' + responseHTML)
					
				}
				$('#composerAttachmentsHolder', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').attr('numberOfAttachmentsCurrentlyIUploading', parseInt($('#composerAttachmentsHolder', '#<?php echo $this->requestParams['messagePanelContextName'] ?>').attr('numberOfAttachmentsCurrentlyIUploading'))+1 );
				                                       
			}   
			
		});


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

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

	// Bind to the add attachment from storage ( cloud-files )
	$("DIV.addStorageAttachment A", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>').hide();
			}
			else {
				$(this).addClass('add_from_storage_currently_open');
				$("DIV#fileUploadStorage", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').show();
				$("DIV#fileUploadStorage", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').loadComposeFiles('', function() { });
			}
		}
		//e.stopPropagation();
	});


	$("INPUT.fileupload-input", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').bind('keyup', function() {                                                                                                                                            
		$(this).searchComposeFiles();                                                                                                                                                                                                    
	});                                                                                                                                                                                                                                  
																																																											 
	$("INPUT.fileupload-input", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').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->requestParams['messagePanelContextName'] ?>' ).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->requestParams['messagePanelContextName'] ?>').removeClass('add_from_storage_currently_open');
			$("DIV#fileUploadStorage", '#<?php echo $this->requestParams['messagePanelContextName'] ?>').hide();
		}

	});
	
	$('.stronglastword').each( function() { $(this).stronglastword(); });
		$("#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');
		setEmailContextTabOrder();
})
</script>
