(function($){
    var $document = $(document);

    $document.ready(function(){
        var $canvases = $('.edit_area_block  .edit_area');

        $.each($canvases, function(key,item) {
            var $item = $(item);
            $item.draggable({
                cursor:'move',
                containment: $item.parent('.edit_area_block'),
                opacity:0.8,
                scroll: false,
                start: function() {
                    $(this).removeClass('active');
                },
                stop: function() {
                    $(this).addClass('active');
                }
            }).resizable({
                aspectRatio:false,
                containment: $item.parent('.edit_area_block'),
                minWidth: 10,
                minHeight: 10,
                resize: function(e, ui) {

                }
            });
        });


        $document.off('click', "#design_areas_save");
        $document.on('click', "#design_areas_save", function(){
            var $areas = $(".edit_area_block .edit_area");
            var $builder_statuses = $('.enable_status:checked');

            var data = {};
            data.token = $('#token_item').val();
            data.areas = [];
            data.statuses = [];
            $.each($areas, function(key, area) {
                var $area = $(area);
                data.areas[data.areas.length] = {
                    view_id: $area.attr('view_id'),
                    x: $area.css('left').replace('px',''),
                    y: $area.css('top').replace('px',''),
                    width: $area.css('width').replace('px',''),
                    height: $area.css('height').replace('px','')
                }
            });

            $.each($builder_statuses, function(key, status) {
                var $status = $(status);
                data.statuses[data.statuses.length] = {
                    view_id: $status.attr('view_id'),
                    status: $status.val()
                }
            });

            $.ajax({
                type: 'POST',
                headers: { "cache-control": "no-cache" },
                async: false,
                url: '/modules/myswissstyle/ajax.php?subject=admin&action=set_builder_areas',
                data: data,
                success: function(data) {
                    data = $.parseJSON(data);

                    if (data.status == 'success') {
                        var $original_body = $('#panel_body');
                        $original_body.animate({backgroundColor: "#66cc66", opacity: 0.5}, 500)
                            .animate({backgroundColor: "#fff", opacity: 1}, 500);
                    }
                }
            });

            return false;
        });
    });

})(SWjQuery);