{% load i18n compress media_tags %}
{% if user.is_staff %}

{% addmedia "css" %}
  <link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}block/css/render_blocks.css"/>
  <link href="{{ STATIC_URL }}block/css/shadowbox.css" rel="stylesheet" type="text/css" />
{% endaddmedia %}

{% addmedia "js" %}
  <script type="text/javascript" src="{{ STATIC_URL }}base/js/jquery-ui.min.js"></script>
  <script type="text/javascript" src="{{ STATIC_URL }}block/js/mootools.v1.11.js"></script>
  <script type="text/javascript" src="{{ STATIC_URL }}block/js/shadowbox/shadowbox-mootools.js"></script>
  <script type="text/javascript" src="{{ STATIC_URL }}block/js/shadowbox/shadowbox.js"></script>
  <script type="text/javascript" src="{{ STATIC_URL }}block/js/jquery.block.js"></script>
{% endaddmedia %}

{% compress js %}
<script type="text/javascript">
// <![CDATA[
(function($) {
  if (!$.browser.msie || $.browser.version != '6.0') {
    $(document).ready(function() {
        var containers = $(".blockContainer:visible");

        function getBlocksOrder() {
            var order = [];
            containers.each(function () {
                var orderList = [];
                var place = $(this).children(".blockPlace").val();
                $(this).find(".block").find(".blockId").each(function() {
                    var val = $(this).val();
                    if (val) {
                        order.push(val +"#"+ place);
                    }
                });
            });
            return order.join(",");
        }

        function initBlockTools() {
            $(".block").each(function() {
                initBlock($(this));
            });
            // initialize shadowbox (if not initialized with multimedia slide)
            var mediaurl = '{{ STATIC_URL }}';
            Shadowbox.init({
                assetUrl: mediaurl,
                loadingImage: mediaurl + 'block/img/loading.gif',
                displayNav: true,
                skipSetup: true,
                displayClose: true,
                continuous: true,
                enableKeys: false
            });
        }

        function initBlock(block) {
            var dragAnchor, confAnchor, divTools, position;
            position = block.position();
            divTools = $("<div>");
            // creating block tools
            dragAnchor = $("<a>");
            dragAnchor.attr("href", "javascript:void(0)");
            dragAnchor.attr("title", "{% trans "Enable/disable blocks dragging" %}");
            dragAnchor.addClass("drag");
            dragAnchor.click(enableDragging);
            confAnchor = $("<a>");
            confAnchor.attr("href", "javascript:void(0)");
            confAnchor.attr("rel", "shadowbox");
            confAnchor.click(loadBlockConfiguration);
            confAnchor.addClass("configure");
            confAnchor.attr("title", "{% trans "Configure block" %}");
            // place all block tools
            divTools.append(dragAnchor);
            divTools.append(confAnchor);
            divTools.addClass("blockTools");
            divTools.css({"left": Math.max(0, position.left - 20)});
            divTools.css({"top": Math.max(0, position.top)});
            block.append(divTools);
            block.mouseenter(function() {
                if(block.attr("id")) {
                    block.children(".blockTools").stop(true, true).show();
                }
            }).mouseleave(function() {
                if(block.attr("id")) {
                    block.children(".blockTools").delay(1000).fadeOut();
                }
            });
        }

        function loadBlockConfiguration() {
            var block_list_url = '{% url block_list %}';
            var block = $(this).parents('.block');
            var block_name = block.attr('id');
            var block_id = block.find('.blockId').val();
            var block_title = block.find('.blockHiddenTitle').html();
            var block_config_url = block_list_url + 'ajax/config/' + block_id;
            $.ajax({
                url: block_config_url,
                context: document.body,
                success: function(data){
                    Shadowbox.open({
                        content:    data,
                        type:       "html",
                        title:      block_title,
                        height:     600,
                        width:      500
                    });
                }
            });
            // when block config was loaded by AJAX (previous function)
            // we change usual submit by a AJAX submit (without refreshing browser)
            $('#config-block-form').live("submit", function(event) {
                event.preventDefault();
                var block_id = $(this).find('[name=blockid]').val();
                var block_name = $(this).find('[name=blockname]').val();
                var render_block_url = '.?render_block=' + block_id;
                $.ajax({
                    type: 'POST',
                    url: $(this).attr('action'),
                    data: $(this).serialize(),
                    success: function(data) {
                        if(data == 'ok') {
                            $('#' + block_name).parent().fadeOut(1000, function() {
                                $('#' + block_name).parent().load(render_block_url, function() {
                                    initBlock($('#' + block_name));
                                }).fadeIn('slow');
                            });
                            Shadowbox.close();
                        } else {
                            // a validation error happens. We will render the form again
                            $('#config-block').replaceWith(data);
                        }
                    }
                });
                return false;
            });

        }

        function enableDragging() {
            var container = $(this).parents(".blockContainer")[0];
            var containerType = "blocks";
            containers.each(function() {
                if ($(this).children().length < 2 || $(this).height() == 0) {
                    var child;
                    child = $("<div>");
                    child.html("Drag here");
                    child.addClass("blockDrag");
                    $(this).append(child);
                }
            });
            if (!containers.hasClass("blockContainerBorder")) {
                containers.addClass("blockContainerBorder");
                containers.sortable({
                    connectWith: '.blockContainer',
                    parent: 'document',
                    opacity: 0.6,
                    revert: true,
                    items: '.block',
                    helper: 'clone',
                    tolerance: 'pointer',
                    start: function(event, ui) {
                        $(".block .blockTools").hide();
                    },
                    stop: function(event, ui) {
                        $(".block .blockTools").hide();
                        disableDragging();
                        recalculatePosition(ui.item);
                        postNewOrder();
                    }
                });
                containers.disableSelection();
            } else {
                disableDragging();
            }
            return false;
        }

        function disableDragging() {
            containers.sortable("destroy");
            containers.removeClass("blockContainerBorder");
            containers.find(".blockDrag").remove();
        }

        function recalculatePosition(ui) {
            var position;
            position = $(ui).position();
            divTools = $(ui).children(".blockTools");
            divTools.css({"left": Math.max(0, position.left - 20)});
            divTools.css({"top": Math.max(0, position.top)});
        }

        function postNewOrder() {
            var newOrder = getBlocksOrder();
            $.ajax({
                url: "{% url blocks_reorder %}",
                type: "POST",
                data: ({new_order : newOrder}),
                dataType: "json",
                success: function(msg) {
                    // It's not necesary to alert the user
                },
                error: function() {
                    window.location = window.location;
                }
            });
        }

        initBlockTools();
    });
  }
})(jQuery);
// ]]>
</script>
{% endcompress %}

{% endif %}
