//BUSQUEDA DE TABMEDICOS
var formaTABMEDICOS = null;
var panelTABMEDICOS = null;
var intMode = 100;
var idTienda = null, idProveedor=null;
var GridStoreTABMEDICOS = null;
var strToday ="";
var strEspecialidadSel = "";
//var map;
var geocoder;
var arrMarkers = [];
var intMiliseconds = 800;

function constructor(intCase){

	//console.log("TABMEDICOS_Constructor");
	idTab = 'TABMEDICOS';
	
    getLocation();
    
	var intWidth = $(document).width()-40;
	var intHeight = $(window).height();

	//alert("intHeight: "+ intHeight +" / intHeight2: "+ intHeight2);

	//$("#div1").css("height", (intHeight-195) +"px");
	//$("#map_canvas").css("height", (intHeight-100) +"px");

	$("#div1").css("height", (intHeight/2)-40 +"px");
	$("#div2").css("height", (intHeight/2)-40 +"px");

	//var strToday = moment().format("DD/MM/YYYY");
	//$("#divFiltrosMedicos").find("#txtFechaGral").val(strToday);

	//
    if(intCase==1){
        getDataMedicos("ENDOCRINOLOGO");
    	initMap();
    }else if(intCase==2){
        getEspecialidades( 1, $("#divFiltrosMedicos").find("#selectEspecialidad") );
        //getDataMedicos("ENDOCRINOLOGO");
        getVendedores();
    	initMap();
    }else if(intCase==3){
        getDataRutas();
    }
    
	//mouseEvent();

	/*$( "#dialog-estadistica-emails" ).dialog({
		  dialogClass: 'clsJustBtnClose',
		  resizable: false,
		  autoOpen: false,
		  position:"top",
		  draggable: false,
		  width: 1500,
		  height: 800,
		  modal: true
		  ,open: function() {}
		  ,close: function() {

		  }
	});
    */
    
    var widthDialog = 700, heightDialog = 600;
    if(intWidth<800){
        widthDialog = intWidth;
        heightDialog = intHeight-50;
    }
    
	$( "#dialog-registrar-visita" ).dialog({
		  dialogClass: 'smallTitleStuff',
		  resizable: false,
		  autoOpen: false,
		  position:"top",
		  draggable: false,
		  width: widthDialog,
		  height: heightDialog,
		  modal: true
		  ,buttons: {
				"Registrar": function() {
					guardarVisita();
				},
				"Cancelar": function() {
					$( this ).dialog( "close" );
				}
		  }
		  ,open: function() {
		      //$(body).css('overflow', 'hidden');
		      $("body").css({ overflow: 'hidden' })
		  }
		  ,close: function() {
            $( "#dialog-registrar-visita" ).find("#intMedico").val('');
            $("body").css({ overflow: 'inherit' })

		  }
	});

}

//LOCATION
var intVisita = 0;
function getLocation(){
	navigator.geolocation.getCurrentPosition(geolocationSuccess, geolocationError);
}

var geolocationSuccess = function(position) {
	var strLat = position.coords.latitude;
	var strLng = position.coords.longitude;
	
	intVisita++;
	
	var intMedico = $( "#dialog-registrar-visita" ).find("#intMedico").val();
	var strData = "("+ intVisita +") Med: " + intMedico + " / Latitud: " + strLat + " / Longitud: "+ strLng ;
	//alert( strData );
	
	var newHtml = $("#div3").html();
	if(newHtml!=""){
	    newHtml = newHtml + strData +"<br/>";
	}
	$("#div3").html(newHtml);
	
	//var strUrl = "data/dataVisitas.php?method=insertar&intUsuario="+ objUsuario.id +"&strLat="+ strLat +"&strLng="+ strLng +"&strDispositivo="+ navigator.userAgent +"&rnd="+ Math.random();
	//$.post(strUrl, function(dataNew){});

};
function geolocationError(error) {

	var intMedico = $( "#dialog-registrar-visita" ).find("#intMedico").val();
    var strData = "("+ intVisita +") Med: " + intMedico + " / code: "+ error.code + " / message: " + error.message ;
   	//alert( strData );
 
	var newHtml = $("#div3").html();
	if(newHtml!=""){
	    newHtml = newHtml + strData +"<br/>";
	}
	$("#div3").html(newHtml);
	
	//var strUrl = "data/dataVisitas.php?method=insertar&intUsuario="+ objUsuario.id +"&strLat=&strLng=&strDispositivo="+ navigator.userAgent +"&rnd="+ Math.random();
	//$.post(strUrl, function(dataNew){});

}

function verCorreo(strHtml){
	var strUrl = '/vista.php?strCodigo='+strHtml;
	
	$("#dialog-vista-correo").find("#iframeVistaCorreo").attr("src",strUrl);
	$("#dialog-vista-correo").dialog("open");
	//var win = window.open(strUrl, 'Vista');
	//win.document.write( strHtml );
	//win.print();
	//win.close();
}

var iconRojo = new google.maps.MarkerImage(
	"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|F00",
	null, /* size is determined at runtime */
	null, /* origin is 0,0 */
	null, /* anchor is bottom center of the scaled image */
	new google.maps.Size(12, 20)
); 

let map;

function makeGeocoder(){
	geocoder = null;
	geocoder = new google.maps.Geocoder();
}

function initMap() {
	//console.log("initMap / initMap");

	map = new google.maps.Map(document.getElementById("map_canvas"), {
		center: { lat: 25.6738675, lng: -100.3635384 },
		zoom: 13,
	});

	makeGeocoder();

    /*const drawingManager = new google.maps.drawing.DrawingManager({
        drawingMode: google.maps.drawing.OverlayType.MARKER,
        drawingControl: true,
        drawingControlOptions: {
          position: google.maps.ControlPosition.TOP_CENTER,
          drawingModes: [
            google.maps.drawing.OverlayType.MARKER,
            google.maps.drawing.OverlayType.CIRCLE,
            google.maps.drawing.OverlayType.POLYGON,
            google.maps.drawing.OverlayType.POLYLINE,
            google.maps.drawing.OverlayType.RECTANGLE,
          ],
        },
        markerOptions: {
          icon: "https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png",
        },
        circleOptions: {
          fillColor: "#ffff00",
          fillOpacity: 1,
          strokeWeight: 5,
          clickable: false,
          editable: true,
          zIndex: 1,
        },
    });
    
    drawingManager.setMap(map);

    */
    
    /*google.maps.event.addListener(map, 'click', function(event) {
        console.log(event.latLng);
        / *console.log(google.maps.geometry.poly.containsLocation(event.latLng, bermudaTriangle));
        var strHtml = $("#sidebar").html();
        $("#sidebar").html( strHtml + "<br/>"+ google.maps.geometry.poly.containsLocation(event.latLng, bermudaTriangle));
        * /
    });*/
			
    const poly = new google.maps.Polyline({
        strokeColor: "#000000",
        strokeOpacity: 1,
        strokeWeight: 3,
        map: map,
    });
    
    // Add a listener for the click event
    google.maps.event.addListener(map, "click", (event) => {
        console.log( "\nevent.latLng: "+ event.latLng );

        var strLatLng = "'"+ event.latLng +"'";
        //var strLatLng = event.latLng;
        strLatLng = strLatLng.replace("(","").replace(")","").replace("'","");
        //console.log( "strLatLng: "+ strLatLng );

        var arrLatLng = strLatLng.split(",");
        var lat = parseFloat(arrLatLng[0]);
        var lng = parseFloat(arrLatLng[1]);
        console.log( "lat: "+ lat +" / lng: "+ lng );

        arrPath.push( new google.maps.LatLng(lat, lng) );
        
        //addLatLngToPoly(event.latLng, poly);
    });

}

/*
function addLatLngToPoly(latLng, poly) {
  const path = poly.getPath();
  // Because path is an MVCArray, we can simply append a new coordinate
  // and it will automatically appear
  path.push(latLng);
  console.log( "latLng: "+ latLng );

  // Update the text field to display the polyline encodings
  const encodeString = google.maps.geometry.encoding.encodePath(path);

  if (encodeString) {
    //document.getElementById("encoded-polyline").value = encodeString;
    console.log( "encoded-polyline: "+ encodeString );
  }
}
*/

var arrPath = [];
var Polygon;

function crearPoligono(){
    console.log("crearPoligono / arrPath.length: "+ arrPath.length);
    
    Polygon = new google.maps.Polygon({
        /*paths: [
          new google.maps.LatLng(25.7339098, -100.2235377),
          new google.maps.LatLng(25.7328346, -100.2184147),
          new google.maps.LatLng(25.7240154, -100.2237153)
        ],*/
        
        paths: arrPath
        ,fillColor: '#ff9900'	
        ,fillOpacity: 0.4
        ,strokeWeight:1
        ,strokeColor:'#ff9900'
        ,map: map
        ,clickable:false
    });    

    seleccionarMedicos();
}

function limpiarMapa(){
    console.log("limpiarMapa / ");
    Polygon.setPath([]);
    arrPath = [];
    arrListMedSel = [];
	generarLista(1, arrItemsGral );
}

function seleccionarMedicos(){
    console.log("seleccionarMedicos ");
    
    if(arrItemsGral!=null){
		if(arrItemsGral.length>0){
			/*
			var strDomicilio = $.trim(arrItemsGral[iGlobal].strDomicilio);
			var strColonia = arrItemsGral[iGlobal].strColonia;
			var strCiudad = arrItemsGral[iGlobal].strCiudad;
			var strEstado = arrItemsGral[iGlobal].strEstado;
			var strCp = arrItemsGral[iGlobal].strCp;
			var strDireccion = strDomicilio +", "+ strColonia +", "+ strCiudad +", "+ strEstado +", "+ strCp;  
            */

    		for (var i=0; i<arrItemsGral.length; i++) {
    			var strMedico = arrItemsGral[i].strMedico;
                
                var strLat = arrItemsGral[i].strLatitud;
    			var strLng = arrItemsGral[i].strLongitud;
    			
    			var objLatLng = new google.maps.LatLng(strLat, strLng);
    			var boolEsta = google.maps.geometry.poly.containsLocation(objLatLng, Polygon);
    			
    			//console.log(boolEsta);

    			if( boolEsta ){
    				console.log("\nAGREGAR MEDICO "+ i +" con strMedico "+ strMedico);
    				arrListMedSel.push( arrItemsGral[i] );
    			}
    		}
    		
			//generarLista(2, arrListMedSel );
			verListaMedicos(true);

		}
	}
	
}

var iGlobal=0;

var arrItemsGral = []/*, arrEstudiosGral = [], arrColsGral = []*/;
function getDataMedicos(strEspecialidadArg){
	console.log("getDataMedicos / strEspecialidadArg: "+ strEspecialidadArg);

	if(1==1){

		clearOverlays();

		$("#divDataMedicos" ).html('<div style="width:100%; text-align:center;"><img src="../images/loading.gif" style="margin:50px auto 50px auto; width:60px;"/></div>');

		//var strFechas = $("#divResumen").find("#txtFechaGral").val();

		var strUrl = "https://www.softwaremedicodigital.com/app/data/catMedicos2020.php?method=consultar";
		
		if(strEspecialidadArg!="" && strEspecialidadArg!=null){
	    	strUrl += "&selectEspecialidad="+ encodeURIComponent(strEspecialidadArg);
		}else{
    		var selectEspecialidad = $("#divFiltrosMedicos").find("#selectEspecialidad").val();
    		if(selectEspecialidad!="" && selectEspecialidad!=null){
    			strUrl += "&selectEspecialidad="+ encodeURIComponent(selectEspecialidad);
    			strEspecialidadSel = encodeURIComponent(selectEspecialidad);
    		}
		}
		
		//var chkConUbicacion = $("#divLatIzquierda").find("#chkConUbicacion").attr("checked");
		//console.log("\n\n\nchkConUbicacion: "+ chkConUbicacion);
		//strUrl += "&chkConUbicacion="+ chkConUbicacion;
		strUrl += "&chkConUbicacion=true";

		$.post(strUrl, function(dataNew){

			var data = $.parseJSON(dataNew);
			arrItemsGral = data.Items;

			if(arrItemsGral.length>0){
				
				generarLista(1, arrItemsGral );

			}else{
				$("#divDataMedicos" ).html("<div style='margin:50px 25% 0 20%; font-weight:bold; font-size:20px; text-align: center;'>"+ data.Msg +"</div>");
			}

		});

	}

}

function getDataRutas(strEspecialidadArg){
	console.log("getDataRutas / strEspecialidadArg: "+ strEspecialidadArg);

	if(1==1){

		clearOverlays();

		$("#divDataMedicos" ).html('<div style="width:100%; text-align:center;"><img src="../images/loading.gif" style="margin:50px auto 50px auto; width:60px;"/></div>');

		//var strFechas = $("#divResumen").find("#txtFechaGral").val();

		var strUrl = "https://www.softwaremedicodigital.com/app/data/catMedicos2020.php?method=getrutas";
		
		if(strEspecialidadArg!="" && strEspecialidadArg!=null){
	    	strUrl += "&selectEspecialidad="+ encodeURIComponent(strEspecialidadArg);
		}else{
    		var selectEspecialidad = $("#divFiltrosMedicos").find("#selectEspecialidad").val();
    		if(selectEspecialidad!="" && selectEspecialidad!=null){
    			strUrl += "&selectEspecialidad="+ encodeURIComponent(selectEspecialidad);
    			strEspecialidadSel = encodeURIComponent(selectEspecialidad);
    		}
		}

		$.post(strUrl, function(dataNew){

			var data = $.parseJSON(dataNew);
			arrItemsGral = data.Items;

			if(arrItemsGral.length>0){
				
                var arrFieldsArg = [ 'intRuta', 'intUsuario', 'intVendedor', 'datFecha', 'intActiva', 'datFechaAlta', 'strClick', 'strFecha' ];

				var arrColumnsArg =  [
				      
				      { header: "Id Ruta", width: 35, dataIndex: 'intRuta', sortable: true },
				      
				      /*{ header: "Titulo", width: 80, dataIndex: 'strTitulo', sortable: true }*/

					  { header: "Socio Vendedor", width: 300, dataIndex: 'intVendedor', sortable: true,  align:'left'
						,renderer: function (value, metaDat, record) {
							var newValue = "";
							newValue += "<span style='font-size: 13px; padding-left:2px; font-weight:bold; '>"+ value +"</span>";

							return newValue;
						} 
					  }
					  ,{ header: "Fecha", width: 200, dataIndex: 'datFecha', sortable: true, align: 'left'}
					  ,{ header: "Activa", width: 120, dataIndex: 'intActiva', sortable: true, align: 'center'}
					  ,{ header: "Fecha Alta", width: 200, dataIndex: 'datFechaAlta', sortable: true, align: 'center'}

				];

				setTimeout(function(){
					makeGridExtJs("divDataRutas", arrFieldsArg, arrColumnsArg, arrItemsGral);
				},300);
				
			}else{
				$("#divDataMedicos" ).html("<div style='margin:50px 25% 0 20%; font-weight:bold; font-size:20px; text-align: center;'>"+ data.Msg +"</div>");
			}

		});

	}

}

function irA(){
    document.location.href='definerutas.php?omar=190280';    
}

function getLatLng(){
	//console.log("getLatLng ");
	
	if(arrItemsGral!=null){
		if(iGlobal<arrItemsGral.length){
			var strDomicilio = $.trim(arrItemsGral[iGlobal].strDomicilio);
			var strColonia = arrItemsGral[iGlobal].strColonia;
			var strCiudad = arrItemsGral[iGlobal].strCiudad;
			var strEstado = arrItemsGral[iGlobal].strEstado;

			var strCp = arrItemsGral[iGlobal].strCp;

			var strDireccion = strDomicilio +", "+ strColonia +", "+ strCiudad +", "+ strEstado +", "+ strCp;  

			var strLat = arrItemsGral[iGlobal].strLatitud;
			var strLng = arrItemsGral[iGlobal].strLongitud;

			if(strLat=="" && strLng=="" && strDomicilio!="" && strColonia!="" ){
				console.log("\n\n\nGeocodificar ("+ iGlobal +") con la direccion "+ strDireccion);

				var request = new Object(); //CREO UN OBJETO
				request.address = strDireccion;
				request.region = "mx";
				
				geocoder.geocode(request, addAddressToMap);
			
			}else{

				if(strLat!="NO ENCONTRADA" && strLng!="NO ENCONTRADA" && strDomicilio!="" && strColonia!="" ){

					var marker = createMarker(iGlobal, strDireccion, strLat, strLng , 0);
					arrMarkers.push(marker);

				}

				iGlobal++;

				setTimeout("getLatLng()", 200);
			}
			
		}else{

			//showMsg('Termino la carga '+ numCarga +'.<br/> Direcciones encontradas '+ (iEncontradas) + '  de ' + arrDirecciones.length + ' registros.<br/><hr/>', 2);
				
		}
	}
}

var iOverQueryLimit = 0;
function addAddressToMap(response, status) { // AGREGA EL PUNTO AL MAPA
	console.log("\naddAddressToMap", response, status);

	if(status=="OK"){

		if(response!=null){
			if(response[0]==null){	
				//console.log(status);
			}else{
							
				var formatted_address = response[0].formatted_address;

				var strLocation = response[0].geometry.location.toString();
				strLocation = strLocation.replace("(","").replace(")","");
				var arrLocation = strLocation.split(",");
				var strLat = $.trim(arrLocation[0]);
				var strLng = $.trim(arrLocation[1]);

				var marker = createMarker(iGlobal, formatted_address, strLat, strLng , 1);
				arrMarkers.push(marker);
				
			}
		}

		iGlobal++;

		setTimeout("getLatLng()", intMiliseconds);

	}else{
		if(status=="OVER_QUERY_LIMIT"){
			iOverQueryLimit++;
		}else if(status=="ZERO_RESULTS"){
			if(arrItemsGral!=null){
				if(iGlobal<arrItemsGral.length){
					var intMedico = arrItemsGral[iGlobal].intMedico;		
					guardarLatLng(intMedico, "NO ENCONTRADA", "NO ENCONTRADA");
				}
			}
		}

		if(iOverQueryLimit<10){
			iGlobal++;

			setTimeout("getLatLng()", intMiliseconds);
		}else{
			console.log("\n\n----------------------------- SE LLEGO A 10 OVER_QUERY_LIMIT, SE REINICIA EN 5 MINS " + new Date() );
			
			iOverQueryLimit = 0;
			makeGeocoder();

			setTimeout("getLatLng()", 1000 * 60 * 1);

		}
	}

}  //CIERRA FUNCION adAdressToMap

var intEncontradas = 0;
function createMarker(iArr, strDireccion, strLat, strLng, intGuardar) {
	intEncontradas++;

	//console.log("\n createMarker / iGlobal: "+ iGlobal +" / iArr: "+ iArr +" / "+ intEncontradas +" encontradas de "+ arrItemsGral.length +" / strDireccion: "+ strDireccion +" / strLat: "+ strLat +" / strLng: "+ strLng );

	var intMedico = "", strMedico = "";

	if(arrItemsGral!=null){
		if(iArr<arrItemsGral.length){
			intMedico = arrItemsGral[iArr].intMedico;			
			strMedico = arrItemsGral[iArr].strMedico;	

			if(intGuardar==1){
				guardarLatLng(intMedico, strLat, strLng);

				$("#divDataMedicos").find("#divImgUbi_"+ intMedico).css({"visibility":"visible","display":"inline-block"});
			}

			var marker = createMarkerFinal(intMedico, strMedico, strDireccion, strLat, strLng);		    
		    return marker;

		}else{

			return null;
		
		}

	}else{
		return null;
	}
	
}

function createMarkerFinal(intMedico, strMedico, strDireccion, strLat, strLng) {

	//console.log("\n createMarker / iGlobal: "+ iGlobal +" / iArr: "+ iArr +" / "+ intEncontradas +" encontradas de "+ arrItemsGral.length +" / strDireccion: "+ strDireccion +" / strLat: "+ strLat +" / strLng: "+ strLng );

	var marker = new google.maps.Marker({
    	id: intMedico
		,position: new google.maps.LatLng( parseFloat(strLat), parseFloat(strLng) )
		,map: map
		,label: intMedico
		,icon: "images/pin1.png"
		/*,draggable: true*/
	    ,animation: google.maps.Animation.DROP
		,title: intMedico
	});

	var infowindow = new google.maps.InfoWindow({
		content: "<b>" + strMedico + "</b><br/>" + strDireccion,
	});

	marker.addListener("click", () => {
	  if (marker.getAnimation() !== null) {
	    marker.setAnimation(null);
		infowindow.close();
	  } else {
	    marker.setAnimation(google.maps.Animation.BOUNCE);
	    infowindow.open(map, marker);
	    addToList(marker.id);
	  }
	});
	
	return marker;

}

var arrListMedSel = [];

function addToList(id){

	var strBg = $("#divLatIzquierda").find("#divId_"+ id).css("background-color");
	//console.log( "\n\n ------> strCase: "+ strCase +", id:"+ id +", strBg:"+ strBg );

	var intCuantosInList = parseInt( $("#divContadorSel").html() );

	if(strBg=="rgb(150, 193, 212)"){ //CELESTE	
		//strCase = "add";

		for (var i=0; i<arrItemsGral.length; i++) {
			var intMedico = arrItemsGral[i].intMedico ;
			
			if( parseInt(id)===parseInt(intMedico) ){
				console.log("\nAGREGAR MEDICO "+ i +" con Id "+ id);
				arrListMedSel.push( arrItemsGral[i] );
			}
		}

		intCuantosInList++;

		$("#divLatIzquierda").find("#divId_"+ id).css({"background":"rgb(200, 100, 255)"});

	}else if(strBg=="rgb(200, 100, 255)"){ //MORADO
		//strCase = "remove";

		var iAEliminar = null;

		for(var i=0; i<arrListMedSel.length; i++){
			var intMedico = arrListMedSel[i].intMedico;
			//console.log( "COMPARANDO id: "+ id +", intMedico: "+ intMedico );
			
			if( parseInt(id)===parseInt(intMedico) ){
				//console.log("REMOVER "+ i +" con Id "+ id);
				//arrListMedSel.slice(i);
				iAEliminar = i;
				break;
			}
		}

		//console.log("401 iAEliminar: "+ iAEliminar);
		
		if(iAEliminar != null){
			//console.log("iAEliminar: "+ iAEliminar);
			arrListMedSel.splice(iAEliminar, 1);
		}

		intCuantosInList--;
		
		for (var i=0; i<arrListMedSel.length; i++) {
			var intMedico = arrListMedSel[i].intMedico ;
			//console.log(intMedico + " en arrListMedSel");
		}

		$("#divLatIzquierda").find("#divId_"+ id).css({"background":"rgb(150, 193, 212)"});

	}

	$("#divContadorSel").html(intCuantosInList);

	//console.log( "-----------------------" );
}

function verListaMedicos(bool){
	//var bool = objCheckbox.checked;
	console.log( "verListaMedicos / bool: "+ bool );

	if(bool){

		clearOverlays(); 
		/*
		for (var i = 0; i < arrMarkers.length; i++ ) {
		arrMarkers[i].setMap(null);
		}
		arrMarkers.length = 0;
		intEncontradas = 0;
		*/

		generarLista(2, arrListMedSel );

	}else{

		clearOverlays(); 

		generarLista(1, arrItemsGral );

	}
}

function generarLista(intCase, arrThis ){

	iGlobal=0;
	iOverQueryLimit = 0;

	var strHtmlGrid = "";

	for (var i=0; i<arrThis.length; i++) {

		var intMedico = arrThis[i].intMedico ;
		var strMedico = arrThis[i].strMedico ;
		var strEspecialidad = arrThis[i].strEspecialidad ;
		var strEmail = arrThis[i].strEmail ;
		var strConsultorio = arrThis[i].strConsultorio;
		
		var strDomicilio = arrThis[i].strDomicilio;
		var strColonia = arrThis[i].strColonia;
		var strCiudad = arrThis[i].strCiudad;
		var strEstado = arrThis[i].strEstado;
		strDomicilio = strDomicilio +", "+ strColonia +", "+ strCiudad +", "+ strEstado;

		var strCp = arrThis[i].strCp;
		var strTelefono = arrThis[i].strTelefono;
		
		var strLat = arrThis[i].strLatitud;
		var strLng = arrThis[i].strLongitud;

		//var strTable = makeGrid( i, strClaveEmpresa, strEmpresa, arrEstudios, true );
		strHtmlGrid += "<div id='divMedico_"+ intMedico +"' onmouseover='changeBg(1, this), readMarkers(1, "+ intMedico +")'  onmouseout='changeBg(0, this), readMarkers(2, "+ intMedico +")' style='background:#FFFFFF; width:100%; height:auto; display:table-cell; float:left; border-bottom:1px solid #ccc; padding:25px 6px 25px 6px; margin:0px; box-sizing:border-box;'>";

			strHtmlGrid += "<div id='divConMed_"+ intMedico +"' style='font-weight:bold; width: 100%; display: flex; '>";

				var strBg = "rgb(150, 193, 212)";
				for(var k=0; k<arrListMedSel.length; k++){
					var intMedicoInList = arrListMedSel[k].intMedico;
					//console.log( "COMPARANDO id: "+ id +", intMedico: "+ intMedico );
					
					if( parseInt(intMedicoInList)===parseInt(intMedico) ){
						strBg = "rgb(200, 100, 255)";
						break;
					}
				}

				//if(intCase==1){ //arrItemsGral
					strHtmlGrid += "<div id='divId_"+ intMedico +"' onclick='addToList("+ intMedico +");' style='float:left; min-width: 50px; text-align:center; padding: 8px 6px 0px; background-color:"+ strBg +"; border-radius:6px;  margin-right:6px; display:inline; pointer-events:auto;'>"+ intMedico +"</div>";
				//}else if(intCase==2){ //arrListMedSel  --- Morado
				//	strHtmlGrid += "<div id='divId_"+ intMedico +"' onclick='addToList("+ intMedico +");' style='float:left; min-width: 50px; text-align:center; height:27px; background-color:rgb(200, 100, 255); border-radius:6px; padding: 12px 6px 0px 6px; margin-right:6px; display:inline; pointer-events:auto;'>"+ intMedico +"</div>";
				//}

				strHtmlGrid += "<div id='divNombre' style='float:left; min-width: 380px; width: 90%; margin-top:6px; font-size: 16px; color: #4d4b4b;'><a href='javascript: editarMedico("+ intMedico +");' style='text-decoration:none;'>"+ i +" - "+ strMedico +"</a></div>";
				//strHtmlGrid += "<div id='divCheckbox' style='float:left; width:25px; margin-top:6px; font-size: 16px; color: #4d4b4b;'><input type='checkbox' id='chkMed_"+ i +"' onchange='onchnChkMed("+ intMedico +")' style='width:18px; height:18px;'/></div>";
				
				var strStyleImgUbi = "";
				//if(strLat=="" && strLng==""){
				if(strLat=="NO ENCONTRADA" && strLng=="NO ENCONTRADA"){
					strStyleImgUbi = "visibility:hidden; display:none;";
				}
				strHtmlGrid += "<div id='divImgUbi_"+ intMedico +"' style='"+ strStyleImgUbi +"float:left; width:25px; text-align: right; margin-top:6px; font-size: 16px; color: #4d4b4b;'><img src='images/pin1.png' style='width:14px;'/></div>";

			strHtmlGrid += "</div>";

			strHtmlGrid += "<div style='float:left; width:100%; padding-left:65px; box-sizing:border-box; font-weight:normal; font-size: 14px; pointer-events:none; color: #759e21;'>";
				strHtmlGrid += strEspecialidad;
			strHtmlGrid += "</div>";
			
			/*strHtmlGrid += "<div style='float:left; width:100%; padding-left:65px; box-sizing:border-box; pointer-events:none; color: #979797;'>";
				strHtmlGrid += "<img src='images/star-icon2.png'/><img src='images/star-icon2.png'/><img src='images/star-icon2.png'/><img src='images/star-icon2.png'/>";
			strHtmlGrid += "</div>";
            */
            
			strHtmlGrid += "<div style='float:left; width:100%; font-weight:normal; pointer-events:none; color: #979797;'>";
				strHtmlGrid += strConsultorio;
			strHtmlGrid += "</div>";
			strHtmlGrid += "<div style='float:left; width:100%; font-weight:normal; pointer-events:none; color: #979797;'>";
				strHtmlGrid += strDomicilio + ", C.P. "+ strCp;
			strHtmlGrid += "</div>";
			strHtmlGrid += "<div style='float:left; width:100%; font-weight:normal; pointer-events:none; color: #979797;'>";
				strHtmlGrid += "Email: "+ strEmail +", Tel. "+ strTelefono;
			strHtmlGrid += "</div>";

            if(intCase==2){
    			strHtmlGrid += "<div style='float:left; width:100%; font-weight:normal; color: #979797;'>";
    				strHtmlGrid += "<input type='button' value='Registrar visita' class='clsBtn' onclick='registrarVisita("+ intMedico +")' />";
    			strHtmlGrid += "</div>";
            }
            
		strHtmlGrid += "</div>";			

		if(intCase==2){ //arrListMedSel
			var marker = createMarkerFinal(intMedico, strMedico, strDomicilio, strLat, strLng);
			arrMarkers.push(marker);
		}

	}

	$("#divDataMedicos" ).html(strHtmlGrid);
	$("#divLatIzquierda").find("#div2" ).html(arrThis.length + " medicos encontrados");

	if(intCase==1){ //arrItemsGral
		setTimeout("getLatLng()", intMiliseconds);
	}

}

function registrarVisita(intMedicoArg){
    getLocation();
    
    //alert("RegistrarVisita  / intMedicoArg: "+ intMedicoArg);
    
    $("#dialog-registrar-visita").find("#intMedico").val( intMedicoArg );
	$("#dialog-registrar-visita").dialog("open");

}

function guardarVisita(){
    
    var intMedico = $("#dialog-registrar-visita").find("#intMedico").val();
    var strConclusion = $("#dialog-registrar-visita").find("#txtConclusion").val();
    alert("intMedico: "+ intMedico +" / strConclusion: "+ strConclusion );

}


function verCorreo(strHtml){
	var strUrl = '/vista.php?strCodigo='+strHtml;
	
	$("#dialog-vista-correo").find("#iframeVistaCorreo").attr("src",strUrl);
	$("#dialog-vista-correo").dialog("open");
	//var win = window.open(strUrl, 'Vista');
	//win.document.write( strHtml );
	//win.print();
	//win.close();
}

function formSubmit(){
	console.log("formSubmit");

	formSubirImg.submit();
	setTimeout(function(){

		getArchivos(intTipoArchivoSel);

	},2000);

	if(1==12){
		$( "#formSubirImg" ).submit(function( event ) {

		  alert( "Handler for .submit() called." );
		  getArchivos(1);

		  //event.preventDefault();

		});
	}
}

function imprimir(){

	var strHtml = $("#divDataMedicos").html();
	var strMapa = $("#div2").html();
	//strMapa = $("#map_canvas").html();

	var win = window.open('', 'printlista');
	win.document.write( strMapa + strHtml );
	win.print();
	//win.close();

}

function guardarLatLng(intMedico, strLat, strLng){
	var strUrl = "https://www.softwaremedicodigital.com/app/data/catMedicos2020.php?method=abc&intMode=3";
	strUrl += "&intMedico="+ intMedico;
	strUrl += "&strLat="+ strLat;
	strUrl += "&strLng="+ strLng;
	
	$.get(strUrl, function(dataNew){

		//var data = $.parseJSON(dataNew);
		console.log(dataNew);

	});
}

function abcMedico(intMedico){
	var strUrl = "https://www.softwaremedicodigital.com/app/data/catMedicos2020.php?method=abc&intMode=2";
	strUrl += "&intMedico="+ intMedico;
	strUrl += "&strLat="+ strLat;
	strUrl += "&strLng="+ strLng;
	//console.log("\n\n\ncargarDatos / strUrl1: "+ strUrl1);
	
	/*
	$.get(strUrl, function(dataNew){

		//var data = $.parseJSON(dataNew);
		console.log(dataNew);

	});
	*/
}

function readMarkers(intCase, idArg){
    
	//ANIMACION NULA PARA TODOS
	
	for (var i=0; i<arrMarkers.length; i++) {
		var objMarker = arrMarkers[i] ;
		var id = objMarker.id ;
		//console.log("readMarkers / idArg: "+ idArg +" / id: "+ id);
		objMarker.setAnimation(null);
	}

	if(intCase==1){
		//ANIMACION PARA UN MARKER
		
		for (var i=0; i<arrMarkers.length; i++) {
			var objMarker = arrMarkers[i] ;
			var id = objMarker.id ;
			//console.log("readMarkers / idArg: "+ idArg +" / id: "+ id);

			if(idArg==id){
				objMarker.setAnimation(google.maps.Animation.BOUNCE);
			}
		}
	}
	
}

function clearOverlays() {	
  console.log("clearOverlays");

  for (var i = 0; i < arrMarkers.length; i++ ) {
    arrMarkers[i].setMap(null);
  }
  arrMarkers.length = 0;
  intEncontradas = 0;
}

function toggleBounce() {
  if (marker.getAnimation() !== null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}
/*---------------------------*/
function changeBg(intCase, objDiv){
	var id = objDiv.id;
	var strBg = $("#"+ id).css("background");

	//console.log("id: "+ id +" / intCase: "+ intCase +" / strBg: "+ strBg);
	//if(strBg=="rgb(241 244 244)"){
	if(intCase==0){
		$("#"+ id).css({"background":"rgb(255 255 255)"});
	}else{
		$("#"+ id).css({"background":"rgb(241 244 244)"});
	}
}

function getEspecialidades(intCase, selObj){
	var strUrl = "https://www.softwaremedicodigital.com/app/data/catMedicos2020.php?method=getespecialidades";
	//console.log("\n\n\ncargarDatos / strUrl1: "+ strUrl1);
	
	$.post(strUrl, function(dataNew){
		var data = $.parseJSON(dataNew);
		var arrItems = data.Items;
		
		selObj.empty();
		//selObj.append('<option value="">Especialidad?</option>');
		for (var i=0; i<arrItems.length; i++) {
		  var lbl = capitalizeFirst( arrItems[i].strEspecialidad );
		  selObj.append('<option value="'+ lbl +'">'+ lbl +'</option>');
		}
		
		if(intCase==1){
			getDataMedicos();
		}

	});
}

function getVendedores(intCase, selObj){
	var strUrl = "https://www.softwaremedicodigital.com/app/data/catMedicos2020.php?method=getvendedores";
	//console.log("\n\n\ncargarDatos / strUrl1: "+ strUrl1);
	
	$.post(strUrl, function(dataNew){
		var data = $.parseJSON(dataNew);
		var arrItems = data.Items;
		var selObj = $("#divFiltrosMedicos").find("#selectVendedor");

		selObj.empty();
		//selObj.append('<option value="">Especialidad?</option>');
		for (var i=0; i<arrItems.length; i++) {
		  var lbl = capitalizeFirst( arrItems[i].strVendedor );
		  selObj.append('<option value="'+ lbl +'">'+ lbl +'</option>');
		}
    
	});
}


function makeGridExtJs(strDivContArg, arrFieldsArg, arrColsArg, arrItemsArg){
	var heightDiv = "", GridStore = "";

	var objDiv = $( "#"+ strDivContArg ); 
	heightDiv = objDiv.css("height");
	console.log("makeGridExtJs", "heightDiv: "+ heightDiv, objDiv);
	
	if(heightDiv!=null){

		heightDiv = parseInt( heightDiv.toString().replace("px","") ) - 0;
		
		GridStore = new Ext.data.JsonStore({
		  root: 'Items',
		  fields: arrFieldsArg,
		  data: { Items: arrItemsArg }
		});   
								
		console.log("makeGridExtJs / arrItemsArg.length = " + arrItemsArg.length);
		
		var gridN = new Ext.grid.GridPanel({
			frame: false,
			width:'100%',
			height: heightDiv,
			fbar : [ new Ext.Toolbar.TextItem('<font size=2>Total: '+ arrItemsArg.length + '</font>')],
			store: GridStore,
			columns: arrColsArg
		});
		
		//'<font size=2>Registros: '+ arrItems.length + '</font>'
		
		console.log("makeGridExtJs / strDivContArg: "+ strDivContArg);

		$( "#"+ strDivContArg ).html("");
		gridN.render( document.getElementById(strDivContArg) );
	}
}

function editarMedico(intMedico){
	console.log("ditarMedico / intMedico: "+ intMedico);

	$( "#dialog-medico" ).dialog("open");

}

function abrirEnviarEmail(){

	var intEmailsSel = arrListMedSel.length;
	console.log("abrirEnviarEmail / intEmailsSel: "+ intEmailsSel);

	if(intEmailsSel>0){

		var strEspecialidad = $("#divFiltrosMedicos").find("#selectEspecialidad").val();
		//$( "#dialog-envio-email" ).find("#div1_0").html("Enviar a<br/><div style='margin-top:10px; font-size:16px;'>"+ strEspecialidad +"</div>");
		//$( "#dialog-envio-email" ).find("#div1_0").html("<div style='margin-top:0px; font-size:16px;'>"+ strEspecialidad +"</div>");
		
		$("#dialog-envio-email").find("#divEmails").empty();

		var strEmails = "";
		var intEmails = 0;
		for (var j=0; j<arrListMedSel.length; j++) {

			var intMedico = arrListMedSel[j].intMedico;
			var strEmail = arrListMedSel[j].strEmail ;
			var strMedico = arrListMedSel[j].strMedico ;

			if(strEmail!==""){

				$("#dialog-envio-email").find("#divEmails").append("<li style='margin-bottom:3px;'>"+ strMedico +"</li>");

				//strEmails += strEmail +",";
				strEmails += intMedico+"*"+strEmail +"*"+strMedico +",";
				intEmails++;
			}
		}

		if(strEmails!=""){
			strEmails = strEmails.substring(0, strEmails.length-1);
			//console.log("strEmails: "+ strEmails);

			//if(intEmails>1){ intEmails+=" emails"; }else{ intEmails+=" email"; }
			//$("#dialog-envio-email").find("#spanNumEmails").html( intEmails );

			//$("#dialog-envio-email").find("#txtEmails").val(strEmails);
			$("#dialog-envio-email").find("#txtEmails").val('443*kropijac@gmail.com*Omar Cruz,1148*kropijac@hotmail.com*Jose Martinez');
			
			$("#dialog-envio-email").dialog("open");

		}else{
			alert("Los médicos seleccionados no tienen email.");
		}

	}else{
		alert("Debe seleccionar médicos");
	}

}

function enviarEmail(intMedico){
	console.log("enviarEmail / intMedico: "+ intMedico);
	
	//var dataForm = new FormData();
	var strCodigoCamp = uniqueID(1, 100, 1000);

	var strTitulo = $("#dialog-envio-email").find("#txtTitulo").val();
    //dataForm.append("strTitulo", strTitulo);
	
	var strAsunto = $("#dialog-envio-email").find("#txtAsunto").val();
    //dataForm.append("strAsunto", strAsunto);

	var strEmails = $("#dialog-envio-email").find("#txtEmails").val();
	var intEnviados = strEmails.split(",").length;
    //dataForm.append("intEnviados", intEnviados);
    //console.log("intEnviados: "+ intEnviados);
	
	var strTextAlt = $("#dialog-envio-email").find("#txtTextoAlternativo").val();
	if(strTextAlt!=""){ strTextAlt = encodeURIComponent(strTextAlt);   }

	var strHtml = $.trim($("#divHtmlVistaPrevia").html());	
	if(strHtml!=""){ strHtml = encodeURIComponent(strHtml);   }

	var strUrl = "procesos/guardarcampania.php?mode=1"; 
    strUrl += "&rnd="+ Math.random();
    
    if(strTitulo!="" && strAsunto!="" && strEmails!="" && strTextAlt!="" && strHtml!=""){ 
    	
    	$("#dialog-envio-email").find("#divEnvioEmail").css({"pointer-events":"none", "opacity":"0.5"});
    	$("#dialog-envio-email").find("#divLoading").css({"display":"block", "position":"absolute"});

	    $.post( strUrl, 
	    	{ strCodigoCamp: strCodigoCamp, strTitulo: strTitulo, strQuery: strAsunto, intEnviados: intEnviados, strTextAlt: strTextAlt, strHtml: strHtml }, 
	    	function( data ) {

			    //alert( "data: " + data ); //data: {"exito":"si","msg":""}

			    var objJson = $.parseJSON(data);
			    if(objJson.exito=="si"){

					var strUrl = "enviaremail.php?"; 
				    strUrl += "&rnd="+ Math.random();
				                
				    $.post( strUrl, 
				    	{ strCodigoCamp: strCodigoCamp, strAsunto: strAsunto, strEmails: strEmails, strTextAlt: strTextAlt, htmlVistaPrevia: strHtml }, 
				    	function( data ) {

						    //alert( "Data: " + data );

							var strUrl = "procesos/guardarcampania.php?mode=2"; 
						    strUrl += "&rnd="+ Math.random();
						                
						    $.post( strUrl, 
						    	{ strCodigoCamp: strCodigoCamp }, 
						    	function( data ) {

								    //alert( "Data: " + data );

							    	$("#dialog-envio-email").find("#divEnvioEmail").css({"pointer-events":"auto", "opacity":"1"});
							    	$("#dialog-envio-email").find("#divLoading").css({"display":"none", "position":"none"});
							    	$("#dialog-envio-email").dialog("close");

							    	subirImagenaPgm(strCodigoCamp, strHtml);

								}
						  	);

						}
				  	);
					
				}

			}
	  	);

  	}else{

  		alert("Debe introducir el Titulo, el Asunto, el Contenido y el Texto Alternativo");

  	}

	/*
	$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: strUrl,
        data: dataForm ,
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        success: function (data) {
   			console.log("data: "+ data);

            //var dataJson = $.parseJSON(data);
    		//var strUrlImagenUrl1 = dataJson.strUrlImagenUrl1;
            
        },
        error: function (e) {
            alert("Error al enviar el correo, favor de intentarlo nuevamente.");
        }
    });
	*/

}

function seleccionarTodos(){
	console.log("seleccionarTodos ");

	var intCuantosInList = parseInt( $("#divContadorSel").html() );

	for (var i=0; i<arrItemsGral.length; i++) {
		var intMedico = arrItemsGral[i].intMedico ;
		
		$("#divLatIzquierda").find("#divId_"+ intMedico).css({"background":"rgb(200, 100, 255)"});

		var bEsta = false;

		for (var j=0; j<arrListMedSel.length; j++) {
			var intMedicoInLisMedSel = arrListMedSel[j].intMedico ;

			if(intMedico==intMedicoInLisMedSel){
				bEsta = true;
				break;
			}
		}

		if(bEsta==false){
			arrListMedSel.push( arrItemsGral[i] );
			intCuantosInList++;
		}

	}

	$("#divContadorSel").html(intCuantosInList);

}




