/**
 * @author Pablo Beca
 * 
 * MailForm plugin for jQuery
 */


jQuery.fn.mailForm = function()
{
   var oForm = $(this);
   var iSpeed = 250;
   var oMsgBox = null;

   makeMsgBox();
   oForm.show();


   oForm.ajaxForm(
   {
      url:        'share/ajax/contacto.ajax.php',
      type:       'POST', 
      dataType:   'json',
      beforeSubmit: function()
      {
         oForm.hide(iSpeed);
         showMsgBox('process', 'Enviando tu mensaje', 'Aguarda unos segundos por favor... Gracias.');
      },
      
      success: function(oR)
      {
         switch (oR.stt)
         {
            case 1:
               showMsgBox('success', 'Mensaje enviado', '<strong>Gracias por contactarte!</strong>. Pronto nos vamos a poner en contacto con vos.');
               
               oMsgBox.after('<div id="blqSuccess"></div>');
               $('#blqSuccess').load('share/ajax/inc.success-msg.php');
               break;


            case 0:
               window.alert('Disculpa, encontramos algunos problemas en los datos. Revísa los campos marcados con rojo por favor y vuelve a enviar tu mensaje.');
               oMsgBox.hide();
               oForm.show(iSpeed);

               showError('txtNombre', 	oR.el.nm);
               showError('txtTelefono',  oR.el.tel);
               showError('txtEmail', 	oR.el.eml);
               showError('txtCiudad', 	oR.el.cty);
               showError('txtMensaje', 	oR.el.msj);
               break;
               
            default:
               window.alert('Lo siento, se produjo un error desconocido');
               break;
         }
      },
      error: function()
      {
         window.alert('Lo siento, se produjo un error desconocido');
      }
   });
   
   
   function makeMsgBox()
   {
      oForm.after('<div id="boxAjaxMsg" class="msgBox"><h3></h3><p></p></div>');      
      oMsgBox = $('#boxAjaxMsg');
      oMsgBox.hide();
   }



   function showMsgBox(sClass, sTtl, sMsg)
   {
      oMsgBox.addClass(sClass);
	  
      $('h3', oMsgBox).html(sTtl);
      $('p', oMsgBox).html(sMsg);
      
      oMsgBox.show(iSpeed);
   }



   function showError(sFieldId, sMsg)
   {
      sFieldErrorId = 'fe-' + sFieldId;
      sFieldWrapperId = 'fw-' + sFieldId;
      
      if (sMsg)
      {
         if ($('#' + sFieldErrorId, oForm).length == 0)
         {
            $('#' + sFieldWrapperId, oForm).append('<div class="fe" id="' + sFieldErrorId + '"></div>');
         }

         $('#' + sFieldErrorId, oForm).html(sMsg);
         $('#' + sFieldWrapperId, oForm).addClass('error');
      }
      else
      {
         $('#' + sFieldErrorId, oForm).remove();
         $('#' + sFieldWrapperId, oForm).removeClass('error');
      }
   }
};



$(function()
{
   $('#frmCto').mailForm();
});
