Built motion from commit c671bd6.|0.0.103
[motion.git] / server / components / xchatty / xchatty.js
index d312091..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,9 +105,9 @@ 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("click", ".xc_btn_signup", xChatty.signUpClick);
         jQuery(document).on("submit", ".xc_form_signup", xChatty.signUpSubmit);
         jQuery(document).on("click", ".xc_btn_send", xChatty.sendClick);
         jQuery(document).on("submit", ".xc_form_reply", xChatty.onSendSubmit);
@@ -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,31 +253,109 @@ 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);
         enquiryForm.addClass("xc_enquiry_sending");
         var formData = jQuery(this).serializeArray();
         formData.push({
+            name: 'data[Enquiry][websiteId]',
+            value: xChatty.config.websiteId
+        });
+        formData.push({
             name: 'data[Enquiry][current_page]',
             value: encodeURIComponent(encodeURIComponent(document.URL))
         });
@@ -318,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(),
@@ -326,8 +444,6 @@ var xChatty = {
               if (result.success === true) {
                   jQuery(".xc_notifications_wrapper").slideUp();
                   jQuery("[data-id=" + tmpMessage.id + "]").remove();
-                  // console.log('result.data', result.data);
-                  console.log('result.data', result.messages[0]);
                   // xChatty.addMessageToChat(result.data);
                   xChatty.addMessageToChat(result.messages[0]);
                   for (var k = 0; k < result.messages.length; k++) {
@@ -411,24 +527,40 @@ var xChatty = {
         }
         xChatty.checkStatus(true);
     },
-    signUpClick: function(e) {
-        e.preventDefault();
-        jQuery(".xc_form_signup").submit();
-    },
+    // signUpClick: function(e) {
+    //     e.preventDefault();
+    //     jQuery(".xc_form_signup").submit();
+    // },
     signUpSubmit: function(e) {
         e.preventDefault();
         if (xChatty.config.processingSignUp)
             return false;
+        xChatty.config.processingSignUp = true;
         var validationErrors = {};
-        if (jQuery.trim(jQuery(".xc_input_fullname").val()) === '' || jQuery(".xc_input_fullname").val() === jQuery(".xc_input_fullname").attr("placeholder")) {
-            validationErrors["fullname"] = [xChatty.Lang.ValidationUsernameRequired];
-        }
-        if (!xChatty.config.hideEmail && (jQuery.trim(jQuery(".xc_input_email").val()) === '' || jQuery(".xc_input_email").val() === jQuery(".xc_input_email").attr("placeholder"))) {
-            validationErrors["email"] = [xChatty.Lang.ValidationEmailRequired];
-        }
-        if (validationErrors.hasOwnProperty("fullname") || validationErrors.hasOwnProperty("email")) {
-            xChatty.renderNotifications(validationErrors, true);
-            return;
+        var signupForm = jQuery(".xc_form_signup");
+        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')];
+          }
+        });
+        // if (jQuery.trim(jQuery(".xc_input_fullname").val()) === '' || jQuery(".xc_input_fullname").val() === jQuery(".xc_input_fullname").attr("placeholder")) {
+        //     validationErrors["fullname"] = [xChatty.Lang.ValidationUsernameRequired];
+        // }
+        // if (!xChatty.config.hideEmail && (jQuery.trim(jQuery(".xc_input_email").val()) === '' || jQuery(".xc_input_email").val() === jQuery(".xc_input_email").attr("placeholder"))) {
+        //     validationErrors["email"] = [xChatty.Lang.ValidationEmailRequired];
+        // }
+        // if (validationErrors.hasOwnProperty("fullname") || validationErrors.hasOwnProperty("email")) {
+        //     xChatty.renderNotifications(validationErrors, true);
+        //     return;
+        // }
+        if (Object.keys(validationErrors).length > 0) {
+          xChatty.renderNotifications(validationErrors,true);
+          xChatty.config.processingSignUp = false;
+          return;
         }
         var now = new Date();
         var dateStr = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
@@ -445,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(),
@@ -459,8 +591,11 @@ var xChatty = {
                     // xChatty.config.signedUp = true;
                     xChatty.setHeaderText();
                     xChatty.disableSignUpForm('xc_form_signup',true);
+                    xChatty.removeOldMessages();
                     xChatty.checkStatus();
-                    xChatty.handleNoAgentResponse();
+
+                    // xChatty.handleNoAgentResponse();
+
                     // xChatty.readMessages();
                     // jQuery(".xc_signup_wrapper").hide();
                     // jQuery(".xc_conversation").show();
@@ -470,6 +605,7 @@ var xChatty = {
                 }
             },
             error: function(err) {
+              xChatty.config.processingSignUp = false;
               var error = {
                 'message': 'Service temporarily unavailable. We back as soon as possible!'
               };
@@ -480,39 +616,6 @@ var xChatty = {
             }
         });
     },
-    handleNoAgentResponse: function() {
-      xChatty.config.timerSignupResponse = setTimeout(function() {
-        if(xChatty.config.processingSignUp && !xChatty.config.signedUp) {
-          xChatty.config.processingSignUp = false;
-          clearTimeout(xChatty.config.timerCheckStatus);
-          var formData = jQuery(this).serializeArray();
-          formData.push({
-              name: 'data[unserved]',
-              value: true
-          });
-          jQuery.ajax({
-              url: xChatty.config.rootPath + "unserved",
-              data: formData,
-              dataType: "jsonp",
-              jsonpCallback: xChatty.getJsonpCallbackName(),
-              success: function(result) {
-                  if (result.success === true) {
-                    var error = {
-                      'message': 'In this moment all agents are busy. Try again!'
-                    };
-                    xChatty.renderErrors(error, true);
-                    xChatty.setHeaderText();
-                    xChatty.disableSignUpForm('xc_form_signup',false);
-                    // xChatty.config.visitor = {
-                    //     fullname: "",
-                    //     avatar: ""
-                    // };
-                  }
-              }
-          });
-        }
-      }, 80*1000); //Now is static, but we have to compute the total timeout for the chat website (sum of timeout of application)
-    },
     setHeaderText: function() {
         if (xChatty.config.signedUp === true)
             jQuery(".xc_chat_head-title").html(xChatty.Lang.HeaderCurrentlyChatting);
@@ -523,30 +626,74 @@ var xChatty = {
         else
             jQuery(".xc_chat_head-title").html(xChatty.Lang.HeaderOffline);
     },
-    checkStatus: function(async) {
-        var chatHtml = '<div class="xc_chat_container" style="display: none;"><div class="xc_chat_head '+xChatty.config.headerShape+'"><i class="xc_header_icon"><span class="xc_notification_badge"><span class="xc_notification_badge_number"></span></span></i><span class="xc_chat_head-title">{HeaderText}</span></div><div class="xc_chat_toggle_container"><div class="xc_sub-head-spacer"></div><div class="xc_notifications_wrapper"><!--<i class="xc_btn_notifications_close">&times;</i>--><ul class="xc_errorlist"></ul></div><div class="xc_enquiry_wrapper"><form class="xc_form_enquiry" accept-charset="UTF-8"><p>{OfflineMessage}</p><input maxlength="45" type="text" name="data[Enquiry][fullname]" placeholder="{UsernamePlaceholder}" class="xc_input_enquiry_fullname" /><input maxlength="85" type="text" name="data[Enquiry][email]" placeholder="{EmailPlaceholder}" class="xc_input_enquiry_email" /><textarea maxlength="1500" placeholder="{EnquiryMessagePlaceholder}" name="data[Enquiry][message]" class="xc_input_enquiry_message"></textarea><a href="#" class="xc_btn_enquiry xc_btn_style">{EnquiryButtonText}</a></form></div><div class="xc_signup_wrapper"><form class="xc_form_signup" accept-charset="UTF-8"><p>{OnlineMessage}</p><input maxlength="45" type="text" name="data[Discussion][fullname]" placeholder="{UsernamePlaceholder}" class="xc_input_fullname" /><input maxlength="85" type="text" name="data[Discussion][email]" placeholder="{EmailPlaceholder}" class="xc_input_email" /><input type="hidden" class="xc_input_visitor_time" name="data[Discussion][visitor_time]" /><a href="#" class="xc_btn_signup xc_btn_style">{StartChatButtonText}</a></form></div><div class="xc_conversation"><div class="xc_conversation_container"><p class="xc_message_intro" data-id="-10">{FirstMessageText}</p></div><div class="xc_composing_container"></div><form class="xc_form_reply" accept-charset="UTF-8"><div class="xc_exit_chat_container"><div class="xc_download_transcript_container" style="display:none;"><a href="'+xChatty.config.rootPath + 'transcript" class="xc_download_transcript">{DownloadTranscript}</a></div><a href="#" class="xc_btn_exit_chat">{ExitChatButtonText}</a><div class="xc_exit_chat_confirmation_wrapper" style="display: none;"><span>{ExitChatQuestionText} </span><a href="#" class="xc_btn_exit_chat_confirm">{ExitChatButtonConfirmText}</a><span> | </span><a href="#" class="xc_btn_exit_chat_cancel">{ExitChatButtonCancelText}</a></div></div><textarea maxlength="750" placeholder="{MessagePlaceholderText}" name="data[Message][message]" class="xc_input_message"></textarea><a href="#" class="xc_btn_send xc_btn_style">{MessageSendButtonText}</a></form></div><div class="xc_footer"><div class="xc_powered"><a>Powered by Xenialab | Trademark xCALLY</a></div></div></div></div>';
-        if (jQuery(".xc_chat_container").length === 0) {
-            for (i in xChatty.Lang) {
-                chatHtml = chatHtml.replace(new RegExp("{" + i + "}", "gm"), xChatty.Lang[i]);
+    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');
+                  }
+                }
+              }
             }
-            jQuery('body').append(chatHtml);
-            if (xChatty.config.hideEmail) {
-                jQuery(".xc_chat_container .xc_input_email").hide();
+          }
+        });
+    },
+    getHTMLTemplate: function() {
+      jQuery.ajax({
+          url: xChatty.config.rootPath + xChatty.config.websiteId + '/html',
+          dataType: 'jsonp',
+          crossDomain: true,
+          success: function (data) {
+            if (jQuery(".xc_chat_container").length === 0) {
+              for (var i in xChatty.Lang) {
+                data = data.replace(new RegExp("{" + i + "}", "gm"), xChatty.Lang[i]);
+              }
+              jQuery('body').append(data);
             }
-        }
-        if (jQuery("#xc_stylesheet").length === 0) {
-            var xcCss = document.createElement('link');
-            xcCss.setAttribute('rel', 'stylesheet');
-            xcCss.type = 'text/css';
-            xcCss.id = 'xc_stylesheet';
-            xcCss.href = xChatty.config.rootPath + "/" + xChatty.config.websiteId + "/styles";
-            document.body.appendChild(xcCss);
-        }
-        if(xChatty.config.downloadTranscript) {
-          jQuery(".xc_download_transcript_container").show();
-        } else {
-          jQuery(".xc_download_transcript_container").hide();
-        }
+            if (jQuery("#xc_stylesheet").length === 0) {
+                var xcCss = document.createElement('link');
+                xcCss.setAttribute('rel', 'stylesheet');
+                xcCss.type = 'text/css';
+                xcCss.id = 'xc_stylesheet';
+                xcCss.href = xChatty.config.rootPath + xChatty.config.websiteId + "/styles";
+                document.body.appendChild(xcCss);
+            }
+            if(xChatty.config.downloadTranscript) {
+              jQuery(".xc_download_transcript_container").show();
+            } else {
+              jQuery(".xc_download_transcript_container").hide();
+            }
+            xChatty.getProactiveActions();
+            xChatty.checkStatus();
+          }
+        });
+    },
+    checkStatus: function(async) {
         clearTimeout(xChatty.config.timerCheckStatus);
         var formData = [];
         if (xChatty.config.isInitialStatusCheck)
@@ -560,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();
@@ -626,13 +784,27 @@ var xChatty = {
                   xChatty.setHeaderText();
                 }
 
-                if(wasSignedUp && result.signed_up === true) {
-                  var duration = xChatty.calculateTimeOutDuration();
-                  xChatty.config.timerReadMessages = setTimeout(function() {
-                    xChatty.readMessages(false);
-                  }, duration);
+                if (!wasSignedUp && xChatty.config.processingSignUp && result.is_unserved) {
+                  xChatty.config.processingSignUp = false;
+                  var error = {
+                    '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();
+                //   // xChatty.config.timerReadMessages = setTimeout(function() {
+                //   //   xChatty.readMessages(false);
+                //   // }, duration);
+                // }
+
             },
             error: function(err) {
               var error = {
@@ -642,9 +814,10 @@ var xChatty = {
             },
             complete: function() {
                 xChatty.setHeaderText();
+                var duration = xChatty.calculateStatusTimeOutDuration();
                 xChatty.config.timerCheckStatus = setTimeout(function() {
                     xChatty.checkStatus(true);
-                }, 25000);
+                }, duration);
             }
         });
     },
@@ -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) {
@@ -971,12 +1145,12 @@ var xChatty = {
                         xChatty.config.decayHistory++;
                     else
                         xChatty.config.decayHistory = 0;
-                    var duration = xChatty.calculateTimeOutDuration();
-                    if (!loadMore) {
-                        xChatty.config.timerReadMessages = setTimeout(function() {
-                            xChatty.readMessages(false);
-                        }, duration);
-                    }
+                    // var duration = xChatty.calculateTimeOutDuration();
+                    // if (!loadMore) {
+                    //     xChatty.config.timerReadMessages = setTimeout(function() {
+                    //         xChatty.readMessages(false);
+                    //     }, duration);
+                    // }
                 } else if (result.success === false) {
                     xChatty.checkStatus(true);
                 } else {}
@@ -988,14 +1162,14 @@ var xChatty = {
               };
               xChatty.renderErrors(error, true);
             },
-            // complete: function() {
-            //   var duration = xChatty.calculateTimeOutDuration();
-            //   if (!loadMore) {
-            //       xChatty.config.timerReadMessages = setTimeout(function() {
-            //           xChatty.readMessages(false);
-            //       }, duration);
-            //   }
-            // }
+            complete: function() {
+              var duration = xChatty.calculateTimeOutDuration();
+              if (!loadMore) {
+                  xChatty.config.timerReadMessages = setTimeout(function() {
+                      xChatty.readMessages(false);
+                  }, duration);
+              }
+            }
         });
     },
     playNotificationSound: function() {
@@ -1020,6 +1194,11 @@ var xChatty = {
         }
         return xChatty.config.defaultTimeout;
     },
+    calculateStatusTimeOutDuration: function() {
+        if (jQuery(".xc_signup_wrapper").is(":visible") && xChatty.config.processingSignUp)
+          return xChatty.config.defaultTimeout;
+        return 15000;
+    },
     getMaxId: function() {
         if (jQuery(".xc_chatrow").length === 0)
             return 0;
@@ -1052,11 +1231,7 @@ var xChatty = {
     },
     disableSignUpForm: function(form, enable) {
       jQuery("." + form + " :input").attr("disabled", enable);
-      if(enable) {
-        jQuery(document).on("click", "." + form + " .xc_btn_signup", function(e) { e.preventDefault();});
-      } else {
-        // jQuery(document).on("click", "." + form + " .xc_btn_signup", xChatty.signUpClick);
-      }
+      jQuery("." + form + " :button").prop("disabled", enable);
     },
     browserTest: function(test) {
         var isOpera = !!(window.opera && window.opera.version);
@@ -1107,14 +1282,14 @@ if (true) {
         xcLoadJS(function() {
             (function($) {
                 jQuery(document).ready(function() {
-                    xChatty.checkStatus(false);
+                    xChatty.getHTMLTemplate();
                 });
             })(jQuery);
         });
     } else {
         (function($) {
             jQuery(document).ready(function() {
-                xChatty.checkStatus(false);
+                xChatty.getHTMLTemplate();
             });
         })(jQuery);
     }