$(document).ready(
    function() {
        $('#cos').append('<div id="resposta"></div>');
        $('button.pass').after('<img src="img/ajax-loader.gif" id="preloader" />');
        $('#nom').after('<div id="nom_msg" class="contacte"></div>');
        $('#email').after('<div id="email_msg" class="contacte"></div>');
        $('#comentaris').after('<div id="comentaris_msg" class="contacte"></div>');

        $('#preloader').hide();


        var options = {
            target:        '#resposta',   // target element(s) to be updated with server response
            beforeSubmit:  validate,      // pre-submit callback
            success:       showResponse,  // post-submit callback. Crec que no es necessari si indiquem el target
            url:           'procesaAjax/'
        };

        // bind form using 'ajaxForm'
        $('#afkCForm').ajaxForm(options);

        function validate(formData, jqForm, options) {
            //alert(formData[0].value); // nom
            //alert(formData[1].value); // email
            //alert(formData[2].value); // comentaris

            $('#nom_msg').html("");
            $('#email_msg').html("");
            $('#comentaris_msg').html("");

            if (!formData[0].value) {
                //alert('El nom és obligatori');
                //document.getElementById("fcForm").nom.focus();
                $('#nom_msg').html("nombre requerido.");
            }
            if (!formData[1].value) {
                $('#email_msg').html("email requerido.");
            }
            if (!formData[2].value) {
                $('#comentaris_msg').html("comentario requerido");
            }

            for (var i=0; i < formData.length -1; i++) {
                if (!formData[i].value) {
                    return false;
                }
            }

            $('#preloader').show();
        }

        function showResponse(responseText, statusText)  { 
            // for normal html responses, the first argument to the success callback 
            // is the XMLHttpRequest object's responseText property 

            // if the ajaxForm method was passed an Options Object with the dataType 
            // property set to 'xml' then the first argument to the success callback 
            // is the XMLHttpRequest object's responseXML property 

            // if the ajaxForm method was passed an Options Object with the dataType 
            // property set to 'json' then the first argument to the success callback 
            // is the json data object returned by the server 

            //alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +  '\n\nThe output div should have already been updated with the responseText.');
            $('#preloader').hide();
            $('#afkCForm').resetForm();
            $('#resposta').css('background-color', '#E1A421').css('border', '1px dashed black').css('text-align', 'center');
        }

    }
);