//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();

	//var intHeight2 = $(window).height();



	//$("#divMedicos").empty();

	//$("#divMedicos").html(dataNew);



	//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");

    }else if(intCase==2){

        cargarEspecialidades( 1, $("#divFiltrosMedicos").find("#selectEspecialidad") );

        //getDataMedicos("ENDOCRINOLOGO");

    }



	initMap();



	//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 abrirDialogEmails(strCase, strCodigo){

	console.log("abrirDialogEmails / strCase: "+ strCase +" / strCodigo: "+ strCodigo);



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



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



	var strUrl = "data/dataEmails.php?method="+ strCase +"&strCodigo="+ strCodigo +"&strFechas="+ strFechas;

	

	$.post(strUrl, function(dataNew){



		//$("#divGridEstadisticaEmails").empty();



		var data = $.parseJSON(dataNew);

		var arrItemsArg = data.arrItems;



		if(arrItemsArg.length>0){



			//$("#divGridEstadisticaEmails").html('');



			if(strCase=="getcampanias"){



				var arrFieldsArg = [ 'intCampania', 'strTitulo', 'strCodigo', 'strQuery', 'intEnviados', 'pctAbiertos', 'intAbiertos', 'pctClicks', 'intClicks'

				,'strFile', 'strTextAlt', 'strHtml', 'strUrlImagen', 'strFechaAlta' ];



				var arrColumnsArg =  [

				      

				      /*{ header: "Id", width: 35, dataIndex: 'intCampania', sortable: true }*/



				      { header: "", width: 40, dataIndex: 'strHtml', sortable: true, align: 'center'

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							newValue += "<a href='javascript: verCorreo(\""+ record.data["strCodigo"] +"\");' style='font-size: 15px; color:#C60; '><img src='images/lupa.png' style='width:23px;'></a>";



							return newValue;

						} 

					  }



				      ,{ header: "Titulo", width: 300, dataIndex: 'strTitulo', sortable: true 

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							//newValue += "<div style='font-size: 15px; '>"+ value +"</div>";

							newValue += "<a href='javascript: abrirDialogEmails(\"getdetallecampania\",\""+ record.data["strCodigo"] +"\");' style='font-size: 15px; color:#C60; padding-left:2px; overflow:hidden; '>"+ value +"</a>";



							return newValue;

						}

				  	  }

					 

					  ,{ header: "Enviados", width: 90, dataIndex: 'intEnviados', sortable: true, align: 'center'

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							newValue += "<span style='font-size: 15px; padding-left:2px; '>"+ value +"</span>";



							return newValue;

						}

					  }



					  ,{ header: "% Abiertos", width: 90, dataIndex: 'pctAbiertos', sortable: true, align: 'center'

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							if(value!=""){ value = "%"+ value; }

							newValue += "<span style='font-size: 15px; color:#C60; padding-left:2px; overflow:hidden; '>"+ value +"</span>";



							return newValue;

						} 

					  }

					  ,{ header: "Abiertos", width: 90, dataIndex: 'intAbiertos', sortable: true, align: 'center'

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							newValue += "<span style='font-size: 15px; padding-left:2px; '>"+ value +"</span>";



							return newValue;

						}

					  }

				  

					  ,{ header: "% Clicks", width: 90, dataIndex: 'pctClicks', sortable: true, align: 'center'

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							if(value!=""){ value = "%"+ value; }

							newValue += "<span style='font-size: 15px; color:#C60; padding-left:2px; overflow:hidden; '>"+ value +"</span>";



							return newValue;

						} 

					  }

					  ,{ header: "Clicks", width: 90, dataIndex: 'intClicks', sortable: true, align: 'center'

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							newValue += "<span style='font-size: 15px; padding-left:2px; '>"+ value +"</span>";



							return newValue;

						}

					  }

					  ,{header: "Fecha de envío", width: 170, dataIndex: 'strFechaAlta', sortable: true 

						,renderer: function (value, metaDat, record) {

							var newValue = "";

							newValue += "<span style='font-size: 15px; padding-left:2px; '>"+ value +"</span>";



							return newValue;

						}

					  }



				];



				$( "#dialog-estadistica-emails" ).find("#divHeader").css("display","none");

				

				setTimeout(function(){

					makeGridExtJs("divGridEstadisticaEmails", arrFieldsArg, arrColumnsArg, arrItemsArg);

				},300);



				$( "#dialog-estadistica-emails" ).dialog("open");



			}else if(strCase=="getdetallecampania"){



				var arrFieldsArg = [ 'intId', 'strCodigo', 'intCliente', 'strCliente', 'strEmail', 'strAbierto', 'strClick', 'strFecha' ];



				var arrColumnsArg =  [

				      

				      /*{ header: "Id", width: 35, dataIndex: 'intCampania', sortable: true }*/

				      

				      /*{ header: "Titulo", width: 80, dataIndex: 'strTitulo', sortable: true }*/



					  { header: "Medico", width: 300, dataIndex: 'strCliente', 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: "Email", width: 200, dataIndex: 'strEmail', sortable: true, align: 'left'}

					  ,{ header: "Abierto", width: 140, dataIndex: 'strAbierto', sortable: true, align: 'center'}

					  ,{ header: "Click", width: 140, dataIndex: 'strClick', sortable: true, align: 'center'}



				];



				$( "#dialog-estadistica-emails" ).find("#divHeader").css("display","inline-block");



				setTimeout(function(){

					makeGridExtJs("divGridEstadisticaEmails", arrFieldsArg, arrColumnsArg, arrItemsArg);

				},300);



			}



		}else{

			

			$( "#dialog-estadistica-emails" ).find("#divHeader").css("display","inline-block");



			$( "#dialog-estadistica-emails" ).find("#divGridEstadisticaEmails").html("<div style='margin:100px 40%; font-size:20px;'>No se encontraron registros</div>");



		}



	});



}



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,

    });

    

    //setPath(path)

    

    // 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);

    });



	// SUCURSALES

	/*if(1==12){

		var rndElement = Math.round(Math.random()* 1000);



		var strUrl = "../mapa/data/sucursales.xml?" + rndElement;

		

		$.get(strUrl, function(data){

			var markers = data.documentElement.getElementsByTagName("marker");

		    //console.log("markers: "+ markers);

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

			   //console.log("i: "+ markers[i].getAttribute("name"));

			   var type = markers[i].getAttribute("type");



			   if(type=="sucursal"){



					var point = new google.maps.LatLng( parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")) );

					var name = markers[i].getAttribute("name");

					var label = markers[i].getAttribute("label");

					var address = markers[i].getAttribute("address");



				    //console.log("i: "+ markers[i].getAttribute("name") +" / type: "+ type);



					var marker = new google.maps.Marker({

			            position: new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))),

			            map: map

			        });

			   }

			}

		 });

	}	*/



}



var arrPath = [];



function setPolygon(){

    console.log("setPolygon / arrPath.length: "+ arrPath.length);

    

    var bermudaTriangle = 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

    });    

}



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 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 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(objCheckbox){

	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>";



			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 = $("#divLatDerecha").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 cargarEspecialidades(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 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 subirImagenaPgm(strCodigoCamp, strHtml){



	var strUrl = "https://www.pgmlab.com/email/subir.php?"; 

    strUrl += "&rnd="+ Math.random();

                

    $.post( strUrl, 

    	{ strCodigoCamp: strCodigoCamp, strHtml: strHtml }, 

    	function( data ) {

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



			/*var objJson = $.parseJSON(data);

		    if(objJson.exito=="si"){



		    }*/

		}

  	);

		

}



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);



}



var objSelObj = "";

function agregarElemento(intTipo){

	console.log("\n ---> agregarElemento / intTipo: "+ intTipo);



	var strHtml = $("#dialog-envio-email").find("#divHtmlVistaPrevia").html();

	var strHtmlNuevo = "";



	var uniqueid = Date.now();

	if(intTipo==1){ //RENGLON

		strHtmlNuevo = "<div id='obj_"+ uniqueid +"' onclick='setObj(this)' title='renglon' class='clsObjVisPre' style='float:left; width:100%; box-sizing:border-box; padding:0px; min-height:50px; height:auto; border:1px solid #ccc;'></div>";

	

	}else if(intTipo==2){ //2 COLS

		strHtmlNuevo = "<div id='div_"+ uniqueid +"' class='clsObjVisPre' title='renglon' style='float:left; width:100%; box-sizing:border-box; padding:0px; min-height:20px; height:auto; border:1px solid #ccc;'>";

			

			strHtmlNuevo += "<div id='obj1_"+ uniqueid +"' onclick='setObj(this)' title='columna1' class='clsObjVisPre' style='float:left; width:50%; box-sizing:border-box; padding:0px; min-height:50px; height:auto; border:1px solid #ccc;'>";

			strHtmlNuevo += "</div>";

			

			uniqueid = Date.now();

			strHtmlNuevo += "<div id='obj2_"+ uniqueid +"' onclick='setObj(this)' title='columna2' class='clsObjVisPre' style='float:left; width:50%; box-sizing:border-box; padding:0px; min-height:50px; height:auto; border:1px solid #ccc;'>";

			strHtmlNuevo += "</div>";



		strHtmlNuevo += "</div>";



	}else if(intTipo==3){ //IMAGEN

		strHtmlNuevo = "<img id='obj_"+ uniqueid +"' src='images/imagenfaltante1.png' title='imagen' onclick='changeSrcImg(this)' class='clsObjVisPre' style='max-width:600px; width:100%; height:auto; padding:0px;'/>";

	

	}else if(intTipo==4){ //TEXTO

		var idTextArea = 'textarea_'+ uniqueid;

		//strHtmlNuevo = "<div id='obj_"+ uniqueid +"' onclick='setObj(this)' ondblclick='escribirTexto(this)' title='texto' class='clsObjVisPre' style='float:left; width:100%; box-sizing:border-box; padding:0px; min-height:20px; height:auto; border:1px solid #ccc;'>";

		strHtmlNuevo = "<div id='obj_"+ uniqueid +"' onclick='setObj(this)' title='texto' class='clsObjVisPre' style='float:left; width:100%; box-sizing:border-box; padding:0px; min-height:20px; height:auto; border:1px solid #ccc;'>";

		strHtmlNuevo += "<textarea id='"+ idTextArea +"' style='width:100%; min-height:150px;'></textarea>";

		strHtmlNuevo += "</div>";



	}



	console.log("\nobjSelObj.nodeName: "+ objSelObj.nodeName );



	if(objSelObj!="" && objSelObj.nodeName==="DIV" ){

		console.log("objSelObj.id: "+ objSelObj.id );



		strHtml = $("#dialog-envio-email").find("#"+ objSelObj.id).html();



		$("#dialog-envio-email").find("#"+ objSelObj.id).html( strHtml += strHtmlNuevo );

	}else{

		$("#dialog-envio-email").find("#divHtmlVistaPrevia").html( strHtml += strHtmlNuevo );

	}



	if(intTipo==4){ //TEXTO

		console.log("ENTRA POR AGREGAR RICHTEXT EDITOR");

		$('#'+ idTextArea).richText();

	}

}



/*

function escribirTexto(objThis){

	console.log("\n---> setObj / objThis: "+ objThis +" / objThis.id: "+ objThis.id +" / objThis.title: "+ objThis.title );

	console.log( $(objThis) );

	console.log("objThis.nodeName: "+ objThis.nodeName);



	//$("#dialog-envio-email").find("#"+ objThis.id).css("border-color","#ea3107");

	$("#dialog-envio-email").find("#"+ objThis.id).append("<textarea style='width:100%; min-height:150px;'></textarea>");



	event.stopPropagation();

}

*/



function setObj(objThis){

	console.log("\n---> setObj / objThis: "+ objThis +" / objThis.id: "+ objThis.id +" / objThis.title: "+ objThis.title );

	console.log( $(objThis) );

	console.log("objThis.nodeName: "+ objThis.nodeName);



	$("#dialog-envio-email").find("#divHtmlVistaPrevia").css("border-color","#ccc");

	$("#dialog-envio-email").find(".clsObjVisPre").css("border-color","#ccc");

	$("#dialog-envio-email").find("#"+ objThis.id).css("border-color","#ea3107");



	//objSelId = objThis.id;

	//objSelObj = $(objThis);



	objSelObj = objThis;



	event.stopPropagation();

}



function setFormat(objThis){

	var intPx = 0;

	if(objThis.id=="spanAplus" || objThis.id=="spanAminus"){

		intPx =  $("#dialog-envio-email").find("#"+ objSelObj.id).css("font-size") ;

		if(intPx!=0){

			intPx = parseInt( intPx.replace("px","") );

		}

	}



	console.log("\n---> setFormat / objThis: "+ objThis +" / objThis.id: "+ objThis.id +" / objThis.nodeName: "+ objThis.nodeName +" / objSelObj.id: "+  objSelObj.id +" / intPx: "+ intPx );

	//console.log( $(objThis) );



	if(objThis.id=="spanClean"){

		objSelObj="";

		$("#dialog-envio-email").find("#divHtmlVistaPrevia").html( '' );

	}else if(objThis.id=="spanRelease"){

		objSelObj = "";

		$("#dialog-envio-email").find(".clsObjVisPre").css("border-color","#ccc");

		$("#dialog-envio-email").find("#divHtmlVistaPrevia").css("border-color","#ea3107");



	}else if(objThis.id=="spanAplus"){

		$("#dialog-envio-email").find("#"+ objSelObj.id).css("font-size", (intPx+2) );

	}else if(objThis.id=="spanAminus"){

		$("#dialog-envio-email").find("#"+ objSelObj.id).css("font-size", (intPx-2) );

	}else if(objThis.id=="spanN"){

		$("#dialog-envio-email").find("#"+ objSelObj.id).css("font-weight","bold");

	}else if(objThis.id=="spanNormal"){

		$("#dialog-envio-email").find("#"+ objSelObj.id).css("font-weight","normal");

	}else if(objThis.id=="spanLeft"){

		//$("#dialog-envio-email").find("#"+ objSelObj.id).css("float","left");

		$("#dialog-envio-email").find("#"+ objSelObj.id).css("text-align","left");

	}else if(objThis.id=="spanCenter"){

		$("#dialog-envio-email").find("#"+ objSelObj.id).css("text-align","center");

	}else if(objThis.id=="spanRight"){

		//$("#dialog-envio-email").find("#"+ objSelObj.id).css("float","right");

		$("#dialog-envio-email").find("#"+ objSelObj.id).css("text-align","right");

	}else if(objThis.id=="spanLink"){

		//$("#dialog-envio-email").find("#"+objThis.id).css("font-weight","bold");

	}else if(objThis.id=="spanSource"){



	}

}



var strIdImgSel = "";

function changeSrcImg(objImg){

	console.log("\n---> changeSrcImg / objImg: "+ objImg +" / objImg.id: "+ objImg.id +" / objImg.src: "+ objImg.src );

	strIdImgSel = objImg.id;

	seleccionarArchivo(1, 1, 1);

}



function dispararSubirArchivo(intCase){

	console.log("dispararSubirArchivo / intCase: "+ intCase);



	//if(intCase==1){ //Ver formulario

		$( "#divSeleccionarArchivo" ).find( "#inputFile" ).trigger("click");

	//}else if(intCase==2){

	//	$("#txtSubirVideo").trigger("click");

	//}

}



function seleccionarArchivo(intCase, intTipo, intMostrar){

	console.log("\n---> seleccionarArchivo / intCase: "+ intCase +" / intTipo: "+ intTipo +" / intMostrar: "+ intMostrar );



	if(intCase==0){ //Ver formulario



		strIdImgSel = "";



		$( "#dialog-envio-email" ).find("#divSeleccionarArchivo").animate({

		    height: "toggle"

		  }, 100, function() {

		    // Animation complete.		

			$( "#dialog-envio-email" ).find("#divSeleccionarArchivo").css("display", "none");

			

			$( "#dialog-envio-email" ).find("#divEnvioEmail").animate({

			    height: "toggle"

			  }, 100, function() {				

				$( "#dialog-envio-email" ).find("#divSeleccionarArchivo").css("display", "none");

				$( "#dialog-envio-email" ).find("#divEnvioEmail").css("display", "inline-block");

			});

		  });



	}else if(intCase==1){ //ver archivos



		$( "#dialog-envio-email" ).find("#divEnvioEmail").animate({

		    height: "toggle"

		  }, 400, function() {

		    // Animation complete.

			

			$( "#dialog-envio-email" ).find("#divEnvioEmail").css("display", "none");



			$( "#dialog-envio-email" ).find("#divSeleccionarArchivo").animate({

			    height: "toggle"

			  }, 10, function() {



				$( "#dialog-envio-email" ).find("#divEnvioEmail").css("display", "none");

				$( "#dialog-envio-email" ).find("#divSeleccionarArchivo").css("display", "inline-block");



				onchRadioTipoArc(intTipo, intMostrar);



			});



		});



	}



}



function onchRadioTipoArc(intTipoArg, intMostrarArg){

	console.log("onchRadioTipoArc / intTipoArg: "+ intTipoArg);



	$("#divSeleccionarArchivo").find(".clsRadioTipoArchivo").removeClass("clsRadioTipoArchivoActivo");

	

	$("#divRadioTipoArc"+ intTipoArg).addClass("clsRadioTipoArchivoActivo");



	if(intTipoArg==1){ var strBuscar = "imagenes";}

	if(intTipoArg==2){ var strBuscar = "videos";}

	console.log("Mostrar solo los "+ strBuscar);



	getArchivos(intTipoArg, intMostrarArg);



}



var intTipoArchivoSel = 1;

function getArchivos(intTipoArg, intMostrarArg){

	console.log("getArchivos / intTipoArg: "+ intTipoArg +" / intMostrarArg: "+ intMostrarArg);



	intTipoArchivoSel = intTipoArg;

	var strUrl = "getArchivos.php?i="+ intTipoArg ;

	//console.log("\n\n\ncargarDatos / strUrl1: "+ strUrl1);

	

	$.get(strUrl, function(dataNew){

		//$("#divSeleccionarArchivo").find("#div2").html(dataNew);



		var strHtml = "";

		var data = $.parseJSON(dataNew);

		var arrItems = data.arrItems;



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

			strHtml += "<div style='float:left; width:200px; height:230px; border:0px solid #ccc;'>";

				

				var strNombre = window.location.protocol +"//"+ window.location.hostname +"/"+ arrItems[i].strNombre;



				if(strNombre.indexOf(".mp4")>0){

					strHtml += "<video src='"+ strNombre +"' style='width:100%; height:84%;' controls></video>";

				}else{

					strHtml += "<img src='"+ strNombre +"' style='width:100%; height:84%;' />";

				}



				strHtml += "<div style='float:left; width:100%; text-align: center; padding: 4px; box-sizing: border-box; border:1px solid #ccc;'>";

				if(intMostrarArg==1){

					strHtml += "<a href='javascript: setArchivo("+ intTipoArg +",\""+ strNombre +"\");' style='text-decoration:none;'>Seleccionar</a>"; 

				}

				strHtml += "</div>"; 

			

			strHtml += "</div>"; 

		}

		

		$("#divSeleccionarArchivo").find("#div2").html(strHtml);



	});

}



function setArchivo(intTipo, strNombre){

	console.log("setArchivo / intTipo: "+ intTipo +" / strNombre: "+ strNombre +" / strIdImgSel: "+ strIdImgSel);



	if(intTipo==1){

		

		//$("#divEnvioEmail").find("#txtImagen").val(strNombre);

		//onchangeImg(strNombre);



		$("#dialog-envio-email").find("#"+ strIdImgSel).attr("src", strNombre);

		

	}else{

		$("#divEnvioEmail").find("#txtVideo").val(strNombre);

		onchangeVideo(strNombre);

	}



	seleccionarArchivo(0);



}



function onchangeImg(valor){

	console.log("onchangeImg / valor: "+ valor);



	$("#imgEmail").attr("src", "https://www.serviciospgmlab.com/" + valor);

	$("#imgEmail").css({"visibility":"visible","display":"inline-block"});

	$("#videoEmail").css({"visibility":"hidden","display":"none"});

        

}



function onchangeVideo(valor){

	//console.log("onchangeVideo / objThis: "+ objThis.id);



	$("#videoEmail").attr("src", "https://www.serviciospgmlab.com/" + valor);

	$("#videoEmail").css({"visibility":"visible","display":"inline-block"});

	$("#imgEmail").css({"visibility":"hidden","display":"none"});



}



