


var $panel = '#contentpanel';
var $block = '.contentblock';




var ContentPanel = {};
ContentPanel.init = function(opts) {

    $panel = $('#contentpanel');
    $block = $('.contentblock');


    this.stabelize_grids($panel);
    if (opts.admin) {
        this.init_sortables(opts.syncorder_url);
        this.init_panel_reload(opts.reload_url);
        this.init_resizables(opts.resize_url);
        this.init_adminbar_adjustments();
        this.init_admin_menu();
        this.init_add_menu();
    }

    //this.init_group_by(opts.group_url);
}


ContentPanel.init_add_menu = function() {

    var add_menu = $('#gencontent_add_menu');
    var add_link = $('#add_content');
    var mode = 'before';
    var current_block = null;
   

   var __init__ = function() {

        init_default_position();
        init_add_menu_move();
        init_add_link_behavior();
        
        $(window).resize(function() {
            add_menu.css('left', $panel.offset().left - 35);
        });
        
    }


    var init_default_position = function() {
        var block = null
        if ($panel.children().length > 0) {
            // panel not empty but no current block chosen
            block = $($panel.children()[0]);
        } 
        set_add_link_attrs(block, 'before');
        add_menu.css('left', $panel.offset().left - 35);
        add_menu.css('display', 'block');
    }


    

    var init_add_menu_move = function() {
        $block.mousemove(function(e) {
            var mouse_y = e.pageY;
            var block_height = $(this).height();
            var block_y = $(this).offset().top;
            var insert_split = block_height / 2;
            var relative_mouse_y = mouse_y - block_y;
            
            //$('#test').html(mouse_y);

            if (relative_mouse_y < insert_split) {
                set_add_link_attrs($(this), 'before');
                mode = 'before';
                
            } else {
                set_add_link_attrs($(this), 'after');
                //$('#test').html('after');
                mode = 'after';
            }

            current_block = $(this);
            
        });
    }

    
 
    
   

    // -------------------------------------------------------------------------------------

    var init_add_link_behavior = function() {
        add_link.mouseover(function(e) {
            
            if (mode == 'before') {
                add_menu.addClass('insert_before');
                add_menu.removeClass('insert_after');
            } else {
                add_menu.addClass('insert_after');
                add_menu.removeClass('insert_before');
            }

            if (current_block == null) {
                add_menu.css('width', '600px');
            } else {
                add_menu.css('width', current_block.width());
            }


        }).mouseout(function(e) {
            add_menu.removeClass('insert_after');
            add_menu.removeClass('insert_before');
        });
    }
    

    var set_add_link_attrs = function(block, mode) {

        if (block != null) {
            var id = block.parent().attr('id');
            var new_href = add_link.attr('href').split('?')[0] + '?insert=' + mode + '&id=' + id;
            add_link.attr('href', new_href);

            if (mode == 'before') 
                top = block.offset().top - 10;
            else
                top = block.offset().top + block.height() - add_menu.height() + 15;
                
        } else {
           top = $panel.offset().top;
        }
        
        add_menu.css({
            'top' : top
        });

    }


    __init__();
   
}







/**
 * Initializes sortable functionality for Blocks
 * @param url:      The syncorder_url
 */
ContentPanel.init_sortables = function(url) {

    $panel.sortable( {
        opacity : 0.7,
        handle : '.dragzone',
        scroll : true,
        helper: 'clone',
        forceHelperSize : true,
        dropOnEmpty: true,
        stop : function(event, ui) {
            // iterate all children of the sortable container
            // and send an ajax request containing the ids of the object
            // in its occuring order
            ContentPanel.stabelize_grids($panel);
            var target_container = $(ui.item).parent();
            var data = [];
            $.each(target_container.children(), function() {
                var id = $(this).attr("id");
                data.push(id);
            });
            $.ajax( {
                type : 'POST',
                url : url,
                data : {
                    'elems' : $.toJSON(data)   
                }
            });
       }
    });
}


/**
 * Display adminmenu on mouseover
 */
ContentPanel.init_admin_menu = function() {
   
    $block.find('.adminbar').css('visibility', 'hidden');

    $block.mouseover(function() {
        $(this).find('.adminbar').css('visibility', 'visible');
        $(this).addClass('adminhover');
    }).mouseout(function() {
        $(this).find('.adminbar').css('visibility', 'hidden');
        $(this).removeClass('adminhover');
    });

    
}


/**
* Reloads panel after a form was sent
* @param url:   reload_url
*/
ContentPanel.init_panel_reload = function(url) {
    
    $(document).unbind('ajaxform.sent');
    $(document).bind('ajaxform.sent', function() {
        $.ajax({
            type : 'GET',
            url : url,
            dataType: 'html',
            beforeSend: function(){
                //alert(url);
            },
            success : function(html) {
                //alert($panel.parent().attr('id'));
                $panel.parent().html(html);
            }
        });
    });
}

/**
 *  Adjusts the width of dragzone and edit_tools to perfectly fit
 *  within the adminbar
 */
ContentPanel.init_adminbar_adjustments = function() {
    var adminbars = $('.adminbar');
    adminbars.each(function() {
        var adminbar = $(this);
        ContentPanel.adjust_adminbar(adminbar);
    });
}

/**
 *  Use this each time the adminbar must be adjusted
 */
ContentPanel.adjust_adminbar = function(adminbar) {
    var dragzone = $(adminbar.children()[0]);
    var tools = $(adminbar.children()[1]);
    width = adminbar.width() - (tools.width() + 23 ); // attention: the 23 is manually aproximated
    dragzone.css('width',  width + 'px');

}




ContentPanel.init_resizables = function(url) {
    var panel_width = $panel.width();
    var grid_limit = panel_width / 12;
    
    $block.resizable({
        containment: $panel,
        grid: [30,30],
        minWidth: 250,
        autoHide: true,
        start: function(event, ui) {
            $(this).css('height', '');
            $($(this).find('.content')[0]).css('height', '');   // reset height of content
            var clone = $(this).parent().clone();
            $('#gencontent_clone_container').html(clone);
            $('#gencontent_clone_container').css('display', 'none');

        },
        resize:  function(event, ui) {
             
            var panel_width = $('#contentpanel').width();
            var grid_limit = panel_width / 12;
            var grid_size = Math.round(ui.size.width / grid_limit);
            if (grid_size > 12)
                grid_size = 12;
            $(this).css('width', '');
            $(this).parent().attr('class', 'grid_' +  grid_size);

            // create clone to preserve y-axis ratio
            var clone = $($('#gencontent_clone_container').children()[0]);
            clone.attr('class', 'grid_' +  grid_size);
            $(this).css('height', $(clone.children()[0]).height());

            ContentPanel.stabelize_grids($panel);
            ContentPanel.adjust_adminbar($(this).find('.adminbar'));
            
        },
        stop: function(event, ui){
            // sync grid with server
            var data = {};
            data.block_id = $(this).parent().attr('id');
            data.grid_size = $(this).parent().attr('class').split('_')[1];

            
            
            ContentPanel.stabelize_grids($panel);
            ContentPanel.adjust_adminbar($(this).find('.adminbar'));
            

            $.ajax( {
                type : 'POST',
                url : url,
                data : {
                    'data' : $.toJSON(data)
                },
                success : function(msg) {

                }
            });

        }
    });
    
}







/**
 *  Takes the gridpanel as argument and stabelizes all grids by adjusting their
 *  heights to the largest height of this row.
 */
ContentPanel.stabelize_grids = function(gridpanel, callback) {


    var main = function() {

        var grids = $(gridpanel).children();
        var grid_summ = 0;
        var grid_list = [];

        
        grids.each(function() {
            
            var grid = $(this);
            var grid_size = get_grid_size(grid);    // get grid size
            grid_summ += grid_size;                 // summ grid size
            grid_list.push(grid);                 // append grid to grid_list

            // -----------------------------------------------------------------
            
            if (grid_summ == 12) {
                // grid exactly match a row
                grid_summ = 0;
                stabelize(grid_list);
                grid_list = [];

            } else if (grid_summ > 12) {
                
                var last_grid = grid_list.pop();     // ectract last
               
                stabelize(grid_list);
                grid_list = [];
                grid_list.push(last_grid);
                stabelize(grid_list);
                grid_summ = get_grid_size(last_grid);
            }

        });

        stabelize(grid_list);

        if (callback) {
            callback();
        }

    }


    /**
     * Returns the size of the grid
     */
    var get_grid_size = function(grid) {
        var grid_class = grid.attr('class').split(' ')[0];
        return parseInt(grid_class.split('_')[1]);
    }



    var stabelize = function(grid_list) {
        var max_height = get_max_height(grid_list);
        $.each(grid_list, function(){
            
            $($(this).find('.content')[0]).css('height', max_height + 'px');
            var content = $($(this).find('.content')[0]);
            // hack to work fine with resizables
            var puffer = parseInt(content.css('padding-top').split('px')[0]) + parseInt(content.css('padding-bottom').split('px')[0]);

            $($(this).find('.contentblock')[0]).css('height', max_height + puffer + 'px');
            
           
        });
    }



    var get_max_height = function(grid_list) {
        var max_height = 0;
        $.each(grid_list, function(){
           var container = $($(this).find('.content')[0]);
           container.css('height', '');

           //var padding = parseInt(container.css('padding-top').split('px')[0]) + parseInt(container.css('padding-bottom').split('px')[0])

           if (container.height()  > max_height){
               max_height = container.height();
           }
        });
       
        return max_height;
    }

    main();

}



/*
 ContentPanel.init_group_by = function(url) {

    var group = [];

    $panel.selectable({
        filter: $block,
        selected: function(event, ui){

            group.push($(ui.selected));
        },
        stop: function(event, ui) {

            if(group.length > 1) {
                $('#groupby').remove();
                var group_btn = $.create('a', {
                    id: 'groupby',
                    style: 'padding: 12px; border: 1px solid red; position: absolute; left: 200px; top: 400px;'
                }, 'Group by');
                $('body').append(group_btn);


                var block_ids = [];
                // send group info to server
                $.each(group, function() {

                    block_ids.push($(this).parent().attr('id'));
                });

                group_btn.click(function() {
                    $.ajax( {
                        type : 'POST',
                        url : url,
                        data : {
                            'block_ids' : $.toJSON(block_ids)
                        }
                    });
                    return false;
                });

            }

        },

        unselected: function(event, ui) {}

    });
}
*/