$(function () {

    var selection;

    $('.leiturasPopup select').change(displayVals);
    displayVals();
    checkInput();

    //display the label and input box if 'Conta Certa' is not chose
    function displayVals() {
        selection = $('.leiturasPopup option:selected').val();
        $('.leiturasPopup input').val("");

        if (selection == 'Conta Certa') {
            $('.leiturasPopup select+label, .leiturasPopup input, .leituraDia, .msgErro').hide();
            $('.leituraCerta').show();
        }
        else {
            $('.leituraCerta').hide();
            $('.leiturasPopup select+label, .leiturasPopup input').show();
            $('.leiturasPopup input').change(checkInput);
        }
    }

    //validates the date on the input box and displays the correct message
    function checkInput() {
        var userDate = $('.leiturasPopup input').val();

        if (userDate) {
            var validInput = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
            if (userDate.match(validInput)) {
                addDays(calculateDate(userDate));
                $('.msgErro').hide();
                $('.leituraDia').show();
            }
            else {
                $('.leituraDia').hide();
                $('.msgErro').show();   
            }
        }
    }

    //creates an object Date with the date provided by the user
    function calculateDate(userDate) {
        var d,
            day = userDate.slice(0, 2);
        month = userDate.slice(3, 5);
        year = userDate.slice(6, 10);

        return d = new Date(year, month - 1, day);
    }

    //add days to the selection
    function addDays(d) {
        if (selection == 'Mensal') {
            d.add(25).days();
            $('.leituraDia span.date').text(d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
        }
        else {
            d.add(50).days();
            $('.leituraDia span.date').text(d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear());
        }
    }

});
