
var session_id = null;
var timer = null; // Der Timer wird werst erst beim ersten Submit gestartet
var last_pos = 0; // letzte Chat-ID, die angezeigt wurde
var consultant = 0; // ID des Beraters
var consultant_name = 'einem Berater';
var language=0; // de
var connected = false; // Berater hat erstmalig geantwortet
var start_time = null; // Date-Objekt beim Absenden der ersten Frage 

$(document).ready(function() {

  var r = location.href.match(/l=(\d+)/);
  if (r && r[1]==1) {
    language=1;
  }
  if (r && r[1]==2) {
    language=2;
  }

  if (language==1) {
    $('#send').val('Submit');
    consultant_name = 'a consultant';
  }
  if (language==2) {
    $('#send').val('Enviar');
    consultant_name = 'un consultor';
  }

  var r = location.href.match(/b=(\d+)/);
  if (r && r[1]) {
    consultant = parseInt(r[1]);
  }

  // Pruefen ob Berater verfuegbar ist
  $.ajax({
    type: "GET",
    url: APP_URL + "/server_client.php",
    cache: false,
    data: "action=checkConsultant&session_id="+session_id+"&consultant="+consultant,
    success: function(response) {
      var result = eval("(" + response + ")");
      if (!result.success) {
        var txt = "Es ist leider zur Zeit kein Berater verfügbar. Bitte versuchen Sie es später noch einmal oder verwenden Sie das Kontaktformular.";
        if (language==1) {
          txt = "Sorry, currently no consultant is available. Please try again later or use our contact form.";
        }
        if (language==2) {
          txt = "Nuestro consultor no esta disponible. Por favor use el formulario de contacto.";
        }
        
        showContactForm(txt);
        return;
      } else {
        consultant_name = result.consultant;
        var txt = "Bitte geben Sie jetzt ihre Frage ein.";
        if (language==1) {
          txt = "Please enter your question.";
        }
        if (language==2) {
          txt = "Por favor haga su pregunta.";
        }
        insertChatLine(txt);
      }
    }
  });



  $('#chattext').focus();
});


function submitText() {

  if (!session_id) {
      var txt = "Bitte warten, Sie werden mit "+consultant_name+" verbunden.";
      if (language==1) {
        txt = "Please wait, connecting with "+consultant_name;
      }
      if (language==2) {
        txt = "Por favor espere, usted se esta conectando con "+consultant_name;
      }
      insertChatLine(txt);
      
      start_time = new Date();
  }

  var text = $("#chattext").attr("value");
  if (text.length == 0) {
    $("#chattext").focus();
    return;
  }

  stopTimer();

  $("#chattext").attr("value", "");
  $("#chattext").focus();

  var now = new Date();
  var zeit = (now.getHours()<10?"0":"") + now.getHours() + ":" + (now.getMinutes()<10?"0":"") + now.getMinutes();


  var htmlold=$("#chatdisplay").html();
  var html = htmlold + "<p class=\"chatline chatown\">" + zeit + ": " + text + "</p>";

  $("#chatdisplay").html(html);

  $('#chatdisplay').animate({scrollTop: $('#chatdisplay')[0].scrollHeight});

  // Post
  if (session_id==null) {
    session_id = createUUID();
  }
  $.post(APP_URL + "/server_client.php", { session_id: session_id, text: text, consultant: consultant, action: 'save' }, function (response) {
    last_pos=parseInt(response);
  });

  startTimer();
}

function createUUID() {
    // http://www.ietf.org/rfc/rfc4122.txt
    var s = [];
    var hexDigits = "0123456789ABCDEF";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01

    var uuid = s.join("");
    return uuid;
}

function startTimer() {
  timer = window.setTimeout(timerEvent, 5000);
}

function stopTimer() {
  if (timer!=null) {
    window.clearTimeout(timer);
    timer=null;
  }
}

function timerEvent() {
  stopTimer();

  $.ajax({
    type: "GET",
    url: APP_URL + "/server_client.php",
    cache: false,
    data: "session_id="+session_id+"&last_pos="+last_pos+"&consultant="+consultant,
    success: chatServerResponseHandler,
    error: startTimer
  });

}

function chatServerResponseHandler(response) {
  var result = eval("(" + response + ")");

  last_pos=result.last_pos;
  
  if (result.lines.length > 0) {
    connected = true;
  }
  
  if (!connected && result.lines.length == 0) {
    if (start_time.getTime() < new Date().getTime() - 1000*60) {
      // keine Antwort nach 60s -> Kontaktformular anzeigen
      
      var txt = "Es ist leider zur Zeit kein Berater verfügbar. Bitte versuchen Sie es später noch einmal oder verwenden Sie das Kontaktformular.";
      if (language==1) {
        txt = "Sorry, currently no consultant is available. Please try again later or use our contact form.";
      }
      if (language==2) {
        txt = "Nuestro consultor no esta disponible. Por favor use el formulario de contacto.";
      }
      
      showContactForm(txt);
      stopTimer();
      return;
    }
    
    insertChatLine("Sie werden verbunden...");
    startTimer();
    return;
  }

  for (var i=0; i<result.lines.length; i++) {
    if (result.lines[i] == "command: end") {
      insertChatLine("Der Chat wurde beendet.");
      stopTimer();
      return;
    }
    
    insertChatLine(result.lines[i]);
  }

  if (result.lines.length > 0) {
    $('#chatdisplay').animate({scrollTop: $('#chatdisplay')[0].scrollHeight});
  }

  startTimer();
}

function insertChatLine(text) {
  var htmlold=$("#chatdisplay").html();
  var html = htmlold + "<p class=\"chatline chatother\">" + text + "</p>";

  $("#chatdisplay").html(html);
}

function print() {
 
  var html = '<style>\
p {\
  margin: 0;\
}\
.chatown {\
  color:#777;\
}\
</style>';
  html += $('#chatdisplay').html();

  var win = window.open("about:blank", "print", "width:500, height:500, menubar:yes, toolbar:yes, dependent:yes");
  
  win.document.write(html);
  win.print();
}

function showContactForm(text) {
  stopTimer();
  $('#contact_form_text').html(text);
  $('.chatcontainer').hide();
  $('#form_contact').show();
}

function sendContactForm() {
  var data = {
    action: 'contact',
    name: $('#form_contact #name').val(),
    company: $('#form_contact #company').val(),
    email: $('#form_contact #email').val(),
    text: $('#form_contact #t_text').val()
  };
  $.post(APP_URL + "/server_client.php", data, function (response) {
    alert("Nachricht gesendet");
    $('#form_contact').hide();
    $('.chatcontainer').show();
    $('#contact_form_text').html('');
  });
}


