$(function () {
    
    function buildValidationIcons() {
        return '<td class="validation_icons"> \
            <span class="wait_spinner"><img src="/images/icons/wait.gif" /></span> \
            <span class="valid"><img src="/images/icons/accept.png" /></span> \
            <span class="invalid"><img src="/images/icons/cancel.png" /></span> \
            <span class="error_message">Error</span> \
        </td>';
    };
    
    $("#appForm table tr").append(buildValidationIcons());
    
    var validateInput = function (obj) {
        var field = $(obj.target);
        var icons = $(field.parent().siblings('.validation_icons').children('span')); 
        var icnWait = $(icons[0]);
        var icnValid = $(icons[1]);
        var icnInvalid = $(icons[2]);
        var strMessage = $(icons[3]);
        
        icons.hide();
        icnWait.fadeIn("normal");
        
        $.getJSON("/dfa/apply/validate", {
            name: field.attr('name'),
            value: field.val()
        }, function (json) {
            if (json !== null) {
                if (json.valid) {
                    icnWait.fadeOut("fast", function () {
                        icnValid.fadeIn("fast");
                    });
                    
                    if (field[0].id == 'fDeliveryDate') {
                        $("#submit_application").show();
                    }
                    if (field[0].id == 'fPickupAddress') {
                        $("#submit_application").show();
                    }
                } else {
                    icnWait.fadeOut("fast", function () {
                        icnInvalid.fadeIn("fast");
                        strMessage.text(json.message).fadeIn("fast");
                    });
                }
            } else {
                icnWait.fadeOut("fast");
            }
        });
        
    };
    
    var checkMinor = function () {
        $("#companion").hide();
        var curr = new Date();
        curr.setFullYear(curr.getFullYear() - 18);
        var dob = Date.parse($(this).val());
        if((curr - dob) < 0) {
            $("#companion").show();
        } else {
            $("#companion").hide();
        }
    };
    
    var recomputeDates = function (e) {
        $.getJSON("/dfa/apply/recompute-dates", {
            pickupDate: $(e.target).val(),
            city: $('#fCity').val(),
            province: $('#fProvince').val()
        }, function (json) {
            if (json !== null) {
                $("#fPersonalAppearance").val(json.personalAppearance).change();
                $("#fDeliveryDate").val(json.deliveryDate).change();
            } 
        });
    };
    
    var getCities = function (e) {
        $.get("/dfa/apply/get-cities", {
            province: $(e.target).val()
        }, function (data) {
            $("#fCity").html(data);
        });
    };
    
    var recomputePA = function (e) {
        $.getJSON("/dfa/apply/recompute-pa", {
            personalAppearance: $(e.target).val(),
            pickupDate: $('#fPickupDate').val(),
            city: $('#fCity').val(),
            province: $('#fProvince').val()
        }, function (json) {
            if (json !== null) {
                $("#fDeliveryDate").val(json.deliveryDate).change();
            } 
        });
    };
    
    $("select").change(validateInput);
    $("input.validate").change(validateInput);
    $("textarea.validate").change(validateInput);
    $("input.validate").keypress(function (e) {
        if (e.which == 13) {
            validateInput(e);
        }
    });
    
    $("#fBirthdate").change(checkMinor);
    $("#fBirthdate").keypress(function (e) {
        if (e.which == 13) {
            checkMinor(e);
        }
    });
    
    $("#fType").change(function () {
        $(".birth_reminder").hide();
        if ($(this).val()) {
            $("#birth_" + $(this).val() + "_reminder").show();
        }
        
        $("#passport_info").hide();
        if ($(this).val() == 'renewal') {
            $("#passport_info").show();
            $("#fPassportNumber").val('');
            $("#fDateIssued").val('');
            $("#fPlaceIssued").val('');
        } else {
            $("#fPassportNumber").val('NA');
            $("#fDateIssued").val('NA');
            $("#fPlaceIssued").val('NA');
        }
        
    });
    
    $("#fCivilStatus").change(function () {
        $("#trSpouse").hide();
        if (($(this).val() == 'married') || ($(this).val() == 'widowed')) {
            $("#trSpouse").show();
            $("#fSpouse").val('');
        } else {
            $("#fSpouse").val('NA');
        }
        
    });
    
    $(".birth_reminder").hide();
   
    $("#submit_application input").click(function () {
        if (confirm('Are you sure you want to submit your application? You cannot edit it after submission.')) {
            var data = $("#appForm").serialize();
            $("#submit_indicator").show();
            $("#output").hide();
            $.post("/dfa/apply/submit", data, function (resp) {
                $("#submit_indicator").hide();
                $("#output").html(resp);
                $("#output").show();
            });
        }
    });
    
    $("#fPickupDate").change(recomputeDates);
    $("#fPickupDate").keypress(function (e) {
        if (e.which == 13) {
            recomputeDates(e);
        }
    });
    
    $("#fPersonalAppearance").change(recomputePA);
    $("#fPersonalAppearance").keypress(function (e) {
        if (e.which == 13) {
            recomputePA(e);
        }
    });
    
    $("#fProvince").change(getCities);
    $("#confirmation").click(function () {
        $("#appForm").show();
        $(this).hide();
    });
});
