//(function() {

$(document).ready(function() {
    
  var streaming = false,
      video        = document.querySelector('#videoObj'),
      cover        = document.querySelector('#cover'),
      canvas       = document.querySelector('#canvasObj'),
      photo        = document.querySelector('#photoObj'),
      photoPaciente = document.querySelector('#imgFotoPaciente'),
      startbutton  = document.querySelector('#startbutton'),
      width = 520 /*200*/,
      /*height = 0*/
      height = 370 /*150*/;

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

  navigator.getMedia(
    { 
      video: true, 
      audio: false 
    },
    function(stream) {
    	
      if (navigator.mozGetUserMedia) { 
        video.mozSrcObject = stream;
        
      } else {
      	//const stream = await navigator.mediaDevices.getUserMedia({ video: true });
				//video.srcObject = stream;

        var vendorURL = window.URL || window.webkitURL;
        //console.log("vendorURL:" + vendorURL);
        //video.src = vendorURL ? vendorURL.createObjectURL(stream) : stream;
        video.srcObject = stream;
        
      }
      video.play();
    },
    function(err) {
      console.log("An error occured! " + err);
    }
  );

  video.addEventListener('canplay', function(ev){
    if (!streaming) {
     
      //height = video.videoHeight / (video.videoWidth/width);
      console.log("video.videoHeight: "+ video.videoHeight +" / video.videoWidth: "+ video.videoWidth +" / 48 height: "+ height);
      
      video.setAttribute('width', width);
      video.setAttribute('height', height);
      canvas.setAttribute('width', width);
      canvas.setAttribute('height', height);
      streaming = true;
    }
    console.log("video.addEventListener");
  }, false);

  function takepicture() {
    console.log("takepicture");
    canvas.width = width;
    canvas.height = height;
    
    //console.log("video: "+ video);
    console.log("width: "+ width +" / height: "+ height);
    
    canvas.getContext('2d').drawImage(video, 0, 0, width, height);
    
    var data = canvas.toDataURL('image/png');
    
    //console.log("data: "+ data);
    
    photo.setAttribute('src', data);

    $('#imgFotoPaciente').attr("src", data);
    
    $('#videoObj').css({"display":"none"});
    $('#photoObj').css({"display":"block"});
    
    abrirCamara();
    //setTimeout(function(){ abrirCamara(); }, 2000);
    
    setTimeout(function(){ 
        
        $('#videoObj').css({"display":"block"});
        $('#photoObj').css({"display":"none"});
    
    }, 2000);
    
  }

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

//})();

});
