/**
 * tell-a-friend.js
 *
 * @author Paul Horton <phorton@doc-net.com>
 * @copyright Doctor Net Limited &copy; 2008
 * @package WebSite.WebSite
 */

function tell_a_friend(str_io) {
   //$('#hidden_update_button').click();
   var int_io_id = -1;
   var str_io_name = "";

   switch (str_io) {
      case 'news':
         int_io_id = $('#int_tell_a_friend_news_id').val()
         str_io_name = 'news';
         break;
      case 'inventory':
      default:
         int_io_id = $('#int_tell_a_friend_product_id').val();
         str_io_name = 'inventory';
   }

   if (validate()) {
      $.ajax({
         async: true,
         type: "POST",
         url: "/ajax-tell-a-friend/tell-a-friend",
         data: "str_io=" + str_io_name + "&int_io_id=" + int_io_id + "&str_your_name=" + encodeURIComponent($('#str_your_name').val()) + "&str_friend_name=" + encodeURIComponent($('#str_friend_name').val()) + "&str_friend_email=" + $('#str_friend_email').val() + "&str_friend_message=" + encodeURIComponent($('#str_friend_message').val()),
         success: function(obj_response) {
            if($('response', obj_response).attr('success') == 'true') {
               alert("Message sent successfully.");
               tb_remove();
            } else {
               if ($('message', obj_response).size() > 0) {
                  str_messages = "<ul>";
                  $('message', obj_response).each(function() {
                     str_messages = str_messages + "<li>" + $(this).text() + "</li>";
                  })
                  str_messages = str_messages +  "</ul>";
                  $('#tell_a_friend_error_messages').html(str_messages);
                  $('#tell_a_friend_error_messages').show();
               } else {
                  $('#tell_a_friend_error_messages').html("There was an error whilst trying to complete your request.");
                  $('#tell_a_friend_error_messages').show();
               }
            }
         },
         error: function(obj, str, exc) {
            // Full on error
            $('#tell_a_friend_error_messages').html("There was an error whilst trying to complete your request.");
            $('#tell_a_friend_error_messages').show();
         }
      });
   }
}

function validate() {
   obj_friend_name = document.getElementById('str_friend_name');
   obj_friend_email = document.getElementById('str_friend_email');

   // Validate Name
   if (obj_friend_name.value.length == 0) {
      alert("Please enter your friend's name and try again.");
      return false;
   }

   // Validate E-mail
   if (obj_friend_email.value.length == 0) {
      alert("The e-mail address you entered (" + obj_friend_email.value + ")is not valid. Please try again.");
      return false;
   }

   return true;
}
