
$(function()
{
  function submit_error(data) {
    $('#error_message').append('<ul></ul>');
    if (data != null) {
      jQuery.each(data.errors,function(key,val)
      {
          $('#error_message ul').append('<li>'+key+':'+val+'</li>');
      });
    }
    $('#success_message').hide();
    $('#error_message').show();

    //reverse the response on the button
    $('button[type="button"]', $form).each(function()
    {
        $btn = $(this);
        label = $btn.prop('orig_label');
        if(label)
        {
            $btn.prop('type','submit' );
            $btn.text(label);
            $btn.prop('orig_label','');
        }
    });
  }

    function after_form_submitted(data)
    {
        if(data.result == 'success')
        {
            $('form#reused_form').hide();
            $('#success_message').show();
            $('#error_message').hide();
        }
        else
        {
            submit_error(data);
        }
    }


	$('#reused_form').submit(function(e)
      {
        e.preventDefault();

        $form = $(this);
        //show some response on the button
        $('button[type="submit"]', $form).each(function()
        {
            $btn = $(this);
            $btn.prop('type','button' );
            $btn.prop('orig_label',$btn.text());
            $btn.text('Sending ...');
        });

        //todo fetch error here

        $.ajax({
                type: "POST",
                url: '/contact-form/handler.php',
                data: $form.serialize(),
                success: after_form_submitted,
                dataType: 'json',
                timeout: 3000
        });

      });
});
