$(document).ready(function() {

    initializeForm();

    $('input').each(function(index) {
        $(this).keydown(function() {
            onKeyDown($(this));
        });

        $(this).blur(function() {
            onBlur($(this));
        });

        $(this).keyup(function(e) {
            onKeyup($(this), e);
        });

        $('input').each(function(index) {
            $(this).keydown(function(e) {
                onFormKeyDown($(this), e);
            });
        });

        $('select').each(function(index) {
            $(this).keydown(function(e) {
                onFormKeyDown($(this), e);
            });
        });

    });
});

var previousValue;

function onKeyDown(field) {
    if (field.val() == "DD"
    || field.val() == "MM"
    || field.val() == "YYYY") {
        field.val("");
        return;
    }

    previousValue = field.val();
}

function onBlur(field){
    if (field.val() == "")
    {
        if(field.attr('name') == 'day')
        {
            field.val('DD');
        }
        if(field.attr('name') == 'month')
        {
            field.val('MM');
        }
        if(field.attr('name') == 'year')
        {
            field.val('YYYY');
        }                
    }
}

function onKeyup(field, event) {
    var chars;

    if (!testInput(field.val())) {
        field.val(previousValue);
        previousValue = "";
        return;
    }
    previousValue = "";

    if (event.which < 48
    || event.which > 57) {
        return;
    }

    if (field.attr('name') == "day"
    || field.attr('name') == "month") {
        chars = 2;
    } else {
        chars = 4;
    }

    if (field.val().length == chars) {
        if (field.attr('name') == 'day') {
            $('#month').focus();
            $('#month').select();
        } else if (field.attr('name') == 'month') {
            $('#year').focus();
            $('#year').select();
        } else {
            $('#select_country').focus();
        }
    }   
    
}

function testInput(x) {
    if (x == "") {
        return true;
    }
    if (x == "DD" || x == "MM" || x == "YYYY") {
        return true;
    }

    var re = /^(\s|\d)+$/;
    return re.test(x);
}

function initializeForm() {
	$('#select_country').focus();
    //$('input.focus:first').focus();
    //$('input.focus:first').select();
}

function onFormKeyDown(field, event) {
    if (event.which == 13) {
		$('form')[0].fadeout('slow').submit();
    }
}
