//
// Script for SH SMS to load clients into select phone number field
//
// whh 2019.11.21 added json data file for clients
// whh 2019.11.24 tidied up formatting for top margin and scrolling
// whh 2018.12.14 updated to interlace sent and receive and all be on one html page
// whh 2019.12.25 set select contact field to empty and lose the dummy entry in contacts.json
// whh 2020.02.19 switched to calling PHP to read data files uploading to JS with AJAX
// whh 2020.03.19 all console logs commented out

// load functions to populate Select fields from clientIFfile.json

function openingSite(){

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

        document.getElementById("Page_Wrapper").style.display = "block";
  // hide page show password
        // document.getElementById("pass").style.display = "block";

        document.getElementById("sms").style.display = "none";
        document.getElementById("phone").style.display = "block";

        // console.log("newMessages");
        newMessages(); // get all new messages for each phone number; this is the app page!

};


//**********************************************************************





// get all messages from SMSmessages that are have empty ClientIds
// get all messages from SMSmessages that are have empty ClientIds
// get all messages from SMSmessages that are have empty ClientIds
function loadUnkown() {

    // console.log("Function Unkown");

// 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);
        //console.table(data);
        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);

        document.getElementById("pass").style.display = "none";
        document.getElementById("sms").style.display = "block";
        document.getElementById("phone").style.display = "none";
        document.getElementById("numpad").style.display = "block";
        document.getElementById("selectNUM").style.display = "none";

        document.getElementById("phoneNumber").innerHTML = "New ClientIds"; // display your phone number at page top

//console.log("selected Client after n: " + valn);

// find just the elements selected for the Phone number of val
        var obje = $.grep(data, function(obj, i){return obj.clientId === ""});
        console.log("No ClientIds: ");
        console.table(obje);
        uselength = obje.length;

        var k = 0;
        var bcolor = "#bdbdbd;";
          for (k=0; k < uselength; k++){

            if (k < obje.length ){

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

                var message =  "<strong>Received Message:</strong> " + obje[k].message
                  + "<br><strong>Date and Time:</strong> " + obje[k].dateTime + "<br>"
                  + "<strong>FROM: </strong>" + obje[k].number;

                  var message2 = "<div class='row p-2 '><div class='col-8' style = 'text-align: left; border-radius: 15px; background-color:" + bcolor + "color:black; position: relative;  z-index:999;'>" + message + "</div></div>";
                  document.getElementById('newWindows').innerHTML += "SMS Received: " + message2;
                  //console.log("Display 1 ");
              }
                            document.getElementById('form-messages').innerHTML += "<br>Messages Will Now be Marked as Read: <br>" + obje[k].number;
          }

          var sendStuff = obje;

          var sendData = function() {
            $.post('markRead.php', {
              data: sendStuff
            }, function(response) {
              //document.getElementById('form-messages').innerHTML += "Messages Will Now be Marked as Read: <br>" + JSON.stringify(obje.number[k]);
              console.log("Response from markRead.php: " + response);
            });
          };

        sendData();

    } // END success of AJAX read SMSmessages

}); // END AJAX read SMSmessages in loadUnknown

} //END loadUnkown


//***************************************************************************

    // When the user clicks on the button, scroll to the top of the document
    function topFunction() {
      document.body.scrollTop = 0; // For Safari
      document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
    }




//***************************************************************************

    // When the user clicks on the button, refresh/reload the page
    function refreshPageFunction(){
    // get sms container from server and reload it in browser resetting page without reload
      //space after + is important
      // $('#sms').load(document.URL +  ' #sms'); // this loose all the page context
    window.location.reload();

    };
