$(document).ready(function()
{
    $('#begin, #start, #end, #finish, input:radio[name=type]').change(function()
    {
        var type   = $('input[name=type]:checked').val();
        var begin  = $('#begin').val().replace(/-/g, '/');
        var end    = $('#end').val().replace(/-/g, '/');
        var start  = type != 'annual' ? $('#start').val() : '00:00';
        var finish = type != 'annual' ? $('#finish').val() : '24:00';

        if(!begin || !end || !start || !finish) return false;

        var url = createLink('attend', 'ajaxGetHours', 'type=leave&begin=' + begin + '&start=' + start + '&end=' + end + '&finish=' + finish + '&leaveType=' + type);
        $.getJSON(url, function(data)
        {
            if(data.result == 'success')
            {
                var hours = type == 'annual' ? Math.round(data.hours / v.workingHours) : data.hours;
                $('#hours').val(hours).change();
            }
        });
    });

    $('#begin').change(function()
    {
        getAnnualBalance();
    })

    $('input:radio[name=type]').change(function()
    {
        var type = $(this).val();
        $('#hoursTip').text(type == 'annual' ? v.daysTip : v.hoursTip);
        $('#annualBalanceTip').toggleClass('hidden', type != 'annual');
        $('.leave-time').toggleClass('hidden', type == 'annual');
        getAnnualBalance();
    })

    $('#begin').change();
})

function getAnnualBalance()
{
    if($('input:radio[name=type]:checked').val() != 'annual') return false;
    var begin = $('#begin').val().replace(/-/g, '/');
    var url = createLink('annual', 'ajaxGetAnnualBalance', 'begin=' + begin);
    $.getJSON(url, function(data)
    {
        if(data.result == 'success')
        {
            $('#annualBalanceTipText').text(data.tip);
        }
    });
}
