{{main_id='editor_main'}}
{{extend 'layout.html'}}
{{
dirs=[{'name':'models', 'reg':'.*\.py$'},
      {'name':'controllers', 'reg':'.*\.py$'},
      {'name':'views', 'reg':'[\w/\-]+(\.\w+)+$'},
      {'name':'modules', 'reg':'.*\.py$'},
      {'name':'static', 'reg': '[^\.#].*'},
      {'name':'private', 'reg':'.*\.py$'}]
   
def file_create_form(location, anchor=None, helptext=""):
    form=FORM(
            LABEL(T("create file with filename:")),
            SELECT(_name='dir', _style='width:100px;', 
               *[OPTION(dir['name'], _value=dir['name']) for dir in dirs]),
            XML('&nbsp;'),LABEL('/', _style='display:inline-block;'),XML('&nbsp;'),
            INPUT(_type="text",_name="filename",requires=IS_NOT_EMPTY(),_class=''),
            TAG['SMALL'](helptext,_class="help-block"),
            INPUT(_type='submit', name=T('filename'), _value=T('Create'), _style='display:block', _id='btn_file_create'), 
            INPUT(_type="hidden",_name="editor"),
            INPUT(_type="hidden",_name="location",_value=location),
            INPUT(_type="hidden",_name="sender",_value=URL('design',args=app)),
            INPUT(_type="hidden",_name="token",_value=session.token),
            #INPUT(_type="hidden",_name="id",_value=anchor),
            _action=URL('create_file'),
            _id='file_create_form',
            _class="generatedbyw2p well well-small")
    return form
            
}}

<!-- begin "edit" block -->
{{
  def shortcut(combo, description):
    return XML('<li class="span5"><span class="teletype-text">%s</span><span>%s</span></li>' % (combo, description))
  def listfiles(app, dir, regexp='.*\.py$'):
      files = sorted(
         listdir(apath('%(app)s/%(dir)s/' % {'app':app, 'dir':dir}, r=request), regexp))
      files = [x.replace(os.path.sep, '/') for x in files if not x.endswith('.bak')]
      return files

  def editfile(path,file,vars={}):
      args=(path,file) if 'app' in vars else (app,path,file)
      url = URL('edit', args=args, vars=vars)
      return A(file, _class='editor_filelink', _href=url, _style='word-wrap: nowrap;')
}}
{{cm=URL('static', 'codemirror')}}
{{js_url=URL('static', 'js')}}
{{css_url=URL('static', 'css')}}
<link rel="stylesheet" href="{{=cm}}/lib/codemirror.css">
<link rel="stylesheet" href="{{='%s/theme/%s.css' % (cm, editor_settings['theme'])}}">
<script src="{{=cm}}/lib/codemirror.js"></script>
<script src="{{=cm}}/addon/edit/matchbrackets.js"></script>
<script src="{{=cm}}/addon/edit/closetag.js"></script>
{{if editor_settings['editor'] != 'default':}}<script src="{{='%s/keymap/%s.js' % (cm, editor_settings['editor'])}}"></script>{{pass}}
<script src="{{=cm}}/mode/python/python.js"></script>
<script src="{{=cm}}/mode/xml/xml.js"></script>
<script src="{{=cm}}/mode/css/css.js"></script>
<script src="{{=cm}}/mode/javascript/javascript.js"></script>
<script src="{{=cm}}/mode/htmlmixed/htmlmixed.js"></script>
<script src="{{=cm}}/addon/hint/show-hint.js"></script>
<script src="{{=cm}}/addon/hint/python-hint.js"></script>
<link rel="stylesheet" href="{{=cm}}/addon/hint/show-hint.css">
<script src="{{=cm}}/addon/search/search.js"></script>
<script src="{{=cm}}/addon/search/searchcursor.js"></script>
<script src="{{=cm}}/addon/dialog/dialog.js"></script>
<script src="{{=cm}}/addon/edit/trailingspace.js"></script>
<link rel="stylesheet" href="{{=cm}}/addon/dialog/dialog.css">
<script src="{{=cm}}/addon/selection/active-line.js"></script>
<script src="{{=cm}}/addon/display/fullscreen.js"></script>
<link rel="stylesheet" href="{{=cm}}/addon/display/fullscreen.css">
<script src="{{=cm}}/addon/fold/foldcode.js"></script>
<script src="{{=cm}}/addon/fold/foldgutter.js"></script>
<script src="{{=cm}}/addon/fold/brace-fold.js"></script>
<script src="{{=cm}}/addon/fold/xml-fold.js"></script>
<script src="{{=cm}}/addon/fold/comment-fold.js"></script>
<script src="{{=cm}}/addon/fold/indent-fold.js"></script>
<script src="{{=cm}}/addon/comment/comment.js"></script>
<link rel="stylesheet" href="{{=cm}}/addon/fold/foldgutter.css">
<script src="{{=cm}}/emmet.min.js"></script>
<script src="{{=js_url}}/ajax_editor.js"></script>
<link rel="stylesheet" href="{{=css_url}}/typeahead.js-bootstrap.css">
<link rel="stylesheet" href="{{=css_url}}/web2py-codemirror.css">
<script type="text/javascript">
var current_font_incr = 0; // Default font-size, 0 means isn't set
$(document).on('shown click', 'a[data-toggle="tab"]', function (e, lineno) {
    var tab_id = $(this).attr('href');
    var editor = $(tab_id + " textarea").data('editor');
    if (editor) {
        editor_height = $(window).height() - $(tab_id + " .well-small").offset().top - $(tab_id + " .well-small").outerHeight(true) - $('.navbar-fixed-bottom').outerHeight() - 60;
        editor.setSize('100%', editor_height);
        editor.refresh();
        if (lineno !== undefined) {
            editor.setCursor(lineno);
            editor.centerOnCursor();
        }
    }
    var n_li = $('#filesTab li').length;
    $.each($('#filesTab li'), function(index, element) {
        $(element).css('max-width', 100/n_li + '%' );
    });
    //$(function(){$('.CodeMirror-scroll').css("height","auto").css("overflow-x","auto");});
});

// Close the selected tab
$(document).on('click', '#filesTab button[class="close"]', function (e) {
    var tab_body   = $($(this).parent().attr("href"));  // it should be a div
    var tab_header = $(this).parent().parent();              // it should be a li
    var saved = $(tab_body.find('textarea').data('editor')).data('saved');
    var close = true;
    if (saved === false) {
        close = confirm("You are closing an unsaved file")
    }
    if (close) {
        if (tab_header.hasClass('active') === true) {     //Set active an other tab
            var $prev = $(tab_header).prev();
            if ($prev.length) {
                $prev.children('a[data-toggle="tab"]').tab('show'); // select previous tab
            } else {
                $(tab_header).next().children('a[data-toggle="tab"]').tab('show'); // select next tab
            }
        }
        tab_header.remove(); //remove li of tab
        tab_body.remove();   //remove tab content (div)
    }
});

// Revert current file
$(document).on('click', '#revert', function (e) {
    e.preventDefault();
    load_file($(this).attr("href"));
});
// Restore current file
$(document).on('click', '#restore', function (e) {
    e.preventDefault();
    load_file($(this).attr("href"));
});

// open the selected file
$(document).on('click', 'a.editor_filelink, a#editor_settingslink', function (e) {
    e.preventDefault();
    var url = $(this).attr("href");
    var lineno = $(this).data("lineno");
    load_file(url, lineno);
});

/* This method updates all editors already instantiated with the selected preferences*/
function update_editor(preferences) {
    var href = "{{="%s/theme/" % cm}}" + preferences.theme + ".css";
    var link = $("<link>");
    link.attr({
        type: 'text/css',
        rel: 'stylesheet',
        href: href
    });
    $("head").append( link );
    if ( preferences.editor != 'default'){
        var src = "{{='%s/keymap/' % cm}}" + preferences.editor + ".js";
        //var src = "/admin/static/codemirror/keymap/" + editor_name + ".js";
        var script = $("<script>");
        script.attr({
            src: src
        });
        $("head").append( script );
    }

    $('textarea[name="data"]') .each(function(id, ta) {
        editor = $(ta).data('editor');
        editor.setOption("theme", preferences.theme);
        editor.setOption("keyMap", preferences.editor);
        editor.setOption("autoCloseTags", (preferences.closetag === 'true'));
        editor.setOption("foldGutter", (preferences.codefolding === 'true'));
        editor.setOption("indentUnit", parseInt(preferences.tabwidth));
        editor.setOption("tabSize", parseInt(preferences.tabwidth));
        editor.setOption("indentWithTabs", (preferences.indentwithtabs === 'true'));
        gutters = editor.getOption("gutters");
        if ( preferences.linenumbers === 'true' && $.inArray('CodeMirror-linenumbers', gutters) === -1 ) {
            gutters.splice(0, 0, 'CodeMirror-linenumbers');
            editor.setOption("gutter", gutters);
        }
        editor.setOption("lineNumbers", (preferences.linenumbers === 'true'));
        editor.setOption("styleActiveLine", (preferences.highlightline === 'true'));
    });
}

// incr/decr editor font-size
$(document).on('click', 'a.font_button', function (e) {
    e.preventDefault();
    var id = $(this).attr('id');
    var new_font_incr;
    switch (id) {
        case 'incr': new_incr = 2; break;
        case 'decr': new_incr = -2; break;
        case 'default': new_incr = 0;
    }
    $('textarea[name="data"]').each(function(id, ta) {
        editor = $(ta).data('editor');
        set_font(editor, new_incr);
    });
    current_font_incr = (new_incr !== 0) ? current_font_incr + new_incr : 0;
});
</script>

{{block sectionclass}}edit{{end}}

<div class='row-fluid'>
<div class="right controls btn-toolbar pull-right">

{{=LOAD('default', 'editor_sessions', ajax=True, _class='btn-group')}}

<div class="btn-group">
  <a class="button btn" onclick="$('#files').toggle(); return false" href="#">Files toggle</a>
</div>
<div class="btn-group">
    <a id="decr" class="button btn font_button">-</a>
    <a id="default" class="button btn font_button" >A</a>
    <a id="incr" class="button btn font_button">+</a>
</div>
<div class="btn-group">
  {{=button(URL('design',args=request.vars.app if request.vars.app else request.args[0], anchor=request.vars.id), T('back'))}}
  <a class="button btn" href="http://web2py.readthedocs.org/en/latest/" target="_blank"><span>{{=T('docs')}}</span></a>
  <a class="button btn" title="{{=T('change editor settings')}}" id="editor_settingslink" href="{{=URL('default', 'edit', args=request.args, vars={'settings':True})}}"><i class="icon-cog"></i></a>
</div>
</div>
</div>
<div id="editor_area" class="row-fluid">
    <div id="files">
        <div class="files-toggle"><span class="arrow"></span></div>
        <div class="files-menu">
            <ul class="nav nav-list" rel="pagebookmark" id="filelist">
            <li><input type="text" placeholder="{{=T('Rapid Search')}}" class="input-block-level typeahead-tw search-query"></li>
            {{auto_complete_list=[]}}
            <br />
            <div>
      	      <button onclick="jQuery('#form').slideToggle()" class="btn btn-mini">{{=T('Create')}}</button>
      	      <br />
	      <div id="form">
        	<div>
        	  {{=file_create_form('%s/' % app, '')}}
        	</div>          			  			
      	      </div>
      	      <script>jQuery('#form').slideToggle()</script>
    	    </div>
    	    <br />            
            <div id="files_menu">
              {{=LOAD('default', 'files_menu', vars={'app':app}, ajax=True)}}
            </div>
            </ul>
        </div>
    </div>
    <div class="span12" id="edit_placeholder">
        <ul class="nav nav-tabs " id="filesTab">
        </ul>
        <div id="myTabContent" class="tab-content">
        </div>
    </div>
    <section id="windows_divs" class="tab-content  ">
        <div id="window_todo" class="tab-pane container-fluid">
            {{=LOAD('default', 'todolist.load', vars={'app':app}, ajax=True, timeout=60000, times="infinity")}}
        </div>
        <div id="window_shortcuts" class="tab-pane container-fluid">
            {{include 'default/editor_shortcuts.html'}}
        </div>
        <div id="window_dbhooks" class="tab-pane container-fluid">
            <h4>Tables hooks</h4>
            <div>{{=LOAD(url="/%s/appadmin/hooks" % app, ajax=True, timeout=60000, times="infinity")}}</div>
        </div>
    </section>
</div>
{{block footer}}
<div id="" class="navbar navbar-inverse navbar-fixed-bottom">
<div class="navbar-inner">
<ul id="windows_hooks" class="nav">
    <li class=""><a href="#window_todo">TODO</a></li>
    <li class=""><a href="#window_shortcuts">Shortcuts</a></li>
    <li class=""><a href="#window_dbhooks">Hooks</a></li>
</ul>
</div>
</div>

<script>
    $(document).on('click', '#window_todo li a', function (e) {
        $(this).find('i').toggleClass('icon-chevron-right');
        $(this).find('i').toggleClass('icon-chevron-down');
    });
    $('#windows_hooks li a').click(function (e) {
        e.preventDefault();
        if ( $(this).parent('li').hasClass('active') ) {
            $(this).parent('li').removeClass('active');
            $($(this).attr('href')).removeClass('active');
        } else {
            $(this).tab('show');
        }
    });
</script>
{{end}}
<script>
$(document).ready(function() {
    var filesMenu = $('#files');
    var ow = filesMenu.outerWidth();
    filesMenu.width(ow);
    $('#files').css('left', '-'+ow+'px');
    $.web2py.trap_form('url', 'form');
    $('#form form').addClass('no_trap'); // Let to reuse the same form
    {{if len(request.args) > 1:}}
    load_file('{{=URL(f='edit', args=request.args, vars=request.get_vars)}}', {{=request.vars.lineno or 1}});
    {{pass}}
});
</script>
<!-- Typeahead scripts here so the page load faster -->
<script src="{{=URL('static', 'js/typeahead.min.js')}}"></script>
<script src="{{=URL('static', 'js/hogan-2.0.0.js')}}"></script>
<script>
    $('.typeahead-tw').typeahead({
        name: 'files',
        local:{{from gluon.serializers import json}}{{=XML(json(auto_complete_list))}},
        template: template_js,
        engine: Hogan,
    });
    $(document).on("typeahead:selected", '.typeahead', function(e, datum) {
        load_file(datum.link);
        $(this).val('');
    });
    /* handlers to manage editor sessions
    */
    $(document).on('click', '#save_session', function(e) {
        e.preventDefault();
        var session_name=prompt("Session name","{{=app}}");

        if (session_name!==null) {
            files = $("[data-path]").map(function(){return $(this).data("path");}).get();
            data = JSON.stringify({ files: files, session_name:session_name});
            $.ajaxSetup({contentType: "application/json"});
            $.web2py.ajax_page("POST", "{{=URL('default', 'editor_sessions')}}", data, 'manage_sessions');
        }
    });
    $(document).on('click', '#saved_sessions a[data-files]', function(e) {
        e.preventDefault();
        files = $(this).data('files');
        array_files = files.split(',');
        $.each(array_files, function(index, value) {
            url = "{{=URL('default','edit')}}/" + value;
            load_file(url);
        });
    });

</script>
<!-- end "edit" block -->
