//VARIABLES GLOBAL var idStepAdd = 1; var map; var mapBuscador; var markerGroup = []; var pointList = []; var markerClusterGroup = null; var selCoop = ""; var selCoopTitulo = ""; var externalUser = false; var listHttpSessionTempData; var isFirstTimePassword = true; var homePage = "REGISTER"; var externalUser = false; var backurl = ""; var theme = ""; //var listConfigurationKeys = []; var localidad = ""; var saveUser = ""; var msjRegistracion = ""; var verMapa = true; var json = ""; $(document).ready(function () { getHttpSessionTempData(); getConfigurationSettings('urlNotificationService'); getConfigurationSettings('domainRegistro'); externalUser = listHttpSessionTempData["externalUser"]; backurl = listHttpSessionTempData["backurl"]; //theme = listHttpSessionTempData["theme"]; closeSession(); //Cerramos sesion para redireccionar al login. showMap(); $('#divSteps').attr('page', 'Usuario'); PreValidationJson(); if(externalUser){ $('.stepAvatar').remove(); //El paso 3 (subir imagen) no se utiliza cuando es AcaMarker $('#divFondo').css('background-image', 'url(../Content/themes/micampo/images/fondo_ACAmarket.jpg)'); $('#spnTituloLogo').text('Market'); $('#figureMarket').show(); } else{ $('#divFondo').css('background-image', 'url(../Content/themes/micampo/images/fondo2.jpg)'); $('#spnTituloLogo').text('Mi Campo'); $('#figureMiCampo').show(); } $('#txtEmail').blur(function () { ValidationField(this); //verificarUsuario(); }); //$('.date').mask('11/11/1111'); //$('.time').mask('00:00:00'); //$('.date_time').mask('00/00/0000 00:00:00'); //$('.cep').mask('00000-000'); //$('.phone').mask('0000-0000'); //$('.phone_with_ddd').mask('(00) 0000-0000'); //$('.mixed').mask('AAA 000-S0S'); //$('.cpf').mask('000.000.000-00', {reverse: true}); //$('.money').mask('000.000.000.000.000,00', {reverse: true}); //$('#txtTelefono').mask('(000) 000-0000'); //$('.txtCuit').mask('00-00000000-0'); $('#txtCuit').blur(function () { ValidationField(this); }); $('#txtNombreApellido').blur(function () { ValidationField(this); //verificarCampos($(this)[0].id); }); $('#txtAddress').blur(function () { $(this).val(localidad); ValidationField(this); //verificarCampos($(this)[0].id); }); $('#txtTelefono').blur(function () { ValidationField(this); //verificarCampos($(this)[0].id); }); $('#txtPassword1').blur(function () { if (!verificarPassword(1)) { $('#errorMensajePw1').html('' + strError); $('#errorMensajePw1').show(); } else { strError = ""; $('#errorMensajePw1').html(''); $('#errorMensajePw1').hide(); } }); $('#txtPassword2').blur(function () { isFirstTimePassword = false; if (!verificarPassword(2)) { $('#errorMensajePw2').html('' + strError); $('#errorMensajePw2').show(); } else { strError = ""; $('#errorMensajePw2').html(''); $('#errorMensajePw2').hide(); } }); $('#txtEmail').change(function(){ $('#txtUsuario').val($('#txtEmail').val()); }); //OpenModal $('#modal-opener').click(function () { window.openModal({ title: '¿Estas seguro de que quieres omitir?', content: 'Al omitir estarás borrando toda la información de usuario ingresada', acceptText: 'Omitir', cancelText: 'Cancelar', context: document.querySelector('.main-container'), }).then( e => window.location.href = "../MiCampo/Login", e => 'Modal Cancelado'); }); function PreValidationJson() { $.ajax({ url: '../WizardRegisterUser/PreValidationJson', //data: "{'theme' : '" + theme + "'}", async: false, type: 'post', contentType: 'application/json', success: function (data) { json = JSON.parse(data); var array = []; for (var i = 0; i < json.length; i++) { var pestana = json[i]; for (var key in pestana) { var keyPestana = key; var value = pestana[key]; for (var attribute in value) { var name = attribute; var valueName = value[attribute]; if (keyPestana == "progress2") verMapa = valueName; if (keyPestana == "saveUser") { saveUser = valueName; } else if (keyPestana == "msjRegistracion") { msjRegistracion = valueName; } if (valueName.ver == true) array.push($("#li" + name)); if (name == "pestanaVisible") { if (valueName == true) $("#" + keyPestana).show(); else $("#" + keyPestana).hide(); } else { if (valueName.ver == true) $("#txt" + name).show(); else $("#txt" + name).hide(); $("#txt" + name).attr("readonly", valueName.readonly); $("#txt" + name).attr("placeholder", valueName.display); $("#txt" + name).attr("validate", valueName.validate); $("#txt" + name).attr("requerid", valueName.requerid); $("#txt" + name).attr("name", name); if (valueName.format != "") $("#txt" + name).mask(valueName.format); } } } $("#step1").empty(); for (var i = 0; i < array.length; i++) $("#step1").append(array[i]); } }, error: function (e) { console.log(e); }, }); } function ValidationField(thisSel) { var validate = $(thisSel).attr("validate"); var name = $(thisSel).attr("name"); var value = $(thisSel).val(); var placeHolder = $(thisSel).attr("placeholder"); if ((validate != "" && validate != undefined) && value != "") { $.ajax({ url: '../WizardRegisterUser/ValidationField?data=' + validate + '&name=' + name + '&value=' + value, type: 'post', contentType: 'application/json', success: function (data) { resp = JSON.parse(data); $('#errorMensaje' + name).html(""); //if (resp.exist == false) { if (resp.isValid && resp.tieneCredito) { $('#errorMensaje' + name).html(""); $("#txt" + name).attr("isValid", true); for (var i = 0; i < resp.fields.length; i++) { var pestana = resp.fields[i]; for (var key in pestana) { var keyPestana = key; var value = pestana[key]; $("#txt" + keyPestana).val(value); $('#errorMensaje' + keyPestana).html(""); $("#txt" + name).attr("isValid", true); } } } else { if (resp.error != "") { $('#errorMensaje' + name).html(resp.error); $("#txt" + name).attr("isValid", false); } //else // $('#errorMensaje' + name).html("El " + placeHolder.toUpperCase() + " no es valido"); } //} //else { // $('#errorMensaje' + name).html("El " + placeHolder.toUpperCase() + " ya existe"); //} }, error: function (e) { console.log(e); }, }); } else if ($("#txt" + name).attr("requerid") == 'true') { if ($("#txt" + name).val() == "") $('#errorMensaje' + name).html("*"); else $('#errorMensaje' + name).html(""); } } }); //FIN DOCUMENT READY function verificarTodosRequeridos() { var entro = true; for (var i = 0; i < json.length; i++) { var pestana = json[i]; for (var key in pestana) { var keyPestana = key; var value = pestana[key]; for (var attribute in value) { var name = attribute; var valueName = value[attribute]; if (valueName.requerid == true) { if ($("#txt" + name).attr("validate") != "" && $("#txt" + name).attr("isValid") == 'false') { $('#errorMensajeCamposRequeridos').html('* Datos obligatorios').show(); entro = false; } else if ($("#txt" + name).val() == "" || $("#txt" + name).attr("isValid") == 'false') { $('#errorMensaje' + name).html("*"); $('#errorMensajeCamposRequeridos').html('* Datos obligatorios').show(); entro = false } } } } return entro; } //let isUsuarioValid = verificarUsuario(); //let isCuitValid = verificarCuit(); //let isNombreValid = verificarCampos('txtNombreApellido') ; //let isLocalidadValid = verificarCampos('txtAddress'); //let isTelefonoValid = verificarCampos('txtTelefono'); //if (!isUsuarioValid || !isCuitValid || !isNombreValid || !isLocalidadValid || !isTelefonoValid) // return false //else // return true } function verificarCampos(idCampo) { var campoRequeridoCompleto = false; //retorna FALSE var strMensaje = ""; if ($('#' + idCampo).val() != ''){ //si el valor del campo tiene algo distinto de vacío campoRequeridoCompleto = true; //retorna TRUE $('#errorMensajeCamposRequeridos').hide(); if(idCampo == 'txtNombreApellido'){ $('#errorMensajeNombreApellido').hide(); } else if(idCampo == 'txtAddress'){ $('#errorMensajeLocalidad').hide(); } else if(idCampo == 'txtTelefono'){ $('#errorMensajeTelefono').hide(); } } else{ if(idCampo == 'txtNombreApellido'){ strMensaje = '*'; $('#errorMensajeNombreApellido').html(strMensaje).show(); } else if(idCampo == 'txtAddress'){ strMensaje = '*'; $('#errorMensajeLocalidad').html(strMensaje).show(); } else if(idCampo == 'txtTelefono'){ strMensaje = '*'; $('#errorMensajeTelefono').html(strMensaje).show(); } $('#errorMensajeCamposRequeridos').html('* Datos obligatorios').show(); } return campoRequeridoCompleto; }; function nextStep(isBack) { if(idStepAdd < 4){ $('#step' + idStepAdd).hide(); if(idStepAdd == 1){ if (!verificarTodosRequeridos()){ $('#step' + idStepAdd).show(); return; } $('#errorMensajeCamposRequeridos').html('* Datos obligatorios').hide(); if ($("#progress2").is(":visible")) { $('#btnBackStep').show(); $('#sectionLogo').hide(); $('#sectionStep').hide(); //Mostramos el mapa setCooperativas(); $('#sectionMap').show(); $('#divSteps').attr('page', 'Mapa'); map.invalidateSize(); //re-ajusta la visualizacion del map map.setZoom(10); } else if(isBack != true) idStepAdd++; } if (idStepAdd == 2){ //Ocultamos el mapa if (verMapa == true) { if (!verificarCooperativa()) return; $('#sectionLogo').show(); $('#sectionStep').show(); $('#sectionMap').hide(); } if(externalUser){//Si es AcaMarker no debe subir una imagen de perfil por lo cual avanzamos directamente a la proximo paso idStepAdd++; $('#divSteps').attr('page', 'Password'); } else{ $('#divSteps').attr('page', 'Foto'); } } else if (idStepAdd == 3){ //Ocultamos Foto $('#divSteps').attr('page', 'Password'); } /* >>> PASO SIGUIENTE <<< */ idStepAdd++; $('#step' + idStepAdd).show(); $('#progress' + idStepAdd).removeClass("current"); $('#progress' + idStepAdd).addClass("complete"); } else if(idStepAdd == 4) { /* >>> PASO FINAL <<< */ verificarCamposRequeridos(); //Verificamos y guardamos $('#divSteps').attr('page', 'Password'); } } function backMainStep(){ idStepAdd = 1; $('#step' + idStepAdd).show(); $('#sectionLogo').show(); $('#sectionStep').show(); $('#sectionMap').hide(); $('#divSteps').attr('page', 'Usuario'); $('#progress' + 2).removeClass("complete"); $('#progress' + 2).addClass("current"); $('#progress' + idStepAdd).removeClass("current"); $('#progress' + idStepAdd).addClass("complete"); } function backStep() { if (idStepAdd == 1) window.location.href = "../MiCampo/Login"; else { $('#progress' + idStepAdd).removeClass("complete"); $('#progress' + idStepAdd).addClass("current"); $('#step' + idStepAdd).hide(); idStepAdd = idStepAdd - 2; if (idStepAdd == 1 && !verMapa) idStepAdd = 0; nextStep(true); $('#progress' + idStepAdd).removeClass("current"); $('#progress' + idStepAdd).addClass("complete"); } } function verificarCooperativa(){ var isSelected = true; if(selCoop == ""){ isSelected = false; window.openModal({ title: 'Aviso', content: 'Por favor, elegí una Cooperativa o Centro de Desarrollo Cooperativo.', acceptText: 'Aceptar', context: document.querySelector('.main-container'), }); } return isSelected; } function setCooperativas() { $('#loader0').show(); var urlSite = listHttpSessionTempData.urlNotificationService; var url = urlSite + "/html/acabaseservice.aspx?mt=GetMapa&appname=aca&domain=aca&fecUpd=" + "20000101"; //&category=CDC $.getJSON(url, function (result) { listCoop = result.result.value; fillMap(listCoop); $('#loader0').hide(); }) .fail(function (jqxhr, textStatus, error) { $('#loader0').hide(); OpenModalError1(textStatus); }); } function verificarUsuario(){ var isUsuarioRequerido = true; var strMensaje = ""; $('#errorMensajeEmail').hide(); $('#errorMensajeEmail').html(''); $('#errorMensajeCamposRequeridos').hide(); var email = $('#txtEmail').val(); if(email == ""){ strMensaje = "*"; isUsuarioRequerido = false; $('#errorMensajeCamposRequeridos').html('* Datos obligatorios').show(); } else if($('#txtEmail').val().toString().indexOf('@') == -1){ strMensaje = "El Email no es valido"; isUsuarioRequerido = false; } else if(verificarAlias()){ strMensaje = "El Email ya existe"; isUsuarioRequerido = false; } // if(!isUsuarioRequerido){ $('#errorMensajeEmail').html(strMensaje); $('#errorMensajeEmail').show(); } return isUsuarioRequerido; } function verificarCuit(){ var isCuitRequerida = true; var validate = $("#txtCuit").attr("validate"); if (validate != "" && $("#txtCuit").val() == "") { $('#errorMensajeCuit').html("*"); $('#errorMensajeCuit').show(); return isCuitRequerida = false; } else if (validate != "" && $("#txtCuit").val() != "") return isCuitRequerida; var strMensaje = ""; $('#errorMensajeCuit').hide(); $('#errorMensajeCuit').html(''); $('#errorMensajeCamposRequeridos').hide(); var cuit = $('#txtCuit').val().split('-').join(''); if(cuit == ""){ strMensaje = "*"; isCuitRequerida = false; $('#errorMensajeCamposRequeridos').html('* Datos obligatorios').show(); } else if(cuit.length < 11 || cuit.length > 11){ strMensaje = "El CUIT no puede ser menor a 11 digitos"; isCuitRequerida = false; } if(isCuitRequerida){ if(isCuitValid()) { if(validateCuit()){ strMensaje = "El CUIT ya existe"; isCuitRequerida = false; } } else{ strMensaje = "El CUIT ingresado no es válido"; isCuitRequerida = false; } } if(!isCuitRequerida){ $('#errorMensajeCuit').html(strMensaje); $('#errorMensajeCuit').show(); } return isCuitRequerida; } function validateCuit(){ var isExist = false; var cuit = $('#txtCuit').val().split('-').join(''); $.ajax({ type: "POST", url: "../WizardRegisterUser/ValidateDomain", data: "{'domain' : '" + cuit + "'}", contentType: "application/json; charset=utf-8", async: false, dataType: "json", success: function (response) { isExist = response.Exist; $('#loader0').hide(); }, error: function (msg) { $('#loader0').hide(); var error = msg.responseText.split("")[1].split("")[0]; OpenModalError1(error); } }); return isExist; } function isCuitValid(){ var isCuitValid = false; var cuit = $('#txtCuit').val().split('-').join(''); $.ajax({ type: "POST", url: "../WizardRegisterUser/IsCuitValid", data: "{'cuit' : '" + cuit + "'}", contentType: "application/json; charset=utf-8", async: false, dataType: "json", success: function (response) { isCuitValid = response.IsCuitValid; $('#loader0').hide(); }, error: function (msg) { $('#loader0').hide(); var error = msg.responseText.split("")[1].split("")[0]; OpenModalError1(error); } }); return isCuitValid; } function verificarPassword(pw) { var isPwdRequerida = true; var pw = $('#txtPassword' + pw).val(); //var pw2 = $('#txtPassword2').val(); //Buscamos espacios en blanco for (var x = 0; x < pw.length; x++) { if (pw.charAt(x) == " ") { strError = "La contraseña no puede tener espacios en blancos"; isPwdRequerida = false; return isPwdRequerida; } } //No guardar contrase�as vacias if (pw.length == 0) { isPwdRequerida = false; strError = "La contraseña no puede estar vacia"; return isPwdRequerida; } // al menos un numero, una minuscula y una mayuscula // minimo 8 caracteres que sean letras, numeros y guion bajo var strCondicion = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])\w{8,}$/; isPwdRequerida = strCondicion.test(pw); if (!isPwdRequerida) { strError = "La contraseña no cumple con los requisitos.";// Debe contener al menos un numero, una minuscula, una mayuscula y minimo 6 caracteres no alfab�ticos (como!, $, #, %)"; return isPwdRequerida; } //Coinciden las contrase�as if (($('#txtPassword1').val() != $('#txtPassword2').val()) && isFirstTimePassword == false) { //La primera vez no se compara la pass con la otra isPwdRequerida = false; strError = "Las contraseñas no coinciden"; return isPwdRequerida; } else { strError = ""; $('#errorMensajePw1').html(''); $('#errorMensajePw1').hide(); $('#errorMensajePw2').html(''); $('#errorMensajePw2').hide(); } return isPwdRequerida; } //se ejecuta cuando se carga un archivo de imagenes. function archivoFoto(evt, foto) { var files = evt.target.files; // FileList object // Obtenemos la imagen del campo "file". for (var i = 0, f; f = files[i]; i++) { //Solo admitimos im�genes. if (!f.type.match('image.*')) { continue; } //ocultamos div input $('#divInputImg').hide(); $('#divViewImg').show(); var reader = new FileReader(); reader.onload = (function (theFile) { return function (e) { // Insertamos la imagen var botonBorrarFoto = 'Borrar'; document.getElementById(foto).innerHTML = ['', botonBorrarFoto].join(''); setTimeout(function () { //forzamos la posicion a vertical de la foto cuando corresponde. var isHorizontal = false; var imageElement = document.getElementById("imgNew" + foto); EXIF.getData(imageElement, function() { if(EXIF.getTag(this, "Orientation") == 6){ //horizontal isHorizontal = true; } }); var newImageData = compressImg("imgNew" + foto); document.getElementById(foto).innerHTML = ['', botonBorrarFoto].join(''); if(isHorizontal){ $("#imgNew" + foto).addClass('imgVertical'); $('#' + foto + ' > a').addClass('btnImgVertical'); } }, 500); }; })(f); reader.readAsDataURL(f); } } //Bug 4738.. Reducción de imagenes.. La imagen seleccionada en caso de ser necesario se reduce proporcionalmente a un tamaño que no supere los 1280px*960px(ancho, alto) //y la calidad se reduce en porcentaje cuando supera los 950000 bytes. //Retorna el base64 de la imagen transformada(comprimida) o no. function compressImg(imageId) { var source_img_obj = document.getElementById(imageId); var imageSplit = source_img_obj.src.split(','); var image_type = imageSplit[0].split(';')[0].split(':')[1]; var width = source_img_obj.naturalWidth; var height = source_img_obj.naturalHeight; var porcWidth = 0; var porcHeight = 0; //Se controla que el tamaño de la imagen no supere los 1280px*960px o los 960px*1280px, en caso de ser así se calcula //el porcentaje que se excede cada medida(ancho y alto). if (width > height && (width > 1280 || height > 960)) { //imagen horizontal porcWidth = 1280 / width; porcHeight = 960 / height; } else if (width <= height && (width > 960 || height > 1280)) {//imagen vertical porcWidth = 960 / width; porcHeight = 1280 / height; } //Si los porcentajes son mayores a 0, se multiplica cada medida por el menor porcentaje(es el que mas cambio) //para que ambas medidas(ancho y alto) se reduzcan proporcionalmente al mismo porcentaje. if (porcWidth > 0 && porcHeight > 0) { if (porcWidth <= porcHeight) { width = width * porcWidth; height = height * porcWidth; } else { width = width * porcHeight; height = height * porcHeight; } } else { //si los porcWidth == 0 && porcHeight == 0(el tamaño esta dentro de lo permitido) se verifica el filezise para ver sino supera los 950000 bytes. var fileSize = Math.round(source_img_obj.src.split(',')[1].length * 6 / 8); if (fileSize <= 950000) { return source_img_obj.src; } } //Se crea un objeto canvas y se va reduciendo la calidad en porcentaje(Ej: 90%, 80%, 70% etc...) hasta que el filezise del mismo no supere los 950000 bytes. for (var i = 1; i < 10; i++) { var quality = 100 - (i * 10); var cvs = document.createElement('canvas'); cvs.width = width; cvs.height = height; cvs.getContext("2d").drawImage(source_img_obj, 0, 0, cvs.width, cvs.height); var newImageData = cvs.toDataURL(image_type, quality / 100); var fileSize = Math.round(newImageData.split(',')[1].length * 6 / 8); if (fileSize <= 950000) { return newImageData; } } return newImageData; } //limpia una foto. function BorrarDatosFoto() { document.getElementById('FotoImg').innerHTML = ""; $('#file_upload').val(''); //$('#FotoImg').html(''); $('#FotoImg').show(); $('#hFotoName').val(''); $('#hFotoType').val(''); $('#hFoto').val(''); $('#divInputImg').show(); $('#divViewImg').hide(); } function verificarCamposRequeridos() { //strError = ""; //$('#errorMensaje').hide(); var isCampoRequerido = true; //password isCampoRequerido = verificarPassword(1); if (!isCampoRequerido) isCampoRequerido = verificarPassword(2); //Submit if (isCampoRequerido) { ViewToServer(); } else { //error window.openModal({ title: 'Aviso', content: strError, acceptText: 'Aceptar', context: document.querySelector('.main-container'), }); } } function ViewToServer() { $('#loader0').show(); var userEdit = {}; userEdit.ID = ""; userEdit.Email = $('#txtEmail').val(); userEdit.Apellido = $('#txtNombreApellido').val(); userEdit.Nombre = $('#txtNombreApellido').val(); userEdit.Telefono = $('#txtTelefono').val(); userEdit.Domicilio = $('#hDomicilio').val(); userEdit.Provincia = $('#hProvincia').val(); userEdit.Localidad = $('#hLocalidad').val(); userEdit.Password = $('#txtPassword1').val(); //setea en el model, la foto cargada var archivo = $("#file_upload").val(); if (archivo.length > 1) { var imageName = $("#file_upload").val().split('\\')[2]; // obtiene nombre imagen var imgExtension = $("#file_upload").val().split('\\')[2].split('.')[1]; var imgBase64 = $("#FotoImg > img")[0].src.split(',')[1]; // obtiene base64 de la imagen userEdit.Foto = imgBase64; userEdit.FotoName = imageName; userEdit.FotoType = imgExtension; } //Coop userEdit.Coop = selCoop; //$('#selectCooperativa').val(); //seteado en el evento del marker userEdit.CoopTitulo = selCoopTitulo; //$("#selectCooperativa option:selected").text(); //seteado en el evento del marker userEdit.Cuit = $('#txtCuit').val().split('-').join(''); //userEdit.RazonSocial = ""; userEdit.Estado = 0; var userJson = JSON.stringify(userEdit); var escapedUserJson = JSON.stringify(userJson); $.ajax({ type: "POST", url: "../WizardRegisterUser/SaveUsuarioJSON", //data: "{'userJson' : '" + userJson + "', 'externalUser' : '" + externalUser + "', 'data' : '" + saveUser + "' }", data: "{\"userJson\" : " + escapedUserJson + ", \"externalUser\" : \"" + externalUser + "\", \"data\" : \"" + saveUser + "\" }", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { if (response.Status == "OK") { OpenModal(msjRegistracion); } else { OpenModalError1(response.Error); } $('#loader0').hide(); }, error: function (msg) { $('#loader0').hide(); OpenModalError1(msg.responseText.split("")[1].split("")[0]); } }); } /*** MAPA ***/ function showMap() { mbUrl = 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw'; //var satellite = L.tileLayer(mbUrl, { id: 'mapbox.satellite', attribution: mbUrl }), // streets = L.tileLayer(mbUrl, { id: 'mapbox.streets', attribution: mbUrl }); var startPoint = [-32.340484, -64.233454]; map = L.map('map_canvas', { editable: true, zoomControl:true, minZoom: 2 }, { center: [-32.340484, -64.233454], zoom: 3, }).setView(startPoint, 5); mapBuscador = L.map('map_canvas_buscador', { editable: true, zoomControl:false, minZoom: 2 }, { center: [-32.340484, -64.233454], zoom: 3 }).setView(startPoint, 5); var satellite = L.tileLayer(mbUrl, { id: 'mapbox.satellite', attribution: mbUrl }).addTo(map); streets = L.tileLayer(mbUrl, { id: 'mapbox.streets', attribution: mbUrl }); var baseLayers = { "Satelite": satellite, "Streets": streets }; L.control.layers(baseLayers).addTo(map); var cartodbAttr = '© OpenStreetMap © CartoDB' var cartodbUrl = 'https://{s}.basemaps.cartocdn.com/dark_only_labels/{z}/{x}/{y}.png' var labels_layer = L.tileLayer(cartodbUrl, { id: 'cartodb_labels', attribution: cartodbAttr }).addTo(map); //Proveedor de busqueda de localides- var arcgisOnline; var domain = listHttpSessionTempData["domainRegistro"] == null ? "" : listHttpSessionTempData["domainRegistro"].toLowerCase(); if (domain == "banrural") arcgisOnline = L.esri.Geocoding.arcgisOnlineProvider({ countries: ["GTM"], categories: ["CITY", "REGION"] }); else arcgisOnline = L.esri.Geocoding.arcgisOnlineProvider({ countries: ["ARG"], categories: ["CITY", "REGION"] }); var gisDay = L.esri.Geocoding.featureLayerProvider({ url: 'https://services.arcgis.com/uCXeTVveQzP4IIcx/arcgis/rest/services/GIS_Day_Final/FeatureServer/0', searchFields: ['STATE_NAME'], // Search these fields for text matches //label: 'GIS Day Events', // Group suggestions under this header formatSuggestion: function (feature) { return feature.properties.Name; // + ' - ' + feature.properties.Organization; // format suggestions like this. } }); var search = BootstrapGeocoder.search({ inputTag: 'txtAddress', placeholder: 'Localidad', providers: [arcgisOnline, gisDay], }).addTo(mapBuscador); search.on('results', function(e){ $("#txtAddress").val(e.text); localidad = e.text; var obj = e.results[0].properties; $('#hDomicilio').val(obj.StAddr); $('#hLocalidad').val(obj.ShortLabel); $('#hProvincia').val(obj.Region); $('#hLatitude').val(obj.DisplayY); $('#hLongitude').val(obj.DisplayX); map.setView([obj.DisplayY, obj.DisplayX], 14); }); $(".input-group").attr("style", "width:100%"); //fin search $('.leaflet-control-zoom').css('top','1.2em');// control de zoom $('.leaflet-control-layers-toggle').remove(); //remove bottom layers $(".leaflet-bottom").remove(); //remove firma $("#map_canvas").height($(window).height() + 'px'); } function fillMap(listCoop){ //Limpiamos marcadores for (var x = 0; x < markerGroup.length; x++) { map.removeLayer(markerGroup[x]); } markerGroup = []; pointList = []; if (markerClusterGroup != null) map.removeLayer(markerClusterGroup); markerClusterGroup = null; if (listCoop.length > 0) { for (var i = 0; i < listCoop.length; i++) { if (listCoop[i].LATITUD == "" && listCoop[i].LONGITUD == "") continue; var point = [listCoop[i].LATITUD, listCoop[i].LONGITUD]; var title = listCoop[i].TITULO; var mIcon = '../Content/themes/micampo/images/marker_mapa.svg'; var jsonIcon = L.icon({ iconUrl: mIcon, //shadowUrl: 'leaf-shadow.png', iconSize: [41, 49], // size of the icon //shadowSize: [41, 49], // size of the shadow iconAnchor: [41, 49], // point of the icon which will correspond to marker's location //shadowAnchor: [41, 49], // the same for the shadow popupAnchor: [-18, -40] // point from which the popup should open relative to the iconAnchor }); var jsonOptions = { point: point, title: title, id: listCoop[i].ID, empresa: listCoop[i].EMPRESA, categoria: listCoop[i].CATEGORIA, htmlDescripcion: listCoop[i].DESCRIPCION, userId: listCoop[i].UserID, marker: marker }; //Agregamos marcador con evento mousedown para obtener el buttom click var marker = new L.marker(new L.LatLng(listCoop[i].LATITUD, listCoop[i].LONGITUD), { icon: jsonIcon, jsonOptions: jsonOptions }) .bindTooltip(listCoop[i].TITULO,{permanent: true, direction: 'top', className: "marker-icon-coop-register"}); marker = marker.on('mousedown ', function (e) { var options = e.target.options.jsonOptions; handleMarkerClick(options, this, e.originalEvent.which); }); markerGroup.push(marker); //array marker pointList.push(point); //array puntos } } if($("#hLatitude").val() == "" && $("#hLongitude").val() == ""){ map.fitBounds([pointList]); } FillClusterGroup(); } function FillClusterGroup(){ markerClusterGroup = L.markerClusterGroup({ spiderfyShapePositions: function (count, centerPt) { var distanceFromCenter = 35, markerDistance = 45, lineLength = markerDistance * (count - 1), lineStart = centerPt.y - lineLength / 2, res = [], i; res.length = count; for (i = count - 1; i >= 0; i--) { res[i] = new Point(centerPt.x + distanceFromCenter, lineStart + markerDistance * i); } return res; } }); for (var x = 0; x < markerGroup.length; x++) { markerClusterGroup.addLayer(markerGroup[x]); } map.addLayer(markerClusterGroup); } function handleMarkerClick(options, marker, click) { if (click == 1) { //click izquierdo $('#btnNextStepMapa').attr('disabled','disabled'); //Eliminar la palabra CDC y COOP CENTRAL /*if(options.title.indexOf('CDC') > -1){ options.title = options.title.replace('CDC ','') options.title = options.title.replace('CDC ','') } if(options.title.indexOf('COOP CENTRAL') > -1){ options.title = options.title.replace('COOP CENTRAL ',''); }*/ window.openModal({ title: '¿Confirmas esta Cooperativa o Centro de Desarrollo Cooperativo?', content: 'Al confirmar estarás seleccionando ' + options.title, acceptText: 'Aceptar', cancelText: 'Cancelar', context: document.querySelector('.main-container'), }).then( e => { selCoop = options.id; selCoopTitulo = options.title; nextStep(); $('#btnNextStepMapa').removeAttr('disabled'); }, e => { $('#btnNextStepMapa').removeAttr('disabled'); }); $('.aca-modal-overlay').css('z-index','9999'); $("div.button-container > button")[0].id="btnAceptarMapa"; $("div.button-container > button")[1].id="btnCancelarMapa"; } else if (click == 3) {//click derecho // } } /*** FIN MAPA ***/ function soloNumeros(e) { var key = window.Event ? e.which : e.keyCode return ((key >= 48 && key <= 57) || (key == 8)) } function OpenModal(msj) { var msjError = ""; var msjTitle = ""; if (msj != "") msjTitle = msj; else { msjError = "Te enviamos un correo electrónico para verificar tu dirección de correo. Por favor, accedé al link de confirmación en ese correo. Tené en cuenta que puede haber llegado a No deseados. Gracias!"; msjTitle = "Felicitaciones! Completaste tu registro en " + (externalUser == true ? "ACA Market." : "ACA Mi Campo."); } window.openModal({ title: msjTitle, content: msjError, cancelWithOverlay: false, showBtnAccept: false, context: document.querySelector('.main-container'), }) .then(e => { //return; if( (externalUser == true) && (backurl != "" || backurl != null) ){ window.location.href = backurl; } else{ window.location.href = "../MiCampo/Login"; } }); } function OpenModalError1(msjError){ window.openModal({ title: 'Aviso', content: msjError, acceptText: 'Aceptar', context: document.querySelector('.main-container'), }); } function getHttpSessionTempData() { $.ajax({ type: "POST", url: "../WizardRegisterUser/GetHttpSessionTempData", contentType: "application/json; charset=utf-8", async: false, dataType: "json", success: function (response) { listHttpSessionTempData = JSON.parse(response.List); }, error: function (msg) { var error = msg.responseText.split("")[1].split("")[0]; OpenModalError1(error); } }); }; //obtiene las keys de configuración del web.config function getConfigurationSettings(keyNotifi) { $.ajax({ type: "POST", url: "../WizardRegisterUser/GetConfigurationSettings", data: "{ 'KeyConfigurationName': '" + keyNotifi + "' }", contentType: "application/json; charset=utf-8", async: false, dataType: "json", success: function (response) { if (response.Status == "OK") { listHttpSessionTempData = JSON.parse(response.List); } else { OpenModalError1(response.Error); } }, error: function (msg) { var error = msg.responseText.split("")[1].split("")[0]; OpenModalError1(error); } }); }; function closeSession() { var url = "../Session/LogoffJSON"; $.getJSON(url, function (result) { console.log("result.Login: " + result.Login); }) .fail(function (jqxhr, textStatus, error) { console.log(textStatus); }); } function verificarAlias() { if(email == "") return; $('#loader0').show(); var isExist = false; var email = $('#txtEmail').val(); $.ajax({ type: "POST", url: "../WizardRegisterUser/ValidateAliasDestinatary", data: "{'alias' : '" + email + "'}", contentType: "application/json; charset=utf-8", async: false, dataType: "json", success: function (response) { isExist = response.Exist; $('#loader0').hide(); }, error: function (msg) { $('#loader0').hide(); var error = msg.responseText.split("")[1].split("")[0]; OpenModalError1(error); } }); return isExist; }; //string.Format (c#) en Javascript String.prototype.format = function() { a = this; for (k in arguments) { a = a.replace("{" + k + "}", arguments[k]) } return a };