(function( $ ) {
   var params = {
      geoCallback: false
   };
   var msg_params =  {
      emailID: "msg_sender",
      subjectID: "msg_subject",
      submitID: "msg_submit",
      bodyID: "msg_body",
      captionID: "msg_caption",
      target: "info@serenacarhire.com",
      caption: "Ask a Question or Leave a Comment",
      ackMsg: "Your message has been forwarded - Thank You.",
      failMsg: "Sorry, there was an error - unable to deliver your message at this time."
   };
   
   $.fn.serenaInit = function(options)
   {
      if (options) $.extend(params, options);
      
      var that = this;
      function recordGeoData(gd)
      {
         gd = $.parseJSON(gd);
         // record result on body element for use by other scripts
         $('body').data('logvisit_result', gd);
         if (params.geoCallback)
         {
            params.geoCallback(gd, that);
         }
      }

      $.get("/php/hs_logvisit.php?path="+document.location.pathname,
            function(data) { recordGeoData(data); });
   };


   $.fn.serenaMessage = function(options)
   {
      if (options) $.extend(msg_params, options);
      
      var that = this;  // The submit button of the message page
      
      function isValidEmailAddress(emailAddress) {
         var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
         return pattern.test(emailAddress);
      };
      
      function sendMailResponse(r)
      {
         if (r.substr(0, 2) == "OK")
            alert(msg_params.ackMsg);
         else
            alert(msg_params.failMsg);
      }

      function sendMail()
      {
         var sender = $('#'+msg_params.emailID).val();
         if (!sender)
         {
            alert("Please enter a valid email address in 'From:'");
            return;
         }
         if (!isValidEmailAddress(sender))
         {
            alert("The email address you have entered does not appear to be valid - please check it.");
            return;
         }
         sender = encodeURIComponent(sender);
         
         var subject = $('#'+msg_params.subjectID).val();
         subject = encodeURIComponent(subject);
         var msg = $('#'+msg_params.bodyID).val();
         if (!msg)
         {
            alert("You have not entered anything in the message panel.");
            return;
         }
         msg = encodeURIComponent(msg);
  
         var uri = "/php/sendmail.php?from="+sender;  
         uri += "&subject="+subject;
         uri += "&msg="+msg;
      alert(uri);
         $.get(uri, function(data) { sendMailResponse(data); });
      }
      $('#'+msg_params.captionID).html(msg_params.caption);
      that.click(sendMail);
   };
})( jQuery );


