var connectionId = null;
var connectionAddress = 'wss://chat1.smarttravelapp.com:443';
var chatGroup = 1;
var socketHandler;
var chatFct = {};

var unreadMessages = 0;
var unreadNotificationId = 1;

var conn;
var me;

var friendList;

var pingTimerStarted = false;

function connOnMessage(e) {
    jsonData = JSON.parse(e.data);
    if (jsonData.method === "websiteConnect" && jsonData.isConnected === false) {
        me = {};
    } else if (jsonData.method === "websiteConnect" && jsonData.isConnected) {
        me = jsonData;
    } else if (jsonData.method === "websiteAllHistory") {
        if (jsonData.messages !== undefined) {
            isAssist=false;
            html = '';
            for (i = 0; i < jsonData.messages.length; i++) {
                if(jsonData.messages[i].isWebsite){
                  isAssist=false;
                  html += '<div class="col-xs-12" style="height:5px;"></div><div class="col-xs-3"></div><div class="col-xs-9 text-right"><span class="ui-corner-all" style="display:inline-block;border:1px solid #eee;background:#eee;padding:3px;">' + jsonData.messages[i].message + '</span></div>';
                }else{
                  isAssist=true;
                  html += '<div class="col-xs-12" style="height:5px;"></div><div class="col-xs-9"><span class="ui-corner-all" style="display:inline-block;border:1px solid #aaa;padding:3px;">' + jsonData.messages[i].message + '</span></div><div class="col-xs-3"></div>';
                }
                updateMessageId('assistance-frame',jsonData.messages[i].messageId);
            }
            $('#chat_dialog').html($('#chat_dialog').html()+html);
            scrollToBottom('chat_dialog');
            if(isAssist && jsonData.messages.length>1){
              triggerOpen();
            }
        }
    } else if (jsonData.method === "websiteMessage") {
        html = '';
        if(jsonData.isWebsite){
          html += '<div class="col-xs-12" style="height:5px;"></div><div class="col-xs-3"></div><div class="col-xs-9 text-right"><span class="ui-corner-all" style="display:inline-block;border:1px solid #eee;background:#eee;padding:3px;">' + jsonData.message + '</span></div>';
        }else{
          html += '<div class="col-xs-12" style="height:5px;"></div><div class="col-xs-9"><span class="ui-corner-all" style="display:inline-block;border:1px solid #aaa;padding:3px;">' + jsonData.message + '</span></div><div class="col-xs-3"></div>';
        }
        updateMessageId('assistance-frame',jsonData.messageId);
        $('#chat_dialog').html($('#chat_dialog').html()+html);
        scrollToBottom('chat_dialog');
        triggerOpen();
    } else {
        console.log(JSON.stringify(jsonData));
    }
};

function connOnOpen(e) {
  console.log("Connection established!");
  sendWebsiteLogin();
  if (pingTimerStarted === false) {
    setTimeout('sendWebsitePing()', 1000);
    pingTimerStarted = true;
  }
}

var restartTimeout = undefined;

function connOnClose(e) {
  if (restartTimeout === undefined) {
    restartTimeout = setTimeout("connStart()", 10000);
  }
}

function connOnError(e) {
    conn.close();
}

function connStart() {
    console.log('Connection to the server...');
    if (restartTimeout !== undefined) {
        clearTimeout(restartTimeout);
        restartTimeout = undefined;
    }
    conn = new WebSocket(connectionAddress);
    conn.onopen = connOnOpen;
    conn.onclose = connOnClose;
    conn.onerror = connOnError;
    conn.onmessage = connOnMessage;
}

connStart();

function updateMessageId(containerId,messageId){
  if($('#'+containerId).attr('data-last-message')<messageId){
    $('#'+containerId).attr('data-last-message',messageId);
  }
}

function newMessage(containerId){
  if($('#chat_block').css('bottom')!=='0px'){
    scrollToBottom(containerId);
  }
}

function scrollToBottom(containerId){
  var d = $('#'+containerId);
  d.scrollTop(d.prop("scrollHeight"));
}

function sendWebsiteLogin() {
    message = {
        method: "websiteConnect",
        sessionId: $('#chat_session_id').val(),
        sessionUser: $('#chat_session_user').val(),
        sessionKey: $('#chat_session_key').val(),
        sessionLanguage: $('#chat_session_language').val(),
        chatGroup: chatGroup,
        lastMessage: $('#assistance-frame').attr('data-last-message')
    };
    conn.send(JSON.stringify(message));
}

function sendWebsitePing() {
    message = {
        method: "websitePing",
        sessionId: $('#chat_session_id').val(),
        sessionUser: $('#chat_session_user').val(),
        sessionKey: $('#chat_session_key').val()
    };
    try {
        conn.send(JSON.stringify(message));
    } catch (e) { }
    setTimeout('sendWebsitePing()', 20000);
}

function sendWebsiteMessage(message,selector) {
  if(message.trim()!==""){
    mess = {
        method: "websiteMessage",
        sessionId: $('#chat_session_id').val(),
        sessionUser: $('#chat_session_user').val(),
        sessionKey: $('#chat_session_key').val(),
        message: message.trim()
    };
    try {
        conn.send(JSON.stringify(mess));
    } catch (e) { }
  }
  $(selector).val("");
}

function triggerOpen(){
  if($('#chat_block').css('bottom')!=='0px'){
    $('#chat_block').stop(true);
    $('#chat_block').animate({
      bottom:0
    },{
      duration:750,
      queue:false
    });
  }
}

$(document).ready(function(){
  // Give a height to the chat container
  height = $(window).height()*0.25;
  if(height<200){
    $('#chat_container').height($(window).height()*0.40);
  }else{
    $('#chat_container').height(height);
  }
  
  // setup the click action on the header & initialize in a reduced position
  $('#chat_header').click(function(){
    $('#chat_block').stop(true);
    if($('#chat_block').css('bottom')=='0px'){
      $('#chat_block').animate({
        bottom:(-$('#chat_container').height())
      },{
        duration:750,
        queue:false
      });
    }else{
      $('#chat_block').animate({
        bottom:0
      },{
        duration:750,
        queue:false
      });
    }
  });
  $('#chat_message').keyup(function(e){
    if(e.keyCode == 13 && $('#chat_message').val()!=="")
    {
      sendWebsiteMessage($('#chat_message').val(),'#chat_message');
    }
  });
  //$('#chat_block').css('bottom',(-$('#chat_container').height())+'px');
  
  // Design the chat container
  $('#chat_dialog').height($('#chat_container').height()-$('#chat_insert').height());
  if($('#chat_started').val()*1===1){
    $('#chat_block').css('bottom','-'+$('#chat_container').height()+'px');
  }
});