{% extends "layout.html" %}

{% block body %}
    <body id="post" class="{{ 'feature' if post.header_image }}">

        <div id="header_stuff">
            <div class="entry-header {{ "hidden" if not post.header_image }}">
                <div class="entry-image">
                    <img src="{{ post.header_image or "" }}">
                </div>

                <div class="image-credit">
                    {{ post.header_caption or "" }}
                </div>
            </div>

            <div class="top-right {% if not post.header_image %}hidden{% endif %}" id="delete_header_button">
                <a href="#">
                    <i class="fa fa-close fa-2x fa-inverse"></i> &nbsp;
                </a>
            </div>
        </div>

        <div class="top-right {% if post.header_image %}hidden{% endif %}" id="add_header_button">
            <a href="#">
                <i class="fa fa-picture-o fa-2x"></i> &nbsp;
            </a>
        </div>

        <div class="sidebar-content">
            <div class="sidebar-item">
                <form method="POST" action="{{ url_for('publish_post', id=post.id) }}" id="publish_form">
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
                </form>
                <a href="#"
                   onclick="$('#publish_form').submit();">
                    <i class="fa fa-book fa-2x"></i> {% if not post.draft %}Un-{% endif %}Publish
                </a>
            </div>

            {% if not post.draft %}
            <div class="sidebar-item">
                <a href="{{ url_for('view_post', slug=post.slug) }}" target="_blank">
                    <i class="fa fa-binoculars fa-2x"></i> View
                </a>
            </div>
            {% else %}
            <div class="sidebar-item">
                <a href="{{ url_for("preview_post", id=post.id) }}" target="_blank">
                    <i class="fa fa-binoculars fa-2x"></i> Preview
                </a>
            </div>
            {% endif %}

            <div class="sidebar-item">
                <form method="POST" action="{{ url_for('delete_post', id=post.id) }}" id="delete_form">
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token() }}">
                    <input type="hidden" name="redirect" value="{{ url_for('list_posts') }}">
                </form>
                <a href="#"
                   onclick="if (confirm('Are you sure you want to delete this post?')){$('#delete_form').submit();}">
                    <i class="fa fa-trash fa-2x"></i> Delete
                </a>
            </div>

            <div class="sidebar-item">
                <a href="{{ url_for("list_posts") }}">
                    <i class="fa fa-list fa-2x"></i> Drafts
                </a>
            </div>
        </div>

        <div id="main" role="main">
            <article class="hentry">
                <header class="header-title">
                    <div class="header-title-wrap">
                        <h1 class="entry-title edit-title" contenteditable="True" id="title">{{ post.title if post else "Post Title" }}</h1>

                        <div class="right-img-button" id="right-scroll">
                            <i id="right_loading" class="fa fa-circle-o-notch fa-spin fa-3x fa-inverse" style="display: none"></i>
                            <a href="#"><span class="fa fa-arrow-circle-right fa-3x fa-inverse"></span></a>
                        </div>

                        <div class="left-img-button" id="left-scroll">
                            <a href="#" class="hidden">
                                <span class="fa fa-arrow-circle-left fa-3x fa-inverse"></span>
                            </a>
                        </div>
                    </div>
                </header>
                <div class="entry-content">
                    <textarea class="editor" id="content">{{ post.content if post else "Content" }}</textarea>
                </div>
            </article>
        </div>
    </body>
{% endblock %}


{% block extra_scripts %}
    <script src="{{ url_for('static', filename='js/plugins/jquery.autosize.js') }}" type="text/javascript"></script>
    <script src="{{ url_for('static', filename='js/plugins/jquery.hotkeys.js') }}" type="text/javascript"></script>
    <script src="{{ url_for('static', filename='js/plugins/jquery.caret-1.5.2.min.js') }}" type="text/javascript"></script>
    <script>
        $(document).ready(function() {
            // Don't laugh at me. This code is horrible I know :(

            $("#delete_header_button").click(function(){
                $("body").removeClass("feature");
                $("#header_stuff").hide();
                $(".entry-header").addClass("hidden");
                $("#right-scroll").hide();
                $("#left-scroll").hide();
                $("#delete_header_button").addClass("hidden");
                $("#add_header_button").removeClass("hidden");
            });

            $("#add_header_button").click(function(){
                $("#left-scroll").show();
                $("#right-scroll").show();
                $("#header_stuff").show();
                $(".entry-header").removeClass("hidden");
                $("body").addClass("feature");

                $("#delete_header_button").removeClass("hidden");
                $("#add_header_button").addClass("hidden");
            });

            window.header_images = [];
            window.header_index = 0;
            window.got_all_images = false;

            var updateHeader = function(idx){
                var num = 3;

                var done = function(idx) {
                    //console.log("Moving to: " + idx);
                    //console.log(window.header_images);
                    window.header_index = idx;
                    var src = window.header_images[idx].url;
                    $(".entry-image img").replaceWith($("<img src='" + src + "'/>"));
                    //$(".entry-image img")[0].src = src;
                    $(".image-credit").text(window.header_images[idx].copyright);

                    $("#right_loading").attr("style", "display: none");
                    $("#right-scroll a").show();

                    if (idx == 0 && !window.got_all_images){
                        $("#left-scroll a").addClass("hidden");
                    } else {
                        $("#left-scroll a").removeClass("hidden");
                    }
                };

                if (idx < 0) {
                    if (window.got_all_images){
                        idx = window.header_images.length - 1;
                    }
                    else {
                        idx = 0;
                    }
                }
                if (idx >= window.header_images.length)
                {
                    if ((idx * num) >= 100){
                        window.got_all_images = true;
                        idx = 0;
                        return done(idx);
                    }
                    $("#right_loading").attr("style", "display: visible");
                    $("#right-scroll a").hide();

                    // Get some new images!
                    return grabHeaderImages(window.header_images.length, num, function(images){
                        //console.log("Got new images:");
                       // console.log(images);
                        images.forEach(function(v) {window.header_images.push(v)}, this);
                        done(idx);
                    })
                }
                return done(idx);
            };

            $("#right-scroll a").click(function(){ updateHeader(window.header_index+1); });
            $("#left-scroll a").click(function(){ updateHeader(window.header_index-1);});

            var grabHeaderImages = function(idx, num, callback){
                $.get("{{ url_for('header_images') }}?idx=" + idx + "&num=" + num, function(data){
                    var header_images = data.images;
                    callback(header_images);
                });
            };

            grabHeaderImages(0, 5, function(images){
                window.header_images = images;

                var header = $(".entry-image img");
                if (!header.attr("src")){
                    updateHeader(0);
                } else {
                    var src = header.attr("src");
                    var our_headers = $.grep(window.header_images, function(obj){ return obj.url == src });
                    if (our_headers.length > 0){
                        window.header_index = window.header_images.indexOf(our_headers[0]);
                    } else {
                        // Add a new item
                        var item = {
                            url: src,
                            copyright: $(".image-credit").text()
                        };
                        window.header_images.unshift(item);
                        window.header_index = 0;
                    }
                    updateHeader(window.header_index);
                }
            });

            var saveData = function(){
                var img = null;
                var caption = null;

                if ($(".entry-image img").is(":visible")){
                    img = $(".entry-image img").attr("src");
                    caption = $(".image-credit").text()
                }

                $.post("{{ url_for('view_draft', id=post.id) }}",
                        {
                            _csrf_token: '{{ csrf_token() }}',
                            title: $('#title').text(),
                            content: $('#content').val(),
                            header_image: img,
                            header_caption: caption,
                        });
                return false;
            };

            $(".editor").autosize().bind('keydown', 'ctrl+s', saveData);
            $(document).bind('keydown', 'ctrl+s', saveData);

            window.ondragover = function(e) {e.preventDefault()};
            window.ondrop = function(e) {e.preventDefault(); upload(e.dataTransfer.files); };

            function upload(files) {
                $("#upload_list").empty();
                $(files).each(function(i,file){
                    if (!file || !file.type.match(/image.*/)) return;

                    var fd = new FormData();
                    fd.append("file", file);
                    fd.append("_csrf_token", "{{ csrf_token() }}");
                    var xhr = new XMLHttpRequest();
                    xhr.open("POST", "{{ url_for('upload_file') }}");
                    xhr.onload = function() {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.status === "ok"){
                            var url = resp.url;
                            var name = resp.name;
                            $('#content').caret('![](' + url + ')');
                        }
                    };
                    xhr.send(fd);
                })
            }
        });
    </script>
{% endblock %}