<div id="mobile_viewmessage" data-role="page">
    <div id="header_viewmessage" data-role="header" data-inset="true" data-position="fixed">
        <a class="btn-back" href="#"  data-transition="slide" data-rel="back">Back</a>
        <h1>View Message</h1>

	    <ul class="menu-right" data-role="menu">
		    <li>
			    <span data-role="button" data-icon="arrow-d" data-iconpos="right">Actions</span>
			    <ul id="menu_email_operation" class="list-menu-right" data-role="listview" data-inset="true">
				    <li><a data-role="button" href="#" data-transition="slide" title="reply" data-iconpos="left" data-icon="false" >Reply</a></li>
				    <li><a data-role="button" href="#" data-transition="slide" title="replyall" data-iconpos="left" data-icon="false" >Reply All</a></li>
				    <li><a data-role="button" href="#" data-transition="slide" title="forward" data-iconpos="left" data-icon="false" >Forward</a></li>
				    <li class="menu-delete"><a data-role="button" href="#" data-transition="slide" title="delete" data-iconpos="left" data-icon="false" >Delete</a></li>
				    <li class="menu-spam"><a data-role="button" href="#" data-transition="slide" title="spam" data-iconpos="left" data-icon="false" >Spam</a></li>
			    </ul>
		    </li>
	    </ul>

    </div>

    <div id="mail_content" data-role="content" data-inset="true">

        <label class="view-msg-from">From:</label>
        <label class="view-msg-to">To:</label>

        <label class="view-msg-subject">Subject</label>
        <label class="view-msg-date">30th May 2012 12:34 PM</label>


    <!--    <div id="hidden-mail-content" style="display: none"></div>-->
        <div id="mail-header">
            <div></div>
        </div>
        <iframe id="iframe-mail-content" class="compose-body" src="" width="100%" scrolling="no" style="border-width: 0;"></iframe>

        <div id="view_attachments">
            <ul>
            </ul>
        </div>
    </div>
<?php /*
    <div id="footer_mail_view" data-role="footer" data-position="fixed" data-theme="d">

		<form id="form_quick_reply">
			<input type="submit" class="view-send-reply" value="Send"/>

			<div class="quick-reply-input"><textarea id="quick-reply-expand"  name="emailBodyText" class="input-email-reply" placeholder="Quick Reply"></textarea></div>
		</form>

    </div>
*/ ?>
</div> <!-- mobile_viewmessage -->

<script type="text/javascript">

	var $viewmessage = {
		pageinit : function() {
			$("[data-role=header]", "#mobile_viewmessage").fixedtoolbar({ tapToggle: false });
			$("[data-role=footer]", "#mobile_viewmessage").fixedtoolbar({ tapToggle: false });

			var $head = $("#iframe-mail-content").contents().find("head");
			$head.append($("<link/>",
				{ rel: "stylesheet", href: "<?php echo $this->siteBaseUrl ?>css/mobile/themes/<?php echo $this->mobileTheme ?>/mobile.css", type: "text/css" })
			);

			var bodyHtml = '<p></p>'
			renderMailBodyHtml(bodyHtml);

			var context = "#header_viewmessage";

			$('a[title=reply]',context).click(function(e) {
				e.preventDefault();
				replyEmail(function() { $.mobile.changePage('#mobile_compose', {transition:'slide'});  });
				return false;
			});

			$('a[title=replyall]',context).click(function(e) {
				e.preventDefault();
				replyAllEmail(function() { $.mobile.changePage('#mobile_compose', {transition:'slide'});  });
				return false;
			});

			$('a[title=forward]',context).click(function(e) {
				e.preventDefault();
				forwardEmail(function() { $.mobile.changePage('#mobile_compose', {transition:'slide'});  });
				return false;
			});

			$('a[title=delete]',context).click(function(e) {
				e.preventDefault();
				$('.btn-back', '#mobile_viewmessage').click();

				deleteEmail(function() {
					var curID = $mail.getCurID();

					$('.mail-row[uid=' + curID + ']', '#mobile_maillist').fadeOut(1500, function() {
						$(this).remove();
						$mail.removeMail(curID);
					})

				});

				return false;
			});

			$('a[title=spam]',context).click(function(e) {
				e.preventDefault();
				$('.btn-back', '#mobile_viewmessage').click();

				spamEmail(function() {
					var curID = $mail.getCurID();

					$('.mail-row[uid=' + curID + ']', '#mobile_maillist').fadeOut(1500, function() {
						$(this).remove();
						$mail.removeMail(curID);
					})

				});

				return false;
			});

			$('#form_quick_reply').submit(function(e) {
				e.preventDefault();
				var data = $(this).serializeObject();

				if(!data['emailBodyText']) return false;

				replyExpress(data);
				return false;
			});

			//
			// fix the virtual keyboard caused fixed position error
			//
			var footer = $('#footer_mail_view');
			$(".input-email-reply", '#form_quick_reply').live("focus", function(e) {

				footer.addClass('quick-reply-focused');
				footer.css('position', 'absolute').css('bottom','0px')

				setTimeout(function() {
					$.scrollTo('max', 0, {axis:'y'});
					$.scrollTo('+=300px', 0, {axis:'y'})
				}, 200)
			});

			$(".input-email-reply", '#form_quick_reply').live("blur", function(e) {
				footer.removeClass('quick-reply-focused');
				footer.css('position','fixed');

			});

			$(".input-email-reply", '#form_quick_reply').keyup( function() {
				if($(this).val().length < 1 ) {
					$(this).height(18);
				}
			});

			$mobile.reload();
		}
		,

		pagebeforeshow : function() {
			$('.input-email-reply', '#mobile_viewmessage').val('');

			var emailInfo = $mail.getMail();
			if(emailInfo) {
				renderMailHeader(emailInfo);
				renderAttachments(emailInfo);
			}

			$('textarea', '#form_quick_reply').height(18);

			if(isInSpamFolder()) {
			    $('.ui-btn-text', '.menu-spam a', '#mobile_viewmessage').text('Not Spam');
			}
			else {
			    $('.ui-btn-text', '.menu-spam a', '#mobile_viewmessage').text('Spam');
			}

		}
		,

		pageshow : function() {

			var emailInfo = $mail.getMail();
			if(emailInfo) {
				renderMailBodyHtml(emailInfo.bodyPreparedHtml);
			}
		}
		,

		pagebeforehide : function() {

			$iframe = $('iframe', '#mobile_viewmessage');
			$iframe.contents().find('body').html('');
			$iframe.css('height', '200px');

		}
	};

	$(document).ready(function(){
		$('body').bind('hideOpenMenus', function(){
			$("ul:jqmData(role='menu')").find('li > ul').hide();
		});
		var menuHandler = function(e) {
			$('body').trigger('hideOpenMenus');
			$(this).find('li > ul').show();
			e.stopPropagation();
		};
		$("ul:jqmData(role='menu') li > ul li").click(function(e) {
			$('body').trigger('hideOpenMenus');
			e.stopPropagation();
		});
		$('body').delegate("ul:jqmData(role='menu')",'click',menuHandler);
		$('body').click(function(e){
			$('body').trigger('hideOpenMenus');
		});


	})

	$(document).delegate("#mobile_viewmessage", "pageinit", $viewmessage.pageinit );
	$(document).delegate("#mobile_viewmessage", "pagebeforeshow", $viewmessage.pagebeforeshow);
	$(document).delegate("#mobile_viewmessage", "pageshow", $viewmessage.pageshow);
	$(document).delegate("#mobile_viewmessage", "pagebeforehide", $viewmessage.pagebeforehide);


	function editMailView($context) {
        $context.toggleClass("in-edit");
        $context.hasClass("in-edit")? $("#footer_mail_view").show() : $("#footer_mail_view").hide();
        var caption = $context.hasClass("in-edit")? "6" : "Z";
        $('.ui-btn-text', $context).html(caption);

        return false;
    }

    function renderMailSetFrom(from) {
        $('.view-msg-from', '#mobile_viewmessage').html("From: " + "<span class='blue-recipient'>" + from + "</span>");
    }

    function renderMailSetTo(to) {
	    var toHtml = "To: ";

	    $.each(to, function(i,v) {
		    toHtml += "<span class='blue-recipient'>" + htmlentities(v) + "</span>";
	    })

	    $('.view-msg-to', '#mobile_viewmessage').html(toHtml);

    }

    function renderMailSetSubject(subject) {
        $('.view-msg-subject', '#mobile_viewmessage').html(subject);
    }

    function renderMailSetDate(dateObject) {
				// console.log(dateObject);
        var date = dateObject.format('ddS mmmm yyyy HH:MM TT');
        $('.view-msg-date', '#mobile_viewmessage').html(date);
    }

    function renderMailHeader(email) {
        var from  = email.headers.from;
        var to = email.headers.to_display;
        var subject = email.headers.subject;
        var dateraw = email.headers.dateraw;
				var oDate   = new Date(dateraw);
				oDate.setTime(oDate.getTime() + (oDate.getTimezoneOffset()*60000) + ($mobile.settings['UTCOffset']*1000));

        renderMailSetFrom(from);
        renderMailSetTo(to);
        renderMailSetSubject(subject);
        renderMailSetDate( oDate );
    }

    function renderMailBodyHtml(bodyPreparedHtml) {
        var $iframe = $('#iframe-mail-content');

	    $iframe.contents().find('body').html('');
	    $iframe.height('200px');        // always reset 200 otherwise the following set won't take effect if shorter than previous height.
	    $iframe.contents().find('body').html(bodyPreparedHtml);
	    $iframe.height($iframe.contents().find("html").height());

    }

    function renderAttachments(email) {

        var $dom = $('#view_attachments ul');
        $dom.empty();

        for(var i=0; i<email.forcedInlines.length; ++i) {
            email.forcedInlines[i].filenameOriginal = jQuery('<div />').text(email.forcedInlines[i].filenameOriginal).html();
            var $row = cloneInlineAttachment(email.headers.uniqueid, email.forcedInlines[i]);

            $dom.append($row);
        }

        for(var i=0; i<email.forcedAttachments.length; ++i) {

            email.forcedAttachments[i].filenameOriginal = jQuery('<div />').text(email.forcedAttachments[i].filenameOriginal).html();
            var $row = cloneForcedAttachment(email.headers.uniqueid, email.forcedAttachments[i]);

            $dom.append($row);

        }
    }

    function showEmail($mailRow) {
        var uniqueId = $mailRow.attr('uid');
        var folder = getCurrentFolder();

        $mobile.showEmail(folder, uniqueId, function(emailInfo) {
			if(emailInfo)
			{
	            emailInfo.folder = folder;
				$mobile.setMailData(emailInfo);
				$.mobile.changePage('#mobile_viewmessage', {transition:'slide'});
			}
        });

    }

    function spamEmail(callback) {
        var mailData = $mobile.getMailData();
        var targetFolder = isInSpamFolder()?  "INBOX" : "Spam";

        $mobile.moveEmail( mailData.folder, targetFolder, mailData.headers['uniqueid'], function(){

            callback && callback();

        });
    }

    function deleteEmail(callback) {
        var mailData  = $mobile.getMailData();
				var trashFldr = "Trash"; // This was set to INBOX.Trash

        $mobile.moveEmail( mailData.folder, trashFldr, mailData.headers['uniqueid'], function(){

            callback && callback();

        });
    }

		function prepareMailTextForReply(text) {
			var TLEN = 72
			var spos = [];
			var frmt = '';
			var last = 0;

			text = text.replace(/(\r\n|\n|\r)/gm,' ');

			if(text.length < TLEN){
				return text;
			}

			for(var y = 0; y < text.length; y+=last){
			//	spos.push( (y + text.substr(y,TLEN).lastIndexOf(' ')) );
				var chnk = text.substr(y,TLEN);
				last = chnk.lastIndexOf(' ');
				frmt += chnk.substr(0,last);
			}

			return frmt;

		}

    function addReplyHeader(emailInfo) {
		  var cc  = (typeof emailInfo.headersOriginal.cc!=='undefined' ? emailInfo.headersOriginal.cc : '');
			console.log(cc);
			var replyText = "\n\n\n\n-------- Original Message ----------";
			replyText += "\nFrom: " + emailInfo.headersOriginal.from;
			replyText += "\nTo: "   + emailInfo.headersOriginal.to;
			replyText += "\nCc: "   + cc;
			replyText += "\nSent: " + emailInfo.headersOriginal.date;
			replyText += "\nSubject: " + emailInfo.headersOriginal.subject;
			replyText += "\n\n" + emailInfo.bodyPreparedText;
			
			return replyText;
    }

	function replyExpress(data) {

		var mailData = $mobile.getMailData();
        if(!mailData) {
            //cannot get mailData!
            return;
        }

		data.emailTo = mailData.headers['reply-to'];

		data.emailSubject = re.test(subject) ? subject : 'Re: ' +  mailData.headers['subject'];
		data.emailSubject = setSubjectPrefix(mailData.headers['subject'],'Re:');

		$mobile.sendEmail(data, function() {
			$('.btn-back', '#mobile_viewmessage').click();
		});

	}

	function replyEmail(callback) {
		$mail.setReplyMode();

		var subject = setSubjectPrefix($mail.getSubject(),'Re:');
		$('input[name=emailSubject]', '#mobile_compose').val(subject);

    var emailInfo = $mail.getMail();
    // console.log(emailInfo); 
		if(emailInfo)
		{
			var replyText = addReplyHeader(emailInfo);
			adjustTextArea(replyText);
	
			callback && callback();   			
		}
		else {
			alert('Cannot read current email! please reload your mail list');
		}
	}

	function replyAllEmail(callback) {
		$mail.setReplyAllMode();
		var subject = setSubjectPrefix($mail.getSubject(),'Re:');

		$('input[name=emailSubject]', '#mobile_compose').val(subject);

		var emailInfo = $mail.getMail();
       
		if(emailInfo)
		{
			var replyText = addReplyHeader(emailInfo);
			adjustTextArea(replyText);
	
			callback && callback();   			
		}
		else {
			alert('Cannot read current email! please reload your mail list');
		}
	}

	function forwardEmail(callback) {
		$mail.setForwardMode();

		var subject = setSubjectPrefix($mail.getSubject(),'Fwd:');

		$('input[name=emailSubject]', '#mobile_compose').val(subject);

		var emailInfo = $mail.getMail();
       
		if(emailInfo)
		{
			var replyText = addReplyHeader(emailInfo);
			adjustTextArea(replyText);
	
			callback && callback();   			
		}
		else {
			alert('Cannot read current email! please reload your mail list');
		}
	}

  function setSubjectPrefix(subject,prefix){
		var re = /^(re|fwd*)\:/i;
		return subject.replace(re,prefix);
	}
</script>


