function doRequest(where, post, doFunction, error) {
    this.Display = function(result) {
        doFunction(result.responseText);
    };

    this.Fail = function(result) {
        if (error)
            alert(error);
    };

    YAHOO.util.Connect.asyncRequest('POST', where, {success: this.Display, failure: this.Fail}, post);
}

function changeValidateRequired(formname, name, required) {
    for (var i = 0; i < validate[formname].length; i++)
        if (validate[formname][i][0] == name) {
            validate[formname][i][2] = required;
            break;
        }
}

function set_focus() {
    document.getElementById('name').focus();
}

function my_popup(module, field_array, call_back_function, form_name) {
    if (!call_back_function) {
        call_back_function = "set_return";
    }

    if (!form_name) {
        form_name = "EditView";
    }

    return open_popup(module, 600, 400, "", true, false, {"call_back_function": call_back_function, "form_name": form_name, "field_to_name_array": field_array});
}

function addEvent(object, eventName, do_function) {
    if (typeof(object) == "string") {
        object = document.getElementById(object);
    }

    if (!object) {
        alert('No object in function addEvent!');
        return;
    }

    if (object.addEventListener) {
        object.addEventListener(eventName, do_function, false);
    } else {
        object.attachEvent('on' + eventName, do_function);
    }
}

function ItemListClear() {
    while (N.rowCount() > 0) {
        N.row(0).deleteRow();
    }
}

addEvent(
    window,
    'load',
    function() {
        //initialize table
        N = new MyTable('itemsTable');

        N.onRefreshRowIndex = function(row) {
            var data = new Object();

            data['index'] = (row.index + 1).toString();
            row.cells.item(0).setData(data);
        };

        N.onCreateRow = function(row) {
            row.newPos = false;

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

                var img = this.cells.item(1).getElementsByTagName('img');

                if (!this.newPos) {
                    img[0].src = "modules/EcmReceipts/images/edit.gif";
                }
                else {
                    img[0].src = "modules/EcmReceipts/images/editset.gif";
                }


                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() {
                var data = new Object();
                this.cells.item(3).getData(data, true);
                this.cells.item(4).getData(data, true);
                this.cells.item(5).getData(data, true);
                this.cells.item(6).getData(data, true);
                this.cells.item(7).getData(data, true);
                this.cells.item(8).getData(data, true);
                this.cells.item(9).getData(data, true);

//                this.cells.item(10).getData(data, true);
//                this.cells.item(11).getData(data, true);
//                this.cells.item(12).getData(data, true);

                //calculate selling_price
                if (data.price) {
                    if (data.discount) {
                        data.selling_price = (data.price - (data.price * data.discount / 100)).toFixed(2);
                    } else {
                        data.selling_price = (data.price).toFixed(2);
                    }
                }
                else {
                    data.selling_price = 0;
                }

                //calculate total
                if (data.price && data.quantity) {
                    data.total = (data.price * data.quantity).toFixed(2);
                }
                else {
                    data.total = 0;
                }

                //alert(data.total+'  '+data.price+'   '+data.quantity);

                this.cells.item(9).setData(data);
                this.cells.item(6).setData(data);

                calculateTotal();
            };

        };

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

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

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

            cell.style.height = 50;
            cell.noSelect = true;

            if (i == 0) {
                cell.setData = function(data) {
                    if (data.index) {
                        cell.firstChild.value = data.index;
                    }
                };

                cell.getData = function(data) {
                    data.index = cell.firstChild.value;
                };

                cell.select = function() {
                    this.selectNext();
                };

                var edit = document.createElement('input');

                edit.setAttribute('type', 'text');
                edit.setAttribute('readOnly', 'readonly');
                edit.setAttribute('tabIndex', 1);
                edit.className = 'inputs';

                cell.appendChild(edit);
            }

            if (i == 1) {
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');

                    data.code = cn[0].value;
                    data.id = cn[1].value;
                    data.unit_name = cn[2].value;
                    data.vat_id = cn[3].value;
                    data.category_id = cn[4].value;
                };

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

                    if (data.code) {
                        cn[0].value = data.code;
                    }

                    if (data.id) {
                        cn[1].value = data.id;
                    }

                    if (data.unit_name) {
                        cn[2].value = data.unit_name;
                    }

                    if (data.vat_id) {
                        cn[3].value = data.vat_id;
                    }

                    if (data.category_id) {
                        cn[4].value = data.category_id;
                    }
                };

                var edit = '<input type="text" readonly="readonly" tabindex="1" class="inputs" autocomplete="off" >';

                cell.innerHTML = edit;
                cell.align = 'right';

                var id = document.createElement('input');

                id.setAttribute('type', 'hidden');
                cell.appendChild(id);

                var unit_id = document.createElement('input');

                unit_id.setAttribute('type', 'hidden');
                //unit_id.setAttribute('value',OPT['default_unit']);
                unit_id.setAttribute('value', 'TMP');
                cell.appendChild(unit_id);

                var vat_id = document.createElement('input');

                vat_id.setAttribute('type', 'hidden');
                //vat_id.setAttribute('value',OPT['default_vat']);
                vat_id.setAttribute('value', '23');
                cell.appendChild(vat_id);

                var category_id = document.createElement('input');

                category_id.setAttribute('type', 'hidden');
                category_id.setAttribute('value', '');
                cell.appendChild(category_id);
            }

            if (i == 2) {
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('textarea');

                    data.name = cn[0].value;
                };

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

                    if (data.name) {
                        cn[0].value = data.name;
                    }
                };

                var textarea = '<textarea tabindex="1" readonly="readonly" style="height:100%" class="inputs"></textarea>';

                cell.innerHTML = textarea;
            }

            if (i == 3) {
                cell.getData = function(data, noAlert) {
                    var tmp = UserFormatNumberToNumber(this.firstChild.value);

                    if (tmp == -1) {
                        ERROR = true;

//                        if (!noAlert) {
//                            alert(MOD['LBL_FORMAT_NUMBER_ERROR'] + ' (' + this.firstChild.value + ')');
//                        }

                        data.quantity = 0;

                        this.firstChild.style.color = 'red';
                    } else {
                        data.quantity = tmp;

                        this.firstChild.style.color = 'black';
                    }

                };

                cell.setData = function(data) {
                    if (data.quantity) {
                        this.firstChild.value = NumberToUserFormatNumber(data.quantity);
                    }
                    else {
                        this.firstChild.value = NumberToUserFormatNumber(0);
                    }
                };

                var edit = '<input type="text" readonly="readonly" tabindex="1" style="text-align:right;" autocomplete="off" class="inputs" value="' + NumberToUserFormatNumber(1) + '">';

                cell.innerHTML = edit;
            }

            if (i == 4) {
                cell.getData = function(data, noAlert) {
                    data.unit_id = this.firstChild.value;
                };

                cell.setData = function(data) {
                    this.firstChild.value = data.unit_id;
                };

                var edit = '<input type="text" readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="">';

                cell.innerHTML = edit;
            }

            if (i == 5) {
                cell.getData = function(data, noAlert) {
                    //
                };

                cell.setData = function(data) {
                    var value;

                    if ((data.price) && (data.discount)) {
                        value = (100 * data.price) / (100 - data.discount);
                    } else {
                        if ((data.price) && !(data.discount)) {
                            value = data.price;
                        }
                        else {
                            value = 0;
                        }
                    }

                    this.firstChild.value = NumberToUserFormatNumber(value);
                };

                var edit = '<input type="text" readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="0">';

                cell.innerHTML = edit;
            }

            if (i == 6) {
                cell.getData = function(data, noAlert) {
                    var tmp = UserFormatNumberToNumber(this.firstChild.value, '%');

                    if (tmp == -1) {
                        ERROR = true;

                        if (!noAlert) {
                            alert(MOD['LBL_FORMAT_NUMBER_ERROR'] + ' (' + this.firstChild.value + ')');
                        }

                        data.discount = 0;

                        this.firstChild.style.color = 'red';

                    } else {
                        data.discount = tmp;

                        this.firstChild.style.color = 'black';
                    }
                };

                cell.setData = function(data) {
                    if (data.discount) {
                        this.firstChild.value = NumberToUserFormatNumber(data.discount, '%');
                    }
                    else {
                        this.firstChild.value = NumberToUserFormatNumber(0, '%');
                    }
                };

                cell.selectNext = function() {
                    var row = this.parentNode.selectNext();

                    row.select();
                    row.cells.item(0).select();
                };

                var edit = '<input type="text" readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="' + NumberToUserFormatNumber(0, '%') + '">';

                cell.innerHTML = edit;

            }

            if (i == 7) {
                cell.getData = function(data, noAlert) {
                    var tmp = UserFormatNumberToNumber(this.firstChild.value);

                    if (tmp == -1) {
                        ERROR = true;

                        if (!noAlert) {
                            alert(MOD['LBL_FORMAT_NUMBER_ERROR'] + ' (' + this.firstChild.value + ')');
                        }

                        data.price = 0;

                        this.firstChild.style.color = 'red';
                    } else {
                        data.price = tmp;

                        this.firstChild.style.color = 'black';
                    }
                };

                cell.setData = function(data) {
                    if (data.price) {
                        this.firstChild.value = NumberToUserFormatNumber(data.price);
                    }
                    else {
                        this.firstChild.value = NumberToUserFormatNumber(0);
                    }
                };

                var edit = '<input type="text" readonly="readonly" tabindex="1" class="inputs" style="text-align:right;" autocomplete="off" value="' + NumberToUserFormatNumber(0) + '">';

                cell.innerHTML = edit;
            }

            if (i == 8) {
                cell.getData = function(data, noAlert) {
                    var cn = this.getElementsByTagName('input');
                    data.vat_value = cn[0].value;
                    data.vat_id = cn[1].value;
                    if (VAT[cn[1].value])
                        data.vat_name = VAT[cn[1].value].name;
                };

                cell.setData = function(data) {
                    if (data.vat_value) {
                        this.getElementsByTagName('input')[0].value = data.vat_value;
                    }

                    if (data.vat_id) {
                        this.getElementsByTagName('input')[1].value = data.vat_id;
                    }

                    if (data.vat_name) {
                        this.getElementsByTagName('input')[2].value = data.vat_name;
                    }
                };

                cell.onDeselect = function() {
                    ERROR = false;

                    var data = new Object();
                    this.getData(data);

                    if (!ERROR) {
                        data.vat_id = data.vat_id;

                        this.setData(data);
                    }
                };

                var inp = document.createElement('input');

                inp.setAttribute('type', 'hidden');
                cell.appendChild(inp);

                var inp = document.createElement('input');

                inp.setAttribute('type', 'hidden');
                cell.appendChild(inp);

                var inp;

                inp = document.createElement('input');
                inp.setAttribute('type', 'text');
                inp.className = 'inputs';
                inp.style.textAlign = "right";
                inp.cell = cell;

                cell.appendChild(inp);
            }

            if (i == 9) {
                cell.getData = function(data) {
                    var cn = this.getElementsByTagName('input');

                    data.total = UserFormatNumberToNumber(cn[0].value);
                };

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

                    if (data.total) {
                        cn[0].value = NumberToUserFormatNumber(data.total);
                    }
                    else {
                        cn[0].value = NumberToUserFormatNumber(0);
                    }
                };

                var edit = document.createElement('input');

                edit.setAttribute('type', 'text');
                edit.setAttribute('value', NumberToUserFormatNumber(0));
                edit.setAttribute('readOnly', 'readonly');
                edit.className = 'inputs';
                edit.style.textAlign = "right";

                cell.appendChild(edit);
            }
        };

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

        var pl = document.getElementById('position_list').value;

        if (pl && pl != '') {
            try {
                pl = eval(pl);

                for (x in pl) {
                    if (typeof(pl[x].code) != "undefined") {
                        var pl_row = pl[x];
                        N.addRow().setData(pl_row);
                    }
                }
            } catch (err) {
                pl = null;
            }
        }

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

        calculateTotal = function() {
            var vats = new Object();

            var subtotal = 0;
            var total = 0;
//            var cbm_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;
//                cbm_total += data.cbm;
            }

            total = subtotal;
            var rt = document.getElementById('result_table');

            for (var i = 1; i < rt.rows.length - 4; 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('subtotal').value = NumberToUserFormatNumber(subtotal);

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

//             document.getElementById('discount_2').value = discount2;
            document.getElementById('total').value = total;
//            document.getElementById('cbm_total').value = cbm_total;
        };

        calculateTotal();

        function HideLoadingView() {
            var slv = document.getElementById('ShowLoadingView');

            if (slv) {
                slv.style.display = 'none';
            }
        }

        setPREVIEW = function() {
//            EcmPreviewPDF('index.php?module=EcmQuotes&action=previewPDF&to_pdf=1&method=I&record='+document.forms.DetailView.record.value,{zoom:75});

            var type = document.getElementById('preview_type').value;

            switch (type)
            {
                default:
                    type = '';
                    break;
                case 'exp':
                    type = 'exp';
                    break;
            }

            console.log(type);

            if (SHOW_PDF_IN_DIV == 1) {
                HideLoadingView();
                //SetTab('preview_PREVIEW');
                EcmPreviewPDF('index.php?module=EcmReceipts&action=previewPDF&to_pdf=1&method=I&record=' + document.forms.DetailView.record.value + '&type=' + type, {zoom: 75});
            }
            else {
                SetTab('panel_PREVIEW');

                document.getElementById('previewPDF').innerHTML = '<iframe style="border:none;width:100%;height:1200px;" frameborder="no" src="index.php?module=EcmReceipts&action=previewPDF&to_pdf=1&method=I&record=' + document.forms.DetailView.record.value + '&type=' + type + '#zoom=75">Yours browser not accept iframes!</iframe>';
            }
        };

        setEMAIL = function(noCheck) {
            SetTab('panel_EMAIL');

            document.getElementById('emailTAB').innerHTML = '<iframe id="emailIFRAME" style="border:none;width:100%;height:670px;" frameborder="no" src="index.php?module=EcmReceipts&action=Emails&to_pdf=1&type=out&pTypeTo=' + document.forms.DetailView.parent_type.value + '&pIdTo=' + document.forms.DetailView.parent_id.value + '&pTypeFrom=Users&pIdFrom=' + document.forms.DetailView.assigned_user_id.value + '&receipt_id=' + document.forms.DetailView.record.value + '&record=' + document.forms.DetailView.email_id.value + '&type=' + type + '">Yours browser not accept iframes!</iframe>';
        };

        setInterval(
            function() {
                doRequest(
                    'index.php',
                    "module=EcmReceipts&action=subpanels&to_pdf=1&record=" + document.forms.DetailView.record.value,
                    function(result) {
                        if (result != '' && document.getElementById('subpanels_div'))
                            document.getElementById('subpanels_div').innerHTML = result;
                    }
                );
            },
            10000
            );

        //quick view
        var main = document.getElementById('main');

        if (main) {
            var h2 = main.getElementsByTagName('h2')[0];

            if (h2) {
                h2.style.display = 'inline';
                var quickInfoH2 = document.getElementById('quickInfoH2');

                if (quickInfoH2) {
                    h2.parentNode.appendChild(quickInfoH2);
                    quickInfoH2.style.display = '';
                }
            }
        }

        if (OPT['setTab'] && OPT['setTab'] != '') {
            if (OPT['setTab'] == 'EMAIL') {
                setEMAIL();
            }
        }

        for (var i = 0; i < N.rowCount(); i++) {
            N.row(i).calculateTotal();
        }
    }
);