{# base template that includes editing controls #}
{% extends "wheelcms_axle/base.html" %}
{% load staticfiles %}

{% block base_stylesheets  %}
{{ block.super }}

<link rel="stylesheet" href="{% static "tagmanager/bootstrap-tagmanager.css" %}" media="screen, projection, print"/>
<link rel="stylesheet" href="{% static "css/upload/jquery.fileupload-ui.css" %}" media="screen, projection, print"/>
{% endblock %}

{% block javascript %}

{{ block.super }}

<script src="{% static "js/upload/jquery.ui.widget.js" %}"></script>
<script src="{% static "js/upload/load-image.min.js" %}"></script>
<script src="{% static "js/upload/canvas-to-blob.min.js" %}"></script>
<script src="{% static "js/upload/jquery.iframe-transport.js" %}"></script>
<script src="{% static "js/upload/jquery.fileupload.js" %}"></script>
<script src="{% static "js/upload/jquery.fileupload-process.js" %}"></script>
<script src="{% static "js/upload/jquery.fileupload-resize.js" %}"></script>
<script src="{% static "js/upload/jquery.fileupload-validate.js" %}"></script>
<script src="{% static "tagmanager/bootstrap-tagmanager.js" %}"></script>

<script type="text/javascript" charset="utf-8">
    var upload_modal = (function() {
        var mode = "any";
        var url = "";
        var callback = null;

        function load_form(url, type) {
            /*
             * Used by the upload modal: load the remote upload form, it can
             * be different depending on the context.
             */
            if(url == '/') {
                url = '';
            }
            var data = $.ajax({
                url: 'fileup?type=' + type,
                dataType:"json",
                async: false
                }).responseText;
            data = $.parseJSON(data);
            var form = data.form;
            $(".uploadform").html(form);

            $("#uploadModal .modal_close").click(function() {
                closecallback();
            });

            var upload = null;

            var fileinput = $("#fileupload input[type=file]");
            fileinput.replaceWith('<div id="filepreview" ></div><span class="btn btn-success fileinput-button"><i class="icon-plus icon-white"></i><span id="filelabel">Add file</span><input id="' + fileinput.attr('id') + '" type="file" name="' + fileinput.attr('name') + '"></span>');
            //var preview = $("#fileupload input[type=file]").parent(".controls")
            $('#fileupload').fileupload({
                url: 'fileup',
                dataType: 'json',
                autoUpload: false,
                previewMaxwidth: 100,
                previewMaxHeight: 100,
                previewCrop: true,
            }).on('fileuploadadd', function(e, data) {
                $("#uploadModal .modal_select").prop('disabled', false);
                upload = data;
            }).bind('fileuploadprocessalways', function(e, data) {
                var file = data.files[data.index];

                // ordinary files don't have a preview
                if(file.preview) {
                    $("#filepreview").html(file.preview).append($('<h4/>').text(file.name));
                }
                else {
                    $("#filepreview").append($('<h4/>').text(file.name));
                }
                $("#filelabel").text("Replace file");
            }).on('fileuploaddone', function (e, data) {
                if(data.result.status == "ok") {
                  $("#uploadModal").modal("hide");

                  var path = data.result.path;
                  if(callback) {
                    callback(path);
                  }
                }
                else {
                    // if anything went wrong, it must have been with the uploaded file
                    $(".upload-alert").text(data.result.errors.storage);
                    $(".upload-alert").addClass("alert");
                }
            });

            $("#uploadModal .modal_select").unbind('click');
            $("#uploadModal .modal_select").prop('disabled', true);
            $("#uploadModal .modal_select").click(function() {
                upload.submit();
            });

        }

        return function(_url, _mode, _callback, _closecallback) {
            /*
             * Open the upload modal. url is where the content will be uploaded
             * to, mode determines what content can be uploaded:
             * - "any" means images and files
             * - "image" means only images
             */
            mode = _mode;
            url = _url;
            callback = _callback;
            closecallback = _closecallback;

            var header = $("#uploadModalLabel");
            var types = $(".upload_types");

            /* XXX
             * The uploadable types should be much more dynamic - we may/will
             * eventually support different types of files and images from
             * which you can chose.
             * Additionally, 'image' and 'file' no longer match the actual spokes
             * (wheelcms_spokes.image, etc)
             */

            if(mode == "any") {
                header.text("Upload content");
                types.html('<select class="select_type"> ' +
                           '<option value="wheelcms_spokes.image">an Image</option> ' +
                           '<option value="wheelcms_spokes.file">a File</option> ' +
                           '</select>');
            } else {
                header.text("Upload an image");
                types.html('<select class="select_type"> ' +
                           '<option value="wheelcms_spokes.image">an Image</option> ' +
                           '</select>');
            }
            $("#uploadModal").modal();
            $(".upload-alert").empty();
            $(".upload-alert").removeClass("alert");
            load_form(url, $(".select_type").val());
            $(".select_type").change(function() {
                load_form(url, $(this).val());
            });
            return false;
        }
    })();

    var wheel_browser = (function() {
        var modal;
        var current_path = '';
        var original = ""; // the original selected path
        var mode = "link";
        var callback = null;
        var initialized = false;
        var current_tab = "browse_local";


        function fix_sizes() {
            /*
             * Make sure the "panels" div takes up exactly the remaining space.
             * Can this be done in css? XXX
             */
            var total = $("#browseModal .modal-body").height();
            var header = $("#browsecrumbs").outerHeight(true);
            var tabs = $("#browseModal .nav-tabs").outerHeight(true);
            var remainder = total - header - tabs;
            $("#panels").height(remainder);

            var iframe = $("#external_iframe");

            // XXX -10 is a hack - iframe scrollbars?
            iframe.outerHeight(total-tabs-10);
            iframe.outerWidth(iframe.parent().innerWidth());

            $("#browse_external_image").height(total-tabs);

        }

        function modal_shown() {
            fix_sizes()
        }

        function load_panels(path, panelid) {
            current_path = path;
            var data = $.ajax({
                url: 'panel?path='+encodeURIComponent(path) + "&original=" + encodeURIComponent(original) + "&mode="+mode,
                dataType:"json",
                async: false
                }).responseText;
            data = $.parseJSON(data);
            var panels = data.panels;
            var crumbs = data.crumbs;
            var upload = data.upload;
            var context_path = data.path;

            // enable/disable upload button depending on data.upload
            $("#browseModal .modal_upload").prop('disabled', !upload);
            $("#browseModal .modal_upload").data('url', context_path);

            var path = data.path;

            var idx = 0;
            for(var i= 0; i < 3; i++) {
                $(".panel" + i).empty();
            }

            for(var i=0; i < panels.length; i++) {
                var paneldata = panels[i];
                var panel = $(".panel" + i);
                panel.html(paneldata);
            }
            $(".crumbcontainer").html(crumbs);
            setTimeout(fix_sizes, 250);
            // find the current selection and see if it's selectable
            select_state($("tr[data-url='" + path + "']").data("selectable") == "yes");
        }

        function select_state(enabled) {
            /* enable/disable the 'Select' button */
            var selectbutton = $("#browseModal .modal_select");

            if(enabled) {
                selectbutton.removeAttr("disabled");
            }
            else {
                selectbutton.attr("disabled", "disabled");
            }
        }

        function tab_selected(e) {
            /*
             * A different tab has been selected. Check the select button state,
             * update the current_tab variable so we'll submit the right data
             */
            var target = e.target.href;
            var hash = target.substring(target.indexOf("#")+1);
            tab_selected = hash;
            select_state(false);
            if(tab_selected == "browse_local") {
                load_panels(current_path, 3);
            }
            else if(tab_selected == "browse_external_link") {
            }
            else if(tab_selected == "browse_external_image") {
            }
            current_tab = tab_selected;
        }

        function handle_external_url_change(e) {
            // something changed in the url field. This may mean something valid has been entered.
            var url = $(this).val().replace(/^\s+|\s+$/g, '');
            select_state(url); // we'll accept any content as long as it's not empty 
        }
        function get_external_link() {
            // normalize link 
            var url = $("#external_url").val();
            url = url.replace(/^\s+|\s+$/g, '');
            if(url && url.indexOf("http") != 0) {
                 url = "http://" + url;
            }
            return url;
        }
        function get_external_image() {
            // normalize image
            var url = $("#external_image_url").val();
            url = url.replace(/^\s+|\s+$/g, '');
            if(url && url.indexOf("http") != 0) {
                 url = "http://" + url;
            }
            return url;
        }
        function init(_mode, _callback) {
            mode = _mode;
            callback = _callback;

            /*
             * Initialize handlers, set title
             */
            var header = $("#browseModalLabel");
            if(mode == "link") {
                header.text("Select content to link to");
            } else {
                header.text("Select an image to insert");
            }

            select_state(false);

            setTimeout(fix_sizes, 250);

            if(initialized) {
                return;
            }
            initialized = true;
            // stuff from here on only should be initialized once

            /*
             * stuff to do once the modal actually shows
             */
            modal.on('shown', modal_shown);
            /*
             * handle tab changes
             */
            modal.find('a[data-toggle="tab"]').on('shown', tab_selected);

            /*
             * Track changes on the external link input so we can
             * enable the <select> button
             */
            $("#external_url").bind('keyup input paste', handle_external_url_change);
            $("#external_image_url").bind('keyup input paste', handle_external_url_change);

            /*
             * The preview button will attempt to load the
             * url in an iframe
             */
            $("#external_url_preview").click(function() {
                var url = get_external_link();
                if(url) {
                    $("#external_iframe").attr("src", url);
                }
                return false;
            });
            /*
             * Same thing for image tab
             */
            $("#external_image_url_preview").click(function() {
                var url = get_external_image();
                if(url) {
                    $("#external_image").attr("src", url);
                }
                return false;
            });
            /*
             * Clicking the <select> button (if enabled) should insert the link.
             * This will depend on which tab is showing
             */
            $(".modal_select").click(function() {
                modal.modal('hide');
                if(callback) {
                    var link = ""
                    var args = {}
                    if(current_tab == "browse_local") {
                        link = current_path;
                        args.local = true;
                    }
                    else if(current_tab == "browse_external_link") {
                        link = get_external_link();
                        args.local = false;
                    }
                    else if(current_tab == "browse_external_image") {
                        link = get_external_image();
                        args.local = false;
                    }
                    show_props(link, mode, args, callback, true);
                }
            });

            /*
             * cliking an entry in a panel should load the subpanel/content
             */
            $("tr.entry").live('click', function() {
                var path = $(this).data('url');
                var panelid = parseInt($(this).parents("div.panel").data('panel'));
                load_panels(path, panelid);
                if($(this).data("selectable") == "yes") {
                    select_state(true);
                }
                else {
                    select_state(false);
                }
                return false;
            });
            /*
             * clicking a path component in the breadcrumb should take you there
             */
            $("a.crumb").live('click', function() {
                var path = $(this).data('url');
                var panelid = parseInt($(this).parents("div.panel").data('panel'));
                load_panels(path, panelid);
                return false;
            });
            var open_upload  = function() {
                var url = $(this).data('url');
                modal.modal('hide');

                upload_modal(url, mode=="link"?"any":"image",
                function(path) { // select, load browser with new path
                    // should scroll to selection(s)!
                    load_panels(path, 3);
                    modal.modal('show');
                },
                function() { // close -- restore browser
                    load_panels(url, 3);
                    modal.modal('show');
                });
            }
            $("#browseModal .modal_upload").click(open_upload);
        }

        function load_link(path, options) {
            /*
             * Load an existing link for updating
             */
            modal.find('a[href="#browse_external_link"]').tab('show');
            $("#external_url").val(path);
            if(path) {
                select_state(true);
            }
        }

        function load_image(path, options) {
            /*
             * Load an existing image for updating
             */
            modal.find('a[href="#browse_external_image"]').tab('show');
            $("#external_image_url").val(path);
            if(path) {
                select_state(true);
            }
        }

        function load_local(path, options) {
            /*
             * Load content browser
             */
            modal.find('a[href="#browse_local"]').tab('show');
            load_panels(path || '', 3);
        }

        return function(path, mode, options, callback) {
            modal = $("#browseModal");
            original = path;
            init(mode, callback);
            modal.modal();
            // move to init?
            if(mode == "link") {
                // hide image
                $("#image_tab").hide()
                $("#link_tab").show()
            }
            else { // image
                // hide link
                $("#image_tab").show()
                $("#link_tab").hide()
            }
            // reset the external tab(s)

            $("#external_title").val("");
            $("#external_url").val("");
            $("#external_target").val("");
            $("#external_iframe").attr("src", "")
            $("#external_image_title").val("");
            $("#external_image_url").val("");
            $("input[name='external_image_size']").attr('checked', false);
            $("#external_image").attr("src", "{% static 'img/preview.png' %}")

            // strip possible actions from the end of the url, e.g. /+download
            path = path.replace(/\/\+[\w_-]+$/, '');

            if(path.indexOf('http') == 0) {
                if(mode == "link") {
                    load_link(path, options);
                } else {
                    load_image(path, options);
                }
            }
            else {
                load_local(path, options);
            }
        }
    })();

    function show_props(path, type, options, callback, newselection) {
        /*
         * Show and re-initialize the properties modal.
         */
        $("#detailsModal").modal();
        var ns = "";
        if(newselection) {
            ns = "&newselection=1";
        }
        $("#detailsModalBody").load("panel_selection_details?path="+encodeURIComponent(path) + "&type=" + type + "&" + $.param(options) + ns);
        $("#detailsModal .modal_select").unbind('click'); // remove previous handler(s)
        $("#detailsModal .modal_change").unbind('click'); // remove previous handler(s)

        $("#detailsModal .modal_select").click(function() {
            if(callback) {
                var args = options || {}
                args.download = false; // it must be set explicitly.
                var formdata = $("#detailsModal form").serializeArray();

                for(var i = 0; i < formdata.length; i++) {
                    args[formdata[i].name] = formdata[i].value;
                }

                callback(path, args);
            }
            $("#detailsModal").modal("hide");
        });
        $("#detailsModal .modal_change").click(function() {
            wheel_browser(path, type, options, callback);
            $("#detailsModal").modal("hide");
        });

    }
    function props_or_browser(path, type, options, callback) {
        if(path) {
            show_props(path, type, options, callback, false);
        }
        else {
            wheel_browser(path, type, options, callback);
        }
    }

    $(document).ready(function() {
        /*
         * enable the tagmanager. We fiddle a bit with the
         * original/generated (hidden) field. We want to preserve the
         * original fieldname for the created hidden field that
         * will get the actual tags
         */
        $(".tagManager").each(function(i, v) {
           var $v = $(v);
           var name = $v.attr("name");
           $v.attr("name", name + "-taginput");
           var vals = $v.val().split(/[,]+/);
           $v.val("");
           $v.tagsManager(
                {prefilled:vals,
                 preventSubmitOnEnter:true,
                 typeahead:true,
                 typeaheadSource:{{typeahead_tags|safe}},
                 hiddenTagListName:name,
                 blinkBGColor_1: '#FFFF9C',
                 blinkBGColor_2: '#CDE69C'});
        });
    });
</script>

{% endblock %}

{% block base_main %}

<!-- Button to trigger modal -->

<div id="browseModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="browseModalLabel" aria-hidden="true">
  <div class="modal-body tabbable">
    <ul class="nav nav-tabs">
      <li id="local_tab" class="active"><a href="#browse_local" data-toggle="tab">Local / Browse</a></li>
      <li id="link_tab" class=""><a href="#browse_external_link" data-toggle="tab">External Link</a></li>
      <li id="image_tab" class=""><a href="#browse_external_image" data-toggle="tab">External Image</a></li>
      <li class="pull-right"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button></a>
    </ul>

    <div class="tab-content">
      <div id="browse_local" class="tab-pane active">
        <div class="row-fluid" id="browsecrumbs">
          <div class="row12 crumbcontainer">
          </div>
        </div>
        <div class="row-fluid" id="panels">
          <div class="span3 panel panel0" data-panel="0" id="panel0">
          </div>
          <div class="span4 panel panel1" data-panel="1" id="panel1">
          </div>
          <div class="span5 panel panel2" data-panel="2" id="panel2">
          </div>
        </div>
      </div>
      <div id="browse_external_link" class="tab-pane">
        <div class="row-fluid">
          <div class="span6">
            <form>
              <legend>External URL</legend>
              <label class="control-label" for="external_url">URL</label>
              <div class="input-append">
                <input id="external_url" type="text" name="url" maxlength="256" />
                <button id="external_url_preview" class="btn">Preview <i class="icon-chevron-right"></i></button>
              </div>
              <div class="help-block">
                Not all sites (e.g. facebook) may support preview/embedding
              </div>
            </form>
          </div>
          <div class="span6">
            <iframe width="90%" id="external_iframe" src=""></iframe>
          </div>
        </div>
      </div>
      <div id="browse_external_image" class="tab-pane">
        <div class="row-fluid">
          <div class="span6">
            <form>
              <legend>External Image</legend>
              <label class="control-label" for="external_image_url">URL</label>
              <div class="input-append">
                <input id="external_image_url" type="text" name="url" maxlength="256" />
                <button id="external_image_url_preview" class="btn">Preview <i class="icon-chevron-right"></i></button>
              </div>
              <div class="help-block">
                Not all sites (e.g. facebook) may support preview/embedding
              </div>
            </form>
          </div>
          <div class="span6">
            <img id="external_image" src="{% static 'img/preview.png' %}" class="img-polaroid">
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-info modal_upload">Upload</button>
    <button class="btn btn-primary modal_select">Select</button>
  </div>
</div>

<div id="uploadModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="uploadModalLabel">Upload a file</h3>
  </div>
  <div class="modal-body">
    <div class="row-fluid">
      <div class="span12 upload-alert">
      </div>
    </div>
    <div class="row-fluid">
      <div class="span12 form-horizontal">
        <div class="control-group">
          <label class="control-label" for="select_type">Upload</label>
          <div class="controls upload_types">
          </div>
        </div>
      </div>
    </div>
    <div class="row-fluid">
      <div class="span12 uploadform">
      </div>
    </div>
  </div>
  <div class="modal-footer">
    <button class="btn modal_close" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary modal_select">Save</button>
  </div>
</div>

<div id="detailsModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3>Selection properties</h3>
  </div>
  <div class="modal-body" id="detailsModalBody">
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-info modal_change">Change selection</button>
    <button class="btn btn-primary modal_select">Select</button>
  </div>
</div>


{{ block.super }}

{% block base_main_edit %} {# block that automatically includes controls #} {% endblock %}
{% endblock %}
