var aStruct = {
    a_layout_work__ct: null,
    form: null,
    root: null,
    root_ct: null,
    form_min_width: 700,
    propsLock: false,
    init: function() {
        var _this = this;
        this.form = $(".a_struct__props");
        this.a_layout_work__ct = $("#a_layout_work__ct");
        this.root = $("#a_struct__root");
        this.root_ct = $("#a_struct__root__ct");

        aStruct.readyOpenBlocks();
        aStruct.sortable.init();

        $(window).resize(function(){
            _this.resized();
        }).resize();
    },
    clean_blocks_width: 0,
    clean_blocks: function(level) {
        aStruct.clean_blocks_width = 0;
        $('.a_struct__block').each(function(bk, be){
            if (bk > level) {
                $(be).remove();
            }else{
                aStruct.clean_blocks_width += $(be).outerWidth();
            }
        });
    },
    render_blocks: function(p){
        if(p != undefined){
            p.remove();
        }
        aStruct.resized();
        aStruct.sortable.init();
    },
    update_block: function(parentId, block, module){
        var active = block.find('.a_struct__block__item__current').data('id');
        $.get(window.location.pathname + (window.location.pathname.indexOf("cat") != -1 ? "" : "cat") + "/struct/List?parentId=" + parentId, function(html) {
            block.html($('<div>' + html + '</div>').find('.a_struct__block').html().trim());
            if(active != undefined){
                block.find('.a_struct__block__item[data-id="'+ active +'"]').addClass('a_struct__block__item__current');
            }
        });
    },
    events: {
        open: function($el, level){
            var parentId = $el.data('id');
            var sblock = $el.closest('.a_struct__block');
            var module = $el.data('module');
            var level = level == undefined || level == '' ? sblock.index() : level;
            var params = $el.data('params') != undefined ? $el.data('params') : '';
            if (aStruct.propsLock){
                aStruct.propsLock = false;
                return false;
            }
            var p = preloader._show('#a_struct__root__ct', {
                'left': sblock.position().left + sblock.outerWidth() + 'px',
                'width': $('#a_struct__root__ct').width() - (sblock.position().left + sblock.outerWidth()) + 'px',
            });

            var _block = sblock;

            _block.find('.a_struct__block__item__props_current').removeClass('a_struct__block__item__props_current');
            _block.find('.a_struct__block__item__current').removeClass('a_struct__block__item__current');
            $el.addClass('a_struct__block__item__current');

            aStruct.form.html('');

            $.get(pathPrefix + module + "/List?parentId=" + parentId + params, function(html) {
                aStruct.clean_blocks(level, p);
                _block.after($('<div>' + html + '</div>').find('#a_struct__root__ct').html().trim());
                aStruct.render_blocks(p);
                aStruct._pushState();
            });
        },
        blank: function(type, level, parentId, $el) {
            var id = $el.data('id');
            var sblock = $el.closest('.a_struct__block');
            var module = $el.hasClass('a_struct__block__item__props') ? $el.parent().data('module') : $el.data('module');
            var p = preloader._show('#a_struct__root__ct', {
                'left': sblock.position().left + sblock.outerWidth() + 'px',
                'width': $('#a_struct__root__ct').width() - (sblock.position().left + sblock.outerWidth()) + 'px',
            });
            var level = level == undefined || level == '' ? sblock.index() : level;
            var parentId = parentId === false ? sblock.prev().find('.a_struct__block__item__current').data('id') : parentId;
            parentId = parentId == undefined ? '' : parentId;
            sblock.find('.a_struct__block__item__props_current').removeClass('a_struct__block__item__props_current');
            sblock.find('.a_struct__block__item__current').removeClass('a_struct__block__item__current');

            if ($el.hasClass('a_struct__block__item__props')) {
                aStruct.propsLock = true;
                var id = $el.parent().data('id');
            }

            var block = null;

            if(id){
                block = $el.closest('.a_struct__block');
                $el.parent().find('.a_struct__block__item__current').removeClass('a_struct__block__item__current');
                if($el.hasClass('a_struct__block__item__props')){
                    sblock.find('.a_struct__block__item__current').removeClass('a_struct__block__item__current');
                    $el.addClass('a_struct__block__item__props_current');
                    $el.parent().addClass('a_struct__block__item__current');
                }else{
                    $el.addClass('a_struct__block__item__current');
                }
            }else{
                block = $el.parent().parent().parent();
            }

            $.get(pathPrefix + module + "/Blank?r=" + Math.random() + (id ? "&Id=" + id : "") + (type ? "&object.Group=" + type : "") + (parentId != "" && typeof parentId != "undefined" ? "&parentId=" + parentId : ""), function(html) {
                aStruct.formHandler(aStruct, html, parentId, block, module);
                aStruct.clean_blocks(level);
                aStruct.render_blocks(p);
                aStruct._pushState();
            });
        },
        orderAddProd: function($el){
            var user = 'user=' + $('.a_form').find('select[name="object.User.Id"]').val();
            var id = 'product=' + $el.data('id');
            var sblock = $el.closest('.a_struct__block');
            var p = preloader._show(sblock);
            $.ajax({
                url: '/Admin/Order/ProductJson/?' + user + '&' + id,
                dataType: 'json',
                type: 'GET',
                success: function(o){
                    var orderTable = $('#order_prods').find('tbody');
                    var clone = orderTable.find('tr:first-child').clone();

                    if(clone == undefined || clone.length == 0){
                        clone = $('<tr data-id=""><td class="a_list__table__td" data-col="title"></td><td class="a_list__table__td" data-col="price"></td><td class="a_list__table__td" data-col="count"><input type="text" name="" size="5" value="" required="required" /></td><td class="a_list__table__td"><img src="/Content/i/icon-delete.png" width="16" height="16" style="cursor: pointer;" onclick="$(this).parent().parent().remove()"></td></tr>');
                    }

                    if(orderTable.find('tr[data-id="' + o.id + '"]').length > 0){
                        alert('Товар не может быть выбран, позиция уже присутствует в списке заказа');
                        p.remove();
                        return false;
                    }
                    clone.attr('data-id', o.id);
                    clone.find('td[data-col]').each(function(i, td){
                        var k = $(td).data('col');
                        var $td = $(td);

                        if(o[k] != undefined){
                            switch(k){
                                case 'count':
                                    $td.find('input').attr('name', o.id + '_count').val(1);
                                    break;
                                default:
                                    $td.html(o[k]);
                                    break;
                            }
                        }
                    });
                    orderTable.append(clone);
                    p.remove();
                    a.popup._hide();
                }
            });
        }
    },

    sortable: {
        init: function(){
            var _this = this;
            $('.a_struct__block__scroll').each(function(i, el){
                var $el = $(el);

                if($el.find('.a_struct__block__item_group').length > 0){
                    $el.find('.a_struct__block__item_group').each(function(j, _el){
                        if($(_el).find('.a_struct__block__item').length > 1){
                            _this.initPlug({parent: $(_el)});
                        }else{
                            return;
                        }
                    });
                }else{
                    _this.initPlug({parent: $el});
                }
            });
        },

        initPlug: function(o){
            var $el = o.parent;
            if($el.data('init-sortable') == undefined){
                $el.data('init-sortable', '1');

                $el.sortable({
                    forcePlaceholderSize: true,
                    items: '.a_struct__block__item:not(.a_struct__block__item[data-module="Cat"],.a_struct__block__item[data-module="Product"])'
                }).bind('sortupdate', function(){
                    aStruct.sortable.sendSortedItem(this);
                });
            }
        },

        sendSortedItem: function(parent){
            var data = '';
            var $parent = $(parent);
            var block = $parent.closest('.a_struct__block');
            var parentId = block.data('parent_id');
            var p = preloader._show($(block));
            var url = '/arm/cat/Sort?parentId=' + parentId + '&SetSort=';
            var dataType = 'html';
            var ajaxCallback = function(o){
                var $data = $(o);
                $data = $data.find('.a_struct__block').html();
                block.html($data);
                aStruct.sortable.init();
                p.remove();
            };

            if($parent.hasClass('a_struct__block__item_group')){
                url = '/s/Admin/SetSortOrder?parentId=' + parentId + '&module=' + $parent.data('module') + '&SetSort=';
                dataType = 'json';
                ajaxCallback = function(o){
                    if(o.status == 'error'){
                        alert(o.message);
                    }
                    p.remove();
                }
            }

            $parent.find('.a_struct__block__item').each(function(i, item){
                data += (i == 0 ? '' : ',') + $(item).data('id');
            });

            $.ajax({
                url: url + data,
                type: 'GET',
                dataType: dataType,
                success: function(o){
                    ajaxCallback(o);
                }
            });
        }
    },

    getParam: function(name){
        var params = window.location.search.replace('?', '');
        if(params == ''){return false;}
        params = params.split('&').filter(function(p){
            if(p.indexOf(name) != -1){
                return true;
            }else{
                return false;
            }
        });

        if(params.length == 0){
            return false
        }else{
            return params[0].replace(name + '=', '');
        }
    },

    readyOpenBlocks: function(){
        var i = 0;
        var parent = $('#a_struct__root__ct');
        var elems = aStruct.getParam('path');
        if(elems==false){return false;}
        elems = elems.split(',');

        aStruct.tempInterval = setInterval(function(){
            var id = elems[parent.find('.a_struct__block').length - 1];
            var ids = id.split(':');
            var clName = $('.a_struct__block__item[data-id="' + ids[0] + '"]');
            if(ids[1] == '1'){
                clName = clName.find('.a_struct__block__item__props');
                clName.attr('onclick', clName.attr('onclick') + ';event.stopPropagation();');
            }
            if(i != parent.find('.a_struct__block').length){
                clName.click();
            }
            i = parent.find('.a_struct__block').length;
            if(parent.find('.a_struct__block').length == elems.length){
                clearInterval(aStruct.tempInterval);
            }
        }, 100);
    },

    _pushState: function(){
        var path = '?path=';

        if($('#a_struct__root__ct').closest('.a_layout_work__ct__popup').length > 0){return false;}
        $('#a_struct__root__ct').find('.a_struct__block__item__current').each(function(i, elem){
            var $elem = $(elem);
            path += (i == 0 ? '' : ',') + $elem.data('id') + ':' + ($elem.find('.a_struct__block__item__props_current').length > 0 ? '1' : '0');
        });
        history.pushState('', '', path);
    },

    resized: function() {
        this.root.width(0);
        this.root.width(this.root.parent().width());
        this.root.height($(window).height() - this.root.offset().top);

        var _this = aStruct;
        var ct = _this.form.length > 0 ? _this.form.parent() : $('#a_struct__root');
        var formHeight = null;


        if(_this.form.find("form").length) {
            _this.form.width(0);

            var delta = _this.a_layout_work__ct.outerWidth() - _this.clean_blocks_width;

            if (delta < aStruct.form_min_width) {
                _this.root_ct.width(_this.clean_blocks_width + aStruct.form_min_width);
                _this.root_ct.css('left', _this.a_layout_work__ct.outerWidth() - _this.root_ct.outerWidth());
                _this.form.width(aStruct.form_min_width);
            } else {
                _this.root_ct.css('left', 0);
                _this.form.width(delta);
            }
        } else {
            _this.root_ct.css('left', 0);
        }

        if(_this.form.find('.a_form').length > 0){
            formHeight = $(window).height() - _this.form.find('.a_form').offset().top;
            _this.form.find('.a_form').outerHeight(formHeight).css('overflow', 'auto');
        }

        $('.redactor_box').each(function(){
            var ta = $(this).find('.HTML');
            var iframe = $(this).find('.redactor_frame');
            var props = ta.closest('.a_struct__props');
            var actionBar = props.find('.a_list__batch_actions');
            var tollBar = $(this).find('.redactor_toolbar');
            var h = props.height() - $(this).offset().top - 5;
            var popBox = null;

            h = h < 200 ? 200 : h;
            ta.height(h);
            iframe.height(h);
        });
        if(ct.find('.a_struct__block__scroll') != undefined && ct.find('.a_struct__block__scroll').length > 0){
            popBox = ct.closest('.a_layout_work__ct__popup__box');
            ct.find('.a_struct__block__scroll').outerHeight(ct.height() - ct.find('.a_struct__block__scroll').position().top);
            ct.find('.a_struct__block__scroll').perfectScrollbar();
        }
    },
    moving_sect_upd: function(_this){
        var parentId = $('.finder_section_select').val();
        var block = $('.a_struct__block[data-parent_id="' + parentId + '"]');
        if($('.finder_section_select').length > 0 && parentId != $('.finder_section_select').data('value')){
            var active = block.find('.a_struct__block__item__current');
            $.get(window.location.pathname + "cat/struct/List?parentId=" + parentId, function(html) {

                block.html($('<div>' + html + '</div>').find('.a_struct__block').html().trim());
                if(active.length > 0){
                    block.find('.a_struct__block__item[data-id="' + active.data('id') + '"]').addClass('a_struct__block__item__current');
                }
                $('.a_struct__props').empty();
                _this._pushState();
            });
        }


    },
    formHandler: function(_this, html, parentId, block, module) {
        _this.form.html(html);
        // a.init.domready();

        var $form = _this.form.find("form");

        langTabs.init();
        translateField.init();
        $('input,select').customizeForm();
        $('textarea.rich').each(function () {
            if ($(this).data('redactor') != '1') {
                $(this).data('redactor', '1');
                $(this).redactor();
            }
        });

        $form.submit(function(){
            var p = preloader._show(_this.form);
            var hiddenFields = '';

            var defaults = {};
            defaults["action"] = $('#select_action_id').val();
            var defaultValues = $('.default_val');
            $('.default_key').each(function(k, v){
                var val = $(defaultValues[k]).val();
                var key = $(v).val();
                if(val.length > 0 && key.length > 0 && key !== "action"){
                    defaults[key] = val;
                }
            });

            hiddenFields += '&object.Defaults=' + JSON.stringify(defaults);

            if ($('#object_Icon_Id').length) {
                hiddenFields += '&object.Icon=' + $('#object_Icon_Id').val();
            }
            if ($('#StructFilesId').length) {
                hiddenFields += '&StructFiles=' + $('#StructFilesId').val();
            }
            //hiddenFields += '&act=' + (parentId == '' ? 'create_continue' : 'apply');
            $('#object_Path_id').val($('#parentStructPath').val() + $('#object_Alias_id').val());

            $.post($form.attr("action"), $form.serialize() + hiddenFields, function(html){
                _this.update_block(parentId, block, module);
                _this.moving_sect_upd(_this);
                _this.formHandler(_this, html, parentId, block, module);
                _this.resized();
                p.remove();
            });
            return false;
        });
    },
    translatePreloader: null,
    translateCallBack: function(json) {
        aStruct.translatePreloader.remove();
        $('#object_Alias_id').removeAttr('disabled');
        if (json.text.length) {
            $('#object_Alias_id').val(json.text[0].toLowerCase().replace(/\s/g, '-'));
        }
    },
    translate: function(text) {
        aStruct.translatePreloader = preloader._show('#object_Alias_id__wrap');
        $.get('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20130902T144345Z.5863936671655044.0537dfa3017a4bba694fb9cac72e8e9bc7cf2800&text=' + text + '&lang=ru-en&callback=aStruct.translateCallBack', function(){});
    },
    selectStruct: function($el, $dest, $layout, parentId, id, parentIdBefore) {
        if ($layout.data('skip') == '1') {
            $layout.data('skip', '0');
            return false;
        }
        $layout.show();
        var p = preloader._show($layout);
        $.get(pathPrefix + "Struct/List" + (parentId ? "?parentId=" + parentId : ''), function(html) {
            var html_dest = $('<div style="overflow-y:scroll;height:' + $layout.height() + 'px;width:' + $layout.width() + 'px;">');
            if (parentIdBefore != undefined) {
                html_dest_item = $('<div onclick="aStrust" class="a_struct__block__item">←</div>');
                html_dest_item.click(function(){
                    aStruct.selectStruct($el, $dest, $layout, parentIdBefore, id);
                });
                html_dest.append(html_dest_item);
            }
            $(html).find('.a_struct__block__item__type_0').each(function(k, item){
                if ($(item).data("id") != id) {
                    var itemHtml = $(item);
                    itemHtml.find('span').remove();
                    var html_dest_item_span = $('<span class="button_pseudo" style="display:inline:block;position:absolute;right:8px;top:8px;width:16px;height:16px;padding:0 3px 0 3px;">~</span>');
                    html_dest_item_span.click(function(){
                        $dest.val($(item).data("id"));
                        $el.html($(item).html());
                        $layout.data('skip', '1');
                        $layout.hide();
                    });
                    var html_dest_item = $('<div class="' + $(item).attr('class') + '">' + itemHtml.html() + '</div>');
                    html_dest_item.append(html_dest_item_span);
                    html_dest_item.click(function(){
                        aStruct.selectStruct($el, $dest, $layout, $(item).data("id"), id, parentId);
                    });
                    html_dest.append(html_dest_item);
                }
            });
            $layout.html(html_dest);
            p.remove();
        });
    },
    delete: function(_this){
        _this = $(_this);
        $.post(_this.attr('href'), '_csrf_token=' + _this.data('csrf') + '&sf_method=delete', function (data) {
            if(data == 'ok'){
                if(_this.data('parent_id') == ''){
                    window.location.search = '';
                    return false;
                }else{
                    $('.a_struct__block__item__current').each(function (i, cur) {
                        if($(cur).data('id') == _this.data('parent_id')){
                            $(cur).click();
                        }
                    });
                }
            }else{
                alert('Нельзя удалить объект с вложениями');
            }
        });
    }
};