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://www.ciaospesa.it/'; var SCMD = 'condizioniGenerali'; var NODISPO = ""; var LOGGEDIN = false; /* 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: 6000}, function(confirm){ setTimeout(fn,200); }); }; function confirmSwal(mex,fn,fn2){ swal({ title: "Avviso", 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'); ldr.firstChild.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 tra i dati disponibili',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, 'non coincidenti',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)); INPUTCOLOR = frm.getElement(fld1).style.borderBottom; frm.getElement(fld1).style.borderBottom = 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+": campo mancante"); 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 = "caratteri"; if(id2==1) c = "carattere"; alertWinScroll(id, 400, ""+nome+": il campo deve contenere un massimo di "+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 = "caratteri"; if(id2==1) c = "carattere"; alertWinScroll(id, 400, ""+nome+": il campo deve contenere " +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+": il valore del campo deve essere inferiore a "+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+": il campo deve essere superiore o uguale al precedente"); 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+": formato non valido"); 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 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(); }; } //****************************************** //********** 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://www.ciaospesa.it/addFoto", fileName:"myfile", multiple:false, dragDrop:false, showFileCounter:false, //maxFileCount:1, //sequential:true, //sequentialCount:2, acceptFiles:"image/*", maxFileSize: 536870912, sizeErrorStr: "troppo grande. Max: " + "512MB", 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://www.ciaospesa.it/loadFoto',"id="+id+"&tbl="+tbl,function(){},'json') .done(function(data){ for(var i=0;i
'+resp.pConsegna[0]['indirizzo']+', '+resp.pConsegna[0]['nCivico']+'
'+resp.pConsegna[0]['comune']; $('#indirizzoModal').html(tmpl); }else{ window.location.reload(false); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } function getPuntoConsegna(id){ viewLoader('Caricamento in corso...'); $.post(URLSITO+'consegnaGet','id='+id,function(){},'text') .done(function(resp){ var modal = document.getElementById('modals-edit_punto_consegna');// modale in cui scrivere if(resp.result='ok'){ var title = getChildTag(modal,"H4"); var frm = getChildTag(modal,"FORM"); frm[0].innerHTML = resp; var fm = formica(frm[0]); title[0].innerHTML = fm.getValue('alias'); $(modal).modal('show'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function modPuntoConsegna(obj){ var frm = formica(obj); flag = true; flag = flag && controlForm(frm, 'Nome del punto consegna','alias',''); flag = flag && controlForm(frm, 'Nome destinatario','nome',''); flag = flag && controlForm(frm, 'Cognome destinatario','cognome',''); flag = flag && controlForm(frm, 'Indirizzo','indirizzo',''); flag = flag && controlForm(frm, 'Civico','nCivico',''); flag = flag && controlForm(frm, 'C.A.P.','cap',''); flag = flag && controlForm(frm, 'Città','citta',''); flag = flag && controlForm(frm, 'Telefono','telefonoMob',''); if(flag){ var radio = document.getElementById('js202306281743'); var ffn = function(){ viewLoader('Salvataggio in corso...'); var fn = function(){window.location.href=URLSITO+'puntiConsegna'} $.post('https://www.ciaospesa.it/consegnaMod',frm.buildUri('php'),function(){},'json') .done(function(resp){ if(resp.result=="ok"){ alertSwal('success',"Modifica effettuata", 'il punto di consegna è stato modificato.', fn); }else if(resp.result=="ko"){ if(resp.error == "ordini"){ alertSwal('warning','Modifica parziale', 'ci sono consegne in corso per questo punto.', fn); }else if(resp.error == "cap"){ alertSwal('error','Punto di consegna non trovato', 'Il tuo punto di consegna non è valido. Riprova cambiando qualcosa.'); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } if(radio.onclick==null){ ffn(); }else{ if(frm.getValue('hot')=='1'){ confirmSwal('Cambiando punto di consegna il carrello verrà svuotato, vuoi continuare?',ffn); }else{ ffn(); } }; } } function delPuntoConsegna(id){ flag = true; if(flag){ viewLoader('Eliminazione in corso...'); $.post('https://www.ciaospesa.it/consegnaDel',"id="+id,function(){},'json') .done(function(resp){ if(resp.result=="ok"){ var fn = function(){window.location.href=URLSITO+'puntiConsegna'} alertSwal('success',"Eliminazione effettuata", 'il punto di consegna è sato eliminato.', fn); }else if(resp.result=="ko"){ if(resp.error == "ordini"){ alertSwal('warning','Eliminazione annullata', 'ci sono consegne in corso per questo punto.'); }else if(resp.error == "hot"){ alertSwal('error','Eliminazione annullata', 'non puoi eliminare il punto consegna in uso.'); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } // *************** carrelli preferiti **************** function prefCarrelloAdd(obj){ var frm = formica(obj); flag = true; flag = flag && controlForm(frm, 'Nome','nome',''); if(flag){ viewLoader('Caricamento in corso...'); $.post('https://www.ciaospesa.it/prefCarrelloAdd',frm.buildUri('php'),function(){},'json') .done(function(resp){ if(resp.result=="ok"){ var fn = function(){$('#modals-salvaCarrello').modal('hide');} alertSwal('success',"Modifica effettuata", 'il carrello è stato aggiunto ai preferiti', fn); }else if(resp.result=="ko"){ if(resp.error == "idOrdine"){ alertSwal('error','Ordine non trovato', 'L\'ordine non è valido.'); }else if(resp.error == "nome"){ alertSwal('warning','Nome carrello duplicato', 'Usa un altro nome per il tuo carrello.'); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } var btn20182305184829 = ''; function getOrariConsegna(obj){ btn20182305184829 = obj.parentNode.parentNode; viewLoader('Caricamento in corso...'); $.post(URLSITO+'orariNegozio','',function(){},'json') .done(function(resp){ var modal = document.getElementById('modals-orariDefinitivi');// modale in cui scrivere var uls = getChildTag(modal,"UL");// uno solo var container = uls[0]; // dove scrivere container.innerHTML = ''; if(resp.result='ok'){ if(resp.orari.length==0){ container.innerHTML = "
  • Spiacente, non sono stati trovati orari utili per la consegna.
  • "; }else{ var msg = ""; var curDay="",d=""; for(var i in resp.orari){ d = resp.orari[i].split("#"); if(curDay!=d[0]){ curDay=d[0]; d[0] = convDate(d[0]); d[0] = d[0].replace(/-/g, "/"); nome = resp.nomi[curDay.replace(/-/g, "_")]; msg += '
  • '+d[0]+'
    '+nome+'
  • '; } msg += '
  • '+d[1]+' - '+d[2]+'
  • '; } container.innerHTML = msg; } $(modal).modal('show'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function setOrariConsegna(dateTime){ var hid = document.getElementById('hid20182305190110'); hid.value=dateTime; var divs = getChildTag(btn20182305184829,"DIV"); dateTime = dateTime.split("#"); dateTime[0] = convDate(dateTime[0]); dateTime[0] = dateTime[0].replace(/-/g, "/"); divs[1].firstChild.innerHTML = ''+dateTime[0]+' · '+dateTime[1]+' - '+dateTime[2]+''; divs[0].style.display='none'; divs[1].style.display='block'; var modal = document.getElementById('modals-orariDefinitivi'); $(modal).modal('hide'); } // funzione che divide in due il compilamento del form nella pagina preinvio (come app) function preInvioDT(){ var hid = document.getElementById('hid20182305190110'); if(hid.value==""){ alertSwal('warning',"Orario di consegna", "scegliere un orario utile per la consegna."); return false; } viewLoader('Caricamento in corso...'); window.location.href=URLSITO+'carrelloPreInvio/'+encodeURIComponent(hid.value.replaceAll('#',' ')); } function metodoPagamento(ty){ /*'1'=Contanti,'2'=Carta di credito,'3'=Bancomat*/ var modal = document.getElementById('modals-metodoPagamento');// modale in cui scrivere var h3 = getChildTag(modal,"H3");// uno solo h3 = h3[0]; var pNota = getChildTag(modal,"P");// dei due il primo pNota = pNota[0]; var form = getChildTag(modal,"FORM");// uno solo form = form[0]; var div = form.firstChild; //replaceClass(div,"","aperto"); var radio = div.firstChild; radio.onclick = function(){ var hid = document.getElementById('hid20182305194222'); if(hid.value=='1'){ hid.value = '0'; replaceClass(this.parentNode,"aperto",""); }else{ hid.value = '1'; replaceClass(this.parentNode,"","aperto"); } } var close = ''; if(ty=="1"){ h3.innerHTML = 'Pagamento in contanti'+close; pNota.innerHTML = 'Il pagamento sarà effettuato al corriere al momento della cosegna. '+' I dati per la fatturazione sono obbligatori.'; // Pagando in contanti potrai decidere se ricevere soltanto lo scontrino o se richiedere la fattura.'; //radio.style.display="inline-block"; radio.style.display="none"; }else if(ty=="4"){ obj = document.getElementById('frm202005172032'); var frm = formica(obj); var dataConsegna = frm.getValue('dataConsegna'); if(dataConsegna==""){ alertSwal('warning',"Orario di consegna", "scegliere un orario utile per la consegna."); var modal = document.getElementById('modals-metodoPagamento'); $(modal).modal('hide'); return false; }else{ var dataMax = '2026-09-24'; dataConsegna = dataConsegna.split('#'); if(dataConsegna[0]>dataMax){ alertSwal('warning',"Pagamento on line", "abilitato per consegne entro il giorno "+convDate(dataMax)+"."); return false; }; } h3.innerHTML = 'Dati di fatturazione e invio ordine'+close; pNota.innerHTML = 'Verrà trattenuto sulla carta un importo pari al "prezzo della spesa maggiorato del 10%" e la transazione sarà completata (con l\'importo reale della spesa) al momento della cosegna.'+ '
    Pagando con carta di credito potrai decidere se ricevere soltanto la ricevuta o se richiedere la fattura.'+ '
    Con l\'invio del presente ordine confermi l\'accettazione delle Condizioni Generali di Vendita già accettate al momento della registrazione '+ 'e di cui puoi prendere visione nella sezione Aiuti ed Istruzioni.'; // checkbox salva carta var div = document.getElementById('apri-chiudi-carta'); var radio = div.firstChild; radio.onclick = function(){ var hid = document.getElementById('hid202311301510'); if(hid.value=='1'){ hid.value = '0'; replaceClass(this.parentNode,"aperto",""); }else{ hid.value = '1'; replaceClass(this.parentNode,"","aperto"); } } }else{ h3.innerHTML = 'Dati di fatturazione e invio ordine'+close; //pNota.innerHTML = 'Il pagamento sarà sempre effettuato al corriere al momento della cosegna.'+' I dati per la fatturazione sono obbligatori.'; pNota.innerHTML = 'Il pagamento sarà effettuato al corriere al momento della cosegna. '+ 'Pagando con carta di credito e bancomat potrai decidere se ricevere soltanto la ricevuta o se richiedere la fattura.'+ '
    Con l\'invio del presente ordine confermi l\'accettazione delle Condizioni Generali di Vendita già accettate al momento della registrazione '+ 'e di cui puoi prendere visione nella sezione Aiuti ed Istruzioni.'; // Il pagamento con carta di credito e bancomat richiedono obbligatoriamente i dati per la fatturazione.'; radio.style.display="inline-block"; } //$(this).toggleClass( 'aperto' );" var hid = document.getElementById('hid20182305193110'); hid.value=ty; $(modal).modal('show'); } function inviaOrdine(obj){ var frm = formica(obj); flag = true; if(flag && frm.getValue('dataConsegna')==""){ alertSwal('warning',"Orario di consegna", "scegliere un orario utile per la consegna."); var modal = document.getElementById('modals-metodoPagamento'); $(modal).modal('hide'); flag = false; } if(flag && frm.getValue('fattura')=="1"){ flag = flag && controlForm(frm, 'Nome e cognome/Ragione sociale','nome_rag',''); if(flag && frm.getValue('piva')=='' && frm.getValue('cfisc')==''){ alertSwal('warning',"Partita Iva o Codice fiscale",'inserire almeno uno'); flag = false; } if(flag && frm.getValue('piva')!='') flag = flag && controlForm(frm, 'Partita IVA','piva','',"cf_pi"); if(flag && frm.getValue('cfisc')!='')flag = flag && controlForm(frm, 'Codice Fiscale','cfisc','',"cf_pi"); //flag = flag && controlForm(frm, 'E-mail','email',''); if(frm.getValue('email')!=''){ flag = flag && controlForm(frm, 'E-mail','email','','@'); } flag = flag && controlForm(frm, 'Città','citta',''); flag = flag && controlForm(frm, 'Indirizzo','indirizzo',''); flag = flag && controlForm(frm, 'C.A.P.','cap',''); if(frm.getValue('sdi')!=''){ flag = flag && controlForm(frm, 'Codice SdI','sdi','','sdi'); } } var idMetodo = frm.getValue('idMetodo'); if(flag){ viewLoader('Caricamento in corso...'); $.post('https://www.ciaospesa.it/inviaOrdine',frm.buildUri('php'),function(){},'json') .done(function(resp){ if(resp.result=="ok"){ if(idMetodo!="4"){ var fn = function(){window.location.href=URLSITO+'home'} alertSwal('success',"Invio effettuato", 'l\'ordine è stato inviato al negozio, grazie per averci scelto.', fn); }else{ var modal = document.getElementById('modals-metodoPagamento'); $(modal).modal('hide'); var modal = document.getElementById('modals-stripe');// modale in cui scrivere $(modal).modal('show'); } }else if(resp.result=="ko"){ if(resp.error == "ordine"){ alertSwal('error','Ordine non trovato', 'L\'ordine non è valido.'); }else if(resp.error == "consegna"){ alertSwal('error','Punto di consegna rifiutato', 'i prodotti sono stati rimossi dal carrello.'); }else if(resp.error == "dataConsegna"){ alertSwal('error','Data di consegna', 'non valida o non più disponibile.'); }else if(resp.error == "stripe"){ var fn = function(){window.location.reload(false)}; alertSwal('error','Paga adesso', 'al momento non disponibile, ci scusiamo per l\'inconveniente.',fn); }else if(resp.error == "dataS"){ var dataMax = '2026-09-24'; alertSwal('warning',"Pagamento on line", "abilitato per consegne entro il giorno "+convDate(dataMax)+"."); }else if(resp.error == "datiFiscali"){ alertSwal('error','Dati di fatturazioni', 'incompleti, per favore, completare il form di invio.'); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } // ************************ Ordini **************** function getOrdine(id){ viewLoader('Caricamento in corso...'); $.post(URLSITO+'ordineGet','id='+id,function(){},'text') .done(function(resp){ var modal = document.getElementById('modals_ordine');// modale in cui scrivere if(resp.result='ok'){ var frm = getChildTag(modal,"FORM"); frm[0].innerHTML = resp; $(modal).modal('show'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function delOrdine(id){ confirmSwal('Vuoi annullare quest\'ordine?',function(){ viewLoader('Archiviazione in corso...'); $.post('https://www.ciaospesa.it/ordineDel',"id="+id,function(){},'json') .done(function(resp){ if(resp.result=="ok"){ var fn = function(){window.location.href=URLSITO+'ordini'} alertSwal('success',"Archiviazione effettuata", 'l\'ordine è sato archiviato.', fn); }else if(resp.result=="ko"){ if(resp.error == "ordini"){ alertSwal('warning','Archiviazione annullata', 'ordine non annullabile.'); }else if(resp.error == "hot"){ alertSwal('error','Archiviazione annullata', 'puoi annullare l\'ordine ad almeno 3 ore dalla consegna.'); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }); } // ************************ Carrelli salvati **************** function getCarrello(id){ viewLoader('Caricamento in corso...'); $.post(URLSITO+'carrelloGet','id='+id,function(){},'text') .done(function(resp){ var modal = document.getElementById('modals_carrello_salvato');// modale in cui scrivere if(resp.result='ok'){ var frm = getChildTag(modal,"FORM"); frm[0].innerHTML = resp; $(modal).modal('show'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function addCarrello(id){ viewLoader('Operazione in corso...'); $.post('https://www.ciaospesa.it/carrelloPlus',"id="+id,function(){},'json') .done(function(resp){ if(resp.result=="ok"){ var fn = function(){window.location.href=URLSITO+'carrelliSalvati'} alertSwal('success',"Modifica effettuata", 'i prodotti sono stati aggiunti al carrello.', fn); }else if(resp.result=="nop"){ alertSwal('warning','Importazione parziale', 'alcuni prodotti del carrello non sono disponibili.'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function delCarrello(id){ confirmSwal('Vuoi cancellare questo carrello preferito?',function(){ viewLoader('Eliminazione in corso...'); $.post('https://www.ciaospesa.it/carrelloDel',"id="+id,function(){},'json') .done(function(resp){ if(resp.result=="ok"){ var fn = function(){window.location.href=URLSITO+'carrelliSalvati'} alertSwal('success',"Eliminazione effettuata", 'il carrello è stato eliminato.', fn); }else if(resp.result=="ko"){ alertSwal('warning','Eliminazione annullata', 'impossibile eliminare il carrello.'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }); } /***************** FACEBOOK **************/ window.fbAsyncInit = function() { FB.init({ appId : '598585120506019',//'739415966247403', cookie : true, // enable cookies to allow the server to access xfbml : true, // parse social plugins on this page version : 'v10.0' // use graph api version 2.8 //autoLogAppEvents : true, }); FB.getLoginStatus(function(response) { if (response.status === 'connected') { if(!LOGGEDIN) getFbUserData(); } }); }; (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/it_IT/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); window.fbAsyncInit = function() { FB.init({ appId: '598585120506019', cookie: true, // This is important, it's not enabled by default version: 'v2.10' }); }; function fbLogin() { FB.login(function (response) { if (response.authResponse) { getFbUserData(); } else { alertSwal('warning','Accesso con Facebook', 'richiesta annullata o non autorizzata.'); } }, {scope: 'email'}); } function getFbUserData(){ FB.api('/me', {locale: 'it_IT', fields: 'id,first_name,last_name,email,picture'},//,age_range,link,gender,locale, function (response) { /*document.getElementById('fbLink').setAttribute("onclick","fbLogout()"); document.getElementById('fbLink').innerHTML = 'Logout from Facebook'; document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!'; document.getElementById('userData').innerHTML = '

    FB ID: '+response.id+'

    Name: '+response.first_name+' '+response.last_name+'

    Email: '+response.email+'

    Gender: '+response.gender+'

    Locale: '+response.locale+'

    Picture:

    FB Profile: click to view profile

    ';*/ /*if(response.age_range==undefined) response.age_range = {'min':18} if(response.age_range['min']<18){ FB.api('/me/permissions', 'delete', function(response) { alertSwal('warning','Richiesta Facebook', 'rifiutata per minori di anni 18', function(){fbLogout()}); }); }else{*/ if(!LOGGEDIN) saveUserData(response); /*}*/ }); } function fbLogout() { var dummy = FB.getLoginStatus(function(response) { if (response.status === 'connected') { FB.logout(function() { location.href='https://www.ciaospesa.it/logout'; }); }else{ location.href='https://www.ciaospesa.it/logout'; } }); if(dummy==undefined){ location.href='https://www.ciaospesa.it/logout'; }; } function glLogin(response) { const responsePayload = decodeJWT(response.credential); saveUserDataG(responsePayload); /*console.log(" Full Name: " + responsePayload.name); console.log(" Given Name: " + responsePayload.given_name); console.log(" Family Name: " + responsePayload.family_name); console.log(" Unique ID: " + responsePayload.sub); console.log(" Profile image URL: " + responsePayload.picture); console.log(" Email: " + responsePayload.email);*/ } function decodeJWT(token) { let base64Url = token.split(".")[1]; let base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/"); let jsonPayload = decodeURIComponent( atob(base64) .split("") .map(function (c) { return "%" + ("00" + c.charCodeAt(0).toString(16)).slice(-2); }) .join("") ); return JSON.parse(jsonPayload); } function saveUserDataG(userData){ viewLoader('Caricamento in corso...'); $.post('https://www.ciaospesa.it/userDataG', {oauth_provider:'google',userData: JSON.stringify(userData)}, function(){},'json') .done(function(resp){ if (resp.result=="ok") { window.location.reload(false); } else { alertSwal('warning','Richiesta google', 'richiesta annullata o non autorizzata.'); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function eliminaUtente() { confirmSwal('1/2 Facendo clic su Ok cancellerai il tuo profilo e i tuoi dati.',function(){ confirmSwal('2/2 Sei sicuro di voler cancellare il tuo account?',function(){ viewLoader('Eliminazione in corso...'); $.post('https://www.ciaospesa.it/userDel','',function(){},'json') .done(function(resp){ if(resp.result=="ok"){ var fn = function(){window.location.href=URLSITO+'logout'} alertSwal('success',"Eliminazione effettuata", 'i tuoi dati sono stati cancellati.', fn); }else if(resp.result=="ko"){ if(resp.error == "ordini"){ alertSwal('warning','Eliminazione annullata', 'hai un ordine pendente.'); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }); }); } function saveUserData(userData){ viewLoader('Caricamento in corso...'); $.post('https://www.ciaospesa.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','email',''); flag = flag && controlForm(frm, 'Email','email','','@'); if (flag) { viewLoader('Caricamento in corso...'); $.post('https://www.ciaospesa.it/forgottenPass', frm.buildUri('php'), function () {}, 'json').done(function (resp) { if (resp.s == "ok") { alertSwal('success','', 'A breve riceverai un\'e-mail per il ripristino della password','window.location.href=URLSITO'); } else if (resp.s == 'no') { alertSwal('error','', "Errore durante la modifica"); } 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, 'Le password','password','password2','='); if (flag) { viewLoader('Caricamento in corso...'); $.post('https://www.ciaospesa.it/resetPass', frm.buildUri('php'), function () {}, 'json').done(function (resp) { if (resp.s == "ok") { alertSwal('success','', 'Password modificata',"location.href='https://www.ciaospesa.it/'"); } else { alertSwal('error','', "Errore durante la modifica"); } }).fail(function () { alertSwal('error','', "Errore di connessione"); }).always(function (resp) { hideLoader(resp,0); }); } } function addCoupon(obj){ var frm = formica(obj); flag = true; flag = flag && controlForm(frm, 'Codice coupon','codice',''); if(flag){ viewLoader('Inserimento in corso...'); var fn = function(){window.location.href=URLSITO+'coupon'} $.post('https://www.ciaospesa.it/couponAdd',frm.buildUri('php'),function(){},'json') .done(function(resp){ if(resp.result=="ok"){ alertSwal('success',"Inserimento effettuato", 'il coupon è sato aggiunto.', fn); }else if(resp.result=="ko"){ alertSwal('warning','Codice coupon', 'non valido o scaduto.', fn); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } } function modServizio(idS,pubS){// simile a carrello.switchServizi viewLoader('Caricamento in corso...'); var strUri="idS[]="+idS+"&pubS[]="+pubS; $.post(URLSITO+'modServizio', strUri, function () {}, 'json') .done(function (resp) { if (resp.s == "ok") { window.location.reload(false); } else { alertSwal('error','', "Errore durante la modifica"); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); } function voto(obj,id,curr,evnt){ var hidd = document.getElementById('rank'+curr); var currentVal = hidd.value; var links = getChildTag(obj.parentNode,"A"); for(var l in links){ if(links[l].className.indexOf('star')>-1){//### stelle switch(evnt){ case "over": if(l-1){//### stelle links[l].onclick = function() {return false;}; links[l].onmouseover = function() {return false;}; links[l].onmouseout = function() {return false;}; links[l].ontouchstart = function() {return false;}; links[l].ontouchend = function() {return false;}; links[l].removeAttribute("href"); } if(links[l].className.indexOf('accesa')==-1) links[l].style.visibility='hidden'; } }; alertSwal('success',"Votazione effettuata", 'grazie per il tuo riscontro.', fn); }else if(resp.result=="ko"){ if(resp.error == "ordini"){ alertSwal('warning','Voto annullato', 'non è stato possibile votare.'); } } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }); } function eliminaCarta(obj,idPm){ confirmSwal("Vuoi eliminare la carta?",function(){ viewLoader('Eliminazione in corso...'); var frm = "pm="+idPm $.post('https://www.ciaospesa.it/eliminaCarta',frm,function(){},'json') .done(function(resp){ if(resp.result=="ok"){ var fn = function(){ var riga = obj.parentNode.parentNode; var radios = getChildTag(riga.parentNode,"INPUT"); for(var r in radios){ if(radios[r].value=="new-card") radios[r].checked=true; } riga.remove(); }; alertSwal('success',"Eliminazione effettuata", '', fn); }else if(resp.result=="ko"){ alertSwal('warning','Eliminazione fallita', ''); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }); }// ************* Detrit ************* /** * Strutture array ad albero, con indicizzazione in memoria * * @param array array array anche di oggetti di un recordset * @param string key nome chiave primaria del recordset (univoca) * * @function set aggiunge un elemento al recordset * @param el elemento con dentro la chiave key * * @function get restituisce un elemento al recordset * @param key valore di key per l'elemento cercato * @throws No Exception * @author Pastix */ // ************* Decimal tree ************* function detrit(array,key) { this.id = key; this.length = 0; this.root = {value:null}; for(k in array){ this.set(array[k]); } return this; } detrit.prototype.set = function(el){ this.pt = this.root; this.add(el,String(el[this.id])); }; 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.length++; }else{ this.add(el,idx[1]); } }; detrit.prototype.get = function(key){ var keys = String(key).split('').reverse().join(']['); if(keys==''){ return null; }else{ try{ return eval('this.root['+keys+'].value'); }catch(err) {return null;} } }; // ************* !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 preferiti != 'undefined' && preferiti.instance=="preferiti") this.controllers.push(preferiti); if(typeof inEvidenza != 'undefined' && inEvidenza.instance=="inEvidenza") this.controllers.push(inEvidenza); if(typeof generico != 'undefined' && generico.instance=="generico") this.controllers.push(generico); }, switchPreferito: function(idProdotto){ var oThis = this; viewLoader('Caricamento in corso...'); $.post(URLSITO+"preferiti","idProdotto="+encodeURIComponent(idProdotto),function(){},'json') .done(function(resp){ if(resp.result=="ok"){ oThis.switchPreferitoDone(idProdotto,resp.preferito); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }, switchPreferitoDone: function(idProdotto,preferito){ for(var j in this.controllers) this.controllers[j].switchPreferito(idProdotto,preferito); }, switchQuantita: function(idProdotto,qta){ var oThis = this; viewLoader('Caricamento in corso...'); $.post(URLSITO+"prodottiCarrello","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+"img/prodotti/generico.png"; if(resp.prodotti[i].img!=""){ iconaz = URLSITO+resp.prodotti[i].img; } if(resp.prodotti[i].qVar==0){ qtaz = qta+" pz"; }else{ qtaz = qta+" gr"; } notificaTopRight(resp.ordine.pzT,iconaz,resp.prodotti[i].nom,qtaz); } } } oThis.switchQuantitaDone(idProdotto,resp); } }).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); // pop up degli orari utili if(carrello.gui.notifica.innerHTML=="" && resp.prodotti.length>0){ carrello.loadOrariUtili(); }; carrello.getCarrello(); }, }; addEvent(window, 'load', function () { dispatcher.initialize(); });// ************* Prodotto ************* var tmplProdotto = ''+ '
    '+ '##nome##'+ '
    '+ '
    '+ '##sconto##'+ '##marca####nome##
    '+ '##prezzo####tagliato##
    '+ '(€ ##prezzoKg## al ##um##)'+ '
    '+ '
    '+ '
    '+ '
    '+ '+'+ '##qta##'+ '-'+ '
    '+ ''+ '
    '; var tmplSconto = '
    ##promo##
    ##perc##
    '; function prodotto(p) { this.id = p.id; var tmpl = tmplProdotto.replace(/##id##/g, p.id); tmpl = tmpl.replace(/##nome##/g, p.nom.replace('"','\"')); tmpl = tmpl.replace(/##marca##/g, p.mrk.replace('"','\"')); //tmpl = tmpl.replace(/##peso##/g, p.ps+' '+p.um); if(p.pro.id!=''){ if(p.pro.cons==0){ var tmplS = tmplSconto.replace(/##perc##/g, "-"+p.pro.sco.replace('"','\"')+"%"); //tmplS = tmplS.replace(/##promocss##/g,'percentuale'); var prezzo = parseFloat(p.pz.replace(",",'.')).toFixed(2); //var sconto = (prezzo*parseInt(p.pro.sco,10)/100).toFixed(2); var sconto = (prezzo*parseFloat(p.pro.scoF)/100); prezzo = (prezzo - sconto).toFixed(2); tmpl = tmpl.replace(/##prezzo##/g, '€ '+prezzo.replace('.',',')+' '); tmpl = tmpl.replace(/##tagliato##/g, '€ '+p.pz); }else{ var tmplS = tmplSconto.replace(/##perc##/g, ''); //tmplS = tmplS.replace(/##promocss##/g,'consegna'); tmpl = tmpl.replace(/##prezzo##/g, '€ '+p.pz); tmpl = tmpl.replace(/##tagliato##/g, ''); } tmplS = tmplS.replace(/##promo##/g, p.pro.nme.replace('"','\"')); tmpl = tmpl.replace(/##sconto##/g, tmplS); }else{ tmpl = tmpl.replace(/##sconto##/g, ''); tmpl = tmpl.replace(/##prezzo##/g, '€ '+p.pz); tmpl = tmpl.replace(/##tagliato##/g, ''); } if(p.img=="") p.img = "img/prodotti/generico.png"; tmpl = tmpl.replace(/##img##/g, URLSITO+p.img); tmpl = tmpl.replace(/##prezzoKg##/g, p.kg); tmpl = tmpl.replace(/##um##/g, p.ump); tmpl = tmpl.replace(/##qta##/g, p.minC); var ele = document.createElement('DIV'); ele.className = 'prodotto'; 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 break; } } this.carrello = {qta:p.minC,qMax:p.qMax,qStp:p.qStp,qVar:p.qVar}; this.tOutId=0; var links = getChildTag(ele,"A"); for(var l in links){ switch(links[l].className){ case "preferito": this.pf = links[l];//### link preferito links[l].onclick = function(){dispatcher.switchPreferito(p.id);};//niente this if(p.pf=="1") replaceClass(this.pf,"","attivo"); break; case "piu": this.piu = links[l];//### link piu' if(p.minC>"0") replaceClass(this.piu.parentNode,"","aperto"); 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'); this.pop = {}; /*"inC": "0", "qMin":1*/ this.dom = ele; return this; } prodotto.prototype.switchPreferito = function(res){ if(res=="0"){ replaceClass(this.pf,"attivo",""); }else if(res=="1"){ replaceClass(this.pf,"","attivo"); } }; prodotto.prototype.setTimeQuantita = function(ty){ if(this.tOutId) clearTimeout(this.tOutId); this.tOutId=0; var qta = parseInt(this.carrello.qta,10); //this.carrello = {qta:p.minC,qMax:p.qMax,qStp:p.qStp,qVar:p.qVar}; if(ty=='+'){ qta += this.carrello.qStp; }else{ qta -= this.carrello.qStp; } if(qta<=0){ qta=0; replaceClass(this.piu.parentNode,"aperto",""); }else{ replaceClass(this.piu.parentNode,"","aperto"); } if(qta>this.carrello.qMax){ qta=this.carrello.qMax; } this.qta.innerHTML = qta; this.carrello.qta = qta; var idProdotto=this.id; var fn = function(){dispatcher.switchQuantita(idProdotto,qta);}; this.tOutId = setTimeout(fn,700);// }; prodotto.prototype.switchQuantita = function(qta){ qta = parseInt(qta,10); if(qta<=0){ qta=0; replaceClass(this.piu.parentNode,"aperto",""); }else{ replaceClass(this.piu.parentNode,"","aperto"); } if(qta>this.carrello.qMax){ qta=this.carrello.qMax; } this.qta.innerHTML = qta; }; 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]; this.pop.id = pr.id; var a,b,c,d,e,f; var divs = getChildTag(this.modal,"DIV"); for(var l in divs){ switch(divs[l].className){ case "carousel-inner": a=divs[l]; break; case "dati col-sm-6": var spans = getChildTag(divs[l],"SPAN"); for(var l in spans){ switch(spans[l].className){ case "marca": spans[l].innerHTML = pr.mrk.replace('"','\"'); break; case "nome_prodotto": spans[l].innerHTML = pr.nom.replace('"','\"'); break; case "prezzo": case "prezzo_listino": if(pr.pro.id!=''){ if(pr.pro.cons==0){ if(spans[l].className=='prezzo'){ var prezzo = parseFloat(pr.pz.replace(",",'.')).toFixed(2); //var sconto = (prezzo*parseInt(pr.pro.sco,10)/100).toFixed(2); var sconto = (prezzo*parseFloat(pr.pro.scoF)/100); prezzo = (prezzo - sconto).toFixed(2); //tmplS = '
    € '+prezzo.replace('.',',')+'   € '+pr.pz+'
    '; tmplS = '€ '+prezzo.replace('.',',')+'   '; }else if(spans[l].className=='prezzo_listino'){ tmplS = '€ '+pr.pz; } }else{ if(spans[l].className=='prezzo'){ //tmplS = '
    € '+pr.pz+'
    '; tmplS = '€ '+pr.pz; }else if(spans[l].className=='prezzo_listino'){ tmplS = ''; } } spans[l].innerHTML = tmplS; }else{ if(spans[l].className=='prezzo'){ spans[l].innerHTML = '€ '+pr.pz; }else if(spans[l].className=='prezzo_listino'){ spans[l].innerHTML = ''; } } break; case "prezzo_campione": spans[l].innerHTML = "(€ "+pr.kg+" al "+pr.ump+")"; break; /*case "pxc": spans[l].innerHTML = "PxC: "+pr.pxc.replace('"','\"'); break;*/ case "prezzo_30": if(pr.pro.id!='') spans[l].innerHTML = "prezzo piu basso ultimi 30gg € "+pr.pz30+""; break; case "quantita": this.pop.qta = spans[l]; spans[l].innerHTML = pr.minC; break; } } break; case "prodotti": this.pop.prodotti=divs[l]; break; case "promo": if(pr.pro.id!=''){ divs[l].style.display='block'; if(pr.pro.cons==0){ var tmplS = tmplSconto.replace(/##perc##/g, "-"+pr.pro.sco.replace('"','\"')+"%"); //tmplS = tmplS.replace(/##promocss##/g,'percentuale'); }else{ var tmplS = tmplSconto.replace(/##perc##/g, ''); //tmplS = tmplS.replace(/##promocss##/g,'consegna'); } var nomeP = pr.pro.nme.replace('"','\"'); if(pr.pro.dsc.trim()!='') nomeP = nomeP+' *';// se manca la sercrizione non mettere * tmplS = tmplS.replace(/##promo##/g, nomeP); divs[l].outerHTML = tmplS; /*var ele = document.createElement('SPAN'); ele.className = 'apice colore1'; ele.innerHTML = ' *'; divs[l].appendChild(ele);*/ }else{ divs[l].style.display='none'; } break; case "nota asterisco": if(pr.pro.dsc.trim()!=''){ var tasto = '
    : '+pr.pro.dsc+tasto; }else{ divs[l].innerHTML = ''; } break; case "caratteristiche disponibilita": divs[l].innerHTML = ''; if(pr.car.length>0){ var sel = document.createElement('SELECT'); sel.name='idCaratteristica'; sel[0] = new Option("Pezzi/Fette o altro", '0', false, false);//Scegli un'opzione pr.car.forEach(function (carat){ sel[sel.options.length] = new Option(carat.n, carat.id, false, carat.s=='1'); }); var p = document.createElement('P'); p.innerHTML = 'Nota per lo shopper'; divs[l].appendChild(p); divs[l].appendChild(sel); divs[l].onchange = this.setTimeQuantitaPop.bind(this,"="); this.idCarat = sel; //divs[l].className = 'disponibilita'; }else{ var inp = document.createElement('INPUT'); inp.value = '0'; inp.name='idCaratteristica'; inp.type = 'hidden'; divs[l].appendChild(inp); this.idCarat = inp; }; 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("img/prodotti/generico.png"); var act="active",x='',y=''; for(var i in pr.img){ x += '
    '; y += '
  • '; act=''; } a.innerHTML = x; b.innerHTML = y; var links = getChildTag(this.modal,"A"); for(var l in links){ switch(links[l].className){ case "preferito": this.pop.pf = links[l];//### link preferito links[l].onclick = this.switchPreferitoPop.bind(this);//niente this if(pr.pf=="1") replaceClass(this.pop.pf,"","attivo"); break; case "piu": this.pop.piu = links[l];//### link piu' links[l].onclick = this.setTimeQuantitaPop.bind(this,"+"); break; case "meno": links[l].onclick = this.setTimeQuantitaPop.bind(this,"-");//### link meno break; } } var selss = getChildTag(this.modal,"SELECT"); for(var l in selss){ switch(selss[l].className){ case "selectpicker": this.noDispo = selss[l];//### select no dispo this.noDispo.innerHTML = NODISPO; this.noDispo.value = pr.noId; this.noDispo.onchange = this.setTimeQuantitaPop.bind(this,"="); break; } } if(resp.suggeriti.length==0){ this.pop.prodotti.innerHTML="Non ci sono prodotti suggeriti"; }else{ this.pop.prodotti.innerHTML=""; } var fn = function(){ dispatcher.switchPreferito(this.id); if(hasClass(this.pf,"attivo")){ replaceClass(this.pf,"attivo",""); }else{ replaceClass(this.pf,"","attivo"); } }; for(var p in resp.suggeriti){ var prod = new prodotto(resp.suggeriti[p]); this.pop.prodotti.appendChild(prod.dom); prod.pf.onclick = fn.bind(prod); }; if(!$(this.modal).hasClass('in')){$(this.modal).modal('show');} this.pop.carrello = {qta:pr.minC,qMax:pr.qMax,qStp:pr.qStp,qVar:pr.qVar}; } }; prodotto.prototype.switchPreferitoPop = function(){ dispatcher.switchPreferito(this.pop.id); if(hasClass(this.pop.pf,"attivo")){ replaceClass(this.pop.pf,"attivo",""); }else{ replaceClass(this.pop.pf,"","attivo"); } }; prodotto.prototype.setTimeQuantitaPop = function(ty){ if(this.tOutId) clearTimeout(this.tOutId); this.tOutId=0; var qta = parseInt(this.pop.carrello.qta,10); if(ty=='+'){ qta += this.pop.carrello.qStp; }else if(ty=='-'){ qta -= this.pop.carrello.qStp; } if(qta<=0) qta=0; if(qta>this.pop.carrello.qMax) qta=this.pop.carrello.qMax; this.pop.qta.innerHTML = qta; this.pop.carrello.qta = qta; var idProdotto=this.pop.id; var noId = this.noDispo.value; var carId = this.idCarat.value; var strUri= "idProdotto="+encodeURIComponent(idProdotto)+"&qta="+encodeURIComponent(qta)+"&idNoDisp="+encodeURIComponent(noId)+"&idCarat="+encodeURIComponent(carId); $.post(URLSITO+"prodottiCarrello",strUri,function(){},'json') .done(function(resp){ }).fail(function(){}) .always(function(resp){}); var fn = function(){dispatcher.switchQuantita(idProdotto,qta);}; this.tOutId = setTimeout(fn,700);// }; // ************* !Prodotto *************// ************* Prodotto ************* var tmplProdottoCarrello = '
    '+ '
    ##nome##
    '+ '
    ##marca####nome##
    '+ //'##peso##'+ '##sconto##'+ '##prezzo####tagliato##'+ '

    Aggiungi ai preferiti

    '+ '
    '+ '-##qta##+
    '+//Aggiungi /*'

    Se il prodotto non è disponibile

    '+*/ '

    Nota per lo shopper

    '+ ''+ '
    '; function prodottoCarrello(p) { this.id = p.id; var tmpl = tmplProdottoCarrello.replace(/##id##/g, p.id); tmpl = tmpl.replace(/##nome##/g, p.nom.replace('"','\"')); tmpl = tmpl.replace(/##marca##/g, p.mrk.replace('"','\"')); var tmplSconto = '
    ##promo## *
    ##perc##
    '; //tmpl = tmpl.replace(/##peso##/g, p.ps+' '+p.um); if(p.pro.id!=''){ if(p.pro.cons==0){ var tmplS = tmplSconto.replace(/##perc##/g, "-"+p.pro.sco.replace('"','\"')+"%"); /*var prezzo = parseFloat(p.pz.replace(",",'.')).toFixed(2); var sconto = (prezzo*parseInt(p.pro.sco,10)/100).toFixed(2); prezzo = (prezzo - sconto).toFixed(2); tmpl = tmpl.replace(/##prezzo##/g, '€ '+prezzo.replace('.',',')+'   € '+p.pz+'');*/ }else{ var tmplS = tmplSconto.replace(/##perc##/g, ''); //tmpl = tmpl.replace(/##prezzo##/g, '€ '+p.pz); } tmplS = tmplS.replace(/##promo##/g, p.pro.nme.replace('"','\"')); tmpl = tmpl.replace(/##sconto##/g, tmplS); }else{ //tmpl = tmpl.replace(/##peso##/g, ''); tmpl = tmpl.replace(/##prezzo##/g, '€ '+p.pz); tmpl = tmpl.replace(/##sconto##/g, ''); } if(p.img=="") p.img = "img/prodotti/generico.png"; tmpl = tmpl.replace(/##img##/g, URLSITO+p.img); //tmpl = tmpl.replace(/##prezzo##/g, "€ "+p.pz); tmpl = tmpl.replace(/##qta##/g, p.minC); var ele = document.createElement('DIV'); ele.className = 'dettaglio_prodotto'; 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 break; case "prezzo": this.pz = spans[l]; break; case "prezzo_listino": this.pzT = spans[l]; break; } } /*var spans = getChildTag(ele,"DIV"); for(var l in spans){ switch(spans[l].className){ case "prezzo": this.pz = spans[l];//### div prezzo break; } }*/ var selss = getChildTag(ele,"SELECT"); for(var l in selss){ switch(selss[l].className){ case "selectpicker": this.noDispo = selss[l];//### select no dispo// ora caratteristiche //this.noDispo.innerHTML = NODISPO; //this.noDispo.value = p.noId; if(p.car.length>0){ this.noDispo.name='idCaratteristica'; this.noDispo[0] = new Option("Pezzi/Fette o altro", '0', false, false);//Scegli un'opzione oThis = this; var xarat = '0'; p.car.forEach(function (carat){ oThis.noDispo[oThis.noDispo.options.length] = new Option(carat.n, carat.id, false, carat.s=='1'); if(carat.s=='1') xarat = carat.id; }); this.noDispo.value = xarat; this.noDispo.onchange = this.setTimeQuantita.bind(this,"="); }else{ this.noDispo.parentNode.style.display='none'; } break; } } var PQ=this.prezzoQuantita(p.minC,p.pz,p.qVar,p.ps,p.kg,p.pro.id,p.pro.cons,p.pro.sco,p.pro.scoF); this.pz.innerHTML = PQ.prezzo; this.pzT.innerHTML = PQ.tagliato; this.carrello = {qta:p.minC,qMax:p.qMax,qStp:p.qStp,qVar:p.qVar,ps:p.ps,pz:p.pz,kg:p.kg,proId:p.pro.id,proCons:p.pro.cons,proSco:p.pro.sco,proScoF:p.pro.scoF}; this.tOutId=0; var links = getChildTag(ele,"A"); for(var l in links){ switch(links[l].className){ case "preferito": this.pf = links[l];//### link preferito links[l].onclick = this.switchPreferito.bind(this); if(p.pf=="1") replaceClass(this.pf,"","attivo"); break; case "piu": this.piu = links[l];//### link piu' if(p.minC>"0") replaceClass(this.piu.parentNode,"","aperto"); links[l].onclick = this.setTimeQuantita.bind(this,"+"); break; case "meno": links[l].onclick = this.setTimeQuantita.bind(this,"-");//### link meno break; } } if(typeof carrello != 'undefined' && carrello.instance=="carrello") this.controller = carrello; this.dom = ele; return this; } prodottoCarrello.prototype.switchPreferito = function(){ var oThis = this; viewLoader('Caricamento in corso...'); $.post(URLSITO+"preferiti","idProdotto="+encodeURIComponent(this.id),function(){},'json') .done(function(resp){ if(resp.result=="ok"){ oThis.switchPreferitoDone(resp.preferito); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }; prodottoCarrello.prototype.switchPreferitoDone = function(res){ if(res=="0"){ replaceClass(this.pf,"attivo",""); }else if(res=="1"){ replaceClass(this.pf,"","attivo"); } }; prodottoCarrello.prototype.setTimeQuantita = function(ty){ if(this.tOutId) clearTimeout(this.tOutId); this.tOutId=0; var qta = parseInt(this.carrello.qta,10); 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.qta = qta; var PQ = this.prezzoQuantita(this.carrello.qta.toString(),this.carrello.pz,this.carrello.qVar,this.carrello.ps,this.carrello.kg,this.carrello.proId,this.carrello.proCons,this.carrello.proSco,this.carrello.proScoF); this.pz.innerHTML = PQ.prezzo; this.pzT.innerHTML = PQ.tagliato; var fn = this.switchQuantita.bind(this); this.tOutId = setTimeout(fn,700);// }; prodottoCarrello.prototype.switchQuantita = function(){ var oThis = this; var strUri= "idProdotto="+encodeURIComponent(this.id)+"&qta="+encodeURIComponent(this.carrello.qta)+"&idNoDisp=&idCarat="+encodeURIComponent(this.noDispo.value); viewLoader('Caricamento in corso...');// da un po' fastidio onestamente $.post(URLSITO+"prodottiCarrello",strUri,function(){},'json') .done(function(resp){ if(resp.result=="ok"){ oThis.switchQuantitaDone(resp); } }).fail(function(){alertSwal('error','', "Errore di connessione");}) .always(function(resp){hideLoader(resp,0);}); }, prodottoCarrello.prototype.switchQuantitaDone = function(resp){ if(resp.result=="ok"){ var prod = resp.prodotti[0]; this.qta.innerHTML = prod.qta; //this.noDispo.value = prod.noId; var PQ = this.prezzoQuantita(prod.minC,prod.pz,prod.qVar,prod.ps,prod.kg,prod.pro.id,prod.pro.cons,prod.pro.sco,prod.pro.scoF); this.pz.innerHTML = PQ.prezzo; this.pzT.innerHTML = PQ.tagliato; this.controller.getCarrello(); } }; prodottoCarrello.prototype.prezzoQuantita = function(qta,pz,qVar,ps,kg,pId,pCon,pSco,pScoF){ if(qta=="0") return {'prezzo':'€ 0,00','tagliato':''}; qta = qta.replace(',', '.'); qta = parseFloat(qta).toFixed(2); pz = pz.replace(',', '.'); pz = parseFloat(pz).toFixed(2); kg = kg.replace(',', '.'); kg = parseFloat(kg).toFixed(2); var pr = parseFloat(qta * pz).toFixed(2); if(qVar=="1") pr = parseFloat(qta * kg / 1000).toFixed(2); /*return "€ "+pr.toFixed(2).toString().replace('.', ',');*/ if(pId!=''){ if(pCon==0){ var prezzo = pr; //var sconto = (prezzo*parseInt(pSco,10)/100).toFixed(2); var sconto = (prezzo*parseFloat(pScoF)/100); prezzo = (prezzo - sconto).toFixed(2); //return '€ '+prezzo.replace('.',',')+'   € '+pr.replace('.', ',')+''; return {'prezzo':'€ '+prezzo.replace('.',',')+'   ','tagliato':'€ '+pr.replace('.', ',')}; }else{ //return '€ '+pr.replace('.', ','); return {'prezzo':'€ '+pr.replace('.',','),'tagliato':''}; } }else{ //return '€ '+pr.replace('.', ','); return {'prezzo':'€ '+pr.replace('.',','),'tagliato':''}; } }; // ************* !Prodotto ************* // ************* Pageing ************* function pageingClass(obj,div,rxp,nr){ this.oObj = obj; this.currPage = 0; this.numPages = Math.ceil(nr/rxp)-1; this.rxp = rxp; this.box = document.getElementById(div); this.box.innerHTML = '
      '; this.box = this.box.firstChild; this.prev = document.createElement('LI'); this.prev.innerHTML = ''; this.prev.className = "disabled"; this.box.appendChild(this.prev); this.prev.firstChild.onclick = this.indietro.bind(this); this.pages = []; for(var i=0; i<=this.numPages;i++){ var ele = document.createElement('LI'); if(i==this.currPage) ele.className = "active"; ele.innerHTML =''; this.box.appendChild(ele); this.pages.push(ele); ele.firstChild.onclick = this.vai.bind(this,i); } //'
    • 1
    • this.next = document.createElement('LI'); this.next.innerHTML = ''; this.box.appendChild(this.next); this.next.firstChild.onclick = this.avanti.bind(this); return this; }; pageingClass.prototype.indietro = function (){ if(this.currPage>0){ this.vai(this.currPage-1); } }; pageingClass.prototype.avanti = function (){ if(this.currPage