function liste() {
  var param = "rech_mc="+encodeURIComponent($("#rech_mc").val()) ;
  // alert($("#cf_url").val()+"/patient/liste?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/patient/liste",
    data:param,
    success:function(msg){
      $("#div_patient").html(msg) ;
      $("#rech_mc").focus() ;
    }
  }) ;
}

function newVille() {
  if($("#new_ville").val()==""){
    alert("Saisissez le nom de la ville...") ;
    $("#new_ville").focus() ;
  }
  else if($("#cp").val()==""){
    alert("Attention le code postal doit être correct...") ;
    $("#cp").focus() ;
  }
  else{
    var param = "cp="+encodeURIComponent($("#cp").val())+"&new_ville="+encodeURIComponent($("#new_ville").val()) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/ville/form_inc_new",
      data:param,
      success:function(msg){
        listeVille() ;
      }
    }) ;
  }
}

function listeVille() {
  var param = "cp="+encodeURIComponent($("#cp").val())+"&id_ville="+$("#id_ville").val() ;
  // alert($("#cf_url").val()+"/ville/liste?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/ville/form_inc_liste",
    data:param,
    success:function(msg){
      $("#div_ville").html(msg) ;
    }
  }) ;
}

function newPrescriptionActe() {
  if($("#new_acte").val()=="0"){
    alert("Veuillez choisir l'acte a ajouter...") ;
    $("#new_acte").focus() ;
  }
  else if(isNaN($("#new_nb_acte").val()) || $("#new_nb_acte").val()==""){
    alert("Le nombre d'acte n'est pas valide...") ;
    $("#new_nb_acte").focus() ;
  }
  else{
    var param = "id="+$("#id_prescription").val()+"&id_acte="+$("#new_acte").val()+"&nb_acte="+$("#new_nb_acte").val() ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/prescription/new_acte",
      data:param,
      success:function(msg){
        prescriptionListeActe() ;
      }
    }) ;
  }
}

function prescriptionListeActe() {
  var param = "id="+$("#id_prescription").val() ;
  // alert($("#cf_url").val()+"/prescription/liste_acte?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/prescription/liste_acte",
    data:param,
    success:function(msg){
      $("#div_liste_acte").html(msg) ;
    }
  }) ;
}



function formPrescription(id){
  var param = "id="+id+"&id_patient="+$("#id").val() ;
  // alert($("#cf_url").val()+"/prescription/form?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/prescription/form",
    data:param,
    success:function(msg){
      if(id==0) $('#modalNew').modal('hide') ;
      $("#div_dialog").html(msg) ;
      $('#dialog-form_prescription').modal('show') ;
      $('#dialog-form_prescription').on('shown.bs.modal', function () {
        prescriptionListeActe() ;
        $("input.date_picker").datepicker({dateFormat:'dd/mm/yy',changeMonth:true,changeYear:true,numberOfMonths:1});
      }) ;
      $('#dialog-form_prescription').on('hide.bs.modal', function () {
        listePrescription() ;
      }) ;
    }
  }) ;
}

function listePrescription() {
  var param = "id="+$("#id").val() ;
  param+="&start="+$("#start").val() ;
  param+="&rech_effectue="+$("#rech_effectue").val() ;
  param+="&rech_effectue_par="+$("#rech_effectue_par").val() ;
  param+="&rech_petit_matin="+$("#rech_petit_matin").val() ;
  param+="&rech_mms="+$("#rech_mms").val() ;
  param+="&rech_du="+$("#rech_du").val() ;
  param+="&rech_au="+$("#rech_au").val() ;
  param+="&rech_acte="+$("#rech_acte").val() ;
  // alert($("#cf_url").val()+"/prescription/patient_liste?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/prescription/patient_liste",
    data:param,
    success:function(msg){
      // alert(msg) ;
      $("#profile").html(msg) ;
      $("input.date_picker").datepicker({dateFormat:'dd/mm/yy',changeMonth:true,changeYear:true,numberOfMonths:1});
    }
  }) ;
}

function forceSupPatient(id) {
  var param = "id="+id ;
  param+="&force=1" ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/patient/supprime",
    data:param,
    success:function(msg){
      liste() ;
    }
  }) ;
}

function supPatient(id) {
  if(confirm("SUPPRIMER CE PATIENT ?")){
    var param = "id="+id ;
    // alert($("#cf_url").val()+"/patient/supprime?"+param) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/patient/supprime",
      data:param,
      success:function(msg){
        if(msg=="deja"){
          if(confirm("Ce patient a encore des rendez vous à venir, supprimer tout de même ?")){
            forceSupPatient(id) ;
          }
        }
        else liste() ;
        // if(msg!="") alert(msg) ;
      }
    }) ;
  }
}

function supRDV(id) {
  if(confirm("SUPPRIMER CE RENDEZ VOUS ?")){
    var param = "id="+id ;
    // alert($("#cf_url").val()+"/visite/trait_new?"+param) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/rdv/supprime",
      data:param,
      success:function(msg){
        $('#dialog-deatils_rdv').modal('hide') ;
      }
    }) ;
  }
}

function detailsRDV(id_rdv) {
  var param = "id="+id_rdv ;
  // alert($("#cf_url").val()+"/rdv/details_rdv?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/rdv/details_rdv",
    data:param,
    success:function(msg){
      $("#div_dialog").html(msg) ;
      $('#dialog-deatils_rdv').modal('show') ;
      $('#dialog-deatils_rdv').on('shown.bs.modal', function () {

      }) ;
      $('#dialog-deatils_rdv').on('hide.bs.modal', function () {
        listePrescription() ;
      }) ;
    }
  }) ;
}

function direct(start) {
  $("#start").val(start) ;
  listePrescription() ;
}

function traitModalModifColonne() {
  var liste = "" ;
  var cpt = 0 ;
  $(".check_rdv").each(function(){
    if($(this).is(':checked')){
      if(cpt>0) liste+="," ;
      liste+=$(this).attr('rel') ;
      cpt++;
    }
  }) ;
  if(liste==""){
    alert("Une erreure s'est produite...") ;
  }
  else if($("#val_colonne").val()==""){
    alert("Veuillez séléctionner une valeur...") ;
    $("#val_colonne").focus() ;
  }
  else{
    var champ = $("#champ_colonne").val() ;
    var param = "champ="+champ ;
    // if(champ=="petit_matin" || champ=="mms"){
    //   val = 0 ;
    //   if($("#val_colonne").is(':checked')) val = 1 ;
    //   param+="&val_colonne="+val ;
    // }
    // else param+="&val_colonne="+$("#val_colonne").val() ;
    param+="&val_colonne="+$("#val_colonne").val() ;
    param+="&liste="+liste ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/patient/trait_modal_modif_colonne",
      data:param,
      success:function(msg){
        if(msg!="") alert(msg) ;
        $('#modal-modif_colonne').modal('hide') ;
      }
    }) ;
  }
}

function cocheDecocheTout() {
  if($("#check_all").is(':checked')){
    $(".check_rdv").attr('checked',true) ;
  }
  else{
    $(".check_rdv").attr('checked',false) ;
  }
}

function supSelection() {
  var liste = "" ;
  var cpt = 0 ;
  $(".check_rdv").each(function(){
    if($(this).is(':checked')){
      if(cpt>0) liste+="," ;
      liste+=$(this).attr('rel') ;
      cpt++;
    }
  }) ;
  if(liste==""){
    alert("Veuillez cocher les lignes concernées...") ;
  }
  else{
    if(confirm("Supprimer les lignes séléctionnées...?")){
      var param = "liste="+liste ;
      $.ajax({
        type:"POST",
        url:$("#cf_url").val()+"/patient/supprime_selection",
        data:param,
        success:function(msg){
          listePrescription() ;
        }
      }) ;
    }
  }
}

function modalModifColonne(champ) {
  var liste = "" ;
  var cpt = 0 ;
  $(".check_rdv").each(function(){
    if($(this).is(':checked')){
      if(cpt>0) liste+="," ;
      liste+=$(this).attr('rel') ;
      cpt++;
    }
  }) ;
  if(liste==""){
    alert("Veuillez cocher les lignes concernées...") ;
  }
  else{
    var param = "champ="+champ+"&liste="+liste ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/patient/modal_modif_colonne",
      data:param,
      success:function(msg){
        $("#div_dialog").html(msg) ;
        $('#modal-modif_colonne').modal('show') ;
        $('#modal-modif_colonne').on('shown.bs.modal', function () {}) ;
        $('#modal-modif_colonne').on('hide.bs.modal', function () {
          listePrescription() ;
        }) ;
      }
    }) ;
  }
}

function traitDetailsRDV() {
  if(!isDateValide($("#rdv_date").val())){
    alert("Date non valide, format attendu : jj/mm/aaaa ") ;
  }
  else{
    var petit_matin = 0 ;
    if($("#rdv_petit_matin").is(":checked")) petit_matin = 1 ;
    var mms = 0 ;
    if($("#rdv_mms").is(":checked")) mms = 1 ;
    var param = "id="+$("#rdv_id").val()+"&petit_matin="+petit_matin+"&mms="+mms ;
    param+="&date="+$("#rdv_date").val() ;
    param+="&id_acte="+$("#rdv_id_acte").val() ;
    // alert($("#cf_url").val()+"/rdv/trait_details_rdv?"+param) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/rdv/trait_details_rdv",
      data:param,
      success:function(msg){
        $('#dialog-deatils_rdv').modal('hide') ;
      }
    }) ;
  }
}

function supprimeRdv(id) {
  if(confirm('Etes vous sur ?')){
    var param = "id="+id ;
    // alert($("#cf_url").val()+"/rdv/maj_rdv?"+param) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/rdv/sup_rdv",
      data:param,
      success:function(msg){
        listePrescription() ;
      }
    }) ;
  }
}

function majRdv(obj) {
  var champ = obj.name ;
  var id = obj.getAttribute("rel") ;
  var type = obj.type ;
  if(type=="checkbox"){
    var val = 0 ;
    if($("#"+champ+"_"+id).is(":checked")) val = 1 ;
  }
  else{
    var val = $("#"+champ+"_"+id).val() ;
  }
  var param = "id="+id+"&champ="+champ+"&val="+encodeURIComponent(val) ;
  // alert($("#cf_url").val()+"/rdv/maj_rdv?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/rdv/maj_rdv",
    data:param,
    success:function(msg){
      if(msg!="") alert(msg) ;
    }
  }) ;
}
function initScan(id_patient_scan) {
  var streaming = false,
      video        = document.querySelector('#video'),
      cover        = document.querySelector('#cover'),
      canvas       = document.querySelector('#canvas'),
      photo        = document.querySelector('#photo'),
      startbutton  = document.querySelector('#startbutton'),
      width = 640,
      height = 0;

      // const constraints = {
      //   video: {
      //     width: { min: 640, ideal: 1920, max: 1920 },
      //     height: { min: 400, ideal: 1080 },
      //     // aspectRatio: 1.777777778,
      //     // frameRate: { max: 30 },
      //     facingMode: "environment"
      //   }
      // };

  navigator.getMedia = ( navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia);

  navigator.getMedia(
    {
      video: {
        width: { min: 480, ideal: 480, max: 480 },
        // height: { min: 380, ideal: 380 },
        // aspectRatio: 1.777777778,
        // frameRate: { max: 30 },
        facingMode: "environment"
      },
      audio: false
    },
    function(stream) {
      if (navigator.mozGetUserMedia) {
        video.mozSrcObject = stream;
        video.srcObject = stream;
      } else {
        video.srcObject = stream;
        // var vendorURL = window.URL || window.webkitURL;
        // video.src = vendorURL.createObjectURL(stream);
      }
      video.play();
    },
    function(err) {
      alert("VERIFIEZ QUE VOTRE WEBCAM N'EST PAS UTILISEE PAR UNE AUTRE APPLICATION") ;
      console.log("An error occured! " + err);
    }
  );

  video.addEventListener('canplay', function(ev){
    if (!streaming) {
      width = video.videoWidth ;
      height = video.videoHeight / (video.videoWidth/width);
      var btnWidth = parseInt($("#startbutton").width()) ;
      var btnHeight = parseInt($("#startbutton").height()) ;
      // alert(btnWidth) ;
      // alert(btnHeight) ;
      $("#startbutton").css("top",(height-(btnHeight+20))+"px") ;
      $("#startbutton").css("left",(width/2)+"px") ;
      $("#startbutton").css("visibility","visible") ;
      video.setAttribute('width', width);
      video.setAttribute('height', height);
      canvas.setAttribute('width', width);
      canvas.setAttribute('height', height);
      streaming = true;
    }
  }, false);

  function takepicture() {
    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(video, 0, 0, width, height);
    // var data = canvas.toDataURL('image/png');
    // alert(canvas.toDataURL('image/base64')) ;
    var param = "id_patient_scan="+id_patient_scan+"&base64="+encodeURIComponent(canvas.toDataURL('image/base64')) ;
    // alert($("#cf_url").val()+"/scan/scan_document?"+param) ;
    $.ajax({
      type: "POST",
      url: $("#cf_url").val()+"/scan/scan_document",
      data: param,
      success: function(msg){
        $('#scanModal').modal('hide') ;
      }
    });
    // photo.setAttribute('src', data);
  }

  startbutton.addEventListener('click', function(ev){
      takepicture();
    ev.preventDefault();
  }, false);
}
function scanDoc() {

  var id_rdv = $("#id_rdv_scan").val() ;
  var id_patient_scan = $("#id_patient_scan").val() ;
  var param = "id_patient_scan="+$("#id_patient_scan").val()+"&id_rdv="+id_rdv ;

  $('#dialog-deatils_rdv').modal('hide') ;
  $("#div_dialog").html("") ;
  $('#dialog-deatils_rdv').modal('dispose') ;
  // alert($("#cf_url").val()+"/scan/simple?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/scan/simple",
    data:param,
    success:function(msg){
      $("#div_dialog").html(msg) ;
      $('#scanModal').modal('show') ;
      $('#scanModal').on('shown.bs.modal', function () {

        initScan(id_patient_scan) ;
        /*
        // alert("ici") ;
        feather.replace();

        const controls = document.querySelector('.controls');
        const cameraOptions = document.querySelector('.video-options>select');
        // const facingOptions = document.querySelector('.facing-options>select');
        const video = document.querySelector('video');
        const canvas = document.querySelector('canvas');
        const screenshotImage = document.querySelector('img');
        const buttons = [...controls.querySelectorAll('button')];
        let streamStarted = false;

        const [play, pause, screenshot] = buttons;
        // alert($("#facingMode").val()) ;
        const constraints = {
          video: {
            width: {
              min: 1280,
              ideal: 1920,
              max: 2560,
            },
            height: {
              min: 720,
              ideal: 1080,
              max: 1440
            },
            facingMode: "environment"
          }
        };

        play.onclick = () => {
          if (streamStarted) {
            video.play();
            play.classList.add('d-none');
            // pause.classList.remove('d-none');
            return;
          }
          if ('mediaDevices' in navigator && navigator.mediaDevices.getUserMedia) {
            const updatedConstraints = {
              ...constraints,
              deviceId: {
                exact: cameraOptions.value
              }
            };
            startStream(updatedConstraints);
          }
        };

        cameraOptions.onchange = () => {
          const updatedConstraints = {
            ...constraints,
            deviceId: {
              exact: cameraOptions.value
            }
          };

          startStream(updatedConstraints);
        };

        const pauseStream = () => {
          video.pause();
          play.classList.remove('d-none');
          pause.classList.add('d-none');
        };

        const doScreenshot = () => {
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
          canvas.getContext('2d').drawImage(video, 0, 0);
          screenshotImage.src = canvas.toDataURL('image/webp');
          screenshotImage.classList.remove('d-none');
          var param = "id_patient_scan="+id_patient_scan+"&base64="+encodeURIComponent(canvas.toDataURL('image/base64')) ;
          // alert($("#cf_url").val()+"/scan/scan_document?"+param) ;
          $.ajax({
            type: "POST",
            url: $("#cf_url").val()+"/scan/scan_document",
            data: param,
            success: function(msg){
              $('#scanModal').modal('hide') ;
            }
          });
          // alert(canvas.toDataURL('image/base64')) ;
        };

        const doChange = () => {

        };

        pause.onclick = pauseStream;
        screenshot.onclick = doScreenshot;
        // change.onclick = doChange;

        const startStream = async (constraints) => {
          const stream = await navigator.mediaDevices.getUserMedia(constraints);
          handleStream(stream);
        };


        const handleStream = (stream) => {
          video.srcObject = stream;
          play.classList.add('d-none');
          // pause.classList.remove('d-none');
          screenshot.classList.remove('d-none');
          change.classList.remove('d-none');

        };


        const getCameraSelection = async () => {
          const devices = await navigator.mediaDevices.enumerateDevices();
          const videoDevices = devices.filter(device => device.kind === 'videoinput');
          const options = videoDevices.map(videoDevice => {
            return `<option value="${videoDevice.deviceId}">${videoDevice.label}</option>`;
          });
          cameraOptions.innerHTML = options.join('');
        };

        getCameraSelection();


          if (streamStarted) {
            video.play();
            play.classList.add('d-none');
            pause.classList.remove('d-none');
            return;
          }
          if ('mediaDevices' in navigator && navigator.mediaDevices.getUserMedia) {
            const updatedConstraints = {
              ...constraints,
              deviceId: {
                exact: cameraOptions.value
              }
            };
            startStream(updatedConstraints);
          }

          */

      }) ;
      $('#scanModal').on('hide.bs.modal', function () {
        detailsRDV(id_rdv) ;
      }) ;
    }
  }) ;

}

function supprimeSnap(id_patient,snap) {
  if(confirm('Etes vous sûr ?')){
    var param = "id_patient="+id_patient+"&snap="+encodeURIComponent(snap) ;
    // alert($("#cf_url").val()+"/patient/liste_snap?"+param) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/patient/supprime_snap",
      data:param,
      success:function(msg){
        listeSnap() ;
      }
    }) ;
  }
}

function afficheMessage(message) {
  $("#div_erreur_upload").html(message) ;
}

function listeSnap() {
  var param = "id="+$("#id").val() ;
  // alert($("#cf_url").val()+"/patient/liste_snap?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/patient/liste_snap",
    data:param,
    success:function(msg){
      $("#snap").html(msg) ;
      $(".div_snap").hover(function(){
        $("#div_isnap_"+$(this).attr('rel')).show() ;
      },function(){
        $("#div_isnap_"+$(this).attr('rel')).hide() ;
      }) ;
    }
  }) ;
}

function form(id) {
  var param = "id="+id ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/patient/form",
    data:param,
    success:function(msg){
      $("#div_patient").html(msg) ;
      listeVille() ;
      listePrescription() ;
      listeSnap() ;
    }
  }) ;
}

function scanOrdonnance() {

  var id_prescription = $("#id_prescription").val() ;
  var param = "id_prescription="+$("#id_prescription").val() ;

  $('#dialog-form_prescription').modal('hide') ;
  $("#div_dialog").html("") ;
  $('#dialog-form_prescription').modal('dispose') ;
  // alert($("#cf_url").val()+"/scan/simple?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/scan/simple",
    data:param,
    success:function(msg){
      $("#div_dialog").html(msg) ;
      $('#scanModal').modal('show') ;
      $('#scanModal').on('shown.bs.modal', function () {
        // alert("ici") ;
        feather.replace();

        const controls = document.querySelector('.controls');
        const cameraOptions = document.querySelector('.video-options>select');
        // const facingOptions = document.querySelector('.facing-options>select');
        const video = document.querySelector('video');
        const canvas = document.querySelector('canvas');
        const screenshotImage = document.querySelector('img');
        const buttons = [...controls.querySelectorAll('button')];
        let streamStarted = false;

        const [play, pause, screenshot] = buttons;
        // alert($("#facingMode").val()) ;
        const constraints = {
          video: {
            width: {
              min: 1280,
              ideal: 1920,
              max: 2560,
            },
            height: {
              min: 720,
              ideal: 1080,
              max: 1440
            },
            facingMode: "environment"
          }
        };

        play.onclick = () => {
          if (streamStarted) {
            video.play();
            play.classList.add('d-none');
            // pause.classList.remove('d-none');
            return;
          }
          if ('mediaDevices' in navigator && navigator.mediaDevices.getUserMedia) {
            const updatedConstraints = {
              ...constraints,
              deviceId: {
                exact: cameraOptions.value
              }
            };
            startStream(updatedConstraints);
          }
        };

        cameraOptions.onchange = () => {
          const updatedConstraints = {
            ...constraints,
            deviceId: {
              exact: cameraOptions.value
            }
          };

          startStream(updatedConstraints);
        };

        const pauseStream = () => {
          video.pause();
          play.classList.remove('d-none');
          pause.classList.add('d-none');
        };

        const doScreenshot = () => {
          canvas.width = video.videoWidth;
          canvas.height = video.videoHeight;
          canvas.getContext('2d').drawImage(video, 0, 0);
          screenshotImage.src = canvas.toDataURL('image/webp');
          screenshotImage.classList.remove('d-none');
          // alert($("#cf_url").val()+"/scan/sav_snap?id_bu="+$("#id_bu").val()+"&base64="+canvas.toDataURL('image/base64')) ;
          $.ajax({
            type: "POST",
            url: $("#cf_url").val()+"/scan/scan_ordonnance",
            data: "id_prescription="+id_prescription+"&base64="+encodeURIComponent(canvas.toDataURL('image/base64')),
            success: function(msg){
              $('#scanModal').modal('hide') ;
            }
          });
          // alert(canvas.toDataURL('image/base64')) ;
        };

        const doChange = () => {

        };

        pause.onclick = pauseStream;
        screenshot.onclick = doScreenshot;
        // change.onclick = doChange;

        const startStream = async (constraints) => {
          const stream = await navigator.mediaDevices.getUserMedia(constraints);
          handleStream(stream);
        };


        const handleStream = (stream) => {
          video.srcObject = stream;
          play.classList.add('d-none');
          // pause.classList.remove('d-none');
          screenshot.classList.remove('d-none');
          change.classList.remove('d-none');

        };


        const getCameraSelection = async () => {
          const devices = await navigator.mediaDevices.enumerateDevices();
          const videoDevices = devices.filter(device => device.kind === 'videoinput');
          const options = videoDevices.map(videoDevice => {
            return `<option value="${videoDevice.deviceId}">${videoDevice.label}</option>`;
          });
          cameraOptions.innerHTML = options.join('');
        };

        getCameraSelection();


          if (streamStarted) {
            video.play();
            play.classList.add('d-none');
            pause.classList.remove('d-none');
            return;
          }
          if ('mediaDevices' in navigator && navigator.mediaDevices.getUserMedia) {
            const updatedConstraints = {
              ...constraints,
              deviceId: {
                exact: cameraOptions.value
              }
            };
            startStream(updatedConstraints);
          }

      }) ;
      $('#scanModal').on('hide.bs.modal', function () {
        formPrescription(id_prescription) ;
      }) ;
    }
  }) ;

}

function traitFormPrescription() {
  if($("#date").val()==""){
    alert("Veuillez selectionner la date de la prescription...") ;
    $("#date").focus() ;
  }
  else if($("#du").val()==""){
    alert("Veuillez selectionner la date de début de la prescription...") ;
    $("#du").focus() ;
  }
  else if($("#au").val()==""){
    alert("Veuillez selectionner la date de fin de la prescription...") ;
    $("#au").focus() ;
  }
  else{

    var param = "id="+$("#id_prescription").val() ;
    param+="&date="+encodeURIComponent($("#date").val()) ;
    param+="&du="+encodeURIComponent($("#du").val()) ;
    param+="&au="+encodeURIComponent($("#au").val()) ;
    param+="&details="+encodeURIComponent($("#details").val()) ;
    // alert($("#cf_url").val()+"/patient/trait_form?"+param) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/prescription/trait_form",
      data:param,
      success:function(msg){
        $('#dialog-form_prescription').modal('hide') ;
      }
    }) ;

  }
}

function initScan(id_patient_scan) {
  var streaming = false,
      video        = document.querySelector('#video'),
      cover        = document.querySelector('#cover'),
      canvas       = document.querySelector('#canvas'),
      photo        = document.querySelector('#photo'),
      startbutton  = document.querySelector('#startbutton'),
      width = 640,
      height = 0;

      // const constraints = {
      //   video: {
      //     width: { min: 640, ideal: 1920, max: 1920 },
      //     height: { min: 400, ideal: 1080 },
      //     // aspectRatio: 1.777777778,
      //     // frameRate: { max: 30 },
      //     facingMode: "environment"
      //   }
      // };

  navigator.getMedia = ( navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia ||
                         navigator.msGetUserMedia);

  navigator.getMedia(
    {
      video: true,
      audio: false
    },
    function(stream) {
      if (navigator.mozGetUserMedia) {
        video.mozSrcObject = stream;
        video.srcObject = stream;
      } else {
        video.srcObject = stream;
        // var vendorURL = window.URL || window.webkitURL;
        // video.src = vendorURL.createObjectURL(stream);
      }
      video.play();
    },
    function(err) {
      alert("VERIFIEZ QUE VOTRE WEBCAM N'EST PAS UTILISEE PAR UNE AUTRE APPLICATION") ;
      console.log("An error occured! " + err);
    }
  );

  video.addEventListener('canplay', function(ev){
    if (!streaming) {
      width = video.videoWidth ;
      height = video.videoHeight / (video.videoWidth/width);
      var btnWidth = parseInt($("#startbutton").width()) ;
      var btnHeight = parseInt($("#startbutton").height()) ;
      // alert(btnWidth) ;
      // alert(btnHeight) ;
      $("#startbutton").css("top",(height-(btnHeight+20))+"px") ;
      $("#startbutton").css("left",(width/2)+"px") ;
      $("#startbutton").css("visibility","visible") ;
      video.setAttribute('width', width);
      video.setAttribute('height', height);
      canvas.setAttribute('width', width);
      canvas.setAttribute('height', height);
      streaming = true;
    }
  }, false);

  function takepicture() {
    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(video, 0, 0, width, height);
    // var data = canvas.toDataURL('image/png');
    // alert(canvas.toDataURL('image/base64')) ;
    var param = "id_patient_scan="+id_patient_scan+"&base64="+encodeURIComponent(canvas.toDataURL('image/base64')) ;
    // alert($("#cf_url").val()+"/scan/scan_document?"+param) ;
    $.ajax({
      type: "POST",
      url: $("#cf_url").val()+"/scan/scan_document",
      data: param,
      success: function(msg){
        $('#scanModal').modal('hide') ;
      }
    });
    // photo.setAttribute('src', data);
  }

  startbutton.addEventListener('click', function(ev){
      takepicture();
    ev.preventDefault();
  }, false);
}

function scanDoc(id_patient) {

  // var id_rdv = $("#id_rdv_scan").val() ;
  var id_patient_scan = id_patient ;
  var param = "id_patient_scan="+id_patient ;

  // $('#dialog-deatils_rdv').modal('hide') ;
  // $("#div_dialog").html("") ;
  // $('#dialog-deatils_rdv').modal('dispose') ;
  // alert($("#cf_url").val()+"/scan/simple?"+param) ;
  $.ajax({
    type:"POST",
    url:$("#cf_url").val()+"/scan/simple",
    data:param,
    success:function(msg){
      $("#div_dialog").html(msg) ;
      $('#scanModal').modal('show') ;
      $('#scanModal').on('shown.bs.modal', function () {

        initScan(id_patient_scan) ;


      }) ;
      $('#scanModal').on('hide.bs.modal', function () {
        listeSnap() ;
      }) ;
    }
  }) ;

}

function traitForm() {
  if($("#nom").val()==""){
    alert("Nom obligatoire...") ;
    $("#nom").focus() ;
  }
  else if($("#prenom").val()==""){
    alert("Prénom obligatoire...") ;
    $("#prenom").focus() ;
  }
  else if($("#cp").val()==""){
    alert("Code postal obligatoire...") ;
    $("#cp").focus() ;
  }
  else if($("#id_ville").val()=="0"){
    alert("Ville obligatoire...") ;
    $("#id_ville").focus() ;
  }
  else{
    var param = "id="+$("#id").val() ;
    param+="&nom="+encodeURIComponent($("#nom").val()) ;
    param+="&prenom="+encodeURIComponent($("#prenom").val()) ;
    param+="&dn="+encodeURIComponent($("#dn").val()) ;
    param+="&adresse="+encodeURIComponent($("#adresse").val()) ;
    param+="&complement="+encodeURIComponent($("#complement").val()) ;
    param+="&cp="+encodeURIComponent($("#cp").val()) ;
    param+="&id_ville="+$("#id_ville").val() ;
    param+="&tel="+encodeURIComponent($("#tel").val()) ;
    param+="&memo="+encodeURIComponent($("#memo").val()) ;
    // alert($("#cf_url").val()+"/patient/trait_form?"+param) ;
    $.ajax({
      type:"POST",
      url:$("#cf_url").val()+"/patient/trait_form",
      data:param,
      success:function(msg){
        // $("#div_patient").html(msg) ;
        alert("MODIFICATIONS ENREGISTREES") ;
        form(msg) ;
      }
    }) ;
  }
}

$(document).ready(function(){
  if($("#action").val()=="new") form(0) ;
  else liste() ;
  // alert("ICI") ;
}) ;
