{% load i18n %}
{% load staticfiles %}
{% load wooey_tags %}
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>{% block title %}{% get_wooey_setting "WOOEY_SITE_NAME" %}{% endblock title %}</title>
    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="//cdn.datatables.net/1.10.6/css/jquery.dataTables.min.css"/>
    <link rel="stylesheet" href="//cdn.datatables.net/responsive/1.0.5/css/dataTables.responsive.css"/>

    <link rel="stylesheet" href="{% static "wooey/css/simple-sidebar.css" %}"/>
    <link href='//fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>

    {% block extra_css %}
    {% endblock extra_css %}


    <style>

        a:hover {
            text-decoration: none;
        }

        body {
            padding-top: 40px; /* navbar */

        }

        .wooey_script_thumbnail .wooey_script_icons {
            position: absolute;
            top: 5px;
            right: 5px;
        }


        .wooey_script_thumbnail {
            position: relative;
        }

        .wooey_script_disabled:hover {
            background: none;
        }

        .wooey-script-group {
            text-transform: uppercase;
            color: #ccc;
            font-size:0.8em;
            font-weight:bold;

            position: absolute;
            bottom: 2px;
            right: 2px;
        }

        .wooey_script_disabled {
            color: #ccc !important;
        }


        .navbar {
            border-radius: 0;
        }

        ol.navbar-breadcrumb {
            float: left;
        }


        .navbar-breadcrumb {
            margin-left: -5px;
            color: #9d9d9d;
            background-color: inherit;
            font-family: "Helvetica Neue",Helvetica,Roboto,Arial,sans-serif;
            font-size: 14px;
            font-style: normal;
            font-weight: 400;
            margin-bottom: 0;
            border-radius: 0;
            padding: 0;
        }

        .navbar-breadcrumb > li {
            line-height: 20px;
            padding: 15px 0px;
        }


        h5 {
            font-weight: bold;
            text-transform: uppercase;
            font-size: 1em;
            color: #555;
        }


        .wooey {
            font-family: 'Pacifico',cursive;
            color: #fff !important;
        }

        .jumbotron.frontpage {
            background-color: #004D66;
            text-align: center;
            margin-bottom:0px;
        }

        .jumbotron.frontpage h1 {
            font-size: 80px;
            color: #fff;
        }
        .jumbotron.frontpage p {
            font-size: 25.6px;
            color: #eee;
            margin-top: 1em;
            font-weight: 100;
        }

        .navbar-header {
            font-size: 2em;
            padding-bottom: 0px;
        }

        .navbar-brand {
            padding: 0px 0px 0px 15px;
            height: 0;
        }

        .navbar-title
        {
            position: absolute;
            left: 0;
            top: 0;
            text-align: center;
            margin: auto;
            margin-left: 50% !important;
            margin-right: 50% !important;
          height:100%;
        }

        .navbar-title a
        {
            text-decoration: none;
            color: #333;
        }

        .wooey-affix{
         max-height: 100%;
         overflow-y: auto;
        }

        .navbar-nav li {
         line-height: 40px;
        }

        .navbar-nav li.register {
            margin-top: 5px;
        }

        .nav-tabs > li.no-hover > a:hover {
            background-color: #fff;
            border-top-color: #fff;
            border-left-color: #fff;
            border-right-color: #fff;
        }

        #wooey-job-table a {
            display: block;
            width: 110px;
            word-wrap: break-word;
        }

        @media(max-width: 1200px){
            .wooey-affix{
                position: relative !important;
            }
        }

        .glyphicon.spinning {
            animation: spin 1s infinite linear;
            -webkit-animation: spin2 1s infinite linear;
        }

        @keyframes spin {
            from { transform: scale(1) rotate(0deg);}
            to { transform: scale(1) rotate(360deg);}
        }

        @-webkit-keyframes spin2 {
            from { -webkit-transform: rotate(0deg);}
            to { -webkit-transform: rotate(360deg);}
        }

        .jobs-badge { display: none; }

        .console {
            background-color:#222;
            font-family:"Courier New",Courier,monospace
        }

        .console-body {
            background: none;
            border: none;
        }

        .console-stdout { color: #0f0; }
        .console-stderr { color: #f00; }
        .console-command { color: #fff; }


        .thumbnail.panel {
            padding: 0;
            aborder-width: 0;
            box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.05);
        }

        .panel-body .form-group {
            margin-left: 1em;
            margin-right: 1em;

        }

        .panel-nopad {
            padding: 0;
        }

        .panel-heading {
            font-weight: bold;
            font-size: 1.5rem;
        }

        .page-header {
            margin: -20px -15px 20px;
            padding: 20px 20px 20px;
            box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.05);
        }

        .center-div {
            padding-top: 30px;
        }

        .panel-heading h4 { margin: 0px; }

        .glyphicon { font-weight: normal; }

        a.icon:after {
            font-family:'Glyphicons Halflings';
            color: rgba(0,0,0,0.3);
            float: right;
            font-weight: normal;
            padding-left: 5px;
        }

        a.icon-collapse:after { content:"\e114"; }
        a.icon-collapse.collapsed:after { content:"\e080"; }

        a.icon-download:after { content:"\e025"; }
        a.icon-download:hover:after { color: #337AB7 !important; }

        a.icon-locked:after { content:"\e033"; }

        a.icon-favorite:after { content:"\e006"; }
        a.icon-favorite:hover:after { color: #F0AD4E !important; }
        a.icon-favorite:hover:after, .is-favorite a.icon-favorite:after { color: #F0AD4E !important; }

        a.icon-pushpin:after { content:"\e146"; }
        a.icon-pushpin:hover:after, .is-favorite a.icon-pushpin:after { color: #F0AD4E !important; }

        .job-metadata, .profile-metadata {
            font-size: 0.9em;
        }

        .job-metadata .label, .profile-metadata .label {
            font-size: 1em;
        }

        .success { color: #5CB85C }
        .warning { color: #F0AD4E }
        .danger { color: #D9534F }

        .center-div { background: url('{% static "wooey/images/pinstripe.png" %}'); }

        .page-header { background: #fff; }

        .numericalign { width: 49%; display: inline-block; }
        .numericalign.numericpart { text-align:right; }

        .preview-table tr, .preview-table th, .preview-table td { text-overflow: ellipsis; white-space: nowrap; }
        .preview-metadata { font-size: 0.8em; }

        .ellided-continuation > td { padding: 0 8px 8px 8px !important; }

        .profile-gravatar-adjust {
            margin-top: -86px;
            margin-left: 80px;
        }

        .panel-table {
            padding: 0px;
        }

        .panel-table .table {
            margin-bottom: 0px;
        }

        .panel-nav-tabs {
            position: relative;
        }

        .panel-nav-tabs ul {
            position: absolute;
            top: -42px;
        }

        .panel-nav-tabs ul:first-child {
            margin-left: 100px;
        }

        .user-is-anonymous .requires-login { display: none; }

        #page-content-wrapper {
            margin: 0;
            padding: 0;
        }

        .sidebar-nav {
            margin-top: 10px;
        }

        #menu-toggle {
            float: left;
            /* margin-right: 0; */
            display: block;
        }

        #sidebarsearchform {
            color: #fff;
            border-radius: 0;
            border: 0;
            background-color: #555;
        }

        li > a.tab-error {
            color: #A94442;
            background-color: #F2DEDE;
        }

        li.active > a.tab-error {
            color: #A94442;
            background-color: #fff;
        }


        .status-submitted-toggle,
        .status-pending-toggle,
        .status-running-toggle,
        .status-completed-toggle,
        .status-revoked-toggle,
        .status-failure-toggle {
            display: none;
        }

        .status-submitted .status-submitted-toggle,
        .status-pending .status-pending-toggle,
        .status-running .status-running-toggle,
        .status-completed .status-completed-toggle,
        .status-revoked .status-revoked-toggle,
        .status-failure .status-failure-toggle
        {
            display: unset !important;
        }



        {% block extra_style %}
        {% endblock extra_style %}
    </style>
</head>
<body class="{% if user.is_authenticated %}user-is-authenticated{% else %}user-is-anonymous{% endif %}">
    <nav class="navbar navbar-inverse navbar-fixed-top">
{#    from http://www.bootply.com/3iSOTAyumP for brand centering #}
      <div class="container-fluid">
        <!-- Brand and toggle get grouped for better mobile display -->
        <div class="navbar-header">
              <button id="menu-toggle" class="navbar-toggle">
                  <span class="sr-only"></span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
                  <span class="icon-bar"></span>
              </button>
            <ol class="breadcrumb navbar-breadcrumb">
              <li><a href="{% url 'wooey:wooey_home' %}" class="navbar-brand wooey">{% get_wooey_setting "WOOEY_SITE_NAME" %}</a></li>
                {% block breadcrumbs %}{% endblock %}
            </ol>

            <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1">
                <span class="sr-only">{% trans "Toggle navigation" %}</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse" id="navbar-collapse-1">
          <ul class="nav navbar-nav navbar-right">
              <!-- List global job queue active, waiting (limit N) -->
              <li class="dropdown disabled" id="job-list-global">
                  <a href="#" class="dropdown-toggle disabled" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans "Queue" %} <span class="badge jobs-badge" id="jobs-badge-global">8</span> <span class="caret"></span></a>

                  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="job-list-global-list">
                  </ul>

              </li>

              {% if request.user.is_authenticated %}
              <!-- List all currently active, waiting jobs for current user -->
              <li class="dropdown disabled" id="job-list-user">
                  <a href="#" class="dropdown-toggle disabled" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans "Jobs" %} <span class="badge jobs-badge" id="jobs-badge-user">8</span> <span class="caret"></span></a>

                  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="job-list-user-list">
                  </ul>

              </li>
              {% endif %}
              <!-- List latest N completed jobs -->
              <li class="dropdown disabled" id="job-list-results">
                  <a href="#" class="dropdown-toggle disabled" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{% trans "Results" %} <span class="badge jobs-badge" id="jobs-badge-results">8</span> <span class="caret"></span></a>

                  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1" id="job-list-results-list">
                  </ul>

              </li>

              {% if request.user.is_authenticated %}
              <li class="dropdown" id="job-list-user">
                  <a href="{% url 'wooey:scrapbook' %}" role="button" aria-haspopup="true" aria-expanded="false">{% trans "Scrapbook" %} <span class="badge scrapbook-badge" id="favorite-wooey-wooeyfile-count">{% get_user_favorite_count request.user 'wooey' 'wooeyfile' %}</span></a>
              </li>

              <li><a href="{% url 'wooey:profile_home' %}"><span class="glyphicon glyphicon-user"> </span> {{ request.user.username }}</a></li>
              <li><a href="{% url "logout" %}?next={{ request.path }}">{% trans "Logout" %}</a></li>
              {% else %}
                  <li>{% include "wooey/registration/login_header.html" %}</li>
              {% endif %}
          </ul>
        </div><!-- /.navbar-collapse -->
      </div><!-- /.container-fluid -->
    </nav>


<div id="wrapper">

        <!-- Sidebar -->
        <div id="sidebar-wrapper" class="sidebar-wrapper">
            <ul class="sidebar-nav">
                <li>
                    <form>
                     <div class="form-group">
                        <input type="text" class="form-control" id="sidebarsearchform"  placeholder="{% trans 'Search for scripts...' %}" value="{{ request.GET.q }}">
                      </div>
                    </form>
                </li>
                <div id="sidebarsearchresults">
                </div>
            </ul>
        </div>
        <!-- /#sidebar-wrapper -->

    <div id="page-content-wrapper" class="{% block page_content_class %}{% endblock page_content_class %}">
    {% block outer_content %}{% endblock %}
    {% block center %}
        <div class="center-div {% block center_content_class %}col-md-10 col-xs-6{% endblock center_content_class %}">
            {% block center_content %}
            {% endblock center_content %}
        </div>

    {% endblock center %}
    </div>

</div>


    {% block js %}
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
    <script type="text/javascript" src="//cdn.datatables.net/1.10.6/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript" src="//cdn.datatables.net/responsive/1.0.5/js/dataTables.responsive.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/showdown/1.2.2/showdown.min.js"></script>
    {% endblock js %}

    {% block extra_js %}
    {% endblock extra_js %}

    <div id="inline-js">
    {% block inline_js %}
    <script  type="text/javascript">

            (function($) {
                // https://github.com/bgrins/bindWithDelay/blob/master/bindWithDelay.js
                $.fn.bindWithDelay = function( type, data, fn, timeout, throttle ) {

                    if ( $.isFunction( data ) ) {
                        throttle = timeout;
                        timeout = fn;
                        fn = data;
                        data = undefined;
                    }

                    // Allow delayed function to be removed with fn in unbind function
                    fn.guid = fn.guid || ($.guid && $.guid++);

                    // Bind each separately so that each element has its own delay
                    return this.each(function() {

                        var wait = null;

                        function cb() {
                            var e = $.extend(true, { }, arguments[0]);
                            var ctx = this;
                            var throttler = function() {
                                wait = null;
                                fn.apply(ctx, [e]);
                            };

                            if (!throttle) { clearTimeout(wait); wait = null; }
                            if (!wait) { wait = setTimeout(throttler, timeout); }
                        }

                        cb.guid = fn.guid;

                        $(this).bind(type, data, cb);
                    });
                };

                })(jQuery);

            function clearErrors($form){
                $form.find('.errorlist').remove();
                $form.find('.has-error').toggleClass('has-error');
            }

            function addUlError($field, error){
                $field.closest('.form-group').addClass('has-error');
                $field.after('<ul class="errorlist list-unstyled alert alert-danger"><li class="error">'+error+'</li></ul>');
            }

            function addInlineError($field, error){
                $field.closest('.form-group').addClass('has-error');
                $field.append('<span class="errorlist error alert-danger">'+error+'</span>');
            }

            function processErrors($form, errors){
                var previous_tab_error = false;

                for (var key in errors){
                    for(var i=0;i<errors[key].length;i++) {
                        var error = errors[key][i];
                        var $field;
                        if (key == '__all__') {
                            //stick it at the form's top
                            $field = $('<ul class="errorlist"></ul>');
                            $field.prependTo($form);
                        }
                        else {
                            $field = $('#' + key);
                            if (!$field.length)
                                $field = $('[name="' + key + '"]');
                            if($form.hasClass('form-inline') || $form.hasClass('navbar-form')){
                                $field2 = $('<span class="errorlist"></span>');
                                $field2.appendTo($field.parent());
                                $field = $field2;
                            }
                        }
                        if ($form.hasClass('form-inline') || $form.hasClass('navbar-form')) {
                            addInlineError($field, error);
                        } else
                            addUlError($field, error);

                        // See if we're in a tabbed view; find the parent tab and set it to error state
                        $tab_pane = $field.closest('.tab-pane');
                        if($tab_pane){
                            id = $tab_pane.attr('id');
                            $obj = $('a[href="#' + id + '"]');
                            $obj.addClass('tab-error');

                            // If first time we've seen a tab error, change the (.active) tab
                            if(!previous_tab_error){
                                $obj.tab('show');
                            }
                        }
                    }
                }
            }

        $(document).ready(function(){
            $('[data-toggle="popover"]').popover();
            $('[data-toggle="tooltip"]').tooltip();
            $('#wooey-login').click(function(event){
            event.preventDefault();
            var $form = $(this).closest('form');
            // if we are cloning a job, we need to specify the fields as the files because the file type input
            // will be blank
            var formData = $form.serializeArray();
            $.ajax({
                url: $form.attr('action'),
                type: 'POST',
                data: formData,
                dataType: 'json',
                async: false,
                cache: false,
                success: function(data){
                    clearErrors($form);
                    if(data.valid){
                        if(data.redirect){
                            window.location.href = data.redirect;
                        }
                    }
                    else{
                        processErrors($form, data.errors)
                    }
                    }
                });
            });

            /* Job urls definitions: need to be template processed */
            var wooey_job_list_urls = {
                global: "{% url 'wooey:global_queue' %}",
                user: "{% url 'wooey:user_queue' %}",
                results: "{% url 'wooey:user_results' %}",
            }


            function celeryRefresh() {
                /* Update the script status lists (navbar) and count pills */
                $.get("{% url "wooey:all_queues_json" %}", function(data){

                    for(var table_key in data['items']) {

                        /* Do total counts first */
                        var total_jobs = data['totals'][table_key]

                        $('#jobs-badge-' + table_key).text( total_jobs )
                        if( total_jobs > 0){
                            $('#jobs-badge-' + table_key).show()
                            $('#job-list-' + table_key).removeClass('disabled')
                            $('#job-list-' + table_key + ' > a').removeClass('disabled')
                        } else {
                            / * Disable button */
                            $('#jobs-badge-' + table_key).hide()
                            $('#job-list-' + table_key).addClass('disabled')
                            $('#job-list-' + table_key + ' > a').addClass('disabled')
                        }


                        var items = [];
                        /* Now add the jobs to the dropdown lists */
                        var job_data = data['items'][table_key];
                        for (var i = 0; i < job_data.length; i++) {
                            job = job_data[i]
                            items.push('<li><a href="' + job['url'] + '">' + job['status'] + '&nbsp;' + job['name'] + '</a></li>')
                        }

                        /* Now add "more" links if count > length */
                        if(total_jobs > job_data.length){
                            items.push('<li role="separator" class="divider"></li>');
                            items.push('<li><a href="'+ wooey_job_list_urls[table_key] +'">{% trans "More..." %}</a>');
                        }

                        /* Empty the list: might be nicer to replace, edit, more intelligently */
                        $("#job-list-" + table_key + "-list").empty();
                        $("#job-list-" + table_key + "-list").append(items);

                    }
                }, "json");
            }


            celeryRefresh();
            /* Update the interface ~15 secs */
            window.setInterval(celeryRefresh, 15 * 1000);


        });

        // using jQuery
        function getCookie(name) {
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
        var csrftoken = getCookie('csrftoken');

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }
        $.ajaxSetup({
            crossDomain: false, // obviates need for sameOrigin test
            beforeSend: function(xhr, settings) {
                if (!csrfSafeMethod(settings.type)) {
                    xhr.setRequestHeader("X-CSRFToken", csrftoken);
                }
            }
        });


        function toggleFavorite(event) {
            /* Submit JSON favorite request and act on result */

            favorite_item = $(event.target);
            var data = new Object();
            identifer = $(event.target).data('favorite');
            identifiers = identifer.split('-');

            data.app = identifiers[0];
            data.model = identifiers[1];
            data.pk = identifiers[2];

            $.ajax({
                url: '/favorite/toggle',
                data: data,
                type: 'post',
                dataType: 'json',
                cache: false,
                success: function(data){
                    /* Act on result */
                        if(data.is_favorite){
                            $('#favorite-' + identifer).addClass('panel-warning is-favorite');
                            $('#favorite-' + identifer).removeClass('panel-default');
                        } else {
                            $('#favorite-' + identifer).addClass('panel-default');
                            $('#favorite-' + identifer).removeClass('panel-warning is-favorite');
                        }

                    $('#favorite-' + data.app + '-' + data.model + '-count').text(data.count);

                    }
                });

            return false;
            }

        var converter = new showdown.Converter({
            'github_flavouring': true,
            'tables': true
        });

        $(document).ready(function(){

            $("a[data-favorite]").click(toggleFavorite);

            $(document).delegate('*[data-toggle="lightbox"]', 'click', function(event) {
                event.preventDefault();
                $(this).ekkoLightbox();
            });


            $("#menu-toggle").click(function(e) {
                e.preventDefault();
                $("#wrapper").toggleClass("toggled");
            });



            $("#sidebarsearchform").bindWithDelay("keyup", function(event){
                var query = $('#sidebarsearchform').val();
                $.ajax({
                    url: '{% url 'wooey:wooey_search_script_json' %}',
                    method: 'GET',
                    data: {q: query},
                    dataType: 'json',
                    async: true,
                    cache: false,
                    contentType: false,
                    success: function(data){

                        $('#sidebarsearchresults').empty()
                        for (var i in data['results']) {
                            $("#sidebarsearchresults").append('<li class="sidebarsearchresult"><a href="' + data['results'][i].url + '">' + data['results'][i].name + '</a></li>')
                        }

                        $('.sidebarsearchresult').bind("click", function(event){
                            $.ajax({
                                url: event.target.href,
                                method: 'GET',
                                dataType: 'html',
                                async: true,

                                cache: false,
                                contentType: false,
                                success: function(html){
                                    $("#page-content-wrapper").html( $(html).find("#page-content-wrapper") );

                                    var div = document.createElement("div");
                                    div.innerHTML = html;
                                    var scripts = div.getElementsByTagName('script');
                                    for (var ix = 0; ix < scripts.length; ix++) {
                                        eval(scripts[ix].text);
                                    }

                                    jQuery.ready();

                                },
                              });
                            return false;
                        });

                    }
                });


            }, 100);

            $(".markdown").each(function( index ) {
                $( this ).html( converter.makeHtml( $( this ).html() ) );
            });



        });

    </script>
    {% endblock inline_js %}
    </div>

</body>
</html>
