$(document).ready(function() {

    $('tr#place').hide();

    $('select#delivery').change(function() {
        value = $(this).val();

        (value == 1) ? $('tr#place').show() : $('tr#place').hide();
        var current_machine = $('input#filter_place').val();

        
        $.getJSON('json2.php?type=delivery', {id: value, current_machine: current_machine}, function(json) {
            if (json.status == 'ok') {
                if(json.machineSelect) {
                    $('td.machineSelect').html(json.machineSelect);
                    $('tr#place').show();
                } else {
                    $('tr#place').hide();
                }
                $('span#tperiod').text(json.period);
                $('span#tprice').text(Number(json.price).toFixed(2));

            } else {
                $('span#tperiod').text('');
                $('span#tprice').text('');
            }

            calculateTotal();
        })
    });
    
    $('select#delivery').change();

    calculateTotal = function() {
        var carttotal = Number($('input#carttotal').val());
        var transport = Number($('span#tprice').text());
        var pcsum = Number($('span#pcsum').text());
        var total = carttotal + transport - pcsum;
        if (total < 0) {
            total = 0;
        }

        $('span#total').text(total.toFixed(2));
    }

    calculateTotal();


    ($('span#pcsum').text()) ? $('tr#pcinput').hide() : $('tr#pcdata').hide();

    $('input#pcadd').click(function() {
        value = $('input#pcinput').val();

        $.getJSON('json2.php?type=presentcard', {code: value}, function(json) {
            if (json.status == 'ok') {
                $('span#pcsum').text(json.pcsum);
                $('tr#pcinput').hide();
                $('tr#pcdata').show();

                calculateTotal();

            } else {
                $('input#pcinput').val('');
            }
        })
    });

    $('input#pcremove').click(function() {
        $('span#pcsum').text('');
        $('tr#pcinput').show();
        $('tr#pcdata').hide();
        $('input#pcinput').val('');

        calculateTotal();
    });


    hidePersonBlock = function() {
        $('div#personblock1').hide();
        $('div#personblock2').hide();
        $('div#companyblock1').show();
        $('div#companyblock2').show();
    }

    hideCompanyBlock = function() {
        $('div#personblock1').show();
        $('div#personblock2').show();
        $('div#companyblock1').hide();
        $('div#companyblock2').hide();
    }

    if ($('input#company').attr('checked')) {
        hidePersonBlock();

    } else {
        hideCompanyBlock();
    }

    $('input#person').click(function() {
        hideCompanyBlock();
    });

    $('input#company').click(function() {
        hidePersonBlock();
    });

});

