
// whh 2019.12.24 handle out going messages from the contact messages froms
// whh 2020.01.08 date handling and message sorting fro display
// whh 2020.01.24 sorting did not work in firefox changed to a non date format number sorting
// whh 2020.02.19 switched to calling PHP to read data files uploading to JS with AJAX
// whh 2020.02.22 and additional grep to show only messages (incoming number) for the hosting number (source)
// whh 2929.03.03 added delete message function
// whh 2020.03.03 added glyph X to each message containing the message time and date to onclick pass to delete.php
// whh 2020.03.19 all console logs commented out
/*
function printMousePos(event) {
  document.body.textContent =
    "clientX: " + event.clientX +
    " - clientY: " + event.clientY;
}

document.addEventListener("click", printMousePos);
*/

function deleteMessageAjax(dateTime) {

  console.log("Running-deleteMessageAjax: contactMessages.js");

       var topLocation = event.pageY;
       topLocation = topLocation - 220 + "px";

       //console.log(topLocation);

//document.getElementById("deletedMessage").innerHTML = " ";

  var localdateTime = atob(dateTime);
  var messageDelete = "Delete";

  //console.log("<br>");
  //console.log("DateTime: " + localdateTime);

//console.log("<br>");
  var formData = "localdateTime=" + localdateTime;
//console.log(formData);
  // Submit the form using AJAX.
      $.ajax({
          type: 'POST',
          url: 'delete.php',
          data: formData,
          dataType : 'HTML',
          success: function(response) {
            $('#deletedMessage').html(response);
            document.getElementById("deletedMessage").style.top = topLocation;
          }

      }) // End Ajax call to delete.php

}// End function deleteMessageAjax



/*   Display a Client List in add/new client window */
function newClientMessages(objnewaNumber, source) {

console.log("Runnning  - contactsMessages.js -"); // message for browser console for debugging

  //clear data
  document.getElementById("phoneNumber").innerHTML = "&nbsp;";
  document.getElementById('newWindows').innerHTML = "&nbsp;";

  document.getElementById('recipient').value = "";




  document.getElementById("phoneNumberSource").style.display = "block";
  // setup attributes for the top your phone number
  document.getElementById("phoneNumberSource").innerHTML = source;
  document.getElementById("phoneNumberSource").style.fontSize = "0.75em";
  document.getElementById("phoneNumberSource").style.color = "grey";
  document.getElementById("phoneNumberSource").style.textAlign = "left"

  document.getElementById("firstName").style.backgroundColor= "black";
  document.getElementById("lastName").style.backgroundColor= "black";
  document.getElementById("firstName").style.color= "white";
  document.getElementById("lastName").style.color= "white";


  // set element to display
  document.getElementById("phoneNumber").innerHTML = objnewaNumber; // display your phone number at section top
  document.getElementById("sms").style.display = "block";
  document.getElementById("phone").style.display = "none";
  document.getElementById("numpad").style.display = "none";
  document.getElementById("selectNumber").style.display = "none";
  document.getElementById("newPhoneList").style.display = "none";
  document.getElementById("contactSubmit").style.display = "none";
  document.getElementById("firstName").style.display = "block";
  document.getElementById("lastName").style.display = "block";
  document.getElementById("type").style.display = "none";
  document.getElementById("phoneNumber").style.display = "block";
  document.getElementById("typeText").style.display = "none";

  // make this input required for this useage

  // make false it is not being used, value is from top of webpage
  document.getElementById("recipient").required  = false;


var valn = objnewaNumber;
var source = source;
// console.log ("SOURCE: " + source + " objnewaNumber: " + objnewaNumber);

/* read in the incoming client messages from SMSmessages.json */
/* read in the incoming client messages from SMSmessages.json */
/* read in the incoming client messages from SMSmessages.json */
        $.ajax({
            url: "SMSMessagesAjax.php",
            async: false,   // asynchronous request? (synchronous requests are discouraged...)
            cache: false,   // with this, you can force the browser to not make cache of the retrieved data
            dataType: "json",  // jQuery will infer this, but you can set explicitly
            success: function(data) {
               // console.table(data);
              // console.log("Data Length from file: " + data.length);

        length = data.length;
/*
          // Sort data by date
            data.sort(function(a, b) {
                a = new Date(a.dateTime);
                b = new Date(b.dateTime);
                return a<b ? -1 : a>b ? 1 : 0;
            });

    console.table(data);
*/
//console.log("from : " + valn);

//console.log("to : " + source);


// find just the elements selected for the Phone number of val
        var objcc = $.grep(data, function(obj, i){return obj.number == valn;});


// show only the messages for this host number
          var objc = $.grep(objcc, function(obj, i){return obj.recipient == source;});
        //console.table(objc);
          var lengthc = objc.length;
//var number = objc[0].number;

        if (lengthc > 1) {var number = objc[0].number;}



        // document.getElementById("recipient").value = number ;
//console.log("Recipient-number: " + number);

//******************************************************************
// load the Sent Messages file
//******************************************************************

// back button to numbers under the current source
// var backNumber = "<div class='row p2'><div class='col-4 p-4'style='margin-top:-50px;'><input class='btn btn-outline-secondary actionbtn'  type='button' value='Back to " + source + "' onClick='phonesNumbersList(" + source + ")'></input></div>";
var backNumber = "<div style='position: fixed; z-index:999999; background-color:transparent;'> <button id='myBtnC' class='backarrow' style='background-color:rgba(0,0,0,0)' onClick='phonesNumbersList(" + source + ")' ><span class='glyphicon glyphicon-backward'></span></button></div> ";


document.getElementById("newWindows").innerHTML += backNumber;

                    $.ajax({
                        url: "SMSMessagesSentAjax.php",
                        async: false,   // asynchronous request? (synchronous requests are discouraged...)
                        cache: false,   // with this, you can force the browser to not make cache of the retrieved data
                        dataType: "json",  // jQuery will infer this, but you can set explicitly
                          success: function(data) {
                            // console.log("unsorted dates:")
                            //console.table(data);
                            // console.log("Data Length from file: " + data.length);

                            length2 = data.length;
/*
                            // Sort data by date
                            data.sort(function(a, b) {
                                a = new Date(a.dateTime);
                                b = new Date(b.dateTime);
                                return a<b ? -1 : a>b ? 1 : 0;
                            });
                            console.table(data);
*/
// find just the elements selected for the Phone number of source and selected incoming client
    //console.log("source: " + source + " - valn: " + valn);

    //console.log("from : " + valn);

    //console.log("to : " + source);


                    // client number selected
                            var objcsent = $.grep(data, function(obj, i){return obj.recipient == valn;});
                            //console.table(objcsent);
                    // your phone number being used for messaging
                            var objcsent = $.grep(objcsent, function(obj, i){return obj.number == source;});
                            //console.table(objcsent);


// get clientId for this message thread and split into first and last name
         // and load the hidden form fields firstName and lastName to pass to the DIDWW.PHP file on Submit
                            //contact = objcsent[0].clientId;
                          //  var contactBoth = contact.split("_");
                          //  var firstName= contactBoth[0];
                          //  var lastName = contactBoth[1];

                  // try to do something if it fails since no ClientId
                   //   exists for that number set contact to unkown
                        try {
                          contact = objcsent[0].clientId;
                          var contactBoth = contact.split("_");
                          var lastName= contactBoth[0];
                          var firstName = contactBoth[1];
                          //console.log("objcsent[0].clientId: " + contact);
                        }
                        catch ( e ) {
                           contact = "Unkown";
                           //console.log("contact: " + contact);
                        }

                        //console.log("firstName: " + firstName);
                        //console.log("lastName: " + lastName);


// put the first and last name into the forms fields to be passed to DIDWW.PHP
              // use contact info from sent messages
              if (contact !== "Unkown"){
                  document.getElementById("firstName").value = firstName ;
                  document.getElementById("lastName").value = lastName ;
                  //console.log("lastName: " + lastName);
                  //console.log("firstName: " + firstName);
                } else {
                      document.getElementById("recipient").required  = false;
                      //console.log("lastNameUND: " + lastName);
                      //console.log("firstNameUND: " + firstName);
                    }
                            // var contactNumber = contactNumber.replace(/ /g,''); // remove spaces


//******************************************************************
// End load Sent messages
//******************************************************************


// clear window content and add clientInfo
// document.getElementById("messageWindowtitle").innerHTML = "<p style='color:#216bd1;}'>" + "<strong> SMS from: " + val + "</strong></p>";

// list all of a SMS message for a phone mumber recieved

if (length <= length2) {
  var uselength = length2;
//console.log("uselength: " + uselength);
    } else {
      var uselength = length;
//console.log("uselength: " + uselength);
  };


var viewMessages = [];
var deleteTimei = [];
var deleteTimej = [];
var k = 0;
var i = 0;
var j = 0;
var bcolor = "#bdbdbd;";
  for (k=0; k < uselength; k++){

    var i = k ;
    if (i < objc.length ){

        // set background of unread messages to light green
        if(objc[i].read === "no"){bcolor = "#c9fca9;"; } else {bolor = "#bdbdbd;";}

        deleteTimei.i = btoa(objc[i].localdateTime);

//console.log ( i + " Time i: " + atob(deleteTimei.i));

        var deleteMessage = "<div class='col-2 p-2' style='margin-top:-60px; margin-left:-70px; position:relative; z-index:9999;'> <button class='btn btn-link' type='button' onClick='deleteMessageAjax(" + "\"" + deleteTimei.i + "\"" + ")' ><span class='glyphicon glyphicon-remove-sign'></span></button></div> ";

//console.log(deleteMessage);

        var message =  "<strong style='font-size:0.75em;'>Received:</strong> " + objc[i].message +  "<br><strong style='font-size:0.5em; line-height: 0;'>" + objc[i].localdateTime + " From: " + objc[i].number + " - To: " + objc[i].recipient + "</strong>" + deleteMessage;

          var message1 = "<div class='row p-2' style = 'margin-left:5%;'><div class='col-10 p-2'  style='text-align: left; border-radius: 15px; background-color:" + bcolor + "color:black; position: relative;  z-index:888;'>" + message + "</div></div>";

          // document.getElementById('newWindows').innerHTML += message2;
          //console.log("Display 1 ");
          date = objc[i].localdateTime;
          count = i
          var dataMessage = {stuff: count, date: date, message: message1} ; // load date to sort on into displpay array

          viewMessages.push(dataMessage);
      }


          // list all of a SMS message for phone mumber
          var j = k ;

      if (j < objcsent.length ){

        deleteTimej.j = btoa(objcsent[j].localdateTime);
        //console.log (j + " Time J: " + atob(deleteTimej.j));

        var deleteMessage2 = "<div class='col-2 p-2' style='margin-top:-60px; margin-left:-70px; position:relative; z-index:9999;'> <button class='btn btn-link' type='button' onClick='deleteMessageAjax(" + "\"" + deleteTimej.j + "\"" + ")' ><span class='glyphicon glyphicon-remove-sign'></span></button></div> ";
        //console.log(deleteMessage2);

          var message = "<strong style='font-size:0.75em;'>" + objcsent[j].result +": </strong> " + objcsent[j].messagein
                    + "<br><strong style='font-size:0.5em; line-height: 0;'>" + "'" + objcsent[j].localdateTime + "'" + " From: " + objcsent[j].number + " - To: " + objcsent[j].recipient + "</strong>" + deleteMessage2;

          var message2 = "<div class='row p-2' style='margin-right:1%;'><div class='col-10 p-2 offset-2' style = 'text-align: left; border-radius: 15px; background-color:#bed3e6; color:black; position: relative;  z-index:66;'>" + message + "</div></div>";


          var date2 = objcsent[j].localdateTime;
          var count2 = j
          var dataMessage2 = {stuff: count2, date:date2, message: message2} ; // load date to sort on into displpay array

          viewMessages.push(dataMessage2);
          //console.table(viewMessages);
          //console.table(viewMessages);

      }

    } // k for loop



    //console.table(viewMessages);
/*
for (i=0; i < viewMessages.length; i++ ) {
    viewMessages[i].date = Date.parse(viewMessages[i].date)
    };
*/

for (let i = 0; i < viewMessages.length; i++) {
    dateStr = viewMessages[i].date;
    d = dateStr.split(",");
    //console.log(d);
    d2 = d[1];
    //console.log(d2);
    d3 = d2.split(" ");
    //console.log(d3);
    d4 = d3[1];
    d5 = d4.split("-");
    //console.log(d5);
    t1 = d3[2];
    mon = d5[1];
    mon2 = ( "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(mon) / 3 + 1 );
    if (mon2 < 10){mon2 = "0" + mon2; }; // if month is single digit add zero at start
    //console.log(mon2);
    d6 = "20" + d5[2] + "-" + mon2 + "-" + d5[0] + "T" + t1;
    //console.log(d6);

    var dates = new Date(d6).getTime();
    //console.log(dates);

    viewMessages[i].date = dates;
   };

//console.table(viewMessages);


viewMessages.sort((a, b) => Number(a.date) - Number(b.date));
//console.log("ascending", viewMessages);

//viewMessages.sort((a, b) => Number(b.date) - Number(a.date));
//console.log("descending", viewMessages);


  //console.table(viewMessages);


      lengthviewMessages = viewMessages.length;

      for (i=0; i < lengthviewMessages; i++){
        // display sorted messages
        document.getElementById('newWindows').innerHTML += viewMessages[i].message;
      };

// document.getElementById('newWindows').innerHTML += "<div id='view3'></div>";

$([document.documentElement, document.body]).animate({
    scrollTop: $("#view3").offset().top
}, 1000 );

  } // SMSmessagesin success

}); // end of SMSmesageson ajax



} //SMSmesages success


}); // end of SMSmesages ajax




$([document.documentElement, document.body]).animate({
    scrollTop: $("#view3").offset().top
}, 1000 );




}; // end of entire function
