$(document).ready(function(){
  var lang=$('.lang').val();

  switch(lang){
    case "pt": msgSend_1="Destinatários válidos";
               msgSend_2="Por favor indique o(s) seguinte(s) dado(s):";
               msgSend_3="Não foi possível enviar o email:";
               msgSend_4="O email foi enviado com sucesso";
               msgSend_5="válido";
               msgSend_Name="Nome";
               msgSend_Email="Email";
               msgSend_To="Destinatários";
               msgComment_1="Por favor indique o seu comentário";
               msgComment_2="O seu comentário foi guardado com sucesso";
               msgRecommendation="A sua recomendação foi registada com sucesso.";
               break;

    case "gb": msgSend_1="Available recipients";
               msgSend_2="Please, indicate following information:";
               msgSend_3="Unable to send email:";
               msgSend_4="Email was successfully sent";
               msgSend_5="Available";
               msgSend_Name="Name";
               msgSend_Email="Email";
               msgSend_To="Recipient's email";
               msgComment_1="Please write your comment";
               msgComment_2="Your comment has been successfully saved";
               msgRecommendation="Your recommendation has been successfully saved.";
               break;

    default:   msgSend_1="Destinatários válidos";
               msgSend_2="Por favor indique o(s) seguinte(s) dado(s):";
               msgSend_3="Não foi possível enviar o email:";
               msgSend_4="O email foi enviado com sucesso";
               msgSend_5="válido";
               msgSend_Name="Name";
               msgSend_Email="Email";
               msgSend_To="Destinatários";
               msgComment_1="Por favor indique o seu comentário";
               msgComment_2="O seu comentário foi guardado com sucesso";
               msgRecommendation="A sua recomendação foi registada com sucesso.";
  }
  
  if($('#user_id').val()!=0){
    $('div#comentar').css('display','block');
    $('div#comment-container').css('display','block');
  }else{
    $('div#comentar').css('display','none');
    $('div#comment-container').css('display','none');
  }

  //ajax send email
  $('.submit_email').click(function(){
    var vinho_id=$(this).attr('vinho_id');
    var vinho_nome=$(this).attr('vinho_nome');

    function trim(str, chars) {
  	  return ltrim(rtrim(str, chars), chars);
    }

    function ltrim(str, chars) {
    	chars = chars || "\\s";
    	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    }

    function rtrim(str, chars) {
    	chars = chars || "\\s";
    	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
    }

    function isValidEmail(email){
      if(email===null)
        return false;

      var re = new RegExp('^[\_]*([a-z0-9]+(\.|\_*)?)+@([a-z][a-z0-9\-]+(\.|\-*\.))+[a-z]{2,6}$');
      m = email.match(re);

      return (m!==null);
    }
  
    function validContentEmail(){
      var obj_list=[];
      obj_list['Nome']=$('input#sender_name');
      obj_list['Email']=$('input#sender_email');
      obj_list['Destinatários']=$('input#dest_emails');

      var errors='';

      for (var name in obj_list)
    	{
        var val=obj_list[name].val();
        
        if (name=='Nome'){
          txtName=msgSend_Name;
        }else if (name=='Email'){
          txtName=msgSend_Email;
        }else{
          txtName=msgSend_To;
        }
        
        if(val=='')
          errors+='<li>'+txtName+'</li>';
        else if(name=='Email'){
          if(!isValidEmail(val))
            errors+='<li>'+txtName+' '+msgSend_5+'</li>';   //errors+='<li>'+msgSend_5+' email</li>';
        }else if(name=='Destinatários'){
          var dest_emails=val.replace(' ','').split(',');
          for(var i=0;i<dest_emails.length;i++){
            var email_addr=trim(dest_emails[i]);
            if(email_addr!='' && !isValidEmail(email_addr)){
              errors+='<li>'+msgSend_1+'</li>';
              break;
            }
          }
        }
    	}

      if(errors!=''){
        var errors_html='<p>'+msgSend_2+':</p><ul style="list-style-type:disc;margin-left:16px;">'+errors+'</ul>';
        $('#email-result').removeClass('successBox').addClass('errorBox').html(errors_html).show();
        return false;
      }

      return true;
    }

    if(!validContentEmail())
      return false;

    $('#email-send-progress').show();
    $.post('/scripts/lstVinhos.php?id='+vinho_id+'&title='+vinho_nome+'&q='+Math.random().toString(),
          $("#email_form").serialize(),
          function(error){
            $('#email-send-progres').hide();
            if(error!=''){
              var errors_html='<p>'+msgSend_3+':</p><p>'+error+'</p>';
              $('#email-result').removeClass('successBox').addClass('errorBox').html(errors_html).show();
              return false;
            }else{
              $('#email-send-progress').hide();
              var success_html='<p>'+msgSend_4+'</p>';
              $('#email-result').removeClass('errorBox').addClass('successBox').html(success_html).show();
              return false;
            }
          }
        );
    
  });
  
  //recomendar
  $('.recomendar').click(function(){
  var vinho_id=$(this).attr('vinho_id');
  var cliente_id=$(this).attr('cliente_id');

   $.post('/scripts/addRecomendacao.php?id='+vinho_id+'&cliente='+cliente_id+'&lang='+lang+'&q='+Math.random().toString(),
    function(error){
      if(error!=''){
        alert(error);
      }else{
        alert(msgRecommendation);
      }
    }
  );
  
  return false;
  
});

  //ajax save comment
  $('.submit_comment').click(function(){
    vinho_id=$(this).attr('vinho_id');
    cliente_id=$(this).attr('cliente_id');

    //1. validar se o camentário está preenchido
    var comentario=$('textarea#comment_comentario').val();

    if (comentario==''){
      var errors_html='<p style="padding:5px;">'+msgComment_1+'</p>';
      $('#comment-result').removeClass('successBox').addClass('errorBox').html(errors_html).show();
      return false;
    }


    //2. guardar na base de dados
    $('#comment-send-progress').show();

    $.post('/scripts/saveComment.php?id='+vinho_id+'&cliente='+cliente_id+'&comment='+comentario+'&lang='+lang+'&q='+Math.random().toString(),
      $("#comment_form").serialize(),
      function(error){
        $('#comment-send-progress').hide();
        if(error!=''){
          var errors_html='<p>'+error+'</p>';
          $('#comment-result').removeClass('successBox').addClass('errorBox').html(errors_html).show();
          $('textarea#comment_comentario').val('');
          return false;
        }else{
          $('#comment-send-progress').hide();
          var success_html='<p>'+msgComment_2+'</p>';
          $('#comment-result').removeClass('errorBox').addClass('successBox').html(success_html).show();

          return false;
        }
      }
    );

  });

});
