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


    $document.off('initCanvasControllers');
    $document.on('initCanvasControllers', function() {

            $document.off('click', '.sys_clipart_container .clipart_item');
            $document.on('click', '.sys_clipart_container .clipart_item',function(){
                var $this = $(this);
                $document.trigger('builder.canvas.init',[
                    $this.attr('clipart_id'),
                    $this.attr('normal_url')
                ]);
            });

            $document.off('click', '.canvas_container.active .remover');
            $document.on('click', '.canvas_container.active .remover',function(){
                $(this).parent().remove();
                $document.trigger('builder.predesign.saver');
                $document.trigger('builder.design.updated');
                $document.trigger('b.scip.txt.par');
            });

            $document.off('mousedown', '.canvas_container');
            $document.on('mousedown', '.canvas_container',function() {
                var $this = $(this);
                if (!$this.hasClass('active')) {

                    $document.trigger('b.scip.txt.par');
                    $('.canvas_container').removeClass('active');
                    $this.addClass('active');

                    var $canvases = $('.sys_builder_container  .builder_area .canvas_container');
                    var z_index = 0;
                    $.each($canvases, function (key, item) {
                        if ($(item).css('z-index') > z_index) {
                            z_index = $(item).css('z-index');
                        }
                    });

                    $this.css('z-index', parseInt(z_index) + 1);

                    if ($this.attr('type') == 'text') {
                        $document.trigger('b.load.txt.par', [$this.find('.value')]);
                        $document.trigger('b.full.txt.upd');
                    }
                }
            });
        }
    );

    $document.off('builder.canvas.init');
    $document.on('builder.canvas.init', function(event, clipart_id, image_url) {

        if (canvas_id == 0) {
            canvas_id = $('.canvas_container').length;
        }

        $('.builder_area .canvas_container.active').removeClass('active');
        var template = $.templateEngine.init('builder.canvas');
        var $view = $('.sys_builder .thumb_container .builder_area.selected');

        var $canvases = $('.sys_builder_container  .builder_area .canvas_container');
        var z_index = 0;
        $.each($canvases, function(key,item) {
            if ($(item).css('z-index')>z_index) {
                z_index = $(item).css('z-index');
            }
        });

        var canvas = template.applyTemplate('container',{
            canvas_id: canvas_id,
            view_id: $view.attr('view_id'),
            clipart_id: clipart_id,
            url: image_url,
            z_index: z_index
        });
        $('.sys_builder_container  .builder_area').append(canvas);

        var $canvas = $('.sys_builder_container .builder_area .canvas_container[canvas_id="' + canvas_id +'"][type="clipart"]');
        var $parent = $canvas.parents('.builder_area');
        $canvas.width(( $parent.width() < $parent.height() ? $parent.width() : $parent.height()) - 45);
        if ($canvas.length >0) {
            $canvas.height($canvas.width());
            canvas_id++;
        }

        $.coreUtilites.ajaxRequest(
            {
                action:'get_clipart_colors',
                clipart_id: clipart_id
            },
            function(data){
                if(data.status == 'success' && data.message.length > 0) {
                    var template = $.templateEngine.init('builder.canvas');
                    var $color_replacer = $('.canvas_container.active[type="clipart"] .color_replacer');
                    $.each(data.message,function(key, item){
                        $color_replacer.append(template.applyTemplate('color_replacer_item',
                            {
                                color:item
                            }));

                        var $item = $color_replacer.find('.color_replace_item:last-child');
                        $item.tinycolorpicker();
                        var itemdata = $item.data("plugin_tinycolorpicker");
                        itemdata.setColor(item);
                        $item.bind("change", function(e,color) {
                            var $this = $(this);
                            $this.attr('color',color);
                            var $config = $this.parent().parent();

                            var colors = {};
                            $.each($config.find('.color_replace_item'), function(i,color_item){
                               colors[i] = $(color_item).attr('color');
                            });

                            $.coreUtilites.ajaxRequest(
                                {
                                    action:'get_color_replaced_clipart',
                                    clipart_id:$config.attr('clipart_id'),
                                    colors: colors
                                },
                                function (data) {
                                    if(data.status == "success") {
                                        $config.css('background', "url(" + data.message.medium + ") no-repeat scroll 0% 0% transparent");
                                    }
                                }
                            );
                        });
                    });
                }
            }
        );

        $document.trigger('builder.canvas.applyDragRes');
        $document.trigger('builder.design.updated');

    });

    $document.off('builder.canvas.build_canvas_item');
    $document.on('builder.canvas.build_canvas_item', function(ev, params, canvas_item) {

        params.url = params.url.replace(/url\(\"(.+)\"\)/, '$1');

        var template = $.templateEngine.init('builder.canvas');

        canvas_id = params.canvas_id;
        var canvas = template.applyTemplate('container',{
            canvas_id: params.canvas_id,
            view_id: params.view_id,
            clipart_id: params.clipart_id,
            url: params.url,
            z_index: params.z_index,
            other_css: ''
        });

        var $canvas = $('<div />').html(canvas);
        $canvas.children().css('height','' + params.height + 'px');
        $canvas.children().css('width','' + params.height + 'px');
        $canvas.children().css('left','' + params.x + 'px');
        $canvas.children().css('top','' + params.y + 'px');
        if(params.rotate) {
            var rotate_radian = parseFloat(params.rotate) * Math.PI / 180;
            $canvas.children().css('transform','rotate(' + rotate_radian + 'rad)');
        }

        $canvas.children().removeClass('active');

        if(params.colors != undefined && params.colors.length > 0) {

            template = $.templateEngine.init('builder.canvas');
            var $color_replacer = $canvas.find('.color_replacer');
            $.each(params.colors, function (key, item) {
                $color_replacer.append(template.applyTemplate('color_replacer_item',
                    {
                        color: item
                    }));
            });
        }
        canvas_item.html = $canvas.html();
        canvas_id++;
    });

    $document.off('builder.clipart.colors.applyColorPicker');
    $document.on('builder.clipart.colors.applyColorPicker', function() {

        var items = $('.color_replacer .color_replace_item');

        $.each(items, function(i, item) {
            var $item = $(item);

            $item.tinycolorpicker();
            var itemdata = $item.data("plugin_tinycolorpicker");
            itemdata.setColor($item.attr('color'));

            $item.bind("change", function (e, color) {
                var $this = $(this);
                $this.attr('color', color);
                var $config = $this.parent().parent();

                var colors = {};
                $.each($config.find('.color_replace_item'), function (i, color_item) {
                    colors[i] = $(color_item).attr('color');
                });

                $.coreUtilites.ajaxRequest(
                    {
                        action: 'get_color_replaced_clipart',
                        clipart_id: $config.attr('clipart_id'),
                        colors: colors
                    },
                    function (data) {
                        if (data.status == "success") {
                            $config.css('background', "url(" + data.message.medium + ") no-repeat scroll 0% 0% transparent");
                        }
                    }
                );
            });
        });


    });

    $document.off('builder.canvas.applyDragRes');
    $document.on('builder.canvas.applyDragRes', function(e, mw,mh) {
        if (mw == undefined) mw=20;
        if (mh == undefined) mh=20;
        var $canvases = $('.sys_builder_container  .builder_area .canvas_container');
        var $edit_helpers = $('.sys_edit_helper');

        $canvases.draggable({
            cursor:'move',
            containment:'.sys_builder_container .builder_area',
            opacity:0.8,
            scroll: false,
            stack:'.sys_builder_container .builder_area .canvas_container',
            start: function() {
                $(this).removeClass('active');
                $edit_helpers.fadeIn(100);
            },
            stop: function() {
                $(this).addClass('active');
                $edit_helpers.fadeOut(500);
            }
        }).resizable({
            grid:[10,1],
            aspectRatio:true,
            containment: $('.sys_builder_container .builder_area'),
            minWidth: mw,
            minHeight: mh,
            /*start: function( event, ui ) {

             },*/
            resize: function(e, ui) {
                var $this = $(this);
                if ($this.attr('type')=="text") {

                    var $chars = $this.find('.preview span');

                    var x_indent = 0;
                    var y_indent = 0;

                    if($chars.length > 0) {

                        var $first_char = $chars.first();
                        var offset = $first_char.offset();
                        var current_offset = $this.offset();
                        x_indent = current_offset.left - offset.left;

                        var min_y_offset = 99999;

                        $.each($chars, function (key, item) {
                            var y_offset = $(item).offset();

                            if (y_offset.top < min_y_offset) {
                                min_y_offset = y_offset.top;
                            }
                        });

                        y_indent = current_offset.top - min_y_offset;
                    }

                    var width = $this.width();
                    var height = $this.height();

                    $this.css("font-size", parseInt($this.height()) + "px");

                    $this.attr('w', width);
                    $this.attr('h', height);
                    $this.attr('x_indent', x_indent);
                    $this.attr('y_indent', y_indent);
                }
            },
            stop: function(e, ui) {
                var $this = $(this);
                if ($this.attr('type')=="text") {
                    $document.trigger('b.full.txt.upd');
                }
            }
        }).rotatable(
            {
                // Callback fired on rotation start.
                start: function (event, ui) {
                },
                // Callback fired during rotation.
                rotate: function (event, ui) {
                },
                // Callback fired on rotation end.
                stop: function (event, ui) {
                    var $this = $(this);
                    var $track = $this.find('.track');

                    var matrix = $this.css("-webkit-transform") ||
                        $this.css("-moz-transform")    ||
                        $this.css("-ms-transform")     ||
                        $this.css("-o-transform")      ||
                        $this.css("transform");

                    var angle = 0;
                    if(matrix !== 'none') {
                        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));
                    }
                    var real_angle = (angle < 0) ? angle + 360 : angle;

                    var rotate_radian = parseFloat(360 - real_angle) * Math.PI / 180;
                    $track.css('transform','rotate(' + rotate_radian + 'rad)');


                }
            }
        );
    });
})(SWjQuery);