/*
 * editLineItem.js
 * author: Karl Cordes
 *
 *  1. Watch links with class 'editLineItem'.
 *  2. When clicked. Fetch their /edit/id page
 *  3. update the contents of the editLineItem div
 *  4. open a dialog box.
 *  5. submit the form via AJAX
 *
 */

$(function() {


   $("#editLineItem").dialog({
        autoOpen: false,
        height: 800,
        width: 800,
        modal: true,
        buttons: {
            'Add Product': function() {

                $.post("/line_items/ajaxSave", $("#LineItemAddForm").serialize(), function(data) {

                    fetchTable();
                     $('#mydebug').html(data);
            }
                );

                $("#LineItemAddForm").resetForm();
                $(this).dialog('close');
            },
            Cancel: function() {
                $(this).dialog('close');
            }
        },
        close: function() {

        },
        open: function () {
            $('.ckeditor').ckeditor();
        }
    });


  

    $("a.editLink").click(function (event) {
        
        var linkTarget = $(this).attr("href");
        
        
        $("#editLineItem").load(linkTarget, function() {

            
            $('#editLineItem').dialog('open');


        });


        event.preventDefault();
       return false;
    });





});


/**
 * Do the simple calculation of net price after discount.
 *
 */


function calcNetPrice() {
    var discountPercent = $("#discountPercent").val();
    var unitPrice = $('#unitPrice').val();


    var quantity = $('#LineItemQuantity').val();


    var grossSellPrice = quantity * unitPrice;

    //Calculate the Sale Discount amount.
    var UnitDiscountAmount = (discountPercent/100) * unitPrice;

    var TotalDiscountAmount = (discountPercent/100) * grossSellPrice;
    UnitDiscountAmount = UnitDiscountAmount.toFixed(2);
    TotalDiscountAmount = TotalDiscountAmount.toFixed(2);

    $('#total_discountAmount').val(TotalDiscountAmount);
    $('#discountAmountEach').val(UnitDiscountAmount);
    $('#net_price_each').val(unitPrice - UnitDiscountAmount);

    $('#grossPrice').val(grossSellPrice);

    var netPrice = grossSellPrice - TotalDiscountAmount;
    $('#netPrice').val(netPrice);

}