/*
 * phpaga
 *
 * This file contains some JavaScript functionality for the billing
 * pages of phpaga.
 *
 * @author Florian Lanthaler <florian@phpaga.net>
 * @version $Id: billing.js 758 2006-12-06 19:24:01Z florian $
 *
 * 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)
        }


// 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.setAttribute('class', 'even');
    } else {
        row.setAttribute('class', 'odd');
    }

    var cell0 = row.insertCell(0);
    var el0 = document.createElement('input');
    el0.setAttribute('type', 'text');
    el0.setAttribute('class', 'tinput');
    el0.setAttribute('size', '18');
    el0.setAttribute('maxlength', '18');
    el0.setAttribute('onblur', '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.setAttribute('onclick', '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.setAttribute('class', 'tinput number');
    el2.setAttribute('size', '10');
    el2.setAttribute('maxlength', '10');
    el2.setAttribute('name', 'lit_qty[]');
    el2.setAttribute('id', 'prodqty' + iteration);
    el2.setAttribute('onblur', "calcLineItemPrice('"+iteration+"');");
    cell2.appendChild(el2);

    var cell3 = row.insertCell(3);
    cell3.setAttribute('class', '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.setAttribute('class', '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.setAttribute('onclick', '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 getPayTerm() {

    showPageStatus();

    AjaxRequest.get(
                    {
                        'url':'service.php?saction=35&id=' + document.getElementById("cpn").value,
                            'onSuccess':function(req){
                                document.getElementById("payterm").value = req.responseText; 
                                hidePageStatus();
                                
                        },
                            
                            'onError':function(req){
                                alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);
                                hidePageStatus();
                            }
                    }
                    );
}


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. */


    if ((document.getElementById('prodcode'+elem_num).value.length > 0)
        && (document.getElementById('prodname'+elem_num).value.length == 0)) {

        curr_elem_num = elem_num;
        showPageStatus();

        AjaxRequest.get(
                        {
                            'url':'service.php?saction=40&prod_code=' + document.getElementById('prodcode'+elem_num).value,
                                'onSuccess':function(req){

                                response = req.responseXML.documentElement;
                                status = response.getElementsByTagName('status')[0].firstChild.data;

                                if (status != 0) {
                                    alert(response.getElementsByTagName('message')[0].firstChild.data);
                                } else if (status == 0) {
                                    price = response.getElementsByTagName('prodprice')[0].firstChild.data;
                                    name = response.getElementsByTagName('prodname')[0].firstChild.data;

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

                                    if (qty.length == 0)
                                        document.getElementById('prodqty'+curr_elem_num).value = 1;

                                    document.getElementById('prodname'+curr_elem_num).value = name;
                                    document.getElementById('unitnetprice'+curr_elem_num).value = price;
                                    document.getElementById('unitnetpricetxt'+curr_elem_num).innerHTML = price;
                                    if (parseInt(qty) != qty)
                                        document.getElementById('prodprice'+curr_elem_num).value = price;
                                    else
                                        document.getElementById('prodprice'+curr_elem_num).value = (qty * price);
                                }

                                hidePageStatus();

                            },

                                'onError':function(req){
                                    alert('Error!\nStatusText='+req.statusText+'\nContents='+req.responseText);
                                    hidePageStatus();
                                }
                        }
                        ); 
    }
}

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);
}
