﻿var Url = {

    // public method for url encoding
    encode: function(string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode: function(string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

var cellValue = '';
function markUpdate(sPostFissi, iTipo, ID_Cur_Servizio) {
    //iTipo 0: text box
    //      1: check box
    //      2: innerCombo
    if (parseInt(ID_Cur_Servizio) > 0) {
        switch (iTipo) {
            case 0:
                var oDati = MM_findObj('field_' + sPostFissi + '_DATI');
                aDati = oDati.value.split('|#|');
                var dbValue = aDati[1];
                var oField = MM_findObj('field_' + sPostFissi);
                var sCurValue = oField.value;
                if (dbValue != sCurValue)
                    oField.style.background = '#66CC66';
                else
                    oField.style.background = '#FFFFFF';
                break;
            case 1:
                var oDati = MM_findObj('field_' + sPostFissi + '_DATI');
                aDati = oDati.value.split('|#|');
                var dbValue = aDati[1];
                var oField = MM_findObj('field_' + sPostFissi);
                if ((oField.checked == true && dbValue == '0') || (oField.checked == false && dbValue == '1'))
                    oField.style.background = '#66CC66';
                else
                    oField.style.background = '#FFFFFF';
                break;
            case 2:

                var oDati = MM_findObj('VCOLD_' + sPostFissi);
                var dbValue = oDati.value.split('@#@')[0];
                var oField = MM_findObj('field_' + sPostFissi);
                var oVCText = MM_findObj('VCText_' + sPostFissi);
                var sCurValue = oField.value;
                if (dbValue != sCurValue)
                    oVCText.style.background = '#66CC66';
                else
                    oVCText.style.background = '#FFFFFF';
                break;

        }
    }
}
function markUpdate_OLD(sPostFissi, iTipo, ID_Cur_Servizio) {
    //iTipo 0: text box
    //      1: check box
    //      2: innerCombo
    var oCurFieldRemoto;
    var aPostFissi = sPostFissi.split('_');
    var sfondoDeselezionato = null;
    var bModificaDaDettaglio = 0;
    var SelColor;
    var DeSelColor;
    var SelRemoteColor;
    var DeSelRemoteColor;
    if (aPostFissi[0] == '1' && MM_findObj('field_0_' + ID_Cur_Servizio + '_' + aPostFissi[2]) != null) //ho modificato dal dettaglio
    {
        oCurFieldRemoto = MM_findObj('field_0_' + ID_Cur_Servizio + '_' + aPostFissi[2]);
        SelColor = sCampoModificato;
        DeSelColor = '#ffffff';
        SelRemoteColor = sCampoModificato;
        DeSelRemoteColor = sSfonfoDettaglio
        bModificaDaDettaglio = 1;
    }
    if (aPostFissi[0] == '0' && MM_findObj('field_1_0_' + aPostFissi[2]) != null) //ho modificato dall'elenco principale
    {
        oCurFieldRemoto = MM_findObj('field_1_0_' + aPostFissi[2]);
        SelColor = sCampoModificato;
        DeSelColor = sSfonfoDettaglio;
        SelRemoteColor = sCampoModificato;
        DeSelRemoteColor = '#ffffff';
    }
    if (parseInt(ID_Cur_Servizio) > 0)
    {
        switch (iTipo) {
            case 0:
                var oDati = MM_findObj('field_' + sPostFissi + '_DATI');
                aDati = oDati.value.split('|#|');
                var dbValue = aDati[1];
                var oField = MM_findObj('field_' + sPostFissi);
                var sCurValue = oField.value;
                if (dbValue != sCurValue) {
                    oField.style.background = SelColor;
                    oCurFieldRemoto.style.background = SelRemoteColor;
                }
                else {
                    oField.style.background = DeSelColor;
                    oCurFieldRemoto.style.background = DeSelRemoteColor;
                }
                break;
            case 1:
                var oDati = MM_findObj('field_' + sPostFissi + '_DATI');
                aDati = oDati.value.split('|#|');
                var dbValue = aDati[1];
                var oField = MM_findObj('field_' + sPostFissi);

                if ((oField.checked == true && (dbValue == '0' || dbValue=='NO') ) || (oField.checked == false && (dbValue == '1' || dbValue == 'SI' ))) {
                    oField.style.background = SelColor;
                    oCurFieldRemoto.style.background = SelRemoteColor;
                }
                else {
                    oField.style.background = DeSelColor;
                    oCurFieldRemoto.style.background = DeSelRemoteColor;
                }
                break;
            case 2:

                var oDati = MM_findObj('VCOLD_' + sPostFissi);
                var dbValue = oDati.value.split('@#@')[0];
                var oField = MM_findObj('field_' + sPostFissi);
                var oVCText = MM_findObj('VCText_' + sPostFissi);
                var sCurValue = oField.value;
                if (dbValue != sCurValue) {
                    oVCText.style.background = SelColor;
                    oCurFieldRemoto.style.background = SelRemoteColor;
                }
                else {
                    oVCText.style.background = DeSelColor;
                    oCurFieldRemoto.style.background = DeSelRemoteColor;
                }
                break;
        }

    }
}

function keyPress(sPostFissi, iTipo, evt, TP1, sQRY, ID_Cur_Servizio, COLUMN_NAME) {
    //iTipo 0: text box
    //      1: check box
    //      2: innerCombo
    var iEvent = Combo_OCX_eventToFire(evt);
    //alert(ID_Cur_Servizio);
    if (iEvent == 27 && parseInt(ID_Cur_Servizio) > 0) // escButton
    {
        switch (iTipo) {
            case 0:
                var oDati = MM_findObj('field_' + sPostFissi + '_DATI');
                aDati = oDati.value.split('|#|');
                var dbValue = aDati[1];
                var DATA_TYPE = aDati[2];
                var oField = MM_findObj('field_' + sPostFissi);
                oField.value = dbValue;
                oField.style.background = '#FFFFFF';
                var sQueryDati = COLUMN_NAME + ';' + CKJString(dbValue) + ';' + sPostFissi + ';' + DATA_TYPE;
                query(TP1, sQRY, ID_Cur_Servizio, 'ElencoLoader', sQueryDati, '');
                break;
            case 1:
                var oDati = MM_findObj('field_' + sPostFissi + '_DATI');
                aDati = oDati.value.split('|#|');
                var dbValue = aDati[1];
                var DATA_TYPE = aDati[2];
                var oField = MM_findObj('field_' + sPostFissi);
                if (dbValue == '1' || dbValue == 'True') 
                    oField.checked = true;
                else
                    oField.checked = false;                
                oField.style.background = '#FFFFFF';
                var sQueryDati = COLUMN_NAME + ';' + CKJBit(oField.checked) + ';' + sPostFissi + ';' + DATA_TYPE;
                query(TP1, sQRY, ID_Cur_Servizio, 'ElencoLoader', sQueryDati, '');
                break;
            case 2:
                var oDati = MM_findObj('VCOLD_' + sPostFissi);                
                var dbValue = oDati.value.split('@#@')[0];
                var dbText = oDati.value.split('@#@')[1];
                var oField = MM_findObj('field_' + sPostFissi);
                var oVCText = MM_findObj('VCText_' + sPostFissi);
                oVCText.value = dbText;
                oField.value = dbValue
                oVCText.style.background = '#FFFFFF';
                break;

        }
    }
    
}

function toggleDiv(show, hide) {
    document.getElementById(hide).style.display = 'none';
    //alert( '...pause here...' ); 
    document.getElementById(show).style.display = 'block';
    nudgeFirefox();
} 

function nudgeFirefox() {
    /* sort out a height problem in firefox */
    document.getElementsByTagName('body')[0].style.height = '99%';
    document.getElementsByTagName('body')[0].style.height = 'auto';
}

function highlight(input, selectionStart, selectionEnd) {
    if (input.setSelectionRange) {
        input.focus();
        input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange) {
        var range = input.createTextRange();
        range.collapse(true);
        range.moveEnd('character', selectionEnd);
        range.moveStart('character', selectionStart);
        range.select();
    }
}

function ckThivValue(oThis, bFocus,sTipo) {
    if (bFocus == 1) {
        cellValue = oThis.value;
        //oThis.value = '';
        highlight(oThis, 0, oThis.value.length);
    }
    else {
        if (oThis.value.length == 0) {
            var sPostFissi = oThis.id.replace('field_', '');
            var IS_NULLABLE = document.getElementById(oThis.id + '_DATI').value.split('|#|')[3];
            if (IS_NULLABLE == 'YES')
                oThis.value = ''; //cellValue;
            else {
                alert('ATTENZIONE!\nQuesto campo non accetta un valore nullo!');
                oThis.value = cellValue;
            }
        }
        else {
            switch (sTipo) {
                case 'money':
                    {
                        oThis.value = formatCurrencyIW(oThis.value);                      
                        break;
                    }

                case 'int':
                    {
                        oThis.value = formatIntIW(oThis.value);
                        break;
                    }    
                case 'real':  case 'float':
                    {
                        oThis.value = formatFloatIW(oThis.value);
                        break;
                    }    
                default:
                    {
                        ;
                    }
            }
            
            }
                
        cellValue = '';    
    }
}

function formatIntIW(intPart) {
    var c = -1;
    var intMpart = '';
    for (var i = intPart.length; i > 0; i--) {
        c++;
        ch = intPart.substring(i - 1, i)
        if (c == 3) {
            intMpart = ch + '.' + intMpart;
            c = 0;
        }
        else
            intMpart = ch + intMpart;
    }
    return intMpart;
}

function formatFloatIW(num) {
    decPos = num.indexOf(',');
    if (decPos == 0) {
        num = '0' + num;
        decPos = 1;
    }
    var iAdd = 0;
    if (decPos >= 0) {
        intPart = num.substring(0, decPos);
        decPart = num.substring(decPos + 1, num.length)
        if (decPart.length > 2) {
            decPart2 = decPart.substring(0, 2);
            if (parseInt(decPart.substring(2, 3)) > 5)
                decPart = (parseInt(decPart2) + 1).toString()
            else
                decPart = decPart2;
            if (decPart == '100') {
                decPart = '00'
                iAdd = 1
            }
            //else
            //  iAdd = 0
        }
        if (decPart.length == 0)
            decPart = '00';
        if (decPart.length == 1)
            decPart = decPart + '0';
        decPart = ',' + decPart;
        intPart = (parseInt(intPart) + iAdd).toString();
    }
    else {
        intPart = num;
        decPart = ',00';
    }
    var intMpart = formatIntIW(intPart);
    return intMpart + decPart;
}

function formatCurrencyIW(num) {
    num=num.replace('€ ', '');
    return '€ ' + formatFloatIW(num);
} 


function aChars_only(myfield, e, aChars, bDecConv) {
    var key;
    var keychar;
    if (window.event)
        key = window.event.keyCode;
    else if (e)
        key = e.which;
    else
        return true;
    keychar = String.fromCharCode(key);
    if (bDecConv && key == 46) //'.'
    {
        if (window.event)
            window.event.keyCode = 44;
        else
            e.which = 44;
        key = 44;
        keychar = ',';        
    }
    if (bDecConv && key == 44 && myfield.value.indexOf(',') > 0)  // posso metter una sola virgola!
        return false;

    //if (bDecConv && myfield.value.indexOf(',') >-1 && (myfield.value.length - myfield.value.indexOf(',')) >2)
    //    return false;

    // control keys
    if ((key == null) || (key == 0) || (key == 8) ||
    (key == 9) || (key == 13) || (key == 27))
        return true;

    // numbers
    else if (((aChars).indexOf(keychar) > -1))
        return true;

    else
        return false;
}


if (brName == 'IE' && MajorverW <= 6) {

    var clear="/img/space.gif" //path to clear.gif

    pngfix = function(){
        try{
	        var els=document.getElementsByTagName('*');
	        var ip=/\.png/i;
	        var i=els.length;
	        while(i-- >0){
		        var el=els[i];
		        var es=el.style;
	            if (el.src){
	                if(el.src.match(ip) && !es.filter){
		                es.height=el.height;
		                es.width=el.width;
		                es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+el.src+"',sizingMethod='crop')";
		                el.src=clear;
	                } else {
		                var elb=el.currentStyle.backgroundImage;
		                if(elb.match(ip)){
			                var path=elb.split('"');
			                var rep=(el.currentStyle.backgroundRepeat=='no-repeat')?'crop':'scale';
			                es.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+path[1]+"',sizingMethod='"+rep+"')";
			                es.height=el.clientHeight+'px';
			                es.backgroundImage='none';
			                var elkids=el.getElementsByTagName('*');
			                if (elkids){
				                var j=elkids.length;
				                if(el.currentStyle.position!="absolute")es.position='static';
				                while (j-- >0)
					                if(!elkids[j].style.position)elkids[j].style.position="relative";
			                }
		                }
	                }
                }
	        }
        }
        catch(err)	{
        }
    }

    window.attachEvent('onload',pngfix);
}

/*
<a href="javascript:void(0)" onClick="javascript:ModificaSize('Div1',1)">+</a>
<a href="javascript:void(0)" onClick="javascript:ModificaSize('Div1',-1)">-</a>
*/
function ModificaSize(sObj,iInt) {
    var oObj
    var iSize
    oObj = MM_findObj(sObj);

    if (oObj.style.fontSize) {
        iSize = parseInt(oObj.style.fontSize.replace('pt', ''));
    } else {
        iSize = 10;
    }
    iSize = iSize + iInt;   /* Se iInt è positivo la size aumenta, se è negativo si decrementa. */
    oObj.style.fontSize = iSize + 'pt';
}

function isEnter(e) {
    var characterCode;
    if (!e) e = window.event;
    if(e.which) {
        characterCode = e.which
    } else {
        characterCode = e.keyCode
    }
    if(characterCode == 13) return true;
    return false;
}

// Imposta i flag nel menu backoffice
function setMenu(j){
    j--;
    cont = 0;
    imgTmp = MM_findObj('child_Ico_' + cont, self.top["Menu"].document);
    while (imgTmp != null)
    {
        if (cont == j)
            imgTmp.src = 'img/ico_b.gif'
        else
            imgTmp.src = 'img/ico_a.gif';
        cont++;
        imgTmp = MM_findObj('child_Ico_' + cont, self.top["Menu"].document);
    }
  
    //per lasciare flaggato il menu padre
    padreHidden = MM_findObj("img_" + j, self.top["Menu"].document);
    if (padreHidden){
        divPadre = padreHidden.value;
        if (divPadre != "")
        {
            divIcoDisplay = MM_findObj(divPadre, self.top["Menu"].document);
            divIcoDisplay.src = 'img/ico_meno.gif';
        }
    }        
}



function ImpostaComboBox(scmbObj, iValore){
    var obj = MM_findObj(scmbObj);
    for (var iCnt = 0; iCnt < obj.options.length; iCnt++){
        if (obj.options[iCnt].value == iValore){
            obj.options[iCnt].selected = true;
            break;
        }
    }
}

function ControllaCF(cf)
{
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return '';
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return "La lunghezza del codice fiscale non è\n"
		+"corretta: il codice fiscale dovrebbe essere lungo\n"
		+"esattamente 16 caratteri.\n";
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return "Il codice fiscale contiene un carattere non valido `" +
				cf.charAt(i) +
				"'.\nI caratteri validi sono le lettere e le cifre.\n";
	}
	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for( i = 1; i <= 13; i += 2 )
		s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	for( i = 0; i <= 14; i += 2 )
		s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
		return "Il codice fiscale non è corretto:\n"+
			"il codice di controllo non corrisponde.\n";
	return "OK";
}



function ControllaPIVA(pi)
{
	if( pi == '' )  return '';
	if( pi == '00000000000') return 'La Partita Iva Inserita non è valida !';
	if( pi == '99999999990') return 'La Partita Iva Inserita non è valida !';
	if( pi.length != 11 )
		return "La lunghezza della partita IVA non è\n" +
			"corretta: la partita IVA dovrebbe essere lunga\n" +
			"esattamente 11 caratteri.\n";
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return "La partita IVA contiene un carattere non valido `" +
				pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
	}
	s = 0;
	for( i = 0; i <= 9; i += 2 )
		s += pi.charCodeAt(i) - '0'.charCodeAt(0);
	for( i = 1; i <= 9; i += 2 ){
		c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 )  c = c - 9;
		s += c;
	}
	if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
		return "La partita IVA non è valida:\n" +
			"il codice di controllo non corrisponde.\n";
	return "OK";
}

function ControllaPIVACEE(pi)
{
	if( pi == '' )  return '';

	if( pi.length > 12 )
		return "La lunghezza della partita IVA supera il limite consentito.";
	validi = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	for( i = 0; i < 12; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return "La partita IVA contiene un carattere non valido `" + pi.charAt(i);
	}
	return "OK";
	//cercare algoritmo di codifica di tutti i paesi EU
}


function DLD_MakeInvisible(aLayer) {
    // Rende invisibile un oggetto
    if ((objLayer = MM_findObj(aLayer)) != null) {
        if (objLayer.style) { objLayer = objLayer.style; }
        objLayer.display = 'none';
    }
}
   
function DLD_MakeVisible(aLayer){
    // Rende visubile un oggetto
	if ((objLayer=MM_findObj(aLayer))!=null) { 
		if (objLayer.style) {objLayer = objLayer.style; }
		objLayer.display = '';; 
	}
}
function DLD_ChangeStatus(aLayer){
    // Alterna la visibilità di un oggetto
	if ((objLayer=MM_findObj(aLayer))!=null) { 
		if (objLayer.style) {objLayer = objLayer.style; }
		objLayer.display = (objLayer.display =='none') ? '':'none'; 
	}
}
function DLD_ChangeClass(aObj,sClass1,sClass2){
    // Alterna la classe CSS di un oggetto
	if ((obj=MM_findObj(aObj))!=null) { 
		obj.className = (obj.className == sClass1) ? sClass2:sClass1; 
	}
}
function DLD_ChangeSrc(aImg,sImg1,sImg2){
    // Alterna l'immagine di un oggetto
	if ((obj=MM_findObj(aImg))!=null) { 
		obj.src = (obj.src.toUpperCase() == sImg1.toUpperCase()) ? sImg2:sImg1; 
	}
}
function MM_findObj(n, d) { //v4.01 Equivalente a getElementById

    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=MM_findObj(n,d.layers[i].document);

    if(!x && d.getElementById) 
        x=d.getElementById(n); 

    return x;
}


function CambiaStato(jID,iAbilitato)
{
    if (document.getElementById(jID) != null) 
    {
        if (iAbilitato == 1)
            document.getElementById(jID).disabled = false;
        else
            document.getElementById(jID).disabled = true;    
    }
}

function innerGet(id_elemento) {
 var elemento;
 if(document.getElementById)
    elemento = document.getElementById(id_elemento);
 else
    elemento = document.all[id_elemento];
 return elemento;
}

function OpenCalendario(jData,jsSO,jShowModal,sOpenerField,mostraOrario,iSoloDateFuture){

    if (isNaN(iSoloDateFuture)) iSoloDateFuture = 1

	var jHZoom = 98;
	var jWZoom = 260;

	var oParametri = new Object();
	    oParametri.jData = jData;
	    oParametri.sOpenerField = document.getElementById(sOpenerField);

	if (jShowModal == 1)
		{
		    oParametri.jShowModal = 1
			if (jsSO =='WINXP')
				jHZoom = jHZoom + 9;
			jHZoom = jHZoom + 75;
			
			window.showModalDialog('/calendario/calendario.asp?' + sOpenerField + '=' + jData + '&sOpenerField=' + sOpenerField + '&sjSM=1'+'&mostraOrario=' + mostraOrario + "&SoloDateFuture=" + iSoloDateFuture,oParametri,'dialogHeight:' + jHZoom + 'px; dialogWidth:' + jWZoom + 'px; status:no; resizable:yes; scroll: No; help: No');	
		}	
	else
		{   oParametri.jShowModal = 0
			jHZoom = jHZoom + 30;

			window.open('/calendario/calendario.asp?' + sOpenerField + '=' + jData + '&sOpenerField=' + sOpenerField + '&sjSM=0'+'&mostraOrario=' + mostraOrario + "&SoloDateFuture=" + iSoloDateFuture,'CALENDARIO','toolbar=no,menubar=no,scrollbars=no,resizable=yes,height=' + jHZoom + ',width=' + jWZoom + ',left=400, top=300');
		}	
}


//var myClip
//ciao=window.open("...htm","nomepagina",'toolbar=yes,scrollbars=yes'); 
function apriVideo(sUrl,sTarget,sStato)
{//sStato
//myClip = fullscreen=yesscrollbars=no

var VideoWin = window.open(sUrl,sTarget,sStato)
}

function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";



    if (tmpNumStr.indexOf(".") == -1)
        tmpNumStr = tmpNumStr + '.00';
    else
        {
          jLen=tmpNumStr.length;
          jDotPos = tmpNumStr.indexOf("."); 
          for(j=1; j<(jLen- jDotPos); j++)
            tmpNumStr = tmpNumStr + '0';
        }    
   

	return tmpNumStr;		// Return our formatted string!
}



function ValueValidation(entered, iMin, iMax, alertbox, datatype, bIsNull) 
{ 
    // Parametri opzionali: 
    // iMin: valore minimo consentito nel field. 
    // iMax: valore massimo consentito nel field. 
    // alertbox: testo per la casella di allarme se il contenuto è illegale. 
    // datatype: inserire 'I' se sono ammessi solo i numeri interi. 
    // bIsNull: true se è permesso il valore nullo 
    with (entered) 
    { 
        if (bIsNull)
        {
            if (value == "")
            {
                return;
            }    
        }
        
        checkvalue=parseFloat(value); 
        
        
        if (datatype) 
        { 
            smalldatatype=datatype.toLowerCase(); 
            if (smalldatatype.charAt(0)=="i") 
            {   
                checkvalue=parseInt(value); 
            } 
        } 
        
        if ((parseFloat(iMin) == iMin && checkvalue<iMin) || (parseFloat(iMax) == iMax && checkvalue>iMax) || value != checkvalue) 
        { 
            alert(alertbox); 
            entered.select();
        } 
    } 
}

function CheckValueValidation(entered, iMin, iMax, alertbox, datatype, bIsNull) { 
    // Parametri opzionali: 
    // iMin: valore minimo consentito nel field. 
    // iMax: valore massimo consentito nel field. 
    // alertbox: testo per la casella di allarme se il contenuto è illegale. 
    // datatype: inserire 'I' se sono ammessi solo i numeri interi. 
    // bIsNull: true se è permesso il valore nullo 
    with (entered) { 
        if (bIsNull){
            if (value == "") return true;
        }
        
        checkvalue = parseFloat(value); 
        
        if (datatype){ 
            smalldatatype = datatype.toLowerCase(); 
            if (smalldatatype.charAt(0) == "i") 
                checkvalue = parseInt(value); 
        } 
        
        if ((parseFloat(iMin) == iMin && checkvalue < iMin) || (parseFloat(iMax) == iMax && checkvalue > iMax) || value != checkvalue) { 
            alert(alertbox); 
            entered.select();
            return false;
        } else {
            return true;
        }
    } 
}

function gestisciQPUxQTAconVincolanteVendita82(obj, idRiga, iQPU, iVincolanteVendita) {
    if (CheckValueValidation(obj,0,99999,'Quantità inserita non valida.','i',false)){
        if (isNaN(iVincolanteVendita)) iVincolanteVendita = 1;
        if (obj.value < iVincolanteVendita){
            alert('La quantità inserita deve essere maggiore di ' + iVincolanteVendita);
            obj.value = iVincolanteVendita;
            MM_findObj('spQta_' + idRiga).innerHTML = iVincolanteVendita * iQPU;
            MM_findObj('qta_' + idRiga).value = iVincolanteVendita * iQPU;
            obj.focus();
            return false;
        } else {
            MM_findObj('spQta_' + idRiga).innerHTML = obj.value * iQPU;
            MM_findObj('qta_' + idRiga).value = obj.value * iQPU;
            return true;
        }
    } else {
        obj.value = iVincolanteVendita;
        MM_findObj('spQta_' + idRiga).innerHTML = iVincolanteVendita * iQPU;
        MM_findObj('qta_' + idRiga).value = iVincolanteVendita * iQPU;
        obj.focus();
        return false;
    }
}

function gestisciQPUxQTAconVincolanteVendita(obj, idRiga, iQPU, iVincolanteVendita) {
    if (CheckValueValidation(obj,0,99999,'Quantità inserita non valida.','i',false)){
        if (isNaN(iVincolanteVendita)) iVincolanteVendita = 1;
        if (obj.value % iVincolanteVendita != 0) {
            alert('La quantità inserita deve essere un multiplo di ' + iVincolanteVendita);
            obj.value = iVincolanteVendita;
            MM_findObj('spQta_' + idRiga).innerHTML = iVincolanteVendita * iQPU;
            MM_findObj('qta_' + idRiga).value = iVincolanteVendita * iQPU;
            obj.focus();
            return false;
        } else {
            MM_findObj('spQta_' + idRiga).innerHTML = obj.value * iQPU;
            MM_findObj('qta_' + idRiga).value = obj.value * iQPU;
            return true;
        }
    } else {
        obj.value = iVincolanteVendita;
        MM_findObj('spQta_' + idRiga).innerHTML = iVincolanteVendita * iQPU;
        MM_findObj('qta_' + idRiga).value = iVincolanteVendita * iQPU;
        obj.focus();
        return false;
    }
}

function checkVincolanteVendita82(obj, iVincolanteVendita) {
    if (obj.value < iVincolanteVendita) {
        alert('La quantità inserita deve essere maggiore di ' + iVincolanteVendita);
        obj.value = iVincolanteVendita;
        obj.focus();
        return false;
    }
}

function checkVincolanteVendita(obj, iVincolanteVendita) {
    if (obj.value % iVincolanteVendita != 0) {
        alert('La quantità inserita deve essere un multiplo di ' + iVincolanteVendita);
        obj.value = iVincolanteVendita;
        obj.focus();
        return false;
    } 
}

function changeCMBDisplay(e,sLocNome, iTipo){
//iTipo 1 = motore
//iTipo 2 = backorder
var evKCode = window.event ? e.keyCode : e.which;
if (evKCode == 13)
    {
    if (iTipo == 1)
        Cerca_Motore(0,4,'archivio.asp')
    if (iTipo == 2)
        SpeedBackorderSubmit()
    }
else
    if(evKCode != 38 &&  evKCode != 40)
        {
            var oTxt
            var oDivTxt
            var oCMB
            var oDivCMB
            oTxt = document.getElementById('InnerCombo_' + sLocNome + '_1');
            oDivTxt = document.getElementById('divInnerCombo_' + sLocNome + '_1');
            oCMB = document.getElementById('InnerCombo_' + sLocNome + '_2');
            oDivCMB = document.getElementById('divInnerCombo_' + sLocNome + '_2');



            if (oDivTxt.style.display=='none')
                {
                    oDivTxt.style.display='block';
                    oDivCMB.style.display='none';

                    oTxt.value=String.fromCharCode(evKCode);
                    
                    
                    oTxt.focus();
                }
            else
                 {
                    oDivTxt.style.display='none';
                    oDivCMB.style.display='block';
                    oCMB.focus();
                }    
        }
}

function  SetInnerCombo(e,sLocNome,sInitStr,iDeltaToSubmit){
var evKCode
var oTxt
var oDivTxt
var oCMB
var oDivCMB
//alert('hh')
oTxt = document.getElementById('InnerCombo_' + sLocNome + '_1') ;
oDivTxt = document.getElementById('divInnerCombo_' + sLocNome + '_1');
oCMB = document.getElementById('InnerCombo_' + sLocNome + '_2');
oDivCMB = document.getElementById('divInnerCombo_' + sLocNome + '_2');

var evKCode = window.event ? e.keyCode : e.which;


if (evKCode != 13)
    sStrTxt = oTxt.value + String.fromCharCode(evKCode);
else
    sStrTxt = oTxt.value;
iLensStrTxt = sStrTxt.length;
//alert('Len:' + iLensStrTxt + ' str:' + sStrTxt);

if ((evKCode == 13 && iLensStrTxt <= iDeltaToSubmit) || (iLensStrTxt == iDeltaToSubmit))
    {
        iLenInnerCmb = oCMB.length
        //alert(oCMB.options[3].text.substr(0,iLensStrTxt).toUpperCase())
        var bTrovato = 0

        for (I=0; I <iLenInnerCmb; I++)
            {
             if (sStrTxt.toUpperCase() == oCMB.options[I].text.substr(0,iLensStrTxt).toUpperCase())
                {
                    oCMB.selectedIndex = I;
                    oDivTxt.style.display='none';
                    oDivCMB.style.display='block';
                    I = iLenInnerCmb;
                    oCMB.focus();
                    bTrovato = 1
                }    

            }
        if (bTrovato == 0)
            {
            if (window.event)
                e.keyCode = 13;
            else
                e.which = 32;    
            oTxt.value=sInitStr;
            }
        //if(evKCode == 13 && iLensStrTxt == iDeltaToSubmit) 
        //    Cerca_Motore(0,4)
/*            {
            
            oO = oTxt;
                while(oO.tagName != 'FORM')
                    {
                        oO = oO.parentElement
                    }
                f = oO.name; 
                d = document[f];    
                d.submit();    
            
            
            }*/
    }        
else
    {
        if (oTxt.value == sInitStr || iLensStrTxt > iDeltaToSubmit-1)
            oTxt.value='';
    }    
}

function InsertCart(jId,sJForm,jLivello,jTipo,jErrore){
 f = sJForm; 
 d = document[f];

 prezzo = d['prz_' + jId].value.toString()
 jCLSID = d.CLSID.value;
 jCLSID_Anonimo = CLSID_Anonimo;
 re = /\,/g;
 prezzo = prezzo.replace(re, ".");
 //alert(parseFloat(prezzo));
d.quantita.value = d['qta_' + jId].value;
if (d['prz_' + jId].value == 'ND' || d['prz_' + jId].value == '' || d['prz_' + jId].value == 0 || parseFloat(prezzo) == 0)
	{
      if (jCLSID == jCLSID_Anonimo) 
		    alert('Attenzione\nNon si può inserire nel carrello un prodotto con prezzo non disponibile o nullo.\nPer visualizzare il prezzo occorre fare la logIn!');
      else
		    alert('Attenzione\nNon si può inserire nel carrello un prodotto con prezzo non disponibile o nullo.');     
	return
	}	
else	
	d.prezzo.value = d['prz_' + jId].value;
	//alert(d.prezzo.value);

d.id.value = jId;
if (d.quantita.value == '' || d.quantita.value == '0')
		alert('Attenzione\nOccorre inserire la quantità.');
else
	{    
		d.azione.value='INSERT_CART';
	    d.action = 'cart.asp';
	    d.myCurrentLink.value = "innerWeb('FRM_CART','_self','archivio.asp','iDet;iTipo;iLivello','" + jId + ";" + jTipo + ";" + jLivello + "')";
		d.submit();
	}
}

function InsertCart2(jId,sJForm,jLivello,jTipo,jUsoCarrello,jErrore,sErrore){
 f = sJForm; 
 d = document[f];

 d.target = "_self";
 
 prezzo = d['prz_' + jId].value.toString()
 jCLSID = d.CLSID.value;
 jCLSID_Anonimo = CLSID_Anonimo;
 re = /\,/g;
 prezzo = prezzo.replace(re, ".");
 //alert(parseFloat(prezzo));
d.quantita.value = d['qta_' + jId].value;
if (d['prz_' + jId].value == 'ND' || d['prz_' + jId].value == '' || d['prz_' + jId].value == 0 || parseFloat(prezzo) == 0)
	{
	  if (jErrore>0)
	        {    
	        alert(sErrore);
	        }
	  else
	    {	    
          if (jCLSID == jCLSID_Anonimo) 
		        alert('Attenzione\nNon si può inserire nel carrello un prodotto con prezzo non disponibile o nullo.\nPer visualizzare il prezzo occorre fare la logIn!');
          else
		        alert('Attenzione\nNon si può inserire nel carrello un prodotto con prezzo non disponibile o nullo.');     
		}        
	return
	}	
else	
	d.prezzo.value = d['prz_' + jId].value;
	//alert(d.prezzo.value);

d.id.value = jId;
if (d.quantita.value == '' || d.quantita.value == '0')
		alert('Attenzione\nOccorre inserire la quantità.');
else
	{    
	    switch(jUsoCarrello)
	        {
	            case 3:
	                d.azione.value=K_PREVENTIVO_CLIENTE_DEL_CLIENTE;
	                break;
	            default:    
		            d.azione.value='INSERT_CART';
		            break;
		     }       
	    d.action = 'cart.asp';
	    d.myCurrentLink.value = "innerWeb('FRM_CART','_self','archivio.asp','iDet;iTipo;iLivello','" + jId + ";" + jTipo + ";" + jLivello + "')";
		d.submit();
	}
}

function change_Action(jId, jCount, jR, jSR, jDet, jTipo, jRicRub,jLivello, jCOD, jMRC, jCAT, jQTA, jPRZ, jTXT, jAREA, jPROMO_PNEUS2000, jSTATO_ART, jSTATO_ART_DESC, jPagSelect, jChoose){

document.FE.quantita.value = document.FE['qta_' + jId + '_' + jCount].value;
mPrezzo = document.FE['prz_' + jId + '_' + jCount].value
if (mPrezzo == 'ND' || mPrezzo == '' || mPrezzo == 0)
	{
		alert('Attenzione\nNon si può inserire nel carrello un prodotto con prezzo non disponibile o nullo.');
		return
	}	
else
	document.FE.prezzo.value = mPrezzo;
	
document.FE.id.value = jId;

    if (document.FE.quantita.value == '' || document.FE.quantita.value == '0')
        alert('Attenzione\nOccorre inserire la quantità.');
    else
   {

    if (jChoose == K_AGGIUNGI_AL_CARRELLO)
        document.FE.azione.value='INSERT_CART';
    
    // Si tratta quindi di un inserimento nel preventivo B2C        
    else
        document.FE.azione.value = K_PREVENTIVO_CLIENTE_DEL_CLIENTE;
                
	document.FE.action = 'cart.asp';
	
	if (jR == "NULL")
	    jR = "";
	
	if (jSR == "NULL")
	    jSR = "";    
	    
	if (jDet == "NULL")
	    jDet = "";    
	    
	if (jTipo == "NULL")
	    jTipo = "";    
	    
	if (jRicRub == "NULL")
	    jRicRub = "";
	    
    if (jCOD == "NULL")
	    jCOD = "";
	    	    
    if (jMRC == "NULL")
	    jMRC = "";	    	    
	    
	if (jCAT == "NULL")
	    jCAT = "";	    
	    
    if (jQTA == "NULL")
	    jQTA = "";	    

    if (jPRZ == "NULL")
	    jPRZ = "";	    

    if (jTXT == "NULL")
	    jTXT = "";	    
	    	    	    
    if (jSTATO_ART == "NULL")
	    jSTATO_ART = "";	    	    	    	    	    	        
	
	if (jSTATO_ART_DESC == "NULL")
	    jSTATO_ART_DESC = "";	
	    
	document.FE.iStat.value=40;    
	
	//alert("jCOD=" + jCOD + " jMRC=" + jMRC + " jCAT=" + jCAT + " jQTA=" + jQTA + " jPRZ=" + jPRZ + " jTXT=" + jTXT + " jAREA=" + jAREA + " jPROMO_PNEUS2000=" + jPROMO_PNEUS2000 + " jSTATO_ART=" + jSTATO_ART);
	
	if ((jCOD != "") || (jMRC != "") || (jCAT != "") || (jQTA != "") || (jPRZ != "") || (jTXT != "") || (jAREA != 0) || (jPROMO_PNEUS2000 != 0) || (jSTATO_ART != "") || (jSTATO_ART_DESC != "")) 
	{   
	    sLBLPar = 'COD;MRC;CAT;QTA;PRZ;TXT;iTipo;AREA;bRicRub;PROMO_PNEUS2000;STATO_ART;STATO_ART_DESC;iPagSelect';
	    sPar = jCOD + ';' + jMRC + ';' + jCAT + ';' + jQTA + ';'+ jPRZ + ';' + jTXT + ';' + jTipo + ';' + jAREA + ';0;' + jPROMO_PNEUS2000 + ';' + jSTATO_ART + ';' + jSTATO_ART_DESC + ';' + jPagSelect;
	    document.FE.myCurrentLink.value = "innerWeb('FRM_CART','_self','archivio.asp','" + sLBLPar + "','" + sPar + "')";
	}
	else
	{
	    document.FE.myCurrentLink.value = "innerWeb('FRM_CART','_self','archivio.asp','iR;iSR;iDet;iTipo;bRicRub;iLivello;iPagSelect','" + jR + ";" + jSR + ";" + jDet + ";" + jTipo + ";" + jRicRub+ ";" + jLivello + ";" + jPagSelect + "')";
	}
	    
	document.FE.submit();
   }
}

function AJAX_change_Action(jId, jCount, jR, jSR, jDet, jTipo, jRicRub, jLivello, jCOD, jMRC, jCAT, jQTA, jPRZ, jTXT, jAREA, jPROMO_PNEUS2000, jSTATO_ART, jSTATO_ART_DESC, jPagSelect, jChoose) {

    document.FE.quantita.value = document.FE['qta_' + jId + '_' + jCount].value;
    mPrezzo = document.FE['prz_' + jId + '_' + jCount].value
    if (mPrezzo == 'ND' || mPrezzo == '' || mPrezzo == 0) {
        alert('Attenzione\nNon si può inserire nel carrello un prodotto con prezzo non disponibile o nullo.');
        return
    }
    else
        document.FE.prezzo.value = mPrezzo;

    document.FE.id.value = jId;

    if (document.FE.quantita.value == '' || document.FE.quantita.value == '0')
        alert('Attenzione\nOccorre inserire la quantità.');
    else {

        if (jChoose == K_AGGIUNGI_AL_CARRELLO) 
            document.FE.azione.value = 'INSERT_CART';

        // Si tratta quindi di un inserimento nel preventivo B2C        
        else
            document.FE.azione.value = K_PREVENTIVO_CLIENTE_DEL_CLIENTE;

        document.FE.action = 'cart.asp';

        if (jR == "NULL") jR = "";
        if (jSR == "NULL") jSR = "";
        if (jDet == "NULL") jDet = "";
        if (jTipo == "NULL") jTipo = "";
        if (jRicRub == "NULL") jRicRub = "";
        if (jCOD == "NULL") jCOD = "";
        if (jMRC == "NULL") jMRC = "";
        if (jCAT == "NULL") jCAT = "";
        if (jQTA == "NULL") jQTA = "";
        if (jPRZ == "NULL") jPRZ = "";
        if (jTXT == "NULL") jTXT = "";
        if (jSTATO_ART == "NULL") jSTATO_ART = "";
        if (jSTATO_ART_DESC == "NULL") jSTATO_ART_DESC = "";

        document.FE.iStat.value = 40;

        if ((jCOD != "") || (jMRC != "") || (jCAT != "") || (jQTA != "") || (jPRZ != "") || (jTXT != "") || (jAREA != 0) || (jPROMO_PNEUS2000 != 0) || (jSTATO_ART != "") || (jSTATO_ART_DESC != "")) {
            var lblArray = 'COD;MRC;CAT;QTA;PRZ;TXT;iTipo;AREA;bRicRub;PROMO_PNEUS2000;STATO_ART;STATO_ART_DESC;iPagSelect';
            var parArray = jCOD + ';' + jMRC + ';' + jCAT + ';' + jQTA + ';' + jPRZ + ';' + jTXT + ';' + jTipo + ';' + jAREA + ';0;' + jPROMO_PNEUS2000 + ';' + jSTATO_ART + ';' + jSTATO_ART_DESC + ';' + jPagSelect;
        }
        else {
            var lblArray = 'iR;iSR;iDet;iTipo;bRicRub;iLivello;iPagSelect';
            var parArray = '" + jR + ";" + jSR + ";" + jDet + ";" + jTipo + ";" + jRicRub + ";" + jLivello + ";" + jPagSelect + "';
        }

        AJAX_InserisciProdotto();
        AJAX_EvidenziaProdotti();
        
    }
}

function AJAX_CollectParams(biStat) {
    //fldNomiAttributi, fldValoriAttributi myRequest("fldNomiAttributi") myRequest("fldValoriAttributi")

    /*
    Costruisci un array con i paramatri che mi son utili per le chiamate AJAX.
    */
    var aParams = new Array();
    aParams.push('AZIONE=' + document.FE.azione.value);
    aParams.push('CLSID=' + document.FE.CLSID.value);
    aParams.push('CLSID2=' + document.FE.CLSID2.value);
    //        aParams.push('sLBL=' + lblArray);
    //        aParams.push('sVAL=' + parArray);
    aParams.push('catRuolo=' + document.FE.catRuolo.value);
    aParams.push('catRuoloCat=' + document.FE.catRuoloCat.value);
    aParams.push('iLng=' + document.FE.iLng.value);
    aParams.push('AREA=' + document.FE.AREA.value);
    aParams.push('TXT1=' + document.FE.TXT1.value);
    aParams.push('ID_AZIENDA=' + document.FE.ID_AZIENDA.value);
    aParams.push('ID_AZIENDA_2=' + document.FE.ID_AZIENDA_2.value);
    aParams.push('URL=' + document.FE.URL.value);
    aParams.push('bRuoloAlternativo=' + document.FE.bRuoloAlternativo.value)
    aParams.push('iSezione=' + document.FE.iSezione.value)
    if (biStat) aParams.push('iStat=' + document.FE.iStat.value);

    aParams.push('id=' + document.FE.id.value);
    aParams.push('quantita=' + document.FE.quantita.value);
    aParams.push('prezzo=' + document.FE.prezzo.value);

    /* ripropago gli attributi che per 82 sono obbligatori */
    var sLBL = document.FR_Header['sLBL'].value;
    var sVAL = document.FR_Header['sVAL'].value;

    var aLBL = sLBL.split(';');
    var aVAL = sVAL.split(';');
    var i;
    for (i = aLBL.length; i-- && aLBL[i] !== 'fldNomiAttributi'; );
    if (i >= 0){
        aParams.push('fldNomiAttributi=' + aVAL[i]);
        aParams.push('fldValoriAttributi=' + Url.encode(aVAL[i + 1]));
    }
    return aParams
}

function AJAX_InserisciProdotto() {
    /*
    Inserisco un prodotto nel carrello
    */
    var ajax = assegnaXMLHttpRequest();
    if (ajax) {

        // inizializzo la richiesta in post
        sUrl = 'LoadCart.asp?op=I&dummy=' + new Date().toString();
        ajax.open("post", sUrl, false);
        ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        ajax.send(AJAX_CollectParams(true).join('&'));

    } 
}

function AJAX_EvidenziaProdotti() {

    var sElenco = '';
    var ajax = assegnaXMLHttpRequest();
    if (ajax) {

        /* Aggiorno il contatore del link al carrello 
        sUrl = 'LoadCart.asp?op=C'
        ajax.open("post", sUrl, false);
        ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        ajax.send(AJAX_CollectParams().join('&'));
        alert('Hai ' + ajax.responseText + ' prodotti nel carrello.');
        */

        /* Aggiorno il contatore del link al carrello */
        sUrl = 'LoadCart.asp?op=L&dummy=' + new Date().toString();
        ajax.open("post", sUrl, false);
        ajax.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        ajax.send(AJAX_CollectParams(false).join('&'));
        sElenco = ajax.responseText;
    }
    var aElenco = sElenco.split('~');

    // Resetto tutti le icone dei carrelli dei prodotti che non sono più selezionati
    var prdList = document.getElementsByName('prdLst');
//    for (var objPrds in prdList) {
    for (var objPrds = 0; objPrds < prdList.length; objPrds++){
        var obj = MM_findObj('imgPrd' + prdList[objPrds].value);
        //var obj = MM_findObj('imgPrd' + prdList.item(objPrds).value)
        //var obj = MM_findObj('imgPrd' + objPrds.value)
        if (obj) {
            if (obj.src != obj.getAttribute('srcNoSel')) {
                obj.src = obj.getAttribute('srcNoSel');
                var objQta = MM_findObj('qta_' + prdList[objPrds].value + '_' + (parseInt(objPrds) + 1));
//                var objQta = MM_findObj('qta_' + prdList.item(objPrds).value + '_' + (parseInt(objPrds) + 1));
                if (objQta) objQta.className = objQta.getAttribute('classNoSel');
             }
        }
    }

    // Estraggo da sLBL e sVAL gli attributi
    var aLBL = document.FR_Header['sLBL'].value.split(';');
    var aVAL = document.FR_Header['sVAL'].value.split(';');
    var sNoteMotore = '';
    var sfldNomiAttributi = '';
    var sfldValoriAttributi = '';
    var i;
    for (i = aLBL.length; i-- && aLBL[i] !== 'fldNomiAttributi'; );
    if (i >= 0) {
        // se ho trovato gli attributi allora procedo con l'estrazione del primo e del secondo attributo
        sfldNomiAttributi = aVAL[i];
        sfldValoriAttributi = aVAL[i + 1];

        var sNomeCampo = ''
        var sValoreCampo = ''
        
        // Dal nome del primo attributo risalgo all'oggetto che lo contiene
        sNomeCampo = MM_findObj(sfldNomiAttributi.split('$')[0]).options[0].text;
        // Normalizzo il nome esposto (options[0])
        sNomeCampo = sNomeCampo.replace(' ', '_');
        sNomeCampo = sNomeCampo.replace(' ', '_');
        // Normalizzo il valore
        sValoreCampo = sfldValoriAttributi.split('$')[0];
//        sValoreCampo = sValoreCampo.replace(' ', '');
//        sValoreCampo = sValoreCampo.replace(' ', '');
        sNoteMotore = sNomeCampo + '=' + sValoreCampo;

        // Dal nome del secondo attributo risalgo all'oggetto che lo contiene
        sNomeCampo = MM_findObj(sfldNomiAttributi.split('$')[1]).options[0].text;
        sNomeCampo = sNomeCampo.replace(' ', '_');
        sNomeCampo = sNomeCampo.replace(' ', '_');
        // Normalizzo il nome valore
        sValoreCampo = sfldValoriAttributi.split('$')[1].replace(' ', '');
        sValoreCampo = sValoreCampo.replace(' ', '');
        sValoreCampo = sValoreCampo.replace(' ', '');
        
        // Ottengo quello che sarebbe il campo "note" nel carrello se inserissi il prodotto ora.
        sNoteMotore = sNoteMotore + ';' + sNomeCampo + '=' + sValoreCampo + ';';
    }

//    for (var prds in aElenco) {
    for (var prds = 0; prds < aElenco.length; prds++) {
        // Dall'elenco appena ottenuto estraggo l'id del prodotto ed il campo note
            var sObj = aElenco[prds].split('|')[0];
            var sNote = aElenco[prds].split('|')[1];
            var obj = MM_findObj('imgPrd' + sObj);
            if (obj && sNote == sNoteMotore)
                if (obj.src != obj.getAttribute('srcSel')) {
                obj.src = obj.getAttribute('srcSel');

                // Devo salire nel DOM per poi ridisendere nel td precedente
                var o = obj.parentNode.parentNode;
    /*
                do o = o.nextSibling;
                while (o && o.nodeType != 1);
    */
                do o = o.previousSibling;
                while (o && o.nodeType != 1);

                o = o.firstChild;

                if (o.nodeType != 1)
                    do o = o.nextSibling;
                    while (o && o.nodeType != 1);
                
                //var objQta = obj.parentNode.parentNode.previousObject.previousObject.firstChild.nextObject;  //che incubo!
                
                objQta = o            
                
                if (objQta) {
                    if (objQta.getAttribute('classSel')) {
                        objQta.className = objQta.getAttribute('classSel');
                    } 
                }
            }
        }
}

function InsertCampagna(jId_Campagna, jNumProdotti)
{
    strQta = ""
    strIdPrd = ""
    strCampagna = ""
    
    for (i=1; i <= jNumProdotti; i++)
    {
        strIdPrd = strIdPrd + document.FE['idPrd_' + jId_Campagna + '_' + i].value + ";"
        strQta_Prd = document.FE['qta_' + jId_Campagna + '_' + i].value * document.FE['qta_Campagna'].value
        strQta = strQta + strQta_Prd + ";"
        
        //strCampagna = strCampagna + document.FE['bCampagna_' + jId_Campagna + '_' + i].value + ";"
        
    }

    //alert(strQta);
    //alert(strIdPrd);
    //alert(strCampagna);
    
    document.FE.quantita.value = strQta;
    document.FE.prezzo.value = "";
	document.FE.id.value = strIdPrd;
    document.FE.id_Campagna_Prd.value = jId_Campagna;    
    
    document.FE.azione.value = 'INSERT_MULTI_CART';
	document.FE.action = 'cart.asp';
	document.FE.id_CarrelloCampagna.value = jId_Campagna;
	document.FE.iStat.value = 45;    
	document.FE.myCurrentLink.value = "innerWeb('FRM_CART','_self','campagne.asp','','')";
	    
	document.FE.submit();
}

function CercaStatoArticolo(p, jTipo, jStatoArticolo, sForm)
{
    f = sForm; 
    d = document[f];
					
	//sLBLPar = 'iTipo;iStatoArticolo';
    //sPar = jTipo + ';' + jStatoArticolo
    
    //innerWeb(f, '_self', 'archivio.asp', sLBLPar, sPar);
    
   
    if (p>0)
	   sLBLPar = 'COD;MRC;CAT;QTA;PRZ;TXT;iTipo;iPagSelect;AREA;bRicRub;PROMO_PNEUS2000;STATO_ART;STATO_ART_DESC';
	else
	   sLBLPar = 'COD;MRC;CAT;QTA;PRZ;TXT;iTipo;AREA;bRicRub;PROMO_PNEUS2000;STATO_ART;STATO_ART_DESC';  
			   
	if (p > 0)
	{ 
		sPar = '' + ';' + '' + ';' + '' + ';' + '' + ';'+ '' + ';' + '' + ';' + jTipo + ';'+ p + ';' + '' + ';0;' + '' + ';' + jStatoArticolo + ';' + ''
	}
	else
	{ 
        sPar = '' + ';' + '' + ';' + '' + ';' + '' + ';'+ '' + ';' + '' + ';' + jTipo + ';' + '' + ';0;' + '' + ';' + jStatoArticolo + ';' + ''
        
	}   
	
    //sLBLPar = 'COD;MRC;CAT;QTA;PRZ;TXT;iTipo;bRicRub;PROMO_PNEUS2000;STATO_ART;STATO_ART_DESC';
	//sPar = '' + ';' + '' + ';' + '' + ';' + '' + ';'+ '' + ';' + '' + ';'+ jTipo + ';0;' + '' + ';' + jStatoArticolo + ';' + ''
			   
	innerWeb(f,'_self','/archivio.asp',sLBLPar, sPar);
	
}

function CercaArticoloSpeciale(sForm){
    f = sForm; 
    d = document[f];
    
    sLBLPar = "COD;MRC;CAT;QTA;PRZ;TXT;iTipo;AREA;bRicRub;PROMO_PNEUS2000;STATO_ART;STATO_ART_DESC_ArticoloSpeciale;TIPOLOGIA;RIC_AGGIUNTIVA;RicercaBarcode";
    sPar = "Codice;;NULL;1;;Testo;4;;0;0;;S;;1;1"
//    sPar = "Codice;;NULL;0;;Testo;4;;0;0;;S;;1;1"
    		   
	innerWeb(f,'_self','/archivio.asp',sLBLPar, sPar);
}

function PrintArchivio(jDet, jTipo, sForm)
{
    //f = sForm; 
    //d = document[f];
    window.open("archivio.asp?iDet=" + jDet + "&bIsStampa=1&iTipo=" + jTipo + "&iLng=" + iLng);
    //d.action = "archivio.asp?iDet=" + jDet + "&bIsStampa=1&iTipo=" + jTipo + "&iLng=" + "<%=iLng%>"
	//d.target = "_new";
	
	//d.submit();

}  

function CheckMinHeight(sMinHeight)
{
    var altezza = window.screen.height;
    var larghezza = window.screen.width;
    
    if (document.getElementById("MnuSinistra") != null)
    {
        if ((larghezza == 800) && (altezza == 600))
        {
            if ((sMinHeight != null) && (sMinHeight.indexOf(";") > -1))
            {
                sHeight800x600 = sMinHeight.substr(0, sMinHeight.indexOf(";"));
                //sHeightAltro = sMinHeight.substr(sMinHeight.indexOf(";") + 1, sMinHeight.length);
            }
            else
            {
                sHeight800x600 = "0"
                //sHeightAltro = "0"
            }
        
            document.getElementById("MnuSinistra").style.height = sHeight800x600 + "px"
        }
        //else
        //{
        //    document.getElementById("MnuSinistra").style.height = sHeightAltro + "px"
        //}    
    }    
} 

function innerFormat(sNum)
{
	
	var nf = new NumberFormat(sNum);
	
    nf.setSeparators(true, nf.PERIOD, nf.COMMA);
    //alert(nf.toFormatted());
    return nf.toFormatted();
    //document.forms[0].txtTryIt.value = innerFormat;
    
}

function goToLogIn()
 {
    
    document.location="../login.asp"; 
 }   
 
function strToArray (sStr){
 var lbl = new Array();
 var s = '';
 var c = 0;
 
  for (iCh = 0; iCh < sStr.length; iCh++)
      {
        ss = sStr.substr(iCh, 1); 
        if (ss == ';')
           {
            lbl[c] = s;
            s = '';
            c++;
           }  
        else
           {
            s = s + ss; 
           }   
      
      }
  return lbl
}  

function innerWeb(frm,sTarget,sUrl,lblArray,parArray){
 f = frm; 
 d = document[f];
  
 var aLbl;
 var aPar;
 
 d.sLBL.value=lblArray;
 d.sVAL.value=parArray; 
 
 d.action=sUrl;
 
 if (top.length != 0)
    {
    d.target= "_top"
    }
 else
    {
	d.target= sTarget;   
    }
 d.submit();
}  

function IW(frm,sTarget,sUrl){
 f = frm; 
 d = document[f];
 d.action=sUrl;
 d.target= sTarget
 d.submit();
 
}  

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

var data;

function dateAdd(date, tipo, valore) {
	(typeof(date)=="number") ? 1==1 : data = new Date(date.getFullYear(),date.getMonth(),date.getDate(),date.getHours(),date.getMinutes(),date.getSeconds(),0);
	
	switch(tipo) {
		case "s":
			si = div(data.getSeconds() + valore, 60);
			s = (data.getSeconds() + valore) % 60;
			si ? addInterval(data.setSeconds(s), "m", si) : data.setSeconds(s);
			break;    
		case "m":
			mi = div(data.getMinutes() + valore, 60);
			m = (data.getMinutes() + valore) % 60;
			mi ? addInterval(data.setMinutes(m), "h", mi) : data.setMinutes(m);
			break;
		case "h":
			hi = div(data.getHours() + valore, 24);
			h = (data.getHours() + valore) % 24;
			hi ? addInterval(data.setHours(h), "dd", hi) : data.setHours(h);
			break;
		case "dd":
			mod = getDaysInMonth(data);
			ddi = div(data.getDate() + valore, mod);
			dd = (data.getDate() + valore) % mod;
			ddi ? addInterval(data.setDate(dd), "mm", ddi) : data.setDate(dd);
			break;
		case "mm":
			mmi = div(data.getMonth() + valore, 12);
			mm = (data.getMonth() + valore) % 12;
			mmi ? addInterval(data.setMonth(mm), "yy", mmi) : data.setMonth(mm);
			break;
		case "yy":
			yy = (data.getFullYear() + valore);
			data.setFullYear(yy);
			break;
		default:
	}
	return data;
}

function getDaysInMonth(aDate){
    var m = new Number(aDate.getMonth());
    var y = new Number(aDate.getYear());

    var tmpDate = new Date(y, m, 28);
    var checkMonth = tmpDate.getMonth();
    var lastDay = 27;

    while(lastDay <= 31){
        temp = tmpDate.setDate(lastDay + 1);
        if(checkMonth != tmpDate.getMonth())
            break;
        lastDay++
    }
    return lastDay;
}

function div(op1, op2) {
  return (op1 / op2 - op1 % op2 / op2)
}

function CKJString(s) {
    //alert(s.replace(/[\']/g, "'"));
    if (s.length == 0)
        return '';
    else    
        return s.replace(/[\']/g, "'");
}

function CKJInt(s) {
    //alert(s.replace(/[\']/g, "'"));
    return s.replace(/[.]/g, "");
}

function CKJDecimal(s) {
    //alert(s.replace(/[\']/g, "'"));
    s = s.replace(/[.]/g, "");
    return s.replace(/[,]/g, ".");
}

function CKJMoney(s) {
    //alert(s.replace(/[\']/g, "'"));
	s=s.toString();
    s=s.replace(/[€. ]/g, "");
    s=s.replace(/[.]/g, "");
    return s.replace(/[,]/g, ".");
}
function CKJBit(s)
{
	var iRet = '0';
	if (s)
		iRet='1';
	//alert(iRet);
	return iRet;
}
function CKJDate(s) {
    var aData;
    var aTime;
    if (s.indexOf(' ') >= 0)  // se c'è uno spazio
    {
        aData = sCurVal.split(' ')[0];
        aTime = sCurVal.split(' ')[1];

        if (isNaN(aData.split('/')[2]) || isNaN(aData.split('/')[0]) || isNaN(aData.split('/')[1]) || isNaN(aTime.split('.')[0]) || isNaN(aTime.split('.')[1]) || isNaN(aTime.split('.')[2])) {
            return '';
        }
        
        return  aData.split('/')[2] + '-' + aData.split('/')[0] + '-' + aData.split('/')[1] + ' ' + aTime.split('.')[0] + ':' + aTime.split('.')[1] + ':' + aTime.split('.')[2];
    }
    else {
        if (isNaN(s.split('/')[2]) || isNaN(s.split('/')[0]) || isNaN(s.split('/')[1])) {
            return '';
        }
        
        return s.split('/')[2] + '-' + s.split('/')[0] + '-' + s.split('/')[1];
    }
    
    

}

function CKGruppi(jCount, ck_Name) {
    f = "frmDettaglio";
    d = document[f];
alert('sono qui')
    for (j = 1; j <= jCount; j++) {
        //alert('field_GDL_CK_' + j);
        if (d[ck_Name].checked)
            d['field_GDL_CK_' + j].disabled = false;
        else
            d['field_GDL_CK_' + j].disabled = true;
    }


}


function isInCombo(sValue, oCombo) {
    
    var bRet = false;
    var sComboValue;
    sValue=sValue.toUpperCase();
    for (nA = 0; nA < oCombo.length; nA++) {
        sComboValue = oCombo[nA].value.toUpperCase();
        //alert(sComboValue + ' == ' + sValue);
        if ((sComboValue == sValue) || (sComboValue == '[' + sValue + ']') || ('[' + sComboValue + ']' == sValue)) {
            bRet = true;
            break;
        }
    }
    return bRet;
    
}

function PopUp_ScegliLink(iTab, sTabella, sField, myId, bFromAJAX, bNoEditor) {
    h = parseInt(self.window.screen.height / 2) - 55
    w = parseInt(self.window.screen.width / 2) - 200

    myWin = window.open('Link.asp?bNoEditor=1&st=0&id=' + myId + '&iTab=' + iTab + '&sField=' + sField + '&Tab=' + sTabella + '&bFromAJAX=1', 'AddRec', 'toolbar=no,menubar=no,scrollbars=no,resizable=yes,left=' + w + ',top=' + h + ',height=110,width=525');
}

function PopUp_UpLoadFile(iTab, sTabella, sField, myId, bFromAJAX) {
    h = parseInt(self.window.screen.height / 2) - 55
    w = parseInt(self.window.screen.width / 2) - 200

    myWin = window.open('popUp.asp?st=2&id=' + myId + '&iTab=' + iTab + '&sField=' + sField + '&Tab=' + sTabella + '&bFromAJAX=1', 'AddRec', 'toolbar=no,menubar=no,scrollbars=no,resizable=yes,left=' + w + ',top=' + h + ',height=110,width=400');
}
