(function($){

    var $document = $(document);

    $document.off('builder.area.init');
    $document.on('builder.area.init', function (event, product_settings) {
        var template = $.templateEngine.init('builder.area');
        var product_thumbs = "";
        var first = false;
        $.each(product_settings.views, function (key, item) {

            if (first==false) {
                first = item.view_id;
            }

            product_thumbs += template.applyTemplate(
                'item',
                {
                    view_id: item.view_id,
                    preview_url: item.background,
                    area_position: item.area_position,
                    area_size: item.area_size
                }
            );
        });
        $(".thumb_container").remove();
        $(".sys_builder").append(template.applyTemplate('container',{items:product_thumbs}));
        $document.trigger('builder.area.apply.area',[first]);
    });

    $document.off('click', '.sys_builder .thumb_container .builder_area');
    $document.on('click', '.sys_builder .thumb_container .builder_area', function(){
        $this = $(this);
        $document.trigger('builder.area.apply.area',[$this.attr('view_id')]);
    });

    $document.off('builder.area.apply.area');
    $document.on('builder.area.apply.area', function(event, view_id) {
        $document.trigger('b.scip.txt.par');
        $document.trigger('builder.predesign.saver');
        $('.sys_builder .thumb_container .builder_area').removeClass('selected');
        var $sys_builder_container = $('.sys_builder_container');
        var $view = $('.sys_builder .thumb_container .builder_area[view_id="' + view_id + '"]');

        var thisRegex = /background\:(.+)\;/g;
        $sys_builder_container.css('background', thisRegex.exec($view.attr('style'))[1]);
        $view.addClass('selected');

        $document.trigger(
            'builder.area.draw',
            [
                $view.attr('area_position').split(','),
                $view.attr('area_size').split(',')
            ]
        );
        $document.trigger('builder.predesign.load',[view_id]);
    });

    $document.off('builder.getAreaViewsIds');
    $document.on('builder.getAreaViewsIds', function(ev, views_ids){

        var $thumbs = $('.thumb_container .builder_area');

        if($thumbs.length > 0) {
            $.each($thumbs, function(i, item){
                views_ids[views_ids.length] = $(item).attr('view_id');
            })
        }
    });

})(SWjQuery);