(function($){

    var text_canvas_id = 0;
    var $document = $(document);
    $document.off('builder.inittextcontrollers');
    $document.on('builder.inittextcontrollers',function() {
        $document.trigger('b.in.fo.st');
        $document.off('keyup','.sys_text_container #sys_text_input');
        $document.on('keyup','.sys_text_container #sys_text_input',function(){
            $document.trigger('b.upd.txt.cv')
        });
        var $box = $('#colorPicker');
        $box.tinycolorpicker();
        var box = $box.data("plugin_tinycolorpicker");
        box.setColor("#000000");
        $box.bind("change", function() {
            $document.trigger('b.full.txt.upd');
        });
        var $box = $('#colorPickerO');
        $box.tinycolorpicker();
        var box = $box.data("plugin_tinycolorpicker");
        box.setColor("#000000");
        $box.bind("change", function() {
            $document.trigger('b.full.txt.upd');
        });

    });

    $document.off('b.upd.txt.cv');
    $document.on('b.upd.txt.cv',function() {
        var canvas = {};
        $document.trigger('b.full.txt.upd', [canvas]);
        canvas.element.css('width','');
        canvas.element.css('height','');
        $document.trigger('update.text.canvas.params',[canvas.element]);

    });

    $document.off('b.full.txt.upd');
    $document.on('b.full.txt.upd', function(e, canvas_init){
        var canvas = {};
        if (canvas_init != undefined) {
            canvas = canvas_init;
        } else {
            canvas = {element:false};
        }

        $document.trigger('b.g.act.txt.cnv', [canvas]);
        if (canvas.element == false) {
            $document.trigger('b.crt.txt.cnv',[canvas]);
        }
        var $value = canvas.element.find('.value');
        $document.trigger('b.upd.txt.setts',[$value]);
        $document.trigger('b.apl.txt.setts',[$value]);
    });

    $document.off('b.g.act.txt.cnv');
    $document.on('b.g.act.txt.cnv',function(el, canvas) {
        var $canvas = $('.sys_builder_container  .builder_area .canvas_container[type="text"].active');
        if($canvas.length == 0) {
            canvas.element = false
        } else {
            canvas.element = $canvas
        }
    });

    $document.off('b.crt.txt.cnv');
    $document.on('b.crt.txt.cnv',function(event,canvas) {
        $('.builder_area .canvas_container.active').removeClass('active');
        var template = $.templateEngine.init('builder.text');
        var $view = $('.sys_builder .thumb_container .builder_area.selected');

        var $textinput = $('#sys_text_input');
        if ($textinput.val() == false) {
            $textinput.val('Text');
        }

        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');
            }
        });

        $('.sys_builder_container .builder_area').append(
            template.applyTemplate('container',{
                canvas_id: text_canvas_id,
                view_id: $view.attr('view_id'),
                z_index: z_index
            })
        );

        canvas.element = $('.sys_builder_container  .builder_area .canvas_container[type="text"][canvas_id="' + text_canvas_id + '"]');


        var $chars = canvas.element.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 = canvas.element.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 = canvas.element.width();
        var height = canvas.element.height();

        canvas.element.css("font-size", parseInt(canvas.element.height()) + "px");

        canvas.element.attr('w', width);
        canvas.element.attr('h', height);
        canvas.element.attr('x_indent', x_indent);
        canvas.element.attr('y_indent', y_indent);

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

    });

    $document.off('b.txt.reinitCreatedTexts');
    $document.on('b.txt.reinitCreatedTexts',function(e, params, html) {

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

        var item = template.applyTemplate('container',{
            canvas_id: params.canvas_id,
            view_id: params.view_id,
            z_index: params.z_index
        });

        var $item = $('<div />').html(item);
        var $value = $item.find('.value');

        $item.find('.canvas_container').removeClass('active');

        $item.children().css('width', '' + params.width + 'px');
        $item.children().css('left', '' + parseInt(parseInt(params.x) + parseInt(params.outline_size)/2) + 'px');
        $item.children().css('top', '' + params.y + 'px');
        $item.children().css('font-size', '' + params.font_size + 'px');

        if(params.rotate) {
            var rotate_radian = parseFloat(params.rotate) * Math.PI / 180;
            $item.children().css('transform','rotate(' + rotate_radian + 'rad)');
        }

        $value.attr('text', params.text);
        $value.attr('fontFamily', params.fontfamily);
        $value.attr('colorpicker', params.text_color);
        $value.attr('colorpickero', params.outline_color);
        $value.attr('curvedsize', params.curved_size);
        $value.attr('outlinesize', params.outline_size);

        if (params.width) {
            $item.children().attr('w', params.width);
        }
        if (params.height) {
            $item.children().attr('h', params.height);
        }

        if (params.x_indent) {
            $item.children().attr('x_indent', params.width);
        }
        if (params.y_indent) {
            $item.children().attr('y_indent', params.width);
        }

        $document.trigger('b.apl.txt.setts',[$value]);

        if(params.curved_size != 0) {

            var $preview = $item.find('.preview');
            $preview.width(params.width);
            $preview.height(params.height);

            if($value.attr('text')) {
                $preview.html($value.attr('text'));
            }
            $document.trigger('b.ap.txt.cur',[$preview, parseFloat(params.curved_size)]);
        }

        html.html = $item.html();

        text_canvas_id = params.canvas_id;
        text_canvas_id++;
    });

    $document.off('b.upd.txt.setts');
    $document.on('b.upd.txt.setts', function(e, value){

        var config = {};
        $document.trigger('b.get.txt.allsettings',[config]);

        $.each(config, function(k, item){
            value.attr(k,item);
        });
    });

    $document.off('b.apl.txt.setts');
    $document.on('b.apl.txt.setts',function(e, value){

        var value = $(value);

        value.next('.preview').remove();
        value.after("<div class='preview'></div>");

        var $preview = value.next('.preview');

        if(value.attr('text') == "") {
            value.parent().remove();
            return;
        }

        if(value.attr('text')) {
            $preview.html(value.attr('text'));
        }
        if(value.attr('fontFamily')) {
            $document.trigger('b.set.txt.ff',[$preview,value.attr('fontFamily')]);
        }
        if(value.attr('colorpicker')) {
            $document.trigger('b.set.txt.clr',[$preview,value.attr('colorpicker')]);
        }
        if(value.attr('colorpickero')) {
            $document.trigger('b.set.txt.os',[
                $preview,
                value.attr('outlinesize'),
                value.attr('colorpickero')
            ]);
        }
        if(value.attr('curvedsize')) {
            $document.trigger('b.ap.txt.cur',[$preview, value.attr('curvedsize')]);
            value.parent().css('width','');
            value.css('height','');
        }
    });


    $document.off('b.get.txt.allsettings');
    $document.on('b.get.txt.allsettings', function(e, result) {
        var $controllers = $('.sys_font_controller_item');
        $.each($controllers, function(k, item){
            var $item = $(item);
            result[$item.attr('name')] = $item.val()
        });
    });


    $document.off('b.set.txt.clr');
    $document.on('b.set.txt.clr',function(event, element, color) {
        if (element.length > 0) {
            element.css('color',color);
        }
    });

    $document.off('b.set.txt.ff');
    $document.on('b.set.txt.ff',function(event, element, font) {
        if (element.length > 0) {
            element.css('font-family',font);
        }
    });

    $document.off('b.set.txt.os');
    $document.on('b.set.txt.os',function(e, element, stoke, color) {
        var canvas = {element:element};
        if (canvas.element.length > 0) {

            if(stoke==0) {
                canvas.element.css('text-shadow','');
            } else {

                canvas.element.css(
                    'text-shadow',
                    '' + stoke + 'px ' +
                    '' + stoke + 'px ' +
                    '' + stoke + 'px ' + color + ',' +

                    '-' + stoke + 'px ' +
                    '-' + stoke + 'px ' +
                    '' + stoke + 'px ' + color + ',' +

                    '-' + stoke + 'px ' +
                    '' + stoke + 'px ' +
                    '' + stoke + 'px ' + color + ',' +

                    '' + stoke + 'px ' +
                    '-' + stoke + 'px ' +
                    '' + stoke + 'px ' + color + ',' +

                    '0px ' +
                    '' + stoke + 'px ' +
                    '' + stoke + 'px ' + color + ',' +

                    '-' + stoke + 'px ' +
                    '0px ' +
                    '' + stoke + 'px ' + color + ',' +

                    '' + stoke + 'px ' +
                    '0px ' +
                    '' + stoke + 'px ' + color + ',' +

                    '0px ' +
                    '-' + stoke + 'px ' +
                    '' + stoke + 'px ' + color + ''
                );
            }
        }
    });

    $document.off('b.in.fo.st');
    $document.on('b.in.fo.st',function(){

        var template = $.templateEngine.init('text.setting');
        var $fontFamily = $('#fontFamily');

        $.each(fonts_list, function(key,item){
            $fontFamily.append(template.applyTemplate(
                'font',
                {
                    name: item.title,
                    family: item.family
                }
            ));
        });

        $document.trigger('initDropdowns',[
            function(){
                var $fonts_dropdown = $('.ss_dropdown[for_id="fontFamily"]');

                $.each(
                    $fonts_dropdown.find('.ss_dropdown_item'),
                    function(k, item){
                        var $item = $(item);
                        if ($item.html() != '') {
                            $item.css('font-family', $item.attr('value') + ',sant-serif');
                        }
                    }
                );
            }
        ]);
    });

    $document.off('b.ap.txt.cur');
    $document.on('b.ap.txt.cur', function(e, element, curved_size) {
        var dir = (curved_size<0)?-1:1;

        curved_size = parseFloat(curved_size);

        if (curved_size<0) { curved_size = curved_size * -1}
        var width = element.width();

        var size = 0;
        if (curved_size != 0) {
            size = parseInt((1/curved_size) * width);
        }

        if(element.find('span').length == 0 && size != 0) {
            element.arctext( {
                radius: "" + size,
                dir: dir
            });
        }
    });

    $document.off('b.scip.txt.par');
    $document.on('b.scip.txt.par', function(e) {
        var settings = {};
        $document.trigger('b.get.txt.allsettings',[settings]);

        $.each(settings,function(key, value){
            switch(key) {
                case 'text':
                    $('#sys_text_input').val('');
                    break;
                case 'colorpicker':
                    $('#colorPicker .colorInner').css('background-color','#000');
                    $('#colorPicker input[name="colorpicker"]').val('#000');
                    break;
                case 'colorpickero':
                    $('#colorPickerO .colorInner').css('background-color','#000');
                    $('#colorPickerO input[name="colorpickero"]').val('#000');
                    break;
                case 'fontfamily':
                    $('#fontFamily').val("");
                    $document.trigger('updateDropdown',['#fontFamily',""]);
                    break;
                case 'outlinesize':
                    $('#outlineSize').val("0");
                    $document.trigger('updateDropdown',['#outlineSize',"0"]);
                    break;
                case 'curvedsize':
                    var $fontfam = $('#curvedSize');
                    $fontfam.val("0");
                    $document.trigger('updateDropdown',['#curvedSize',"0"]);
                    break;
            }
        });
    });

    $document.off('b.load.txt.par');
    $document.on('b.load.txt.par', function(e, element) {
        var settings = {};
        $document.trigger('b.get.txt.allsettings',[settings]);
        var $element = $(element);

        $.each(settings,function(key, value){
            switch(key) {
                case 'text':
                    $('#sys_text_input').val($element.attr('text'));
                    break;
                case 'colorpicker':
                    $('#colorPicker .colorInner').css('background-color',$element.attr('colorpicker'));
                    $('#colorPicker input[name="colorpicker"]').val($element.attr('colorpicker'));
                    break;
                case 'colorpickero':
                    $('#colorPickerO .colorInner').css('background-color',$element.attr('colorpickero'));
                    $('#colorPickerO input[name="colorpickero"]').val($element.attr('colorpickero'));
                    break;
                case 'fontfamily':
                    $('#fontFamily').val($element.attr('fontfamily'));
                    $document.trigger('updateDropdown',['#fontFamily',$element.attr('fontfamily')]);
                    break;
                case 'outlinesize':
                    $('#outlineSize').val($element.attr('outlinesize'));
                    $document.trigger('updateDropdown',['#outlineSize',$element.attr('outlinesize')]);
                    break;
                case 'curvedsize':
                    $('#curvedSize').val($element.attr('curvedsize'));
                    $document.trigger('updateDropdown',['#curvedSize',$element.attr('curvedsize')]);
                    break;
            }
        });
    });

    $document.off('click', '.sys_builder .sys_builder_container .builder_area .sys_selector');
    $document.on('click', '.sys_builder .sys_builder_container .builder_area .sys_selector', function(){
        var $canvas = $('.sys_builder .sys_builder_container .builder_area .canvas_container.active');
        if($canvas.length == 0) return;

        $canvas.removeClass('active');
        if ($canvas.attr('type') == 'text') {
            $document.trigger('b.scip.txt.par');
        }
    });

    $document.off('click', '.sys_builder .sys_builder_container .clear');
    $document.on('click', '.sys_builder .sys_builder_container .clear', function(){
        var $canvas = $('.sys_builder .sys_builder_container .builder_area .canvas_container.active');

        if($canvas.length == 0) return;

        $canvas.removeClass('active');
        if ($canvas.attr('type') == 'text') {
            $document.trigger('b.scip.txt.par');
        }
    });

    $document.off('update.text.canvas.params');
    $document.on('update.text.canvas.params',function(e, canvas){
        var $canvas_item = $(canvas);

        if ($canvas_item.attr('type')=="text") {

            var $chars = $('.sys_builder_container .builder_area .canvas_container .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 = $canvas_item.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 = $canvas_item.width();
            var height = $canvas_item.height();

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

            $canvas_item.attr('w', width);
            $canvas_item.attr('h', height);
            $canvas_item.attr('x_indent', x_indent);
            $canvas_item.attr('y_indent', y_indent);
        }
    });

})(SWjQuery);