<div id="mobile_folderlist" data-role="page">
    <div data-role="header" data-inset="true" data-position="fixed">
		<a class="main-menu" href="#" data-slidemenu="#slidemenu" data-slideopen="false" data-icon="smico" data-corners="false" data-iconpos="notext">Menu</a>
        <h1>Home</h1>
        <a class="header-button-edit" href="#" onclick="toggleFolderlistEditMode();">Z</a>
    </div>

    <div data-role="content" data-inset="true">
<!--
        <ul id="list_mail_folder" data-role="listview" data-split-theme="b" data-split-icon="delete">

								</ul>
-->
    </div>


    <div id="footer_folder" data-role="footer" data-inset="true" data-position="fixed" style="display:none;">
        <!--
        <div data-role="navbar" class="footer-normal" style="display:none">
            <ul>
                <li>
                    <a title="contacts" href="#mobile_groups" data-icon="contact-group" data-transition="slide"></a>
                </li>

				<li>
                    <a title="calendar" href="#mobile_calendars" data-icon="calendar" data-transition="slide"></a>
                </li>

                <li>
                    <a title="settings" href="#mobile_settings" data-icon="settings" data-iconpos="top" data-transition="slide"></a>
                </li>

                <li>
                    <a title="logout" href="#" data-icon="logout" data-iconpos="top" data-transition="slide"></a>
                </li>
            </ul>
        </div>
    -->
	    <div data-role="navbar" class="footer-edit-mode">
		    <ul>
			    <li>
				    <a href="#" data-icon="new-folder" data-iconpos="left" onclick="createFolder($(this));"></a>
			    </li>
		    </ul>
	    </div>
	</div>
</div>

<div id="mobile_folderselection_list" data-role="page">
    <div data-role="header" data-inset="true" data-position="fixed" >
	    <a class="btn-back" href="#"  data-rel="back">Cancel</a>
	    <h1>Select Folder</h1>
    </div>

    <div data-role="content">
        <ul id="selection_mail_folder" data-role="listview">

        </ul>
    </div>

</div>

<script type="text/javascript">
    function buildFolderSelection(folderList) {
        var $ul = $('#selection_mail_folder');
        $ul.empty();

        for(var i = 0; i < folderList.length; ++i) {
	        if($mobile.getCurrentFolderGlobalName() === folderList[i].globalName) {
		        continue;
	        }

            var $node = $('<li class="mail-folder"><a  class="folder-mail"></a></li>').clone();
            $('a', $node).html(getFolderHtmlName(folderList[i].localName)).data('folderData', folderList[i]);

            $('a', $node).click(function() {
                var UIDs = getSelectedMailUIDs();
                var fromFolder = $mobile.getCurrentFolderGlobalName();
                var toFolder = $(this).data('folderData').globalName;


	            var selectedRows = getSelectedMailNodes();
	            
	            $('.btn-back', '#mobile_folderselection_list').click();
	           	enableMaillistEditMode(false);

                $mobile.moveEmail(fromFolder, toFolder, UIDs, function(json) {
                	setTimeout(function(){
		                uiRemoveMailRows(selectedRows);
	                }, 1000);
                });

            });

            $ul.append($node).listview('refresh');
        }
    }

	/**
	 * toggle edit mode
     * @param mode null-do toggle, 1-on, -1-off
	 */
    function toggleFolderlistEditMode(mode) {
        $context = $('.header-button-edit', '#mobile_folderlist');

        if(mode==1 && $context.hasClass('in-edit') || mode==-1 && !$context.hasClass('in-edit')) {
            return;
        }

        $context.toggleClass("in-edit");

        var inEditMode =  $context.hasClass("in-edit");
        var caption = inEditMode ? "Done" : "Edit";
        $('.ui-btn-text', $context).html(caption);
        toggleDeleteButton(inEditMode);

		if(inEditMode) {
			//$(".footer-normal", "#mobile_folderlist").hide();
			$("#footer_folder", "#mobile_folderlist").show();
		}
		else {
			//$(".footer-normal", "#mobile_folderlist").show();
			$("#footer_folder", "#mobile_folderlist").hide();

		}


		$('.ui-icon-arrow-r').toggle();
    }

    function createFolder($context) {

        mobilePrompt('Folder Name', function(name) {
            $mobile.createFolder(name, function() {
                var folder = {
                    localName : name,
                    globalName : "INBOX." + name,
                    selectable: true
                }
                renderFolder(folder, $("#list_mail_folder"));
            })
        });
    }

	function deleteFolder($context) {
		var data = $context.data('folderData');

		if(!confirm("Are you sure to delete the folder [" + data.localName + "] and along with all emails inside?" )) {
			return;
		}

		$mobile.deleteFolder(data.globalName, function() {
			$context.parent().fadeOut('slow', function() {
				$context.parent().parent().parent().remove();
			})
		})
	}

    function getFolderName(folderGlobalName) {
		var idx = folderGlobalName.lastIndexOf('.');
	    return idx < 0 ? folderGlobalName : folderGlobalName.substring(idx + 1);
    }

    function getFolderHtmlName(folderGlobalName) {
	    var depth = folderGlobalName.split(".").length - 2;

	    var indent = '';
	    for(var i=0; i<depth; ++i) {
		    indent += '&nbsp;&nbsp;'
	    }

	    return getFolderName(folderGlobalName);
    }

    function getFolderLevel(folderGlobalName) {
	    var depth = folderGlobalName.split(".").length - 2;

		return depth>0? depth : 0;
    }

	function renderFolder(data, $placeDom, $contactBtn) {
		var folderGlobalName = data.globalName;
		var $node = cloneFolderRow();


        var id = "folder_" + ( data.isMainFolder? data.localName.toLowerCase().replace(" ", "_") : CryptoJS.MD5(data.globalName).toString() );
        $node.attr('id', id);

        if(data.isMainFolder) {
            $node.removeClass('custom-folder').addClass('system-folder');
        }

			var subLevel = getFolderLevel(folderGlobalName);
			if(subLevel>0) {
				$node.addClass('sub-folder').addClass('level-'+subLevel);
			}

			$('a', $node).data('folderData', data);
			$('span.folder-name', $node).html(getFolderHtmlName(folderGlobalName));

		if(!data.isMainFolder){
			$placeDom.append($node).listview('refresh');
		} else {
			if(folderGlobalName.toLowerCase()==='inbox'){
				$contactBtn.before($node);
			} else {
				$contactBtn.after($node);
			}
		}
	}

	function renderFolders(json) {
		//TODO: check result when failure

        toggleFolderlistEditMode(-1);
		var $btn = $('ul.folders-list li.contacts-page-button').remove();
		var $placeDom = $("#list_mail_folder");

		$('ul.folders-list').empty().append($btn);
		$placeDom.empty();

		if(json instanceof Array) {
			for(var i=0; i< json.length; ++i) {
				renderFolder(json[i],$placeDom,$btn);
			}
		}
	}

    function updateFolderTotals() {

	    return;
	    /* disabled because performance issue
        $mobile.updateFolderTotals(function(json) {
            if(json instanceof Array) {
                $.each(json, function(i,v) {

                    $unseen = $('#' + v.id +' span.ui-li-count', '#list_mail_folder');

                    if(v.info.unseen == 0) {
                        $unseen.hide();
                    }
                    else {
                        $unseen.addClass('enabled').html(v.info.unseen).show();
                    }

                });
            }
        })
        */
    }

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

		$('a[title=calendar]', '#mobile_folderlist').bind('click', function(e) {
			e.preventDefault();
			calendars.list();
			return false;
		});

	    $mobile.reload();
    });

    $( document ).delegate( "#mobile_folderlist", "pageshow", function() {
	    setHeaderCaption( "#mobile_folderlist", $mobile.getAccount() );

	    if($mailfolder.needReloadFolderlist()) {

		    $mobile.listFolder(function(json) {

			    renderFolders(json);
			    updateFolderTotals();

			    $mailfolder.updateFolderlistTimestamp();

		    })

	    }

    });

    $(document).delegate("#mobile_folderlist", "pagebeforehide", function() {
		closeSlideMenu();
	});

    $( document ).delegate( "#mobile_folderselection_list", "pageshow", function() {
        $mobile.listFolder(function(json) {
            buildFolderSelection(json);
        })
    });

</script>
