Regalamiunsorriso/rus/admin/_V4/_js/_ablia.js
2026-03-14 20:04:39 +01:00

3392 lines
94 KiB
JavaScript

/*ver. 6.1.3
13-12-2019 validateForm4 uguale al 3 ma gestiscefinalmente il form
29-09-2019 translateAll translateAllCR
25-09-2019 replaceAll
20-09-2019 changeAdminLang e triggerEvent PER IMPUTAJAX
10-07-2019 Ab.changeAdminLang
27-03-2019 corretto Ab.clrField
21-03-2019 aggiunto Ab.toDouble che mi teiene conto della stringa formattata 1.234,56
13-02-2019 corretto aggiornamento status msg
12-3-2018 postsubmitaj. messo tutto sotto document ready. spostato in cima lo show del tab altrimenti il focus poteva non funzionare!!!
5-03-2018 corretto gestione ckeditor con event listener
01-03-2018 aggiunto magnify su postSubmitAj
20-10-2017 cssSize
15-10-2017 confirmDelete4
06-09-2017 TOLTO postClickICheckCR E postClickICheck. ADESSO IL CLICK SUL CHECKBOX ESEGUE ONCHANGE SUL CHECK....
21-08-2017 getJsonFromForm e hasAttr per oggetti jquery
06-06-2017 corretto focusNext(
10-05-2017 disabledEventPropagation
27-4-2017
*/
var locale = "IT";
var helpWin;
var helpWinW;
var msgInterval;
var changingLang = false;
//**************** DETECT BROWSER **************************************************
//CS1.1
var exclude = 1;
var agt = navigator.userAgent.toLowerCase();
var win = 0;
var mac = 0;
var lin = 1;
if (agt.indexOf('win') != -1) {
win = 1;
lin = 0;
}
if (agt.indexOf('mac') != -1) {
mac = 1;
lin = 0;
}
var lnx = 0;
if (lin) {
lnx = 1;
}
var ice = 0;
var ie = 0;
var ie4 = 0;
var ie5 = 0;
var ie6 = 0;
var com = 0;
var dcm;
var ie7 = 0;
var ie8 = 0;
var op5 = 0;
var op6 = 0;
var op7 = 0;
var ns4 = 0;
var ns6 = 0;
var ns7 = 0;
var mz7 = 0;
var kde = 0;
var saf = 0;;
var chro = 0;
if (typeof navigator.vendor != "undefined" && navigator.vendor == "KDE") {
var thisKDE = agt;
var splitKDE = thisKDE.split("konqueror/");
var aKDE = splitKDE[1].split("; ");
var KDEn = beanPezza.loat(aKDE[0]);
if (KDEn >= 2.2) {
kde = 1;
ns6 = 1;
exclude = 0;
}
} else if (typeof navigator.vendor != "undefined" && navigator.vendor.indexOf('Google') != -1) {
chro = 1;
} else if (agt.indexOf('webtv') != -1) {
exclude = 1;
} else if (typeof window.opera != "undefined") {
exclude = 0;
if (/opera[\/ ][5]/.test(agt)) {
op5 = 1;
}
if (/opera[\/ ][6]/.test(agt)) {
op6 = 1;
}
if (/opera[\/ ][7-9]/.test(agt)) {
op7 = 1;
}
} else if (typeof document.all != "undefined" && !kde) {
exclude = 0;
ie = 1;
if (typeof document.getElementById != "undefined") {
ie5 = 1;
if (agt.indexOf("msie 6") != -1) {
ie6 = 1;
dcm = document.compatMode;
if (dcm != "BackCompat") {
com = 1;
}
}
if (agt.indexOf("msie 7") != -1) {
ie7 = 1;
dcm = document.compatMode;
if (dcm != "BackCompat") {
com = 1;
}
}
if (agt.indexOf("msie 8") != -1) {
ie8 = 1;
dcm = document.compatMode;
if (dcm != "BackCompat") {
com = 1;
}
}
} else {
ie4 = 1;
}
} else if (typeof document.getElementById != "undefined") {
exclude = 0;
if (agt.indexOf("netscape/6") != -1 || agt.indexOf("netscape6") != -1) {
ns6 = 1;
} else if (agt.indexOf("netscape/7") != -1 || agt.indexOf("netscape7") != -1) {
ns6 = 1;
ns7 = 1;
} else if (agt.indexOf("gecko") != -1) {
ns6 = 1;
mz7 = 1;
} else if (agt.indexOf("safari") != -1 || (typeof document.childNodes != "undefined" && typeof document.all == "undefined" && typeof navigator.taintEnabled == "undefined")) {
mz7 = 0;
ns6 = 1;
saf = 1;
}
} else if ((agt.indexOf('mozilla') != -1) && (parseInt(navigator.appVersion) >= 4)) {
exclude = 0;
ns4 = 1;
if (typeof navigator.mimeTypes['*'] == "undefined") {
exclude = 1;
ns4 = 0;
}
}
if (agt.indexOf('escape') != -1) {
exclude = 1;
ns4 = 0;
}
if (typeof navigator.__ice_version != "undefined") {
exclude = 1;
ie4 = 0;
}
//alert("ns44 "+ns4 +" ie5 "+ie5+" mozz "+mz7+" chro "+chro+" ie6"+ie6+" ie7"+ie7+" ie8"+ie8);
//********************************************************
//********************************************************
//********************************************************
//********************************************************
// S T A R T
//********************************************************
//********************************************************
//********************************************************
var Ab = {};
Ab.prototype = {
version: 6.0,
//coordinate x e y del mouse
coordx: 0,
coordy: 0
};
//********************************************************
//********************************************************
// P R I N T
//********************************************************
//********************************************************
//********************************************************
Ab.printW = function () {
window.print();
return true;
}
/////////////////////////////////////////////////////////
// controlli salvataggi e cancellazione /////////////////
/////////////////////////////////////////////////////////
Ab.confirmDelete = function () {
return confirm("I dati saranno cancellati. Vuoi continuare?");
}
Ab.confirmDelete4 = function (okDeleteProcess) {
var input = false,
retVal = false;;
swal({
title: "Cancellazione Record",
text: "I dati saranno cancellati. Vuoi continuare?",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "si",
cancelButtonText: "no",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
okDeleteProcess();
} else {
}
});
return retVal;
//return confirm("I dati saranno cancellati. Vuoi continuare?");
}
/////////////////////////////////////////////////////
// gestione preve e next nelle liste con paginazione
/////////////////////////////////////////////////////
//caso maschere di ricerca
Ab.prevPage = function () {
var f = document.main;
//richiamo anche un metodo che carica i checkBox e i checkRadio
if (typeof checkRadioCR == 'function')
checkRadioCR();
if (typeof checkBoxesCR == 'function')
checkBoxesCR();
f.action = f.actionPage.value;
f.cmd.value = "search";
f.flgReport.value = "";
f.pageNumber.value = f.pageNumber.value - 1;
f.target = "";
Ab.submitAj();
//f.submit();
}
Ab.nextPage = function () {
var f = document.main;
//richiamo anche un metodo che carica i checkBox e i checkRadio
if (typeof checkRadioCR == 'function')
checkRadioCR();
if (typeof checkBoxesCR == 'function')
checkBoxesCR();
f.action = f.actionPage.value;
f.cmd.value = "search";
f.flgReport.value = "";
f.pageNumber.value = eval(f.pageNumber.value) + 1;
f.target = "";
//alert(f.pageNumber.value);
//f.submit();
Ab.submitAj();
}
Ab.goPage = function (l_pageNumber) {
alert('verificare quando viene chiamata!!!');
//richiamo anche un metodo che carica i checkBox e i checkRadio
if (typeof checkRadioCR == 'function')
checkRadioCR();
if (typeof checkBoxesCR == 'function')
checkBoxesCR();
var f = document.main;
f.action = f.actionPage.value;
f.cmd.value = "search";
f.flgReport.value = "";
f.pageNumber.value = l_pageNumber;
f.target = "";
Ab.submitAj();
//f.submit();
}
Ab.goPage = function () {
//richiamo anche un metodo che carica i checkBox e i checkRadio
if (typeof checkRadioCR == 'function')
checkRadioCR();
if (typeof checkBoxesCR == 'function')
checkBoxesCR();
Ab.goPageMod(document.main);
}
Ab.goPage2 = function () {
//richiamo anche un metodo che carica i checkBox e i checkRadio
if (typeof checkRadioCR == 'function')
checkRadioCR();
if (typeof checkBoxesCR == 'function')
checkBoxesCR();
Ab.goPageMod2(document.main);
}
Ab.goPageMod = function (f) { //var f = document.main;
var page = 0;
$("input[name='pageNumberGo']").each(function (item) {
if ($(this).val() != "") {
page = $(this).val();
return;
}
});
if (parseFloat(page) <= parseFloat(f.totPageNumber.value)) {
f.action = f.actionPage.value;
f.cmd.value = "search";
f.pageNumber.value = page;
f.target = "";
Ab.submitAj(f.name);
//f.submit();
} else
alert('Errore!!');
}
Ab.goPageMod2 = function (f) {
//var f = document.main;
if (parseFloat(f.pageNumberGo2.value) <= parseFloat(f.totPageNumber.value)) {
f.action = f.actionPage.value;
f.cmd.value = "search";
f.pageNumber.value = f.pageNumberGo2.value;
f.target = "";
Ab.submitAj(f.name);
//f.submit();
} else
alert('Errore!!');
}
//caso finestre secondarie di ricerca
Ab.prevPageSW = function () {
var f = document.main;
f.act.value = "sw";
prevPage();
}
Ab.nextPageSW = function () {
var f = document.main;
f.act.value = "sw";
nextPage();
}
Ab.goPageSW = function (l_pageNumber) {
var f = document.main;
f.action = f.actionPage.value;
f.act.value = "sw";
goPage(l_pageNumber);
}
//caso maschere di dettaglio per liste secondarie
Ab.prevPageDetail = function (searchType) {
var f = document.main;
f.action = f.actionPage.value;
f.cmd.value = "md";
f.act.value = searchType;
var pn;
if (typeof searchType == "undefined") {
pn = Ab.prendiElementoDaId("pageNumber");
} else
pn = Ab.prendiElementoDaId("pageNumber_" + searchType);
pn.value = eval(pn.value) - 1;
Ab.submitAj();
}
Ab.nextPageDetail = function (searchType) {
var f = document.main;
f.action = f.actionPage.value;
f.cmd.value = "md";
f.act.value = searchType;
var pn;
if (!searchType) {
pn = Ab.prendiElementoDaId("pageNumber");
} else {
pn = Ab.prendiElementoDaId("pageNumber_" + searchType);
}
console.log(searchType);
console.log(pn.value);
pn.value = eval(pn.value) + 1;
Ab.submitAj();
}
Ab.goPageDetail = function (searchType) {
var f = document.main;
f.action = f.actionPage.value;
f.cmd.value = "md";
if (typeof searchType == "undefined") {
var pn = Ab.prendiElementoDaId("pageNumber");
var pnN = Ab.prendiElementoDaId("pageNumberGo");
var totPage = Ab.prendiElementoDaId("totPageNumber");
} else {
var pn = Ab.prendiElementoDaId("pageNumber_" + searchType);
var pnN = Ab.prendiElementoDaId("pageNumberGo_" + searchType);
var totPage = Ab.prendiElementoDaId("totPageNumber_" + searchType);
}
if (parseFloat(pnN.value) <= parseFloat(totPage.value)) {
pn.value = pnN.value;
Ab.submitAj();
} else {
alert('Errore!!');
}
}
Ab.goPageDetail2 = function (searchType) {
var f = document.main;
f.action = f.actionPage.value;
f.cmd.value = "md";
if (typeof searchType == "undefined") {
var pn = Ab.prendiElementoDaId("pageNumber");
var pnN = Ab.prendiElementoDaId("pageNumberGo2");
var totPage = Ab.prendiElementoDaId("totPageNumber");
} else {
var pn = Ab.prendiElementoDaId("pageNumber_" + searchType);
var pnN = Ab.prendiElementoDaId("pageNumberGo2_" + searchType);
var totPage = Ab.prendiElementoDaId("totPageNumber_" + searchType);
}
if (parseFloat(pnN.value) <= parseFloat(totPage.value)) {
pn.value = pnN.value;
Ab.submitAj();
} else {
alert('Errore!!');
}
}
///////////////////////////////////////////////
///////////////////////////////////////////////
Ab.popUp = function (menuName, left, top) {
///////////////////////////////////////////////
///////////////////////////////////////////////
toleft = typeof left;
totop = typeof top;
if (ns4 == 1) {
screenWidth = window.innerWidth;
if (left != 0 && toleft != "undefined") {
// document.layers[menuName].left = left;
}
if (top != 0 && totop != "undefined") {
//document.layers[menuName].top = top;
}
// alert(document.layers[menuName].visibility );
document.layers[menuName].visibility = "show";
//alert(document.layers[menuName].visibility );
} else {
screenWidth = document.body.clientWidth;
if (left != 0 && toleft != "undefined") { //alert('l='+left);
document.getElementById(menuName).style.pixelLeft = left;
}
if (top != 0 && totop != "undefined") { //alert('pio2');
document.getElementById(menuName).style.pixelTop = top;
}
document.getElementById(menuName).style.visibility = "visible";
}
//registrazione di current tab
// if ((ct=findObj('currentTab'))!=null)
// {
// ct.value=menuName;
//alert(menuName);
// }
}
Ab.popDown = function (menuName) {
if (ns4) {
document.layers[menuName].visibility = "hide";
} else {
//alert("down"+document.getElementById(menuName).style.visibility);
document.getElementById(menuName).style.visibility = "hidden";
}
}
//////////////////////////////////////////////
//determinazione delle coordinate del mouse
//////////////////////////////////////////////
grabXY = function (ev) {
if (ns4 || mz7 || chro) {
Ab.coordx = ev.pageX;
Ab.coordy = ev.pageY
} else {
Ab.coordx = event.clientX;
Ab.coordy = event.clientY;
}
}
Ab.motionListener = function () {
if (ns4 || mz7 || chro) {
window.addEventListener(Event.MOUSEMOVE, grabXY, true);
//window.onmousemove = grabXY;
} else {
// document.attachEvent(Event.MOUSEMOVE, modifyText);
document.onmousemove = grabXY;
}
}
//non mi ricordo a che serve questa roba
Ab.motionListener();
Ab.openWin = function (URL) {
aWindow = window.open(URL, "listwindow", "resizable=yes,scrollbars=yes,status=0,width=200,height=100");
}
Ab.newWindow = function (mypage, myname, w, h, scroll) {
var winl = (screen.width - w) / 2;
var wint = (screen.height - h) / 2;
winprops = 'height=' + h + ',width=' + w + ',top=' + wint + ',left=' + winl + ',scrollbars=' + scroll + ',resizable';
//alert (mypage+" "+myname+" "+ winprops);
win = window.open(mypage, myname, winprops);
if (parseInt(navigator.appVersion) >= 4) {
win.window.focus();
}
}
/////////////////////////////////////////7
/////////////////////////////////////////7
Ab.leftCenter = function (menuName)
/////////////////////////////////////////7
/////////////////////////////////////////7
{
left = 0;
if (ns4 || mz7 || chro) {
screenWidth = window.innerWidth;
//alert('ns mnuname'+menuName);
layerWidth = parseInt(document.layers[menuName].clip.width);
//alert('dopowidth');
} else {
screenWidth = document.body.clientWidth;
layerWidth = parseInt(document.getElementById(menuName).style.width);
}
// alert('lw='+layerWidth);
// alert(screenWidth);
// alert('left='+left);
left = (screenWidth - layerWidth) / 2;
if (left <= 0) {
//alert('left;'+left);
left = 1;
}
return left;
}
//////////////////////////////////////////////////////////
/// valida form //////////////////////////////////////////
/////////////////////////////////////////////////////////
Ab.findObj = function (n, d) { //v3.0
var p, i, x;
if (!d)
d = document;
if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
d = parent.frames[n.substring(p + 1)].document;
n = n.substring(0, p);
}
if (!(x = d[n]) && d.all)
x = d.all[n];
for (i = 0; !x && i < d.forms.length; i++)
x = d.forms[i][n];
for (i = 0; !x && d.layers && i < d.layers.length; i++)
x = Ab.findObj(n, d.layers[i].document);
return x;
}
Ab.validateForm2 = function () { //v3.0
//R per required
//isNum per numerico
//isNumKey una chiave.. uguale a isNum>0 ma cambio il messaggio
//isNum>x per numerico maggiore di x
//isNum<x per numerico minore di x
//isEmail per indirizzo email
//inRange1:10 per ..
//3 stringhe
//1: nome del field
//2: se '' visualizza il nome del field, altrimenti questo campo
//3: R/N+''/isNum/isEmail/inRangea:b
//
//esempi
// validateForm2('nomeform,'textfield','','R','textfield2','','NisNum','textfield3','','NisEmail','textfield4','','RinRange2:10')
//
var i, p, q, nm, nf, desc, test, testN, num, min, max, errors = '',
args = Ab.validateForm2.arguments;
nf = args[0];
nomeForm=args[0];
var setfoc = "";
//alert('forms'+nf);
for (i = 1; i < (args.length - 2); i += 3) {
test = args[i + 2];
//val= $("#"+nomeForm+" #"+args[i]);
//alert(val);
val = Ab.findObj(args[i]);
//val=document[nf][args[i]];
if (args[i + 1] == "")
desc = val.name;
else
desc = args[i + 1];
if (val) {
nm = val.name;
if ((val = val.value) != "") {
if (test.indexOf('isEmail') != -1) {
p = val.indexOf('@');
if (p < 1 || p == (val.length - 1)) {
errors += '- ' + desc + ' non un indirizzo valido.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
} else if (test != 'R') {
//alert(val);
if (locale == "IT") {
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(',', '.');
//tolgo gli zeri finali
var dotIdx = val.indexOf('.');
//alert("dotidx0"+dotIdx);
if (dotIdx != -1) {
var j = val.length - 1;
/* while(val.charAt(i)!='.' && val.charAt(i)=='0' ) NON FUNZIONA.. forse perche' usavo i invece di j!!*/
while (val.charAt(j) != '.') {
//alert("j="+j+" val charat(j):"+val.charAt(j));
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else j = dotIdx;
}
if (val.charAt(val.length - 1) == '.')
val = val.substr(0, val.length - 1);
}
} else if (locale == "US" || locale == "UK") {
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace('.', ',');
//tolgo gli zeri finali
var dotIdx = val.indexOf(',');
if (dotIdx != -1) {
var j = val.length - 1;
while (val.charAt(j) != ',') {
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else
j = dotIdx;
}
if (val.charAt(val.length - 1) == ',')
val = val.substr(0, val.length - 1);
}
//alert("US:"+val);
}
//da correggere il caso 33,40 Non mi accetta lo 0 finale!!!'
num = parseFloat(val);
//alert('num:'+num);
// if (val!=''+num && val!=''+num +'0'&& val!=''+num +'00'&& val!=''+num +'000' ) errors+='- '+desc+' non numerico.\n';
if (val != '' + num) {
errors += '- ' + desc + ' non numerico.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
if (test.search(/[><]/) != -1) {
if (test.charAt(0) == 'R') {
testN = test.substring(7, test.length);
} else {
testN = test.substring(6, test.length);
}
//alert('test:'+test+' tn: '+testN+" num: "+num +" pftn: "+parseFloat(testN));
if (test.indexOf('>') != -1 && num <= parseFloat(testN)) {
errors += '- ' + desc + ' <= ' + testN + '.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
if (test.indexOf('<') != -1 && num >= parseFloat(testN)) {
errors += '- ' + desc + ' >= ' + testN + '.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
}
//alert('test:'+test+' tn: '+testN);
if (test.indexOf('isNumKey') != -1) {
if (num <= 0) {
errors += '- ' + desc + ' obbligatorio.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
}
if (test.indexOf('inRange') != -1) {
p = test.indexOf(':');
min = test.substring(8, p);
max = test.substring(p + 1);
if (num < min || max < num) {
errors += '- ' + desc + ' deve essere un numero tra ' + min + ' e ' + max + '.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
}
}
} else if (test.charAt(0) == 'R') {
errors += '- ' + desc + ' obbligatorio.\n';
//alert(i + " - " + errors);
if (setfoc === "") {
setfoc = args[i];
}
}
}
}
if (errors) alert('Il form contiene i seguenti errori:\n' + errors);
if (setfoc !== "") {
//alert(setfoc);
Ab.setFocus(setfoc);
}
return (errors == '');
}
Ab.validateForm = function () { //v3.0 23/07/2002
//R per required
//isNum per numerico
//isNumKey una chiave.. uguale a isNum>0 ma cambio il messaggio
//isNum>x per numerico maggiore di x
//isNum<x per numerico minore di x
//isEmail per indirizzo email
//inRange1:10 per ..
//3 stringhe
//1: nome del field
//2: se '' visualizza il nome del field, altrimenti questo campo
//3: R/N+''/isNum/isEmail/inRangea:b
//
//esempi
// validateForm('textfield','','R','textfield2','','NisNum','textfield3','','NisEmail','textfield4','','RinRange2:10')
//
var i, p, q, nm, desc, test, testN, num, min, max, errors = '',
args = Ab.validateForm.arguments;
/*
var out = '';
for (var i in args) {
out += i + ": " + args[i] + "\n";
}
alert(out);
*/
var setfoc = "";
for (i = 0; i < (args.length - 2); i += 3) {
test = args[i + 2];
val = Ab.findObj(args[i]);
if (args[i + 1] == "")
desc = val.name;
else
desc = args[i + 1];
if (val) {
nm = val.name;
if ((val = val.value) != "") {
if (test.indexOf('isEmail') != -1) {
p = val.indexOf('@');
if (p < 1 || p == (val.length - 1)) {
errors += '- ' + desc + ' non un indirizzo valido.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
} else if (test != 'R') {
//alert(val);
if (locale == "IT") {
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(',', '.');
//tolgo gli zeri finali
var dotIdx = val.indexOf('.');
//alert("dotidx0"+dotIdx);
if (dotIdx != -1) {
var j = val.length - 1;
/* while(val.charAt(i)!='.' && val.charAt(i)=='0' ) NON FUNZIONA.. forse perche' usavo i invece di j!!*/
while (val.charAt(j) != '.') {
//alert("j="+j+" val charat(j):"+val.charAt(j));
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else j = dotIdx;
}
if (val.charAt(val.length - 1) == '.')
val = val.substr(0, val.length - 1);
}
} else if (locale == "US" || locale == "UK") {
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace('.', ',');
//tolgo gli zeri finali
var dotIdx = val.indexOf(',');
if (dotIdx != -1) {
var j = val.length - 1;
while (val.charAt(j) != ',') {
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else
j = dotIdx;
}
if (val.charAt(val.length - 1) == ',')
val = val.substr(0, val.length - 1);
}
//alert("US:"+val);
}
//da correggere il caso 33,40 Non mi accetta lo 0 finale!!!'
num = parseFloat(val);
//alert('num:'+num);
// if (val!=''+num && val!=''+num +'0'&& val!=''+num +'00'&& val!=''+num +'000' ) errors+='- '+desc+' non numerico.\n';
if (val != '' + num) {
errors += '- ' + desc + ' non numerico.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
if (test.search(/[><]/) != -1) {
if (test.charAt(0) == 'R') {
testN = test.substring(7, test.length);
} else {
testN = test.substring(6, test.length);
}
//alert('test:'+test+' tn: '+testN+" num: "+num +" pftn: "+parseFloat(testN));
if (test.indexOf('>') != -1 && num <= parseFloat(testN)) {
errors += '- ' + desc + ' <= ' + testN + '.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
if (test.indexOf('<') != -1 && num >= parseFloat(testN)) {
errors += '- ' + desc + ' >= ' + testN + '.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
}
if (test.indexOf('isNumKey') != -1) {
if (num <= 0) {
errors += '- ' + desc + ' obbligatorio.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
}
if (test.indexOf('inRange') != -1) {
p = test.indexOf(':');
min = test.substring(8, p);
max = test.substring(p + 1);
if (num < min || max < num) {
errors += '- ' + desc + ' deve essere un numero tra ' + min + ' e ' + max + '.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
}
}
} else if (test.charAt(0) == 'R') {
errors += '- ' + desc + ' obbligatorio.\n';
if (setfoc === "") {
setfoc = args[i];
}
}
}
}
if (errors) {
sweetAlert("Errore!", "Il form contiene i seguenti errori:\n" + errors, "error");
//('Il form contiene i seguenti errori:\n'+errors);
}
if (setfoc !== "") {
//alert(setfoc);
Ab.setFocus(setfoc);
}
return (errors == '');
}
//ckAll per combobox
Ab.checkAll = function (f, ckAll) {
for (var i = 0; i < f.elements.length; i++) {
var e = f.elements[i];
if (e.name != ckAll)
e.checked = f[ckAll].checked;
}
}
//////////////////////////////////
//funzioni di menu
//esempio
//Ab.callAbl('/admin/contab/Documento') //chiama search
//Ab.callAbl('/admin/contab/Documento',,,"id_tipologiaDocumento=210)
//////////////////////////////////
Ab.callAbl = function (theSvlt, theCmd, theAct, theValues) {
var f = document.menu;
//default
var cmd = "search";
var act = "";
if (theCmd != null)
cmd = theCmd;
if (theAct != null)
act = theAct;
if (theSvlt.charAt(0) == "/") { //path assoluto
theSvlt = webApp + theSvlt;
}
if (theValues) {
f.action = theSvlt + ".abl?" + theValues;
} else {
f.action = theSvlt + ".abl";
}
//alert(f.action);
f.cmd.value = cmd;
f.act.value = act;
//f.submit();
Ab.submitAj("menu");
}
Ab.closeWindow = function () {
if (confirm("Vuoi chiudere la finestra? (il record NON sar aggiornato)"))
window.close();
}
Ab.getVal = function (field) {
var val = Ab.findObj(field);
if (val)
val = val.value;
else
val = "";
return val;
}
////////////////////////////////
//change language
////////////////////////////////
Ab.lang = function (code) {
var hrf = location.href;
//alert (hrf);
var f = document.menu;
f.action = "Lang.abl";
f.hrf.value = hrf;
f.lang.value = code;
f.submit();
}
////////////////////////////////
//clrfield (pulisce l'elenco dei campi passati come parametri
////////////////////////////////
Ab.clrField = function () {
var args = Ab.clrField.arguments;
var f = document[args[0]];
var length = args.length;
///che senso ha questo???
//if(args.length % 2 == 0)
//{
// length = length - 1;
//}
for (i = 1; i < (length); i++) {
if ($("#" + args[i]).length) {
//esiste
if ($("#" + args[i]).is("checkbox")) {
$("#" + args[i]).attr('checked', 'checked')
} else {
$("#" + args[i]).val("");
}
}
}
// se c'è un primo campo (penso ci sia sempre) ci metto il focus
if (args[2].length > 0) {
//$('#'+args[1]).select();
//$('#'+args[1]).focus();
Ab.setFocus(args[2]);
//alert(args[1].length + " " + args[1]);
}
//eventuale script alla fine
if (args.length % 2 == 0) {
Ab.executeProcess(args[length], "");
}
}
Ab.clrFieldOld = function () {
var args = Ab.clrField.arguments;
var f = document[args[0]];
var length = args.length;
///che senso ha questo???
//if(args.length % 2 == 0)
//{
// length = length - 1;
//}
for (i = 1; i < (length); i++) {
if ($("#" + args[i]).length) {
if (f[args[i]].type == "checkbox") {
f[args[i]].checked = false;
} else {
f[args[i]].value = "";
}
}
}
// se c'è un primo campo (penso ci sia sempre) ci metto il focus
if (args[2].length > 0) {
//$('#'+args[1]).select();
//$('#'+args[1]).focus();
Ab.setFocus(args[2]);
//alert(args[1].length + " " + args[1]);
}
if (args.length % 2 == 0) {
Ab.executeProcess(args[length], "");
}
}
//////////////////////////////////////////
// SCELTA AUTOMATICA LINGUA DEL BROWSER
//////////////////////////////////////////
Ab.getBrowserLang = function () {
var lang;
if (typeof navigator.userLanguage != "undefined") {
lang = navigator.userLanguage.toLowerCase();
} else if (typeof navigator.language != "undefined") {
lang = navigator.language.toLowerCase();
} else {
lang = locale.toLowerCase;
}
if (lang.length > 2)
lang = lang.substring(0, 2);
return lang;
}
////////////////////////////////////////////////////////////////////////////////////////////
// REDIRET LANG
/*
funzione per fare il redirect della stessa pagina ma con la lingua del browser.
Subito dopo function.js iserire
<form name="langForm"><input name="hrf" type="hidden" /><input name="lang" type="hidden" value="<%=lang%>" /></form><script language="JavaScript1.2" >if(document.langForm.lang.value=="")redirectLang();</script>
*/
///////////////////////////////////////////////////////////////////////////////////////////
Ab.redirectLang = function () {
code = getBrowserLang();
var hrf = location.href;
//alert (hrf);
var f = document.langForm;
f.action = "Lang.abl";
f.hrf.value = hrf;
//devo verificare il parametro lang....
//se non sepcificato scelgo inglese
//alert("redlang "+code);
//##############################
// QUESTA PARTE POTREBBE VARIARE A SECONDA DELLE LINGUE SUPPORTATE DAL SITO
//##################################################
if (code == "" || code == "it" || code == "en")
f.lang.value = code;
else
f.lang.value = "en";
f.submit();
}
//////////////////////////////////////////////////////
// GESTIONE ELEMENTI DEI FORM
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// radio button
//////////////////////////////////////////////////////
Ab.setRadioButtonValue = function (formName, flgName) {
//imposta un campo hidden di none flgName al valore del radio button 'rb'+flgname selezionato
//es: setRadioButtonValue("dettaglio","flgPlaAntPos");
//var f = document.form[formName];
var f = document.getElementById(formName);
var flag = document.getElementById(flgName);
if (flag != null) {
var radioGrp = f['rb' + flgName];
//var radioGrp=document.getElementById('rb'+flgName);
flag.value = "";
for (var i = 0; i < radioGrp.length; i++) {
if (radioGrp[i].checked) {
flag.value = radioGrp[i].value;
break;
}
}
}
}
//////////////////////////////////////////////////////
// CHECK BOX
//////////////////////////////////////////////////////
Ab.setChekBoxValue = function (formName, flgName, ckValue, unckValue) {
//imposta un campo hidden di none flgName al valore del ckValue se checked, unckValue se unchecked
//es: setChekBoxValue("dettaglio","flgSommaCRL","1","0");
//var f = document.form[formName];
var f = document.getElementById(formName);
//alert('flgName: '+flgName);
var flag = document.getElementById(flgName);
if (flag != null) {
//var ckbox=f['ck'+flgName];
var ckbox = document.getElementById('ck' + flgName);
if (ckbox != null) {
if (ckbox.checked) flag.value = ckValue;
else flag.value = unckValue;
}
}
}
/////////////////////////////////////////////////
// GESTIONE FORM INSERIMENTO PER AUTOMATISMI
//
// UTILIZZARE SU CAMPI
// onFocus="this.select();" onKeyDown="focusNextOnCr(event,'XXXXX');" onKeyUp="return focusNext(this,event,'XXXX',NN);"
// SE ICLUSO ANCHE dateInput.js
// PER I CAMPI DATA
//// onFocus="this.select();" onChange="checkDate(this);printDate(this,'giorno')" onKeyDown="if(event.keyCode==13) {focusNextOnCr(event,'XXXXX');} else {formatDate(this, window.event.keyCode,'down')}" onKeyUp="formatDate(this, window.event.keyCode,'up');focusNext(this,event,'XXXX',10);"
// PER I CAMPI TIME
// onFocus="this.select();" onChange="" onKeyDown="if(event.keyCode==13) {focusNextOnCr(event,'XXXX');} else {formatTime(this, window.event.keyCode,'down')}" onKeyUp="formatTime(this, window.event.keyCode,'up');focusNext(this,event,'XXX',5);"
/////////////////////////////////////////////////
Ab.focusNextOnCr = function (e, nextField) {
var field = e.target.id;
//F1==112
//ctrlKey
//shiftKey
//altKey
//utlilizzare
//onKeyDown="focusNextOnCr(event,nextField);"
var keyCode = e.keyCode;
//alert(e.shiftKey+" "+e.ctrlKey+" "+e.altKey+" "+keyCode);
if (keyCode == 13) {
if (nextField == "") {
Ab.rendiNextField(this);
} else {
document.getElementById(nextField).focus();
}
}
//else if(keyCode>=112 && keyCode<=124)
else if ((e.altKey && keyCode == 112) || keyCode == 112) {
e.preventDefault();
var value = $('[nextField="' + field + '"]').val();
//console.dir(value);
if ($('[nextField="' + field + '"]').val() != undefined) {
$('[nextField="' + field + '"]').focus();
} else {
var prev = Ab.rendiPrevField(field);
$('[name="' + prev + '"]').focus();
}
}
}
/////////////////////////////////////////////////
/////////////////////////////////////////////////
// mi va al next field se la lunghezza=len
//mettere su onkeyup !!!
/////////////////////////////////////////////////
/////////////////////////////////////////////////
Ab.focusNext = function (input, e, nextField, len) {
//utilizzare onKeyUp="return focusNext(this,event,'field',nn);
//var keyCode = (isNN) ? e.which : e.keyCode;
// var filter = (isNN) ? [0,8,9] : [0,8,9,16,17,18,37,38,39,40,46];
var keyCode = e.keyCode;
var filter = [0, 8, 9, 16, 17, 18, 37, 38, 39, 40, 46];
var f = document.main;
//if(event.keyCode==13) {document.getElementById('codiceTS').focus();
if (keyCode != 13 && input.value.length >= len && !containsElement(filter, keyCode)) {
input.value = input.value.slice(0, len);
//elemento successivo
//input.form[(getIndex(input)+1) % input.form.length].focus();
document.getElementById(nextField).focus()
}
function containsElement(arr, ele) {
var found = false,
index = 0;
while (!found && index < arr.length)
if (arr[index] == ele)
found = true;
else
index++;
return found;
}
function getIndex(input) {
var index = -1,
i = 0,
found = false;
while (i < input.form.length && index == -1)
if (input.form[i] == input) index = i;
else i++;
return index;
}
return true;
}
//////////////////////////////////////
//funzioni trim stringa
//////////////////////////////////////
Ab.leftTrim = function (stringa) {
while (stringa.substring(0, 1) == ' ') {
stringa = stringa.substring(1, stringa.length);
}
return stringa;
}
Ab.rightTrim = function (stringa) {
while (stringa.substring(stringa.length - 1, stringa.length) == ' ') {
stringa = stringa.substring(0, stringa.length - 1);
}
return stringa;
}
Ab.trim = function (stringa) {
while (stringa.substring(0, 1) == ' ') {
stringa = stringa.substring(1, stringa.length);
}
while (stringa.substring(stringa.length - 1, stringa.length) == ' ') {
stringa = stringa.substring(0, stringa.length - 1);
}
return stringa;
}
//////////////////////////////////////////////////
//// focus
//////////////////////////////////////////////////
Ab.setFocus = function (theField) {
//alert(theField);
if ($("#" + theField)) {
$("#" + theField).select();
$("#" + theField).focus();
}
//document.getElementById(theField).focus();
//if(document.getElementById(theField).type!='select-one')
// document.getElementById(theField).select();
}
//////////////////////////////////////////////////
// funzione per prendere un elemento con id univoco
// con jquery è praticamente inutile
//////////////////////////////////////////////////
Ab.prendiElementoDaId = function (id_elemento) {
//alert('deprecata');
var elemento;
if (document.getElementById)
elemento = document.getElementById(id_elemento);
else
elemento = document.all[id_elemento];
return elemento;
}
Ab.getValId = function (id_elemento) {
return Ab.prendiElementoDaId(id_elemento).value;
}
////////////////////////////////////////////////////////
// lancio l'help
////////////////////////////////////////////////////////
Ab.help = function (cod) {
if (cod == null) {
cod = Ab.getValId("actionPage");
cod = cod.substring(0, cod.length - 4);
//alert(document.main)
if ($('#pageType').val() == 'R')
cod = cod + "_CR";
//alert(cod);
}
//theAction=webApp+"/admin/help/v/H.abl?cmd=view&cod="+cod;
theMainHelpPage = webApp + "/admin/help/v/index.jsp?cod=" + cod;
//debug
//helpWin=window.open(theMainHelpPage);
//NO DEBUG
helpWin = window.open(theMainHelpPage, "HELP", "width=1020,height=700,status=yes,resizable=yes,top=0,left=0,scrollbars=yes");
//helpWin=dhtmlwindow.open('helpBox', 'ajax', 'external.htm', 'Help - '+id, 'width=650px,height=400px,left=300px,top=100px,resize=0,scrolling=1');
}
Ab.helpW = function (titolo, pagina, ww, hh) {
//help del bean definito da actionPage
//alert(tableName);
helpWinW = dhtmlwindow.open('helpBox', 'ajax', pagina, 'Help - ' + titolo, 'width=' + ww + 'px,height=' + hh + 'px,left=300px,top=100px,resize=1,scrolling=1');
}
Ab.closeHW = function () {
if (typeof (helpWinW) != "undefined")
helpWinW.close();
else {
window.close();
}
}
////////////////////////////////////////////////////////
// build sitemat è in tutte le servlet
////////////////////////////////////////////////////////
Ab.buildSitemap = function () {
if (confirm("Vuoi creare la sitemap?")) {
var f = document.main;
f.action = f.actionPage.value;
f.fileName.value = prompt("Inserisci nome file (vuoto per nome file default)", f.fileName.value);
//alert('pio_'+f.eMail.value);
if (f.fileName.value != 'null') {
//popUp("ELAB");
f.cmd.value = "buildSM";
f.submit();
}
}
}
////////////////////////////////////////////////////////////////////////
// executeFunctionByName
////////////////////////////////////////////////////////////////////////
Ab.executeFunctionByName = function (functionName, context, args) {
//var args = Array.prototype.slice.call(arguments).splice(2);
var namespaces = functionName.split(".");
var func = namespaces.pop();
//luca
//var arg = args.split(',');
for (var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
//alert('Function: executeFunctionByName');
//alert(func + " - " + args);
// la call vuole i paramtri divisi da virgola come fosse una chiamata normale
return context[func].call(this, args);
//return context[func].apply(context, args);
// la apply vuole i parametri come vettore
//return context[func].apply(this, arg);
}
//////////////////////////////////////////////
//per aggiungere l'editor html all'elemento
////////////////////////////////////////////
/********************************************************/
/********** == validate form 2 + gestisce le lingue ***/
/********************************************************/
Ab.validateForm3 = function () { //v3.0
//R per required
//isNum per numerico
//isNumKey una chiave.. uguale a isNum>0 ma cambio il messaggio
//isNum>x per numerico maggiore di x
//isNum<x per numerico minore di x
//isEmail per indirizzo email
//inRange1:10 per ..
//3 stringhe
//1: nome del field
//2: se '' visualizza il nome del field, altrimenti questo campo
//3: R/N+''/isNum/isEmail/inRangea:b
//
//esempi
// validateForm3('en','nomeform,'textfield','','R','textfield2','','NisNum','textfield3','','NisEmail','textfield4','','RinRange2:10')
//
var i, p, q, nm, nf, lang, desc, test, testN, num, min, max, errors = '',
args = Ab.validateForm3.arguments;
//default
var langIdx = 0;
lang = args[0];
nomeForm=args[1];
//per aumentare le lingue....
if (lang == "en")
langIdx = 1;
nf = args[1];
//messaggi. Arrei in lingua. 1 italiano, 2 inglese
msg_mail = [" non un indirizzo valido.\n", " is not a valid email address.\n"];
msg_number = [" non numerico.\n", " is not a number.\n"];
msg_mand = [" obbligatorio.\n", " is a mandatory field.\n"];
msg_err = ["Il form contiene i seguenti errori:\n", "Errors founds on the form:\n"];
msg_errTitle = ["Errore!", "Error!"];
msg_betw = [" deve essere un numero tra ", " the number must be betwen "];
msg_betwAnd = [" e ", " and "];
for (i = 2; i < (args.length - 2); i += 3) {
test = args[i + 2];
//val= $("#"+nomeForm+" #"+args[i]);
//alert(val);
val = Ab.findObj(args[i]);
//val=document[nf][args[i]];
if (args[i + 1] == "")
desc = val.name;
else
desc = args[i + 1];
if (val) {
nm = val.name;
if ((val = val.value) != "") {
if (test.indexOf('isEmail') != -1) {
p = val.indexOf('@');
if (p < 1 || p == (val.length - 1)) errors += '- ' + desc + msg_mail[langIdx];
} else if (test != 'R') {
//alert(val);
if (locale == "IT") {
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(',', '.');
//tolgo gli zeri finali
var dotIdx = val.indexOf('.');
//alert("dotidx0"+dotIdx);
if (dotIdx != -1) {
var j = val.length - 1;
/* while(val.charAt(i)!='.' && val.charAt(i)=='0' ) NON FUNZIONA.. forse perche' usavo i invece di j!!*/
while (val.charAt(j) != '.') {
//alert("j="+j+" val charat(j):"+val.charAt(j));
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else j = dotIdx;
}
if (val.charAt(val.length - 1) == '.')
val = val.substr(0, val.length - 1);
}
} else if (locale == "US" || locale == "UK") {
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace('.', ',');
//tolgo gli zeri finali
var dotIdx = val.indexOf(',');
if (dotIdx != -1) {
var j = val.length - 1;
while (val.charAt(j) != ',') {
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else
j = dotIdx;
}
if (val.charAt(val.length - 1) == ',')
val = val.substr(0, val.length - 1);
}
//alert("US:"+val);
}
//da correggere il caso 33,40 Non mi accetta lo 0 finale!!!'
num = parseFloat(val);
//alert('num:'+num);
// if (val!=''+num && val!=''+num +'0'&& val!=''+num +'00'&& val!=''+num +'000' ) errors+='- '+desc+' non numerico.\n';
if (val != '' + num) errors += '- ' + desc + msg_number[langIdx];
if (test.search(/[><]/) != -1) {
if (test.charAt(0) == 'R') {
testN = test.substring(7, test.length);
} else {
testN = test.substring(6, test.length);
}
//alert('test:'+test+' tn: '+testN+" num: "+num +" pftn: "+parseFloat(testN));
if (test.indexOf('>') != -1 && num <= parseFloat(testN)) errors += '- ' + desc + ' <= ' + testN + '.\n';
if (test.indexOf('<') != -1 && num >= parseFloat(testN)) errors += '- ' + desc + ' >= ' + testN + '.\n';
}
//alert('test:'+test+' tn: '+testN);
if (test.indexOf('isNumKey') != -1) {
if (num <= 0) errors += '- ' + desc + msg_mand[langIdx];
}
if (test.indexOf('inRange') != -1) {
p = test.indexOf(':');
min = test.substring(8, p);
max = test.substring(p + 1);
if (num < min || max < num) errors += '- ' + desc + msg_betw[langIdx] + min + msg_betwAnd[langIdx]; + max + '.\n';
}
}
} else if (test.charAt(0) == 'R') errors += '- ' + desc + msg_mand[langIdx];
}
}
if (errors) {
sweetAlert(msg_errTitle[langIdx], msg_err[langIdx] + errors, "error");
}
return (errors == '');
}
/********************************************************/
/********** == validate form 4 che gestisce correttamente il parametro form ***/
/********************************************************/
Ab.validateForm4 = function () { //v3.0
//R per required
//isNum per numerico
//isNumKey una chiave.. uguale a isNum>0 ma cambio il messaggio
//isNum>x per numerico maggiore di x
//isNum<x per numerico minore di x
//isEmail per indirizzo email
//inRange1:10 per ..
//3 stringhe
//1: nome del field
//2: se '' visualizza il nome del field, altrimenti questo campo
//3: R/N+''/isNum/isEmail/inRangea:b
//
//esempi
// validateForm3('en','nomeform,'textfield','','R','textfield2','','NisNum','textfield3','','NisEmail','textfield4','','RinRange2:10')
//
var i, p, q, nm, nf, lang, desc, test, testN, num, min, max, errors = '',
args = Ab.validateForm4.arguments;
//default
var langIdx = 0;
lang = args[0];
nomeForm=args[1];
//per aumentare le lingue....
if (lang == "en")
langIdx = 1;
nf = args[1];
//messaggi. Arrei in lingua. 1 italiano, 2 inglese
msg_mail = [" non un indirizzo valido.\n", " is not a valid email address.\n"];
msg_number = [" non numerico.\n", " is not a number.\n"];
msg_mand = [" obbligatorio.\n", " is a mandatory field.\n"];
msg_err = ["Il form contiene i seguenti errori:\n", "Errors founds on the form:\n"];
msg_errTitle = ["Errore!", "Error!"];
msg_betw = [" deve essere un numero tra ", " the number must be betwen "];
msg_betwAnd = [" e ", " and "];
for (i = 2; i < (args.length - 2); i += 3) {
test = args[i + 2];
val= $("#"+nomeForm+" #"+args[i]);
//alert(val);
//val = Ab.findObj(args[i]);
//val=document[nf][args[i]];
if (args[i + 1] == "")
desc = val.name;
else
desc = args[i + 1];
if (val) {
nm = val.name;
if ((val = val.value) != "") {
if (test.indexOf('isEmail') != -1) {
p = val.indexOf('@');
if (p < 1 || p == (val.length - 1)) errors += '- ' + desc + msg_mail[langIdx];
} else if (test != 'R') {
//alert(val);
if (locale == "IT") {
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(/[.]/, '');
val = val.replace(',', '.');
//tolgo gli zeri finali
var dotIdx = val.indexOf('.');
//alert("dotidx0"+dotIdx);
if (dotIdx != -1) {
var j = val.length - 1;
/* while(val.charAt(i)!='.' && val.charAt(i)=='0' ) NON FUNZIONA.. forse perche' usavo i invece di j!!*/
while (val.charAt(j) != '.') {
//alert("j="+j+" val charat(j):"+val.charAt(j));
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else j = dotIdx;
}
if (val.charAt(val.length - 1) == '.')
val = val.substr(0, val.length - 1);
}
} else if (locale == "US" || locale == "UK") {
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace(/[,]/, '');
val = val.replace('.', ',');
//tolgo gli zeri finali
var dotIdx = val.indexOf(',');
if (dotIdx != -1) {
var j = val.length - 1;
while (val.charAt(j) != ',') {
if (val.charAt(j) == '0') {
val = val.substr(0, j);
j--;
} else
j = dotIdx;
}
if (val.charAt(val.length - 1) == ',')
val = val.substr(0, val.length - 1);
}
//alert("US:"+val);
}
//da correggere il caso 33,40 Non mi accetta lo 0 finale!!!'
num = parseFloat(val);
//alert('num:'+num);
// if (val!=''+num && val!=''+num +'0'&& val!=''+num +'00'&& val!=''+num +'000' ) errors+='- '+desc+' non numerico.\n';
if (val != '' + num) errors += '- ' + desc + msg_number[langIdx];
if (test.search(/[><]/) != -1) {
if (test.charAt(0) == 'R') {
testN = test.substring(7, test.length);
} else {
testN = test.substring(6, test.length);
}
//alert('test:'+test+' tn: '+testN+" num: "+num +" pftn: "+parseFloat(testN));
if (test.indexOf('>') != -1 && num <= parseFloat(testN)) errors += '- ' + desc + ' <= ' + testN + '.\n';
if (test.indexOf('<') != -1 && num >= parseFloat(testN)) errors += '- ' + desc + ' >= ' + testN + '.\n';
}
//alert('test:'+test+' tn: '+testN);
if (test.indexOf('isNumKey') != -1) {
if (num <= 0) errors += '- ' + desc + msg_mand[langIdx];
}
if (test.indexOf('inRange') != -1) {
p = test.indexOf(':');
min = test.substring(8, p);
max = test.substring(p + 1);
if (num < min || max < num) errors += '- ' + desc + msg_betw[langIdx] + min + msg_betwAnd[langIdx]; + max + '.\n';
}
}
} else if (test.charAt(0) == 'R') errors += '- ' + desc + msg_mand[langIdx];
}
}
if (errors) {
sweetAlert(msg_errTitle[langIdx], msg_err[langIdx] + errors, "error");
}
return (errors == '');
}
////////////////////////////////////////////////
// aggiusta i campi euro e "
/////////////////////////////////////////////
Ab.aggiustaInputText = function (campo) {
//var f = document.main;
campo.value = campo.value.replace(/\u20ac/g, "€");
campo.value = campo.value.replace("\"", "\'");
}
////////////////////////////////////////////////
//gestione submit per form dettaglio e ricerca
////////////////////////////////////////////////
Ab.submitForm = function (evt) {
if ($("#pageType").val() == "D") {
//dettaglio
saveCommand();
} else if ($("#pageType").val() == "R") {
//ricerca
searching();
}
}
////////////////////////////////////////////////
// utilizzata per il salvataggio di una pagina
// e riposizionamento sul campo successivo
// di solito con
// jsDateInputS
// jsTimeInputS
// jsNumberInputS
// jsCrS
//////////////////////////////////////////////////
Ab.saveNextFocus = function (evt, nextFocus) {
$("#currentFocus").val(nextFocus);
Ab.submitForm(evt);
}
////////////////////////////////
//rendiNextField(field,[num])
//restituisce il primo campo successivo a field
// oppure num campo successivo
////////////////////////////////
Ab.rendiNextField = function () {
var args = Ab.rendiNextField.arguments,
field = args[0],
num = 1,
name = "";
//console.dir(args);
//alert(args.length);
if (args.length == 2)
num = args[1];
//alert("num:"+num);
var allInputs = $("input[type=text],input[type=radio],input[type=checkbox], textarea, select").filter(":visible").filter(":not([readonly])");
var ret = "";
//alert("1:"+field.name);
//allInputs.each(function(item){
// if ($(item).attr("name") == field) {
// ret = allInputs[i + num].name;
// return;
// }
// });
len = allInputs.length;
for (var i = 0; i < len; i++) {
//console.log(allInputs[i].name);
if (allInputs[i].name == field) {
if (allInputs[i + num]) {
ret = allInputs[i + num].name;
break;
}
}
}
//alert("2:"+ret);
return ret;
}
////////////////////////////////
//rendiPrevField(field,[num])
//restituisce il primo campo precedente a field
// oppure num campo successivo
////////////////////////////////
Ab.rendiPrevField = function () {
var args = Ab.rendiPrevField.arguments,
field = args[0],
num = 1,
name = "";
//alert(args.length);
if (args.length == 2)
num = args[1];
var allInputs = $("input:visible, textarea:visible, select:visible");
var ret = "";
if (field.name != undefined) {
name = field.name;
} else {
name = $("#" + field).attr("name");
}
for (var i = allInputs.length - 1; i > 0; i--) {
if (allInputs[i].type != "hidden" && allInputs[i].type != "") {
if (allInputs[i].name == name) {
ret = allInputs[i - num].name;
break;
}
}
}
//alert("2:"+ret);
return ret;
}
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
// imposta il focus al camo successivo o al num campo successivo
// parametri setFocusNextField(field,[num])
////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////
Ab.setFocusNextField = function () {
$("#" + Ab.rendiNextField(Ab.setFocusNextField.arguments[0])).select();
$("#" + Ab.rendiNextField(Ab.setFocusNextField.arguments[0])).focus();
}
//////////////////////////////////////////////////////
// esegue una funzione che pu avere o meno i parametri
// quindi
// xxx()
// oppure
// xx(arg1,arg2,...)
//////////////////////////////////////////////////////
Ab.executeProcess = function (postProcess, ppArgs) {
if (postProcess != null) {
var idx1 = postProcess.indexOf("(");
var func = postProcess.substring(0, idx1);
//verifico se ci sono argomenti
//se ho argomenti uso quelli come parametri
//altrimenti eseguo la funziona passando
//il parametro successivo
var idx2 = postProcess.lastIndexOf(")");
if ((idx2 - idx1) == 1) {
//non ci sono parametri
if (ppArgs === undefined || ppArgs == null)
Ab.executeFunctionByName(func, window);
else
Ab.executeFunctionByName(func, window, ppArgs);
} else {
//ci sono parametri....
//alert('con parm');
var args = postProcess.substring(idx1 + 1, idx2);
//alert(func+" x"+args+"xx");
Ab.executeFunctionByName(func, window, args);
}
}
}
//////////////////////////////////////////////
//V. 4 LTE
// funzione che mi sottomette un form (di defaul sottomette il form main)
// e ricarica il div di default mainContent se non specificato altrimenti
//
//////////////////////////////////////////////
Ab.submitAj = function (form, target, postProcess, async, debug) {
if (debug) {
alert("aaa");
}
theForm = "main";
theTarget = "mainContent";
//form di default --> main
if (form != undefined && form != null) {
theForm = form;
}
if (debug) {
alert("bbb");
}
//target di deault --> mainContent
if (target != undefined && target != null) {
theTarget = target;
}
if (debug) {
alert("ccc");
}
//gestione async
//deve essere nella pagina che viene caricata e sostituita
if (async != undefined && async != null) {
$("#_async").val(async);
} else {
$("#_async").val("");
}
if (debug) {
alert("ddd");
}
if (!$("#" + theForm).attr("action") || $("#" + theForm).attr("action") == "") {
if (debug) {
alert("eee");
}
// se non è stato settato l'action sulla form provo a settarlo atuomaticamente dal campo actionPage
// (se esiste e se è compilato)
// altrimenti mando l'errore
/*
if ($("#actionPage", theForm) && $("#actionPage", theForm).val() != "")
{
$("#"+theForm).attr("action", $("#actionPage", theForm).val());
}
else
{
*/
alert("ERRORE! manca il campo actionPage!");
//}
} else {
if (debug) {
alert("fff");
}
//
//alert( $("#"+theForm).attr("action"));
//
$.ajax({
type: "POST",
url: $("#" + theForm).attr("action"),
data: $("#" + theForm).serialize(),
dataType: 'html',
cache: 'false',
success: function (response) {
$("#_async").val("");
/////////////////////
// var $frag=$(response);
// console.log( $frag.filter('form').get());
//
//carico il target
$("#" + theTarget).html(response);
if ($.AdminLTE) {
$.AdminLTE.layout.fix();
postSubmitAj();
}
//alert($("#pageTitle").val());
//postprocess
if (postProcess != undefined && postProcess != null) {
Ab.executeProcess(postProcess);
}
},
error: function (err) {
sweetAlert(err, 'error');
}
});
}
}
///////////////////////////////////////////////
//
///////////////////////////////////////////////
Ab.printPdf = function (titolo, pagina, ww, hh) {
var w = 500,
h = 400;
if (ww != null)
w = ww;
if (hh != null)
h = hh;
//
window.open(pagina, titolo, "width=" + w + ",height=" + h + ",status=yes,resizable=yes,top=0,left=0,scrollbars=yes");
//dhtmlwindow.open('Pdf print', 'iframe', pagina, ' '+titolo, 'width='+w+'px,height='+h+'px,left=300px,top=100px,resize=1,scrolling=1');
}
//////////////////////////////////////////////////////
// fetch
// chiama la servlet passandogli i comandi e ritorna un valore che viene inserito o nella divList
// oppure passato come parametro alla funzione postProcess
// DA TESTARE A FONDO...
//////////////////////////////////////////////////////
Ab.fetch = function (servlet, command, divList, postProcess, async, type) {
//gestione chiamate asincrone
if (async != undefined && async != null) {
$("#_async").val(async);
//imposto una immagine di attesa
$("#" + divList).html("<img src='" + webApp + "/admin/_V4/_img/attesa.gif' width='16' height='16'>");
//alert('pio');
} else {
$("#_async").val("");
}
if (async == undefined) {
async = true;
}
if (type == undefined) {
type = "html";
}
$.ajax({
type: "POST",
url: servlet,
data: command,
dataType: type,
async: async,
success: function (msg) {
$("#_async").val("");
if ("#" + divList != null) {
$("#" + divList).html(msg);
if (postProcess != null) {
Ab.executeProcess(postProcess, msg);
}
} else if (postProcess != null) {
Ab.executeProcess(postProcess, msg);
}
},
error: function () {
$("#" + divList).html("Chiamata fallita, si prega di riprovare...");
//alert("Chiamata fallita, si prega di riprovare...");
$("#_async").val("");
}
});
}
//////////////////////////////////////////////////////
// fetch
// chiama la servlet passandogli i comandi e ritorna un valore che viene inserito o nella divList
// oppure passato come parametro alla funzione postProcess
// DA TESTARE A FONDO...
//
// Versione 4.0
// Differisce dalla precedente per la chiamata alla funzione di postProcess (callback)
// in quanto dovendo passare soltanto la response della chiamata ajax si può far più facilmente con:
// if (postProcess && postProcess!=null)
// {
// postProcess(msg);
// }
//
// la chiamata alla funzione col postProcess va' fatta scrivendo il nome della funzione senza gli apici:
//
// Ab.fetch4(actionPage, "cmd=getPrezzoUnitario&id_clifor=" + id_clifor+"&flgTipoListino="+flgTipoListino, null,
// postCaricaPrezzoUnitario);
//Ab.fetch4("../menu/StatusMsg.abl", "cmd=aggiornaStatusMsg", "statusMsg",null,false)
//////////////////////////////////////////////////////
Ab.fetch4 = function (servlet, command, divList, postProcess, async, type) {
//gestione chiamate asincrone
if (async != undefined && async != null) {
$("#_async").val(async);
//console.log("fetch4 asynk:"+async);
if (async != 'hidden') {
//imposto una immagine di attesa
$("#" + divList).html("<img src='" + webApp + "/admin/_V4/_img/attesa.gif' width='16' height='16'>");
}
//alert('pio');
} else {
$("#_async").val("");
}
if (async == undefined) {
async = true;
}
if (type == undefined) {
type = "html";
}
$.ajax({
type: "POST",
url: servlet,
data: command,
dataType: type,
async: async,
success: function (msg) {
$("#_async").val("");
if ("#" + divList != null) {
//console.log("fetch4: risultato:--"+msg+"++");
if ($("#" + divList).html() != msg) {
//console.log("fetch4 aggiorno msg: ##"+msg+"## attuale: ##"+$("#"+divList).html()+"##");
$("#" + divList).html(msg);
}
}
if (postProcess && postProcess != null) {
postProcess(msg);
}
},
error: function () {
$("#" + divList).html("Chiamata fallita, si prega di riprovare...");
//alert("Chiamata fallita, si prega di riprovare...");
$("#_async").val("");
}
});
}
////////////////////////////////////////
// salva l'immagine tramite ajax
////////////////////////////////////////
Ab.saveImage = function (id, codImage) {
//grab all form data
// $('#cmd').val("loadImg");
//var formData = new FormData($('form#main')[0]);
//alert(document.getElementById("btn-upload_"+codImage));
var sampleFile = document.getElementById("btn-upload_" + codImage).files[0];
var oMyForm = new FormData();
//oMyForm.append("file", $('#imgFile_'+codImage).files[0]);
oMyForm.append("imgFile", sampleFile);
oMyForm.append("cmd", "loadImg");
oMyForm.append("totImgNumber", $("#totImgNumber").val());
oMyForm.append("codImage", codImage);
oMyForm.append("id", id);
// oMyForm.append("nomeOriginale",id);
//alert(sampleFile);
if (typeof sampleFile != "undefined") {
$("#imgNew_" + codImage).attr("src", "../_V4/_img/wait.gif");
var action = "";
if ($("#actionPage", "#main")) {
action = $("#actionPage", "#main").val();
} else {
action = $("#main").attr("action");
}
$.ajax({
url: action,
type: 'POST',
data: oMyForm,
chache: false,
async: true,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
//xhr: opt.progress,
beforeSend: function () {},
success: function (response) {
var result = $.parseJSON(response);
//
var messaggio = result[0].message;
$('#messaggi').html(messaggio);
if ($('#messaggi').length > 0 && $('#messaggi').html().length > 0) {
Ab.showMessage($('#messaggi').html());
}
if ($('#messaggi').length > 0)
msgInterval = setTimeout("$('#messaggi').fadeOut(200);msgGone=true", 10000);
Ab.showImgBtnArea(codImage);
$('#imgNew_' + codImage).attr("src", result[0].imgPath).load(function () {
this.width;
// Note: $(this).width() will not work for in memory images
});
},
error: function () {
$("#imgNew_" + codImage).attr("src", "../_V4/_img/placeHold.gif");
}
});
}
}
//////////////////////////////////////////
// cancella l'immagine annuncio tramite ajax
//////////////////////////////////////////
Ab.deleteImage = function (id, codImage) {
//grab all form data
// $('#cmd').val("loadImg");
//var formData = new FormData($('form#main')[0]);
//alert(document.getElementById("btn-upload_"+codImage));
var sampleFile = document.getElementById("btn-upload_" + codImage).files[0];
var oMyForm = new FormData();
//oMyForm.append("file", $('#imgFile_'+codImage).files[0]);
oMyForm.append("imgFile", sampleFile);
oMyForm.append("cmd", "removeImg");
oMyForm.append("codImage", codImage);
oMyForm.append("id", id);
oMyForm.append("totImgNumber", $("#totImgNumber").val());
//$("#imgNew_"+codImage).attr("src", "_img/wait.gif");
var action = "";
if ($("#actionPage", "#main")) {
action = $("#actionPage", "#main").val();
} else {
action = $("#main").attr("action");
}
$.ajax({
url: action,
type: 'POST',
data: oMyForm,
chache: false,
async: false,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
//xhr: opt.progress,
beforeSend: function () {},
success: function (response) {
var result = $.parseJSON(response);
//
var messaggio = result[0].message;
$('#messaggi').html(messaggio);
console.log("deleteimg: " + messaggio);
if ($('#messaggi').length > 0 && $('#messaggi').html().length > 0) {
Ab.showMessage($('#messaggi').html());
}
if ($('#messaggi').length > 0)
msgInterval = setTimeout("$('#messaggi').fadeOut(200);msgGone=true", 10000);
if (result[0].result == true) {
Ab.hideImgBtnArea(codImage);
$('#imgNew_' + codImage).attr("src", "../_V4/_img/placeHold.gif").load(function () {
this.width;
// Note: $(this).width() will not work for in memory images
});
}
},
error: function () {
}
});
}
/////////////////////////////////////////////////////
// chiama la servlet che restituisce l'immagine a dimensione
// reale. Utilizzo questa perchè il tmst potrebbe cambiare
// continuamente se ho una modifica
/////////////////////////////////////////////////////
Ab.showImage = function (id, codImage) {
var left = ($(window).width() / 2) - (900 / 2);
top = ($(window).height() / 2) - (600 / 2);
theServlet = $("#actionPage").val() + "?cmd=showImage&id=" + id + "&codImage=" + codImage;
popup = window.open(theServlet, "Immagine " + codImage, "width=900, height=600, top=" + top + ", left=" + left);
}
/////////////////////////////////////////////////////
// mostra la btn area nel caso di immagine presente
//durante la prima visualizzazione
/////////////////////////////////////////////////////
Ab.showImgBtnArea = function (codImage) {
$('#btn-area-div_' + codImage).show();
//alert('pio');
}
/////////////////////////////////////////////////////
// nasconde la btn area nel caso di immagine presente
//durante la prima visualizzazione
/////////////////////////////////////////////////////
Ab.hideImgBtnArea = function (codImage) {
$('#btn-area-div_' + codImage).hide();
}
/////////////////////////////////////////////////////
// rimuove il layout di fade che viene inserito
// quando si richiama una modal bootstrap
/////////////////////////////////////////////////////
Ab.removeFadeModal = function () {
if ($(".modal-backdrop").length > 0) {
$(".modal-backdrop").remove();
}
$("body").removeClass("modal-open");
}
//********************************************************
//********************************************************
// HOME SULLA BREADCUMB
//********************************************************
//********************************************************
Ab.dashboard = function () {
var f = document.main;
f.action = "_inc-menu.jsp";
f.cmd.value = "";
f.act.value = "";
Ab.submitAj();
}
//********************************************************
//********************************************************
// mostra messaggio toastr ( _V3)
//********************************************************
//********************************************************
tipoMessaggi = {};
tipoMessaggi = {
warn: "warning",
error: "error",
ok: "success",
info: "info"
}
Ab.showMessage = function (msg, title, block, typeClass) {
if (!typeClass) {
typeClass = tipoMessaggi.ok;
if (msg.toLowerCase().indexOf("error") >= 0) {
typeClass = tipoMessaggi.error;
}
if (msg.toLowerCase().indexOf("warning") >= 0 || msg.toLowerCase().indexOf("attenzione") >= 0) {
typeClass = tipoMessaggi.warn;
}
}
if (block) {
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": true,
"onclick": null,
"showDuration": "0",
"hideDuration": "0",
"timeOut": "0",
"extendedTimeOut": "0",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"tapToDismiss": false
}
} else {
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "3000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
}
toastr[typeClass](msg, title);
//toastr.info(msg);
}
//********************************************************
//********************************************************
// POST SUBMIT AJ. CIò CHE VIENE FATTO DOPO OGNI SUBMIT AJ
// SOLO NEL CASO IN CUI SIA NEL FRAMEWORK LTE
// MOOOOOOLTO IMPORTANTE!!!!!!
//********************************************************
//********************************************************
var postSubmitAj = function () {
$(document).ready(function () {
/////////////////////////////////////////////////////
//gestione tabs
/////////////////////////////////////////////////////
if ($('#currentTab') && $('#currentTab').val() != "")
$('#tabs a[href="' + $('#currentTab').val() + '"]').tab('show');
/////////////////////////////////////////////////////
//Initialize Select2 Elements
/////////////////////////////////////////////////////
//if($(".select2")){
// $(".select2").select2();
//
// }
//iCheck for checkbox and radio inputs
if ($('input[type="checkbox"].minimal, input[type="radio"].minimal')) {
$('input[type="checkbox"].minimal, input[type="radio"].minimal').iCheck({
checkboxClass: 'icheckbox_minimal-blue',
radioClass: 'iradio_minimal-blue',
focusClass: 'hover'
});
}
/////////////////////////////////////////////////////
//current focus
/////////////////////////////////////////////////////
//console.log($("#currentFocus").val());
if ($("#currentFocus") && $("#currentFocus").val() != "") {
//console.log("setfocus di currentfocus1");
Ab.setFocus($("#currentFocus").val());
//console.log("setfocus di currentfocus2");
} else {
//console.log("default focus "+$("[defaultFocus=focus]").attr("id"));
if ($("[defaultFocus=focus]")) {
if ($("[defaultFocus=focus]").hasClass("select2")) {
//$("[defaultFocus=focus]").select2('close');
$("[defaultFocus=focus]").focus();
} else
$("[defaultFocus=focus]").focus();
}
}
/////////////////////////////////////////////////////
//ricarico il titolo
/////////////////////////////////////////////////////
$(document).prop('title', $("#pageTitle").val());
$("#pageTitleContent").html($("#pageTitle").val());
$("#printTitleContent").html($("#pageTitle").val());
/////////////////////////////////////////////////////
//ricarico la sidebar se ho fatto il logon
/////////////////////////////////////////////////////
if ($("#logonRes").val() != "" && typeof ($("#logonRes").val()) != "undefined") {
//ricarico la pagina sidebar...
$('#sidebarContent').load('_inc-sidebar.jsp');
}
/////////////////////////////////////////////////////
//Initialize formattazione capi data, numerici, time, email, colore
//utlizza le classi datemask, numberinput, numberinput0, timemask, emailmask, colorpicker
/////////////////////////////////////////////////////
//Datemask dd/mm/yyyy
if ($(".datemask")) {
$(".datemask").inputmask("dd/mm/yyyy", {
"placeholder": "gg/mm/aaaa"
});
//$(".datemask").inputmask("dd/mm/yyyy", {"placeholder": "gg/mm/aaaa", "oncomplete": function(){ alert($(this).val()); } });
// $("#date").inputmask("d/m/y",{ "oncomplete": function(){ alert('inputmask complete'); } });
}
//numero con 2 decimali (default)
if ($(".numberinput")) {
$(".numberinput").numeric({
decimalPlaces: 2,
decimal: ","
});
}
//numero intero
if ($(".numberinput0")) {
$(".numberinput0").numeric();
}
//time
if ($(".timemask")) {
$(".timemask").inputmask("h:s", {
"placeholder": "hh:mm"
});
}
//email mask
if ($(".emailmask")) {
$(".emailmask").inputmask({
mask: "*{1,20}[.*{1,20}][.*{1,20}][.*{1,20}]@*{1,20}[.*{2,6}][.*{1,2}]",
greedy: false,
onBeforePaste: function (pastedValue, opts) {
pastedValue = pastedValue.toLowerCase();
return pastedValue.replace("mailto:", "");
},
definitions: {
'*': {
validator: "[0-9A-Za-z!#$%&'*+/=?^_`{|}~\-]",
cardinality: 1,
casing: "lower"
}
}
});
}
//color picker
if ($(".colorpicker")) {
$(".colorpicker").colorpicker();
}
/////////////////////////////////////////////////////
//INIZIALIZZO CKEDITOR (textarea con classi ckeditor)
//
/////////////////////////////////////////////////////
$('.ckeditor').each(function (i, obj) {
currentId = $(this).attr('id');
CKEDITOR.replace(currentId);
//
});
CKEDITOR.on("instanceCreated", function (event) {
event.editor.on("change", function () {
var originalField = jQuery(this).attr("name");
// alert(originalField);
$("#" + originalField).val(event.editor.getData());
});
});
/////////////////////////////////////////////////////
//alert messaggi
//popup solo su warning e errori?? da decidere
/////////////////////////////////////////////////////
//console.log("post submit..."+$('#messaggi').html());
//Ab.showMessage($('#messaggi').html(),"titolo...");
if ($("#beanMsg").length) {
if ($("#beanMsg").val().toLowerCase().indexOf("error") > 0 || $("#beanMsg").val().toLowerCase().indexOf("warning") > 0 || $("#beanMsg").val().toLowerCase().indexOf("attenzione") > 0) {
if ($("#beanMsg").val() != "") {
var toastrType = "success";
var timeoutVal = 5000;
if ($("#beanMsg").val().toLowerCase().indexOf("error") > 0) {
toastrType = "error";
timeoutVal = 0;
} else if ($("#beanMsg").val().toLowerCase().indexOf("warning") > 0 || $("#beanMsg").val().toLowerCase().indexOf("attenzione") > 0) {
toastrType = "warning";
}
//alert($("#beanMsg").val());
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": timeoutVal,
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
//$.toaster($("#beanMsg").val(), "Attenzione", priority);
toastr[toastrType]($("#beanMsg").val());
//$.toaster({ message : $("#beanMsg").val(), title : '', priority : priorityVal, timeout: timeoutVal});
}
} else {
/////////////////////////////////////////////////////
// il testo su msg va via automaticamente dopo tot se non è un warning o errore
/////////////////////////////////////////////////////
clearTimeout(msgInterval);
msgInterval = setTimeout("$('#messaggi').html('');", 3000);
}
}
/////////////////////////////////////////////////////
// eventi di modifica da registrare ogni volta
/////////////////////////////////////////////////////
if ($("#pageType").val() == "D") {
$("input").on("focus", null, null, function () {
if ($("#currentFocus"))
$("#currentFocus").val(this.id);
});
$(":input:visible").on("input", null, null, function () {
dataChanged();
});
$("select").on("change", null, null, function () {
dataChanged();
});
$("select").on("focus", null, null, function () {
if ($("#currentFocus"))
$("#currentFocus").val(this.id);
});
//////////
// GESTIONE CHECKBOXES
$(":checkbox").on("click keyup", null, null, function () {
dataChanged();
});
$(":checkbox").on("focus", null, null, function () {
if ($("#currentFocus"))
$("#currentFocus").val(this.id);
});
$(":checkbox").on("ifChanged", null, null, function () {
dataChanged();
var name = $(this).attr("name").replace("ck", "");
// controllo lo stato della checkbox e valorizzo la input
if ($(this).is(":checked")) {
$("#" + name).val(1);
} else {
$("#" + name).val(0);
}
//eseguo l'onchange sul campo text corrispondente
//se funziona evito postClickICheck
$("#" + name).change();
/*
if (typeof postClickICheck == 'function') {
postClickICheck(name);
}
*/
//if (postClickICheck)
// postClickICheck();
});
//
/*$(".editor").on("keyup", null, null, function () {
dataChanged();
});*/
}
//gestione documentReadyScript standard
if ($("#pageType").val() == "D") {
if (typeof documentReadyScript == 'function')
documentReadyScript();
} else if ($("#pageType").val() == "R") {
if (typeof documentReadyScriptCR == 'function') {
documentReadyScriptCR();
}
//////////
// GESTIONE CHECKBOXES
$(":checkbox").on("focus", null, null, function () {
if ($("#currentFocus"))
$("#currentFocus").val(this.id);
});
//
$(":checkbox").on("ifChanged", null, null, function () {
//dataChanged();
var name = $(this).attr("name").replace("ck", "");
// controllo lo stato della checkbox e valorizzo la input
if ($(this).is(":checked")) {
$("#" + name).val(1);
} else {
$("#" + name).val(0);
}
//eseguo l'onchange sul campo text corrispondente
//se funziona evito postClickICheck
$("#" + name).change();
/*if (typeof postClickICheckCR == 'function') {
postClickICheckCR(name);
}
*/
//if (postClickICheck)
// postClickICheck();
});
}
/////////////////////////////////////////////////////
//gestione popover (help?)
/////////////////////////////////////////////////////
$(function () {
// $('[data-toggle="popover"]').popover()
$('.input-sm').attr("data-placement", "top");
$('.input-sm').attr("data-trigger", "manual");
$('.input-sm').attr("title", "Help");
$('.input-sm').popover();
})
/////////////////////////////////////////////////////
//magnify .. zoom immagini
/////////////////////////////////////////////////////
$('[data-toggle="magnify"]').each(function () {
var $mag = $(this);
$mag.magnify()
})
});
};
//********************************************************
//********************************************************
// GESTISCE IL MESSAGGIO DEI DATI CAMBIATI
//********************************************************
//********************************************************
//DA VERIFICARE!!!!!!
function dataChanged() {
var toastrType = "info";
var timeoutVal = 3000;
//var msgDatiCambiati="<label class='msgWarn'>Dati Cambiati... </label>";
var msgDatiCambiati = "<label class='msgWarn'>Dati Cambiati... </label>";
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": timeoutVal,
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
//$.toaster($("#beanMsg").val(), "Attenzione", priority);
//fastidioso... lo tolgo....
//toastr[toastrType](msgDatiCambiati);
$('#messaggi').html(msgDatiCambiati);
clearTimeout(msgInterval);
}
//********************************************************
//********************************************************
// INVIA MESSAGGIO IN ALTO A DX CON TOASTR
//toastrType: success, error, warning, info
//********************************************************
//********************************************************
Ab.popupMsg = function (toastrType, msg) {
var timeoutVal = 3000;
var lblClass = "";
if (toastrType == "success") {
lblClass = "msgSuccess";
} else if (toastrType == "info") {
lblClass = "msgInfo";
} else if (toastrType == "warning") {
lblClass = "msgWarning";
} else if (toastrType == "error") {
lblClass = "msgError";
timeoutVal = 0;
}
var theMsg = "<label class='" + lblClass + "'>" + msg + "</label>";
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": true,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": timeoutVal,
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
//$.toaster($("#beanMsg").val(), "Attenzione", priority);
toastr[toastrType](theMsg);
$('#messaggi').html(theMsg);
clearTimeout(msgInterval);
}
//DA TOGLIERE !!!!! VEDERE DOVE è E TOGLIERE
function popupMsg(toastrType, msg) {
//alert('pio');
Ab.popupMsg(toastrType, msg);
}
//////////////////////////////////////////////////////////
/// swap image ///////////////////////////////////////////
/////////////////////////////////////////////////////////
Ab.preloadImages = function () { //v3.0
var d = document;
if (d.images) {
if (!d.MM_p) d.MM_p = new Array();
var i, j = d.MM_p.length,
a = preloadImages.arguments;
for (i = 0; i < a.length; i++)
if (a[i].indexOf("#") != 0) {
d.MM_p[j] = new Image;
//alert('loading:'+a[i]);
d.MM_p[j++].src = a[i];
}
}
}
Ab.swapImgRestore = function () { //v3.0
var i, x, a = document.sr;
for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
x.src = x.oSrc;
}
Ab.swapImage = function () { //v3.0
var i, j = 0,
x, a = arguments;
document.sr = new Array;
for (i = 0; i < (a.length - 2); i += 3) {
if ((x = Ab.findObj(a[i])) != null) {
document.sr[j++] = x;
if (!x.oSrc)
x.oSrc = x.src;
x.src = a[i + 2];
}
}
}
//********************************************************
//********************************************************
// SALVA FILE TRAMITE AJAX (SIMILE A SAVEIMAGE PER CARICAMENTO IMMAGINI
// passo un id del bean relativo e un codfile nel caso di n file da inserire
// il nome del file da caricare è btn-upload_file_[codFile]
//********************************************************
//********************************************************
Ab.saveFile = function (id, codFile) {
//grab all form data
// $('#cmd').val("loadImg");
//var formData = new FormData($('form#main')[0]);
//alert(document.getElementById("btn-upload_"+codImage));
var sampleFile = document.getElementById("btn-upload_file_" + codFile).files[0];
var oMyForm = new FormData();
//oMyForm.append("file", $('#imgFile_'+codImage).files[0]);
oMyForm.append("fileName", sampleFile);
oMyForm.append("cmd", "saveFile");
oMyForm.append("codFile", codFile);
oMyForm.append("id", id);
// oMyForm.append("nomeOriginale",id);
//alert(sampleFile);
if (typeof sampleFile != "undefined") {
//$("#imgNew_"+codImage).attr("src", "../_V4/_img/wait.gif");
var action = "";
if ($("#actionPage", "#main")) {
action = $("#actionPage", "#main").val();
} else {
action = $("#main").attr("action");
}
$.ajax({
url: action,
type: 'POST',
data: oMyForm,
chache: false,
async: true,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
//xhr: opt.progress,
beforeSend: function () {},
success: function (response) {
var result = $.parseJSON(response);
//
//alert(result[0].message);
$('#messaggi').fadeIn(100);
$('#messaggi').html(result[0].message);
//cancello msg dopo il timeout
if ($('#messaggi').length > 0) {
msgInterval = setTimeout("$('#messaggi').fadeOut(200);msgGone=true", 10000);
}
//messaggio sul file
if (result[0].result == true) {
$("#uploadFileRes_" + codFile).html("File: <a target='_blank' href='" + result[0].fileNameLink + "'>" + result[0].fileName + "</a>");
$("#fileNameOnServer_" + codFile).val(result[0].fileName);
} else {
$("#uploadFileRes_" + codFile).html("ERRORE!");
$("#fileNameOnServer_" + codFile).val("");
}
//carico l'immagine
//alert(result[0].imgPath);
//Ab.showImgBtnArea(codImage);
/*
$('#imgNew_'+codImage).attr("src", result[0].imgPath).load(function(){
this.width;
// Note: $(this).width() will not work for in memory images
});
*/
},
error: function () {
/*$('#messaggi').fadeIn(100);
$('#messaggi').html("ERRORE! VERIFICA LA DIMENSIONE DEL FILE");
if ($('#messaggi').length > 0) {
msgInterval = setTimeout("$('#messaggi').fadeOut(200);msgGone=true", 10000);
}*/
$("#uploadFileRes_" + codFile).html("ERRORE! VERIFICA LA DIMENSIONE DEL FILE");
//$("#imgNew_" + codFile).attr("src", "../_V4/_img/placeHold.gif");
}
});
}
}
/*************************************************/
/*************************************************/
/* AGGIORNA MESSAGGIO THREAD /*
/*ha bisogno di un attivatore sulla document ready*/
/* Ab.startAggiornaThreadMsg()/*
/*************************************************/
/*************************************************/
var intervalTMAgg;
var secPool1 = 10,
secPool2 = 3;
var secTMAgg = secPool2;
Ab.aggiornaThreadMsg = function () {
if ($("#threadMsg").length) {
if ($("#threadMsg").html().length > 2) {
if (secTMAgg == secPool1) {
secTMAgg = secPool2;
clearInterval(intervalTMAgg);
intervalTMAgg = setInterval("Ab.aggiornaThreadMsg()", secTMAgg * 1000);
}
} else {
if (secTMAgg == secPool2) {
secTMAgg = secPool1;
clearInterval(intervalTMAgg);
intervalTMAgg = setInterval("Ab.aggiornaThreadMsg()", secTMAgg * 1000);
}
}
console.log("checkAggiornamento: sec=" + secTMAgg + " contenuto:*" + $("#threadMsg").html().length + "##");
//FETCH DI ACCIORNAMENTO
Ab.fetch4($("#actionPage").val(), "cmd=aggiornaThreadMsg", "threadMsg", null, "hidden")
} else {
//console.log("clear interval");
clearInterval(intervalTMAgg);
}
}
/*************************************************/
/*************************************************/
/* ATTIVATORE AGGIORNA MESSAGGIO THREAD /*
/* DA RICHIAMERE SULLA DOCUMENT READY */
/*************************************************/
/*************************************************/
Ab.startAggiornaThreadMsg = function () {
if ($("#threadMsg").length) {
if ($("#threadMsg").html().length > 2) {
secTMAgg = secPool2;
}
console.log("documentReadyScriptCR: sec=" + secTMAgg);
clearInterval(intervalTMAgg);
intervalTMAgg = setInterval("Ab.aggiornaThreadMsg()", secTMAgg * 1000);
} else {
clearInterval(intervalTMAgg);
}
}
/*************************************************/
/*************************************************/
/* Fermo la propagazione dell'evento*/
/*************************************************/
/*************************************************/
Ab.disabledEventPropagation = function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else if (window.event) {
window.event.cancelBubble = true;
}
}
/**********************************************************/
/**********************************************************/
/* ESTENSIONE JQUERY PER IL TEST DELL'ATTRIBUTO SU UN OGGETTO JQUERY*/
/**********************************************************/
/**********************************************************/
$.fn.hasAttr = function (name) {
return this.attr(name) !== undefined;
};
/**********************************************************/
/**********************************************************/
/* MI TIRA FUORI I DATI DI UN FORM IN FORMATO JSON. FILTRA
SOLO QUELLO CON ATTRIBUTO jsonData */
/**********************************************************/
/**********************************************************/
Ab.getJsonFromForm = function ($form) {
var serialized = $form.serializeArray();
var s = '';
var data = {};
for (s in serialized) {
if ($("#" + serialized[s]['name']).hasAttr("jsonData")) {
data[serialized[s]['name']] = serialized[s]['value']
}
}
return JSON.stringify(data);
}
/**********************************************************/
/**********************************************************/
/* RELOAD CSS SIZE, PER CAMBIARE LA DIMENSIONE DEL TESTO E ICONE */
/* abliaLteNormal abliaLteMedium abliaLteBig abliaLteVeryBig abliaLteSmall
/**********************************************************/
/**********************************************************/
Ab.switchCssSize = function () {
var cssSize = $("#cssLteSize");
if (cssSize.attr("href").indexOf("abliaLteNormal") > -1) {
console.log("switch to abliaLteMedium");
cssSize.attr("href", "../_V4/_lte/_css/abliaLteMedium.css");
} else if (cssSize.attr("href").indexOf("abliaLteMedium") > -1) {
console.log("switch to abliaLteSmall");
cssSize.attr("href", "../_V4/_lte/_css/abliaLteSmall.css");
} else if (cssSize.attr("href").indexOf("abliaLteSmall") > -1) {
console.log("switch to abliaLteBig");
cssSize.attr("href", "../_V4/_lte/_css/abliaLteBig.css");
} else if (cssSize.attr("href").indexOf("abliaLteVeryBig") > -1) {
console.log("switch to abliaLteBig");
cssSize.attr("href", "../_V4/_lte/_css/abliaLteBig.css");
} else if (cssSize.attr("href").indexOf("abliaLteBig") > -1) {
console.log("switch to abliaLteNormal");
cssSize.attr("href", "../_V4/_lte/_css/abliaLteNormal.css");
}
}
//********************************************************
//********************************************************
// semplicemente fa il console log
//utilizzato per i breakpont
//********************************************************
//********************************************************
Ab.debug = function (msg) {
console.log("Debug: " + msg);
}
/*************************************************/
/*************************************************/
/* AGGIORNA MESSAGGIO di STATUS /*
/*ha bisogno di un attivatore sulla document ready*/
/* Ab.startAggiornaStatusMsg()/*
/*************************************************/
/*************************************************/
var intervalSMAgg;
var secPoolSm1 = 10,
secPoolSm2 = 3;
var secSMAgg = secPoolSm2;
Ab.aggiornaStatusMsg = function () {
if ($("#statusMsg").length) {
if ($("#statusMsg").html().length > 2) {
if (secSMAgg == secPoolSm1) {
secSMAgg = secPoolSm2;
clearInterval(intervalSMAgg);
intervalSMAgg = setInterval("Ab.aggiornaStatusMsg()", secSMAgg * 1000);
}
} else {
if (secSMAgg == secPoolSm2) {
secSMAgg = secPoolSm1;
clearInterval(intervalSMAgg);
intervalSMAgg = setInterval("Ab.aggiornaStatusMsg()", secSMAgg * 1000);
}
}
console.log("aggiornaStatusMsg checkAggiornamento: sec=" + secSMAgg + " lunghezza contenuto tra ##: ##" + $("#statusMsg").html().length + "##");
//FETCH DI ACCIORNAMENTO
Ab.fetch4("../menu/StatusMsg.abl", "cmd=aggiornaStatusMsg", "statusMsg", null, "hidden")
} else {
//console.log("clear interval");
clearInterval(intervalSMAgg);
}
}
/*************************************************/
/*************************************************/
/* ATTIVATORE AGGIORNA MESSAGGIO status /*
/* DA RICHIAMERE SULLA DOCUMENT READY */
/*************************************************/
/*************************************************/
Ab.startAggiornaStatusMsg = function () {
if ($("#statusMsg").length) {
if ($("#statusMsg").html().length > 2) {
secSMAgg = secPoolSm2;
}
console.log("startAggiornaStatusMsg: sec=" + secSMAgg);
clearInterval(intervalSMAgg);
intervalSMAgg = setInterval("Ab.aggiornaStatusMsg()", secSMAgg * 1000);
} else {
clearInterval(intervalSMAgg);
}
}
/*************************************************/
/*************************************************/
/* DOCUMENT READY GLOBALE... PARTE 1 VOLTA SOLA */
/*************************************************/
/*************************************************/
$(document).ready(function () {
console.log("init startAggiornaStatusMsg!");
Ab.startAggiornaStatusMsg();
});
/*************************************************/
/*************************************************/
/* da stringa a numero */
/*************************************************/
/*************************************************/
Ab.toDouble = function (number) {
if (locale == "IT") {
number = number.replace(/[.]/, '');
number = number.replace(/[.]/, '');
number = number.replace(/[.]/, '');
number = number.replace(/[.]/, '');
number = number.replace(',', '.');
//tolgo gli zeri finali
var dotIdx = number.indexOf('.');
//alert("dotidx0"+dotIdx);
if (dotIdx != -1) {
var j = number.length - 1;
/* while(number.charAt(i)!='.' && number.charAt(i)=='0' ) NON FUNZIONA.. forse perche' usavo i invece di j!!*/
while (number.charAt(j) != '.') {
//alert("j="+j+" number charat(j):"+number.charAt(j));
if (number.charAt(j) == '0') {
number = number.substr(0, j);
j--;
} else j = dotIdx;
}
if (number.charAt(number.length - 1) == '.')
number = number.substr(0, number.length - 1);
}
} else if (locale == "US" || locale == "UK") {
number = number.replace(/[,]/, '');
number = number.replace(/[,]/, '');
number = number.replace(/[,]/, '');
number = number.replace(/[,]/, '');
number = number.replace('.', ',');
//tolgo gli zeri finali
var dotIdx = number.indexOf(',');
if (dotIdx != -1) {
var j = number.length - 1;
while (number.charAt(j) != ',') {
if (number.charAt(j) == '0') {
number = number.substr(0, j);
j--;
} else
j = dotIdx;
}
if (number.charAt(number.length - 1) == ',')
number = number.substr(0, number.length - 1);
}
//alert("US:"+number);
}
//da correggere il caso 33,40 Non mi accetta lo 0 finale!!!'
num = parseFloat(number);
//alert('num:'+num);
// if (number!=''+num && number!=''+num +'0'&& number!=''+num +'00'&& number!=''+num +'000' ) errors+='- '+desc+' non numerico.\n';
if (number != '' + num) {
//non è numeroco
return 0;
} else {
return num;
}
}
/*************************************************/
/*************************************************/
/* string prototyper per startsWith e endsWith.*/
/*************************************************/
/*************************************************/
// Checks that string starts with the specific string
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str) {
return this.slice(0, str.length) == str;
};
}
// Checks that string ends with the specific string...
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str) {
return this.slice(-str.length) == str;
};
}
/*************************************************/
/*************************************************/
/* cambia lingua alla parte amministrativa...*/
/*************************************************/
/*************************************************/
Ab.changeAdminLang = function (lang) {
//la pagina finisce per / o per html
var page = window.location.href;
var idx = page.lastIndexOf("/");
if (idx > 0) {
var page1 = page.substring(0, idx);
} else {
var page1 = page;
}
//console.log("changeAdminLang "+page1+" --"+page1.endsWith('menu'));
theSvlt = page1 + "/index-" + lang + ".html";
//alert(theSvlt);
changingLang = true;
location.href = theSvlt;
}
/*************************************************/
/*************************************************/
/* dato un elemento, il tipo di evento e il codice del tasto esegue il comando sull'elemento..*/
/*type--> keyup keydown, ecc. ecc. il prefisso "on" lo metto io */
/* es: triggerEvent(nextButton, 'keyup', 13); // simulate mouse/enter key press */
/* https://stackoverflow.com/questions/3368578/trigger-a-keypress-keydown-keyup-event-in-js-jquery */
/* UTILIZZATO ININPUTAJAX PER LA RICERA CONLA LENTE DI INGRANDIMENTO SE SU SMARTPHONE */
/* keycode --> 13 ad esempio è invio */
/*************************************************/
/*************************************************/
Ab.triggerEvent = function (elId, type, keyCode) {
//el=$(elId);
el = document.getElementById(elId);
//alert('pio');
//jQuery.noConflict();
if ('createEvent' in document) {
//alert('pio1');
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.keyCode = keyCode;
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
//alert('pio2');
var e = document.createEventObject();
e.keyCode = keyCode;
e.eventType = type;
el.fireEvent('on' + e.eventType, e);
}
}
/*************************************************/
/*************************************************/
/* REPLACEALL */
/*************************************************/
/*************************************************/
Ab.replaceAll = function (str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
/*************************************************/
/*************************************************/
/* CHIAMATA DA DETTAGLIO: TRADUCE SE CI SONO TUTTI I CAMPI DESCTXTLANG DALLA LINGUA DI DEFAULT */
/*************************************************/
/*************************************************/
Ab.translateAll = function () {
swal({
title: "Traduzione Automatica",
text: "Per i campi in lingua non salvati, verra' inserita la traduzione tramite google translator. Sei Sicuro?",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "si",
cancelButtonText: "no",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
$("#main").attr("action", $("#actionPage").val());
$("#cmd", "#main").val("translateAll");
$("#act", "#main").val("");
$("#cmd2").val("");
$("#act2").val("");
//$("#pageNumber").val("1");
Ab.submitAj('main');
} else {
}
});
}
/*************************************************/
/*************************************************/
/* CHIAMATA DA DETTAGLIO: TRADUCE SE CI SONO TUTTI I CAMPI DESCTXTLANG DALLA LINGUA DI DEFAULT */
/*************************************************/
/*************************************************/
Ab.translateAllCR = function () {
swal({
title: "Traduzione Automatica",
text: "Per i campi in lingua non salvati, verra' inserita la traduzione tramite google translator. Sei Sicuro?",
type: "warning",
showCancelButton: true,
confirmButtonClass: "btn-danger",
confirmButtonText: "si",
cancelButtonText: "no",
closeOnConfirm: true,
closeOnCancel: true
},
function (isConfirm) {
if (isConfirm) {
$("#main").attr("action", $("#actionPage").val());
$("#cmd", "#main").val("translateAllCR");
$("#act", "#main").val("");
$("#cmd2").val("");
$("#act2").val("");
//$("#pageNumber").val("1");
Ab.submitAj('main');
} else {
}
});
}