/*******************************

CHATOLIO

CLIENT-SIDE CUSTOM JS FUNCTIONS

*******************************/


Chatolio = {
  store: {},
  dict: {},
  stats: {
    session_id: 0,
    start: 0,
    chats: [],
    lastChatStartedBy: 'rep',
    isOffline: false,
    pages_count: 0,
    ip: '',
    referer: ''
  }
};

/*** dictionary for translation ***/
Chatolio.dict = {
  en: {
    talkingTo             : "You are talking to",
    liveSupport           : "live support",
    webcamComingSoon      : 'Webcam Coming soon..',
    toSendText            : 'to',
    sendButton            : 'Send',
    hideButton            : 'Hide',
    closeButton           : 'Close',
    endDiscussionButton   : 'End discussion',
    endedDiscussionText   : 'The discussion has ended',
    moreInfoText          : 'Do you need more information',
    introText             : 'A member of our online team would want to chat with you. This person is currently available to answer your questions live:',
    webBasedText          : 'Rest assured, this chat tool is fully web-based. When using it, no software will be installed or used on your computer.',
    doAcceptInvitation    : 'do-acceptInvitation',
    doDeclineInvitation   : 'do-declineInvitation',
    doJoinDiscussion      : 'do-joinDiscussion',
    yesEnterChatButton    : 'Yes, enter chat',
    noThanksButton        : 'No Thanks',
    enterNameText         : 'Please enter your name:',
    beginChatButton       : 'Begin chat session',
    askedForChatStatusText: 'A representative will shortly contact you',
    invitedStatusText     : 'A representative offers you some help',
    activeStatusText      : 'You are currently in discussion',
    inactiveStatusText    : 'The discussion became inactive',
    endedStatusText       : 'The discussion ended.',
    disturbStatusText     : 'You are in "do not disturb" mode',
    offlineStatusText     : 'You are offline',
    askForChatButton      : 'Ask for chat',
    openChatButton        : 'Open chat',
    showChatButton        : 'Show chat',
    resumeChatButton      : 'Resume chat',
    nameGreeting          : 'Hi, my name is',
    greeting              : "I am here to help you with any questions you may have",

    WhenServiceBusy       : "All our representatives are currently busy",
    WhenServiceOffline    : "Our live chat service is currently closed, please come back later.",
    WhenServiceAvailable  : "A representative will shortly contact you",
    WhenServiceBusy       : "All our representatives are currently busy.",
    WhenServiceBusy2      : "You are next on the waiting line !",
    
    textFromYou           : "(you)",
    
    StatusBusyText        : "I am currently busy helping many customers. This might mean a longer delay for me to be able to answer. Thank you for your patience.",
    
    lastelem              : ""
  },
  fr: {
    talkingTo             : "Vous discutez avec",
    liveSupport           : ": support en ligne",
    webcamComingSoon      : 'Webcam disponible bientôt..',
    toSendText            : 'pour',
    sendButton            : 'Envoyer',
    hideButton            : 'Réduire',
    closeButton           : 'Fermer',
    endDiscussionButton   : 'Terminer discussion',
    endedDiscussionText   : 'La discussion est terminée',
    moreInfoText          : "Avez-vous besoin d'information",
    introText             : 'Un membre de notre équipe voudrait discuter avec vous. Cette personne est présentement disponible pour répondre à vos questions:',
    webBasedText          : "Soyez assuré que cet outil de clavardage s'exploite entièrement à partir du Web. Aucun logiciel ne sera installé ou lancé sur votre ordinateur pendant l'utilisation.",
    yesEnterChatButton    : 'Oui, accepter',
    noThanksButton        : 'Non merci',
    enterNameText         : 'Veuillez entrer votre nom:',
    beginChatButton       : 'Commencer la discussion',
    askedForChatStatusText: 'Un représentant vous contactera sous peu',
    invitedStatusText     : 'Un représentant est disponible pour vous aider',
    activeStatusText      : 'Vous êtes présentement en discussion',
    inactiveStatusText    : 'La discussion est devenue inactive',
    endedStatusText       : 'La discussion est terminée.',
    disturbStatusText     : 'Vous êtes en mode "ne pas déranger"',
    offlineStatusText     : 'Vous êtes hors-ligne',
    askForChatButton      : 'Demander service',
    openChatButton        : 'Commencer la discussion',
    showChatButton        : 'Ouvrir la discussion',
    resumeChatButton      : 'Revenir à la discussion',
    nameGreeting          : "Bonjour, je m'appelle",
    greeting              : "Je suis ici pour vous conseiller et pour répondre à toutes vos questions",
    
    WhenServiceBusy       : "Tout nos représentants sont présentement occupés",
    WhenServiceOffline    : "Le service d'appel est présentement fermé.  Veuillez réessayer plus tard.",
    WhenServiceAvailable  : "Un représentant vous contactera sous peu",
    WhenServiceBusy       : "Tout nos représentants sont présentement occupés.",
    WhenServiceBusy2      : "Vous êtes la prochaine personne dans la file !",
    
    textFromYou           : "(vous)",
    
    StatusBusyText        : "Je suis présentement occupé à aider plusieurs clients. Ceci peut se traduire par un délai plus long pour vous répondre. Merci de votre patience.",
    
    lastelem              : ""
  }
};
/**********************************/

Chatolio.launcher = function(container, type) {
  this.container = container;
  this.type = type;
  this.connect_uri = "/ardap";
  this.init();
};

Chatolio.launcher.prototype.init = function() {
  var scope = this;
  var chatolio_node = Y.Node.get("#" + scope.container);
  if(chatolio_node) {
    Y.use("io", function() {
      var uri = "/ardap/" + scope.type;
      var cfg = {
        method: "GET",
        on : {
          success : function(id, r, args) {
            var text = Chatolio.evaluateTemplate(r.responseText, Y.get("body").getAttribute("xlang"));
            //var text = r.responseText;
            chatolio_node.set("innerHTML", text);
            scope.loadUserDetails(chatolio_node);
            
            // LF 2009-09-16: to set initial status to custom buttons
            if(chatclient.VisitorConnector.SINGLETON.initialData.service.state == 'OFFLINE') {
              Chatolio.triggerStatusUpdate({state: 'OFFLINE'});
            } else {
              Chatolio.triggerStatusUpdate(chatclient.VisitorConnector.SINGLETON.initialData.visitor);
            }
            
            // LF 2009-11-02: stats
            window.setInterval(function(){Chatolio.sendStats()}, 30000);
          },
          
          failure : function(id, r, args) {
            chatolio_node.set("innerHTML", "Unable to initialize chat server");
          }
        }
      };
      Y.io(uri, cfg);
    });
  }
};


Chatolio.launcher.prototype.loadUserDetails = function(chatolio_node) {
  var scope = this;
  
  if(scope.type == "dashboard-body") {
    dashboard.start();
  }
  else if(scope.type == "chatclient-body") {
    var url = document.referrer;
    var title = document.referrer.split('/')[2];
    chatclient.start({url: window.location.href, title: jQuery("head title").text()}, {url: url, title: title});
  }
  
  chatolio_node.setStyle("display", "");
};

// LF 2009-06-15: to center client chat window
Chatolio.centerChatWindow = function(event) {
  
  var chatPanel = jQuery('.ChatClient.w-applet');
  /*
  // adjust chat window size
  if(event && event.name == 'operator/inviteVisitor') {
    // set inline style
    chatPanel.css({
      'width': '486px',
      'height': '327px'
    });
  } else {
    // clear inline style
    chatPanel.css({
      'width': '',
      'height': ''
    });
  }
  */
  // center chat window
  var win_w = jQuery(window).width();
  var win_h = jQuery(window).height();
  var chat_w = (chatPanel.width() || 400);
  var chat_h = (chatPanel.height() || 300);
  var parent_offset = jQuery('#ardap-applet-container').offset();
  var stop = jQuery(window).scrollTop();
  
  chatPanel.css({
    'left': ((win_w / 2) - (chat_w / 2) - parent_offset.left),
    'top': ((win_h / 2) - (chat_h / 2) - parent_offset.top + stop - 57) // FC: 57px works on 514ALIX...
  });

};

// LF 2009-07-07: helper function for image loading
Chatolio.onLoadImage = function(selector) {
  
  var imagesToBind = jQuery(selector, jQuery('img'));
  
  imagesToBind.hide();
  
  if(!imagesToBind.data('onloadHandler')) {
  
    imagesToBind
      .bind('load', function() {
         jQuery(this).show();
       })
      .data('onloadHandler', 1);
  };
};

Chatolio.evaluateTemplate = function(template, lang) {

  lang = lang || 'en';
  
  var bundle = Chatolio.dict[lang] || {};
  
  var content = template;
  
  // format: #{{label}}
  
  for(key in bundle) {
    // content = content.replace(/\#\{\{label\}\}/, bundle['label']);
    eval("content = content.replace(/\~\{\{" + key +"\}\}/g, bundle['" + key + "']);");
  };
  
  // remove undefined tags from template
  content = content.replace(/\~\{\{[a-zA-Z0-9_]*\}\}/g, '');
  
  return(content);
};

// LF 2009-10-01
Chatolio.statsObserver = function(event) {
  
  //Chatolio.debug(event);
  
  if(event && event.name) {
    /*** catch any error ***/
    try {
      
      // rep_id when we are in discussion.
      var repid = jQuery(chatclient.VisitorConnector.SINGLETON.chatClient.ui).data('repid') || 0;
      
      // get cookie if it exists
      var jsonObj = Y.Cookie.getSub("chatolio", "stats", function(jsonString) {
        return Y.JSON.parse(jsonString);
      });
      
      if(jsonObj) {
        // if there was a cookie, we update local stats object
        Chatolio.stats = jsonObj;
      } else {
        // if there was no cookie, we get stats from local stats object
        jsonObj = Chatolio.stats;
      }
      
      /********* START OR CLOSE A SESSION ********/
      if(event.name.search(/service/) > -1) {
        // if service is closed *AND* there is no discussion
        if(event.name.search(/close/) > -1) {
          
          if(!repid) {
            Chatolio.stats = {
              session_id: 0,
              start: 0,
              chats: [],
              lastChatStartedBy: 'rep',
              isOffline: true,
              pages_count: 0,
              ip: '',
              referer: ''
            };
          };
          
          Chatolio.stats.isOffline = true;
          //throw('service is OFFLINE');
        } else {
          Chatolio.stats.pages_count = Chatolio.stats.pages_count || 1;
          Chatolio.stats.isOffline = false;
        }
      }
      
      if(event.name.search(/visitPage/) > -1) {
        // if service is closed *AND* there is no discussion
        if(chatclient.VisitorConnector.SINGLETON.initialData.service.state == 'OFFLINE') {
          
          if(!repid) {
            Chatolio.stats = {
              session_id: 0,
              start: 0,
              chats: [],
              lastChatStartedBy: 'rep',
              isOffline: true,
              pages_count: 0
            };
          };
          
          Chatolio.stats.isOffline = true;
          //throw('service is OFFLINE');
        } else {
          Chatolio.stats.isOffline = false;
        };
        Chatolio.stats.start = Chatolio.stats.start || event.source.time * 1000;
        Chatolio.stats.end = Chatolio.stats.end || 0;
        Chatolio.stats.pages_count = Chatolio.stats.pages_count || 0;
        Chatolio.stats.ip = event.source.ip || '';
        Chatolio.stats.referer = event.data.referer.url || '';
        Chatolio.stats.pages_count++;
      }
      /*********************************************/
      
      // if the user asked for chat, we set the started_by flag to 'user'
      if(event.name.search(/askForOperator/) > -1) {
        Chatolio.stats.lastChatStartedBy = 'user';
      }
      
      // when the operator invites the visitor
      if(event.name.search(/inviteVisitor/) > -1) {
        
      }
      
      /* START A CHAT */
      if(event.name.search(/joinDiscussion/) > -1 || event.name.search(/acceptInvitation/) > -1) {
        var discussionID = 'id_' + event.source.discussionID || event.source.discussions[0];
        Chatolio.stats.chats = Chatolio.stats.chats || [];
        //Chatolio.stats.chats[discussionID] = Chatolio.stats.chats[discussionID] || {};
        
        if(Chatolio.stats.chats.length == 0 || Chatolio.stats.chats[Chatolio.stats.chats.length - 1].end) {
          
          Chatolio.stats.chats.push({
            start: event.source.time * 1000,
            end: 0,
            started_by: Chatolio.stats.lastChatStartedBy,
            ended_by: 'user',
            rep_id: repid
          });
          
        }
        
      }
      
      /* CLOSE A CHAT */
      if(event.name.search(/cancelDiscussion/) > -1) {
        
        //var discussionID = 'id_' + event.source.discussionID;
        Chatolio.stats.chats = Chatolio.stats.chats || [];
        //Chatolio.stats.chats[discussionID] = Chatolio.stats.chats[discussionID] || {};
        
        var discussion = Chatolio.stats.chats[Chatolio.stats.chats.length - 1];
        //discussion.end = event.source.time * 1000;
        
        if(event.name.search(/visitor/) > -1) {
          discussion.ended_by = 'user';
        } else {
          discussion.ended_by = 'rep';
        }
        
        Chatolio.stats.lastChatStartedBy = 'rep';
        
        // IF WE ARE OFFLINE, CALL Chatolio.sendStats() before resetting Chatolio.stats
        if(Chatolio.stats.isOffline) {
          
          // update cookie before sending stats
          // JSON encode and update cookie (expires in 5 minutes for session)
          var jsonString = Y.JSON.stringify(Chatolio.stats);
          Y.Cookie.setSub("chatolio", "stats", jsonString, {
            path: "/",
            expires: new Date(new Date().getTime() + (60000 * 5))
          });
          
          // send stats
          Chatolio.sendStats();
          Chatolio.stats = {
            session_id: 0,
            start: 0,
            chats: [],
            lastChatStartedBy: 'rep',
            isOffline: true,
            pages_count: 0
          };
          
          // exit
          //throw('close session after chat');
        }
        
      }
      
      /* REGISTER A MESSAGE IN A CHAT */
      if(event.name.search(/message/) > -1) {
        //var discussionID = 'id_' + (event.source.discussionID || event.source.uid);
        Chatolio.stats.chats = Chatolio.stats.chats || [];
        //Chatolio.stats.chats[discussionID] = Chatolio.stats.chats[discussionID] || {};
        
        var discussion = Chatolio.stats.chats[Chatolio.stats.chats.length - 1];
        
        discussion.messages = discussion.messages || [];
        // we ignore 'pre-message' type
        if(event.data.message.type == 'text') {
          discussion.messages.push({
            timestamp: event.data.message.time * 1000,
            direction: (event.data.message.author.uid == event.source.visitorID ? 1 : 0),
            message: event.data.message.text
          });
          discussion.end = event.data.message.time * 1000;
        };
      };
      
      // JSON encode and update cookie (expires in 5 minutes for session)
      var jsonString = Y.JSON.stringify(Chatolio.stats);
      Y.Cookie.setSub("chatolio", "stats", jsonString, {
        path: "/",
        expires: new Date(new Date().getTime() + (60000 * 5))
      });
      
    } catch(e) {
      // catch error here
      Chatolio.debug(e);
    };
    
  }

};

Chatolio.clearStats = function() {
  
  // reset page view count
  Chatolio.stats.pages_count = 0;
  
  // clean the chat list
  if(Chatolio.stats.chats.length > 3) {
    Chatolio.stats.chats.shift();
  }
  
  // clear messages in current or last discussion
  if(Chatolio.stats.chats.length > 0) {
    var lastDiscussion = Chatolio.stats.chats[Chatolio.stats.chats.length - 1];
    lastDiscussion.messages = [];
  }
  
  // JSON encode and update cookie (expires in 5 minutes for session)
  var jsonString = Y.JSON.stringify(Chatolio.stats);
  Y.Cookie.setSub("chatolio", "stats", jsonString, {
    path: "/",
    expires: new Date(new Date().getTime() + (60000 * 5))
  });
  
};

Chatolio.sendStats = function(override) {
  
  // rep_id when we are in discussion.
  var repid = jQuery(chatclient.VisitorConnector.SINGLETON.chatClient.ui).data('repid') || 0;
  
  // do not send stats if we are OFFLINE
  if(Chatolio.stats.isOffline && !repid && !override) {
    return;
  }
  
  // get cookie
  var jsonString = Y.Cookie.getSub("chatolio", "stats");
  
  jQuery.ajax({
    url: '/dealersite/chatolio/stats.spy',
    data: {
      data: jsonString,
      cmd: 'submit'
    },
    type: 'POST',
    cache: false,
    dataType: "json",
    success: function(json) {
      Chatolio.stats.session_id = json.session_id || 0;
      Chatolio.clearStats();
    }
  });
};

/* Dealersite Event Trigger */
Chatolio.triggerEventListener = function() {
  var visibleButton = null;
  var panels = jQuery("#ardap-applet-container .VisitorPresence .w-panels > .panel");
  
  panels.each(function(){
    var panel = this;
    if(!jQuery(panel).hasClass('hidden')) {
      var bodies = jQuery(".body", panel);
  
      bodies.each(function(){
        var b = this;
        if(!jQuery(b).hasClass('hidden')) {
          if(!visibleButton) {
            visibleButton = jQuery('input:button', b);
          }
        }
      });      
    }
  });
  
  if(visibleButton) {
    jQuery(visibleButton).click();
  }
}

/* Dealersite Status Change Trigger */
Chatolio.triggerStatusUpdate = function(model) {

  // we keep service status
  Chatolio.store.service = Chatolio.store.service || {};
  
  var updateClass = function(new_class) {
    var b = jQuery(".ardap-notifier-container .ardap-notifier-statusimage");
    b.each(function() {
      var im = this;
      var att = jQuery(im).attr("classstyle");
      var nc = new_class;
      if(att) {
        nc = nc + "-" + att;
      }

      im.className = "ardap-notifier-statusimage " + nc;
      
      var parentLink = $(im).parent();
      var onlinelink = parentLink.attr('onlinelink') || 'JavaScript:Chatolio.triggerEventListener();';
      var offlinelink = parentLink.attr('offlinelink') || 'JavaScript:;';
      if(new_class == 'offline') {
        parentLink.attr('href', offlinelink);
      } else {
        parentLink.attr('href', onlinelink);
      }
    });
    
  };

  if(model && typeof(model.state) != "undefined") {
    switch(model.state) {
      case "VIEWING":
        // When client arrives on a page...
        if(Chatolio.store.service.state == 'OFFLINE') break;
        //Chatolio.debug(model.state);
        updateClass("viewing");
        break;
      case "ASKED_FOR_CHAT":
        if(Chatolio.store.service.state == 'OFFLINE') break;
        //Chatolio.debug(model.state);
        updateClass("askedforchat");
        break;
      case "INVITED":
        if(Chatolio.store.service.state == 'OFFLINE') break;
        //Chatolio.debug(model.state);
        updateClass("invited");
        break;
      case "ENDED":
        if(Chatolio.store.service.state == 'OFFLINE') break;
        //Chatolio.debug(model.state);
        updateClass("ended");
        break;
      case "DO_NOT_DISTURB":
        if(Chatolio.store.service.state == 'OFFLINE') break;
        //Chatolio.debug(model.state);
        updateClass("dnd");
        break;
      case "CHATTING":
        if(Chatolio.store.service.state == 'OFFLINE') break;
        //Chatolio.debug(model.state);
        updateClass("chatting");
        break;
      case "INACTIVE":
        if(Chatolio.store.service.state == 'OFFLINE') break;
        //Chatolio.debug(model.state);
        updateClass("inactive");
        break;
      case "AVAILABLE":
        //Chatolio.debug(model.state);
        updateClass("available");
        Chatolio.store.service = model;
        break;
      case "BUSY":
        //Chatolio.debug(model.state);
        updateClass("busy");
        Chatolio.store.service = model;
        break;
      case "OFFLINE":
        //Chatolio.debug(model.state);
        updateClass("offline");
        Chatolio.store.service = model;
        break;
      default:
        Chatolio.debug("Unhandled status change trigger: " + model.state);
        break;        
    }
  }
}

Chatolio.debug = function(s) {
  if(typeof(console) != "undefined" && typeof(console.debug) == "function") {
    console.debug(s);
  }
};


/**** LIVE EVENTS ****/

if(typeof(jQuery) != "undefined") {

  // here we may put live events
  
};
/**********************/
