$(function()
{
    /* Change product. */
    $(document).on('change', '[name^=product]', function()
    {
        var unit = $(this).find('option:selected').attr('data-unit');
        if(unit == 0) return false;
        
        $(this).parents('.row').find('[name^=unit]').val(unit);
    });
    
    PRECISION = 100;

    /* Change product amount and compute product money. */
    $(document).on('change', '[name^=amount]', function()
    {
        var price  = $(this).parents('.row').find('[name^=price]').val();
        var amount = $(this).val();
        if(price == '' || amount == '') return false;

        var money = Math.round(price * amount * PRECISION) / PRECISION;

        $(this).parents('.row').find('[name^=money]').val(money).change();
    });
    
    /* Change product price and compute product money. */
    $(document).on('change', '[name^=price]', function()
    {
        var amount = $(this).parents('.row').find('[name^=amount]').val();
        var price  = $(this).val();
        if(price == '' || amount == '') return false;

        var money = Math.round(price * amount * PRECISION) / PRECISION;

        $(this).parents('.row').find('[name^=money]').val(money).change();
    });
    
    /* Compute order money. */
    $(document).on('change', '[name^=money]', function()
    {
        var total     = 0;
        var moneyList = $('[name^=money]');
        for(i = 0; i < moneyList.length; i++)
        {
            if($.isNumeric(moneyList[i].value))
            {
                total += parseFloat(moneyList[i].value);
            }
        }

        total = Math.round(total * PRECISION) / PRECISION;

        $('#plan').val(total);
    });

    $(document).on('click', '.btn-add-product', function()
    {  
        $(this).before($('.template').html().replace(/KEY/g, v.key));
        v.key++;
    });

    $(document).on('click', '.product-deleter', function()
    {  
        if($(this).parents('.children').find('.row').length > 1)
        {
            $(this).closest('.row').remove();
        }
        else
        {
            $(this).closest('.row').find('input,select,textarea').val('');
        }

        $('[name^=money]').change();
    });
})
