Built motion from commit c671bd6.|0.0.103
[motion.git] / server / components / xchatty / xchatty.js
index 66335b2..e9ae0a5 100644 (file)
@@ -17,6 +17,7 @@ var xChatty = {
         processingSignUp: {{processingSignUp}},
         processingEnquiry: {{processingEnquiry}},
         processingSend: {{processingSend}},
+        processingRating: {{processingRating}},
         visitor: {
             fullname: '',
             avatar: ''
@@ -38,15 +39,16 @@ var xChatty = {
         hideEmail: {{hideEmail}},
         hideOffline: {{hideOffline}},
         headerShape: '{{headerShape}}',
-        downloadTranscript: {{downloadTranscript}}
+        downloadTranscript: {{downloadTranscript}},
+        roomId: 0
     },
     Lang: {
         "HeaderCurrentlyChatting": "Live Chat",
         "HeaderOnline": '{{HeaderOnline}}',
         "HeaderOffline": "{{HeaderOffline}}",
         "OperatorOfflineMessage": "It appears as if all operators are currently offline.",
-        "OfflineMessage": "{{{OfflineMessage}}}",
-        "OnlineMessage": '{{OnlineMessage}}',
+        "OfflineMessage": "{{& OfflineMessage}}",
+        "OnlineMessage": '{{& OnlineMessage}}',
         "UsernamePlaceholder": '{{UsernamePlaceholder}}',
         "EmailPlaceholder": '{{EmailPlaceholder}}',
         "EnquiryMessagePlaceholder": "{{EnquiryMessagePlaceholder}}",
@@ -70,7 +72,14 @@ var xChatty = {
         "ValidationEnquiryMaxLength": "The enquiry may not exceed 1500 characters",
         "ValidationMessageRequired": "Please enter your message",
         "ValidationMessageMaxLength": "The message may not exceed 750 characters",
-        "DownloadTranscript": "Download Transcript"
+        "DownloadTranscript": "Download Transcript",
+        "RatingMessage": "{{& RatingMessage}}",
+        "RatingSendText": "{{RatingSend}}",
+        "RatingSkipText": "{{RatingSkip}}",
+        "MessageAgentsBusy": "{{& MessageAgentsBusy}}",
+        "EmailTitle": "{{EmailTitle}}",
+        "NameTitle": "{{NameTitle}}",
+        "MessageTitle": "{{MessageTitle}}"
     },
     init: function() {
         jQuery(".xc_chat_container").css('margin-bottom', '-50px');
@@ -96,7 +105,7 @@ var xChatty = {
             xChatty.config.windowFocused = false;
         });
         jQuery(document).on("click", ".xc_chat_head", xChatty.headerClick);
-        jQuery(document).on("click", ".xc_btn_enquiry", xChatty.enquiryClick);
+        // jQuery(document).on("click", ".xc_btn_enquiry", xChatty.enquiryClick);
         jQuery(document).on("submit", ".xc_form_enquiry", xChatty.enquirySubmit);
         // jQuery(document).on("click", ".xc_btn_signup", xChatty.signUpClick);
         jQuery(document).on("submit", ".xc_form_signup", xChatty.signUpSubmit);
@@ -108,6 +117,8 @@ var xChatty = {
         jQuery(document).on("click", ".xc_btn_notifications_close", xChatty.btnNotificationsCloseClick);
         jQuery(document).on("keyup", ".xc_chat_container textarea, .xc_chat_container input", xChatty.messageKeyUp);
         jQuery(document).on("keydown", ".xc_input_message", xChatty.messageKeyDown);
+        jQuery(document).on("submit", ".xc_form_rating", xChatty.ratingSubmit);
+        jQuery(document).on("click", ".xc_button_skip_rating", xChatty.skipRatingSubmit);
         jQuery('[placeholder]').each(function() {
             jQuery(this).css('color', '#ccc').val(jQuery(this).attr('placeholder'));
         }).bind('focus', function() {
@@ -120,8 +131,22 @@ var xChatty = {
                 jQuery(this).val(jQuery(this).attr('placeholder')).css('color', '#ccc');
             }
         });
+        window.onbeforeunload = xChatty.handleDocumentUnload;
         xChatty.readMessages();
     },
+    handleDocumentUnload: function() {
+      if (!xChatty.processingSignUp) {
+        jQuery.ajax({
+          url: xChatty.config.rootPath + xChatty.config.websiteId + "/abandon",
+          data: [],
+          dataType: "jsonp",
+          complete: function() {
+            return null;
+          }
+        });
+      }
+      return null;
+    },
     initAnimateHover: function() {
         if (xChatty.config.animateHover !== true)
             return;
@@ -165,10 +190,10 @@ var xChatty = {
             }
         });
     },
-    enquiryClick: function(e) {
-        e.preventDefault();
-        jQuery(".xc_form_enquiry").submit();
-    },
+    // enquiryClick: function(e) {
+    //     e.preventDefault();
+    //     jQuery(".xc_form_enquiry").submit();
+    // },
     btnExitChatClick: function(e) {
         e.preventDefault();
         jQuery(".xc_exit_chat_confirmation_wrapper").show();
@@ -184,17 +209,28 @@ var xChatty = {
             value: true
         });
         jQuery.ajax({
-            url: xChatty.config.rootPath + "signout",
+            url: xChatty.config.rootPath + xChatty.config.websiteId + "/signout",
             data: formData,
             dataType: "jsonp",
             jsonpCallback: xChatty.getJsonpCallbackName(),
             success: function(result) {
                 if (result.success === true) {
-                    xChatty.resetDefaultState();
+                    // xChatty.resetDefaultState();
+                    xChatty.config.signedUp = false;
+                    xChatty.config.visitor = {
+                        fullname: "",
+                        avatar: ""
+                    };
+                    jQuery(".xc_conversation_container").empty();
+                    jQuery(".xc_conversation_container").html('<p class="xc_message_intro" data-id="-10">' + xChatty.Lang.FirstMessageText + '</p>');
+                    jQuery(".xc_exit_chat_confirmation_wrapper").hide();
+                    jQuery(".xc_btn_exit_chat").show();
+                    jQuery(".xc_conversation").hide();
+                    jQuery('.xc_rating_wrapper').show();
                 } else {}
             },
             complete: function() {
-                xChatty.checkStatus(true);
+                // xChatty.checkStatus(true);
             }
         });
     },
@@ -203,6 +239,10 @@ var xChatty = {
         jQuery(".xc_exit_chat_confirmation_wrapper").hide();
         jQuery(".xc_btn_exit_chat").show();
     },
+    removeOldMessages: function () {
+      jQuery(".xc_conversation_container").empty();
+      jQuery(".xc_conversation_container").html('<p class="xc_message_intro" data-id="-10">' + xChatty.Lang.FirstMessageText + '</p>');
+    },
     resetDefaultState: function() {
         xChatty.config.signedUp = false;
         xChatty.config.visitor = {
@@ -213,25 +253,99 @@ var xChatty = {
         jQuery(".xc_conversation_container").html('<p class="xc_message_intro" data-id="-10">' + xChatty.Lang.FirstMessageText + '</p>');
         jQuery(".xc_exit_chat_confirmation_wrapper").hide();
         jQuery(".xc_btn_exit_chat").show();
+        jQuery('.xc_rating_wrapper').hide();
+        jQuery('.xc_form_rating')[0].reset();
         jQuery(".xc_chat_head").trigger("click");
     },
+    skipRatingSubmit: function (e) {
+      e.preventDefault();
+      if (xChatty.config.processingRating)
+        return false;
+      xChatty.config.processingRating = true;
+      var formData = [];
+      formData.push({
+          name: 'data[Rating][room_id]',
+          value: xChatty.config.roomId
+      });
+      jQuery.ajax({
+          url: xChatty.config.rootPath + "rating",
+          data: formData,
+          dataType: "jsonp",
+          success: function(result) {
+              xChatty.config.processingRating = false;
+              xChatty.resetDefaultState();
+          },
+          error: function(err) {
+            var error = {
+              'message': 'Service temporarily unavailable. We back as soon as possible!'
+            };
+            xChatty.renderErrors(error, true);
+            // xChatty.config.timerSendMessages = setTimeout(function() {
+            //   xChatty.handleAjaxSubmitCall(formData, enquiryForm);
+            // }, 5000);
+          }
+      });
+    },
+    ratingSubmit: function (e) {
+      e.preventDefault();
+      if (xChatty.config.processingRating)
+        return false;
+      xChatty.config.processingRating = true;
+      var formData = jQuery(this).serializeArray();
+      formData.push({
+          name: 'data[Rating][room_id]',
+          value: xChatty.config.roomId
+      });
+      jQuery.ajax({
+          url: xChatty.config.rootPath + "rating",
+          data: formData,
+          dataType: "jsonp",
+          success: function(result) {
+              xChatty.config.processingRating = false;
+              xChatty.resetDefaultState();
+          },
+          error: function(err) {
+            var error = {
+              'message': 'Service temporarily unavailable. We back as soon as possible!'
+            };
+            xChatty.renderErrors(error, true);
+            // xChatty.config.timerSendMessages = setTimeout(function() {
+            //   xChatty.handleAjaxSubmitCall(formData, enquiryForm);
+            // }, 5000);
+          }
+      });
+    },
     enquirySubmit: function(e) {
         e.preventDefault();
         if (xChatty.config.processingEnquiry)
             return false;
         var validationErrors = {};
-        if (jQuery.trim(jQuery(".xc_input_enquiry_fullname").val()) === '' || jQuery(".xc_input_enquiry_fullname").val() === jQuery(".xc_input_enquiry_fullname").attr("placeholder")) {
-            validationErrors["fullname"] = [xChatty.Lang.ValidationUsernameRequired];
-        }
-        if (jQuery.trim(jQuery(".xc_input_enquiry_email").val()) === '' || jQuery(".xc_input_enquiry_email").val() === jQuery(".xc_input_enquiry_email").attr("placeholder")) {
-            validationErrors["email"] = [xChatty.Lang.ValidationEmailRequired];
-        }
-        if (jQuery.trim(jQuery(".xc_input_enquiry_message").val()) === '' || jQuery(".xc_input_enquiry_message").val() === jQuery(".xc_input_enquiry_message").attr("placeholder")) {
-            validationErrors["message"] = [xChatty.Lang.ValidationEnquiryRequired];
-        }
-        if (validationErrors.hasOwnProperty("fullname") || validationErrors.hasOwnProperty("email") || validationErrors.hasOwnProperty("message")) {
-            xChatty.renderNotifications(validationErrors, true);
-            return;
+        var signupForm = jQuery(".xc_form_enquiry");
+        jQuery('.xc_form_enquiry :input').each(function () {
+          var el = jQuery(this);
+          if (el.val() === el.attr('placeholder')) {
+            el.val('');
+          }
+          if ((jQuery.trim(el.val()) === '' || el.val() === el.attr('placeholder')) && el.attr('required') === 'required' ) {
+            validationErrors[el.attr('id')] = ['Please enter the field ' + el.attr('data-label')];
+          }
+        });
+        // if (jQuery.trim(jQuery(".xc_input_enquiry_fullname").val()) === '' || jQuery(".xc_input_enquiry_fullname").val() === jQuery(".xc_input_enquiry_fullname").attr("placeholder")) {
+        //     validationErrors["fullname"] = [xChatty.Lang.ValidationUsernameRequired];
+        // }
+        // if (jQuery.trim(jQuery(".xc_input_enquiry_email").val()) === '' || jQuery(".xc_input_enquiry_email").val() === jQuery(".xc_input_enquiry_email").attr("placeholder")) {
+        //     validationErrors["email"] = [xChatty.Lang.ValidationEmailRequired];
+        // }
+        // if (jQuery.trim(jQuery(".xc_input_enquiry_message").val()) === '' || jQuery(".xc_input_enquiry_message").val() === jQuery(".xc_input_enquiry_message").attr("placeholder")) {
+        //     validationErrors["message"] = [xChatty.Lang.ValidationEnquiryRequired];
+        // }
+        // if (validationErrors.hasOwnProperty("fullname") || validationErrors.hasOwnProperty("email") || validationErrors.hasOwnProperty("message")) {
+        //     xChatty.renderNotifications(validationErrors, true);
+        //     return;
+        // }
+        if (Object.keys(validationErrors).length > 0) {
+          xChatty.renderNotifications(validationErrors,true);
+          return;
         }
         xChatty.config.processingEnquiry = true;
         var enquiryForm = jQuery(this);
@@ -322,7 +436,7 @@ var xChatty = {
     },
     handleAjaxSendCall: function(formData, tmpMessage, messageForm) {
       jQuery.ajax({
-          url: xChatty.config.rootPath + "send",
+          url: xChatty.config.rootPath + xChatty.config.websiteId + "/send",
           data: formData,
           dataType: "jsonp",
           jsonpCallback: xChatty.getJsonpCallbackName(),
@@ -421,10 +535,14 @@ var xChatty = {
         e.preventDefault();
         if (xChatty.config.processingSignUp)
             return false;
+        xChatty.config.processingSignUp = true;
         var validationErrors = {};
         var signupForm = jQuery(".xc_form_signup");
-        jQuery('.xc_form_signup input').each(function () {
+        jQuery('.xc_form_signup :input').each(function () {
           var el = jQuery(this);
+          if (el.val() === el.attr('placeholder')) {
+            el.val('');
+          }
           if ((jQuery.trim(el.val()) === '' || el.val() === el.attr('placeholder')) && el.attr('required') === 'required' ) {
             validationErrors[el.attr('id')] = ['Please enter the field ' + el.attr('data-label')];
           }
@@ -441,6 +559,7 @@ var xChatty = {
         // }
         if (Object.keys(validationErrors).length > 0) {
           xChatty.renderNotifications(validationErrors,true);
+          xChatty.config.processingSignUp = false;
           return;
         }
         var now = new Date();
@@ -458,7 +577,7 @@ var xChatty = {
             });
         }
         jQuery.ajax({
-            url: xChatty.config.rootPath + "signup",
+            url: xChatty.config.rootPath + xChatty.config.websiteId + "/signup",
             data: formData,
             dataType: "jsonp",
             jsonpCallback: xChatty.getJsonpCallbackName(),
@@ -472,6 +591,7 @@ var xChatty = {
                     // xChatty.config.signedUp = true;
                     xChatty.setHeaderText();
                     xChatty.disableSignUpForm('xc_form_signup',true);
+                    xChatty.removeOldMessages();
                     xChatty.checkStatus();
 
                     // xChatty.handleNoAgentResponse();
@@ -485,6 +605,7 @@ var xChatty = {
                 }
             },
             error: function(err) {
+              xChatty.config.processingSignUp = false;
               var error = {
                 'message': 'Service temporarily unavailable. We back as soon as possible!'
               };
@@ -505,6 +626,43 @@ var xChatty = {
         else
             jQuery(".xc_chat_head-title").html(xChatty.Lang.HeaderOffline);
     },
+    handleSnippetOpen: function () {
+      if (!jQuery(".xc_chat_toggle_container").is(":visible")) {
+        jQuery(".xc_chat_head").trigger("click");
+      }
+    },
+    getProactiveActions: function () {
+      jQuery.ajax({
+          url: xChatty.config.rootPath + xChatty.config.websiteId + '/proactive',
+          dataType: 'jsonp',
+          crossDomain: true,
+          success: function (data) {
+            if (data.length > 0) {
+              for (var i in data) {
+                if (data.hasOwnProperty(i)) {
+                  var proAction = data[i];
+                  switch (proAction.type) {
+                    case 'mouseOver':
+                      if (proAction.hasOwnProperty('selector') && proAction.selector) {
+                        jQuery(document).on("mouseover", proAction.selector, xChatty.handleSnippetOpen);
+                      }
+                      break;
+                    case 'timeout':
+                      if (proAction.hasOwnProperty('timeout') && proAction.timeout > 0) {
+                        setTimeout(function () {
+                          xChatty.handleSnippetOpen();
+                        }, proAction.timeout * 1000);
+                      }
+                      break;
+                    default:
+                      console.log('Event type not supported');
+                  }
+                }
+              }
+            }
+          }
+        });
+    },
     getHTMLTemplate: function() {
       jQuery.ajax({
           url: xChatty.config.rootPath + xChatty.config.websiteId + '/html',
@@ -512,7 +670,7 @@ var xChatty = {
           crossDomain: true,
           success: function (data) {
             if (jQuery(".xc_chat_container").length === 0) {
-              for (i in xChatty.Lang) {
+              for (var i in xChatty.Lang) {
                 data = data.replace(new RegExp("{" + i + "}", "gm"), xChatty.Lang[i]);
               }
               jQuery('body').append(data);
@@ -530,6 +688,7 @@ var xChatty = {
             } else {
               jQuery(".xc_download_transcript_container").hide();
             }
+            xChatty.getProactiveActions();
             xChatty.checkStatus();
           }
         });
@@ -548,20 +707,31 @@ var xChatty = {
                 value: (jQuery(".xc_chat_toggle_container").is(":visible") && !jQuery(".xc_chat_container").hasClass("xc_chat_closing"))
             });
         jQuery.ajax({
-            url: xChatty.config.rootPath + "status",
+            url: xChatty.config.rootPath + xChatty.config.websiteId + "/status",
             dataType: "jsonp",
             data: formData,
             async: async,
-            jsonpCallback: xChatty.getJsonpCallbackName(),
             success: function(result) {
                 jQuery(".xc_notifications_wrapper").slideUp();
                 var wasSignedUp = xChatty.config.signedUp;
+                if (wasSignedUp && result.signed_up === false) {
+                  clearTimeout(xChatty.config.timerReadMessages);
+                  clearTimeout(xChatty.config.timerCheckStatus);
+                  jQuery(".xc_conversation_container").empty();
+                  jQuery(".xc_conversation_container").html('<p class="xc_message_intro" data-id="-10">' + xChatty.Lang.FirstMessageText + '</p>');
+                  jQuery(".xc_exit_chat_confirmation_wrapper").hide();
+                  jQuery(".xc_btn_exit_chat").show();
+                  jQuery(".xc_conversation").hide();
+                  jQuery('.xc_rating_wrapper').show();
+                  return;
+                }
                 if (result.success) {
                     xChatty.config.visitor.fullname = result.fullname;
                     xChatty.config.visitor.avatar = result.avatar;
                     xChatty.config.signedUp = result.signed_up;
                     xChatty.config.isOnline = result.online;
                     xChatty.config.hasSessionSaf = result.has_session_saf;
+                    xChatty.config.roomId = result.room_id;
                 }
                 if (result.success && result.signed_up === false && xChatty.config.signedUp) {
                     xChatty.resetDefaultState();
@@ -617,13 +787,16 @@ var xChatty = {
                 if (!wasSignedUp && xChatty.config.processingSignUp && result.is_unserved) {
                   xChatty.config.processingSignUp = false;
                   var error = {
-                    'message': 'In this moment all agents are busy. Try again!'
+                    'message': xChatty.Lang.MessageAgentsBusy
                   };
                   xChatty.renderErrors(error, true);
                   xChatty.setHeaderText();
                   xChatty.disableSignUpForm('xc_form_signup',false);
                 }
 
+                jQuery('.xc_rating_wrapper').hide();
+                jQuery('.xc_form_rating')[0].reset();
+
                 // if(wasSignedUp && result.signed_up === true) {
                 //   xChatty.readMessages(false);
                 //   // var duration = xChatty.calculateTimeOutDuration();
@@ -653,7 +826,7 @@ var xChatty = {
         var cStr = parseInt(new Date().getTime() / 1000).toString().substring(5) + (Math.random() + ' ').substring(5, 10);
         var mult = parseInt(cStr.charAt(Math.floor(Math.random() * cStr.length)));
         mult = (mult === 0 || mult === 1) ? mult + 2 : mult;
-        var cStr = mult.toString() + cStr.toString() + (cStr * mult).toString();
+        cStr = mult.toString() + cStr.toString() + (cStr * mult).toString();
         callback += cStr.toString().split("").reverse().join("");
         return callback;
     },
@@ -667,7 +840,7 @@ var xChatty = {
             jQuery(".xc_notifications_wrapper").removeClass("xc_notification_error");
         }
         jQuery(".xc_notifications_wrapper ul.xc_errorlist").html("");
-        for (k in errorMessages) {
+        for (var k in errorMessages) {
             for (var l = 0; l < errorMessages[k].length; l++)
                 jQuery(".xc_notifications_wrapper ul.xc_errorlist").append(jQuery("<li>" + errorMessages[k][l] + "</li>"));
         }
@@ -853,10 +1026,11 @@ var xChatty = {
           }
         ];
         text = " " + text + " ";
+        var regex;
         for (var i = 0; i < smilies.length; i++) {
             for (var j = 0; j < smilies[i].s.length; j++) {
                 var smilie = ' <i style="background-image: url(' + ('{XC_REP}' + '?resource=smilies/' + smilies[i].r + '.png') + ');" class="xc_smilie" >' + jQuery.trim(smilies[i].s[j].toString()) + '</i> ';
-                var regex = new RegExp(xChatty.escapeRegExp(smilies[i].s[j]), 'g');
+                regex = new RegExp(xChatty.escapeRegExp(smilies[i].s[j]), 'g');
                 text = text.replace(regex, smilie);
             }
         }
@@ -871,7 +1045,7 @@ var xChatty = {
                 jQuery(this).addClass("xc_link_internal");
             }
         });
-        var regex = new RegExp(xChatty.escapeRegExp("{XC_REP}"), 'g');
+        regex = new RegExp(xChatty.escapeRegExp("{XC_REP}"), 'g');
         text = jQuery(tmp).html().replace(regex, xChatty.config.assetBase);
         return jQuery.trim(text).replace(/\n/g, '<br />');
     },
@@ -910,7 +1084,7 @@ var xChatty = {
         }
         jQuery.ajax({
             data: requestData,
-            url: xChatty.config.rootPath + "read",
+            url: xChatty.config.rootPath + xChatty.config.websiteId + "/read",
             dataType: "jsonp",
             jsonpCallback: xChatty.getJsonpCallbackName(),
             success: function(result) {