$(function()
{

    $("#submit-comentario").click(function()
    {
        doValidationForm();
    });

    $('.commentform').submit(function() {
        return false;
    });


function doValidationForm()
{
    var url = '/async/validateform'
    var data = {};

    $(".commentform input:text").each(function()
    {
        var id = $(this).attr('id');
        data[id] = $(this).val();
        $("#"+id).parent().find('.errors').remove();
    });

    $(".commentform input:hidden").each(function()
    {
        var id = $(this).attr('id');
        data[id] = $(this).val();
     
    });

    $(".commentform textarea").each(function()
    {
        var id = $(this).attr('id');
        data[$(this).attr('name')] = $(this).val();
        $("#"+id).parent().find('.errors').remove();

    });

    $(".commentform input:checkbox").each(function()
    {
        var id = $(this).attr('id');
        data[$(this).attr('name')] = $(this).val();
        $("#"+id).parent().find('.errors').remove();

    });

    $.ajax(
    {
        type: 'POST',
        url:url, 
        data:data,
        beforeSend: function() {
            $('#submit-comentario').hide();
        },
        success:function(respuesta)
        {
            var error = 0;
            
            $.each(respuesta.errores, function(id,items)
            {
                $.each(items, function(id,item){

                   $("#"+id).parent().append(getErrorHtml(item, id));
                   error+=1;
                });



            });

            if (!$('input[name=condiciones]').is(':checked'))
            {
                $("#condiciones").parent().append(getErrorHtml(["Debe aceptar las condiciones"], "condiciones"));
                error+=1;
            }

            if (error==0){

                $('.commentform').html(getMessageHtml());

                $(':input','.commentform')
                .not(':button, :submit, :reset, :hidden')
                .val('')
                .removeAttr('checked')
                .removeAttr('selected');

                $.post('/async/comentario', respuesta.dataForm[0]);

                return false;
            }else{
                $('#submit-comentario').show();
            }
        }
        

    });


}

function getMessageHtml()
{
    var o = '<ul class="mensaje">';
    o += '<li> Gracias por enviarnos su comentario</li>';
    o += '<li> En breve se publicar&aacute;</li>';
    o += '</ul>';

    return o;
}

function getErrorHtml(formErrors , id)
{
    var o = '<ul id="errors-'+id+'" class="errors">';
    for(errorKey in formErrors)
    {
        o += '<li>' + formErrors[errorKey] + '</li>';
    }
    o += '</ul>';
    return o;
}

});
