var INPUTCOLOR = ""; //colore del bordo dell'input di default var INPUTERROR = "1px solid #FF9900"; var GIORNI = Array("lun","mar","mer","gio","ven","sab","dom"); var timeOutId; //Timeout di alertWin var URLSITO = 'https://igelsielatalpa.it/'; var SCMD = 'login-signin'; var LOGGEDIN = false; var LASTLOGIN = 15; /* ALERT ********************************/ function alertSwal(ty,ti,mex,fn){ //type = warning, error, success, info, question if(fn==undefined) fn=function(){}; swal({ title: ti, text: mex, type: ty, timer: 60000}, function(confirm){ setTimeout(fn,200); }); }; function confirmSwal(mex,fn,fn2){ swal({ title: "Attenzione", text: mex, type: 'warning', showCancelButton: true, confirmButtonText: 'Ok', cancelButtonText: 'Annulla' }, function(confirm){ if(confirm){ setTimeout(fn,200); }else{ setTimeout(fn2,200); } }); } function viewLoader(mex){ var ldr = document.getElementById('nonsolospinner'); var ldrdiv = document.getElementById('nonsolospinnerdiv'); var ldrtxt = document.getElementById('nonsolospinnertesto'); ldrtxt.innerHTML = mex; ldr.style.display = "block"; ldrdiv.style.display = "block"; } function hideLoader(cont,dbg){ if(dbg){ if(typeof(cont)!='string') cont = JSON.stringify(cont); var ldr = document.getElementById('nonsolospinner'); ldr.firstChild.innerHTML = cont; }else{ var ldr = document.getElementById('nonsolospinner'); var ldrdiv = document.getElementById('nonsolospinnerdiv'); ldr.style.display = "none"; ldrdiv.style.display = "none"; ldr.firstChild.innerHTML = ''; } } function notificaTopRight(tot,img,nome,qta){ var tmpl = '
'+ '
TOTALE: € '+tot+'
'+ '
'+ '
'+ '' + '
'+ '
'+ nome+'
'+qta+ '
'+ '
'+ '
'; $.notify({ message: tmpl, },{ z_index: 1051, delay: 4000, animate: { enter: 'animated fadeInDown', exit: 'animated fadeOutUp' } }); } /* DEBUG ********************************/ function ja(o){ alert(JSON.stringify(o)); console.log(JSON.stringify(o)); } function sja(o){ var str = ''; for(var i in o){ if(str!='') str +=','; str += i +":" + typeof o[i]; } alert(str); } /* FORM ********************************/ function normalizeCampo(obj){ obj.style.borderBottom = INPUTCOLOR; } function ctrlKey(e,o){ if(e.keyCode==13) document.getElementById(o).click(); } function toUri(obj){ var strUri=''; if(obj.name!="" && obj.name!=undefined){ switch(obj.type){ case 'checkbox': case 'radio': if((obj.type === 'radio' || obj.type === 'checkbox') && obj.checked) { var val=(obj.value!=='')? obj.value : '1'; strUri += '&'+obj.name+'='+encodeURIComponent(val); }else{ strUri += '&'+obj.name+'='; } break; default: strUri += '&'+obj.name+'='+encodeURIComponent(obj.value); break; } } return strUri; } function buildUri(obj){ var strUri =''; for(var n=0; n0) fields['dataId'] = []; for(var n=0; n stringify of objects //mode=mix => key= stringify for array and key=value for the rest //mode=php => key[]=val1&...key[]=valn for array and key=value for the rest if(mode==undefined) mode = 'php'; var strUri = ''; var objUri = {}; var mixUri = ''; for(var i in this.nodes){ var v = this.getValue(i); objUri[i.replace('[]','')]=v; if(v.constructor === Array){ v.forEach(function(e){ strUri += '&'+i+'='+encodeURIComponent(e); }); mixUri += '&'+encodeURIComponent(i.replace('[]',''))+'='+encodeURIComponent(JSON.stringify(v)); }else{ strUri += '&'+encodeURIComponent(i)+'='+encodeURIComponent(v); mixUri += '&'+encodeURIComponent(i)+'='+encodeURIComponent(v); } } switch(mode){ case 'json': return JSON.stringify(objUri); break; case 'mix': return mixUri; break; case 'php': return strUri; break; } } return form; } /* validazione campi */ function indirizzoEmailValido(indirizzo) { if (window.RegExp) { var nonvalido = "(@.*@)|(\\.\\.)|(@\\.)|(\\.@)|(^\\.)"; var valido = "^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$"; var regnv = new RegExp(nonvalido); var regv = new RegExp(valido); if (!regnv.test(indirizzo) && regv.test(indirizzo)) return true; return false; }else { if(indirizzo.indexOf("@") >= 0) return true; return false; } } function controlForm(frm,nome,fld1,fld2,tipo){ if(tipo==undefined) tipo = ''; switch(tipo){ case "":// controlla se il campo e vuoto false (quindi ="" o =0...tanti zeri) if(frm.getValue(fld1) == false){ alertSwal('warning',nome, 'Campo mancante',frm.focus.bind(frm,fld1)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; } return true; break; case "_":// controlla se il campo = vuoto con "" if(frm.getValue(fld1) == ""){ alertSwal('warning',nome, 'Campo mancante',frm.focus.bind(frm,fld1)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; } return true; break; case "@": // controlla la validita del campo mail if(!indirizzoEmailValido(frm.getValue(fld1))){ alertSwal('warning',nome, 'Formato non valido',frm.focus.bind(frm,fld1)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; } return true; break; case "hS":// controlla se il campo autoSuggest = vuoto if(frm.getValue(fld2) == ""){ if(frm.getValue(fld1) == false){ alertSwal('warning',nome, 'Campo mancante',frm.focus.bind(frm,fld1)); }else{ alertSwal('warning',nome, 'Non presente nei dati a disposizione ',frm.focus.bind(frm,fld1)); } INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; }else{ return true; } break; case "date<": if(frm.getValue(fld2) != "" && frm.getValue(fld1) != ""){ var arr1 = frm.getValue(fld1).split("-"); var arr2 = frm.getValue(fld2).split("-"); var d1 = new Date(arr1[2],arr1[1]-1,arr1[0]); var d2 = new Date(arr2[2],arr2[1]-1,arr2[0]); var r1 = d1.getTime(); var r2 = d2.getTime(); if(r1 > r2){ alertSwal('warning',nome, 'Le date sono invertite',frm.focus.bind(frm,fld1)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; } return true; }else{ return true; } break; case "ore<": if(frm.getValue(fld2)!="" && frm.getValue(fld1)!="" && frm.getValue(fld2)!="00:00" && frm.getValue(fld1)!="00:00"){ var arr1 = frm.getValue(fld1).split(":"); var arr2 = frm.getValue(fld2).split(":"); arr1[0]= parseInt(arr1[0],10); arr1[1]= parseInt(arr1[1],10); arr2[0]= parseInt(arr2[0],10); arr2[1]= parseInt(arr2[1],10); if(arr1[0] > arr2[0] || (arr1[0] == arr2[0] && arr1[1] > arr2[1])){ alertSwal('warning',nome, 'Gli orari sono invertiti',frm.focus.bind(frm,fld1)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; } return true; }else{ return true; } break; case "n": // controlla se il campo e' un numero if(isNaN(frm.getValue(fld1).replace(',','.'))){ alertSwal('warning',nome, 'Il campo deve contenere solo numeri',frm.focus.bind(frm,fld1)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; }else{ return true; } break; case "=": // confronta due campi if(frm.getValue(fld1) != frm.getValue(fld2)){ alertSwal('warning', nome, 'i campi non combaciano',frm.focus.bind(frm,fld1)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = INPUTERROR; return false; }else{ return true; } break; case "cf": // controlla codice fiscale var r = new RegExp("^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$"); if(!r.test(frm.getValue(fld1))){ alertSwal('warning',nome, 'Formato non valido',frm.focus.bind(frm,fld1)); frm.getElement(fld1).style.border = INPUTERROR; return false; }else{ return true; } break; case "pi": // controlla partita iva var r = new RegExp("^[0-9]{11}$"); if(!r.test(frm.getValue(fld1))){ alertSwal('warning',nome, 'Formato non valido',frm.focus.bind(frm,fld1)); frm.getElement(fld1).style.border = INPUTERROR; return false; }else{ return true; } break; case "cf_pi": // controlla codice fiscale or Partita iva var r1 = new RegExp("^[a-zA-Z]{6}[0-9]{2}[a-zA-Z][0-9]{2}[a-zA-Z][0-9]{3}[a-zA-Z]$"); var r2 = new RegExp("^[0-9]{11}$"); if(!r1.test(frm.getValue(fld1)) && !r2.test(frm.getValue(fld1))){ alertSwal('warning',nome, 'Formato non valido',frm.focus.bind(frm,fld1)); frm.getElement(fld1).style.border = INPUTERROR; return false; }else{ return true; } break; case "sdi": // controlla codice sdi var r = new RegExp("^[a-zA-Z0-9]{7}$"); if(!r.test(frm.getValue(fld1))){ alertSwal('warning',nome, 'Formato non valido',frm.focus.bind(frm,fld1)); frm.getElement(fld1).style.border = INPUTERROR; return false; }else{ return true; } break; case "c<": // controlla se il campo e' piu' corto di un tot if(frm.getValue(fld1).length < fld2){ alertSwal('warning',nome, "lunghezza minima " +fld2+ " caratteri",frm.focus.bind(frm,fld1)); frm.getElement(fld1).style.border = INPUTERROR; return false; }else{ return true; } break; // TODO case "h": // controlla se il campo hidden = vuoto if(document.getElementById(id2).value == false){ alertWinScroll(id, 400, ""+nome+": missin field"); document.getElementById(id).focus(); document.getElementById(id).style.border = "1px solid #FF9900"; return false; }else{ return true; } break; case "c": // controlla se il campo e' piu' lungo di un tot if(document.getElementById(id).value.length > id2){ var c = "chars"; if(id2==1) c = "char"; alertWinScroll(id, 400, ""+nome+": field must be at least "+id2+" "+c); document.getElementById(id).focus(); document.getElementById(id).style.border = "1px solid #FF9900"; return false; }else{ return true; } break; case "n=": // controlla se il campo e' lungo n if(document.getElementById(id).value.length != id2){ var c = "chars"; if(id2==1) c = "char"; alertWinScroll(id, 400, ""+nome+": field must be " +id2+ " "+c); document.getElementById(id).focus(); document.getElementById(id).style.border = "1px solid #FF0000"; return false; }else{ return true; } break; case "v<": // controlla se il valore del campo e' < di tot if(parseInt(document.getElementById(id).value)>id2){ alertWin(nome+": value of the field must be lower than "+id2); document.getElementById(id).focus(); document.getElementById(id).style.border = "1px solid #FF0000"; return false; }else{ return true; } case "v>": // controlla se il valore del campo e' > di tot if(parseInt(document.getElementById(id).value)=": // controlla se il valore del campo e' >= di tot if(parseInt(document.getElementById(id).value)= del I if(convDate(document.getElementById(id).value)>convDate(document.getElementById(id2).value)){ alertWin(nome+": field value must be greater or equal to the previous"); document.getElementById(id2).focus(); document.getElementById(id2).style.border = "1px solid #FF0000"; return false; }else{ return true; } break; case "doc": // controllo se il file = un doc obj = document.getElementById(id); var extensions = new Array(); extensions[1] = "doc"; extensions[0] = "docx"; extensions[2] = "pdf"; extensions[3] = "rtf"; /*extensions[4] = "bmp";*/ var image_file = obj.value; var image_length = image_file.length; var pos = image_file.lastIndexOf('.') + 1; var ext = image_file.substring(pos, image_length); var final_ext = ext.toLowerCase(); for (i = 0; i < extensions.length; i++){ if(extensions[i] == final_ext){ return true; } } alertWinScroll(id, 400, ""+nome+": invalid format"); document.getElementById(id).focus(); document.getElementById(id).style.border = "1px solid #FF9900"; return false; break; case "img": // controllo se il file = una img obj = document.getElementById(id); var extensions = new Array(); extensions[1] = "jpg"; extensions[0] = "jpeg"; extensions[2] = "gif"; extensions[3] = "png"; /*extensions[4] = "bmp";*/ var image_file = obj.value; var image_length = image_file.length; var pos = image_file.lastIndexOf('.') + 1; var ext = image_file.substring(pos, image_length); var final_ext = ext.toLowerCase(); for (i = 0; i < extensions.length; i++){ if(extensions[i] == final_ext){ return true; } } alertWin("Seleziona un'immagine con una delle seguenti estensioni:\n\n gif, jpeg, jpg"); return false; break; default: alertWin("tipo non riconosciuto"); return false; } } // ********************* Modale ****************** // Eventi nella pagina function addEvent(obj, evType, fn){ if(obj.addEventListener){ obj.addEventListener(evType, fn, true); return true; } else if (obj.attachEvent){ var r = obj.attachEvent("on"+evType, fn); return r; } else { return false; } } function once(e,fn) { target = (e.currentTarget) ? e.currentTarget : e.srcElement; if(target.removeEventListener){ target.removeEventListener(e.type, fn); }else{ target.detachEvent('on'+e.type, fn); } target['on'+e.type]=null;//inline event var args = Array.prototype.slice.call(arguments); var dump = args.shift(); dump = args.shift(); fn.apply(this, args); try { var new_e = new e.constructor(e.type, e); target.dispatchEvent(new_e); }catch(err) {} } function isMobile() { try{ document.createEvent("TouchEvent"); return true; } catch(e){ return false; } } /* Matematica ********************************/ /*** Returns a random integer between min (inclusive) and max (inclusive)*/ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } function genPass(n){ // Generazione password casuale if(n<4) return ""; var lets = "abcdefghiljkmnopqrstuvwxyz"; var nums = "0123456789"; var spes = "!$%&()=?*[]<>"; var elaborazione = ''; var nLet = n-4; var nNum = 2; var nLetM = 1; var nSpe = 1; for (var contatore=0; contatore').val(z).html(z)); if(ex==z) obj[0].lastChild.selected = true; } } function daysInMonth(month, year) { return new Date(year, month, 0).getDate(); } function getAge(dob){ var year = Number(dob.substr(0, 4)); var month = Number(dob.substr(5, 2)) - 1; var day = Number(dob.substr(8, 2)); var today = new Date(); var age = today.getFullYear() - year; if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) { age--; } return age; } function convDate(data){ dummy2 = data.split("-").reverse().join("-"); return dummy2; } function toJSDate (dateTime) { var dateTime = dateTime.split(" "); var date = dateTime[0].split("-"); var time = dateTime[1].split(":"); date[1] = date[1]==0?11:--date[1]; return new Date(date[0], date[1], date[2], time[0], time[1], time[2], 0); } function dataPicker(id,open,current){ if(open==undefined) open=0;// istanzia ed apri il picker if(current==undefined) current=true;//On show, use the current date/time var obj; if(typeof id == 'string'){ obj = $('#'+id); }else{ obj = $(id); }; obj.datetimepicker({ locale:'it', format: 'DD-MM-YYYY', icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-chevron-up", down: "fa fa-chevron-down", previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-screenshot', clear: 'fa fa-trash', close: 'fa fa-remove', inline: true }, useCurrent:current //debug:true }).on('dp.change', function (ev) { $(obj[0]).trigger( "change" ); //obj.trigger( "change" ); }); if(open){ obj[0].onfocus=function(){}; obj.blur(); obj.focus(); }; } function timePicker(id,open,current){ if(open==undefined) open=0; if(current==undefined) current=true; var obj; if(typeof id == 'string'){ obj = $('#'+id); }else{ obj = $(id); }; obj.datetimepicker({ locale:'it', format: 'H:mm', // use this format if you want the 24hours timepicker //format: 'h:mm A', //use this format if you want the 12hours timpiecker with AM/PM toggle icons: { time: "fa fa-clock-o", date: "fa fa-calendar", up: "fa fa-chevron-up", down: "fa fa-chevron-down", previous: 'fa fa-chevron-left', next: 'fa fa-chevron-right', today: 'fa fa-screenshot', clear: 'fa fa-trash', close: 'fa fa-remove', inline: true }, useCurrent:current //On show, use the current date/time //debug:true }).on('dp.change', function (ev) { $(obj[0]).trigger( "change" ); }); if(open){ // istanzia ed apri il picker obj[0].onfocus=function(){}; obj.blur(); obj.focus(); }; } function isNumeric(val) { return val !== "NaN" && (+val)+'' === val + '' } //****************************************** //********** GOOGLE MAP ********** //****************************************** var map; var cellX = 0; var cellY = 0; var marker = null; function initMap(x,y) { cellX = document.getElementById(x); cellY = document.getElementById(y); var zoom = 14; if(cellX.value == "" || cellX.value == "0") cellX.value = "37.5319673"; if(cellY.value == "" || cellY.value == "0") { cellY.value = "14.0360382"; zoom=7; }; var latLng = new google.maps.LatLng(Number(cellX.value),Number(cellY.value)); var iconColor = new google.maps.MarkerImage("http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png"); var geocoder = new google.maps.Geocoder(); var infowindow = new google.maps.InfoWindow({content: ""}); var myOptions = { zoom: zoom, center: latLng, mapTypeControl: true, mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU }, zoomControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"), myOptions); var marker = new google.maps.Marker({ position: latLng, title: 'Sposta', map: map, icon: iconColor, draggable: true }); function updateMarkerPosition(latLng) { cellX.value = String(Math.round(latLng.lat() * 1000000) / 1000000); cellY.value = String(Math.round(latLng.lng() * 1000000) / 1000000); } // Update current position info. updateMarkerPosition(latLng); google.maps.event.addListener(marker, 'dragend', function() { updateMarkerPosition(marker.getPosition()); }); google.maps.event.addListener(marker, 'drag', function() { updateMarkerPosition(marker.getPosition()); }); var googleSeachControlDiv = document.createElement('DIV'); var googleSeachControl = new GoogleSeachControl(googleSeachControlDiv, map); googleSeachControlDiv.index = 1; map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(googleSeachControlDiv); function GoogleSeachControl(controlDiv, map) { controlDiv.style.margin = '5px'; var controlUI = document.createElement('DIV'); controlUI.style.backgroundColor = 'white'; controlUI.style.cursor = 'pointer'; controlUI.style.textAlign = 'center'; controlUI.title = "Cerca"; controlDiv.appendChild(controlUI); var controltxtbox = document.createElement('input'); controltxtbox.setAttribute("id", "txt_googleseach"); controltxtbox.setAttribute("type", "text"); controltxtbox.setAttribute("value", ""); controlUI.appendChild(controltxtbox); var controlbtn = document.createElement('input'); controlbtn.setAttribute("id", "btn_googleseach"); controlbtn.setAttribute("type", "button"); controlbtn.setAttribute("value", "Cerca"); controlUI.appendChild(controlbtn); controltxtbox.onkeyup = function(){ctrlKey(event,'btn_googleseach');}; google.maps.event.addDomListener(controlbtn, 'click', function() { GoogleSeachAddress(); }); } function GoogleSeachAddress() { var address = document.getElementById("txt_googleseach").value; if (geocoder) { geocoder.geocode({ 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); newLatLng = new google.maps.LatLng(results[0].geometry.location.lat(),results[0].geometry.location.lng()); marker.setPosition(newLatLng); cellY.value = String(Math.round(results[0].geometry.location.lng() * 1000000) / 1000000); cellX.value = String(Math.round(results[0].geometry.location.lat() * 1000000) / 1000000); infowindow.setContent("
lat " + results[0].geometry.location.lat() + "
lng " + results[0].geometry.location.lng() + "
hai cercato:" + address + "
"); infowindow.open(map, marker); /*google.maps.event.addListener(marker, 'click', function() { infowindow.open(map, marker); });*/ } else { alert("Indirizzo non trovato, risposta del geocoder: " + status); } }); } } } //****************************************** //********** FINE GOOGLE MAP ********** //****************************************** /******************FILES******************/ function engageSingleFoto(id,tbl,btn){ $("#"+btn+id).uploadFile({ url:"https://igelsielatalpa.it/addFoto", fileName:"myfile", multiple:false, dragDrop:false, showFileCounter:false, //maxFileCount:1, //sequential:true, //sequentialCount:2, acceptFiles:"image/*", maxFileSize: 268435456, sizeErrorStr: "troppo grande. Max: ", abortStr:"interrompi", cancelStr:"annulla", doneStr:"fatto", multiDragErrorStr: "Drag & Drop multiplo di file non autorizzato.", extErrorStr:"estenzione non autorizzata.", uploadErrorStr:"Upload non autorizzato.", maxFileCountErrorStr:"non autorizzato. Numero massimo di files: ", uploadStr:"Carica...", deletelStr: "Elimina", formData: {"id": id,"tbl":tbl}, showPreview:true, statusBarWidth:'auto', previewWidth: "auto", //previewHeight: "335px", onLoad:function(obj){ $.post('https://igelsielatalpa.it/loadFoto',"id="+id+"&tbl="+tbl,function(){},'json') .done(function(data){ for(var i=0;i 0) { item.msrc = childElements[0].getAttribute('src'); // thumbnail url if(childElements.length > 1) { item.title = childElements[1].innerHTML; // caption (contents of figure) } } var mediumSrc = el.getAttribute('data-med'); if(mediumSrc) { size = el.getAttribute('data-med-size').split('x'); // "medium-sized" image item.m = { src: mediumSrc, w: parseInt(size[0], 10), h: parseInt(size[1], 10) }; }*/ // original image item.o = { src: item.src, w: item.w, h: item.h }; items.push(item); } return items; }; // find nearest parent element var closest = function closest(el, fn) { return el && ( fn(el) ? el : closest(el.parentNode, fn) ); }; var onThumbnailsClick = function(e) { e = e || window.event; e.preventDefault ? e.preventDefault() : e.returnValue = false; var eTarget = e.target || e.srcElement; var clickedListItem = closest(eTarget, function(el) { return el.tagName === 'A'; }); if(!clickedListItem) { return; } var clickedGallery = clickedListItem.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;//clickedListItem.parentNode; var childNodes = clickedGallery.querySelectorAll("[data-item='picture']");//clickedListItem.parentNode.childNodes, var numChildNodes = childNodes.length, nodeIndex = 0, index; clickedGallery = clickedListItem.parentNode;// il template ha un html strano for (var i = 0; i < numChildNodes; i++) { if(childNodes[i].nodeType !== 1) { continue; } if(childNodes[i] === clickedListItem) { index = nodeIndex; break; } nodeIndex++; } /*NON FUNZIONA* if(clickedListItem.id!=''){ var id = '0'; var regex = new RegExp("foto\d*"); if(regex.test(clickedListItem.id)) id = clickedListItem.id.replace('foto',''); index = id; }*/ if(index >= 0) { openPhotoSwipe( index, clickedGallery ); } return false; }; var photoswipeParseHash = function() { var hash = window.location.hash.substring(1), params = {}; if(hash.length < 5) { // pid=1 return params; } var vars = hash.split('&'); for (var i = 0; i < vars.length; i++) { if(!vars[i]) { continue; } var pair = vars[i].split('='); if(pair.length < 2) { continue; } params[pair[0]] = pair[1]; } if(params.gid) { params.gid = parseInt(params.gid, 10); } return params; }; var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) { var pswpElement = document.querySelectorAll('.pswp')[0], gallery, options, items; galleryElement = galleryElement.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode; items = parseThumbnailElements(galleryElement); // define options (if needed) options = { galleryUID: galleryElement.getAttribute('data-pswp-uid'), getThumbBoundsFn: function(index) { // See Options->getThumbBoundsFn section of docs for more info var thumbnail = items[index].el.children[0], pageYScroll = window.pageYOffset || document.documentElement.scrollTop, rect = thumbnail.getBoundingClientRect(); return {x:rect.left, y:rect.top + pageYScroll, w:rect.width}; }, addCaptionHTMLFn: function(item, captionEl, isFake) { if(!item.title) { captionEl.children[0].innerText = ''; return false; } captionEl.children[0].innerHTML = item.title + '
Photo: ' + item.author + ''; return true; }, }; if(fromURL) { if(options.galleryPIDs) { // parse real index when custom PIDs are used // https://photoswipe.com/documentation/faq.html#custom-pid-in-url for(var j = 0; j < items.length; j++) { if(items[j].pid == index) { options.index = j; break; } } } else { options.index = parseInt(index, 10) - 1; } } else { options.index = parseInt(index, 10); } // exit if index not found if( isNaN(options.index) ) { return; } options.mainClass = 'pswp--minimal--dark'; options.barsSize = {top:0,bottom:0}; options.captionEl = true; options.fullscreenEl = true; options.shareEl = false; options.bgOpacity = 0.85; options.tapToClose = true; options.tapToToggleControls = false; if(disableAnimation) { options.showAnimationDuration = 0; } // Pass data to PhotoSwipe and initialize it gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options); // see: http://photoswipe.com/documentation/responsive-images.html var realViewportWidth, useLargeImages = false, firstResize = true, imageSrcWillChange; gallery.listen('beforeResize', function() { var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : 1; dpiRatio = Math.min(dpiRatio, 2.5); realViewportWidth = gallery.viewportSize.x * dpiRatio; if(realViewportWidth >= 1200 || (!gallery.likelyTouchDevice && realViewportWidth > 800) || screen.width > 1200 ) { if(!useLargeImages) { useLargeImages = true; imageSrcWillChange = true; } } else { if(useLargeImages) { useLargeImages = false; imageSrcWillChange = true; } } if(imageSrcWillChange && !firstResize) { gallery.invalidateCurrItems(); } if(firstResize) { firstResize = false; } imageSrcWillChange = false; }); gallery.listen('gettingData', function(index, item) { if( useLargeImages ) { item.src = item.o.src; item.w = item.o.w; item.h = item.o.h; } else { item.src = item.m.src; item.w = item.m.w; item.h = item.m.h; } }); gallery.init(); /* fullscreen mode on photo click, don't close gallery on esc */ //gallery.ui.getFullscreenAPI().enter(); /* or fullscreen and close the gallery on esc let psAPI = gallery.ui.getFullscreenAPI(); psAPI.enter(); gallery.listen('close', function (name) { psAPI.exit(); });*/ }; // select all gallery elements var galleryElements = document.querySelectorAll( gallerySelector ); for(var i = 0, l = galleryElements.length; i < l; i++) { galleryElements[i].setAttribute('data-pswp-uid', i+1); galleryElements[i].onclick = onThumbnailsClick; } // Parse URL and open gallery if it contains #&pid=3&gid=1 var hashData = photoswipeParseHash(); if(hashData.pid && hashData.gid) { openPhotoSwipe( hashData.pid, galleryElements[ hashData.gid - 1 ], true, true ); } }; // ********************* Admin ****************** function newPass(obj,num){ document.getElementById(obj).value = genPass(num); } //********************Contattaci****************** function contatta(obj){ var frm = formica(obj); flag = true; flag = flag && controlForm(frm, "Nome",'nome'); flag = flag && controlForm(frm, "E-mail",'blabla','','@'); var strUri = frm.buildUri('php'); if(flag){ viewLoader('Invio in corso...'); $.post('https://igelsielatalpa.it/inviaContatti',strUri,function(){},'json') .done(function(resp){ var fn = function (){ frm.getElement('nome').value = ""; if(frm.nodes['tel']) frm.getElement('tel').value = ""; frm.getElement('blabla').value = ""; if(frm.nodes['oggetto']) frm.getElement('oggetto').value = ""; frm.getElement('messaggio').value = ""; } if(resp.s=="ok"){ alertSwal('success',"Messaggio inviato", "Grazie, verrai ricontattato al piu presto.", fn); }else{ alertSwal('error','',"Errore di invio"); } }) .fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } // ********************* Login ****************** function ctrlLogin(obj){ var frm = formica(obj); flag = true; flag = flag && controlForm(frm, 'E-mail','email',''); if(frm.getValue('email')!=''){ flag = flag && controlForm(frm, 'E-mail','email','','@'); } flag = flag && controlForm(frm, 'Password','pass',''); if(flag){ viewLoader('Loading...'); $.post('https://igelsielatalpa.it/validate',frm.buildUri('php'),function(){},'json') .done(function(resp){ if(resp.s=="ko"){ alertSwal('error','Accesso negato', 'E-mail o password errate'); }else if(resp.s=="ok"){ window.location.href=URLSITO+"catalogoProdotti"; }else if(resp.s=="eml"){ alertSwal('warning','Utente non verificato', 'Il tuo profilo deve essere attivato dal nostro staff, ti informeremo per e-mail.'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } // ********************* Signin ****************** function ctrlSignin(obj){ var frm = formica(obj); flag = true; flag = flag && controlForm(frm, 'Nome','nome',''); flag = flag && controlForm(frm, 'Cognome','cognome',''); flag = flag && controlForm(frm, 'Email','email',''); if(frm.getValue('email')!=''){ flag = flag && controlForm(frm, 'Email','email','','@'); } flag = flag && controlForm(frm, 'Telefono','telefono',''); flag = flag && controlForm(frm, 'Password','pass',''); flag = flag && controlForm(frm, 'Password','pass','6','c<'); flag = flag && controlForm(frm, 'Password','pass','pass2','='); if(flag && frm.getValue("idPunto")=='0'){ flag = flag && controlForm(frm, 'Indirizzo consegna','indirizzoConsegna',''); } if(flag && frm.getValue("idPunto")=='-1'){ flag=false; var fn = function(){frm.focus("idPunto")}; alertSwal('warning',"Punto di ritiro/consegna", "scelta obbligatoria.",fn); } if(flag && frm.getValue("informativa")==false){ flag=false; alertSwal('warning',"Trattamento dei dati personali", "Accettare l'informativa.",function(){frm.focus("informativa")}); } if(flag){ viewLoader('Loading...'); $.post('https://igelsielatalpa.it/signin',frm.buildUri('php'),function(){},'json') .done(function(resp){ if(resp.result=="dup"){ alertSwal('error','Registrazione annullata', 'Email già esistente, sceglierne una differente'); }else if(resp.result=="ok"){ var fn = function(){window.location.reload(false);}; alertSwal('success','Registrazione riuscita', 'valideremo la tua registrazione ed invieremo una notifica per email.',fn); }else if(resp.result=="ko"){ alertSwal('error','Registrazione non valida', 'Campi obbligatori mancanti'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } function saveUserData(userData){ viewLoader('Loading...'); $.post('https://igelsielatalpa.it/userData', {oauth_provider:'facebook',userData: JSON.stringify(userData)}, function(){},'json') .done(function(resp){ if (resp.result=="ok") { window.location.reload(false); } else { alertSwal('warning','Richiesta Facebook', 'richiesta annullata o non autorizzata.'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function forgottenPass(obj) { var frm = formica(obj); flag = true; flag = flag && controlForm(frm, 'Email','emailF',''); flag = flag && controlForm(frm, 'Email','emailF','','@'); if (flag) { viewLoader('Loading...'); $.post('https://igelsielatalpa.it/forgottenPass', frm.buildUri('php'), function () {}, 'json').done(function (resp) { if (resp.s == "ok") { alertSwal('success','Ti è stata inviata un email', 'per reimpostare la tua password ','window.location.href=URLSITO+"login-signin"'); } else if (resp.s == 'no') { alertSwal('error','', "Email non trovata"); } else { alertSwal('error','', "Errore durante la modifica"); } }).fail(function () { alertSwal('error','', "Errore di connessione"); }).always(function (resp) {hideLoader(resp,0);}); } } function changePass(obj) { var frm = formica(obj); flag = true; flag = flag && controlForm(frm, 'Password','password',''); flag = flag && controlForm(frm, 'Password','password','6','c<'); flag = flag && controlForm(frm, 'Password e ripeti password','password','password2','='); if (flag) { viewLoader('Loading...'); $.post('https://igelsielatalpa.it/resetPass', frm.buildUri('php'), function () {}, 'json').done(function (resp) { if (resp.s == "ok") { alertSwal('success','Password cambiata', 'con successo',"location.href='https://igelsielatalpa.it/login-signin'"); } else { alertSwal('error','', "Errore durante la modifica"); } }).fail(function () { alertSwal('error','', "Errorore di connessione"); }).always(function (resp) {hideLoader(resp,0);}); } } function stopAllVideo(){ $('iframe.item').each(function(){ this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*') }); } function notificaTopRight(tot,img,nome,qta){ var tmpl = '
'+ '
TOTALE: € '+tot+'
'+ '
'+ '
'+ '' + '
'+ '
'+ nome+'
'+qta+ '
'+ '
'+ '
'; $.notify({ message: tmpl, },{ z_index: 1051, delay: 4000, animate: { enter: 'animated fadeInDown', exit: 'animated fadeOutUp' } }); } function inviaOrdine(){ confirmSwal('Confermi l\'invio dell\'ordine?',function(){ viewLoader("Invio in corso"); var note = document.getElementById('noteOrdine').value; $.post('https://igelsielatalpa.it/inviaOrdine','note='+encodeURIComponent(note),function(){},'json') .done(function(resp){ var fn = function(){window.location.href=URLSITO+'ordini'}; if(resp.s=="ok"){ alertSwal('success','Ordine inviato', '',fn); }else if(resp.s=="dup"){ alertSwal('warning',resp.t, '',fn); }else if(resp.s=="noajax"){ alertSwal('error','Permesso negato', ''); }else{ alertSwal('error','', "Errore durante la modifica"); } }) .fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }); } function getOrdine(id){ viewLoader('Caricamento in corso...'); $.post(URLSITO+'ordineGet','id='+id,function(){},'json') .done(function(resp){ var modal = document.getElementById('modals_ordine');// modale in cui scrivere var divs = getChildTag(modal,"DIV"); for(var l in divs){ switch(divs[l].className){ case "pull-left nomeProdotto": divs[l].innerHTML = 'Ordine N.'+resp.num+' del '+resp.dataI+ '    -    Articoli '+ '  '+resp.art+'    -    '+ ''+ '  Stampa    -    '+ ''+ '  Scarica'; break; } } if(resp.result='ok'){ var frm = getChildTag(modal,"FORM"); var tblOrd = '
'+ ''+ ''+ '##prodotti##
##nomecliente##  ##articoli##Totale: €##totOrdine##
ProdottoQuantitàPrezzoTotale
'; var trProdotto = '##nome##'+ '
  ##nome##
##qta##€ ##prezzoU##€ ##prezzoT##'; var tblTotale = '

Totale ordine

'+ ''+ ''+ '
Prodotti€##totProdotti##
Spedizione€##totSpedizione##
Totale€##tot##
'; var html = ''; var prod = ''; var tuttiProd = ''; var tuttiHtml = ''; for(o in resp.ordini){ html = tblOrd.replace(/##nomecliente##/g, '['+resp.ordini[o].id.replace('"','\"')+'] '+'CL'+resp.ordini[o].idC+' '+resp.ordini[o].nomC.replace('"','\"')); html = html.replace(/##articoli##/g, resp.ordini[o].art); html = html.replace(/##totOrdine##/g, resp.ordini[o].totNoSped.replace('"','\"')); tuttiProd = ''; for(p in resp.ordini[o].prod){ prod = trProdotto; if(resp.ordini[o].prod[p].img.length>0){ prod = prod.replace(/##img##/g, resp.ordini[o].prod[p].img[0].replace('"','\"')); }else{ prod = prod.replace(/##img##/g, "images/prodotti/generico.png"); } prod = prod.replace(/##nome##/g, resp.ordini[o].prod[p].n.replace('"','\"')); prod = prod.replace(/##qta##/g, resp.ordini[o].prod[p].qta.replace('"','\"')); prod = prod.replace(/##prezzoU##/g, resp.ordini[o].prod[p].p.replace('"','\"')); prod = prod.replace(/##prezzoT##/g, resp.ordini[o].prod[p].pTot.replace('"','\"')); tuttiProd += prod; } html = html.replace(/##prodotti##/g, tuttiProd); tuttiHtml += html; } tblTotale = tblTotale.replace(/##totProdotti##/g, parseFloat(resp.totNoSped).toFixed(2)); tblTotale = tblTotale.replace(/##totSpedizione##/g, parseFloat(resp.sped).toFixed(2)); tblTotale = tblTotale.replace(/##tot##/g, (parseFloat(resp.totNoSped)+parseFloat(resp.sped)).toFixed(2)); frm[0].innerHTML = tuttiHtml+tblTotale; $(modal).modal('show'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } // ************* Detrit ************* /* @version 23/02/2022 migliorata legenda * Strutture array ad albero, con indicizzazione in memoria * @example new detrit([{id:'1',name:'a'},{id:'2',name:'b'},{id:'3',name:'c'}],'id'); * * @param array array array anche di oggetti di un recordset * @param string key nome chiave primaria del recordset (univoca) * * @example if(objD==undefined) objD = new detrit([],'id'); * * @function set aggiunge un elemento al recordset * @param el elemento con dentro la chiave key * * @example objD.set({id:4,name:'d'}); * * @function get restituisce un elemento al recordset * @param key valore di key per l'elemento cercato * * @function del elimina un elemento al recordset * @param key valore di key per l'elemento cercato * @function setAttribute aggiunge un attributo al record * @param key valore di key per l'elemento cercato * @param name nome attributo * @param value valore attributo * * objD.setAttribute(1,'coord',{x:'1',y:'2'}) * @function getAttribute restituisce un attributo del record * @param key valore di key per l'elemento cercato * @param name nome attributo cercato * @function delAttribute elimina un attributo del record * @param key valore di key per l'elemento cercato * @param name nome attributo da eliminare * @example ciclare gli elementi del recordset di nome r * for(var k=r.keys.length-1;k>=0;k--){// eliminare tutti i record var pId = r.keys[k]; var p = r.get(pId); p.pObj.destroy();//distruggo un attributo di nome pObj r.del(pId);// butto elemento detrit } * * @throws No Exception * @author Pastix */ // ************* Decimal tree ************* function detrit(array,key) { this.id = key;// name of primary key this.root = {}; this.keys = new Array();// All primary key values for(k in array){ this.set(array[k]); } return this; } detrit.prototype.lastArray = function(str){// private var n = str.length-1; return([str[n],str.slice(0,n)]); }; detrit.prototype.add = function(el,name){// private var idx = this.lastArray(name); if(this.pt[idx[0]]==undefined) this.pt[idx[0]] = {value:null}; this.pt = this.pt[idx[0]]; if(idx[1]==''){ this.pt.value = el; this.keys.push(el[this.id]); return this.pt.value; }else{ this.add(el,idx[1]); } }; detrit.prototype.set = function(el){// public this.pt = this.root; if(el[this.id]==undefined) return false; return this.add(el,String(el[this.id])); }; detrit.prototype.get = function(key){// public var keys = String(key).split('').reverse().join(']['); if(keys==''){ return undefined; }else{ try{ return eval('this.root['+keys+'].value'); }catch(err) {return undefined;} } }; detrit.prototype.del = function(key){// public var keys = String(key).split('').reverse().join(']['); if(keys==''){ return undefined; }else{ try{ this.pt = eval('this.root['+keys+']'); var index = this.keys.indexOf(this.pt.value[this.id]); if (index > -1) this.keys.splice(index, 1); this.pt.value = null; }catch(err) {return undefined;} } return undefined; }; detrit.prototype.setAttribute = function(key,name,value){// public var keys = String(key).split('').reverse().join(']['); if(keys=='' || name==''){ return false; }else{ try{ this.pt = eval('this.root['+keys+']'); this.pt.value[name] = value; return this.pt.value; }catch(err) {return false;} } }; detrit.prototype.getAttribute = function(key,name){// public var keys = String(key).split('').reverse().join(']['); if(keys=='' || name==''){ return false; }else{ try{ this.pt = eval('this.root['+keys+']'); return this.pt.value[name]; }catch(err) {return undefined;} } }; detrit.prototype.delAttribute = function(key,name){// public var keys = String(key).split('').reverse().join(']['); if(keys=='' || name==''){ return false; }else{ try{ this.pt = eval('this.root['+keys+']'); delete this.pt.value[name]; return this.pt; }catch(err) {return undefined;} } }; // ************* !Detrit *************// var dispatcher = { //Instanza instance:'dispatcher', controllers:[], initialize : function(){ try{ // Nome istanza var inst = eval(this.instance+".instance"); if(this.instance!=inst){alert('Wrong instance name');return false;} }catch(err) {alert('Wrong instance name');return false;} if(typeof generico != 'undefined' && generico.instance=="generico") this.controllers.push(generico); }, switchQuantita: function(idProdotto,qta){ var oThis = this; viewLoader('Caricamento in corso...'); $.post(URLSITO+"setProdotto","idProdotto="+encodeURIComponent(idProdotto)+"&qta="+encodeURIComponent(qta),function(){},'json') .done(function(resp){ if(resp.result=="ok"){ //if(qta!=0){ for(var i in resp.prodotti){ if(resp.prodotti[i].id==idProdotto){ var iconaz = URLSITO+"images/prodotti/generico.png"; if(resp.prodotti[i].img!=""){ iconaz = URLSITO+resp.prodotti[i].img[0]; } if(resp.prodotti[i].qVar==0){ qtaz = qta+" pz"; }else{ qtaz = qta+" gr"; } } } //} notificaTopRight(resp.pzT,iconaz,resp.prodotti[i].n,qtaz); oThis.switchQuantitaDone(idProdotto,resp); }else if(resp.result=="disp"){ alertSwal('warning','', resp.t); var prod = window.generico.prodotti.get(idProdotto); prod.switchQuantita(resp.n); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }, switchQuantitaDone: function(idProdotto,resp){ for(var j in this.controllers) this.controllers[j].switchQuantita(idProdotto,resp); } }; addEvent(window, 'load', function () { dispatcher.initialize(); }); var generico = { //Instanza instance:'generico',gui:{},fascia:'', initialize : function(box,ty){ try{ // Nome istanza var inst = eval(this.instance+".instance"); if(this.instance!=inst){alert('Wrong instance name');return false;} }catch(err) {alert('Wrong instance name');return false;} // Elementi interfaccia viewLoader('Caricamento in corso'); //window.requestAnimationFrame(function(){viewLoader('Caricamento in corso...');}); this.setInterface(box); this.getGenerici(); hideLoader('',0); //window.requestAnimationFrame(function(){hideLoader('',0);}); //; }, setInterface:function(box){ //GUI this.gui.box = document.getElementById(box); this.gui.icon = document.getElementById('carrelloIco'); this.gui.categorie = document.getElementById('categorieBox'); this.gui.notifica = false; if(this.gui.icon!=null){ var spans = getChildTag(this.gui.icon,"SPAN"); for(var l in spans){ if(spans[l].className=="s_color_bg p_color") this.gui.notifica = spans[l];//### icona articoli } }else{ var tasto = document.getElementById('tastoCarrello'); tasto.style.display = 'none'; var clm = document.getElementById('colonnaSx'); clm.style.display = 'none'; } if(this.prodotti==undefined) this.prodotti = new detrit([],'id'); this.gui.box.innerHTML = ''; }, //************ ricevo i generici dal server *********** getGenerici: function(ty){ var self = this; $.post(URLSITO+'prodotti','',function(){},'json') .done(function(resp){self.updProdotti(resp);}) .fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){}); }, updProdotti: function(resp){ if(resp.result=="ok"){ this.fascia = {da:resp.o.da,da:resp.o.a}; if(resp.prodotti.length==0){ this.gui.box.innerHTML="Spiacente, nessun prodotto trovato."; }else{ var categoria=''; var nItem = 0; for(var p in resp.prodotti){ if(this.prodotti.get(resp.prodotti[p].id)){// aggiorna }else{// crea // categoria if(resp.prodotti[p].c!=categoria){ // separatori di categoria var ele = document.createElement('DIV'); ele.className = "comment-box"; ele.style.position = "relative"; ele.style.display = "inline-block"; ele.style.width = "100%"; ele.style.paddingTop='0'; ele.innerHTML = '

'+resp.prodotti[p].c+'

'; this.gui.box.appendChild(ele); // elenco delle categorie ele = document.createElement('LI'); ele.innerHTML = ''+resp.prodotti[p].c+''; this.gui.categorie.appendChild(ele); categoria = resp.prodotti[p].c; }; // prodotto var prod = new prodotto(resp.prodotti[p]); this.gui.box.appendChild(prod.dom); this.prodotti.set(prod); nItem += parseInt(resp.prodotti[p].art,10); }; } this.updNotifica(nItem); } }else{ var mex ='
'+ '
'+ '
'+ '
Siamo spiacenti ma il negozio è chiuso.'; if(resp.o.s=='ko'){ if(resp.o.prev!='') mex +='
L\'ultima data utile per effettuare l\'ordine è stata il '+resp.o.prev; } mex +='
'; if(resp.o.s=='ko' && resp.o.next!=false){ mex += '
La prossima apertura è prevista dal '+resp.o.next[0]+' al '+resp.o.next[1]+'
'; } mex += '
Per informazioni sui prodotti del negozio vi invitiamo a contattarci.
'; mex += '

Al fine di evitare che le nostre e-mail finiscano tra lo spam o la posta indesiderata,
ti consigliamo di inserire tra i tuoi contatti di posta elettronica la nostra e-mail noreply@igelsielatalpa.it
'; mex += '
'; this.gui.box.innerHTML = mex; } }, switchQuantita: function(idProdotto,resp){ //var prod = this.prodotti.get(idProdotto); // il resp contiene i dati ordine, e prodotto, passo solo il necessario //if(prod) prod.switchQuantita(resp.prodotti[0].qta); this.updNotifica(resp.art); }, updNotifica: function(nItem){ if(this.gui.notifica) this.gui.notifica.innerHTML = nItem; } }; // ************* Prodotto ************* var tmplProdotto = '
'+ '
##nome##
'+ '
'+ '

##nome##

##prezzo##
'+ '
€ ##prezzoKg## ##um##
'+ '
'+ '-1+
'+ '
'; function prodotto(p) { this.id = p.id; this.tOutId=0; var tmpl = tmplProdotto;//tmplProdotto.replace(/##id##/g, p.id); tmpl = tmpl.replace(/##nome##/g, p.n.replace('"','\"')); tmpl = tmpl.replace(/##marca##/g, p.c.replace('"','\"')); tmpl = tmpl.replace(/##prezzo##/g, '€ '+parseFloat(p.p.pz).toFixed(2)); if(p.img.length==0) p.img = Array('images/prodotti/generico.png'); tmpl = tmpl.replace(/##img##/g, URLSITO+p.img[0]); tmpl = tmpl.replace(/##prezzoKg##/g, parseFloat(p.p.kg).toFixed(2)); tmpl = tmpl.replace(/##um##/g, p.p.umk); var ele = document.createElement('DIV'); ele.className = "col-md-4 col-sm-6 col-xs-12 default-item"; ele.style.display = "inline-block"; ele.innerHTML = tmpl; var spans = getChildTag(ele,"SPAN"); for(var l in spans){ switch(spans[l].className){ case "quantita": this.qta = spans[l];//### span quantita this.qta.contentEditable = 'true'; var oThis = this; var fn = function(){ var exQTA = oThis.carrello.qta; var q = oThis.qta.innerHTML.replace(/[^\d]/gm,''); if(q=='') q='0'; oThis.qta.innerHTML = q; oThis.carrello.qta = parseInt(q,10); if(exQTA!=oThis.carrello.qta) oThis.setTimeQuantita("0"); }; this.qta.addEventListener("keypress", function(event) { if (event.key === "Enter") { oThis.qta.blur(); event.preventDefault(); } }); this.qta.onblur = fn; $(this.qta).tooltip(); break; } } var ts = p.ts.split(":").map(function(x) {return parseInt(x, 10);});// tutto int this.carrello = {qta:ts[0],qMax:ts[2],qStp:ts[3],qVar:ts[4]};//qMin e' 0 sempre var links = getChildTag(ele,"A"); for(var l in links){ switch(links[l].className){ case "piu": this.piu = links[l];//### link piu' links[l].onclick = this.setTimeQuantita.bind(this,"+"); break; case "meno": links[l].onclick = this.setTimeQuantita.bind(this,"-");//### link meno break; case "detProdotto": links[l].onclick = this.getDettaglio.bind(this);//### link modale break; } } // modale der il dettaglio this.modal = document.getElementById('modals-detProdotto'); /*"inC": "0", "qMin":1*/ this.dom = ele; this.switchQuantita(this.carrello.qta); return this; } prodotto.prototype.setTimeQuantita = function(ty){ var qta = this.carrello.qta;//INT //if(qta='') qta=0; if(this.tOutId) clearTimeout(this.tOutId); this.tOutId=0; if(ty=='+'){ qta += this.carrello.qStp; }else if(ty=='-'){ qta -= this.carrello.qStp; } if(qta<=0) qta=0; if(qta>this.carrello.qMax) qta=this.carrello.qMax; this.qta.innerHTML = qta;//+(this.carrello.qVar==1?'Gr':'') this.carrello.qta = qta; var idProdotto=this.id; var fn = function(){dispatcher.switchQuantita(idProdotto,qta);}; this.tOutId = setTimeout(fn,700);// }; prodotto.prototype.getDettaglio = function(){ var self = this; viewLoader('Caricamento in corso...'); $.post(URLSITO+'detProdotto','idProdotto='+this.id,function(){},'json') .done(function(resp){self.getDettaglioDone(resp);}) .fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }; prodotto.prototype.getDettaglioDone = function(resp){ if(resp.result == "ok"){ var pr = resp.prodotto[0]; var a,b,c,d; var divs = getChildTag(this.modal,"DIV"); for(var l in divs){ switch(divs[l].className){ case "carousel-inner": a=divs[l]; break; case "pull-left nomeProdotto": c=divs[l]; break; case "modal-footer": d=divs[l]; break; } } /*var ols = getChildTag(this.modal,"OL"); for(var l in ols){ switch(ols[l].className){ case "carousel-indicators": b=ols[l]; break; } }*/ // carosello if(pr.img.length==0){ pr.img.push("images/prodotti/generico.png"); pr.imgDs.push({tt:'',st:'',ds:''}); } var act="active",x='',y=''; for(var i in pr.img){ x += '
'; x += ''; //y += '
  • '; act=''; } a.innerHTML = x; //b.innerHTML = y; c.innerHTML = pr.nome; d.innerHTML = pr.dsc; if(!$(this.modal).hasClass('in')){$(this.modal).modal('show');} } }; prodotto.prototype.switchQuantita = function(qta){ qta = parseInt(qta,10); if(qta<=0) qta=0; if(qta>this.carrello.qMax) qta=this.carrello.qMax; this.qta.innerHTML = qta; this.carrello.qta = qta; }; // ************* !Prodotto ************* var genericoCarrello = { //Instanza instance:'genericoCarrello',gui:{},fascia:'', initialize : function(box,ty){ try{ // Nome istanza var inst = eval(this.instance+".instance"); if(this.instance!=inst){alert('Wrong instance name');return false;} }catch(err) {alert('Wrong instance name');return false;} // Elementi interfaccia this.setInterface(box); this.getGenerici(); //; }, setInterface:function(box){ //GUI this.gui.box = document.getElementById(box); this.gui.icon = document.getElementById('carrelloIco'); this.gui.tot = document.getElementById('totaleBox'); this.gui.invia = document.getElementById('inviaBtn'); this.gui.notifica = false; if(this.gui.icon!=null){ var spans = getChildTag(this.gui.icon,"SPAN"); for(var l in spans){ if(spans[l].className=="s_color_bg p_color") this.gui.notifica = spans[l];//### icona articoli } }else{ } var spans = getChildTag(this.gui.tot,"SPAN"); for(var l in spans){ switch(spans[l].className){ case "prodottiCS": this.gui.tPro = spans[l]; break; case "spedizioneCS": this.gui.tSpe = spans[l]; break; case "totaleCS": this.gui.tTot = spans[l]; break; } } if(this.ordini==undefined) this.ordini = new detrit([],'id'); }, //************ ricevo i generici dal server *********** getGenerici: function(ty){ var self = this; $.post(URLSITO+'prodottiCarrello','',function(){},'json') .done(function(resp){self.updProdotti(resp);}) .fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){}); }, updProdotti: function(resp){ if(resp.result=="ok" || resp.result=="disp"){ this.fascia = {da:resp.o.da,da:resp.o.a}; if(resp.ordini.length==0){ this.gui.box.innerHTML='
    Spiacente, nessun ordine trovato.
    '; this.gui.tot.style.display='none'; this.gui.invia.style.display='none'; }else{ if(resp.result=="disp"){ alertSwal('warning','', resp.t); if(resp.notifica){ var ordDispo = this.ordini.get(resp.notifica.idO); var prod = ordDispo.prodotti.get(resp.notifica.idP); prod.qta.innerHTML = resp.n; prod.carrello.qta = parseInt(resp.n,10); } return false; } var tot = (parseFloat(resp.totNoSped)+parseFloat(resp.sped)).toFixed(2); this.updNotifica(resp.art); this.gui.tPro.innerHTML = "€"+resp.totNoSped.toFixed(2); this.gui.tSpe.innerHTML = "€"+resp.sped.toFixed(2); this.gui.tTot.innerHTML = "€"+tot; if(tot==0) this.gui.invia.style.display='none'; for(var o in resp.ordini){ var ord = resp.ordini[o]; var OrdDTR = this.ordini.get(ord.idO); if(OrdDTR){// aggiorna if(resp.notifica && resp.notifica.idO==ord.idO){ var t = (parseFloat(ord.totNoSped)+parseFloat(ord.sped)).toFixed(2); if(OrdDTR.totBox) OrdDTR.totBox.innerHTML = 'Totale: €'+t;// prezzo ordine if(OrdDTR.totArt) OrdDTR.totArt.innerHTML = ord.art;// articoli ordine if(resp.notifica.vp==0){// notifica qtaz = resp.notifica.qta+" pz"; }else{ qtaz = resp.notifica.qta+" gr"; } notificaTopRight(t,resp.notifica.img[0],resp.notifica.n,qtaz); PrdDTR = OrdDTR.prodotti.get(resp.notifica.idP); PrdDTR.tot.innerHTML = '€ '+parseFloat(resp.notifica.pz).toFixed(2); } }else{ // Ordini var eleOrd = document.createElement('DIV'); eleOrd.className = "shop_cart_table container"; eleOrd.style.padding = "20px"; var cliente = ''; if(ord.nomC!=''){ cliente = ''+ord.nomC+''+ '  '+ord.art+'Totale: €'+parseFloat(ord.totNoSped).toFixed(2)+'';//+parseFloat(ord.sped)) } var html = '
    '+ ''+cliente+''+ '
    ProdottoQuantitàPrezzoTotale
    '; eleOrd.innerHTML = html; var curOrdine = {id:ord.idO,idC:ord.idC}; var box =''; var tbls = getChildTag(eleOrd,"TABLE"); for(var l in tbls){ switch(tbls[l].className){ case "table table-1": box = tbls[l];//### TR del prodotto break; } } var tbls = getChildTag(eleOrd,"TD"); for(var l in tbls){ switch(tbls[l].className){ case "totOrdine": curOrdine.totBox = tbls[l];//### totale Ordine break; } } var tbls = getChildTag(eleOrd,"SPAN"); for(var l in tbls){ switch(tbls[l].className){ case "totArt": curOrdine.totArt = tbls[l];//### totale Ordine break; } } curOrdine.prodotti = new detrit([],'id'); for(var p in ord.prod){// prodotto var prod = new prodottoCarrello(ord.prod[p],ord.idO); box.appendChild(prod.dom); curOrdine.prodotti.set(prod); //nItem += parseInt(resp.prodotti[p].art,10); } this.gui.box.appendChild(eleOrd); this.ordini.set(curOrdine); } } } }else{ var mex ='
    '+ '
    '+ '
    '+ '
    Siamo spiacenti ma il negozio è chiuso.'; if(resp.o.s=='ko'){ if(resp.o.prev!='') mex +='
    L\'ultima data utile per effettuare l\'ordine è stata il '+resp.o.prev; } mex +='
    '; if(resp.o.s=='ko' && resp.o.next!=false){ mex += '
    La prossima apertura è prevista dal '+resp.o.next[0]+' al '+resp.o.next[1]+'
    '; } mex += '
    Per informazioni sui prodotti del negozio vi invitiamo a contattarci.
    '; mex += '

    Al fine di evitare che le nostre e-mail finiscano tra lo spam o la posta indesiderata,
    ti consigliamo di inserire tra i tuoi contatti di posta elettronica la nostra e-mail noreply@igelsielatalpa.it
    '; mex += '
    '; this.gui.box.innerHTML = mex; this.gui.tot.style.display='none'; } }, switchQuantita: function(idProdotto,idOrdine,qta){// retrocompatibilita' //var prod = this.prodotti.get(idProdotto); // il resp contiene i dati ordine, e prodotto, passo solo il necessario //if(prod) prod.switchQuantita(resp.prodotti[0].qta); var self = this; var strUri = 'idProdotto='+idProdotto+'&idOrdine='+idOrdine+'&qta='+qta; $.post(URLSITO+'prodottiCarrello',strUri,function(){},'json') .done(function(resp){self.updProdotti(resp);}) .fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){}); }, updProdotto : function(resp,idProdotto,idOrdine){ //Totale: €'+(parseFloat(ord.totNoSped)+parseFloat(ord.sped)).toFixed(2) }, updNotifica: function(nItem){ if(this.gui.notifica) this.gui.notifica.innerHTML = nItem; } }; // ************* Prodotto ************* var tmplProdottoCarrello = '##nome##'+ '
    ##nome##
    '+ '
    '+ '-1'+ '+
    '+ '
    ##pzU####pzT##'; function prodottoCarrello(p,idO) { this.id = p.id; this.idO = idO; this.tOutId=0; var tmpl = tmplProdottoCarrello;//tmplProdotto.replace(/##id##/g, p.id); tmpl = tmpl.replace(/##nome##/g, p.n.replace('"','\"')); tmpl = tmpl.replace(/##pzU##/g, '€ '+parseFloat(p.p.pz).toFixed(2)); if(p.img.length==0) p.img = Array('images/prodotti/generico.png'); tmpl = tmpl.replace(/##img##/g, URLSITO+p.img[0]); tmpl = tmpl.replace(/##pzT##/g, '€ '+parseFloat(p.pTot).toFixed(2)); var ele = document.createElement('TR'); ele.innerHTML = tmpl; var spans = getChildTag(ele,"SPAN"); for(var l in spans){ switch(spans[l].className){ case "quantita": this.qta = spans[l];//### span quantita this.qta.contentEditable = 'true'; var oThis = this; var fn = function(){ var exQTA = oThis.carrello.qta; var q = oThis.qta.innerHTML.replace(/[^\d]/gm,''); if(q=='') q='0'; oThis.qta.innerHTML = q; oThis.carrello.qta = parseInt(q,10); if(exQTA!=oThis.carrello.qta) oThis.setTimeQuantita("0"); }; this.qta.addEventListener("keypress", function(event) { if (event.key === "Enter") { oThis.qta.blur(); event.preventDefault(); } }); this.qta.onblur = fn; $(this.qta).tooltip(); break; case "color2": this.tot = spans[l];//### span prezzo totale break; } } var ts = p.ts.split(":").map(function(x) {return parseInt(x, 10);});// tutto int this.carrello = {qta:ts[0],qMax:ts[2],qStp:ts[3],qVar:ts[4]};//qMin e' 0 sempre var links = getChildTag(ele,"A"); for(var l in links){ switch(links[l].className){ case "piu": this.piu = links[l];//### link piu' links[l].onclick = this.setTimeQuantita.bind(this,"+"); break; case "meno": links[l].onclick = this.setTimeQuantita.bind(this,"-");//### link meno break; case "detProdotto": links[l].onclick = this.getDettaglio.bind(this);//### link modale break; } } // modale der il dettaglio this.modal = document.getElementById('modals-detProdotto'); /*"inC": "0", "qMin":1*/ this.dom = ele; this.switchQuantita(this.carrello.qta); return this; } prodottoCarrello.prototype.setTimeQuantita = function(ty){ var qta = this.carrello.qta;//INT if(this.tOutId) clearTimeout(this.tOutId); this.tOutId=0; if(ty=='+'){ qta += this.carrello.qStp; }else if(ty=='-'){ qta -= this.carrello.qStp; } if(qta<=0) qta=0; if(qta>this.carrello.qMax) qta=this.carrello.qMax; this.qta.innerHTML = qta;//+(this.carrello.qVar==1?'Gr':'') this.carrello.qta = qta; var idProdotto=this.id; var idOrdine=this.idO; var fn = function(){genericoCarrello.switchQuantita(idProdotto,idOrdine,qta);}; this.tOutId = setTimeout(fn,700);// }; prodottoCarrello.prototype.switchQuantita = function(qta){ qta = parseInt(qta,10); if(qta<=0) qta=0; if(qta>this.carrello.qMax) qta=this.carrello.qMax; this.qta.innerHTML = qta; // TODO correggi prezzo totale this.tot }; prodottoCarrello.prototype.getDettaglio = function(){ var self = this; viewLoader('Caricamento in corso...'); $.post(URLSITO+'detProdotto','idProdotto='+this.id,function(){},'json') .done(function(resp){self.getDettaglioDone(resp);}) .fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }; prodottoCarrello.prototype.getDettaglioDone = function(resp){ if(resp.result == "ok"){ var pr = resp.prodotto[0]; var a,b,c,d; var divs = getChildTag(this.modal,"DIV"); for(var l in divs){ switch(divs[l].className){ case "carousel-inner": a=divs[l]; break; case "pull-left nomeProdotto": c=divs[l]; break; case "modal-footer": d=divs[l]; break; } } // carosello if(pr.img.length==0){ pr.img.push("images/prodotti/generico.png"); pr.imgDs.push({tt:'',st:'',ds:''}); } var act="active",x='',y=''; for(var i in pr.img){ x += '
    '; x += ''; //y += '
  • '; act=''; } a.innerHTML = x; //b.innerHTML = y; c.innerHTML = pr.nome; d.innerHTML = pr.dsc; if(!$(this.modal).hasClass('in')){$(this.modal).modal('show');} } }; // ************* !Prodotto *************