(function($){

        var $document = $(document);

        var start_recreation = 0;

        $document.off('builder.predesign.saver');
        $document.on('builder.predesign.saver',function(){
            var $view = $('.sys_builder .thumb_container .builder_area.selected');

            var $builder_area = $('.sys_builder .sys_builder_container .builder_area');
            if($builder_area.html()) {
                saved_designs[$view.attr('view_id')] = $builder_area.html();
            }
        });

        $document.off('builder.predesign.load');
        $document.on('builder.predesign.load',function(event, view_id){
            if(saved_designs[view_id] != undefined) {
                $('.sys_builder .sys_builder_container .builder_area').html(saved_designs[view_id]);
            }
            $document.trigger('builder.canvas.applyDragRes');
            $document.trigger('builder.clipart.draggabler');
            $document.trigger('builder.clipart.colors.applyColorPicker');

            $.each($('.sys_builder_container  .builder_area .canvas_container'), function(_, canvas){
                var $canvas = $(canvas);

                if ($canvas.attr('type') == 'text') {
                    var $value = $canvas.find('.value');
                    $document.trigger('b.apl.txt.setts', $value);
                }
            });


        });

        $document.off('builder.predesign.get');
        $document.on('builder.predesign.get', function(event, designs) {
            $document.trigger('builder.predesign.saver');
            var i = 0;


            var edit_areas_params = {};


            $.each($('.thumb_container').find('.builder_area'), function(k, element){
                var $element = $(element);
                edit_areas_params[$element.attr('view_id')] = $element.attr('area_position').split(',');
            });

            $.each(saved_designs, function(key,item){
                var designs_objects = $(item);
                $.each(designs_objects, function(design_key, design){
                    var $design = $(design);
                    if ($design.hasClass('canvas_container')) {

                        var design_item = {};

                        design_item.view_id = $design.attr('view_id');
                        design_item.z_index = $design.css('z-index');


                        design_item.edit_area = {
                            x: edit_areas_params[design_item.view_id][0],
                            y: edit_areas_params[design_item.view_id][1]
                        };

                        design_item.y = $design.css('top').replace('px', '');
                        design_item.rotate = getRotationDegrees($design);
                        design_item.type = $design.attr('type');
                        design_item.canvas_id = $design.attr('canvas_id');

                        if($design.attr('type') == 'text') {

                            design_item.x = parseInt($design.css('left').replace('px', ''));
                            var $text_value = $design.find('.value');
                            design_item.text = $text_value.attr('text');
                            design_item.text_color = $text_value.attr('colorpicker');
                            design_item.fontfamily = $text_value.attr('fontfamily');
                            design_item.outline_size = $text_value.attr('outlinesize');
                            design_item.outline_color = $text_value.attr('colorpickero');
                            design_item.curved_size = $text_value.attr('curvedsize');
                            design_item.font_size = parseInt($design.css('font-size').replace('px', ''));

                            if ($design.attr('w')){
                                design_item.width = $design.attr('w').replace('px', '');
                            }
                            if ($design.attr('h')) {
                                design_item.height = $design.attr('h').replace('px', '');
                            }

                            if ($design.attr('x_indent') && $design.attr('x_indent') > 0) {
                                design_item.x_indent = design_item.x - $design.attr('x_indent');
                            }
                            if ($design.attr('y_indent') && $design.attr('y_indent')>0) {
                                design_item.y_indent = design_item.y - $design.attr('y_indent');
                            }

                            /* Parse transform details */
                            var $current_preview_letters = $design.find('.preview span');
                            if ($current_preview_letters.length > 0) {
                                design_item.transform_indent = [];

                                $.each($current_preview_letters, function(k,letter){

                                    var transform_string = $(letter).css('transform');

                                    if (transform_string.match(/matrix/)) {
                                        var transforms = transform_string.split('(')[1].split(')')[0].split(',');
                                        design_item.transform_indent[design_item.transform_indent.length]
                                            = {x: transforms[4].trim(), y: transforms[5].trim()};
                                    } else if (transform_string.match(/translateX/)) {

                                        var translate_x = /translateX\((-?\d+)px\)/.exec(transform_string)[1];
                                        var translate_y = /translateY\((-?\d+)px\)/.exec(transform_string)[1];

                                        design_item.transform_indent[design_item.transform_indent.length]
                                            = {x: translate_x.trim(), y: translate_y.trim()};
                                    }
                                });

                            }
                        }

                        if($design.attr('type') == 'clipart') {
                            design_item.x = parseInt(parseFloat($design.css('left').replace('px', '')));
                            design_item.clipart_id = $design.attr('clipart_id');
                            var re = /.+(http.+png).+/;
                            design_item.url = $design.css('background-image').replace(re, "$1");
                            design_item.colors = [];
                            design_item.width = $design.css('width').replace('px', '');
                            design_item.height = $design.css('height').replace('px', '');

                            var $colors = $design.find('.color_replacer .color_replace_item');
                            if($colors.length > 0) {
                                $.each($colors, function(i, color){
                                    design_item.colors[design_item.colors.length] = $(color).attr('color');
                                });
                            }
                        }

                        designs[i] = design_item;
                        i++;
                    }
                });
            });

        });

        $document.off('builder.predesign.recreate');
        $document.on('builder.predesign.recreate', function(ev, designs_array) {
            if (start_recreation == 0) {
                start_recreation = 1;
                $.each(designs_array, function (i, designs) {
                    var item = {html: ''};
                    if (saved_designs[designs['view_id']] === undefined) {
                        var template = $.templateEngine.init('builder.area');
                        saved_designs[designs['view_id']] = template.applyTemplate('area_in_predesign');
                    }

                    if (designs.type == 'clipart') {
                        $document.trigger('builder.canvas.build_canvas_item', [designs, item]);
                    }

                    if (designs.type == 'text') {
                        $document.trigger('b.txt.reinitCreatedTexts', [designs, item]);
                    }

                    if (item.html != "") {
                        saved_designs[designs['view_id']] += item.html;
                    }
                });

                $document.trigger('builder.predesign.load', [$('.thumb_container .builder_area.selected').attr('view_id')]);
                $document.trigger('builder.canvas.applyDragRes');
                $document.trigger('builder.clipart.colors.applyColorPicker');
                $document.trigger('builder.design.updated');
                start_recreation = 0;
            }
        });

        $document.off('builder.predesign.remove');
        $document.on('builder.predesign.remove',function(event, view_id){
            if(saved_designs[view_id] != undefined) {
                saved_designs[view_id] = null;
            }
        });

    function getRotationDegrees(obj) {
        var matrix = obj.css("-webkit-transform") ||
            obj.css("webkitTransform")    ||
            obj.css("-moz-transform")    ||
            obj.css("-ms-transform")     ||
            obj.css("-o-transform")      ||
            obj.css("transform");

        var angle = 0;
        if(matrix) {
            if (matrix.match(/^rotate.+/) != null) {
                angle = $.coreUtilites.ra_de(matrix.replace('rotate(', '').replace('rad)', ''));
            }

            if (matrix.match(/^matrix.+/) != null) {
                var values = matrix.split('(')[1].split(')')[0].split(',');
                var a = values[0];
                var b = values[1];
                angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
            }
        }
        return (angle < 0) ? angle + 360 : angle;
    }



})(SWjQuery);