/* because of perfect code portability! */
document.forms.EditView = document.forms.DetailView;

var CHANGER = new changer();
CHANGER.interval = 500;
  

/**
 * Node list to array converter.
 *
 * @param {NodeList} nl
 * @returns {Array}
 */
var nl2a = function(nl) {
    var a = new Array();

    for (var i in nl) {
        var tmpNli = nl[i];
        a.push(tmpNli);
    }

    return a;
};

var modifyDetails = function() {
    return true;

    var select = document.getElementById('_type');
    // select.getValue = selectGetValue;

    var selectedValues = select.value;
    // var type = selectedValues[0];
    var xtype = (select.value) ? 1 : 0;
    
    var div = document.getElementById('DETAILS');
    var forms = div.getElementsByClassName('tabForm');
    var form = forms[0];
    
    var tr = form.getElementsByTagName('tr');
    
    tr[8].style.display = (xtype != 1) ? 'table-row' : 'none';
    tr[9].style.display = (xtype != 1) ? 'table-row' : 'none';
    tr[10].style.display = (xtype != 1) ? 'table-row' : 'none';

    // tr[11].style.display = (xtype != 1) ? 'table-row' : 'none';
    // tr[12].style.display = (xtype != 1) ? 'table-row' : 'none';
    // tr[13].style.display = (xtype != 1) ? 'table-row' : 'none';
    // tr[14].style.display = (xtype != 1) ? 'table-row' : 'none';

    return;
}

var modifyTable = function() {
    // return true;
    
    var select = document.getElementById('type');
    select.getValue = selectGetValue;

    var selectedValues = select.getValue();
    var type = selectedValues[0];
    var xtype = (select.getValue()[0] == 1) ? 1 : 0;

    var chunks = new Array();
    chunks[0] = new Array();
    chunks[1] = new Array();
    
    /* BOF: Build chunks table. */
    var head = document.getElementById('head');
    var headRow = head.children[0];
    var headerCells = nl2a(head.getElementsByTagName('td'));

    // console.log(headerCells);
    
    var filter = function(parent , array, param, neg) {
        if(typeof(neg) == 'undefined') {
            neg = false;
        }
        
        var regexp = new RegExp('use_' + param);
        
        // console.log(regexp);
        // return;
        
        var returnArray = array.filter(function(element) {
            // console.log(element.parentNode.parentNode == parent);
        
            if(typeof(element) == 'object' && element.parentNode == parent) {
                // console.log('x', element, element.getAttribute('class').match(regexp));
                // return true;
                
                if(!element.getAttribute('class')) {
                    element.setAttribute('class', '')
                }
                
                if(element.getAttribute('class').match(regexp)) {
                    return !neg;
                } else {
                    return neg;
                }
            }
            
            return false;
        });
        
        return returnArray;
    };
    
    chunks[0][0] = filter(headRow, headerCells, type, true);
    chunks[1][0] = filter(headRow, headerCells, type, false);
    
    // console.log(chunks);
    // return;
    
    for (var i = 0, iCounter = N.rowCount(); i < iCounter; i++) {
        var row = N.row(i);
        var rowCells = nl2a(row.getElementsByTagName('td'));

        chunks[0][i + 1] = filter(row, rowCells, type, true);
        chunks[1][i + 1] = filter(row, rowCells, type, false);
    }
    
    // console.log(chunks);
    // return;
    
    /* BOF: Toggle display. */
    for (var i = 0, iCounter = chunks[0].length; i < iCounter; i++) {
        var tmpRow = chunks[0][i];

        for (var j = 0, jCounter = tmpRow.length; j < jCounter; j++) {
            var tmpCell = tmpRow[j];
            tmpCell.style.display = 'none';
            // tmpCell.style.display = (xtype == 0) ? 'table-cell' : 'none';
        }
    }

    for (var i = 0, iCounter = chunks[1].length; i < iCounter; i++) {
        var tmpRow = chunks[1][i];

        for (var j = 0, jCounter = tmpRow.length; j < jCounter; j++) {
            var tmpCell = tmpRow[j];
            tmpCell.style.display = 'table-cell';
            // tmpCell.style.display = (xtype == 1) ? 'table-cell' : 'none';
        }
    }
    /* EOF: Toggle display. */
    
    return;
};

/* Decree */
addEvent(
    window,
    'load',
    function() {


        CHANGER.add(
            'account_acc_wn',
            'checked',
            function(obj) {
                if (true == obj.checked) {
                    document.getElementById('acc_wn').disabled = true;
                    document.getElementById('acc_wn_code').disabled = true

                    document.getElementById('btn_acc_wn_code').disabled = true
                    document.getElementById('btn_clr_acc_wn_code').disabled = true

                    return true;
                }

                document.getElementById('acc_wn').disabled = false;
                document.getElementById('acc_wn_code').disabled = false;

                document.getElementById('btn_acc_wn_code').disabled = false;
                document.getElementById('btn_clr_acc_wn_code').disabled = false;
            },
            false
        );

        CHANGER.add(
            'account_acc_ma',
            'checked',
            function(obj) {
                if (true == obj.checked) {
                    document.getElementById('acc_ma').disabled = true;
                    document.getElementById('acc_ma_code').disabled = true

                    document.getElementById('btn_acc_ma_code').disabled = true
                    document.getElementById('btn_clr_acc_ma_code').disabled = true

                    return true;
                }

                document.getElementById('acc_ma').disabled = false;
                document.getElementById('acc_ma_code').disabled = false;

                document.getElementById('btn_acc_ma_code').disabled = false;
                document.getElementById('btn_clr_acc_ma_code').disabled = false;
            },
            false
        );
        
        set_focus();

        //initialize register
        N = new MyTable('itemsTable');
        N.divParent = document.getElementById('itemsTableDIV');
        
        var _type = document.getElementById('_type');
        // _type.getValue = selectGetValue;
            console.log('type', _type.value);

                switch (_type.value) {
                    default:
                        break;
                    case '0': // Ogólny
                        modifyTable(0);
                        modifyDetails(0);

                        // zob_nal.setValue(1);
                        // zob_nal.disabled='disabled';
                        
                            // ITEMS_menu.style.display='inline-block';
                            
                        // var updateButton = document.getElementById('update_button');
                        // updateButton.style.display = 'block';

                        break;
                    case '1': // Płatniczy
                        modifyTable(1);
                        modifyDetails(1);

                        // zob_nal.setValue(1);
                        // zob_nal.disabled='';
                        
                            // ITEMS_menu.style.display='none';
                        
                        // var updateButton = document.getElementById('update_button');
                        // updateButton.style.display = 'none';

                        break;
                    case '2': // Sprzedaży - tylko odbiorca
                        modifyTable(0);
                        modifyDetails(0);

                        // zob_nal.setValue(1);
                        // zob_nal.disabled='disabled';
                        
                            // ITEMS_menu.style.display='inline-block';
                            
                        // var recipient_account = document.getElementById('recipient_account');
                        // var recipient_account_code = document.getElementById('recipient_account_code');
                        // acc_code.value = recipient_account_code.value;
                        // object.value = recipient_account.value;

                        // var updateButton = document.getElementById('update_button');
                        // updateButton.style.display = 'block';

                        break;
                    case '3': // Zakupu - tylko dostawca
                        modifyTable(0);
                        modifyDetails(0);
                        
                        // zob_nal.setValue(1);
                        // zob_nal.disabled='disabled';
                        
                            // ITEMS_menu.style.display='inline-block';
                            
                        // var supplier_account = document.getElementById('supplier_account');
                        // var supplier_account_code = document.getElementById('supplier_account_code');
                        // acc_code.value = supplier_account_code.value;
                        // object.value = supplier_account.value;

                        // var updateButton = document.getElementById('update_button');
                        // updateButton.style.display = 'block';

                        break;
                }

        var from_popup_return = false;

        function returnedData(popup_reply_data) {
            from_popup_return = true;

            var form_name = popup_reply_data.form_name;
            var name_to_value_array = popup_reply_data.name_to_value_array;

            for (var the_key in name_to_value_array) {
                if (the_key == 'toJSON') {
                    //
                }
                else {
                    var displayValue = name_to_value_array[the_key].replace(/&amp;/gi, '&').replace(/&lt;/gi, '<').replace(/&gt;/gi, '>').replace(/&#039;/gi, '\'').replace(/&quot;/gi, '"');

                    var e = document.getElementById(the_key);

                    if (e) {
                        e.value = displayValue;
                    }
                }
            }

           // if(N.selectedRow)
               // N.selectedRow.calculateTotal();
        }

        N.onRefreshRowIndex = function(row) {
            return true;
            
            var data = new Object();
            data['index'] = (row.index + 1).toString();

            row.cells.item(0).setData(data);
        };

        N.onCreateRow = function(row) {
            // console.log(row);
            
            row.newPos = false;
            row.style.height = OPT['row_item_height'];

            row.ondblclick = function() {
                this.newPos = !this.newPos;

                for (var i = 0; i < this.myTable.colCount(); i++) {
                    this.cells.item(i).change(!this.newPos);
                }
            };

            row.onSelect = function() {
                for (var i = 0; i < this.myTable.colCount(); i++) {
                    this.cells.item(i).style.height = OPT['row_item_height_selected'];
                    this.cells.item(i).change(!this.newPos);
                }
            };

            row.onDeselect = function() {
                for (var i = 0; i < this.myTable.colCount(); i++) {
                    this.cells.item(i).style.height = OPT['row_item_height'];
                    this.cells.item(i).change(false);
                }
            };

            row.calculateTotal = function() {
                calculateTotalItems();
                // console.log('calculateTotal');
                return true;

                var data = new Object();

                this.cells.item(3).getData(data, true);
                this.cells.item(5).getData(data, true);
                this.cells.item(6).getData(data, true);

                if (data.quantity && data.price) {
                    data.price2 = data.price - data.price * data.discount / 100;
                    data.total = data.quantity * data.price2;
                }
                else {
                    data.total = 0;
                    data.price2 = 0;
                }

                this.cells.item(7).setData(data);
                this.cells.item(10).setData(data);

                calculateTotalItems();
            };
        };

        var itd = document.getElementById('itemsTableDIV');
        
        itd.onscroll = function() {
            // console.log('onscroll');
            return true;

            if (!AjaxSearch1Items.AjaxSearchFrozen)
                if (N.selectedCell && N.selectedCell.LeftPosition && N.selectedCell.TopPosition) {
                    var top = N.selectedCell.TopPosition + N.selectedCell.offsetHeight;

                    if (((N.selectedCell.offsetTop + N.selectedCell.offsetHeight - this.scrollTop) > (this.offsetHeight + 5)) || ((N.selectedCell.offsetTop - this.scrollTop) < (-10)))
                        AjaxSearch1Items.div.style.display = 'none';
                    else
                        AjaxSearch1Items.div.style.display = '';

                    AjaxSearch1Items.div.style.top = top - this.scrollTop;
                }
        };

        N.onCreateCell = function(cell) {
            var i = cell.index;

            cell.change = function(select) {
                //
            };

            cell.style.height = OPT['row_item_height'];

            // cell.select = function() {
                // var d = new Date();
                // console.log(d + " " + i);
            // }
            
            cell.onDeselect = function() {
                var data = this.parentNode.getData();

                console.log(data);
                
                // if (!data.id || data.id == '') {
                    // var data2 = new Object();

                    this.parentNode.setData(data);
                // }
            };
            
            // Code.
            if (i == 0) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log('change', cn);
                    
                    if(select) {
                        cn[0].name = 'i_code';
                        cn[0].id = 'i_code';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                    }
                }
                
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');
                    
                    if(cn[0].value) {
                        data.i_code = cn[0].value;
                    } else {
                        data.i_code = false;
                    }
                };

                cell.setData = function(data) {
                    var cn = this.getElementsByTagName('input');
                    
                    if(data.i_code) {
                        cn[0].value = data.i_code;
                    } else {
                        cn[0].value = '';
                    }
                };
                
                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'text');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.className = 'inputs';

                cell.appendChild(edit0);
            }

            // Name.
            if (i == 1) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log('change', cn);
                    
                    if(select) {
                        cn[0].name = 'i_name';
                        cn[0].id = 'i_name';
                        
                        cn[1].name = 'ecmfkvattable_id';
                        cn[1].id = 'ecmfkvattable_id';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                        
                        cn[1].name = '';
                        cn[1].id = '';
                    }
                }
                
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');
                    
                    if(cn[0].value) {
                        data.i_name = cn[0].value;
                    } else {
                        data.i_name = false;
                    }
                    
                    if(cn[1].value) {
                        data.ecmfkvattable_id = cn[1].value;
                    } else {
                        data.ecmfkvattable_id = false;
                    }
                };

                cell.setData = function(data) {
                    var cn = this.getElementsByTagName('input');
                    
                    if(data.i_name) {
                        cn[0].value = data.i_name;
                    } else {
                        cn[0].value = '';
                    }
                    
                    if(data.ecmfkvattable_id) {
                        cn[1].value = data.ecmfkvattable_id;
                    } else {
                        cn[1].value = '';
                    }
                };
                
                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'text');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.className = 'inputs';

                cell.appendChild(edit0);
                  
                var edit1 = document.createElement('input');
                edit1.setAttribute('type', 'hidden');
                // edit1.setAttribute('readOnly', 'readonly');
                edit1.setAttribute('tabIndex', 1);
                edit1.className = 'inputs';

                cell.appendChild(edit1);
                  
                /* Vattalbe unsused this time.
                var img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_IMG_SEARCH']);
                img.setAttribute('src', 'modules/EcmInvoiceOuts/images/search.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    try {
                        this.parentNode.select();
                    } catch(e) {
                        //
                    }

                    this.parentNode.ajax_search = false;

                    var ecmpopup = my_popup(
                            'EcmFkVatTables',
                            {
                                'id':'ecmfkvattable_id',
                                'name':'i_name',
                                'position':'i_code'
                            }
                        );

                    setTimeout(
                        function(){
                            ecmpopup.focus();
                        },
                        200
                    );
                }

                // Search image button.
                cell.appendChild(img);
                */
            }

            // Wn.
            if (i == 2) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log('change', cn);
                    
                    if(select) {
                        cn[0].name = 'i_acc_wn';
                        cn[0].id = 'i_acc_wn';
                        
                        cn[1].name = 'i_acc_wn_code';
                        cn[1].id = 'i_acc_wn_code';
                        
                        cn[2].name = 'i_acc_wn_name';
                        cn[2].id = 'i_acc_wn_name';
                        
                        cn[3].name = 'i_acc_wn_type';
                        cn[3].id = 'i_acc_wn_type';
                        
                        cn[4].name = 'i_account_acc_wn';
                        cn[4].id = 'i_account_acc_wn';
                        
                        cn[5].name = 'i_acc_wn_kind';
                        cn[5].id = 'i_acc_wn_kind';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                        
                        cn[1].name = '';
                        cn[1].id = '';
                        
                        cn[2].name = '';
                        cn[2].id = '';
                        
                        cn[3].name = '';
                        cn[3].id = '';
                        
                        cn[4].name = '';
                        cn[4].id = '';
                        
                        cn[5].name = '';
                        cn[5].id = '';
                    }
                }
                
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');
                    
                    if(cn[0].value) {
                        data.i_acc_wn = cn[0].value;
                    } else {
                        data.i_acc_wn = false;
                    }
                    
                    if(cn[1].value) {
                        data.i_acc_wn_code = cn[1].value;
                    } else {
                        data.i_acc_wn_code = false;
                    }
                    
                    if(cn[2].value) {
                        data.i_acc_wn_name = cn[2].value;
                    } else {
                        data.i_acc_wn_name = false;
                    }
                    
                    if(cn[3].value) {
                        data.i_acc_wn_type = cn[3].value;
                    } else {
                        data.i_acc_wn_type = 0;
                    }

                    if(cn[4].value) {
                        data.i_account_acc_wn = cn[4].value;
                    } else {
                        data.i_account_acc_wn = 0;
                    }
                    
                    if(cn[5].value) {
                        data.i_acc_wn_kind = cn[5].value;
                    } else {
                        data.i_acc_wn_kind = false;
                    }
                };

                cell.setData = function(data) {
                    // console.log(data);
                    
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log(cn);
                    
                    if(data.i_acc_wn) {
                        cn[0].value = data.i_acc_wn;
                    } else {
                        cn[0].value = '';
                    }
                        
                    if(data.i_acc_wn_code) {
                        cn[1].value = data.i_acc_wn_code; 
                    } else {
                        cn[1].value = '000';
                    }
                    
                    if(data.i_acc_wn_name) {
                        cn[2].value = data.i_acc_wn_name; 
                    } else {
                        cn[2].value = 'Brak'; 
                    }
                    
                    if(data.i_acc_wn_type) {
                        cn[3].value = data.i_acc_wn_type; 
                    } else {
                        cn[3].value = '0'; 
                    }
                    
                    if(data.i_account_acc_wn) {
                        cn[4].value = data.i_account_acc_wn;
                    } else {
                        cn[4].value = '0';
                    }
                    
                    if(data.i_acc_wn_kind) {
                        cn[5].value = data.i_acc_wn_kind;
                    } else {
                        cn[5].value = '0';
                    }
                };

                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'hidden');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.className = 'inputs';

                cell.appendChild(edit0);
                
                var edit1 = document.createElement('input');
                edit1.setAttribute('type', 'text');
                edit1.setAttribute('readOnly', 'readonly');
                edit1.setAttribute('tabIndex', 1);
                edit1.className = 'inputs';

                cell.appendChild(edit1);
                
                var edit2 = document.createElement('input');
                edit2.setAttribute('type', 'text');
                edit2.setAttribute('readOnly', 'readonly');
                edit2.setAttribute('tabIndex', 1);
                edit2.className = 'inputs';

                cell.appendChild(edit2);
                
                var edit3 = document.createElement('input');
                edit3.setAttribute('type', 'hidden');
                edit3.setAttribute('readOnly', 'readonly');
                edit3.setAttribute('tabIndex', 1);
                edit3.className = 'inputs';

                cell.appendChild(edit3);
                
                var edit4 = document.createElement('input');
                edit4.setAttribute('type', 'hidden');
                // edit4.setAttribute('readOnly', 'readonly');
                edit4.setAttribute('tabIndex', 1);
                edit4.className = 'inputs';

                cell.appendChild(edit4);
                
                var edit5 = document.createElement('input');
                edit5.setAttribute('type', 'hidden');
                // edit5.setAttribute('readOnly', 'readonly');
                edit5.setAttribute('tabIndex', 1);
                edit5.className = 'inputs';

                cell.appendChild(edit5);
                
                /* Bank account unused this time.
                var img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_IMG_SEARCH']);
                img.setAttribute('src', 'modules/EcmInvoiceOuts/images/search.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    try {
                        this.parentNode.select();
                    } catch(e) {
                        //
                    }

                    this.parentNode.ajax_search = false;

                    var ecmpopup = my_popup(
                            'EcmBankAccounts',
                            {
                                // 'id': 'id_p',
                                // 'short_name': 'short_name_p',
                                // 'name': 'name_p',
                                // 'code': 'code_p',
                                // 'analytic': 'analytic_p',
                                // 'synthetic': 'synthetic_p'
                                //
                                'id': 'i_acc_wn',
                                // 'short_name': 'acc_wn_short_name',
                                'name': 'i_acc_wn_name',
                                'code': 'i_acc_wn_code',
                                // 'analytic': 'acc_wn_analytic',
                                // 'synthetic': 'acc_wn_synthetic'
                                'type': 'i_acc_wn_type'
                            }
                        );

                    setTimeout(
                        function(){
                            ecmpopup.focus();
                        },
                        200
                    );
                }

                // Search iwnge button.
                cell.appendChild(img);
                */
            }

            // Ma.
            if (i == 3) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log('change', cn);
                    
                    if(select) {
                        cn[0].name = 'i_acc_ma';
                        cn[0].id = 'i_acc_ma';
                        
                        cn[1].name = 'i_acc_ma_code';
                        cn[1].id = 'i_acc_ma_code';
                        
                        cn[2].name = 'i_acc_ma_name';
                        cn[2].id = 'i_acc_ma_name';
                        
                        cn[3].name = 'i_acc_ma_type';
                        cn[3].id = 'i_acc_ma_type';
                        
                        cn[4].name = 'i_account_acc_ma';
                        cn[4].id = 'i_account_acc_ma';
                        
                        cn[5].name = 'i_acc_ma_kind';
                        cn[5].id = 'i_acc_ma_kind';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                        
                        cn[1].name = '';
                        cn[1].id = '';
                        
                        cn[2].name = '';
                        cn[2].id = '';
                        
                        cn[3].name = '';
                        cn[3].id = '';
                        
                        cn[4].name = '';
                        cn[4].id = '';
                        
                        cn[5].name = '';
                        cn[5].id = '';
                    }
                }
                
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');
                    
                    if(cn[0].value) {
                        data.i_acc_ma = cn[0].value;
                    } else {
                        data.i_acc_ma = false;
                    }
                    
                    if(cn[1].value) {
                        data.i_acc_ma_code = cn[1].value;
                    } else {
                        data.i_acc_ma_code = false;
                    }
                    
                    if(cn[2].value) {
                        data.i_acc_ma_name = cn[2].value;
                    } else {
                        data.i_acc_ma_name = false;
                    }
                    
                    if(cn[3].value) {
                        data.i_acc_ma_type = cn[3].value;
                    } else {
                        data.i_acc_ma_type = 0;
                    }
                    
                    if(cn[4].value) {
                        data.i_account_acc_ma = cn[4].value;
                    } else {
                        data.i_account_acc_ma = 0;
                    }
                    
                    if(cn[5].value) {
                        data.i_acc_ma_kind = cn[5].value;
                    } else {
                        data.i_acc_ma_kind = false;
                    }
                };

                cell.setData = function(data) {
                    // console.log(data);
                    
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log(cn);
                    
                    if(data.i_acc_ma) {
                        cn[0].value = data.i_acc_ma;
                    } else {
                        cn[0].value = '';
                    }
                        
                    if(data.i_acc_ma_code) {
                        cn[1].value = data.i_acc_ma_code; 
                    } else {
                        cn[1].value = '000';
                    }
                    
                    if(data.i_acc_ma_name) {
                        cn[2].value = data.i_acc_ma_name; 
                    } else {
                        cn[2].value = 'Brak'; 
                    }
                    
                    if(data.i_acc_ma_type) {
                        cn[3].value = data.i_acc_ma_type; 
                    } else {
                        cn[3].value = '0'; 
                    }
                    
                    if(data.i_account_acc_ma) {
                        cn[4].value = data.i_account_acc_ma;
                    } else {
                        cn[4].value = '0';
                    }
                    
                    if(data.i_acc_ma_kind) {
                        cn[5].value = data.i_acc_ma_kind;
                    } else {
                        cn[5].value = '0';
                    }
                };

                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'hidden');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.className = 'inputs';

                cell.appendChild(edit0);
                
                var edit1 = document.createElement('input');
                edit1.setAttribute('type', 'text');
                edit1.setAttribute('readOnly', 'readonly');
                edit1.setAttribute('tabIndex', 1);
                edit1.className = 'inputs';

                cell.appendChild(edit1);
                
                var edit2 = document.createElement('input');
                edit2.setAttribute('type', 'text');
                edit2.setAttribute('readOnly', 'readonly');
                edit2.setAttribute('tabIndex', 1);
                edit2.className = 'inputs';

                cell.appendChild(edit2);
                
                var edit3 = document.createElement('input');
                edit3.setAttribute('type', 'hidden');
                edit3.setAttribute('readOnly', 'readonly');
                edit3.setAttribute('tabIndex', 1);
                edit3.className = 'inputs';

                cell.appendChild(edit3);
                
                var edit4 = document.createElement('input');
                edit4.setAttribute('type', 'hidden');
                // edit4.setAttribute('readOnly', 'readonly');
                edit4.setAttribute('tabIndex', 1);
                edit4.className = 'inputs';

                cell.appendChild(edit4);
                
                var edit5 = document.createElement('input');
                edit5.setAttribute('type', 'hidden');
                // edit5.setAttribute('readOnly', 'readonly');
                edit5.setAttribute('tabIndex', 1);
                edit5.className = 'inputs';

                cell.appendChild(edit5);
                
                /* Bank account uniused this time.
                var img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_IMG_SEARCH']);
                img.setAttribute('src', 'modules/EcmInvoiceOuts/images/search.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    try {
                        this.parentNode.select();
                    } catch(e) {
                        //
                    }

                    this.parentNode.ajax_search = false;

                    var ecmpopup = my_popup(
                            'EcmBankAccounts',
                            {
                                // 'id': 'id_p',
                                // 'short_name': 'short_name_p',
                                // 'name': 'name_p',
                                // 'code': 'code_p',
                                // 'analytic': 'analytic_p',
                                // 'synthetic': 'synthetic_p'
                                //
                                'id': 'i_acc_ma',
                                // 'short_name': 'acc_ma_short_name',
                                'name': 'i_acc_ma_name',
                                'code': 'i_acc_ma_code',
                                // 'analytic': 'acc_ma_analytic',
                                // 'synthetic': 'acc_ma_synthetic'
                                'type': 'i_acc_ma_type'
                            }
                        );

                    setTimeout(
                        function(){
                            ecmpopup.focus();
                        },
                        200
                    );
                }

                // Search image button.
                cell.appendChild(img);
                */
            }

            // Amount.
            if (i == 4) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log('change', cn);
                    
                    if(select) {
                        cn[0].name = 'i_amount';
                        cn[0].id = 'i_amount';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                    }
                }
                           
                cell.getData = function(data,noAlert) {
                  var tmp = UserFormatNumberToNumber(this.firstChild.value);
                  
                  if(tmp < 0) {
                    data.i_amount = 0;           
                  } else {
                    data.i_amount = tmp;
                  }
                  
                }
                
                cell.setData = function(data) {
                  if(data.i_amount) 
                  this.firstChild.value = NumberToUserFormatNumber(data.i_amount); 
                  else 
                  this.firstChild.value = NumberToUserFormatNumber(0);
                  
                }
                        
                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'text');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.style.textAlign = 'right';
                edit0.className = 'inputs';

                cell.appendChild(edit0);
            }
           
            // Payment condition
            if (i == 5) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log('change', cn);
                    
                    if(select) {
                        cn[0].name = 'i_sp_zap';
                        cn[0].id = 'i_sp_zap';
                        
                        cn[1].name = 'i_il_dni';
                        cn[1].id = 'i_il_dni';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                        
                        cn[1].name = '';
                        cn[1].id = '';
                    }
                }
                
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');

                    // console.log('Kinds ', data.i_acc_ma_kind, data.i_acc_wn_kind);
                    // console.log(data.i_acc_ma_kind != 'Rozrachunkowe' && data.i_acc_wn_kind != 'Rozrachunkowe');
                    
                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    )
                    {
                        data.i_sp_zap  = false;
                    } else {    
                        if(cn[0].value) {
                            data.i_sp_zap = cn[0].value;
                        } else {                     
                            var sp_zap = document.getElementById('sp_zap');
                            var sp_zap_name = document.getElementById('sp_zap_name');
                            
                            // console.log(sp_zap_name);
                            
                            if(sp_zap.value != '') {
                                data.i_sp_zap = sp_zap_name.value;
                            } else {
                                data.i_sp_zap = false;
                            }
                        }
                    }
                    
                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    )
                    {
                        data.i_il_dni  = false;
                    } else {   
                        if(cn[1].value) {
                            data.i_il_dni = parseInt(cn[1].value);
                        } else {   
                            var sp_zap = document.getElementById('sp_zap');
                            var il_dni = document.getElementById('il_dni');
                            
                            if(sp_zap.value != '') {
                                data.i_il_dni = il_dni.value;
                            } else {
                                data.i_il_dni = false;
                            }
                        }
                    }
                };

                cell.setData = function(data) {
                    var cn = this.getElementsByTagName('input');

                    // console.log('Kinds ', data.i_acc_ma_kind, data.i_acc_wn_kind);
                    // console.log(data.i_acc_ma_kind != 'Rozrachunkowe' && data.i_acc_wn_kind != 'Rozrachunkowe');
                    
                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    )
                    {
                        cn[0].value  = '';
                    } else {  
                        if(data.i_sp_zap) {
                            cn[0].value = data.i_sp_zap;
                        } else {
                            var sp_zap = document.getElementById('sp_zap');
                            var sp_zap_name = document.getElementById('sp_zap_name');
                            
                            if(sp_zap.value != '') {
                                cn[0].value = sp_zap_name.value;
                            } else {
                                cn[0].value = '';
                            }
                        }
                    }

                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    ){
                        cn[1].value  = '';
                    } else {  
                        if(data.i_il_dni) {
                            cn[1].value = data.i_il_dni;
                        } else {
                            var sp_zap = document.getElementById('sp_zap');
                            var il_dni = document.getElementById('il_dni');
                            
                            if(sp_zap.value != '') {
                                cn[1].value = il_dni.value;
                            } else {
                                cn[1].value = '';
                            }
                        }
                        // cn[1].onchange();
                    }
                    
                };

                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'text');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.className = 'inputs';

                cell.appendChild(edit0);
                
                var edit1 = document.createElement('input');
                edit1.setAttribute('type', 'text');
                edit1.setAttribute('readOnly', 'readonly');
                edit1.setAttribute('tabIndex', 1);
                edit1.className = 'inputs';

                cell.appendChild(edit1);
                
                /* Payment conditions unused this time.
                var img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_IMG_SEARCH']);
                img.setAttribute('src', 'modules/EcmInvoiceOuts/images/search.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    try {
                        this.parentNode.select();
                    } catch(e) {
                        //
                    }

                    this.parentNode.ajax_search = false;

                    var ecmpopup = my_popup(
                            'EcmPaymentConditions',
                            {
                                'name':'i_sp_zap',
                                'days':'i_il_dni'
                            }
                        );

                    setTimeout(
                        function(){
                            ecmpopup.focus();
                        },
                        200
                    );
                }

                // Search image button.
                cell.appendChild(img);
                */
            }
           
            // Currency
            if (i == 6) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    
                    // console.log('change', cn);
                    
                    if(select) {
                        cn[0].name = 'i_symb_wa';
                        cn[0].id = 'i_symb_wa';
                        
                        cn[1].name = 'i_kurs_wal';
                        cn[1].id = 'i_kurs_wal';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                        
                        cn[1].name = '';
                        cn[1].id = '';
                    }
                }
                
                cell.getData = function(data) {

                    // console.log('get');
                    // console.log(data);

                    var cn = this.getElementsByTagName('input');

                    // console.log(cn[0].value);

                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    ) 
                    {
                        data.i_symb_wa = '';
                    } else {                    
                        if(cn[0].value) {
                            data.i_symb_wa = cn[0].value;
                        } else {
                            data.i_symb_wa = 'PLN';
                        }
                    }
                    // console.log('x: ', cn[1].value);

                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    ) 
                    {
                        data.i_kurs_wal = '';
                    } else {
                        if(cn[1].value) {
                            data.i_kurs_wal = UserFormatNumberToNumber(cn[1].value);
                        } else {
                            data.i_kurs_wal = 1.0;
                        }
                    }
                    
                    };

                cell.setData = function(data) {

                    // console.log('set');
                    // console.log(data);

                    var cn = this.getElementsByTagName('input');

                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    )
                    { 
                        cn[0].value = '';
                    } else {
                        if(data.i_symb_wa) {
                            cn[0].value = data.i_symb_wa;
                        } else {
                            cn[0].value = 'PLN';
                        }
                    }
                    
                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    )
                    { 
                        cn[1].value = '';
                    } else {
                        if(data.i_kurs_wal) {
                            cn[1].value = NumberToUserFormatNumber(data.i_kurs_wal);
                        } else {
                            cn[1].value = NumberToUserFormatNumber(1.0);
                        }
                    }
                };
                
                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'text');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.className = 'inputs';

                cell.appendChild(edit0);
                
                var edit1 = document.createElement('input');
                edit1.setAttribute('type', 'text');
                edit1.setAttribute('readOnly', 'readonly');
                edit1.setAttribute('tabIndex', 1);
                edit1.className = 'inputs';

                cell.appendChild(edit1);
               
                /* Currency options unsused this time.
                //currency
                var div=document.createElement('div');
                div.setAttribute('style','display:none; float:right; text-align:right; border: 1px #cccccc solid; padding:3px;');
                
                for(var key in CURRENCY){
                    var tmp = CURRENCY[key];
                
                    if(tmp){
                        var option = document.createElement('a');

                        option.setAttribute('name', tmp.conversion_rate);
                        option.setAttribute('style', 'cursor: pointer; clear: both;');
                        option.innerHTML = tmp.name;
                        
                        option.onclick = function() {
                            var cn = cell.getElementsByTagName('input');
                    
                            // console.log(this);
                    
                            cn[0].value= this.innerHTML;
                            cn[1].value= NumberToUserFormatNumber(this.name);
                            
                            div.style.display = 'none';
                        }
                        
                        div.appendChild(option);
                        div.appendChild(document.createElement('br'));
                    }
                }

                var img=document.createElement('img');
                img.setAttribute('src','modules/EcmQuotes/images/edit_position.gif');
                img.setAttribute('style','cursor:pointer;display:block;');
                
                img.onclick=function(){
                    if(div.style.display=='none') {
                        div.style.display='block';
                    } else { 
                        div.style.display='none';
                    }
                }

                cell.appendChild(document.createElement('br'));
                
                var inp0 = document.createElement('input');
                inp0.setAttribute('type','hidden');
                
                cell.appendChild(inp0); 
                cell.appendChild(div); 
                cell.appendChild(img); 
                */
                
                /*
                var img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_IMG_SEARCH']);
                img.setAttribute('src', 'modules/EcmInvoiceOuts/images/search.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    try {
                        this.parentNode.select();
                    } catch(e) {
                        //
                    }

                    this.parentNode.ajax_search = false;

                    var ecmpopup = my_popup(
                            'Currencies',
                            {
                                'name': 'i_symb_wa',
                                'conversion_rate': 'i_kurs_wal'
                            }
                        );

                    setTimeout(
                        function(){
                            ecmpopup.focus();
                        },
                        200
                    );
                }

                // Search image button.
                cell.appendChild(img);
                */
            }
           
            // Date dok.
            if (i == 7) {
                cell.change = function(select) {
                    var cn = this.getElementsByTagName('input');
                    // var im = this.getElementsByTagName('img');
                    
                    // console.log('change', cn);
                    // console.log('change', im);
                    
                    if(select) {
                        cn[0].name = 'i_dat_zap';
                        cn[0].id = 'i_dat_zap';
                        
                        // im[0].id = 'i_dat_zap_trigger';
                    } else {
                        cn[0].name = '';
                        cn[0].id = '';
                        
                        // im[0].id = '';
                    }
                    
                    
                }
                
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');

                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    )
                    { 
                        data.i_dat_zap  = false;
                    } else {
                        if(cn[0].value.match(/\d{2}\.\d{2}\.\d{4}/)) {
                            var tmp = cn[0].value;
                            var date = tmp.substr(6, 4) + '-' + tmp.substr(3, 2) + '-' + tmp.substr(0, 2);

                            data.i_dat_zap = date;
                        } else {
                            var date = new Date();

                            var d = date.getDate().toString();
                            var m = (date.getMonth() + 1).toString();
                            var y = date.getFullYear().toString();

                            data.i_dat_zap = y + '-' + (m.length <= 1 ? ('0' + m) : m) + '-' + (d.length <= 1 ? ('0' + d) : d);
                        }
                        // console.log('get: ', cn[0].value, data.i_dat_zap);
                    }
                };

                cell.setData = function(data) {
                    var cn = this.getElementsByTagName('input');

                    // console.log(data.i_dat_zap.match(/\d{4}-\d{2}-\d{2}/));

                    if(
                        !((
                            (data.i_acc_ma_kind == '4') ||
                            (data.i_acc_wn_kind == '4')
                        )
                            ||
                        (
                            (data.i_acc_ma_kind == 'Rozrachunkowe') ||
                            (data.i_acc_wn_kind == 'Rozrachunkowe')
                        ))
                    )
                    { 
                        cn[0].value  = '';
                    } else {
                        if(data.i_dat_zap.match(/\d{4}-\d{2}-\d{2}/)) {
                            var tmp = data.i_dat_zap;
                            var date = tmp.substr(8, 2) + '.' + tmp.substr(5, 2) + '.' + tmp.substr(0, 4);

                            cn[0].value = date;
                        } else {
                            var date = new Date();

                            var d = date.getDate().toString();
                            var m = (date.getMonth() + 1).toString();
                            var y = date.getFullYear().toString();

                            cn[0].value = (d.length <= 1 ? ('0' + d) : d) + '.' + (m.length <= 1 ? ('0' + m) : m) + '.' + y;
                        }
                    }
                    // console.log('set: ', data.i_dat_zap, cn[0].value);
                };

                var edit0 = document.createElement('input');
                edit0.setAttribute('type', 'text');
                edit0.setAttribute('readOnly', 'readonly');
                edit0.setAttribute('tabIndex', 1);
                edit0.className = 'inputs';

                cell.appendChild(edit0);
                   
                // var img = document.createElement('img');
                // img.setAttribute('alt', 'Wprowadź datę');
                // img.setAttribute('src', 'themes/Sugar5/images/jscalendar.gif');
                // img.style.cursor = 'pointer';

                // Search image button.
                // cell.appendChild(img);
            }
            
            /* Options unused this time.
            // Options.
            if (i == 8) {
                var img;

                //insert
                img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_INSERT_NEW_ROW']);
                img.setAttribute('src', 'modules/EcmFkPackages/images/insertrow.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    this.parentNode.myTable.addRow(this.parentNode.parentNode.index + 1);
                };

                //delete
                cell.appendChild(img);
                cell.appendChild(document.createTextNode(" "));
                
                img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_DELETE_ROW']);
                img.setAttribute('src', 'modules/EcmFkPackages/images/deleterow.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    removeReservation(cell);
                    this.parentNode.parentNode.deleteRow();
                };

                cell.appendChild(img);
                cell.appendChild(document.createElement('br'));

                //move up
                img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_MOVE_ROW_UP']);
                img.setAttribute('src', 'modules/EcmFkPackages/images/moverowup.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    this.parentNode.parentNode.moveUp();
                };

                cell.appendChild(img);
                cell.appendChild(document.createTextNode(" "));

                //move down
                img = document.createElement('img');
                img.setAttribute('alt', MOD['LBL_MOVE_ROW_DOWN']);
                img.setAttribute('src', 'modules/EcmFkPackages/images/moverowdown.gif');
                img.style.cursor = 'pointer';

                img.onclick = function() {
                    this.parentNode.parentNode.moveDown();
                };

                cell.appendChild(img);
            }
            */
        };

        N.onSetCellData = function(row, cell, data) {
            if (cell.innerHTML == '') {
                cell.innerHTML = '&nbsp;';
            }
        };

        var pl = document.getElementById('items_list').value;
                console.log(pl.length);

        if (pl && pl != '') {
            try {
                pl = eval(pl);
                console.log(pl);
                
                for (x in pl) {
                    var pl_row = pl[x];

                    console.log(pl_row);
                    // if (!pl[x].code || pl[x].code == '')
                    // {
                        //
                    // } else {
                        N.addRow().setData(pl_row);
                    // }
                }
            } catch (err) {
                pl = null;
            }
        }

        if (N.rowCount() == 0) {
            N.addRow();
        }

        calculateTotalItems = function() {
            var a_wn = 0;
            var a_ma = 0;
        
            for (var i = 0; i < N.rowCount(); i++) {
                var data = N.row(i).getData();

                // console.log('data ', data);
                
                // console.log('type wn', data.i_acc_wn_type, 'amount ', data.i_amount);
                
                if(data.i_acc_wn_type == '1' || data.i_acc_wn_type == 'Bilansowe') {
                    a_wn += data.i_amount;
                }
                
                // console.log('type ma', data.i_acc_ma_type, 'amount ', data.i_amount);
                
                if(data.i_acc_ma_type == '1' || data.i_acc_ma_type == 'Bilansowe') {
                    a_ma += data.i_amount;
                }
            }
            
            // console.log('total wn ', a_wn, 'total ma ', a_ma);
            
            var amount_wn = document.getElementById('amount_wn');
            var amount_ma = document.getElementById('amount_ma');
            
            amount_wn.value = NumberToUserFormatNumber(a_wn);
            amount_ma.value = NumberToUserFormatNumber(a_ma);
            
            return true;

            var vats = new Object();
            var subtotal = 0;
            var total = 0;

            for (var i = 0; i < N.rowCount(); i++) {
                var data = N.row(i).getData();

                if (OPT.to_is_vat_free == 0) {
                    if (data.vat_id && data.name != '') {
                        if (typeof(vats[data.vat_id]) != "object") {
                            vats[data.vat_id] = new Object();
                            vats[data.vat_id]['vat'] = 0;
                        }

                        vats[data.vat_id]['vat'] += data.total;
                    }
                }

                subtotal += data.total;
            }

            total = subtotal;

            var rt = document.getElementById('position_result_register');

            for (var i = 1; i < rt.rows.length - 1; i++) {
                if (!vats[rt.rows.item(i).id]) {
                    rt.deleteRow(i);
                    --i;
                } else {
                    vats[rt.rows.item(i).id]['node'] = rt.rows.item(i);
                }
            }

            for (var x in vats) {
                if (VAT[x]) {
                    vats[x]['vat'] = vats[x]['vat'] * (parseFloat(VAT[x].value) / 100);
                    total += vats[x]['vat'];

                    var txL = MOD['LBL_VAT'] + ' (' + VAT[x].name + ')';
                    var txF = NumberToUserFormatNumber(vats[x]['vat']);
                }

                if (vats[x]['node']) {
                    vats[x]['node'].id = x;
                    vats[x]['node'].cells.item(0).innerHTML = txL;
                    vats[x]['node'].cells.item(1).innerHTML = "<input type='text' readonly='readonly' style='border:0px;font-weight:900;width:100%;text-align:right;' value='" + txF + "'>";
                } else {
                    rt.insertRow(1);

                    rt.rows.item(1).id = x;
                    rt.rows.item(1).insertCell(0);
                    rt.rows.item(1).cells.item(0).className = 'positionsLabel';
                    rt.rows.item(1).cells.item(0).innerHTML = txL;
                    rt.rows.item(1).insertCell(1);
                    rt.rows.item(1).cells.item(1).className = 'positionsField';
                    rt.rows.item(1).cells.item(1).innerHTML = "<input type='text' readonly='readonly' style='border:0px;font-weight:900;width:100%;text-align:right;' value='" + txF + "'>";
                }
            }

            var total2 = total;

            total2 = ((OPT['type'] == "correct") ? '-' : '') + NumberToUserFormatNumber(total2).toString();
            total = ((OPT['type'] == "correct") ? '-' : '') + NumberToUserFormatNumber(total).toString();

            document.getElementById('articles_subtotal').value = NumberToUserFormatNumber(subtotal);

            if (document.getElementById('articles_total'))
                document.getElementById('articles_total').value = total2;
        };

        ItemListSave = function(json) {
            var data = '';

            for (var i = 0; i < N.rowCount(); i++) {
                data = data + '&items_' + i.toString() + '=' + JSON.stringifyNoSecurity(N.row(i).getData());
            }

            return data;
        };

        ItemsList = function(json) {
            var data = '';

            for (var i = 0; i < N.rowCount(); i++) {
                data = data + '||||' + JSON.stringifyNoSecurity(N.row(i).getData());
            }

            return data;
        };

        if (typeof sqs_objects != 'undefined') {
            sqs_objects["code_p"] = {
                "method": "get_product_array",
                "modules": ["EcmProducts"],
                "field_list": ["index_dbf", "id", "name", "currency_id"],
                "populate_list": ["code_p", "id_p", "name_p", "currency_id_p"],
                "conditions": [{
                        "name": "index_dbf",
                        "op": "like_custom",
                        "end": "%",
                        "value": ""
                    }],
                "limit": "30",
                "order": "index_dbf",
                "no_match_text": "No Match"
            };

            sqs_objects["name_p"] = {
                "method": "get_product_array",
                "modules": ["EcmProducts"],
                "field_list": ["date_entered", "name", "id", "index_dbf", "currency_id"],
                "populate_list": ["name_p", "name_p", "id_p", "code_p", "currency_id_p"],
                "conditions": [{
                        "name": "name",
                        "op": "like_custom",
                        "end": "%",
                        "value": ""
                    }],
                "limit": "30",
                "order": "name",
                "no_match_text": "No Match"
            };
        }

        function generateNumber() {
            var url = 'to_pdf=1&generate=1&module=EcmFkPackages&action=generateNumber&type=normal&template_id=' + document.getElementById('template_id').value;//+'&record='+document.forms.EditView.record.value;

            //if(document.getElementById('template_id').value == '') { alert('There are no DocumentTemplates in data base!'); return;}
            doRequest(
                'index.php',
                url,
                function(result) {
                    var arr = eval(result)[0];

                    document.getElementById('number').value = arr.number;
                    document.getElementById('document_no').value = arr.document_no;
                },
                ''
                );
        };

        calculateTotalItems();

        if (OPT['new_number']) {
            generateNumber();

            document.getElementById('ITEMS_menu').style.display = 'none';
            document.getElementById('SERVICES_menu').style.display = 'none';

            //save PW
            document.getElementById('stock_doc_inside_in').value = '1';
        }

        function setToAddrEmail(str) {
            if (str && str != '')
                str = eval(str);
            else
                str = '';

            if (typeof(str) == "object")
                str = str[0];
            else
                str = '';

            if (document.getElementById('parent_type').value == 'Accounts') {
                //= document.getElementById('to_addrs_field'); if(tmp) tmp.value = (str=='')?'':(((str.name)?str.name:'')+' <'+((str.email1)?str.email1:'')+'>; ');
                tmp = document.getElementById('parent_address_street');

                if (tmp) {
                    tmp.value = (str.billing_address_street) ? str.billing_address_street : '';
                }

                tmp = document.getElementById('parent_address_city');

                if (tmp) {
                    tmp.value = (str.billing_address_city) ? str.billing_address_city : '';
                }

                tmp = document.getElementById('parent_address_postalcode');

                if (tmp) {
                    tmp.value = (str.billing_address_postalcode) ? str.billing_address_postalcode : '';
                }

                tmp = document.getElementById('parent_address_country');

                if (tmp) {
                    tmp.value = (str.billing_address_country) ? str.billing_address_country : '';
                }

//                tmp = document.getElementById('to_nip');
//
//                if (tmp) {
//                    tmp.value = (str.sic_code) ? str.sic_code : '';
//                }

                tmp = document.getElementById('to_vatid');

                if (tmp) {
                    tmp.value = (str.nip) ? str.nip : '';
                }

                tmp = document.getElementById('to_is_vat_free');

                if (tmp) {
                    tmp.checked = (str.is_vat_free == 1) ? true : false;
                }

                document.getElementById('parent_name_copy').value = document.getElementById('parent_name').value;

                tmp = document.getElementById('ecmlanguage');

                if (tmp && str.ecmlanguage) {
                    if (tmp.value != str.ecmlanguage) {
                        tmp.value = str.ecmlanguage;
                        setTexts();
                    }
                }
            }
        }

        function ChangeAccessFunction(obj, type) {
            var objs = obj.getElementsByTagName('input');

            for (var i = 0; i < objs.length; i++)
                if (objs[i].id != 'parent_name' && objs[i].id != 'parent_id' && objs[i].name != 'btn_parent_name' && objs[i].name != 'btn_clr_parent_name' && objs[i].name != 'btn_create_parent_name') {
                    objs[i].disabled = type;
                }

            var objs = obj.getElementsByTagName('textarea');

            for (var i = 0; i < objs.length; i++) {
                objs[i].disabled = type;
            }

            var objs = obj.getElementsByTagName('select');

            for (var i = 0; i < objs.length; i++) {
                if (objs[i].id != 'parent_type') {
                    objs[i].disabled = type;
                }
            }

            if (type == 'disabled') {
                TabsMainBlock = true;
            } else {
                TabsMainBlock = false;
            }

        }

        // console.log('N done');
    }
);
/* /Decree */