﻿$(document).ready(function($){

    // set the focus to the first form field
    $("#txtName").focus();

	// submit click handler: 
	// 1. set up so that validation runs client- and server-side, but the validation rules need only be set up server-side
	// 2. degrades gracefully, i.e. form still functions if the client does not support javascript, e.g. handheld devices and browsers in locked-down corporate networks
    $("#btnSubmit").click(function() {
        // serialise the form values, excluding asp.net viewstate fields
        var res = $("#Form")
            .find("input,textarea,select,hidden")
            .not("#__VIEWSTATE,#__EVENTVALIDATION,#__EVENTTARGET,#__EVENTARGUMENT")
            .serialize();
            
        // clear all form fields that may have been highlighted as incorrect on a previous submit
        //$(document).removeClass("ValidationAlert"); <- this does not seem to work, so loop through the fields
        var inputFields = res.split("&");
        for (fieldCount=0; fieldCount < inputFields.length; fieldCount++)
            $("#" + inputFields[fieldCount].split("=")[0]).removeClass("ValidationAlert");

        // post the serialised form fields to the existing page 
        $.post("rkdwm.aspx",
            res + "&ajaxValidation=true", 
            function(result) {
                if (result == "")
                {
                    // if form is valid, post the form with a hidden field so that the code-behind will process it as if the button was clicked
                    $('#Form').append('<input id="scriptSubmit" name="scriptSubmit" type="hidden" value="true" />');
                    $("#Form").submit();
                }
                else
                {
                    // process the return values: 'errorField1,errorField2,...|errorMessage'
                    // 1. add highlighting to the fields that require attention
                    // 2. display the validation message
                    var results = result.split("|");
                    var valErrorFields = results[0];
                    var valMessage = results[1];
                    var errorFields = valErrorFields.split(",");
                    for (fieldCount=0; fieldCount<errorFields.length; fieldCount++)
                    {
                        $("#" + errorFields[fieldCount]).addClass("ValidationAlert");
                    }
                    $("#Message").html("<br />" + valMessage);
                }
            });

        // do not post the form
        return false;
    });

});

