/*
 * phpaga
 *
 * This file contains some JavaScript functionality for the billing
 * pages of phpaga.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id$
 *
 * Copyright (c) 2006, Florian Lanthaler <florian@phpaga.net>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *
 *    * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *
 *    * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *
 *    * Neither the name of Florian Lanthaler nor the names of his
 *      contributors may be used to endorse or promote products derived
 *      from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

function delLineItem(i) {
    document.getElementById('tbllineitems').deleteRow(i)
        }

function delExpenseLine(i) {
    document.getElementById('tblexpenses').deleteRow(i)
        }

// inspired by
// http://www.mredkj.com/tutorials/tableaddrow.html
// Last updated 2005-10-25

function addLineItem()
{
    var tbl = document.getElementById('tbllineitems');
    var lastRow = tbl.rows.length;
    // if there's no header row in the table, then iteration = lastRow + 1
    var iteration = lastRow;

    var prev = lastRow - 1;
    if (prev < 0) {
        prev = 0;
    }

    var lastClass = tbl.rows[prev].getAttribute('class');

    var row = tbl.insertRow(lastRow);

    if (lastClass == 'odd') {
        row.className = 'even';
    } else {
        row.className = 'odd';
    }

    var cell0 = row.insertCell(0);
    var el0 = document.createElement('input');
    el0.setAttribute('type', 'text');
    el0.className = 'tinput';
    el0.setAttribute('size', '18');
    el0.setAttribute('maxlength', '18');
    el0.onblur = function() { getProdInfo(iteration); }
    el0.setAttribute('name', 'lit_prodcode[]');
    el0.setAttribute('id', 'prodcode' + iteration);
    cell0.appendChild(el0);

    var elcat = document.createElement('img');
    elcat.setAttribute('src', 'img/phpaga/catalog.png');
    elcat.setAttribute('height', '16');
    elcat.setAttribute('width', '16');

    anchor = document.createElement("a");
    anchor.href = '#';
    anchor.onclick = function () { getProductCatalog(this.parentNode.parentNode.rowIndex); }
    anchor.appendChild(elcat);

    cell0.appendChild(anchor);

    var el0c = document.createElement('input');
    el0c.setAttribute('type', 'hidden');
    el0c.setAttribute('name', 'lit_mat_id[]');
    cell0.appendChild(el0c);

    var el0b = document.createElement('input');
    el0b.setAttribute('type', 'hidden');
    el0b.setAttribute('name', 'lit_op_id[]');
    cell0.appendChild(el0b);

    var cell1 = row.insertCell(1);
    var el1 = document.createElement('textarea');
    el1.setAttribute('cols', '60');
    el1.setAttribute('rows', '2');
    el1.setAttribute('wrap', 'virtual');
    el1.setAttribute('name', 'lit_desc[]');
    el1.setAttribute('id', 'prodname' + iteration);
    cell1.appendChild(el1);

    var cell2 = row.insertCell(2);
    var el2 = document.createElement('input');
    el2.setAttribute('type', 'text');
    el2.className = 'tinput number';
    el2.setAttribute('size', '10');
    el2.setAttribute('maxlength', '10');
    el2.setAttribute('name', 'lit_qty[]');
    el2.setAttribute('id', 'prodqty' + iteration);
    el2.onblur = function() { calcLineItemPrice(iteration) };
    cell2.appendChild(el2);

    var cell3 = row.insertCell(3);
    cell3.className = 'number';

    var el3s = document.createElement('span');
    el3s.setAttribute('id', 'unitnetpricetxt' + iteration);
    cell3.appendChild(el3s);

    document.getElementById('unitnetpricetxt' + iteration).innerHTML = "&nbsp;";

    var el3i = document.createElement('input');
    el3i.setAttribute('type', 'hidden');
    el3i.setAttribute('name', 'lit_unitnetprice[]');
    el3i.setAttribute('id', 'unitnetprice' + iteration);
    cell3.appendChild(el3i);

    var cell4 = row.insertCell(4);
    var el4 = document.createElement('input');
    el4.setAttribute('type', 'text');
    el4.className = 'tinput number';
    el4.setAttribute('size', '15');
    el4.setAttribute('maxlength', '15');
    el4.setAttribute('name', 'lit_netprice[]');
    el4.setAttribute('id', 'prodprice' + iteration);
    cell4.appendChild(el4);

    var cell5 = row.insertCell(5);

    var eldel = document.createElement('img');
    eldel.setAttribute('src', 'img/phpaga/delete.png');
    eldel.setAttribute('height', '16');
    eldel.setAttribute('width', '16');

    delanchor = document.createElement("a");
    delanchor.href = '#';
    delanchor.onclick = function () { delLineItem(this.parentNode.parentNode.rowIndex); }
    delanchor.appendChild(eldel);

    cell5.appendChild(delanchor);

}

function removeRowsFromTable()
{
    var tbl = document.getElementById('tbllineitems');
    var lastRow = tbl.rows.length;

    for (i = lastRow - 1; i > 0; i--) {

        if (tbl.rows[i].cells[4].getElementsByTagName('input')[0].checked) {
            tbl.deleteRow(i);
        }
    }
}

function companyChanged() {

    getPayTerm();
    getEmployees();
}

function getPayTerm() {

    showPageStatus();

    $.ajax({
        url: 'service.php?saction=35&id='+$('#cpn').val(),
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function(result) {

            hidePageStatus();

            if (result == null) {
                alert('An unexpected error has occurred.');
            } else if (result.status != 0 && result.status != 30) {
                alert(result.message);
            } else {

                if (result.status == 0) {
                    $('#payterm').val(result.data.term);
                }
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

            msg = textStatus;
            if (textStatus == 'parsererror')
                msg = 'Invalid response from the server.';

            hidePageStatus();
            alert(msg);
        }
    });
}

function getEmployees() {

    showPageStatus();

    $.ajax({
        url: 'service.php?saction=48&id='+$('#cpn').val(),
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function(result) {

            hidePageStatus();

            if (result == null) {
                alert('An unexpected error has occurred.');
            } else if (result.status != 0 && result.status != 30) {
                alert(result.message);
            } else {

                el = $('#pe_id_recipient').get(0);
                el.options.length = 0;
                items = result.data.persons;

                if (items.length > 0) {
                    el.options[0] = new Option('', '');
                    $.each(items, function () { el.options[el.options.length] = new Option(this.name, this.id); });
                    $('#pe_id_recipient').removeAttr('disabled');
                } else 
                    $('#pe_id_recipient').attr('disabled', 'disabled');
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {

            msg = textStatus;
            if (textStatus == 'parsererror')
                msg = 'Invalid response from the server.';

            hidePageStatus();
            alert(msg);
        }
    });
}

function getProdInfo(elem_num) {

    /* If prod_code is set and prod_name is not set then fetch product information.
       Do not fetch data for rows that have already been filled out. */

    prodcode = $('#prodcode'+elem_num).val();
    prodname = $('#prodname'+elem_num).val();

    if ((prodcode.length > 0) && (prodname.length == 0)) {

        curr_elem_num = elem_num;
        showPageStatus();

        $.ajax({
            url: 'service.php?saction=40&prod_code='+prodcode,
            type: 'GET',
            dataType: 'json',
            cache: false,
            success: function(result) {

                hidePageStatus();

                if (result == null) {
                    alert('An unexpected error has occurred.');
                } else if (result.status != 0 && result.status != 30) {
                    alert(result.message);
                } else {

                    if (result.status == 0) {
                        price = result.data.prod_price;
                        name = result.data.prod_name;
                    } else {
                        price = null;
                        name = '';
                    }

                    var qty = $('#prodqty'+curr_elem_num).val();

                    if ((qty == null) || (qty.length == 0))
                        $('#prodqty'+curr_elem_num).val(1);

                    $('#prodname'+curr_elem_num).val(name);

                    if (price != null) {
                        $('#unitnetprice'+curr_elem_num).val(price);
                        $('#unitnetpricetxt'+curr_elem_num).html(price);
                    } else {
                        $('#unitnetprice'+curr_elem_num).val('');
                        $('#unitnetpricetxt'+curr_elem_num).html('');
                    }

                    if ((price != null) && (price.length > 0)) {
                        if (parseInt(qty) != qty)
                            $('#prodprice'+curr_elem_num).val(price);
                        else
                            $('#prodprice'+curr_elem_num).val(qty * price);
                    }
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {

                msg = textStatus;
                if (textStatus == 'parsererror')
                    msg = 'Invalid response from the server.';

                hidePageStatus();
                alert(msg);
            }
        });
    }
}

function calcLineItemPrice(elem_num) {

    var qty = document.getElementById('prodqty'+curr_elem_num).value;
    var unitprice = document.getElementById('unitnetprice'+curr_elem_num).value;

    if (isNumeric(qty) && isNumeric(unitprice)) {
        var res = (qty * unitprice);

        if (res.toFixed)
            res = res.toFixed(2);

        document.getElementById('prodprice'+curr_elem_num).value = res;
    }
}

function getProductCatalog(elem_num) {

    var pbox = document.getElementById('prodselectbox');
    var prcode = document.getElementById('prodcode'+elem_num);

    document.getElementById('prodselectdest').value = elem_num;

    x = findPosX(prcode);
    y = findPosY(prcode);

    w = pbox.offsetWidth;

    if (x > w) {
        x = x - w;
    }

    if (y > pbox.offsetHeight) {
        y = y - pbox.offsetHeight + 20;
    }

    pbox.style.left = x+"px";
    pbox.style.top = y+"px";

    pbox.style.visibility = "visible";
}


function selectProduct(prod_code) {

    var elem_num = document.getElementById('prodselectdest').value;

    document.getElementById('prodcode'+elem_num).value = prod_code;
    document.getElementById('prodname'+elem_num).value = '';

    document.getElementById('prodselectbox').style.visibility = "hidden";
    getProdInfo(elem_num);
}
