<?php $config = Zend_Registry::get('config'); ?>
<ul id="jsddm">
	<li id="action_new" title="<?php echo $this->translate("New Email") ?>"><a href="#" tabindex="0" style="width:65px;">
		<!--<span><strong>--><?php print $this->translate('New Email')?>l<!--</span></strong>--></a></li>
		<li id="action_new_drop" class="compose-drop">
		<a class="new-arrow" tabindex="0" title="<?php echo $this->translate("New Menu") ?>"><?php echo $this->translate("New Menu") ?><!--<span class="arrow">▼</span>--></a>
		<ul id='menuOptions' class="menu_drop">
			<li><a href="#" id="newEmailButton" tabindex="0"><?php print $this->translate('New Email')?></a></li>
			<li><a href="#" id='newContactButton' tabindex="0"><?php print $this->translate('New Contact')?></a></li>
			<li class="bottom" id='newEventButton'><a href="#" tabindex="0"><?php print $this->translate('New Event')?></a></li>
		<?php if( $this->serviceProvidersEnabled && $this->SIPEnabled && $this->selectedSIPAccount !== null && $config->global['SIPType'] == 'SAMSUNG'): ?>
			<li id='newSMSButton'><a href="#" onclick="$phone.newIM();jsddm_close();" tabindex="0"><?php print $this->translate('New SMS')?></a></li>
		<?php endif; ?>
		</ul>
	</li>
</ul>

<ul id="for_messages">
	<li id="action_get_mail" title="<?php echo $this->translate("Get Mail") ?>"><a href="#" tabindex="0"><!--<span><strong>--><?php print $this->translate('Get Mail')?><!--</strong></span>--></a></li>
	<li id="action_reply" title="<?php echo $this->translate("Reply") ?>" aria-live="assertive"><a href="#" tabindex="0"><!--<span><strong>--><?php print $this->translate('Reply')?><!--</strong></span>--></a></li>
	<li id="action_reply_all" title="<?php echo $this->translate("Reply All") ?>" aria-live="assertive"><a href="#" tabindex="0"><!--<span><strong>--><?php print $this->translate('Reply All')?><!--</strong></span>--></a></li>
	<li id="action_forward" title="<?php echo $this->translate("Forward") ?>" aria-live="assertive"><a href="#" tabindex="0"><!--<span><strong>--><?php print $this->translate('Forward')?><!--</strong></span>--></a></li>
	<li id="action_junk" title="<?php echo $this->translate("Spam") ?>" aria-live="assertive"><a href="#" tabindex="0"><span><strong><?php print $this->translate('Spam')?></strong></span></a></li>
	<?php if (array_key_exists('enableSpamReporting', $config->global) && $config->global['enableSpamReporting']): ?>
	<li id="action_not_junk" title="<?php echo $this->translate("Not Spam") ?>" aria-live="assertive"><a href="#" tabindex="0"><span><strong><?php print $this->translate('Not Spam')?></strong></span></a></li>
	<?php endif; ?>
	<li id="action_delete" title="<?php echo $this->translate("Delete") ?>" aria-live="assertive"><a href="#" tabindex="0"><span><strong><?php print $this->translate('Delete')?></strong></span></a></li>
	<!-- <li id="action_empty" title="<?php echo $this->translate("Empty") ?>" aria-live="assertive"><a href="#" tabindex="0"><span><strong><?php print $this->translate('Empty')?></strong></span></a></li> -->
	<li id="action_help" title="Help"><a target="_blank" tabindex="0" href="mail/settings/help/helpFile/email"><span><strong><?php echo $this->translate('Help')?></strong></span></a></li>
</ul>

<ul class="move-mail-button" id="jsddm">
  <li id="action_more" title="Move Mail"><a id="move-mail-dropdown" class="moredrop" href="#" tabindex="0" style="text-align:right">Move Mail▼</a>
    <ul id='menuOptions' class="menu_drop_more_viewmsgs">
      <li id='action_more_selectallmail'><a href="#" tabindex="0"><?php print $this->translate('Select All')?></a></li>    
      <li id='action_more_deselectallmail'><a class="deselected" href="#" tabindex="0"><?php print $this->translate('Deselect')?></a></li>
      <li id='action_more_flagselected'><a href="#" class="deselected" tabindex="0"><?php print $this->translate('Flag')?></a></li>
      <li id='action_more_unflagselected'><a href="#" class="deselected" tabindex="0"><?php print $this->translate('Remove Flag')?></a></li>
      <li id='action_more_markselectedasread'><a href="#" class="deselected" tabindex="0"><?php print $this->translate('Mark as Read')?></a></li>
      <li class="bottom" id='action_more_markselectedasunread' ><a class="deselected" tabindex="0" href="#"><?php print $this->translate('Mark as Unread')?></a></li>
    </ul> 
  </li>
</ul>  

<ul id="jsddm">
	<li id="action_more" title="<?php echo $this->translate("More") ?>"><a class="moredrop" href="#" tabindex="0" style="text-align:right"><?php print $this->translate('More')?>▼</a>
		<ul id='menuOptions' class="menu_drop_more_viewmsgs">
			<li id='action_more_selectallmail'><a href="#" tabindex="0"><?php print $this->translate('Select All')?></a></li>
			<li id='action_more_deselectallmail'><a class="deselected" href="#" tabindex="0"><?php print $this->translate('Deselect')?></a></li>
			<li id='action_more_flagselected'><a href="#" class="deselected" tabindex="0"><?php print $this->translate('Flag')?></a></li>
			<li id='action_more_unflagselected'><a href="#" class="deselected" tabindex="0"><?php print $this->translate('Remove Flag')?></a></li>
			<li id='action_more_markselectedasread'><a href="#" class="deselected" tabindex="0"><?php print $this->translate('Mark as Read')?></a></li>
			<li class="bottom" id='action_more_markselectedasunread' ><a class="deselected" tabindex="0" href="#"><?php print $this->translate('Mark as Unread')?></a></li>
		</ul>
	</li>
</ul>



<ul id="for_views" aria-live="polite">
	<li id="two_pane" title='<?php echo $this->translate("2 Pane view") ?>'><a id="PaneToggleB2" role="button" aria-pressed="<?php echo $this->listViewType=='compact'?'false':'true' ?>" href="#" tabindex="0" class="toggle<?php echo $this->listViewType=='compact'?'off':'on' ?>"><?php print $this->translate('Two Pane')?> view is <?php echo $this->listViewType=='compact'?'off':'on' ?></a></li>
	<li id="three_pane" title='<?php echo $this->translate("3 Pane view") ?>'><a id="PaneToggleB1" role="button" aria-pressed="<?php echo $this->listViewType=='compact'?'true':'false' ?>" href="#" tabindex="0" class="toggle<?php echo $this->listViewType=='compact'?'on':'off' ?>"><?php print $this->translate('Three Pane')?> view is <?php echo $this->listViewType=='compact'?'on':'off' ?></a></li>
</ul>
<script type="text/javascript" language="JavaScript">
$( function() {
	currentid = false;
	function newEventBootstrap()
	{
		if(currentid !== false)
		{
			clearTimeout(currentid);
		}
		// bootstrap for the calendar's newEvent function.
		if( typeof newEvent != "undefined" )
		{
			// all green
			newEvent();
		}
		else
		{
			// we need to wait.
			currentid = setTimeout(newEventBootstrap, 200);
		}
	};

	// Setup the button state ( Delete and Junk depending on checkbox )
	enableMailActions();

	// More menu
	$('#action_more_selectallmail a').bind("click", function()
	{
		selectAllMail()
		enableMailActions();
		$(jsddm_target).focus();
    $(this).css('outline','none');
	} )
	$('#action_more_deselectallmail a').bind("click", function() 
	{ 
		deselectAllMail()
    $(jsddm_target).focus();
    $(this).css('outline','none');
	} )
	
	$('#action_more_markselectedasread a').bind("click", function() { 
		flagSelectedMessages('seen');
		$(jsddm_target).focus();
    $(this).css('outline','none');
	 } );

	$('#action_more_markselectedasunread a').bind("click", function() { 
		flagSelectedMessages('unseen') 
		$(jsddm_target).focus();
    $(this).css('outline','none');
	} );

	$('#action_more_flagselected a').bind("click", function() { 
		flagSelectedMessages('flagged', true) 
		$(jsddm_target).focus();
    $(this).css('outline','none');
	} );

	$('#action_more_unflagselected a').bind("click", function() { 
		flagSelectedMessages('-flagged') 
		$(jsddm_target).focus();
    $(this).css('outline','none');
	} );

	
	$('#action_junk a').bind('click', function() 
	{
		if( $(this).attr('disabled') )
		{
			return false;	
		}

		setSpamStatus('<?php echo urlencode(urlencode($this->mainFolders['Spam'])) ?>');
		return false;
	} )
	
	$('#action_not_junk a').bind('click', function() 
	{
		if( $(this).attr('disabled') )
		{
			return false;	
		}

		setSpamStatus('<?php echo urlencode(urlencode($this->mainFolders['Inbox'])) ?>');
		return false;
	} )
	

	quota = []; // Practically needs to be global.
	$('#action_delete a').bind('click', function() 
	{

		if( $(this).attr('disabled') )
		{
			return false;
		}
		
		// delete call or sms logs
		/*
		if( getSelectedCallFolder() )
		{
			if( !confirm('Are you sure you want to delete the selected logs? This action cannot be undone.') ) 
				return
			
			deleteSelectedLogItemsAndUpdateUI();
			return;
		}
*/
		var $delete_button = $(this)
		if( $delete_button.attr('disabled') ) return;

		$delete_button.attr('disabled','true')
		setTimeout(function(){ $delete_button.attr('disabled','') }, 1000);
		
		visiblePanelContext = getVisiblePanelContext();
		
		if( $('.messageCheckbox:checked', visiblePanelContext).length > 0 )
		{
			
			// triggered from a message list tab
			contextFolder = $('#listFolder', visiblePanelContext).attr('value');
			var actually_delete = false;
			if( contextFolder == '<?php echo urlencode(urlencode($this->mainFolders['Trash'])) ?>') 
			{
			
				if( confirm('<?php echo addslashes($this->translate("Are you sure you want to delete these messages?")) ?>') )
				{
				
					actually_delete = true;
					
				}
				else
				{
					
					return false;
					
				}
				
			}
			else
			{
			    if( quota[0] && quota[0] > quota[1] * 0.9 )
				{
				
					if( confirm('<?php echo addslashes($this->translate("Your mailbox is nearly full. Do you want to delete these messages completely instead of moving them to the trash?")) ?>') )
					{
						
						actually_delete = true;
						
					}
					else
					{
						
						return false;
						
					}
				    
					
				}
				
			}
			$('.messageCheckbox:checked:first', visiblePanelContext).parent().parent().moveMessages( contextFolder, '<?php echo urlencode(urlencode($this->mainFolders['Trash'])) ?>', visiblePanelContext, actually_delete );
			
		}
		else
		{
		
			//Viewing a message
			contextFolder = $('#relatedMessageFolder', visiblePanelContext).attr('value');
			
			messageListContext = $('#primary_content_inner .messagesListForm ', '#messageList');
			
			// hide the message that is being moved from the message list
			var id = $('#relatedMessageUID', visiblePanelContext).attr('value');
			if(!id) return;

			$('tr#' + id, messageListContext).hide();
			$('tr#' + id, messageListContext).addClass('hidden');
			
            $.php(moduleBaseUrl + '/mail/movetofolder/fromFolder/' + contextFolder + '/toFolder/<?php echo urlencode(urlencode($this->mainFolders['Trash'])) ?>/UID/' + $('#relatedMessageUID', visiblePanelContext).attr('value'));

			//if visible tab is a message then find its index and remove it
			
			$('#navMessages li').each( function(tabIndex) 
			{ 
			
				visiblePanelContext = getVisiblePanelContext(); 
				if( $(this).attr('name') == visiblePanelContext ) 
				{
				
					$('#navMessages').tabs('remove', tabIndex);
				    return false;
				
				}
			})

			$('#navMessages').tabs('select',0)
			$('#nav').tabs('select',0)
			
		}
		return false;
	});
	
	$('#action_empty a').bind('click', function() 
	{
		
		if( $(this).attr('disabled') )
			return false;
		
		visiblePanelContext = getVisiblePanelContext();
		
		contextFolder = $('#listFolder', visiblePanelContext).attr('value');
		if( contextFolder != '<?php echo urlencode(urlencode($this->mainFolders['Trash'])) ?>' &&  contextFolder != '<?php echo urlencode(urlencode($this->mainFolders['Spam'])) ?>') 
			return false;
		
		if( confirm('<?php echo addslashes($this->translate("Are you sure you want to delete all messages in this folder?")); ?>') )
			$.emptyMailFolder( contextFolder, urlencode(visiblePanelContext) );
		
		return false;
	
	});
	
	$('#action_new a').bind('click', function()
	{
		
		openNewComposerTab()
		
	})
	

	$('#action_get_mail a').bind('click', function()
	{
		
		if( !$(this).attr('disabled') )
			$('#folder_inbox a').trigger('click');
		return false;
		
	})

	$('#action_reply a').bind('click', function()
	{
		
		if( !$(this).attr('disabled') )
			prepareEditor('reply');
		return false;
		
	})

	$('#action_reply_all a').bind('click', function()
	{
	
		if( !$(this).attr('disabled') )
			prepareEditor('replyall');
		return false;
	
	})

	$('#action_forward a').bind('click', function()
	{
		
		if( $(this).attr('disabled') )
			return false;
		visiblePanelContext = getVisiblePanelContext();
		uniqueIds = new Array();
		//determine if to harvest uniqueId(s) from currently visible message tab or from checked list
		//i.e. no messageCheckboxes in current visible context - then must be message view 
		if( $('.messageCheckbox:checked', visiblePanelContext).length == 0 )
		{
			
			relatedMessageFolder = $('#relatedMessageFolder', visiblePanelContext).attr('value');
			uniqueIds.push( $('#relatedMessageUID', visiblePanelContext).attr('value') );
			
		}
		else
		{
			
			relatedMessageFolder = $('#listFolder', visiblePanelContext).attr('value');

			//get list is 2pane
			$('.messageCheckbox:checked', visiblePanelContext).each( function()
			{
				
				uniqueIds.push( $(this).attr('value') );
				//immediately mark the list item as replied
				$(this).parent().parent().children('td:first').children('#msgIcon').addClass('reply');
				$(this).parent().children('#msgIcon').addClass('reply');
			});
			
		}
		forwardMessagesInNewTab(uniqueIds, relatedMessageFolder);
	
	});

	// Bind for the new Email button
	$('#newEmailButton').bind('click', function()
    {
        openNewComposerTab();
        $('.menu_drop').hide();
    }).bind('keydown',function(e){
        if(e.which==ENTER_KEY){
				  e.stopPropagation();
					e.preventDefault();
					$(this).click();
					jsddm_close();
				}
		});

	// Bind for the new Contact button
	$('#newContactButton').bind('click', function()
	{

		//temporarily mod the tab url so that it loads with the edit form(aware) else will load normally and will need hack to show form and will flash inbetween
		origContactTabUrl = $('li#nav_add:first a', 'body div#header:last').data('href.tabs')
		$('#nav').tabs('url', 1, origContactTabUrl + '/index/addNewContact/true')
		
		$('#nav').tabs('select', 1)
		
		$('#nav').tabs('url', 1, origContactTabUrl )
		
	}).bind('keydown',function(e){
			if(e.which==ENTER_KEY){
				e.stopPropagation();
				e.preventDefault();
				$(this).click();
				jsddm_close();
			}
	});

	$('#newEventButton').bind('click', function()
	{

		$('#nav').tabs('select', 2);

		// TODO: All Atmail JS functions should use a JQ function
		newEventBootstrap();
	
	});

	currentListViewType = '<?php echo $this->listViewType ?>';
	
	$('#for_views').bind('click', function(e)
	{
		//lowlight other view types, highligh active view, load active view
		clickedId = $(e.target).attr('id');
		var toggle = $('#' + clickedId, '#for_views').attr('className').match(/toggleo(n|f{2})/)[0];
		
		// Only trigger, if we are not the active tab already
		// Atmail has this totally backwards, in case there is any confusion for the next few lines...
		if(toggle == 'toggleoff')
		{
			$('a:not(#' + clickedId + ')', '#for_views').removeClass('toggleon').addClass('toggleoff').attr('aria-disabled','true');
			$('#' + clickedId, '#for_views').removeClass('toggleoff').addClass('toggleon').attr('aria-disabled','false');
			if(clickedId == 'PaneToggleB1')
			{
				currentListViewType = 'compact';
				appliedViewType = "3p";
			}
			else
			{
				currentListViewType = 'twoPane';
				appliedViewType = "2p";
			}
			
			//show loading pane
			var pageNumber = $("#pageNumber").val();
			if(pageNumber == undefined)
			{
				// page not loaded
				pageNumber = 1;
			}
			$('#Email #primary #messageList #primary_content').html('');
			$('#Email #primary #messageList #primary_content').block({ message: "<h1 class='loading-text'><img alt='loadding...' class='loadingimg' src='<?php echo $this->siteBaseUrl ?>images/25.gif' width='28' height='28'/><span class='loading'><?php echo $this->translate('Loading...') ?></span></h1>", centerX:false, centerY:false, overlayCSS: {backgroundColor: 'transparent', opacity: 0.4}, css: {backgroundColor: 'transparent',color: '#575757',border: '0'} });
			
			//dont specify folder until we have multiple folder views/contexts
			//$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/listViewType/' + currentListViewType + "/selectFolder/" + $("#listFolder").val() + "/page/" + $("#pageNumber").val());
			$.php('<?php echo $this->moduleBaseUrl ?>/mail/listfoldermessages/listViewType/' + currentListViewType + "/page/" + pageNumber );
			
			// perm apply setting
			$.php('<?php echo $this->moduleBaseUrl ?>/settings/webmailsave?fields[DefaultView]=' + appliedViewType + '&save=1');
			// and ensure settings ui is updated (because it is cached)
			$("#View option", '#global').removeAttr('selected');
			$("#View option[value=" + appliedViewType + "]", '#global').attr('selected', 'true');
			
			$('div#navMessages').tabs('select', 0);
		}

	} );

	$('.move-mail-button').bind('click',setMovableFoldersMenu);
} );

function setMovableFoldersMenu(){
	var console = console || window.console;
  var $menu = $('.move-mail-button li:first ul:first');
  $menu.empty();
  $('#nav_secondary').find('[foldernameglobal]').each(function(i,fldr){
    var name = $(fldr).attr('foldernameglobal');
    if(name == "Trash" || name == "Spam"){ return }
    var text = urldecode(name).replace(/%2F/g,' &gt; ').replace(/\+/g,' ');
    var btn  = $('<a tabindex="0" href="#">'+text+'</a>')
                .bind('click',moveMail)
                .attr('data-folder',name);
    var li   = $('<li></li>').append(btn);
		$menu.css('width','auto');
    $menu.append(li);
    $menu.find(':last').addClass('bottom');
  	// console.log(name);
  });
	setEmailContextTabOrder();
 // $('#action_move_mail').css('display','block');
}

function  urldecode(str){
    return decodeURIComponent((str + '').replace(/%(?![\da-f]{2})/gi, function () {
        // PHP tolerates poorly formed escape sequences
        return '%25';
    }).replace(/\+/g, '%20'));
}

function moveMail(){
  var moveToFolder = $(this).attr('data-folder');
  jsddm_close();
  // If trash click trash button
  if( moveToFolder == 'Trash' ){
    return $('#action_trash a').click();
  }

  // If spam click spam button
  if( moveToFolder == 'Spam'){
    return $('#action_not_junk').click();
  }

  visiblePanelContext = getVisiblePanelContext();
  if( $('.messageCheckbox:checked',visiblePanelContext).length > 0 ){
    contextFolder = $('#listFolder', visiblePanelContext).attr('value');
    if(contextFolder != moveToFolder){
			$('.messageCheckbox:checked', visiblePanelContext)
      	.parent()
      	.parent()
      	.moveMessages(contextFolder, moveToFolder, visiblePanelContext, null);
		}
  }
}

</script>


