<div id="mobile_compose" data-role="page">

    <div data-role="header" data-inset="true" data-position="fixed">
        <a class="compose-cancel" href="#" data-rel="back">Cancel</a>
        <h1>Compose</h1>
			<div data-role="controlgroup" data-type="horizontal" class="maillist-header-btn-group">
        		<a href="#" class="compose-send" data-role="button">Send</a>
				<a href="#" class="compose-save" data-role="button">Save</a>
			</div>
    </div>

    <div data-role="content" data-inset="true">
        <form id="id_compose_form" action="api/mobilemail/send" method="post" target="#mobile_maillist">
	        <div class="leftcompose">
		        <strong>To:</strong>
	        </div>
	        <div class="rightcompose">
		        <div id="form_to">
			        <input type="text" name="emailTo" value='' id="id_input_to" class="email-input"/>
		        </div>
	        </div>

	        <div class="leftcompose">
		        <strong class="form-cc-label">Cc:</strong>
	        </div>
	        <div class="rightcompose">
		        <div id="form_cc">
			        <input type="text" name="emailCc" value='' id="id_input_cc" class="email-input"/>
		        </div>
	        </div>

	        <div class="leftcompose">
		        <strong class="form-bcc-label">Bcc:</strong>
	        </div>
	        <div class="rightcompose">
		        <div id="form_bcc">
			        <input type="text" name="emailBcc" value='' id="id_input_bcc" class="email-input"/>
		        </div>
	        </div>


<!--
            <label for="id_input_to" class="ui-hidden-accessible">To:</label>
            <input id="id_input_to" class="input-email" type="text" name="emailTo" value="" placeholder="To"/>
            <ul id="id_input_to_autocomplete" data-role="listview" data-inset="true"></ul>

            <label for="id_input_cc" class="ui-hidden-accessible">To:</label>
            <input id="id_input_cc" class="input-email" type="text" name="emailCc" value="" placeholder="Cc"/>
	        <ul id="id_input_cc_autocomplete" data-role="listview" data-inset="true"></ul>

	        <label for="id_input_bcc" class="ui-hidden-accessible">To:</label>
            <input id="id_input_bcc" class="input-email" type="text" name="emailBcc" value="" placeholder="Bcc" style="display: none;"/>
	        <ul id="id_input_bcc_autocomplete" data-role="listview" data-inset="true"></ul>

-->
<!--            <label for="id_text_compose" class="ui-hidden-accessible">Compose:</label>-->

	        <label for="id_input_subject" class="ui-hidden-accessible">Subject:</label>
	        <input id="id_input_subject" type="text" name="emailSubject" value="" placeholder="Subject"/>

	        <textarea id="id_text_compose" name="emailBodyText" placeholder="Compose here"></textarea>
	        
	        <div class="attachments" style="display:none;">
	        	
	        </div>

        </form>
    </div>

</div>

<script type="text/javascript">
	var emailToTextBoxListHandle;
	var emailCcTextBoxListHandle;
	var emailBccTextBoxListHandle;

	function enableSendButton(bEnable) {
		if(bEnable) {
			$('.compose-send', '#mobile_compose').attr('disabled','').css('opacity','1.0');
		}
		else {
			$('.compose-send', '#mobile_compose').attr('disabled','true').css('opacity','0.6');
		}
	}


	function initializeTextboxList() {
		emailToTextBoxListHandle = new TextboxList($('#id_input_to', '#mobile_compose'), {
			bitsOptions : {editable : {addOnBlur : true }},
			unique : false,
			onUpdate : function(handle) {
				enableSendButton(handle.val())
			},
			plugins : {autocomplete : {placeholder : false, cacheSize : $mobile.autocompleteCacheSize }}
		});
		emailCcTextBoxListHandle = new TextboxList(  $('#id_input_cc',  '#mobile_compose'), {bitsOptions:{editable:{addOnBlur:true }}, unique: false, plugins: {autocomplete: {placeholder:false,cacheSize: $mobile.autocompleteCacheSize }}});
		emailBccTextBoxListHandle = new TextboxList( $('#id_input_bcc', '#mobile_compose'), {bitsOptions:{editable:{addOnBlur:true }}, unique: false, plugins: {autocomplete: {placeholder:false,cacheSize: $mobile.autocompleteCacheSize }}});
	

		if( $.jCacher.get('autocomplete') )
		{
			var 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: 'mail/contacts/autocomplete/limit/50',
				dataType: 'json',
				success: function(r)
				{
					// above static lookup, enable dynamic lookup
/*					if(r.length >= 50)
					{
						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);
				}
			})
		}
	}

	function splitEmail(emailstr) {

		if(!emailstr) {
			return [];
		}

		// the /,(?=(?:[^"]|"[^"]*")*$)/ regex prevents the string from
		// splitting on commas inside quotes
		var newArray = emailstr.split(/,(?=(?:[^"]|"[^"]*")*$)/);
		newArray = unique(newArray);

		for(var index in newArray) {

			//already html entities
			//newArray[index] = $('<div/>').text( newArray[index] ).html()
			//TextboxList.add = function(plain, id, html, afterEl)
			if( newArray[index].length > 0 )
			{
				newArray[index] = $.trim(html_entity_decode(newArray[index]));

				// remove blank descriptions
				if(	newArray[index].indexOf('"" ') == 0 ||
					newArray[index].indexOf("'' ") == 0)
				{
					newArray[index] = newArray[index].substring(3);
				}

				// remove <> from just emails
				if(newArray[index][0] == '<' && newArray[index][newArray[index].length - 1] == '>')
				{
					newArray[index] = newArray[index].substring(1, newArray[index].length - 1);
				}

			}
		}

		return newArray;
	}

	function setReplyBox(val, handle) {
		if(!val) {
			return;
		}

		if(!handle) {
			handle = emailToTextBoxListHandle;
		}

		var emails = splitEmail(val);
		for(var i in emails) {
			var recip = emails[i].toLowerCase();
			var me    = $mobile.settings['Account'].toLowerCase();
		  if(recip.indexOf(me) === -1){
				handle.add( emails[i] );
			}
		}
	}

	function updateReplyFields() {
		// clear textboxlist first
		$('li.textboxlist-bit-box-deletable', '#mobile_compose').remove()
		$('li.textboxlist-bit-editable', '#form_to').not(':last').remove();
		$('li.textboxlist-bit-editable', '#form_cc').not(':last').remove();
		$('li.textboxlist-bit-editable', '#form_bcc').not(':last').remove();
		$('.rightcompose>div>input', '#id_compose_form').val('');

		if($mail.isModeNew()) {
			adjustTextArea('');
		}
		else if($mail.isModeForward()) {
		}
        else if($mail.isModeNewFromConatct()) {
            setReplyBox( $mail.mailFromContact );
        }
		else if($mail.isModeReply()) {
			setReplyBox( $mail.getReplyTo());
		}
		else if($mail.isModeReplyAll()) {
			setReplyBox( $mail.getReplyAllTo());
			setReplyBox( $mail.getReplyAllCc(), emailCcTextBoxListHandle );
		}
		
		var attachmentsDiv = $(".attachments", '#id_compose_form');
		attachmentsDiv.empty();
		
		
		if($mail.isModeForward()) {
			
			var attachments = $mail.getMail()['attachmentsList'];
			
			if(attachments && attachments.length) 
			{

				var i = 0;
				for(var k in attachments) 
				{
					var $inputFS = $('<input/>').attr('type','hidden').attr('name','attachments['+i+'][filenameFS]').val(attachments[k]['filenameFS']);
					attachmentsDiv.append($inputFS);
					
					var $inputOri = $('<input/>').attr('type','hidden').attr('name','attachments['+i+'][filenameOriginal]').val(attachments[k]['filenameOriginal']);
					attachmentsDiv.append($inputOri);
					
					var $inputMime = $('<input/>').attr('type','hidden').attr('name','attachments['+i+'][mimeType]').val(attachments[k]['mimeType']);
					attachmentsDiv.append($inputMime);

					++i;
				}
							
			}			
			
		}

	}

    function checkComposeData() {
        var data = $('#id_compose_form').serializeObject();

        if(!data.emailTo && !data.emailCc && !data.emailBcc) {
            alert('Recipient cannot be empty!');
	        $('#id_input_to').focus();
            return false;
        }

        if(!data.emailSubject && !confirm('The message does not contain a subject. Are you sure you want to send?') ) {
	        $('#id_input_subject').focus();
            return false;
        }

        if(!data.emailBodyText && !confirm('The message does not contain content in the body. Are you sure you want to send?') ) {
	        $('#id_text_compose').focus();
            return false;
        }

        return true;
    }

	function sendEmail() {
		$("#id_compose_form").submit();
	}

	function saveDraft(){
		var data = $("#id_compose_form").serialize();
		$mobile.saveDraft(data,function(json){
			if(json.UID){
				$("#id_compose_form").append('<input type="hidden" name="draftUID" value="'+json.UID+'" />');
			} else {
				var err = json.error? json.error:"Unable to save draft";
				alert(err);
			}
		});
	}

	function showBcc() {
		$('.form-cc-label', '#id_compose_form').html("Cc:");
		$('.form-bcc-label', '#id_compose_form').parent().show();
		$('#form_bcc').parent().show();
	}

	function hideBcc() {
		$('.form-cc-label', '#id_compose_form').html("Cc/Bcc:");
		$('.form-bcc-label', '#id_compose_form').parent().hide();
		$('#form_bcc').parent().hide();
	}

	function adjustTextArea(value) {
		var $textarea = $('#id_text_compose');

		var signature = $mobile.getSignature();
		if( signature && signature.length > 0) {
			value = '\n\n' + signature + '\n\n' + value;
		}

		$textarea.val(value);
		$textarea.height(100);

		setTimeout(function(){

			var maxHeight = Math.max($textarea[0].scrollHeight, $textarea[0].clientHeight) + 20;
			if(maxHeight < 100) {
				maxHeight = 100;
			}

			$textarea.height(maxHeight);
			
		}, 400);


	}

	$( document ).delegate( "#mobile_compose", "pageinit", function() {

		initializeTextboxList();

        $(".compose-send", '#mobile_compose').click(function(e) {
            e.preventDefault();
	        e.stopPropagation();

	        if($(this).attr('disabled')==='true') {
		        return false;
	        }

            if(checkComposeData() ) {
                sendEmail();
            }

            return false;
        });

			$(".compose-save",'#mobile_compose').click(function(e){
				e.preventDefault();
				e.stopPropagation();
				
				saveDraft();
			});

        if(!isAndroid()) {
			$('.textboxlist', '#id_compose_form').click(function(e) {
				$('input:last', $(this)).focus();

				if($(this).parent().attr('id') === 'form_cc') {
					showBcc();
				}

				return false;
			})

			$('.leftcompose', '#id_compose_form').click(function(e) {
				$('input:last', $(this).next()).focus();

				if($('.form-cc-label', $(this)).length) {
					showBcc();
				}

				return false;
			})        	
        }

		$("#id_compose_form").submit(function(e){
			e.preventDefault();

			var data = $(this).serialize();
			$mobile.sendEmail(data);
		});

		$mobile.reload();
	});

	$("#mobile_compose").bind('pagebeforeshow', function() {
		if(!isAndroid()) {
			hideBcc();
		}

		updateReplyFields();
		enableSendButton($('#id_input_to').val());
	})


</script>

