$(document).ready(function () {

    $('#add_patient').on('click', function(){add_patient(false)});
    $('#add_and_start_visit').on('click', function(){add_patient(true)});

    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    };

    function add_patient(redirect){

        fio = $('#fio').val();
        dob = $('#dob').val();
        med_card = $('#med_card').val();
        sex = $('#sex').val();
        telephone = $('#telephone').val();
        email = $('#email').val();
        false_form = false
        lang = getUrlParameter('lang');
        if(false_form==false)
        {
            var message = {
                fio: fio,
                dob:dob,
                med_card:med_card,
                sex:sex,
                telephone:telephone,
                email:email
            }
            $.ajax({
                type:'POST',
                url: '/add_patient',
                async: !1,
                processData: false,  // tell jQuery not to process the data
                contentType: false,  // tell jQuery not to set contentType
                data: JSON.stringify(message),
                success: (data) => {
                    if(data['success'] == true)
                    {
                        $('#success').slideDown(500);
                        $('#success').delay(2000).slideUp();

                        if(redirect == true){
                            if(lang == 'en')
                                window.location.href = '/visit/new_visit?patient_id='+data['id']+'?lang=en';
                            else
                                window.location.href = '/visit/new_visit?patient_id='+data['id'];
                        }
                        else
                        {
                            fio = $('#fio').val('');
                            dob = $('#dob').val('');
                            med_card = $('#med_card').val('');
                            sex = $('#sex').val('');
                            telephone = $('#telephone').val('');
                            email = $('#email').val('');
//                            show_success('Пациент добавлен', false);
                        }
                    }
                    else
                    {
                        $('#exception').slideDown(500);
                        $('#exception').delay(2000).slideUp();
                    }
                }
            });
        }
    }

});
