/**
-------------------------------------------------------
VARIABILI GLOBALI JAVASCRIPT
-------------------------------------------------------
**/
//definisco il delimitatore per elenco negozi Card
var delimiter = ",";

//definizione di stile per visibilità true/false
var bStile = true

//definizione primo passaggio per storico Card
var bPrimoPassaggio = true

/**
-------------------------------------------------------
OPENSTORICO(strURL)
-------------------------------------------------------
**/
function OpenStorico(strURL){
	window.document.location.href = strURL
}
	
/**
-------------------------------------------------------
APRITOTALI(anno)
-------------------------------------------------------
**/
function ApriTotali(anno){
	var width = screen.width - 100;
	var height = Math.round(screen.height / 3);
	window.open('/Riepilogo_Totali.asp?anno='+anno,'totaliBCC','scrollbars=no,resizable=no,width=' + width + ',height=' + height + ',left=50,top=50');
}

/**
-------------------------------------------------------
APRIBUDGETGENERALE(anno)
-------------------------------------------------------
**/
function ApriBudgetGenerale(anno){
	var width = screen.width - 100;
	var height = screen.height - 200;
	window.open('/Riepilogo_Budget.asp?anno='+anno,'TotaliBCC','scrollbars=yes,resizable=yes,width=' + width + ',height=' + height + ',left=50,top=50');
}

/**

-------------------------------------------------------
ApriBudgetLimiteSconto
-------------------------------------------------------
**/
function ApriBudgetLimiteSconto()
{
	window.open('riepilogo_limite_sconto.asp', 'TotaliSconto', 'scrollbars=no, resizable=no, width=720, height=300, left=100, top=100');
}
/**
-------------------------------------------------------
APRIINFO(intTipo)
-------------------------------------------------------
**/
function ApriInfo(intTipo){
	window.open('/card_info.asp?intTipo='+intTipo,'Info','scrollbars=yes,resizable=yes,width=300,height=200,left=100,top=100');
}
/**
-------------------------------------------------------
APRIINFOPAGINA(intTipo)
-------------------------------------------------------
**/

function ApriInfoPagina(intTipo){
    var x=screen.width;
    var y=screen.height;
    var hx=x/2;
    var hy=y/2;
    var a=600; //Inserire i valori per il resize
    var b=600; //della finestra popup 
    var ha=a/2;
    var hb=b/2;
    var dx=hx-ha;
    var dy=(hy-hb)-20;

	window.open('/card_info.asp?intTipo='+intTipo+'&infoPagina=True','Info','scrollbars=yes,resizable=yes,width=600,height=200,left='+dx+',screenX='+dx+',top=100,screenY=100');
}
/**
-------------------------------------------------------
APRIINFOEX(FuncId, ProgIdMsg)
-------------------------------------------------------
**/
function ApriInfoEx(FuncId, ProgIdMsg)
{
	window.open('/card_info.asp?intTipo=100&idMsg=' + ProgIdMsg + '&FuncId=' + FuncId, 'Info', 'scrollbars=yes,resizable=yes,width=300,height=200,left=100,top=100');
}

/**
-------------------------------------------------------
APRIINFOPARAM(FuncId, ProgIdMsg, w, h)
-------------------------------------------------------
**/
function ApriInfoParam(FuncId, ProgIdMsg, parametri, w, h)
{
	window.open('/card_info.asp?'+parametri+'&idMsg=' + ProgIdMsg + '&FuncId=' + FuncId, 'Info', 'scrollbars=yes,resizable=yes,width='+w+',height='+h+',left=100,top=100');
}
/**
-------------------------------------------------------
APRIINFOEX2(InfoType, ValuePar1, ValuePar2)
-------------------------------------------------------
**/
function ApriInfoEx2(InfoType, ValuePar1, ValuePar2)
{
	window.open('card_info.asp?intTipo=' + InfoType + '&ValuePar1=' + ValuePar1 + '&ValuePar2=' + ValuePar2, 'Info', 'scrollbars=yes,resizable=yes,width=400,height=250,left=100,top=100');
}

/**
-------------------------------------------------------
APRIMULTIFLUSSO(intTipo) Questa funzione è da eliminare quando sarà tutto ok sulla versione II
-------------------------------------------------------
**/
function ApriMultiFlusso(){
	window.open('card_popupMultiFlusso.asp?BitPrivilegio=4','multiflusso','scrollbars=yes,resizable=yes,width=800,height=600,left=100,top=100');
}

/**
-------------------------------------------------------
APRIMULTIFLUSSOII(intTipo)
-------------------------------------------------------
**/
function ApriMultiFlussoII(){
	/** 
		Modificato per passare un titolo diverso per ogni pulsante
		al popup multiflusso. S.T. 03-07-2007
	**/
	if (document.getElementById("titoloPopupMultiflussoId").value){
		parametro = '?titolo=' + document.getElementById("titoloPopupMultiflussoId").value;
	}
	window.open('card_popupMultiFlusso_II.asp'+ parametro,'multiflusso','scrollbars=yes,resizable=yes,width=600,height=600,left=100,top=100');
}

/**
-------------------------------------------------------
APRIMULTIFLUSSOCASH(intTipo)
-------------------------------------------------------
**/
function ApriMultiFlussoCash(){
	//window.open('card_popupMultiFlussoCash.asp','multiflussocash','scrollbars=yes,resizable=yes,width=600,height=600,left=100,top=100');
	window.open('card_popupMultiFlusso.asp?BitPrivilegio=2','multiflussocash','scrollbars=yes,resizable=yes,width=600,height=600,left=100,top=100');
}

/**
-------------------------------------------------------
APRIMULTIFLUSSOCREDIT(intTipo)
-------------------------------------------------------
**/
function ApriMultiFlussoCredit(){
	window.open('card_popupMultiFlussoCredit.asp','multiflussocredit','scrollbars=yes,resizable=yes,width=600,height=600,left=100,top=100');
}

/**
-------------------------------------------------------
InfoChiavi(intInfo)
-------------------------------------------------------
**/
function InfoChiavi(IDGruppo){
	window.open('card_info.asp?intTipo=3&IDGruppo='+IDGruppo,'Info','scrollbars=yes,resizable=yes,width=300,height=150,left=100,top=100');
}


function postAction(whichPage)
{
	document.forms[0].action = whichPage;
	document.forms[0].submit();
}

/**
-------------------------------------------------------
ApriPromozione()
-------------------------------------------------------
**/
function ApriPromozione(bBase, IdPromozione, Sconto, MaxImporto, ValoreSconto, StartDateDiscount, EndDateDiscount) {
    var doPost, idPromotionAsPromoter;

    //alert('IdPromozione=' + IdPromozione);
    //alert('IdPostByPromotion=' + document.getElementById("IdPostByPromotion").value);

    /** deve rimanere per gestire la promozione Prima spendi meno spendi (idpromozione = 95)**/
    if (!bBase) {
        if (document.forms[0].ScontoBase.value == "" || document.forms[0].Sconto.value == "") {
            Sconto = "";
        }
        else {
            Sconto = eval(eval(document.forms[0].Sconto.value) + eval(document.forms[0].ScontoBase.value))
        }
    }
    
    //--AGL 2011/03/15
    //  Se la promozione che è stata scelta è una di quelle che necessita chiavi di attivazioni
    // "Scarico" gli eventuali controlli già renderezzati
    if (document.getElementById("divCodAttPrivilegioGiaUtilizzato"))
        document.getElementById("divCodAttPrivilegioGiaUtilizzato").innerHTML = "";

    if (document.getElementById("TxtCodAttivazionePriv"))
        document.getElementById("TxtCodAttivazionePriv").value = "";


    //  Devo fare in modo che nella card_discount venga visualizzato il blocco di codice che ne gestisce l'utilizzo
    if (renderCodiceAttivazione(IdPromozione)) {
        document.getElementById("abilitaCodiceAttivazionePriv").value = "1";
        doPost = true;
        if (document.getElementById("IdPostByPromotion")) {
            if (document.getElementById("IdPostByPromotion").value == 0) {
                doPost = true;
                document.getElementById("IdPostByPromotion").value = 1;
            }
            else
                doPost = false;
        }

        if (doPost)
            postAction("card_master.asp?ACTION=Privilegi");
    }

    if (document.getElementById("IdIdPromotionAsPromoter"))
        idPromotionAsPromoter = document.getElementById("IdIdPromotionAsPromoter").value;
    else
        idPromotionAsPromoter = -1;

    //Caso Promoter
    if (document.getElementById("SelDescrDiscount").value == idPromotionAsPromoter) {
        doPost = true;
        if (document.getElementById("IdPostByPromotion")) {
            if (document.getElementById("IdPostByPromotion").value == 0) {
                doPost = true;
                document.getElementById("IdPostByPromotion").value = 1;
            }
            else
                doPost = false;
        }

        if (doPost == true)
            postAction("card_master.asp?ACTION=Privilegi");
    }
    else //Caso No Promoter
    {
        if (!renderCodiceAttivazione(IdPromozione)) {
            document.getElementById("abilitaCodiceAttivazionePriv").value = "0";
            doPost = false;
            if (document.getElementById("IdPostByPromotion"))
                if (document.getElementById("IdPostByPromotion").value == 1) {
                doPost = true;
                document.getElementById("IdPostByPromotion").value = 0;
            }
            if (doPost == true)
                postAction("card_master.asp?ACTION=Privilegi");
        }
    } //Fine caso No Promoter

    if (IdPromozione == "95" && Sconto != "" && MaxImporto != "") {
        if (confirm("Confermi apertura promozione ?")) {
            if (document.getElementById("popupIFrameTR")) {
                document.getElementById("popupIFrameTR").className = "hideLoading";
                document.getElementById("popupIFrameTD").className = "hideLoading";
                document.getElementById("popupIFrame").className = "hideLoading";
                document.getElementById("popupIFrame").src = "";
            }

            if (document.forms[0].Descrizione)
                document.forms[0].Descrizione.disabled = false;

//            if (document.forms[0].SelDescrDiscount)
//                document.forms[0].SelDescrDiscount.disabled = true;

			if (document.forms[0].txtDescSconto)
                document.forms[0].txtDescSconto.disabled = false;

            var startDate = "";
            var endDate = "";

            document.forms[0].StartDateDiscount.value = startDate;
            document.forms[0].EndDateDiscount.value = endDate;

            var varStep = 1;
            if (document.forms[0].Step)
                varStep = document.forms[0].Step.value;


            if (!bBase) {
                CheckFormPromozione(false, document.forms[0]);
                window.open('card_discount_promozione.asp?Sconto=' + Sconto + '&MaxImporto=' + MaxImporto + '&ValoreSconto=' + ValoreSconto + '&StartDateDiscount=' + StartDateDiscount + '&EndDateDiscount=' + EndDateDiscount + '&step=' + varStep, 'Promozione', 'scrollbars=yes,resizable=yes,width=650,height=450,left=100,top=100');
            }
            else {
                var descrizionePromozione = "PIU SPENDI MENO SPENDI ON LINE";
                if (document.forms[0].Descrizione.value != descrizionePromozione)
                    document.forms[0].Descrizione.value = descrizionePromozione;
                window.open('card_discount_promozione.asp?Sconto=' + Sconto + '&MaxImporto=' + MaxImporto + '&ValoreSconto=' + ValoreSconto + '&StartDateDiscount=' + StartDateDiscount + '&EndDateDiscount=' + EndDateDiscount + '&step=1', 'Promozione', 'scrollbars=yes,resizable=yes,width=650,height=450,left=100,top=100');
            }
        }
        else {

            IdPromozione = "0";

            document.forms[0].Descrizione.value = "Non disponibile";
            document.forms[0].Descrizione.disabled = true;
//            document.forms[0].SelDescrDiscount.disabled = false;
			document.forms[0].txtDescSconto.disabled = false;
            document.forms[0].Sconto.value = "";
            document.forms[0].ValoreSconto.value = "";
            document.forms[0].ValoreSconto2.value = "";
            document.forms[0].MaxImporto.value = "";
            document.forms[0].NChiavi.value = "1";
            document.forms[0].NPersone.value = "1";
            document.forms[0].StartDateDiscount.value = "";
            document.forms[0].EndDateDiscount.value = "";

            document.forms[0].ScontoPromozione.value = "";
            document.forms[0].TettoPromozione.value = "";
            document.forms[0].TipoPromozione.value = "";
            document.forms[0].AttivaPromozione.value = "0";

        }
    }
    else {

        if (IdPromozione == "95") {

            alert("Devi inserire la percentuale di sconto e il tetto di spesa!");
            Obj.value = "0";

        }
        else {
            //in data 24/07/2006 nuova gestione con ajax
            caricaPromozioneAjax();
        }
    }
}

function checkCodiceAttivazPriv(codAttivazione) {
    var xmlhttp;
    var idpromozione = 0;
    if (document.getElementById("SelDescrDiscount").value == "0")
        idpromozione = document.getElementById("SelExtraDiscount").value;
    else
        idpromozione = document.getElementById("SelDescrDiscount").value;

    if (idpromozione == 0) {
        document.getElementById("divCodAttPrivilegioGiaUtilizzato").innerHTML = "";
        return;
    }

    var idcarta = document.getElementById("IDCarta").value;
        
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "/res/codAttivazionePrivilegio.asp?codAtt=" + codAttivazione + "&idpromo=" + idpromozione + "&idcarta=" + idcarta, false);
        xmlhttp.send();

        //xmlhttp.onreadystatechange = function() {
            if (xmlhttp.status == 200) {
                document.getElementById("divCodAttPrivilegioGiaUtilizzato").innerHTML = xmlhttp.responseText;
                if (xmlhttp.responseText != "")
                    document.getElementById("BtnCreaPrivilegiBC").disabled = true;
                else
                    document.getElementById("BtnCreaPrivilegiBC").disabled = false;
            }
        //} 

    }
    else {// code for IE6, IE5
        xmlhttp = getXMLHttpRequest();
        xmlhttp.open("GET", "/res/codAttivazionePrivilegio.asp?codAtt=" + codAttivazione + "&idpromo=" + idpromozione + "&idcarta=" + idcarta, false);
        xmlhttp.send(null);
        if (xmlhttp.responseText != "") {
            document.getElementById("divCodAttPrivilegioGiaUtilizzato").innerHTML = xmlhttp.responseText;
            document.getElementById("BtnCreaPrivilegiBC").disabled = true;
        }
        else {
            document.getElementById("divCodAttPrivilegioGiaUtilizzato").innerHTML = '';
            document.getElementById("BtnCreaPrivilegiBC").disabled = false;
        }
    }


}

var bRender = false;
function renderCodiceAttivazione(idpromozione) {
    var xmlhttp;
    
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", "/res/codAttivazionePrivilegio.asp?idp=" + idpromozione, false);
        xmlhttp.send();
        if (xmlhttp.status == 200) {
            if (xmlhttp.responseText == "render")
                bRender = true;
            else
                bRender = false;
        } 
    }
    else {// code for IE6, IE5
        xmlhttp = getXMLHttpRequest(); //new ActiveXObject("MSXML2.XMLHTTP.3.0"); //ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.open("GET", "/res/codAttivazionePrivilegio.asp?idp=" + idpromozione, false);
        xmlhttp.send(null);
        if (xmlhttp.responseText == "render") {
            bRender = true;
        }
        else {
            bRender = false;
        }
    }
    
    return bRender;
}


function getXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP");
        }
        catch (ex) {
            return null;
        }
    }
}


/**
-------------------------------------------------------
CONTROLLO DIMENSIONI TEXTAREA
-------------------------------------------------------
**/
function CheckTextAreaDimesioni(TheForm, TheObject,TheDimension){
	if (TheObject.value.length >= TheDimension) {
		alert("Max " + TheDimension + " caratteri !")
		TheObject.value = TheObject.value.substr(0,TheDimension);
	}
}

/**
-------------------------------------------------------
GESTIONE PAGINAZIONE
-------------------------------------------------------
**/
function avanti(whichpage,strpage){
	if (document.forms[0].SelRicerca)
		if ((document.forms[0].SelRicerca.value == "IDCASH") || (document.forms[0].SelRicerca.value == "IDDISCOUNT")  )
			document.forms[0].SelRicerca.value = "NIDCARTA";
	document.forms[0].whichpage.value = whichpage;
	document.forms[0].action = strpage
	document.forms[0].submit();
}

/**
-------------------------------------------------------
GESTIONE PAGINAZIONE PRIVILEGI
-------------------------------------------------------
**/
function avantiPrivilegi(whichpage,idcarta,flusso){
	document.forms[0].idcartap.value = idcarta;
	document.forms[0].flusso.value = flusso;
	document.forms[0].whichpage.value = whichpage;
	
	if (document.forms[0].IDUser) {
		document.forms[0].stato.value = 'S';
		document.forms[0].action = "card_master.asp?ACTION=Conferma"		
	}
	else
		document.forms[0].action = "card_privilegio.asp"
	
	document.forms[0].submit();
}

/**
-------------------------------------------------------
GESTIONE PRIVILEGIO
-------------------------------------------------------
**/
function ViewPrivilegio(IDCarta, flusso, bNewWindow, privType, stato)
{
	if (bNewWindow == true)
		window.open('card_privilegio.asp?Stato=' + stato + '&SelectPrivType=' + privType + '&IDCarta=' + IDCarta + '&flusso=' + flusso,'AddPrivilegio','scrollbars=yes,resizable=yes,width=1100,height=650,left=4,top=4');
	else
		location.href = 'card_privilegio.asp?Stato=' + stato + '&SelectPrivType=' + privType + '&IDCarta=' + IDCarta + '&flusso=' + flusso;
}

function ViewPrivilegesSummary(IDCarta, flusso, bNewWindow, privType, stato)
{
	if (bNewWindow == true)
		window.open('card_privileges_summary.asp?IDCarta=' + IDCarta + '&flusso=' + flusso, 'AddPrivilegio', 'scrollbars=yes,resizable=yes,width=1100,height=450,left=50,top=100');
	else
		location.href = 'card_privileges_summary.asp?IDCarta=' + IDCarta + '&flusso=' + flusso;
}

function AddPrivilegio(IDCarta, flusso, stato){
	
	window.opener.location.href = "card_master.asp?ACTION=Conferma&IDCarta=" + IDCarta + '&Modifica=no'+'&flusso='+flusso+'&stato='+stato;
	window.close();
}

function AddPrivilegioInSameWindow(IDCarta, flusso, stato){
	
	location.href = "card_master.asp?ACTION=Conferma&IDCarta=" + IDCarta + '&Modifica=no'+'&flusso='+flusso+'&stato='+stato;
}

function AddPrivilegioCard(IDCarta,flusso){

	window.location.href = "card_master.asp?ACTION=Conferma&IDCarta=" + IDCarta + '&Modifica=no'+'&flusso='+flusso+'&stato=S';

}

function AddPrivilegioCard2(IDCarta,flusso){

	window.open("http://www.basicbank.net/card_master.asp?ACTION=Conferma&IDCarta=" + IDCarta + '&Modifica=no'+'&flusso='+flusso+'&stato=S','AddPrivilegio','scrollbars=yes,resizable=yes,width=1100,height=650,left=4,top=4');

}


/**
-------------------------------------------------------
SELPAGESIZE_ONCHANGE()
-------------------------------------------------------
**/
//function selPageSize_OnChange(TheForm, box){
	//TheForm.pagesize.value = box.options[box.selectedIndex].value;
//}

/**
------------------------------------------------------
NEWSEARCH(strPar)
-------------------------------------------------------
**/
function NewSearch(strPar,strUrl) {
	if (strPar == "web"){
		if (strUrl == "")
			strUrl = 'SearchCp/default.asp?Tipo=P&Ricerca=au_logus_web&strFunzioneUscita=fupdateweb&ChiudeFinestra=SI';
		PopUp = window.open(strUrl, 'Search', 'width=620,height=480,left=50,top=50,resizable=yes,scrollbars=auto,status=0');
	}
	if (strPar == "po"){
		//var strUrl = 'SearchCp/default.asp?Tipo=P&Ricerca=unutente&strFunzioneUscita=fupdatepo&ChiudeFinestra=SI';
		PopUp = window.open(strUrl, 'Search', 'width=720,height=480,left=50,top=50,resizable=yes,scrollbars=auto,status=0');
	}
	if (strPar == "cp"){
		if (strUrl == "")
			strUrl='SearchCp/default.asp?Tipo=C&Ricerca=standard1&strFunzioneUscita=fupdatecp&ChiudeFinestra=SI';
		PopUp = window.open(strUrl, 'Search', 'width=720,height=480,left=50,top=50,resizable=yes,scrollbars=auto,status=0');
	}
	if (strPar == "pof")
	{
		strUrl= "/franchising/PO_START.ASP?TIPO=P&MODALITA=SELEZIONA&ALLBOOK=N&GOFUNC=fupdateperson"
		window.open(strUrl, 'Search', 'width=850,height=700,left=50,top=15,resizable=yes,scrollbars=yes,status=0'); 
	}
	if (strPar == "cpf")
	{
		strUrl= "/franchising/PO_START.ASP?TIPO=C&MODALITA=SELEZIONA&ALLBOOK=N&GOFUNC=fupdatecompany"
		window.open(strUrl, 'Search', 'width=750,height=500,left=25,top=20,resizable=yes,scrollbars=yes,status=0');
	}
}

/**
-------------------------------------------------------
FUPDATEWEB(strAusId,strAus)
-------------------------------------------------------
**/
function fupdateweb (strAusId,strAus) {
	document.HiddenForm.IDUser.value = "";
	document.HiddenForm.IDUserAW.value = strAusId;
	document.HiddenForm.IDCompany.value = "";
	document.HiddenForm.submit();
	return true;
}

/**
-------------------------------------------------------
FUPDATEPO (strAusId, strAus)
-------------------------------------------------------*
*/
function fupdatepo (strAusId,strAus) {
	document.HiddenForm.IDUser.value = strAusId;
	document.HiddenForm.IDUserAW.value = "";
	document.HiddenForm.IDCompany.value = "";
	document.HiddenForm.submit();
	return true;
}

/**
-------------------------------------------------------
FUPDATEPONOMINATIVO (sIdPerson, sNominativo)
-------------------------------------------------------*
*/
function fupdateponominativo (sIdPerson, sNominativo) {
	document.basicprivilege.NomeD.value = sNominativo;
	document.basicprivilege.Nome.value = sNominativo;
	document.basicprivilege.IDUserGC.value = sIdPerson;
	if (document.basicprivilege.AziendaD)
	   document.basicprivilege.AziendaD.value = '';
    if (document.basicprivilege.Azienda)
	   document.basicprivilege.Azienda.value = '';
	document.basicprivilege.IDCompanyGC.value = '0';
	document.basicprivilege.IDCpLocationGC.value = '0';
	return true;
}

/**
-------------------------------------------------------
FUPDATECP (strCpId, strCpLocId)
-------------------------------------------------------
**/
function fupdatecp (strCpId,strCpLocId) {
	document.HiddenForm.IDUser.value = "";
	document.HiddenForm.IDUserAW.value = "";
	document.HiddenForm.IDCompany.value = strCpId;
	document.HiddenForm.IDCpLocation.value = strCpLocId;
	document.HiddenForm.submit();
	return true;
}

/**
-------------------------------------------------------
FUPDATECPAZIENDA (strCpId, strCpLocId, sRagSociale)
-------------------------------------------------------
**/
function fupdatecpazienda (strCpId, strCpLocId, sRagSociale) {
	document.basicprivilege.NomeD.value = '';
	document.basicprivilege.Nome.value = '';
	document.basicprivilege.IDUserGC.value = '0';
	document.basicprivilege.AziendaD.value = sRagSociale;
	document.basicprivilege.Azienda.value = sRagSociale;	
	document.basicprivilege.IDCompanyGC.value = strCpId;
	document.basicprivilege.IDCpLocationGC.value = strCpLocId;
	return true;
}




function CheckPrivilegi(TheForm, TheObject){
	var TheLength = eval('document.'+TheForm.name + '.'+TheObject.name + '.length');
	if (TheObject.checked) {
		for (i=0;i<TheLength;i++) 
			eval('document.'+TheForm.name + '.'+TheObject.name + '[' + i + '].checked = false;'); 
		TheObject.checked = true
	}
}

function ApriLegenda(Tipo,intTipo,IDTipologia){
	window.open('card_legenda.asp?Tipo='+Tipo+'&intTipo='+intTipo+'&IDTipologia='+IDTipologia,'Legenda','scrollbars=yes,resizable=no,width=500,height=250,left=100,top=100');
}

function GetDiscountType(){
	return document.forms[0].SelDiscountCombo[document.forms[0].SelDiscountCombo.selectedIndex].value;
}

function GetDiscountTypePopup(){
	var tempValue = "";
	for(j=0; j<document.forms[0].TipologiaDiscount.length ;j++){
		if (document.forms[0].TipologiaDiscount[j].checked)
			tempValue = document.forms[0].TipologiaDiscount[j].value;
	}
	return tempValue;
}

function GetExtraDiscountType(IDTipologia){
	if (IDTipologia == 1){
		return document.forms[0].SelExtraDiscount[document.forms[0].SelExtraDiscount.selectedIndex].value;
	}
	else if (IDTipologia == 2){
//		return document.forms[0].SelDescrDiscount[document.forms[0].SelDescrDiscount.selectedIndex].value;
		return document.forms[0].SelDescrDiscount.value;
	}
}


function MoveOption (TheForm, MoveFrom, MoveTo, ToDo) {
	var SelectFrom = eval('document.'+TheForm.name + '.'+MoveFrom);
	var SelectTo = eval('document.'+TheForm.name + '.'+MoveTo);
	var SelectedIndex = SelectFrom.options.selectedIndex;
	var container;
	if (ToDo=='Add') {
		container=eval('document.'+TheForm.name + '.'+ToDo+MoveTo);
	}
	if (ToDo=='Remove') {
		container=eval('document.'+TheForm.name + '.'+ToDo+MoveFrom);
	}
	if (SelectedIndex == -1 && ToDo=='Add' ) {
		alert("Selezionare un negozio da attivare.");
	} else if (SelectedIndex == -1 && ToDo=='Remove' ) {
		alert("Selezionare un negozio da eliminare.");
	} else {
		for (i=0; i<SelectFrom.options.length; i++) {
			if(SelectFrom.options[i].selected) {
				var name = SelectFrom.options[i].text;
				var ID = SelectFrom.options[i].value;
				
				SelectFrom.options[i] = null;
				SelectTo.options[SelectTo.options.length]=new Option (name,ID);
				i=i-1;
				
			}
		}
	}
}

function SetOption (TheForm, MoveTo){
	var SelectFrom = eval('document.'+TheForm.name + '.'+MoveTo);
	var container;

	//Ripulisco il container
	eval('document.' + TheForm.name + '.Add' + MoveTo + '.value = \'\'');
	container = eval('document.'+TheForm.name + '.Add'+MoveTo);

	//mpv:Modifica in data 22/09/2004 tolte le combe dei negozi
	//carico il container con i valori dei flussi
	//for (i=0; i<SelectFrom.options.length; i++) {
	//		var name = SelectFrom.options[i].value;
	//		container.value = container.value + name + delimiter;
	//}
	
	//tolgo l'ultima virgola all'interno del container
	//container.value = container.value.substring(0, container.value.length - 1);
	
	//carico il container con il valore del flusso
	container.value = container.value + SelectFrom.value;



}
function CheckFormPromozione(bClose,TheForm){

	var bSubmit = false;
	var Sconto = 		eval ( eval(eval('document.'+TheForm.name + '.Sconto.value'))  + eval(eval('document.'+TheForm.name + '.ScontoBase.value')) );
	var ScontoEstensione = eval('document.'+TheForm.name + '.Sconto.value');
	var MaxImporto = 	eval('document.'+TheForm.name + '.MaxImporto');
	var ValoreSconto = 	eval('document.'+TheForm.name + '.ValoreSconto');


	
	if (ScontoEstensione.length == 0)
		alert("Sconto non inserito");
	else
	if ((MaxImporto.value == 0) && !(MaxImporto.readOnly))
		alert("Tetto di spesa non inserito");
	else
		bSubmit = true;
		
	if (bSubmit) {
		window.opener.document.forms[0].ScontoPromozione.value = window.opener.document.forms[0].ScontoPromozione.value + ',' + Sconto;
		window.opener.document.forms[0].TettoPromozione.value  = window.opener.document.forms[0].TettoPromozione.value  + ',' + ValoreSconto.value;
		window.opener.document.forms[0].TipoPromozione.value  = window.opener.document.forms[0].TipoPromozione.value  + ', 95' // + document.forms[0].SelExtraDiscount.value;
		window.opener.document.forms[0].AttivaPromozione.value = window.opener.document.forms[0].SelExtraDiscount.value ;
		window.opener.document.forms[0].SelExtraDiscount.disabled = true;
//		if (window.opener.document.forms[0].SelDescrDiscount)
//			window.opener.document.forms[0].SelDescrDiscount.disabled = true;
		if (window.opener.document.forms[0].txtDescSconto)
			window.opener.document.forms[0].txtDescSconto.disabled = true;


		//window.opener.document.forms[0].Descrizione.value = "";
		if (bClose) window.close();
	}
}

function ChiudiFormPromozione(){

	if (window.opener.document.forms[0].AttivaPromozione.value == "0") {

		if(window.opener.document.forms[0].Descrizione)
			window.opener.document.forms[0].Descrizione.value = "";
			
		window.opener.document.forms[0].ScontoPromozione.value = "";
		window.opener.document.forms[0].TettoPromozione.value = "";
		window.opener.document.forms[0].TipoPromozione.value = "";
		window.opener.document.forms[0].SelExtraDiscount.value = "0";
		window.opener.document.forms[0].SelExtraDiscount.disabled = false;
		
//		if (window.opener.document.forms[0].SelDescrDiscount)
//			window.opener.document.forms[0].SelDescrDiscount.disabled = false;
		if (window.opener.document.forms[0].txtDescSconto)
			window.opener.document.forms[0].txtDescSconto.disabled = false;


		window.opener.document.forms[0].MaxImporto.value = "";
		window.opener.document.forms[0].Sconto.value = "";
		window.opener.document.forms[0].ValoreSconto.value = "";
		window.opener.document.forms[0].ValoreSconto2.value = "";

		if (window.opener.document.forms[0].NChiavi)
			window.opener.document.forms[0].NChiavi.value = "";
			
		if (window.opener.document.forms[0].NPersone)
			window.opener.document.forms[0].NPersone.value = "";
			
		window.opener.document.forms[0].StartDateDiscount.value = "";
		window.opener.document.forms[0].EndDateDiscount.value = "";
	}
	window.close();
}


function CheckFormMaster (bNotInsertNegozi, bTrovato, TheForm, TheEAN,TheName, TheCompany, TheAddress, TheEmail, TheExpiryDate ,TheselLingua, TheselValida, TheEndFlusso){
		
	var EAN =		eval('document.'+TheForm.name + '.'+TheEAN+'.value');
	var Nome = 		eval('document.'+TheForm.name + '.'+TheName+'.value');
	var NomeCompany = 	eval('document.'+TheForm.name + '.'+TheCompany+'.value');
	var Indirizzo = 	eval('document.'+TheForm.name + '.'+TheAddress+'.value');
	var Email = 		eval('document.'+TheForm.name + '.'+TheEmail+'.value');
	var ExpiryDate = 	eval('document.'+TheForm.name + '.'+TheExpiryDate+'.value');	
	var SelLingua = 	eval('document.'+TheForm.name + '.'+TheselLingua);
	var SelValida = 	eval('document.'+TheForm.name + '.'+TheselValida);
	var EndFlusso = 	eval('document.'+TheForm.name + '.'+TheEndFlusso);

	if (!CheckEAN(EAN)){
		alert("Codice EAN non corretto");
		if (!document.forms[0].EAN.disabled) {
			document.forms[0].EAN.select();
			document.forms[0].EAN.focus();			
		}
	}
	else
	if (Nome.length == 0 && NomeCompany.length == 0)
		alert("Nome Utente o Nome Company obbligatorio");
	else
	if (Indirizzo.length == 0)
		alert("Indirizzo non inserito");
	else 
	if (bNotInsertNegozi && (Email.length == 0))
		alert("Email non inserita");
	else
	if (ExpiryDate.length == 0)
		alert("Data scadenza non inserita");
	else
	//mpv:Modifica in data 22/09/2004 tolte le combe dei negozi
	//if (EndFlusso.length == 0)
	//	alert("Negozio non inserito");
	//else
	if (SelLingua.options[SelLingua.selectedIndex].value == "")
		alert("Lingua non inserita");
	//else
	//if ( bTrovato &&  SelValida.options[SelValida.selectedIndex].value == "")
	//	alert("Validità non inserita");
	else {
		//Set flusso nel container per privilegi
		SetOption(TheForm, TheEndFlusso);
		//Submit del FORM
		TheForm.submit();
	}
}

function CheckEAN (EAN){

	var bSubmit = false;
	if (!(document.forms[0].EAND == undefined)) {
		if (EAN.length != 13 && EAN.length !=0){
			bSubmit = false;
		}
		else
		if (EAN.substring(0,1) != '3' && EAN.substring(0,1) != '2' && EAN.substring(0,1) != '1' && EAN.length !=0 && !document.forms[0].EAN.disabled){
			bSubmit = false;			
		}
		else
		if (!CalcolaDigit(EAN) && EAN.length !=0 ){
			bSubmit = false;
		}
		else {
			bSubmit = true;
		}
	}else
		bSubmit = true;
		
	return bSubmit
}

function CalcolaDigit(ccod) {
	var Somma = 0
	var SommaPari = 0
	var SommaDispari = 0 
	var CheckDigit = 0
	var t = ""
	var ccodCalcolato = ""

	t = ccod.substr(0, 12)

	SommaDispari =	parseInt(ccod.substr(0, 1))  +
			parseInt(ccod.substr(2, 1)) +
			parseInt(ccod.substr(4, 1)) +
			parseInt(ccod.substr(6, 1)) + 
			parseInt(ccod.substr(8, 1)) +
			parseInt(ccod.substr( 10, 1))
	SommaPari =     parseInt(ccod.substr(1, 1))  +
			parseInt(ccod.substr(3, 1)) +
			parseInt(ccod.substr(5, 1)) + 
			parseInt(ccod.substr(7, 1)) + 
			parseInt(ccod.substr(9, 1)) +
			parseInt(ccod.substr(11, 1))

	SommaPari = SommaPari * 3
	Somma     = SommaPari + SommaDispari

	if ((Somma / 10) == (parseInt(Somma / 10))) {
		CheckDigit = 0
	}
	else {
		CheckDigit = (parseInt(Somma/10) + 1) * 10 - Somma
	}  
	
	ccodCalcolato = ccod.substr(0, 12) + CheckDigit.toString()
	//alert(ccod == ccodCalcolato)

	return (ccod == ccodCalcolato)
}


function CheckFormStringaPrivilegi(TheForm,bTrovato){	
	
	var bSubmit = false;
	credit = false;
	cash = false;
	discount = false;
	if(document.getElementById('Privilegio_1') != null){credit =   document.getElementById('Privilegio_1').checked;}
    if(document.getElementById('Privilegio_2') != null){cash =   document.getElementById('Privilegio_2').checked;}
    if(document.getElementById('Privilegio_4') != null){discount =  document.getElementById('Privilegio_4').checked;}
//	if (bTrovato)
//		if (!TheForm.Privilegio_0[0].checked && !TheForm.Privilegio_0[1].checked && !TheForm.Privilegio_1.checked )
//			alert("Selezionare almeno un tipo di Privilegio !");
//		else
//			bSubmit = true;
//	else
//		if (!TheForm.Privilegio_1.checked )
//			alert("Selezionare almeno un tipo di Privilegio !");
//		else
//			bSubmit = true;
		
	if (!credit && !cash && !discount)
			alert("Selezionare almeno un tipo di Privilegio !");
		else	
	//Submit del FORM
	//if (bSubmit)
		TheForm.submit();

}


function CheckFormPrivilegi(TheForm, bytePrivilegio){

	var bSubmit1 = true;
	var bSubmit2 = true;
	var bSubmit4 = true;

	if  (1 & bytePrivilegio){
		bSubmit1 = CheckFormPrivilegiCredit(TheForm);
	}

	if  (2 & bytePrivilegio) {
		bSubmit2 = CheckFormPrivilegiCash(TheForm);
	}

	if  (4 & bytePrivilegio) {
		bSubmit4 = CheckFormPrivilegiDiscount(TheForm);
	}

	//Submit del FORM
	if (bSubmit1 && bSubmit2 && bSubmit4) {
	    TheForm.BtnCreaPrivilegiBC.disabled = true;
		// DEBUG
	    TheForm.submit();
	    setPremuto();
	}


}

function CheckFormPrivilegiCredit(TheForm){
	var bSubmit = false;
	
	var Importo = 		eval('document.'+TheForm.name + '.ImportoCredit.value');
	var EndDateCredit = 	eval('document.'+TheForm.name + '.EndDateCredit.value');
	var Messaggio = 	eval('document.'+TheForm.name + '.MessaggioCredit.value');
    var Note = 		eval('document.'+TheForm.name + '.NoteCredit.value');		
    
    var multiflusso = eval('document.'+TheForm.name + '.multiflussocredit.value');    
    var multiflussoGruppi = eval('document.'+TheForm.name + '.SelGruppiMultiFlussoCredit.value');    

    
	if (Importo.length == 0)
		alert("Importo non inserito");
	else
	if (EndDateCredit.length == 0)
		alert("Data scadenza non inserita");
	else	
	if (multiflusso.length == 0 && multiflussoGruppi.length == 0)
		alert("Seleziona i Siti/Negozi destinatari del privilegio Credit");
	else	
	if (Note.length == 0)
		alert("Privilegio Credit, note non inserite");
	else	
	    bSubmit = true;
	    
    return bSubmit;	    
}

function CheckFormPrivilegiCash(TheForm){
	var bSubmit = false;



	var bInsertNegoziAndFranchising = TheForm.InsertNegoziAndFranchising.value == 'True' ||
					TheForm.InsertNegoziAndFranchising.value == 'true' ||
					TheForm.InsertNegozi.value == 'True' && TheForm.BCCDesc.value == 'GC' ||
					TheForm.InsertNegozi.value == 'true' && TheForm.BCCDesc.value == 'GC' ||
					TheForm.InsertNegozi.value == 'True' && TheForm.BCCDesc.value == 'CR' ||
					TheForm.InsertNegozi.value == 'true' && TheForm.BCCDesc.value == 'CR' ;

	var Importo = 		eval('document.'+TheForm.name + '.Importo.value');
	var EndDateCash = 	eval('document.'+TheForm.name + '.EndDateCash.value');
	var Messaggio = 	eval('document.'+TheForm.name + '.Messaggio.value');
	var BCCDesc = 		eval('document.'+TheForm.name + '.BCCDesc.value');

	if(TheForm.TipologiaCash.value == "PR"){ //Provvigioni
		if(BCCDesc == "")
			alert("Selezionare la causale");
		else
		if (Importo.length == 0)
			alert("Importo non inserito");
		else bSubmit = true;	
	}else if(TheForm.BCCDesc.value == "BG"){ //BasicGiftCard
		var StartDateCash = 	eval('document.'+TheForm.name + '.StartDateCash.value');
		var IDUserDonatoreGC = eval('document.'+TheForm.name + '.IDUserGC.value');
		var IDCompanyDonatriceGC = eval('document.'+TheForm.name + '.IDCompanyGC.value');
        var CodiceEAN = eval('document.'+TheForm.name + '.CodiceEAN.value');
        if (CodiceEAN.length == 0)
			alert("Codice EAN non iserito");
		else
		if (CodiceEAN.length < 13)
			alert("Codice EAN deve essere lungo 13 caratteri");
		else
		if (Importo.length == 0)
			alert("Importo non inserito");
		else
		if (EndDateCash.length == 0)
			alert("Data scadenza non inserita");
		else
		if (SplitReverse(StartDateCash) > SplitReverse(EndDateCash) )
			alert("La data inizio validità è posterire alla data di fine validità");
		else
			bSubmit = true;
    
    }else
	if (bInsertNegoziAndFranchising ) {	//Altri privilegi cash
		var StartDateCash = 	eval('document.'+TheForm.name + '.StartDateCash.value');
		var IDUserDonatoreGC = eval('document.'+TheForm.name + '.IDUserGC.value');
		var IDCompanyDonatriceGC = eval('document.'+TheForm.name + '.IDCompanyGC.value');

		if (Importo.length == 0)
			alert("Importo non inserito");
		else
		if (EndDateCash.length == 0)
			alert("Data scadenza non inserita");
		else
		if (SplitReverse(StartDateCash) > SplitReverse(EndDateCash) )
			alert("La data inizio validità è posterire alla data di fine validità");
		else
		if (IDUserDonatoreGC == '0' && IDCompanyDonatriceGC == '0')
			alert("Selezionare o l'utente donatore o la company donatrice");
		else
			bSubmit = true;

	}
	else {
		//var SelFlussiCash = 	eval('document.'+TheForm.name + '.SelFlussiCash.value');
		var Fatturazione = 	eval('document.'+TheForm.name + '.Fatturazione.value');
		var Sponsorizzazione = 	eval('document.'+TheForm.name + '.Sponsorizzazione');
		var NumeroContratto = 	eval('document.'+TheForm.name + '.NumeroContratto');
		var IdCdc = 		eval('document.'+TheForm.name + '.IdCdc');
		var Note = 		eval('document.'+TheForm.name + '.Note.value');
		var multiflussocash = eval('document.'+TheForm.name + '.multiflussocash.value');

		if (Importo.length == 0){
			alert("Importo non inserito");
			document.getElementById("Importo").focus();
		}else
		if (EndDateCash.length == 0){
			alert("Data scadenza non inserita");
		    document.getElementById("EndDateCash").focus();
		}
		else
		//if (Messaggio.length == 0)
		//	alert("Privilegio Cash, testo mail non inserito");
		//else
		if ((BCCDesc == '.') || (BCCDesc == '')){
			alert("Privilegio Cash, causale non inserita");
		    document.getElementById("BCCDesc").focus();
		}
		else
		//if (SelFlussiCash.length == 0)
		//	alert("Negozio non inserito");
		//else
		if (multiflussocash.length == 0){
			alert("Seleziona i Siti/Negozi destinatari del privilegio Cash ");
		    document.getElementById("btn_MUltiflussicash").focus();
		}else
		if (Fatturazione == '0'){
			alert("Società a cui fatturare non inserita");
		    document.getElementById("Fatturazione").focus();
		}	
		else
		if ( (!Sponsorizzazione.disabled) && (Sponsorizzazione.value == '0') ){
			alert("Company di sponsorizzazione non inserita");
			document.getElementById("Sponsorizzazione").focus();
		}
		else
		//if ( (!NumeroContratto.disabled) && (NumeroContratto.value == 'N.Contratto') )
		if ( (!NumeroContratto.disabled) && ((NumeroContratto.value == '') || (NumeroContratto.value == '0'))){
			alert("Numero del contratto non inserito");
			document.getElementById("NumeroContratto").focus();
		}
		else
		if ( (!IdCdc.disabled) && (IdCdc.value == '0') ){
			alert("DotCom non inserita");
			document.getElementById("IdCdc").focus();}
		else
		if ((!IdCdc.disabled) && CheckBudgetResiduo(Importo, BCCDesc, IdCdc.value)){
			alert("L'importo supera il residuo del budget a disposizione");
			document.getElementById("Importo").focus();
		}
		else
		if (Note.length == 0){
			alert("Privilegio Cash, note non inserite");
			document.getElementById("Note").focus();
			}
		else
			bSubmit = true;

	}





	return bSubmit;
}

function CheckBudgetResiduo(Importo,BCCDesc,IdCdc){
	//alert(Importo + ' ' + BCCDesc+' '+ IdCdc)
	var bReturn = true;
	
	for (indice=0;indice < ElencoBudgetResiduo.length; indice++) {
		if (ElencoBudgetResiduo[indice] == BCCDesc && ElencoBudgetResiduo[indice + 2] == IdCdc) {

			if (Importo > ElencoBudgetResiduo[indice + 4]) {
				bReturn = true;
				break;
			}
			else
				bReturn = false;

		}
			
	}
	return bReturn	
}

function Trim(str) {
	return str.replace(/\s+$|^\s+/g,"");
}

function CheckFormPrivilegiDiscount(TheForm){
	var bSubmit = false;
	var discountMinValue = 0;
	var discountMinValueErrMsg = '';

	var Promozioni = 0;
	if (TheForm.SelExtraDiscount)
        Promozioni = eval('document.'+TheForm.name + '.SelExtraDiscount.value');
	var Convenzioni = 0;
//	if (TheForm.SelDescrDiscount)
	if (TheForm.txtDescSconto)
        Convenzioni = eval('document.'+TheForm.name + '.SelDescrDiscount.value');

	var Descrizione = 	eval('document.'+TheForm.name + '.Descrizione.value');
	var NChiavi = 		eval('document.'+TheForm.name + '.NChiavi.value');
	var Sconto = 		eval('document.'+TheForm.name + '.Sconto.value');
	var MaxImporto = 	eval('document.'+TheForm.name + '.MaxImporto');
	var SelFlussiDiscount = eval('document.'+TheForm.name + '.SelFlussiDiscount.value');
	var SelFlussiDiscountD = eval('document.'+TheForm.name + '.SelFlussiDiscountD.value');
	var Testo = 		eval('document.'+TheForm.name + '.Testo.value');
	var StartDateDiscount = eval('document.'+TheForm.name + '.StartDateDiscount.value');
	var EndDateDiscount = 	eval('document.'+TheForm.name + '.EndDateDiscount.value');
	var ValoreSconto2 = eval('document.'+TheForm.name + '.ValoreSconto2.value');
	if (document.getElementById("IdDiscountMinValue"))
		discountMinValue = document.getElementById("IdDiscountMinValue").value;
	if (document.getElementById("IdDiscountMinValueErrMsg"))
		discountMinValueErrMsg = document.getElementById("IdDiscountMinValueErrMsg").value;

	var multiflusso = eval('document.'+TheForm.name + '.multiflusso.value');
	var note = eval('document.' + TheForm.name + '.Note.value');

	if (Promozioni == 0 && Convenzioni == 0)
	    alert("Selezionare almeno una Promozione oppure un Gruppo di Sconto");
	else
	    if (Trim(Descrizione).length == 0) {
	    alert("Descrizione del privilegio non inserita");
	} else
	    if (NChiavi.length == 0 || NChiavi < 1) {
	    alert("Numero di chiavi non corretto");
	    document.getElementById("NChiavi").focus();
	}
	else
	    if (Sconto.length == 0 || Sconto >= 100) {
	    alert("Sconto non inserito oppure maggiore/uguale a 100%");
	    document.getElementById("Sconto").focus();
	} else
	    if (Sconto < discountMinValue)
	    alert(discountMinValueErrMsg);
	else
	    if ((MaxImporto.value == 0) && !(MaxImporto.readOnly)) {
	    alert("Tetto di spesa non inserito");
	    document.getElementById("MaxImporto").focus();
	}
	else
	    if (SelFlussiDiscount.length == 0 || SelFlussiDiscountD.length == 0 || SelFlussiDiscount != SelFlussiDiscountD) {
	    alert("Negozio non inserito");
	    document.getElementById("EmessoDa").focus();
	}
	else
	    if (multiflusso.length == 0) {
	    alert("Seleziona i Siti/Negozi destinatari del privilegio Discount ");
	    document.getElementById("btn_MUltiflussi").focus();
	}
	// 02/02/2012: commentato per togliere obbligatorietà alle note dopo che in un primo tempo
	// si pensava di considerarlo obbligatorio
	//else 
	    //if (note.length == 0) {
			//alert("Il campo Note è obbligatorio.");
			//document.getElementById("Note").focus();
	//}
	else
	    if (StartDateDiscount.length == 0) {
	    alert("Data inizio validità non inserita");
	    document.getElementById("StartDateDiscount").focus();
	}
	else
	    if (EndDateDiscount.length == 0) {
	    alert("Data fine validità non inserita");
	    document.getElementById("EndDateDiscount").focus();
	} else
	    if (SplitReverse(StartDateDiscount) > SplitReverse(EndDateDiscount)) {
	    alert("La data inizio validità è posterire alla data di fine validità");
	    document.getElementById("StartDateDiscount").focus();
	}
	else {
	    if (document.forms[0].NChiavi.value >= 1000 && document.forms[0].NPersone.value == 1)
	        if (confirm("Attenzione : il processo di creazione ci metterà almeno " + parseInt(document.forms[0].NChiavi.value / 5000 + 0.9) + " minuti !"))
	        bSubmit = true;
	    else
	        bSubmit = false;
	    else
	        if (document.forms[0].NPersone.value >= 1000 && document.forms[0].NChiavi.value == 1)
	        if (confirm("Attenzione : il processo di creazione ci metterà almeno " + parseInt(document.forms[0].NPersone.value / 5000 + 0.9) + " minuti !"))
	        bSubmit = true;
	    else
	        bSubmit = false
	    else
	        bSubmit = true;

	}
	if (bSubmit == true) {
      
      if (document.getElementById("idResiduoLimiteSconto") && document.getElementById("IdDefaultCompanyDiscount")){
          var budgetResiduo = CheckBudgetSconto();
          
          if (!parseFloat(budgetResiduo))
          {
            alert("Errore: l'importo residuo del budget è negativo. Contattare l'amministrazione.");
            bSubmit = false;          
          }
          else {
              if(parseFloat(budgetResiduo) >= 0) {
                alert("L'importo supera il residuo a disposizione. Residuo: " + budgetResiduo);
                bSubmit = false;
              }
          }
      }
      
    }
    if (bSubmit == true)
		if (document.getElementById("IdDiscountForCash"))
			if (document.getElementById("IdDiscountForCash").value == "")
			{
				bSubmit = false;
				alert("Sconto per il valore della cash da riconoscere non inserito oppure maggiore/uguale a 100%");
				document.getElementById("IdDiscountForCash").focus();
			}
    if (bSubmit == true)
		if (document.getElementById("IdNoteCash"))
			if (document.getElementById("IdNoteCash").value == "")
			{
				bSubmit = false;
				alert("Note non inserite per il privilegio cash da creare in automatico");
				document.getElementById("IdNoteCash").focus();
			}
    if (bSubmit == true)
		if (document.getElementById("IdDiscountCashInvoice"))
		{
			if (document.getElementById("IdDiscountCashInvoice").value == 0)
			{
				bSubmit = false;
				alert("E' necessario definire la company e la DotCom da cui verrà detratto il budget");
				document.getElementById("IdDiscountCashInvoice").focus();   
			}
        }
		
	if (document.getElementById("TxtCodAttivazionePriv")) {
	    var codAttivazione = document.getElementById("TxtCodAttivazionePriv").value;
	    if (codAttivazione == "") {
	        alert("Il campo codice di attivazione privilegio è obbligatorio.");
	        bSubmit = false;
	    }
	    else {
	        if (checkCodiceAttivazPriv(codAttivazione)) {
	            document.getElementById("TxtCodAttivazionePriv").focus();
	            alert("Inserire un codice di attivazione valido.");
	            bSubmit = false;
	        }	    
	    }
	}
	return bSubmit;
}




/**
-------------------------------------------------------
INIZIALIZZAFORMRICERCA()
-------------------------------------------------------
**/
function InizializzaFormRicerca(TheForm, sTipo){

	var loading = document.getElementById("loading");
	var loaded = document.getElementById("loaded");
	if (loading) loading.style.display="none";
	if (loaded) loaded.style.display="block";
	if (TheForm.SelRicerca)
	{
		if (sTipo == "STORICO" ){
			//verifico se il browser supporta gli stili testando una combo qualsiasi
			if (TheForm.SelRicerca.style){
				bStile = true
			}
			SelRicerca_onChange(TheForm);
			SelPeriodo_onChange(TheForm, '', '');
			SelAnno_onChange(TheForm);
			bPrimoPassaggio = false;
			ShowIssuedBy(TheForm);
		}

		if (sTipo == "TESSERE" ){
			//verifico se il browser supporta gli stili testando una combo qualsiasi
			if (TheForm.SelRicerca.style){
				bStile = true
			}
			SelRicerca_onChange(TheForm);
			bPrimoPassaggio = false;
		}
	}
}

function ShowIssuedBy(TheForm)
{
	var search_suggest = document.getElementById('search_suggest');
	var bSuggest = (search_suggest)?true:false;
	
	MostraCombo(TheForm.btnSelect);
	if(bSuggest)search_suggest.style.display = 'none';
	NascondiInput(TheForm.Txt2);
	if (TheForm.SelSocieta)
		RiempiCombo(TheForm.SelSocieta, ElencoIssuedby[0], IssuedBy);
	NascondiCombo(TheForm.Sel3);
}

function CheckNoAllFOnSearch(TheForm)
{
	var num = TheForm.SelRicerca.selectedIndex;
	var valore = TheForm.SelRicerca[num].value;
	if (valore == "FLUSSOVALIDO" && TheForm.SelFlussiStorico.value == "ALLF")
	{
		alert(TheForm.AlertOnSelectFlusso.value);
	}
	else
	{
		Clessidra();
		btnSelect_onClick(TheForm, 'Card_master_storico.asp');
	}
} 

/**
-------------------------------------------------------
    SELRICERCA_ONCHANGE(TheForm)
-------------------------------------------------------
**/
function SelRicerca_onChange(TheForm){
	var selCodFlusso;
	var box = TheForm.SelRicerca;
	var num = TheForm.SelRicerca.selectedIndex;
	var valore = TheForm.SelRicerca[num].value;

	var TipoRicerca = eval('document.'+TheForm.name + '.' + valore + '.value');

	var search_suggest = document.getElementById('search_suggest');
	bSuggest = (search_suggest)?true:false;
	if (TheForm.SelFlussiStorico)
		TheForm.SelFlussiStorico.style.display = 'none';
	selCodFlusso = false;
	switch (TipoRicerca){
		case "N" :
			TheForm.Txt1.value = "";
			MostraCombo(TheForm.btnSelect);
			if(bSuggest)search_suggest.style.display = 'none';
			NascondiInput(TheForm.Txt1);
			NascondiInput(TheForm.Txt2);
			NascondiCombo(TheForm.Sel2);
			break;
		case "T" :

			if (bPrimoPassaggio)
				TheForm.Txt1.value = Txt1;
			else
				TheForm.Txt1.value = "INSERIRE";

			MostraCombo(TheForm.btnSelect);
			MostraInput(TheForm.Txt1);
			NascondiInput(TheForm.Txt2);
			NascondiCombo(TheForm.Sel2);
			NascondiCombo(TheForm.Sel3);
			TheForm.Txt1.focus();
			TheForm.Txt1.select();
			break;
		case "X" :
			if (bPrimoPassaggio) {
				TheForm.Txt1.value = Txt1;
				TheForm.Txt2.value = Txt2;
			}
			else {
				TheForm.Txt1.value = "FROM";
				TheForm.Txt2.value = "TO";
			}

			MostraCombo(TheForm.btnSelect);
			MostraInput(TheForm.Txt1);
			MostraInput(TheForm.Txt2);
			NascondiCombo(TheForm.Sel2);
			NascondiCombo(TheForm.Sel3);
			break;
		case "D" :
			TheForm.Txt1.value = "DATA";
			MostraCombo(TheForm.btnSelect);
			if(bSuggest)search_suggest.style.display = 'none';
			NascondiInput(TheForm.Txt1);
			NascondiInput(TheForm.Txt2);
			NascondiCombo(TheForm.Sel2);
			NascondiCombo(TheForm.Sel3);
			break;
		case "E" :
			TheForm.Txt1.value = "ELENCO";
			MostraCombo(TheForm.btnSelect);
			if(bSuggest)search_suggest.style.display = 'none';
			NascondiInput(TheForm.Txt1);
			NascondiInput(TheForm.Txt2);
			if (valore == "ISSUEDBY") 
			{
				RiempiCombo(TheForm.Sel2,ElencoIssuedby[0],IssuedBy);
				MostraCombo(TheForm.Sel2);
				NascondiCombo(TheForm.Sel3);
			}
			if (valore == "FLUSSOVALIDO")
			{
				MostraCombo(TheForm.SelFlussiStorico);
				selCodFlusso = true;
			}

			break;
		case "P" :
			//TheForm.Txt1.value = "";
			NascondiInput(TheForm.btnSelect);
			if(bSuggest)search_suggest.style.display = 'none';
			NascondiInput(TheForm.Txt1);
			NascondiInput(TheForm.Txt2);
			NascondiCombo(TheForm.Sel2);
			NascondiCombo(TheForm.Sel3);
			if (valore == "IDCASH"){
				window.open('/Kcard_Storico.asp','IDCASH','scrollbars=yes,resizable=yes,width=830,height=600,left=30,top=30');	
			}
			else if (valore == "IDDISCOUNT"){
				window.open('/Gruppi_Storico.asp','IDDISCOUNT','scrollbars=yes,resizable=yes,width=830,height=600,left=30,top=30');	
			}

			break;
	}
	if (selCodFlusso == false)
		if (TheForm.SelFlussiStorico)
			TheForm.SelFlussiStorico.selectedIndex = 0;

	//RiempiInput(TheForm.Txt1,num,'');
	//MostraInput(TheForm.Txt1);
}


/**
-------------------------------------------------------
	RIEMPIINPUT(Txt,num,valore)
-------------------------------------------------------
**/
function RiempiInput(Txt,num,valore){
	if (valore!='' && bPrimoPassaggio==true){
		Txt.value = valore
	}
	else {
		Txt.value = "";
	}
}     

/**
-------------------------------------------------------
    	MOSTRAINPUT(txt)
-------------------------------------------------------
**/
function MostraInput(txt){
	txt.size=16;
	txt.disabled=false;
	if (bStile) txt.style.display = ''
}


/**
-------------------------------------------------------
	NASCONDIINPUT(txt)
-------------------------------------------------------
**/
function NascondiInput(txt){
	//txt.value='*****'
	if (txt != null){
		txt.disabled=true;
		if (bStile) txt.style.display = 'none'
	}
}




/**
-------------------------------------------------------
    SELANNO_ONCHANGE(TheForm)
-------------------------------------------------------
**/
function SelAnno_onChange(TheForm){
	var box = TheForm.SelAnno
	var Periodo = TheForm.SelPeriodo
	if (box.selectedIndex == 0){
		Periodo.disabled=true;
		Periodo.selectedIndex=0;
		NascondiCombo(TheForm.SelSettimana);
		NascondiCombo(TheForm.SelMese);
		NascondiCombo(TheForm.SelGiorno);
	}
	else {
		Periodo.disabled=false;
		if (Periodo.selectedIndex==1) {
		 	ComponiSettimane(TheForm);
		}
	}
}

/**
-------------------------------------------------------
    SELPERIODO_ONCHANGE(TheForm)
-------------------------------------------------------
**/
function SelPeriodo_onChange(TheForm){
	var box = TheForm.SelPeriodo
	var num = box.selectedIndex
	var Oggi = new Date()
	//var MeseSel   = ''
	if (MeseSel == '' || !bPrimoPassaggio) MeseSel=Oggi.getMonth()+1;
	//var GiornoSel = ''
	if (GiornoSel == '' || !bPrimoPassaggio) GiornoSel=Oggi.getDate();


	var Mesi = new Array(
	  'Gennaio'   , '1',
	  'Febbraio'  , '2',
	  'Marzo'     , '3',
	  'Aprile'    , '4',
	  'Maggio'    , '5',
	  'Giugno'    , '6',
	  'Luglio'    , '7',
	  'Agosto'    , '8',
	  'Settembre' , '9',
	  'Ottobre'   ,'10',
	  'Novembre'  ,'11',
	  'Dicembre'  ,'12');

	var Giorni = new Array(
	'Tutti','ALL',1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,
	11,11,12,12,13,13,14,14,15,15,16,16,17,17,18,18,19,19,20,20,
	21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,30,30,31,31);
	
	if (num==0 || num>2){
	NascondiCombo(TheForm.SelSettimana);
	NascondiCombo(TheForm.SelMese);
	NascondiCombo(TheForm.SelGiorno);
	}
	if (num==1){
	  ComponiSettimane(TheForm);
	}
	if (num==2){
	  NascondiCombo(TheForm.SelSettimana);
	  RiempiCombo(TheForm.SelMese,Mesi,MeseSel);
	  MostraCombo(TheForm.SelMese);
	  RiempiCombo(TheForm.SelGiorno,Giorni,GiornoSel);
	  MostraCombo(TheForm.SelGiorno);
	}
}

/**
-------------------------------------------------------
COMPONISETTIMANE(TheForm)
-------------------------------------------------------
**/
function ComponiSettimane(TheForm) {
	var box = TheForm.SelSettimana
	var box2= TheForm.SelAnno
	var iAnno = box2.options[box2.selectedIndex].value
	var numeroSettimana
	var settimanaCaricata = new Date(SelSettimana)
	if (settimanaCaricata!='') {
		var giorno = settimanaCaricata.getDate()+5; //incremento il giorno di 5
		settimanaCaricata.setDate(giorno);
	}
	if (settimanaCaricata!='' && bPrimoPassaggio){
		var Oggi = new Date(settimanaCaricata); //data passata dal form + 5 giorni
	}
	else {
		var Oggi = new Date(); //data odierna
		Oggi.setYear(iAnno) //sostituisco l'anno con quello selezionato nella combo SelAnno
	}
	
	SvuotaCombo(box)
	var myDataPG = new Date(iAnno, 0, 1); //1° gennaio dell'anno
	var myDataUG = new Date(iAnno, 0, 1); //1° gennaio dell'anno
	myDataPG.setDate(myDataPG.getDate() - myDataPG.getDay() + 1);   // setta il primo giorno della settimana
	myDataUG.setDate(myDataUG.getDate() - myDataUG.getDay() + 1 + 6); // setta l'ultimo giorno della settimana
	var k = 0
	while (myDataPG.getFullYear() <= iAnno){
	var label = (k+1).toString() + '° - From ' + myDataPG.getDate().toString() + '/' + (myDataPG.getMonth()+1).toString() + ' To ' + myDataUG.getDate().toString() + '/' + (myDataUG.getMonth()+1).toString() ;
	var value = myDataPG.getFullYear() + '/' +(myDataPG.getMonth()+1).toString() + '/' + myDataPG.getDate();
	box.options[k] = new Option(label,value);
	if (Oggi-myDataPG > 0) numeroSettimana = k;
		myDataPG.setDate(myDataPG.getDate() + 7);
		myDataUG.setDate(myDataUG.getDate() + 7);
		k++
	}
	box.selectedIndex = (numeroSettimana);
	MostraCombo(box);
	NascondiCombo(TheForm.SelMese);
	NascondiCombo(TheForm.SelGiorno);
}


/**
-------------------------------------------------------
RIEMPICOMBO(box,list,valore)
box       = Combo da popolare
list      = array monodimensionale di testi e valori da inserire
valore  = valore da selezionare
-------------------------------------------------------
**/
function RiempiCombo(box,list,valore){
	var sel = 0;
	while (box.options.length) box.options[0] = null;
	for(i=0;i<list.length;i+=2){
		box.options[i/2] = new Option(list[i],list[i+1]);
		if (list[i+1]==valore){
		  	sel = Math.floor(i/2);
		}
	}
	box.selectedIndex=sel;
}

/**
-------------------------------------------------------
    MOSTRACOMBO(box)
-------------------------------------------------------
**/
function MostraCombo(box){
	box.disabled=false;
	if (bStile) box.style.display = '';
}


/**
-------------------------------------------------------
    NASCONDICOMBO(box)
 -------------------------------------------------------
**/
function NascondiCombo(box)
{
	if (box)
	{
		if (box.options.length != 0 ) SvuotaCombo(box);
		box.disabled=true;
		if (bStile) box.style.display = 'none';
	}
}

/**
-------------------------------------------------------
    SVUOTACOMBO(box)
-------------------------------------------------------
**/
function SvuotaCombo(box){
	while (box.options.length!=1) box.options[0] = null;
	box.options[0] = new Option('**','');
	box.selectedIndex = 0;
}
    
/**
-------------------------------------------------------
BTNSELECT_ONCLICK()
-------------------------------------------------------
**/
function btnSelect_onClick(TheForm, ThePage){
	
	TheForm.action = ThePage;
	TheForm.submit();
}  



/**
-------------------------------------------------------
FONCLICKPRICE(OBJ)
-------------------------------------------------------
**/
function fOnClickPrice(OBJ){
	bRet = true;
	if (OBJ.readOnly == false && OBJ.value == "0") {
		OBJ.value = "";
		OBJ.focus();
		alert("L'importo deve essere diverso da '0'");
		return false;
	}
		
	trovato = 0;
	if(IsValidValue(OBJ.value, "0123456789.") == 1) { 
		var allValid = 1;
		for (i = 0;  i < OBJ.value.length;  i++) {
			ch = OBJ.value.charAt(i);
			if(ch == ".") {
				trovato = 1;
				break;
			}
		}
		if(trovato == 1 && i < OBJ.value.length - i) {
			trovato = 0;
			for (j = i + 1;  j < OBJ.value.length;  j++) {
				ch = OBJ.value.charAt(j);
				if(ch == ".") {
					trovato = 1;
					break;
				}
			}
			if(trovato == 1) {
				OBJ.value = OBJ.value.substr(0,OBJ.value.length-1);
				alert("Non utilizzare i separatori delle migliaia");
				OBJ.focus();
				return false;
			} 
		}
	} else {
		OBJ.value = OBJ.value.substr(0,OBJ.value.length-1);
		alert("Per le cifre decimali utilizzare '.'");
		OBJ.focus();
		return false;
	}
	return false;
}

/**
-------------------------------------------------------
ISVALIDVALUE(strValue, strcheckOK)
-------------------------------------------------------
**/
function IsValidValue(strValue, strcheckOK){
	var allValid = 1;
	for (i = 0;  i < strValue.length;  i++) {
		ch = strValue.charAt(i);
		for (j = 0;  j < strcheckOK.length;  j++)
			if(ch == strcheckOK.charAt(j))
				break;
			if(j == strcheckOK.length) {
				allValid = 0;
				break;
			}
	}
	if(!allValid){
		return 0;}	// FALSE
	else
		return 1; // TRUE
}

/**
-------------------------------------------------------
FORMATTAN(OBJ,importo)
-------------------------------------------------------
**/
function FormattaN(OBJ,importo){
	var num = importo.value*100;
	var strNum = "";
	var len = 0;
	var _int = 0;
	var dec = 0;
	
	num = (Math.round(num));
	strNum = num.toString()
	len = strNum.length
	_int = strNum.slice(0,len-2)
	dec = strNum.slice(len-2)
	OBJ.value = _int + "." + dec
}

/**
-------------------------------------------------------
FORMATTAN(importo)
-------------------------------------------------------
**/
function FormattaN(importo){
	  var num = importo*100;
	  num = (Math.round(num)/100);
	  return num
}

/**
-------------------------------------------------------
btnIllimitatoOnClick(TheForm)
-------------------------------------------------------
**/
function btnIllimitatoOnClick(TheForm){
	TheForm.MaxImporto.value = "0";
	TheForm.MaxImporto.readOnly=true;
	TheForm.MaxImporto.style.display='none';
	TheForm.btnIllimitato.disabled=true;
	TheForm.btnIllimitato.style.display='none';
	TheForm.btnRiabilitaMaxImporto.disabled=false;
	TheForm.btnRiabilitaMaxImporto.style.display='';
	TheForm.ValoreSconto.value = "0";
	TheForm.ValoreSconto2.value = '';
}

/**
-------------------------------------------------------
btnRiabilitaMaxImportoOnClick(TheForm)
-------------------------------------------------------
**/
function btnRiabilitaMaxImportoOnClick(TheForm) {
	TheForm.MaxImporto.value = "";
	TheForm.ValoreSconto.value = "";
	TheForm.MaxImporto.readOnly=false;
	TheForm.MaxImporto.style.display='';
//	TheForm.MaxImporto.focus();
	if (TheForm.btnIllimitato) {
		TheForm.btnIllimitato.disabled=false;
		TheForm.btnIllimitato.style.display='';
		TheForm.btnRiabilitaMaxImporto.disabled=true;
		TheForm.btnRiabilitaMaxImporto.style.display='none';
	}
	TheForm.SelFlussiDiscount.value = TheForm.SelFlussiDiscountD.value;
}

function ControllaPercentuale(IdInput)
{
	if (document.getElementById(IdInput))
		if (document.getElementById(IdInput).value >= 100) 
		{
			alert("Lo sconto non può essere superiore o uguale al 100%");
			document.getElementById(IdInput).value = "";
			document.getElementById(IdInput).focus();
		}
}

/**
-------------------------------------------------------
CalcolaSconto(TheForm,MaxImporto)
-------------------------------------------------------
**/
function CalcolaSconto(TheForm,MaxImporto){
	TheForm.MaxImporto.value = FormattaN(MaxImporto);
	if (TheForm.Sconto.value < 100 ) {
		TheForm.ValoreSconto.value = FormattaN( MaxImporto - MaxImporto * (TheForm.Sconto.value/100) );
		TheForm.ValoreSconto2.value = FormattaN( MaxImporto * (TheForm.Sconto.value/100) );
	}
	if (TheForm.Sconto.value >= 100 ){
		alert ("Lo sconto non può essere superiore o uguale al 100 %")
		TheForm.Sconto.value = '';
		TheForm.ValoreSconto.value = '';
		TheForm.ValoreSconto2.value = '';
	}
}

/**
-------------------------------------------------------
CalcolaSconto2(TheForm,MaxImporto)
-------------------------------------------------------
**/
function CalcolaSconto2(TheForm,MaxImporto,Sconto){
	TheForm.MaxImporto.value = FormattaN(MaxImporto);
	if (Sconto != 0) {
		TheForm.ValoreSconto.value  = FormattaN(MaxImporto - MaxImporto *( eval(eval(Sconto) +  eval(TheForm.ScontoBase.value))/ 100) );
		TheForm.ValoreSconto2.value = FormattaN(MaxImporto * (eval(eval(Sconto) +  eval(TheForm.ScontoBase.value))/ 100) );
	}
}

/**
-------------------------------------------------------
CheckNChiavi(TheForm)
-------------------------------------------------------
**/
function CheckNChiavi(TheForm)
{
		if (TheForm.NChiavi.value > 0) {
			TheForm.NPersone.value = 1;
		}
		CheckNFlusso(TheForm);
}

/**
-------------------------------------------------------
CheckNPersone(TheForm)
-------------------------------------------------------
**/
function CheckNPersone(TheForm)
{
		if ((TheForm.NPersone.value != "") && (TheForm.NPersone.value > 0)) {
			TheForm.NChiavi.value = 1
		}
		CheckNFlusso(TheForm);
}

/**
-------------------------------------------------------
CheckNFlusso(TheForm)
-------------------------------------------------------
**/
function CheckNFlusso(TheForm)
{
		
		if ((TheForm.NChiavi.value > 1) || (TheForm.NPersone.value > 1)){
			if (TheForm.SelFlussiDiscountD.length > 2 ){
				TheForm.btn_MUltiflussi.disabled = true;
				TheForm.lbl_Multiflussi.disabled = false;
				MostraInputMF(TheForm.lbl_Multiflussi);
				
				if (TheForm.multiflusso && TheForm.multiflusso.value.split(",").length > 1)
				{
					TheForm.lbl_Multiflussi.value = 'Multiflusso';
					if (TheForm.multiflusso.value.indexOf('KSTR') == -1)
						TheForm.multiflusso.value = TheForm.multiflusso.value + ',KSTR';
					TheForm.SelFlussiDiscount.value = 'KSTR';
					TheForm.SelFlussiDiscountD.value = 'KSTR';
				}
				else
				{ 
					TheForm.lbl_Multiflussi.value = 'Thegigastore.com';
					TheForm.multiflusso.value = 'KSTR';
					TheForm.SelFlussiDiscount.value = 'KSTR';
					TheForm.SelFlussiDiscountD.value = 'KSTR';
				}
				TheForm.SelFlussiDiscountD.disabled = true;
			}
			else {
				alert("Attenzione funzione non abilitata, \nsarà inserita 1 sola chiave e 1 sola persona.")
				TheForm.NChiavi.value  = 1 
				TheForm.NPersone.value = 1
				TheForm.SelFlussiDiscountD.selectedIndex = 1;
				TheForm.SelFlussiDiscount.value = TheForm.SelFlussiDiscountD[TheForm.SelFlussiDiscountD.selectedIndex].value;	//'ALLF';
				//TheForm.SelFlussiDiscountD.value = '';	//'ALLF';
				TheForm.SelFlussiDiscountD.disabled = false;
			}
		}
		else {
			//TheForm.SelFlussiDiscountD.selectedIndex = 1;
			if (TheForm.btn_MUltiflussi){TheForm.btn_MUltiflussi.disabled = false;}

			if (TheForm.SelFlussiDiscountD.length > 2 )
			{TheForm.SelFlussiDiscountD.selectedIndex = 0;}
			else{TheForm.SelFlussiDiscountD.selectedIndex = 1;}
			
			TheForm.SelFlussiDiscount.value = TheForm.SelFlussiDiscountD[TheForm.SelFlussiDiscountD.selectedIndex].value;
			TheForm.SelFlussiDiscountD.disabled = false;

		}
}



/**
-------------------------------------------------------
BCCDESC_ONCHANGE(TheForm,tipo)
-------------------------------------------------------
**/
function BCCDesc_onChange(TheForm, tipo, bInsertNegoziAndFranchising){	
	
	bInsertNegoziAndFranchising = bInsertNegoziAndFranchising == 'true' || bInsertNegoziAndFranchising == 'True'

	if (tipo != 0){
		
		if (!bInsertNegoziAndFranchising) {
			
			ComponiFatturazione(TheForm, tipo);

//			if (tipo == "BS"){
				//PopUp = window.open('AvvisoSponsorizzazione.asp', 'avviso','width=500, height=180, resizable=yes, scrollbars=no, status=0');							
//			}
		}
		else {
			
			if (tipo == "GC" || tipo == "CR" || tipo == "BG"){
			    //				alert("Attendere il caricamento della pagina !");
			    setPremuto();
				document.forms[0].action = "/card_master.asp?ACTION=Privilegi&Privilegio_0=2&simulaFranchising=" + true ;
				document.forms[0].submit();
			}
			else if(tipo == "MO" || tipo == "MU"){
				 msg = TheForm.hddDescOperazione.value;
				 TheForm.DescOperazione.value = msg.replace("{0}",tipo =="MO"? "Franchising" : "Retail");
				 TheForm.Importo.focus();
			}
			else {
			    //				alert("Attendere il caricamento della pagina !");
			    setPremuto();
				document.forms[0].action = "/card_master.asp?ACTION=Privilegi&Privilegio_0=2&simulaFranchising=" + false ;
				document.forms[0].submit();				
			}			
		}	
	}
} 


/**
-------------------------------------------------------
COMPONIFATTURAZIONE(TheForm,tipo)
-------------------------------------------------------
**/
function ComponiFatturazione(TheForm,tipo){
	
	if (tipo == "BS" || tipo == "BI"){
	    document.getElementById("tr_sponsorizzazioni").style.display = '';
		PopolaFatturazione(TheForm,1);
		if (TheForm.btnAggiungi!=undefined)
			MostraInput(TheForm.btnAggiungi);
		if (tipo == "BS")
		{
//			TheForm.NumeroContratto.value = 'N.Contratto';
			MostraInput(TheForm.NumeroContratto);
		    document.getElementById("DivContratto").style.display = '';
		}
		else{
			NascondiInput(TheForm.NumeroContratto);
			document.getElementById("DivContratto").style.display = 'none';
		}
		PopolaSponsorizzazione(TheForm,0);
		ComponiDotCom(TheForm,TheForm.Sponsorizzazione.selectedIndex,'Sponsorizzazione',tipo);
	} else {
	    document.getElementById("tr_sponsorizzazioni").style.display = 'none';
		PopolaFatturazione(TheForm,0);
		NascondiInput(TheForm.btnAggiungi);
		NascondiCombo(TheForm.Sponsorizzazione);
		NascondiInput(TheForm.NumeroContratto);
		ComponiDotCom(TheForm,TheForm.Fatturazione.selectedIndex,'Fatturazione',tipo);
	}
}

/**
-------------------------------------------------------
POPOLAFATTURAZIONE(num)
-------------------------------------------------------
**/
function PopolaFatturazione(TheForm,num) {
	//funzione collegata asp PopolaFatturazione()
	RiempiCombo(TheForm.Fatturazione,ElencoFatturazione[num],'');
	MostraCombo(TheForm.Fatturazione);

}

/**
-------------------------------------------------------
POPOLASPONSORIZZAZIONE(num)
-------------------------------------------------------
**/
function PopolaSponsorizzazione(TheForm,num) {
	//funzione collegata asp PopolaSponsorizzazione()
	if (TheForm.Sponsorizzazione) {
		RiempiCombo(TheForm.Sponsorizzazione,ElencoSponsorizzazione[num],'');
		MostraCombo(TheForm.Sponsorizzazione);
	}
}

/**
-------------------------------------------------------
POPOLAISSUEDBY(num)
-------------------------------------------------------
**/
function PopolaIssuedby(TheForm,num) {
	//funzione collegata asp PopolaIssuedby()
	//RiempiCombo(TheForm.Sponsorizzazione,ElencoIssuedby[num],'');
	//MostraCombo(TheForm.Sponsorizzazione);
}



/**
-------------------------------------------------------
COMPONIDOTCOM(TheForm,indice,nomeCombo,tipo)
-------------------------------------------------------
**/
function ComponiDotCom(TheForm,indice,nomeCombo,tipo){

	var bTrovato = false;

		 
	for (i=0; i<ElencoFranchising.length ;i++){
		if (indice == ElencoFranchising[i]){
			var box = TheForm.IdCdc;
			if (box.options.length != 0 ) SvuotaCombo(box);
			box.disabled = true;
			bTrovato = true;
		}
	}
	
	if (!bTrovato) {
		if (tipo == "BS" || tipo == "BI") {
			if (nomeCombo == 'Sponsorizzazione'){
				RiempiCombo(TheForm.IdCdc,ElencoDotCom[indice],'');
				MostraCombo(TheForm.IdCdc)
			}
		}
		else {
			if (nomeCombo == 'Fatturazione') {
				RiempiCombo(TheForm.IdCdc,ElencoDotCom[indice],'');
				MostraCombo(TheForm.IdCdc)
			}
		}
	}
}

/**
-------------------------------------------------------
APRINUOVECOMPANY()
-------------------------------------------------------
**/
function ApriNuoveCompany(){
	var strUrl = "searchCP/default.asp?Tipo=C&QtaASelezionare=1&IdCountry=All&strGoto=/AggiungiNuoveCompany.asp&ConStrIdEliminati=NO&ChiudeFinestra=NO"
	if (window.PopUp)
        if (! PopUp.closed) PopUp.close();
	PopUp = window.open(strUrl, 'avviso','width=640, height=500, resizable=yes, scrollbars=no, status=0');
}

/**
-------------------------------------------------------
SETNEWVALUE(THEFORM, THETEXT, THEVALUE )
-------------------------------------------------------
**/
function SetNewValue(TheForm, TheText, TheValue ){
	var TheForm = document.forms[0];
	TheForm.Fatturazione.options[TheForm.Fatturazione.length] = new Option (TheText,TheValue);
}

/**
-------------------------------------------------------
INIZIALIZZADATICASH(THEFORM)
-------------------------------------------------------
**/
function InizializzaDatiCash(TheForm, bInsertNegoziAndFranchising){
	if(TheForm.TipologiaCash.value == "PR"){
		return;
	}
	if (!bInsertNegoziAndFranchising) {

    //if (!bInsertNegoziAndFranchising && !bGift) {
		PopolaFatturazione(TheForm,0);
		NascondiCombo(TheForm.Sponsorizzazione);
		NascondiInput(TheForm.NumeroContratto);
		if (TheForm.btnAggiungi){
			if (bStile) {
				TheForm.btnAggiungi.style.display = 'none'
			}
		}
		
		//TheForm.SelFlussiCash.value = TheForm.SelFlussiCashD.value
		ComponiDotCom(TheForm,0,'Fatturazione','')
		

			
		if (TheForm.BCCDesc.value == "BS" || TheForm.BCCDesc.value == "BI"){			
		
			//PopUp = window.open('AvvisoSponsorizzazione.asp', 'avviso','width=500, height=180, resizable=yes, scrollbars=no, status=0');
			ComponiFatturazione(TheForm, TheForm.BCCDesc.value);
						
		}
		
	}	
}



/**
-------------------------------------------------------
ADDCOMPANYFATTURAZIONE(THEFORM, OBJ)
-------------------------------------------------------
**/
function AddCompanyFatturazione (TheForm, Obj) {
	
	TheForm.SelFlussiCash.value =  Obj.value;
	
	var bTrovato = false;
	//Popolo la combo Fatturazione con le sole società BasicNet e BasicItalia
	/*PopolaFatturazione(TheForm,2)

	for (i=0; i<ElencoFranchising.length ;i++){
		if (Obj.value == ElencoFranchising[i]) {
			TheForm.Fatturazione.options[TheForm.Fatturazione.length] = new Option (Obj.value + ' - ' + ElencoFranchising[i+1], ElencoFranchising[i+2]);
			bTrovato = true;
		}
	}
	*/
	if(!bTrovato && (TheForm.BCCDesc.value == "BS" || TheForm.BCCDesc.value == "BI"))
		PopolaFatturazione(TheForm,1);
	else
	if (!bTrovato && (TheForm.BCCDesc.value != "BS" || TheForm.BCCDesc.value == "BI"))
		PopolaFatturazione(TheForm,0);		
}

/**
-------------------------------------------------------
ADDCOMPANY(THEFORM, OBJ)
-------------------------------------------------------
**/
function AddCompanyHidden(TheForm, Obj) {
	TheForm.SelFlussiDiscount.value =  Obj.value;
	//In caso di modifica della combo Siti/negozi di validita -- solo caso discount -- faccio comparire il seguente testo
	document.forms[0].lbl_Multiflussi.value = 'Selezionare nuovamente i Siti/Negozi di validità';
	document.forms[0].SelGruppiMultiFlussoD.value = '';
	document.forms[0].multiflusso.value = ''; 	
}
/**
-------------------------------------------------------
InfoPerson(ID) + InfoCompany
-------------------------------------------------------
**/
function InfoPerson(id){
      var strUrl;
      strUrl = 'InfoUser.asp?IDPerson=' + id
      window.open(strUrl,'InfoPerson','menubar=no,height=300,width=400,scrollbars=yes');
}

function InfoCompany(id,IDAddress){
	if (IDAddress == undefined) { IDAddress = 0};
	
	var strUrl;
	strUrl = '/InfoUser.asp?IDCompany=' + id + '&IDAddress=' +IDAddress;
	window.open(strUrl,'InfoCompany','menubar=no,height=400,width=400,scrollbars=yes');
}

function InfoBeneficiario(id){
      var strUrl;
      strUrl = 'InfoUserNew.asp?IDCarta=' + id
      window.open(strUrl,'InfoPerson','menubar=no,height=300,width=400,scrollbars=yes');
}

function InfoBeneficiario2(id){
      var strUrl;
      strUrl = 'http://www.basicbank.net/InfoUserNew.asp?IDCarta=' + id
      window.open(strUrl,'InfoPerson','menubar=no,height=300,width=400,scrollbars=yes');
}
						
/**
-------------------------------------------------------
ValidaPrivilegio(Tipo, Valida,IDAutoCount,IDPrivilegio,BitPrivilegio,flusso)
-------------------------------------------------------
**/
function ValidaPrivilegio(myPage,Tipo,Valida,IDAutoCount,IDPrivilegio,BitPrivilegio,flusso){
	var strPaginaRutorno = ""
	if (Tipo==1) strPaginaRitorno = "/card_master.asp?ACTION=Conferma&stato=S&";
	if (Tipo==2 || Tipo==3) strPaginaRitorno = "/card_privilegio.asp?";
	
	document.forms[0].whichpage.value = myPage;
	
	var strMessaggio = "";
	if (Tipo==1 || Tipo==2) strMessaggio = "Confermi abilitazione/disabilitazione Privilegio ?";
	if (Tipo==3) strMessaggio = "Confermi autorizzazione al trattamento dei dati ?";
	
	if (confirm(strMessaggio)) {
		document.forms[0].action = strPaginaRitorno + "Valida="+Valida+"&IDAutoCount="+IDAutoCount+"&IDPrivilegio="+IDPrivilegio+"&BitPrivilegio="+BitPrivilegio+"&flusso="+flusso;
		document.forms[0].submit();
	}
}
				
/**
-------------------------------------------------------
ValidaCarta(Valida,IDCarta)
-------------------------------------------------------
**/
function ValidaCarta(myPage,Valida,IDCarta){

	if (confirm("Confermi abilitazione/disabilitazione Carta ?")) {

		document.forms[0].whichpage.value = myPage;
		document.forms[0].action = "/card_master_storico.asp?Valida="+Valida+"&IDCarta="+IDCarta;
		document.forms[0].submit();
	}
}

// FILE INCLUSO PER IL FUNZIONAMENTO DEL MENU E DELLE FINESTRE POP-UP
function openWindow(url) {
    popUpWin = window.open(url,'product','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,width=800,height=600,screenX=110,screenY=10,left=110,top=10');

	if (!popUpWin.focus()) {
		popUpWin.focus();
	}

	popUpWin.location.href = url;
	popUpWin.opener = self
}

function openWindowGift(url) {

	popUpWin = window.open(url,'giftwrap','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=250,height=350,screenX=110,screenY=10,left=110,top=10');
	
}

function openWindowTell2(url) {

	popUpWin = window.open(url,'tell','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=420,height=420,screenX=110,screenY=10,left=110,top=10');
}

function openWindowTaglie(url) {

	popUpWin = window.open(url,'taglie','toolbar=0,location=0,scrollbars=1,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,width=580,height=440,screenX=110,screenY=10,left=110,top=10');
}

function openWindowValuta(url) {

	popUpWin = window.open(url,'valuta','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=auto,resizable=0,width=500,height=560,screenX=110,screenY=10,left=110,top=10');
}

function openWindowTell(url) {

	popUpWin = window.open(url,'tell','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=410,height=550,screenX=110,screenY=10,left=110,top=10');
}

function openWindowBC(url) {

	popUpWin = window.open(url,'tell','toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0,width=500,height=550,screenX=110,screenY=10,left=110,top=10');
}

function openWindowDettagli(url) {

	popUpWin = window.open(url,'dettagli','toolbar=0,location=0,directories=0,scrollbars=1,status=0,menubar=0,scrollbars=1,resizable=1,width=750,height=400,screenX=110,screenY=10,left=20,top=100');
}

/**
----------------------------------------------------------------------------------------------------------
	FUNZIONI PER IL POPUP MULTIFLUSSO - viene caricata sul'onLoad del body della card_popUpMultiflusso.asp
----------------------------------------------------------------------------------------------------------
**/
function CaricaChecked(){
	var negEmittente = window.opener.document.forms[0].SelFlussiDiscountD.value;
	var multiflusso = window.opener.document.forms[0].multiflusso.value;

	arrayOfFlussi = multiflusso.split(',');
	
	//Gestisce il cambio di selezione sulla combo SelFlussiDiscountD dopo riapertura del popup
	var myVar	= false;
	if(arrayOfFlussi.length>0)
	{
		for(k = 0; k<arrayOfFlussi.length; k++)
		{
			if(arrayOfFlussi[k]==negEmittente){myVar= true;}
		}
	}

	//Rivalorizzo tutte le checkbox sulla pagina dopo la riapertura
	for (i = 0; i<document.forms[0].MF_Discount.length ; i++)
	{
		if(document.forms[0].MF_Discount[i].getAttribute("id") == "WHOF") {

			CheckCausale (document.forms[0].MF_Discount[i].value, true)
							
		}
		
		//if(myVar)
		//{
			for(j = 0 ; j < multiflusso.length; j++)
			{
				if(document.forms[0].MF_Discount[i].value == arrayOfFlussi[j])
				{
					document.forms[0].MF_Discount[i].checked = true;
				}
			}
		//}

		// Seleziona la checkbok relativa al negozio emittente e la disabilito
		if(document.forms[0].MF_Discount[i].value==negEmittente)
		{
			document.forms[0].MF_Discount[i].checked = true;	
			document.forms[0].MF_Discount[i].disabled = true;

			CheckCausale (document.forms[0].MF_Discount[i].value, false)

		}
		
	} 
	
	//Gestisco anche la selezione dei GruppiMultiflusso 
	var gruppiMultiflusso 	= window.opener.document.forms[0].SelGruppiMultiFlussoD.value;
	if(gruppiMultiflusso.length>0)
	{
		for (m = 0; m<document.forms[0].MF_Discount.length ; m++)
		{
			if(gruppiMultiflusso.indexOf(document.forms[0].MF_Discount[m].getAttribute("id"))!=-1)
			{
			    document.forms[0].MF_Discount[m].checked = true;
				document.forms[0].MF_Discount[m].disabled = true;
			}
		}
	}
	//Rivalorizzo la hidden dei gruppi
	document.forms[0].GruppiMultiflussoD.value = gruppiMultiflusso;
	if(gruppiMultiflusso != ""){
		var arrGruppiMultiflusso = gruppiMultiflusso.split(",");
		for(var tmp in arrGruppiMultiflusso){
			if(arrGruppiMultiflusso[tmp] != ""){
				var chkName = "chk"+arrGruppiMultiflusso[tmp];
				document.getElementById(chkName).checked = true;
			}
		}
	}


}

/**
----------------------------------------------------------------------------------------------------------
	FUNZIONI PER IL POPUP MULTIFLUSSO - viene caricata sul'onLoad del body della card_popUpMultiflusso.asp
	DOVRA SOSTITUIRE LA PRECEDENTE CaricaChecked()
----------------------------------------------------------------------------------------------------------
**/
function CaricaCheckedII(callerSelFlussiDiscountD, callerMultiflusso, callerSelGruppiMultiFlussoD)
{
	var negEmittente = callerSelFlussiDiscountD.value;
	var multiflusso = callerMultiflusso.value;
	if (multiflusso != "") {
	    arrayOfFlussi = multiflusso.split(',');

	    //Gestisce il cambio di selezione sulla combo SelFlussiDiscountD dopo riapertura del popup
	    var myVar = false;
	    if (arrayOfFlussi.length > 0) {
	        for (k = 0; k < arrayOfFlussi.length; k++) {
	            if (arrayOfFlussi[k] == negEmittente) { myVar = true; }
	        }
	    }

	    //Rivalorizzo tutte le checkbox sulla pagina dopo la riapertura

	    for (i = 0; i < document.forms[0].MF_Discount.length; i++) {
	        if (document.forms[0].MF_Discount[i].getAttribute("id") == "WHOF") {

	            CheckCausale(document.forms[0].MF_Discount[i].value, true)

	        }

	        for (j = 0; j < multiflusso.length; j++) {
	            if (document.forms[0].MF_Discount[i].value == arrayOfFlussi[j]) {
	                document.forms[0].MF_Discount[i].checked = true;
	            }
	        }

	        // Seleziona la checkbok relativa al negozio emittente e la disabilito
	        if (document.forms[0].MF_Discount[i].value == negEmittente) {
	            document.forms[0].MF_Discount[i].checked = true;
	            document.forms[0].MF_Discount[i].disabled = true;

	            CheckCausale(document.forms[0].MF_Discount[i].value, false)

	        }

	    }

	    //Gestisco anche la selezione dei GruppiMultiflusso
//	    var gruppiMultiflusso = callerSelGruppiMultiFlussoD.value;
	    if (gruppiMultiflusso.length > 0) {
	        for (m = 0; m < document.forms[0].MF_Discount.length; m++) {
	            if (gruppiMultiflusso.indexOf(document.forms[0].MF_Discount[m].getAttribute("id")) != -1) {
	                document.forms[0].MF_Discount[m].checked = true;
	                document.forms[0].MF_Discount[m].disabled = true;
	            }
	        }
	    }
	    
	    //Rivalorizzo la hidden dei gruppi
	    document.forms[0].GruppiMultiflussoD.value = gruppiMultiflusso;

	    if (gruppiMultiflusso != "") {
	        var arrGruppiMultiflusso = gruppiMultiflusso.split(",");
	        for (var tmp in arrGruppiMultiflusso) {
	            if (arrGruppiMultiflusso[tmp] != "") {
	                var chkName = "chk" + arrGruppiMultiflusso[tmp];
	                document.getElementById(chkName).checked = true;
	            }
	        }
	    }
	}
}

function CheckCausale(flusso, bDisabled) {
	var tmpVarOR = document.getElementById(flusso + "_OR");
	var tmpVarOC = document.getElementById(flusso + "_OC");
	var tmpVarOT = document.getElementById(flusso + "_OT");

	if(tmpVarOR)
		tmpVarOR.disabled = bDisabled;

	if(tmpVarOC)
		tmpVarOC.disabled = bDisabled;
		
	if(tmpVarOT)
		tmpVarOT.disabled = bDisabled;

	if (bDisabled) 
	{
		if (tmpVarOR)
			tmpVarOR.checked = false;
		if (tmpVarOC)
			tmpVarOC.checked = false;
		if (tmpVarOT)
			tmpVarOT.checked = false;
	}
		
}

function CheckCausaleOne(flusso, elencoCausali)
{
	for (index = 0; index < elencoCausali.length; index++)
	{
		var tmpCausale = document.getElementById(flusso + "_" + elencoCausali[index]);
		if (tmpCausale)
		{
			for (idxIntern = 0; idxIntern < elencoCausali.length; idxIntern++)
				if (index != idxIntern)
				{
					var tmpAltraCausale = document.getElementById(flusso + "_" + elencoCausali[idxIntern]);
					if (tmpAltraCausale)
					{
						if (tmpCausale.checked)
							tmpAltraCausale.disabled = true;
						else
							tmpAltraCausale.disabled = false;
					}
				}
		}
	}
}



function CheckMultiflussi(GruppoMF,ALLF){

	//Valorizzo la variabile sui raggruppamenti multiflusso che sono stati creati
    var myGroups = document.forms[0].GruppiMultiflussoD.value
    bAbilita = true;
    if (document.getElementById("chk" + GruppoMF)) {
        var bAbilita = document.getElementById("chk" + GruppoMF).checked;
    }
//	if(myGroups.indexOf(GruppoMF) ==-1)
//	{
		if(bAbilita){
			document.forms[0].GruppiMultiflussoD.value = document.forms[0].GruppiMultiflussoD.value + GruppoMF + ',';	
		}else{
			
			document.forms[0].GruppiMultiflussoD.value = document.forms[0].GruppiMultiflussoD.value.replace(GruppoMF + ',','');
		}
//	}
	
	for (i = 0; i< document.forms[0].MF_Discount.length ; i++)
	{		
		//Se l'id della checkbox attuale = groupMF
		if(document.forms[0].MF_Discount[i].getAttribute("id") == GruppoMF)
		{
		
			if (GruppoMF == "WHOF")
				CheckCausale (document.forms[0].MF_Discount[i].value, false)
			if (!ALLF) 
			{
				document.forms[0].MF_Discount[i].disabled = true;
			}
			document.forms[0].MF_Discount[i].checked = bAbilita ;
		}
	}
}



function ChiudiFormMultiflusso(){
	var selezionati = false;
	var conferma 	= false;
	var res; 
	res = confirm('Sei sicuro di confermare i negozi selezionati?');
	if (!res)
	{
		return false;
	}
	
	var mystring = '';
	for (i = 0; i< document.forms[0].MF_Discount.length ; i++)
	{
		if (document.forms[0].MF_Discount[i].checked)
		{
		    mystring = mystring + document.forms[0].MF_Discount[i].value + ',';
			selezionati = true;
		}
	}	
	var lstring = mystring.length;

	mystring = mystring.substr(mystring,lstring-1);
	
	if(!selezionati)
	{
		alert("Selezionare almeno un negozio.");
		return false;
	}
	else
	{
		var labelMultiflusso = '';
		if(mystring.length>5)
		{
			labelMultiflusso = 'Multiflusso';
		}
		else
		{
			for(j=0; j<document.forms[0].labelFlusso.length ;j++)
			{
				if(document.forms[0].labelFlusso[j].getAttribute("id") == mystring)
				{
					labelMultiflusso = document.forms[0].labelFlusso[j].getAttribute("value");
				}
			}			
		}
		var mystring2 = document.forms[0].GruppiMultiflussoD.value;
//		if(mystring2.length>0)
//		{
		    window.opener.document.forms[0].SelGruppiMultiFlussoD.value = mystring2;
//		}
		//Assegno il valore all'etichetta
		    if (window.opener.document.forms[0].lbl_Multiflussi) {
		        window.opener.document.forms[0].lbl_Multiflussi.value = labelMultiflusso;
		        MostraInputMF(window.opener.document.forms[0].lbl_Multiflussi);
		        window.opener.document.forms[0].multiflusso.value = mystring;
		    }
		    else {
		        window.opener.document.getElementById("ctl00_ContentPlaceHolder1_" + lbl_Multiflussi).value = labelMultiflusso
		        MostraInputMF(window.opener.document.getElementById("ctl00_ContentPlaceHolder1_" + lbl_Multiflussi));
		        window.opener.document.getElementById("ctl00_ContentPlaceHolder1_" +multiflusso).value = mystring;
		    }
		
		
		visualizzaChiaviUtentiDiscount(mystring);
		//Attivazione automatica del privilegio Discount per KSTR
		//if (document.forms[0].AttivaDC[0].checked)
		//	window.opener.document.forms[0].AttivaDC.value = "1";
		//else
		//	window.opener.document.forms[0].AttivaDC.value = "0";


		//default discount
		var tempValue = "4";
		//controllo esistenza oggetto TipologiaDiscount
		if (document.forms[0].TipologiaDiscount) {
			for(j=0; j<document.forms[0].TipologiaDiscount.length ;j++){
				if (document.forms[0].TipologiaDiscount[j].checked)
					tempValue = document.forms[0].TipologiaDiscount[j].value;
			}
		}
		//controllo esistenza oggetto SelDiscountCombo
		if (window.opener.document.forms[0].SelDiscountCombo) {
			window.opener.document.forms[0].SelDiscountCombo.value = tempValue;
			window.opener.document.forms[0].SelDiscountCombo.disabled = true;
		}
		//assegnazione bitprivilegio Discount
		window.opener.document.forms[0].SelDiscount.value = tempValue;

		// Legge le impostazioni per la causale ordine e compone una stringa con gli eventuali settaggi separati da virgola
		var causaleOrdine = '';
		for (i = 0; i< document.forms[0].MF_Causale.length ; i++)
		{
			if (document.forms[0].MF_Causale[i].checked)
			{
				causaleOrdine = causaleOrdine + document.forms[0].MF_Causale[i].value + ',';
			}
		}

		window.opener.document.forms[0].SelCausaliWholeSale.value = causaleOrdine;

		window.close();
		return true;
	}
}

// Data: 16/10/2006
// Questa versione scrive le informazioni recuperata dalla pagina negli oggetti passati alla funzione stessa
// Dovrà essere sostituita a quella precedente, quando funzionerà correttamente
// Il parametro <callerSelDiscountCombo> può assumere il valore <null>
function ChiudiFormMultiflussoII(callerSelGruppiMultiFlussoD, callerLbl_Multiflussi, callerMultiflusso, callerSelDiscountCombo,
    callerSelDiscount, callerSelCausaliWholeSale)
{
	var selezionati = false;
	var conferma 	= false;
	var res;
	res = confirm('Sei sicuro di confermare i negozi selezionati?');
	if (!res)
	{
		return false;
	}

	var mystring = '';
	for (i = 0; i< document.forms[0].MF_Discount.length ; i++)
	{
		if (document.forms[0].MF_Discount[i].checked)
		{
			mystring = mystring + document.forms[0].MF_Discount[i].value + ',';
			selezionati = true;
		}
    }
    
	var lstring = mystring.length;

	mystring = mystring.substr(mystring,lstring-1);

	if(!selezionati)
	{
		alert("Selezionare almeno un negozio.");
		return false;
	}
	else
	{
		var labelMultiflusso = '';
		if(mystring.length>5)
		{
			labelMultiflusso = 'Multiflusso';
		}
		else
		{
			for(j=0; j<document.forms[0].labelFlusso.length ;j++)
			{
				if(document.forms[0].labelFlusso[j].getAttribute("id") == mystring)
				{
					labelMultiflusso = document.forms[0].labelFlusso[j].getAttribute("value");
				}
			}
		}
		var mystring2 = document.forms[0].GruppiMultiflussoD.value;
		if(mystring2.length>0)
		{
			callerSelGruppiMultiFlussoD.value = mystring2;
		}

	
		//Assegno il valore all'etichetta
		//callerLbl_Multiflussi.value = labelMultiflusso;
		callerLbl_Multiflussi.innerText = labelMultiflusso;
	    MostraInputMF(callerLbl_Multiflussi);
	    callerMultiflusso.value = mystring;

		//Attivazione automatica del privilegio Discount per KSTR
		//if (document.forms[0].AttivaDC[0].checked)
		//	window.opener.document.forms[0].AttivaDC.value = "1";
		//else
		//	window.opener.document.forms[0].AttivaDC.value = "0";


		//default discount
		var tempValue = "4";
		//controllo esistenza oggetto TipologiaDiscount
		if (document.forms[0].TipologiaDiscount) {
			for(j=0; j<document.forms[0].TipologiaDiscount.length ;j++){
				if (document.forms[0].TipologiaDiscount[j].checked)
					tempValue = document.forms[0].TipologiaDiscount[j].value;
			}
		}
		//controllo esistenza oggetto SelDiscountCombo
		if (callerSelDiscountCombo) {
			callerSelDiscountCombo.value = tempValue;
			callerSelDiscountCombo.disabled = true;
		}
		//assegnazione bitprivilegio Discount
		callerSelDiscount.value = tempValue;

		// Legge le impostazioni per la causale ordine e compone una stringa con gli eventuali settaggi separati da virgola
		var causaleOrdine = '';
		for (i = 0; i< document.forms[0].MF_Causale.length ; i++)
		{
			if (document.forms[0].MF_Causale[i].checked)
			{
				causaleOrdine = causaleOrdine + document.forms[0].MF_Causale[i].value + ',';
			}
		}

		callerSelCausaliWholeSale.value = causaleOrdine;
		window.close();
		return true;
	}
}

function Azzera_lbl_MultiflussiCash()
{
	NascondiInputMF(document.forms[0].lbl_Multiflussi);
}

//######################### CREDIT ##########################
function CheckMultiflussiCredit(GruppoMF){		
	//Valorizzo la variabile sui raggruppamenti multiflusso che sono stati creati
	
	var myGroups = document.forms[0].GruppiMultiflussoCredit.value

	if(myGroups.indexOf(GruppoMF) ==-1)
	{
		document.forms[0].GruppiMultiflussoCredit.value = document.forms[0].GruppiMultiflussoCredit.value + GruppoMF + ',';
	}
	
	for (i = 0; i< document.forms[0].MF_DiscountCredit.length ; i++)
	{
		//Se l'id della checkbox attuale = groupMF
		if(document.forms[0].MF_DiscountCredit[i].getAttribute("id") == GruppoMF)
		{
			document.forms[0].MF_DiscountCredit[i].disabled = true;
			document.forms[0].MF_DiscountCredit[i].checked = true;
		}
	}	
}

function CaricaCheckedCredit(){

	var multiflussoCredit = window.opener.document.forms[0].multiflussocredit.value;

	arrayOfFlussi = multiflussoCredit.split(',');

	//Alla riapertura del popup dopo una prima selezione riposiziono i valorei sulle checkbox
	for (i = 0; i< document.forms[0].MF_DiscountCredit.length ; i++)
	{
		for(j = 0 ; j < multiflussoCredit.length; j++)
		{
			if(document.forms[0].MF_DiscountCredit[i].value == arrayOfFlussi[j])
			{
				document.forms[0].MF_DiscountCredit[i].checked = true;
			}
		}
	}	
	
	//Gestisco anche la selezione dei GruppiMultiflusso
	var gruppiMultiflussoCredit 	= window.opener.document.forms[0].SelGruppiMultiFlussoCredit.value;
	if(gruppiMultiflussoCredit.length>0)
	{
		for (m = 0; m<document.forms[0].MF_DiscountCredit.length ; m++)
		{
			if(gruppiMultiflussoCredit.indexOf(document.forms[0].MF_DiscountCredit[m].getAttribute("id"))!=-1)
			{
				document.forms[0].MF_DiscountCredit[m].disabled = true;
			}
		}
	}
	//Rivalorizzo la hidden dei gruppi
	document.forms[0].GruppiMultiflussoCredit.value = gruppiMultiflussoCredit;

}

function ChiudiFormMultiflussoCredit(){
	var selezionati = false;
	var conferma 	= false;
	var res; 
	res = confirm('Sei sicuro di confermare i negozi selezionati?');
	if (!res)
	{
		return false;
	}
	
	var mystring = '';
	for (i = 0; i< document.forms[0].MF_DiscountCredit.length ; i++)
	{
		if (document.forms[0].MF_DiscountCredit[i].checked)
		{
			mystring = mystring + document.forms[0].MF_DiscountCredit[i].value + ',';
			selezionati = true;
		}
	}	
	var lstring = mystring.length;

	mystring = mystring.substr(mystring,lstring-1);
	
	if(!selezionati)
	{
		alert("Selezionare almeno un negozio.");
		return false;	
	}
	else
	{
		var labelMultiflussoCredit = '';
		if(mystring.length>5)
		{
			labelMultiflussoCredit = 'Multiflusso';
		}
		else
		{
			for(j=0; j<document.forms[0].labelFlussoCredit.length ;j++)
			{
				if(document.forms[0].labelFlussoCredit[j].getAttribute("id") == mystring)
				{
					labelMultiflussoCredit = document.forms[0].labelFlussoCredit[j].getAttribute("value");
				}
			}			
		}
		var mystring2 = document.forms[0].GruppiMultiflussoCredit.value;
		if (mystring2.length >= 5)
		{
			mystring2 = mystring2.substr(mystring2,mystring2.length-1);
			window.opener.document.forms[0].SelGruppiMultiFlussoCredit.value = document.forms[0].GruppiMultiflussoCredit.value;
		}		
		window.opener.document.forms[0].lbl_MultiflussiCredit.value = labelMultiflussoCredit;
		MostraInputMF(window.opener.document.forms[0].lbl_MultiflussiCredit);
		window.opener.document.forms[0].multiflussocredit.value = mystring;
		
		window.close();
		return true;
	}	
}
//######################## CREDIT FINE ##########################


//------------------Multiflusso Cash--------------------------------------------------------
 
function CaricaCheckedCash(){

	var multiflussocash = window.opener.document.forms[0].multiflussocash.value;

	arrayOfFlussi = multiflussocash.split(',');

	//Alla riapertura del popup dopo una prima selezione riposiziono i valorei sulle checkbox
	for (i = 0; i< document.forms[0].MF_DiscountCash.length ; i++)
	{
		for(j = 0 ; j < multiflussocash.length; j++)
		{
			if(document.forms[0].MF_DiscountCash[i].value == arrayOfFlussi[j])
			{
				document.forms[0].MF_DiscountCash[i].checked = true;
			}
		}
	}	
	
	//Gestisco anche la selezione dei GruppiMultiflusso
	var gruppiMultiflussoCash 	= window.opener.document.forms[0].SelGruppiMultiFlussoCash.value;
	if(gruppiMultiflussoCash.length>0)
	{
		for (m = 0; m<document.forms[0].MF_DiscountCash.length ; m++)
		{
			if(gruppiMultiflussoCash.indexOf(document.forms[0].MF_DiscountCash[m].getAttribute("id"))!=-1)
			{
				document.forms[0].MF_DiscountCash[m].disabled = true;
			}
		}
	}
	//Rivalorizzo la hidden dei gruppi
	document.forms[0].GruppiMultiflussoCash.value = gruppiMultiflussoCash;

}

function CheckMultiflussiCash(GruppoMF){		
	//Valorizzo la variabile sui raggruppamenti multiflusso che sono stati creati
	
	var myGroups = document.forms[0].GruppiMultiflussoCash.value
	if(myGroups.indexOf(GruppoMF) ==-1)
	{
		document.forms[0].GruppiMultiflussoCash.value = document.forms[0].GruppiMultiflussoCash.value + GruppoMF + ',';
	}
	
	for (i = 0; i< document.forms[0].MF_DiscountCash.length ; i++)
	{
		//Se l'id della checkbox attuale = groupMF
		if(document.forms[0].MF_DiscountCash[i].getAttribute("id") == GruppoMF)
		{
			/*document.forms[0].MF_DiscountCash[i].disabled = true;*/
			document.forms[0].MF_DiscountCash[i].checked = true;
		}
	}	
}

function ChiudiFormMultiflussoCash(){
	var selezionati = false;
	var conferma 	= false;
	var res; 
	res = confirm('Sei sicuro di confermare i negozi selezionati?');
	if (!res)
	{
		return false;
	}
	
	var mystring = '';
	for (i = 0; i< document.forms[0].MF_DiscountCash.length ; i++)
	{
		if (document.forms[0].MF_DiscountCash[i].checked)
		{
			mystring = mystring + document.forms[0].MF_DiscountCash[i].value + ',';
			selezionati = true;
		}
	}	
	var lstring = mystring.length;

	mystring = mystring.substr(mystring,lstring-1);
	
	if(!selezionati)
	{
		alert("Selezionare almeno un negozio.");
		return false;	
	}
	else
	{
		var labelMultiflussoCash = '';
		if(mystring.length>5)
		{
			labelMultiflussoCash = 'Multiflusso';
		}
		else
		{
			for(j=0; j<document.forms[0].labelFlussoCash.length ;j++)
			{
				if(document.forms[0].labelFlussoCash[j].getAttribute("id") == mystring)
				{
					labelMultiflussoCash = document.forms[0].labelFlussoCash[j].getAttribute("value");
				}
			}			
		}
		var mystring2 = document.forms[0].GruppiMultiflussoCash.value;
		if (mystring2.length >= 5)
		{
			mystring2 = mystring2.substr(mystring2,mystring2.length-1);
			window.opener.document.forms[0].SelGruppiMultiFlussoCash.value = document.forms[0].GruppiMultiflussoCash.value;
		}		
		window.opener.document.getElementById("tr_MultiflussiCash").style.display = "";
		window.opener.document.forms[0].lbl_MultiflussiCash.value = labelMultiflussoCash;
		MostraInputMF(window.opener.document.forms[0].lbl_MultiflussiCash);
		window.opener.document.forms[0].multiflussocash.value = mystring;
		
		window.close();
		return true;
	}	
}

function InizializzaDatiMultiflussoCash(TheForm){	
	NascondiInputMF(TheForm.lbl_MultiflussiCash);		
}

function InizializzaDatiMultiflusso(TheForm){	
	NascondiInputMF(TheForm.lbl_Multiflussi);		
}

function MostraInputMF(txt){
	txt.size=55;
	txt.disabled=false;
	if (bStile) txt.style.display = ''
}

function NascondiInputMF(txt){
	//txt.value='*****'
	if (txt != null){
		txt.disabled=true;
		if (bStile) txt.style.display = 'none'
	}
}

function OpenPopUpConsumato(idcarta,idgruppo,bitprivilegio,emessoDa,sconto)
{
    window.open('Riepilogo_Consumato.asp?idcarta='+idcarta+'&idgruppo='+idgruppo+'&bitprivilegio='+bitprivilegio+'&emessoDa='+emessoDa+'&sconto='+sconto,'consumato','scrollbars=yes,resizable=yes,width=700,height=400,left=100,top=100')
}

function OpenPopUpConsumatoCRAL(idcarta, idgruppo, bitprivilegio, sconto)
{
    window.open('riepilogo_consumato_cral.asp?idcarta='+idcarta+'&idgruppo='+idgruppo+'&bitprivilegio='+bitprivilegio+'&sconto='+sconto,'consumato','scrollbars=yes,resizable=yes,width=400,height=400,left=100,top=100');
}

function InfoBasiccardDett(numOrdine, flusso, bitprivilegio)
{
      strUrl = "Info_BasicCard_Dett.asp?nOrdine=" + numOrdine + "&flusso=" + flusso + "&bitprivilegio=" + bitprivilegio;
      window.open(strUrl,"Info",'scrollbars=yes,resizable=yes,width=600,height=330,left=20,top=20');
}

function InfoBasiccardDettSameWindow(numOrdine, flusso, bitprivilegio)
{
      strUrl = "Info_BasicCard_Dett.asp?nOrdine=" + numOrdine + "&flusso=" + flusso + "&bitprivilegio=" + bitprivilegio;
      document.location = strUrl;
}

//Pulsante reset su card_PopUpMultiflusso.asp
function ResetCheckMultiflussoD()
{
	// Svuoto le hidden sulla card_discount.asp	
	window.opener.document.forms[0].SelGruppiMultiFlussoD.value = '';
	window.opener.document.forms[0].multiflusso.value = '';
	window.document.forms[0].submit();
}

//Pulsante reset su card_PopUpMultiflussoII.asp
function ResetCheckMultiflussoDII(callerSelGruppiMultiFlussoD, callerMultiflusso)
{
	// Svuoto le hidden sulla card_discount.asp
	callerSelGruppiMultiFlussoD.value = '';
	callerMultiflusso.value = '';
	window.document.forms[0].submit();

}

//Pulsante reset su card_PopUpMultiflussoCash.asp
function ResetCheckMultiflussoCash()
{
	// Svuoto le hidden sulla card_cash.asp
	window.opener.document.forms[0].SelGruppiMultiFlussoCash.value = '';
	window.opener.document.forms[0].multiflussocash.value = '';
	window.document.forms[0].submit();
}


/**
-------------------------------------------------------
SelezionaCheck(flg)
-------------------------------------------------------
**/
function SelezionaCheck (flg)
{
	
	if (flg == 0)
	{
		var stato = false;
	}
	else
	{
		var stato = true;
	}
	if (document.forms[0].chk_add)
	{			
		if (document.forms[0].chk_add.length == undefined)	
			document.forms[0].chk_add.checked = stato;
		else
			for (i=0; i<document.forms[0].chk_add.length; i++)
			{
				document.forms[0].chk_add[i].checked = stato;
			}
	}
}

/**
-------------------------------------------------------
btnStampa_onClick()
-------------------------------------------------------
**/
function btnStampa_onClick(ThePage){
	var bsubmit = false;
	
	if (document.forms[0].chk_add.length == undefined) {	
		if (document.forms[0].chk_add.checked)
			bsubmit = true;
	}			
	else {
		for (i=0; i<document.forms[0].chk_add.length; i++)
		{
			if (document.forms[0].chk_add[i].checked )
			{
				bsubmit = true;
				break
			}
				
		}
	}
	
	if (bsubmit) {
		document.forms[0].isPostBack.value = "OK";
		document.forms[0].action = ThePage;
		document.forms[0].submit();
	}
	else {
		alert("Selezionare almeno una Card.")
	}
}  

/**
-------------------------------------------------------
AddIdCompanyLocation(TheForm, TheObject)
DEVE esistere nella pagina che utilizza questa funzione un oggetto HTML
con attributo id idFlussiRetail che contenga l'elenco dei flussi RETAIL
-------------------------------------------------------
**/
function AddIdCompanyLocation(TheForm, TheObject){
	
	//controllo che esista l'oggetto
	var showLocationAddress = false;
	if (TheForm.IDCompanyLocation) {
		var flussiRetailObj = document.getElementById('idFlussiRetail');
		if (flussiRetailObj != null && TheObject.value != '') {
			var idxString = flussiRetailObj.value.indexOf(TheObject.value);
			if (idxString >= 0)
				showLocationAddress = true;
		}
		if (showLocationAddress == true) {
			//mostra combo
			TheForm.IDCompanyLocation.disabled = false;
			if (bStile) TheForm.IDCompanyLocation.style.display = '';
			TheForm.setteb0.style.display = '';
			TheForm.setteb1.style.display = '';
//			TheForm.setteb2.style.display = '';
			TheForm.setteb3.style.display =  '';
		}
		else {
			//disabilita combo
			TheForm.IDCompanyLocation.disabled = true;
			if (bStile) TheForm.IDCompanyLocation.style.display = 'none';
			TheForm.setteb0.style.display = 'none';
			TheForm.setteb1.style.display = 'none';
//			TheForm.setteb2.style.display = 'none';
			TheForm.setteb3.style.display = 'none';
		}
	}
}

/**
---------------------------------------------------------
AbilitaDescrizione (TheForm, TheObject)
---------------------------------------------------------
**/
function AbilitaDescrizione (TheForm, TheObject){
	if (TheObject.value != 10 )  {
		TheForm.Descrizione.disabled = false;
//		TheForm.Descrizione.value = TheObject.options[ TheObject.selectedIndex].text;
		TheForm.Descrizione.value = document.getElementById("txtDescSconto").value;

	}
	else {
		TheForm.Descrizione.disabled = false;
		TheForm.Descrizione.value = "";

	}

	if (TheObject.value == 0)  {
	    if (TheForm.SelExtraDiscount)
		    TheForm.SelExtraDiscount.disabled = false;
		TheForm.Descrizione.disabled = true;
		TheForm.Descrizione.value = "Non disponibile";
	}
	else {
//	    if (TheForm.SelExtraDiscount)
//		    TheForm.SelExtraDiscount.disabled = true;
	}
}

/**
---------------------------------------------------------
SplitReverse(inp)
---------------------------------------------------------
**/

function SplitReverse(inp) {
	var temp = '';
	var outp = '';
	
	temp = inp.split('/')
	
	if (temp.length > 0)
		outp = temp [2] + temp [1] + temp [0]
		
	return outp ;
} 


/**
---------------------------------------------------------
AggiornaPosizionePromozioni(whichpage, IDPromozione, PosizioneCombo, Direzione, IDTipologia)
---------------------------------------------------------
**/

function AggiornaPosizionePromozioni(whichpage, selPageSize, IDPromozione, PosizioneCombo, Direzione, IDTipologia) { 	
	var Redirect = "card_promozioni_base.asp";
	window.document.location.href = '/card_promozioni_base_update.asp?Posizioni=1&Redirect='+Redirect+'&IDPromozione='+IDPromozione+'&PosizioneCombo='+PosizioneCombo+'&Direzione='+Direzione+'&whichpage='+whichpage+'&selPageSize='+selPageSize+'&IDTipologia='+IDTipologia;
} 

/**
-------------------------------------------------------
ApriAggiornamentoPromozioni(Posizioni, whichpage, selPageSize, IDPromozione,IDTipologia) dovrà essere eliminata perchè sostituita dalla versione II
-------------------------------------------------------
**/
function ApriAggiornamentoPromozioni(Posizioni, whichpage, selPageSize, IDPromozione, IDTipologia){
	var Redirect = "card_promozioni_base.asp";
	window.open('/card_promozioni_base_update.asp?Posizioni='+Posizioni+'&Redirect='+Redirect+'&IDPromozione='+IDPromozione+'&whichpage='+whichpage+'&selPageSize='+selPageSize+'&IDTipologia='+IDTipologia,'AggiornaPromozioni','scrollbars=yes,resizable=no,width=600,height=400,left=100,top=100');
}

/**
-------------------------------------------------------
ApriAggiornamentoPromozioniII(Posizioni, whichpage, selPageSize, IDPromozione,IDTipologia)
-------------------------------------------------------
**/
function ApriAggiornamentoPromozioniII(Posizioni, whichpage, selPageSize, IDPromozione, IDTipologia, pubblicazione, filtro, valoreFiltro){
    
    if (pubblicazione == undefined){
        pubblicazione = 1;
    }
	var Redirect = "card_promozioni_base.asp";
	if (filtro != undefined || valoreFiltro != undefined) {
	    //window.open('/card_promozioni_base_update_II.asp?Posizioni='+Posizioni+'&Redirect='+Redirect+'&IDPromozione='+IDPromozione+'&whichpage='+whichpage+'&selPageSize='+selPageSize+'&IDTipologia='+IDTipologia+'&pubblicazione='+pubblicazione+'&filtro='+filtro+'&valoreFiltro='+valoreFiltro,'AggiornaPromozioni','scrollbars=yes,resizable=no,width=600,height=700,left=100,top=100');
	    window.open('/jump.asp?GOTO=http://www2.basicbank.net/bbx/Jump.aspx&WHERE=http://www2.basicbank.net/bbx/AmministraConvenzioni.aspx?IDPromozione=' + IDPromozione, 'AggiornaPromozioni', 'scrollbars=yes,resizable=yes,width=1050,height=700,left=100,top=100');
	} else {
	    //window.open('/card_promozioni_base_update_II.asp?Posizioni='+Posizioni+'&Redirect='+Redirect+'&IDPromozione='+IDPromozione+'&whichpage='+whichpage+'&selPageSize='+selPageSize+'&IDTipologia='+IDTipologia+'&pubblicazione='+pubblicazione,'AggiornaPromozioni','scrollbars=yes,resizable=no,width=600,height=700,left=100,top=100');
	    if (IDPromozione == 0) {
	        window.open('/jump.asp?GOTO=http://www2.basicbank.net/bbx/Jump.aspx&WHERE=http://www2.basicbank.net/bbx/AmministraConvenzioni.aspx', 'AggiornaPromozioni', 'scrollbars=yes,resizable=yes,width=1050,height=700,left=100,top=100');
	    } else {
	        window.open('/jump.asp?GOTO=http://www2.basicbank.net/bbx/Jump.aspx&WHERE=http://www2.basicbank.net/bbx/AmministraConvenzioni.aspx?IDPromozione=' + IDPromozione, 'AggiornaPromozioni', 'scrollbars=yes,resizable=yes,width=1050,height=700,left=100,top=100');
	    } 
	}  
}

/**
-------------------------------------------------------
Funzioni per cambio modalità cursore
-------------------------------------------------------
**/

function Clessidra() {
	document.body.style.cursor = "wait";
}
		
function No_Clessidra() {
	document.body.style.cursor = "default";
}

/**
---------------------------------------------------------------------------------------------------------------
Controlla il cambio location company e se diverso dalla location base blocca il tipo di gruppo di sconto
---------------------------------------------------------------------------------------------------------------
**/
function ChangeCompanyLocation(htmlIdSelectLocation, baseIdLocation, htmlIdSelExtraDiscount, htmlIdSelectDiscount, 
								indexDiscountToSet)
{
	if (document.getElementById(htmlIdSelectLocation))
	{
		if (document.getElementById(htmlIdSelectLocation).value == baseIdLocation)
		{
			document.getElementById(htmlIdSelectDiscount).disabled = false;
			document.getElementById(htmlIdSelectDiscount).selectedIndex = 0;
			document.getElementById(htmlIdSelectDiscount).onchange();
		}
		else
		{
			document.getElementById(htmlIdSelExtraDiscount).selectedIndex = 0;
			document.getElementById(htmlIdSelExtraDiscount).onchange();
			document.getElementById(htmlIdSelectDiscount).selectedIndex = indexDiscountToSet;
			document.getElementById(htmlIdSelectDiscount).onchange();
			document.getElementById(htmlIdSelectDiscount).disabled = true;
		}
	}	
}

function IsNumeric(sText)
{
	var ValidChars = "0123456789.";
	var IsNumber = true;
	var Char;
 
	for (i = 0; i < sText.length && IsNumber == true; i++) 
	{ 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) 
		{
			IsNumber = false;
		}
	}
	return IsNumber;
}

function thousandSeparator(decimalDigits, Value)
{
    // Separator Length. Here this is thousand separator 
    var separatorLength = 3; 
    var OriginalValue = Math.round(Value * Math.pow(10, decimalDigits)) / Math.pow(10, decimalDigits);
    var TempValue = "" + OriginalValue;
    var NewValue = ""; 

    // Store digits after decimal 
    var pStr;

    // store digits before decimal 
    var dStr; 

    // Add decimal point if it is not there
	if (TempValue.indexOf(".") == -1)
	{
	   TempValue+="."
	}

    dStr=TempValue.substr(0,TempValue.indexOf(".")); 

    pStr=TempValue.substr(TempValue.indexOf(".")) 

    // Add "0" for remaining digits after decimal point 
    while (pStr.length-1< decimalDigits){pStr+="0"} 

    if(pStr =='.') 
            pStr ='';
   //----LC 05/02/2009---------------------------------------//
   //se la variabile ha un segno bisogna che non rientri nel conteggio del separatore delle migliaia 
   //quindi sottraggo 1 alla lunghezza della stringa
   len = dStr.length;
   if(dStr.substr(0,1) == "-" || dStr.substr(0,1) == "+")
	   len--;
   //--------------------------------------------------------//
   if(len > separatorLength) 
  {
        // Logic of separation 
       while( dStr.length > separatorLength) 
      {
              NewValue = "," + dStr.substr(dStr.length - separatorLength) + NewValue;
             dStr = dStr.substr(0,dStr.length - separatorLength);
       }
       NewValue = dStr + NewValue; 
   }
   else 
  {
       NewValue = dStr;
   }
   // Add decimal part 
   NewValue = NewValue + pStr;
    // Show Final value 
    return NewValue; 
}

function CalcolaDifferenza(objFirst, objSecond)
{
	if (IsNumeric(objFirst.value) == true && IsNumeric(objSecond.value) == true)
		return objFirst.value - objSecond.value;
	else
		return 0;
}

function OpenAbilitaStorico()
{
	var flusso = '';
	var CPCash = '';
	if (document.getElementById('IdFlussoCardAbilita'))
		flusso = document.getElementById('IdFlussoCardAbilita').value;
	if (document.getElementById('IdCPCashCardAbilita'))
		CPCash = document.getElementById('IdCPCashCardAbilita').value;
	window.location.href = '/card_abilitaStorico.asp?Flusso=' + flusso + '&CPCash=' + CPCash;
}

function CheckLength(obj,objCount,maxchars)
{
        chars=obj.value
        if (chars.length > maxchars)
        {
            obj.value=chars.substr(0,maxchars);
            obj.blur();
        }
        objCount.value = maxchars-obj.value.length;
    
}

/////////////////////////////////////////////////////////////////////////////////////////////////
//Funzioni utilizzate per la gestione unica del popup multiflusso sia per Cash che per Discount//
////////////////////////////////////////////////////////////////////////////////////////////////
function CheckMultiflussiAll(GruppoMF,ALLF,BitPrivilegio){
	var myGroups = document.forms[0].GruppiMultiflussoD.value
	var bAbilita = document.getElementById("chk"+GruppoMF).checked;

	
	if(bAbilita)
		//aggiunge il gruppo selezionato alla stringa contenuta nella textbox "GruppiMultiflussoD"
		document.forms[0].GruppiMultiflussoD.value = document.forms[0].GruppiMultiflussoD.value + GruppoMF + ',';	
	else
		//rimuove il gruppo selezionato alla stringa contenuta nella textbox "GruppiMultiflussoD"
		document.forms[0].GruppiMultiflussoD.value = document.forms[0].GruppiMultiflussoD.value.replace(GruppoMF + ',','');

	if(BitPrivilegio == 4){
	    var negEmittente = window.opener.document.forms[0].SelFlussiDiscountD.value;
		for (i = 0; i< document.forms[0].MF_Discount.length ; i++)
		{		
			//Se l'id della checkbox attuale = groupMF
			if(document.forms[0].MF_Discount[i].getAttribute("id") == GruppoMF)
			{
				if ( document.forms[0].MF_Discount[i].value !=negEmittente){
					if (GruppoMF == "WHOF")
						CheckCausale (document.forms[0].MF_Discount[i].value, false)
					if (!ALLF) 
					{
						document.forms[0].MF_Discount[i].disabled = bAbilita;
					}
					document.forms[0].MF_Discount[i].checked = bAbilita ;
				}
			}
		}
	}else if(BitPrivilegio == 2){
		
		for (i = 0; i< document.forms[0].MF_DiscountCash.length ; i++)
		{
			//Se l'id della checkbox attuale = groupMF
			if(document.forms[0].MF_DiscountCash[i].getAttribute("id") == GruppoMF)
			{
				/*document.forms[0].MF_DiscountCash[i].disabled = true;*/
				if (GruppoMF == "WHOF")
					CheckCausale (document.forms[0].MF_DiscountCash[i].value, false)
				if (!ALLF) 
				{
					document.forms[0].MF_DiscountCash[i].disabled = bAbilita;
				}
				document.forms[0].MF_DiscountCash[i].checked = bAbilita;

			}
		}
	}
}

function ChiudiFormMultiflussoAll(BitPrivilegio){
	
	if(BitPrivilegio == 4){
		ChiudiFormMultiflusso();
	}else if(BitPrivilegio == 2){
		var selezionati = false;
		var conferma 	= false;
		var res; 
		res = confirm('Sei sicuro di confermare i negozi selezionati?');
		if (!res)
		{
			return false;
		}
		
		var mystring = '';
		for (i = 0; i< document.forms[0].MF_DiscountCash.length ; i++)
		{
			if (document.forms[0].MF_DiscountCash[i].checked)
			{
				mystring = mystring + document.forms[0].MF_DiscountCash[i].value + ',';
				selezionati = true;
			}
		}	
		var lstring = mystring.length;

		mystring = mystring.substr(mystring,lstring-1);
		
		if(!selezionati)
		{
			alert("Selezionare almeno un negozio.");
			return false;	
		}
		else
		{
			var labelMultiflussoCash = '';
			if(mystring.length>5)
			{
				labelMultiflussoCash = 'Multiflusso';
			}
			else
			{
				for(j=0; j<document.forms[0].labelFlusso.length ;j++)
				{
					if(document.forms[0].labelFlusso[j].getAttribute("id") == mystring)
					{
						labelMultiflussoCash = document.forms[0].labelFlusso[j].getAttribute("value");
					}
				}			
			}
			var mystring2 = document.forms[0].GruppiMultiflussoD.value;
//			if (mystring2.length >= 5)
//			{
				mystring2 = mystring2.substr(mystring2,mystring2.length-1);
				window.opener.document.forms[0].SelGruppiMultiFlussoCash.value = document.forms[0].GruppiMultiflussoD.value;
//			}		
			window.opener.document.getElementById("tr_MultiflussiCash").style.display = "";
			window.opener.document.forms[0].lbl_MultiflussiCash.value = labelMultiflussoCash;
			MostraInputMF(window.opener.document.forms[0].lbl_MultiflussiCash);
			window.opener.document.forms[0].multiflussocash.value = mystring;
			
			window.close();
			return true;
		}	
	}
}

function ResetCheckMultiflussoAll(BitPrivilegio){
	if(BitPrivilegio == 4){
		ResetCheckMultiflussoD();
	}else if(BitPrivilegio == 2){
		ResetCheckMultiflussoCash();
	}
}

function CaricaCheckedAll(BitPrivilegio){
	var gruppiMultiflusso = "";
	if(BitPrivilegio == 4){
		var negEmittente = window.opener.document.forms[0].SelFlussiDiscountD.value;
		var multiflusso = window.opener.document.forms[0].multiflusso.value;

		arrayOfFlussi = multiflusso.split(',');
		
		//Gestisce il cambio di selezione sulla combo SelFlussiDiscountD dopo riapertura del popup
		var myVar	= false;
		if(arrayOfFlussi.length>0)
		{
			for(k = 0; k<arrayOfFlussi.length; k++)
			{
				if(arrayOfFlussi[k]==negEmittente){myVar= true;}
			}
		}

		//Rivalorizzo tutte le checkbox sulla pagina dopo la riapertura
		for (i = 0; i<document.forms[0].MF_Discount.length ; i++)
		{
			if(document.forms[0].MF_Discount[i].getAttribute("id") == "WHOF") {

				CheckCausale (document.forms[0].MF_Discount[i].value, true)
								
			}
			
			//if(myVar)
			//{
				for(j = 0 ; j < multiflusso.length; j++)
				{
					if(document.forms[0].MF_Discount[i].value == arrayOfFlussi[j])
					{
						document.forms[0].MF_Discount[i].checked = true;
					}
				}
			//}

			// Seleziona la checkbok relativa al negozio emittente e la disabilito
			if(document.forms[0].MF_Discount[i].value==negEmittente)
			{
				document.forms[0].MF_Discount[i].checked = true;	
				document.forms[0].MF_Discount[i].disabled = true;

				CheckCausale (document.forms[0].MF_Discount[i].value, false)

			}
			
		} 
		
		//Gestisco anche la selezione dei GruppiMultiflusso 
		gruppiMultiflusso 	= window.opener.document.forms[0].SelGruppiMultiFlussoD.value;
		if(gruppiMultiflusso.length>0)
		{
			for (m = 0; m<document.forms[0].MF_Discount.length ; m++)
			{
				if(gruppiMultiflusso.indexOf(document.forms[0].MF_Discount[m].getAttribute("id"))!=-1)
				{
					document.forms[0].MF_Discount[m].checked = true;
					document.forms[0].MF_Discount[m].disabled = true;
				}
			}
		}
		//Rivalorizzo la hidden dei gruppi
	    //document.forms[0].GruppiMultiflussoD.value = gruppiMultiflusso;

	}else if(BitPrivilegio == 2){
		var multiflussocash = window.opener.document.forms[0].multiflussocash.value;

		arrayOfFlussi = multiflussocash.split(',');

		//Alla riapertura del popup dopo una prima selezione riposiziono i valorei sulle checkbox
		for (i = 0; i< document.forms[0].MF_DiscountCash.length ; i++)
		{
			for(j = 0 ; j < multiflussocash.length; j++)
			{
				if(document.forms[0].MF_DiscountCash[i].value == arrayOfFlussi[j])
				{
					document.forms[0].MF_DiscountCash[i].checked = true;
				}
			}
		}	
		
		//Gestisco anche la selezione dei GruppiMultiflusso
		gruppiMultiflusso 	= window.opener.document.forms[0].SelGruppiMultiFlussoCash.value;
		if(gruppiMultiflusso.length>0)
		{
			for (m = 0; m<document.forms[0].MF_DiscountCash.length ; m++)
			{
				if(gruppiMultiflusso.indexOf(document.forms[0].MF_DiscountCash[m].getAttribute("id"))!=-1)
				{
					document.forms[0].MF_DiscountCash[m].disabled = true;
				}
			}
		}
		//Rivalorizzo la hidden dei gruppi
		//document.forms[0].GruppiMultiflussoCash.value = gruppiMultiflusso;
	}
	document.forms[0].GruppiMultiflussoD.value = gruppiMultiflusso;
	
	if(gruppiMultiflusso != ""){
		var arrGruppiMultiflusso = gruppiMultiflusso.split(",");
		for(var tmp in arrGruppiMultiflusso){
			if(arrGruppiMultiflusso[tmp] != ""){
				var chkName = "chk"+arrGruppiMultiflusso[tmp];
				document.getElementById(chkName).checked = true;
			}
		}
	}
}

function visualizzaChiaviUtentiDiscount(flussiToCheck){
    //Se nell'elenco dei gruppi dei negozi è presente anche il kappastore, allora visualizzo
    //le chiavi e gi utenti

    var arrFlussiToCheck = flussiToCheck.split(",");
    var doc = document;
    if (!document.getElementById("flussiWSTF"))
        doc = window.opener.document;
   
    mystring = doc.getElementById("flussiWSTF").value;
    var bInsertNegozi = doc.getElementById("InsertNegozi").value;
    
    if (bInsertNegozi == "False") {
        if (doc.getElementById("trKeyUser") != null) {
            doc.getElementById("trKeyUser").style.display = "none";
            doc.getElementById("trKey").style.display = "none";
            for (var tmp in arrFlussiToCheck) {
                if (arrFlussiToCheck[tmp] != "") {
                    if (mystring.indexOf(arrFlussiToCheck[tmp]) != -1) {
                        doc.getElementById("trKeyUser").style.display = "inline";
                        doc.getElementById("trKey").style.display = "inline";
                    } 
                }
            }
        }
    }
    window.opener.contatoreRighe();
}


////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Gestione DrillDown Panels/////////////////////////////////////////////////////////////////////////////////
//1. Ogni pannello deve chiamarsi "divDD" + numero progressivo//////////////////////////////////////////////// 
//2. Ogni gif su cui clickare per aprire o chiudere il pannello deve chiamarsi "imgDD" + numero progressivo///
////////////////////////////////////////////////////////////////////////////////////////////////////////////
function collapsePanel(pannello, src) {
    var divName = "divDD" + pannello;
    var imgName = "imgDD" + pannello;
    var imgSrc = src != "" ? src : document.getElementById(imgName).src;
    var displayStyle = "";

    if (imgSrc.indexOf("Dn") > 0) {
        displayStyle = "inline";
        imgSrc = "../../Images/toggleUpBlue.gif";
    } else {
        displayStyle = "none";
        imgSrc = "../../Images/toggleDnBlue.gif";
    }
    document.getElementById(divName).style.display = displayStyle;
    document.getElementById(imgName).src = imgSrc;
}


function collapsePanels() {
    var imgSrcArr = document.getElementById("imgDD").src.split("/");
    var imgSrc = imgSrcArr[imgSrcArr.length - 1];
    if (imgSrc.indexOf("Dn") > 0)
        document.getElementById("imgDD").src = "../../Images/toggleUpBlue.gif";
    else
        document.getElementById("imgDD").src = "../../Images/toggleDnBlue.gif";

    pannelli = countElementsByName("IMG", "imgDD");
    for (i = 1; i <  pannelli; i++) {
        collapsePanel(i, imgSrc);
    }
}


function countElementsByName(tagName,prefisso) {
    c = 0;
    oColl = document.getElementsByTagName(tagName);
    
    for (i = 0; i < oColl.length; i++) {
        curInp = oColl.item(i);
        if (curInp.id.substring(0,5) == prefisso){
            c++;
        }
    }
    return c;
}
