Asiik.Calc = function() {

    var $wrap = $(document.getElementById('calc-form'));

    var $fields, $total;

    var heap = new Array();
    var pool = new Array();

    var cache = new Object();

    var calcType;
    var disableQ = false;

    var loadState = false;

    function _init_() {
        $wrap.find('.calc-type input').change(function() {
            return setCalcType(this.value);
        });
    }


    function setCalcType(type) {
        if (loadState) {
            return false;
        }
        calcType = type;
        if (!cache[calcType]) {
            loadState = true;
            Asiik.getJSON({
                '_do' : 'get_calc_fields',
                'type' : calcType
            }, responseDrawFields);
        } else {
            responseDrawFields(cache[calcType]);
        }
    }


    function responseDrawFields(data) {
        loadState = false;
        cache[calcType] = data;
        heap = [];
        pool = [];
        if (!$fields) {
            $fields = $(document.createElement('div')).appendTo($wrap);
        }
        $fields.empty();
        if ($total) {
            $total.empty();
        }

        if (data.type) {
            disableQ = (data.type.disableQ == '1');
            heap.push({
                id : '-1',
                floorPrice : parseInt(data.type.floorPrice),
                basicPrice : parseInt(data.type.basicPrice)
            });
            drawSqueareFields(data.type);
        }

        if (data.fields) {
            for (var i = 0; i < data.fields.length; i++) {
                drawField(data.fields[i]);
            }
        }
        drawFloorField();
        var $btn = $(document.createElement('button'))
            .html('Расчитать стоимость')
            .click(calculate)
            .appendTo($fields);
    }

    function drawSqueareFields(type) {
        var $field = $(document.createElement('div'))
            .addClass('field')
            .html(
                '<div class="title">Размер стенового проема (можно изменить)</div>' +
                'Ширина (мм) <input type="text" size="4" class="t" name="width" value="' + type.defaultWidth + '">' +
                'Высота (мм) <input type="text" size="4" class="t" name="height" value="' + type.defaultHeight + '">'
            )
            .appendTo($fields);
    }

    function drawFloorField() {
        var $field = $(document.createElement('div'))
            .addClass('field')
            .html('<strong>Этаж</strong> <input type="text" size="4" class="t" name="floor" value="1">')
            .appendTo($fields);
    }

    function drawField(field, parentId) {
        var $field = $(document.createElement('div'))
            .addClass('field')
            .html('<div class="title">' + field.title + '</div>')
            .appendTo($fields);
        for (var i = 0; i < field.items.length; i++) {
            var floor = (field.items[i].floor == '1');
            var price = parseInt(field.items[i].price) || 0;
            var id = field.items[i].id;
            var $label = $(document.createElement('label'))
                .html(field.items[i].title)
                .appendTo($field);
            var $input = $(document.createElement('input'))
                .attr({
                    'type' : field.type,
                    'name' : field.name
                })
                .change(itemChangeHandler)
                .val(id)
                .prependTo($label);
            var p = {
                id : id,
                name : field.name,
                type : field.type,
                floorPrice : (floor) ? price : 0,
                basicPrice : (floor) ? 0 : price,
                _$ : $input
            };
            if (parentId) {
                p.parentId = parentId;
            }
            var subItems = field.items[i].s;
            if (subItems) {
                p.sub = [];
                for (var j = 0; j < subItems.length; j++) {
                    p.sub.push(drawField(subItems[j], id).hide());
                }

            }
            pool.push(p);
        }
        return $field;
    }

    function itemChangeHandler() {
        var id = this.value;
        var name = this.name;
        var checked = this.checked;

        var p;
        for (var i = 0; i < pool.length; i++) {
            if (pool[i].id == id) {
                p = pool[i];
                break;
            }
        }

        if (p) {
            if ((p.type === 'radio') || ((p.type == 'checkbox') && (!checked))) {
                dropFromHeap(p);
            }
            if (checked) {
                appendToHeap(p);
            }
        }
    }

    function dropFromHeap(p, removeAttr) {
        var idx = -1;
        for (var i = 0; i < heap.length; i++) {
            if ((heap[i].name == p.name) && ((p.type === 'radio') || (heap[i].id == id))) {
                idx = i;
                break;
            }
        }
        if (idx > -1) {
            var old = heap[idx];
            if (old.sub) {
                for (var i = 0; i < old.sub.length; i++) {
                    old.sub[i].hide();
                }
            }
            heap.splice(idx, 1);
            if (removeAttr) {
                p._$.removeAttr('checked');
            }
            for (var i = 0; i < heap.length; i++) {
                if (heap[i].parentId == old.id) {
                    dropFromHeap(heap[i], true);
                }
            }
        }
    }

    function appendToHeap(p) {
        heap.push(p);
        if (p.sub) {
            for (var i = 0; i < p.sub.length; i++) {
                p.sub[i].show();
            }
        }
    }

    function calculate() {
        var price = 0;

        var square = parseInt($fields.find('input[name="width"]').val()) * parseInt($fields.find('input[name="height"]').val()) / 1000000;
        if (!square) {
            square = 0;
        }

        var floor = parseInt($fields.find('input[name="floor"]').val()) || 1;

        var basicPrice = heap[0].basicPrice;
        var floorPrice = heap[0].floorPrice;

        if (!disableQ) {
            if (square < 1.19) {
                price += basicPrice * 1.3;
            } else if (square <= 1.89) {
                price += basicPrice * 1;
            } else {
                price += basicPrice * square / 1.89;
            }
        } else {
            price += basicPrice * square;
        }

        price += floorPrice * floor;

        for (var i = 1; i < heap.length; i++) {
            price += heap[i].basicPrice + (heap[i].floorPrice * floor);
        }


        price = Math.ceil(price);

        if (!$total) {
            $total = $(document.createElement('div'))
                .addClass('total')
                .appendTo($wrap);
        }
        $total.html('Общая стоимость составит ' + price.toPrice());

    }

    _init_();
}

