/**************************************************************************************************************
	stefano guagnini
	1/2/2002
 **************************************************************************************************************
 
	Tools.js 
	--------
	
*************************************************************************************************************/

var _CONST_IPMVER_PATH = "c:\\programmi\\monetc\\ipm\\ipm.ver";

/************************************************************************************************************/

function SetTitle( divID, szAppName, szAppVer )
{
	var div_obj = typeof(divID) == "string" ? document.all(divID) : divID;
	
	div_obj.innerHTML =	"<table width=735 border=0 cellpadding=0 cellspacing=0>" +
						"<tr>" +
							// canvass giugno 2007 - per il nuovo logo viene colorato di rosso lo sfondo della cella che lo contiene
							// e viene eliminata la barra bianca verticale di separazione
							"<td width=1 valign=top rowspan=2 style=\"background:#ff0000\"><img src=\"/dslib/images/logobig.gif\"></td>" +
							/*"<td width=1 rowspan=2>&nbsp;</td>" + */
							"<td width=733 class=banner align=right valign=center><label id=title_app_name class=banner>" + szAppName + "</label>&nbsp;<label id=title_app_ver class=bannerversion>" + szAppVer + "</label>&nbsp;&nbsp;&nbsp;</td>" +
						"</tr><tr>" +
							"<td width=733 align=right class=banner><div id=tab_container>&nbsp;</div></td>" +
						"</tr><tr>" +
							"<td width=610 align=right colspan=3><div id=keypad_container>&nbsp;</div></td>" +
						"</tr>" +
						"</table>";
}

function ChangeTitle( szAppName, szAppVer )
{
	if ( szAppName != null )
		title_app_name.innerText = szAppName;
		
	if ( szAppVer != null )
		title_app_ver.innerText = szAppVer;
}

/************************************************************************************************************/

var GEN_KP_BUTTON=0, 
	GEN_KP_BUTTON_ICON=2,	//1, 
	GEN_KP_LINK=2,
	
	GEN_KP_NEW = 0,
	GEN_KP_SAVE	= 1,
	GEN_KP_CLEAR = 2,
	GEN_KP_EXIT	= 3,
	GEN_KP_SUBMIT = 4,
	GEN_KP_PRINT = 5,
	GEN_KP_PREV	= 6,
	GEN_KP_NEXT	= 7,
	GEN_KP_HELP	= 8,
	GEN_KP_RETRY = 9;
	
var _KEYPADDESC = new Array("Nuovo","Sospendi","Annulla","Chiudi","Invia","Stampa","Precedente","Successivo","Aiuto","Riprova");

var _kpPtr = null;
var _kpMode = GEN_KP_LINK;
var _kpPrefix = "";
var _kpHtml = "";
var _kpBtnCnt=0;

function OpenKeypad( divID, mode, szPrefix )
{
	if ( divID == null )
		_kpPtr = keypad_container;
	else
		_kpPtr = typeof(divID) == "string" ? document.all(divID) : divID;
	_kpMode = mode;
	_kpPrefix = szPrefix;
	_kpBtnCnt = 0;
	
	if ( _kpMode == GEN_KP_LINK )
		_kpHtml = "<table border=0 align=left width=\"100%\"><tr><td align=right>";
	else
		_kpHtml = "<table border=0 align=left width=\"100%\"><tr><td align=left>";
}

function AddKeypad( btnID, szCmd, szDescr )
{
	var descr, icon;
	
	if ( btnID >= 0 && btnID <= 9 )
	{
		//	pulsanti predefiniti...
		//		mi aspetto 2 parametri
		descr = _KEYPADDESC[btnID];
		btnID = _kpPrefix + "kp_btn" + btnID;
	}
	else
	{
		//	pulsante personalizzato
		//		mi aspetto 3 parametri
		descr = szDescr;
		//icon = szIcon != null && szIcon.length ? szIcon : null;
	}

	if ( _kpMode == GEN_KP_LINK )
	{
		//	GESTIONE TRAMITE STYLE X IE4. CON IE5 SI PUO USARE CLASSNAME
		
		if ( _kpBtnCnt > 0 )
			_kpHtml += "&nbsp;|&nbsp;"
		
		_kpHtml += "<label	id=" + btnID + " class=navigationlink " +
							"onClick=\"if(!InputManager.IsReadonly(this)){" + szCmd +"}\" " + 
							"onmouseover=\"if(!InputManager.IsReadonly(this)){InputManager.Hilight(1,this);}\" " +
							"onmouseout=\"if(!InputManager.IsReadonly(this)){InputManager.Hilight(0,this);}\">&nbsp; " +
							"&nbsp;<u>"+descr+"</u>&nbsp;" +
					"</label>&nbsp;";
	}
	else
	{
		_kpHtml += "&nbsp;<button id=" + btnID + " " +
				   "onClick=\"if(!InputManager.IsReadonly(this)){"+szCmd+";}\"> " + 
				   descr + "</button>";
	}
	
	_kpBtnCnt++;
}

function CloseKeypad()
{
	_kpHtml += "</td></tr></table>";
	_kpPtr.innerHTML = _kpHtml;
	_kpHtml = "";
	_kpPtr = null;
}

function SetKeypad( divID, mode, szPrefix )
{
	OpenKeypad( divID, mode, szPrefix );
	for ( var btn=0; btn<arguments.length-3; btn++ )
		if ( arguments[btn+3] != "" )
			AddKeypad( btn, arguments[btn+3] );
	CloseKeypad();
}

/************************************************************************************************************/

var _waitWnd;
var _waitCallBackFunction;
var _waitTimeout;
var _waitElapsed;

function _waitResponse()
{
	var done = false;

	try
	{	
		done = _waitWnd.document.readyState == "complete" || _waitWnd.document.readyState == "loaded"; 
	}	
	catch(e)
	{
		done = false; 
	}
	
	if ( done )
	{
		_waitCallBackFunction(_waitElapsed);
	}
	else if ( (_waitElapsed+=1000) > _waitTimeout )
	{
		_waitCallBackFunction(-1);
	}
	else
	{
		setTimeout( "_waitResponse()", 1000 );
	}
}

function SubmitAndWait( pForm, pWnd, pCallBack, msTimeOut )
{
	pWnd.location = "about:blank";
	
	_waitWnd = pWnd;
	_waitCallBackFunction = pCallBack;
	_waitTimeout = msTimeOut;
	_waitElapsed = 0;

	if ( pForm._submit_time == null )
	{	
		var p = document.createElement( "INPUT" );
		p.type = "hidden";
		p.id = p.name = "_submit_time";
		pForm.appendChild(p);
	}
	
	pForm._submit_time.value = Config.ServerTime();
	pForm.target = (pWnd.id != null && pWnd.id != "") ? pWnd.id : pWnd.name;

	setTimeout( "document.all('" + pForm.id + "').submit()", 1000 );
	setTimeout( "_waitResponse()", 2000 );
}

/************************************************************************************************************/

function ResizeFullScreen()
{
	window.focus();
	window.moveTo(0,0);
	window.resizeTo( screen.availWidth,screen.availHeight );
}

/************************************************************************************************************/

var _fdf_counter = 0;

function _submitFDF(q)
{
	if ( q.form._fdf_target == null )
	{	
		var p = document.createElement( "INPUT" );
		p.type = "hidden";
		p.name = p.id = "_fdf_target";
		p.value = q.target;
		q.form.appendChild(p);
	}
	else
	{
		q.form._fdf_target.value = q.target;
	}

	q.form.target = q.target;
	q.form.submit();
}

function SubmitFDF(pForm, pASP)
{
	var ret = -1;

	if ( pASP != null ) 
		pForm.action = pASP;

	if ( Number(window.navigator.userAgent.substr(window.navigator.userAgent.indexOf("MSIE")+5,3)) >= 6 )
	{
		try{
			var pKernel = GetKernelObj();
			ret = pKernel.showFdfDocuments(pForm);
		}
		catch(e){}
	}

	if ( ret < 0 )
	{
		_fdf_counter++;

		var p = window.open("about:blank","fdf_"+_fdf_counter);
		try{
			p.document.open();
			p.document.write("Attendere caricamento in corso... " );
			p.document.close();
		}
		catch(e){}

		if ( window.fdfqueue == null )
			window.fdfqueue = new Array();

		var q = new Object();
		q.form = pForm;
		q.target = "fdf_"+_fdf_counter;
			
		window.fdfqueue.push( q );
		setTimeout("_submitFDF(window.fdfqueue.pop());", 2000 );
	}

	return 0;
}

/************************************************************************************************************/

function SubmitPDF(pForm, pASP, filename)
{
    var ret = "";

	if ( pASP != null || pAsp == "" ) 
		pForm.action = pASP;
		
	if ( filename == null || filename == "" )
	    filename = pForm.id;
		
	if ( Number(window.navigator.userAgent.substr(window.navigator.userAgent.indexOf("MSIE")+5,3)) >= 6 )
	{
		try{
			var pKernel = GetKernelObj();
			ret = pKernel.DownLoadPdfDocument(pForm,filename);
		}
		catch(e){}
	}

	if ( ret == "" )
	{
		_fdf_counter++;

		var p = window.open("about:blank","fdf_"+_fdf_counter);
		try{
			p.document.open();
			p.document.write("Attendere caricamento in corso... " );
			p.document.close();
		}
		catch(e){}

		pForm.target = "fdf_"+_fdf_counter;
		pForm.submit();
	}

	return ret;
}

/************************************************************************************************************/

function OpenPDF(szUrl)
{
	var ret = -1;

	if ( Number(window.navigator.userAgent.substr(window.navigator.userAgent.indexOf("MSIE")+5,3)) >= 6 )
	{
		try{
			var pKernel = GetKernelObj();
			ret =  pKernel.showPdfDocument(szUrl);
		}
		catch(e){}
	}

	if ( ret != 0 )
		window.open(szUrl);
		
	return 0;
}


/************************************************************************************************************/

function OpenInfoPdf(dummy,szContract)
{
    var szUrl = location.protocol + "//" + location.host + "/workstation/dspdf/documents/dinamici/";

	if ( NormalizeCardType(szContract) == 2 )
	{
		//	ricaricabile
		szUrl += "Informativa_DL_196-2003_ric_CONS.pdf";
	}
	else
	{
		//	abb persona/impresa/lib.prof.
		szUrl += "Informativa_DL_196-2003_ind-imp_CONS.pdf";
	}
	
	return OpenPDF(szUrl);
}

/************************************************************************************************************/

function OpenInfoSetefi()
{
    var szUrl = location.protocol + "//" + location.host + "/workstation/dspdf/documents/dinamici/";	
	szUrl += "INF-X-Setefi.pdf";
		
	return OpenPDF(szUrl);
}

/************************************************************************************************************/

function IPMAlign()
{
	var szTID = Config.TID(), szSIA = Config.SIA(), ret;
	try
	{
		var pObj = new ActiveXObject("MonetC.Manager");
		ret = pObj.AllineaChiavi(szSIA,szTID,_CONST_IPMVER_PATH);
		delete(pObj);
	}
	catch(e){ret=-1}
	alert( ret == 0 ? DSLIB[14] : DSLIB[15] );
}

/************************************************************************************************************/

function RunExeFile(bSync,szPath,szArgs,p3,p4)
{
	//	bSync = true => chiamata sincrona, false => chiamata asincrona
	//	szPath = path dell'eseguibile
	//	szArg = parametri all'exe
	//
	//	if bSync
	//
	//		p3 = TimeOut in secondi
	//		p4 = Flags (0=nulla, 1=kill exe after timeout)
	//
	//	else
	//
	//		p3 = true => full screen
	//
	//	endif
	
	var ret=0;
	try{
		var pKernel = GetKernelObj();
		ret = bSync ? pKernel.SyncRunner(szPath,szArgs,p3,p4) : pKernel.Execute(szPath,szArgs,p3);
	}
	catch(e){
		ret = -1
	}
	
	if ( ret < 0 && ret != -10003)
		alert(DSLIB[16]);

	return ret;
}

/************************************************************************************************************/

var _BrowserConnection_IsOnLine=0;
var _BrowserConnection_IsOffLine=1;
var _BrowserConnection_SetOnLine=2;
var _BrowserConnection_SetOffLine=3;
var _BrowserConnection_IsRasOn=4;
var _BrowserConnection_IsRasOff=5;
var _BrowserConnection_ActRAS=6;

function BrowserConnection(cmd)
{
	try
	{
		var pKernel = GetKernelObj();

		switch( cmd )
		{
			case 0:	//	verifica online
				return window.navigator.onLine;
				
			case 1:	//	verifica offline
				return !window.navigator.onLine;

			case 2:	//	mette online
				return pKernel.SetBrowserConnectionState(1)==0;
				
			case 3:	//	mette offline
				return pKernel.SetBrowserConnectionState(0)==0;
			
			case 4:	//	verifica connessione ras (true->connesso)
				return pKernel.GetRasStatus("VO_CONNECT", 0)==0;
			
			case 5:	//	verifica connessione ras (true->NON connesso)
				return pKernel.GetRasStatus("VO_CONNECT", 0)!=0;
				
			case 6:	//	attiva connessione ras
				return pKernel.GetRasStatus("VO_CONNECT", 1)==0;
		}
	}
	catch(e){};
	
	return -1;
}

/************************************************************************************************************/

function GetKernelObj()
{
	if ( window.kernelObj == null )
	{
		var conf;
		try{
			conf = Config.Context()
		}
		catch(e){
			conf = null;
		}
	
		try{
			if ( conf == DS_CONTEXT || conf == OS_CONTEXT )
			{
				window.kernelObj = new ActiveXObject("KERNELXP.WebKernel");
			}
			else if ( conf == OP_CONTEXT )
			{
				window.kernelObj = new ActiveXObject("CIRIO.KeyManager.1");
			}
		}
		catch(e){
		
			window.kernelObj = null;
		}

		if ( window.kernelObj == null )
		{
			//	non ha riconosciuto il context, vado per tentativi...
			try{
				window.kernelObj = new ActiveXObject("KERNELXP.WebKernel");
			}
			catch(e){
				window.kernelObj = null;
			}
			if ( window.kernelObj == null )
			{
				try{
					window.kernelObj = new ActiveXObject("CIRIO.KeyManager.1");
				}
				catch(e){
					window.kernelObj = null;
				}
			}
		}
	}

	return window.kernelObj;
}

/************************************************************************************************************/

var _logDebug	=	1;
var _logInfo	=	2;
var _logWarning	=	4;
var _logPanic	=	8;
var _logFatal	=	16;
var _logLevelDescr = new Array();
_logLevelDescr[1]  = "Debug";
_logLevelDescr[2]  = "Info";
_logLevelDescr[4]  = "Warning";
_logLevelDescr[8]  = "Panic";
_logLevelDescr[16] = "Fatal";

function writelog( nLevel, szMessage )
{	try{
		if ( window.logLevel & nLevel && Config.DealerCode() == "DEAL3.00001" )
		{
			var pKernel = GetKernelObj();
			pKernel.RemoteLogWriter( nLevel, szMessage + "\xFF" + Config.ID() );
		}
	}
	catch(e){}
}

/************************************************************************************************************/

function SendMailTo( szTO, szCC, szBCC, szSubject, szBody, szUser, szAttach, nBodyFormat )
{
	//	nBodyFormat:
	//		0 - Text
	//		1 - Html
	if ( szUser == null || szUser == "" )
	{
		if ( szTO == null ) szTO = " ";
		if ( szCC == null ) szCC = " ";
		if ( szBCC == null ) szBCC = " ";
		if ( szSubject == null ) szSubject = " ";
		if ( szBody == null ) szBody = " ";
		location = "mailto:" + szTO + "?szCC=" + szCC + "&szBCC=" + szBCC + "&subject=" + szSubject + "&body=" + szBody;
		return 0;
	}
	else
	{
		try
		{
			var mail=new ActiveXObject("OSALMAIL.AnonymousMail");
			return mail.SendAsAnonymous(	nBodyFormat,
											"pntestex2000.partnernettest.it",
											"25",
											szUser,
											szTO,
											szCC,
											szSubject,
											szBody,
											szAttach);
		}
		catch(e)
		{
			return -1;
		}
	}
}

/************************************************************************************************************/

function OpenHLRZones()
{
  window.open("/dslib/dialogs/hlr.htm", "HlrZones", "toolbar=no,status=no,menubar=no,width=500,height=400,scrollbar=yes");
}

/************************************************************************************************************/

function PromoDateSelection( startdate, enddate, allowed_days, joined_days, reptimes, repdelta, mindays, maxdays )
{
    var input = new Object();
        input.startdate = startdate;
	    input.enddate = enddate;
	    input.allow = allowed_days;
	    input.join = joined_days;
	    input.repdelta = repdelta;
	    input.reptimes = reptimes;
	    input.mindays = mindays;
	    input.maxdays = maxdays;

	return window.showModalDialog("/dslib/dialogs/calendar.htm",input,"dialogHeight:280px;dialogWidth:300px;");
}

/************************************************************************************************************/

function InitDsLibrary(szDsFolderLib,nLogLevel,bCheckHpg,tmStamp,szModuleName)
{
	//	verifica se arrivo da homepage
	if ( bCheckHpg ) 
		CheckHPG();

	//	imposta directory DSLIB	
	if ( szDsFolderLib != null )
		window.dslib_url = szDsFolderLib;

	//	livello di log
	if ( nLogLevel != null )
	{
		if ( isNaN(Number(nLogLevel)) )
		{
			var q = 0;
			var p = nLogLevel.split("|");
			for ( x in p )
				for ( y in _logLevelDescr )
					if ( _logLevelDescr[y].toLowerCase() == p[x].toLowerCase() )
						q |= y;

			window.logLevel = q;
		}
		else
		{
			window.logLevel = nLogLevel;
		}
	}

	//	timestamp
	if ( window.timeStamp == null )
	{
		if ( tmStamp == null || tmStamp == "" )
		{
			var dt = new Date();
			window.timeStamp = dt.valueOf().toString();
		}
		else window.timeStamp = tmStamp;
	}

	//	nome modulo
	if ( szModuleName != null )
		window.moduleName = szModuleName;

}

/***********************************************************************************************************/

function CheckHPG()
{
	try
	{
		var p = window;
		
		while( p != null )
		{
			if ( p.isHomepage != null && p.isHomepage )
				return;
			else
				p = p.opener;
		}
	}
	catch(e){}
	
	alert( DSLIB[20] );
	location = "about:blank";
}

/***********************************************************************************************************/

function CheckMultisimPwd(bSilent)
{
    if ( bSilent == null || !bSilent )
         if ( !confirm( DSLIB[27] ) )
             return -1;

    var out = window.showModalDialog("/dslib/dialogs/multisim.htm","Password Attivazioni Multiple","dialogHeight:320px;dialogWidth:350px;");
    return out.code;
}

function CheckTenderPwd()
{
    var out = window.showModalDialog("/dslib/dialogs/multisim.htm","Password di Accesso","dialogHeight:320px;dialogWidth:350px;");
    return out.code;
}
/***********************************************************************************************************/

function NormalizeCustType(typeCust)
{
    if ( typeof(typeCust) == "string" )
	{
	    switch( typeCust.charAt(0).toUpperCase() )
	    {
	        case "P": typeCust = 1; break;      //  PERSONA
	        case "L": typeCust = 2; break;      //  LIB.PROF.
	        case "I":                           //  IMPRESA CORPORATE
	        case "C": typeCust = 3; break;      //  IMPRESA FLAT
	        case "E": typeCust = 4; break;      //  ESENTE TCG
	        default: typeCust = Number(typeCust);
	    }
	}
	return typeCust;
}

/***********************************************************************************************************/

function NormalizeCardType(typeCard)
{
    if ( typeCard == null )
        return 2;
        
    if ( typeof(typeCard) == "string" )
	{
	    switch( typeCard.charAt(0).toUpperCase() )
	    {
	        case "A": 
	        case "S": 
	        case "1": typeCard = 1; break;
	        case "": 
	        case "R": 
	        case "2": typeCard = 2; break;
	    }
	}
	return typeCard;
}

/***********************************************************************************************************/

function PrintExemption(szCustomer,szFiscalIvaCode,seqID,szDate)
{
    var param = "?Customer="+szCustomer+"&FiscalIvaCode="+szFiscalIvaCode+"&SeqID="+seqID+"&Date=";
    if ( szDate != null )
        param += szDate;
    
    window.open("/dslib/dialogs/exemptionprint.htm"+param, "Exemption", "toolbar=no,status=no,menubar=no,width=500,height=400,scrollbar=yes");
}

/***********************************************************************************************************/
var disableSmartClient = false;
function runSmartClient(scName, aSync, skipDownload, xmlParameters) {
    if (disableSmartClient && (isDealerOtO()|| isDealerOC())) {
        if (scName != "PPMSC" && scName != "DFW")
            alert(GetErrorMsg(350, "", "DSLIB").Description);
        return ""; 
    }
    if (aSync == null)
        aSync = true;

    if (skipDownload == null)
        skipDownload = false;

    if (xmlParameters == null)
        xmlParameters = "";

    //	provo a lanciare col nuovo startup
    try {
        var pObj = new ActiveXObject("DealerStation.DSLibrary.StartUp");
        var server = location.host;
        if (Config.Context() != DS_CONTEXT)
            server = server.toLowerCase().replace("open.vodafone.it", "open.vodafoneomnitel.it");

        pObj.Server = server;
        pObj.Module = scName;
        pObj.ClientId = (Config.Context() == DS_CONTEXT) ? window.PcCode : window.OmnipointID;
        pObj.UserCode = (Config.Context() == DS_CONTEXT) ? window.DealerCode : window.OmnipointID;
        pObj.SkipDownload = skipDownload;
        pObj.Async = aSync;
        pObj.Domain = "";
        pObj.UserName = Config.UserName();
        pObj.Password = decode64OTO(Config.UserPwd());
        pObj.AppParameters = xmlParameters;
        if (isDealerOtO() || isDealerOC()) {
            var isacookievalue = CookieManager.SecureFind("O2OSSCD");
            if (isacookievalue != null && isacookievalue != "")
                pObj.ISACookieValue = isacookievalue;
            else {
                alert(GetErrorMsg(349, "", "DSLIB").Description);
                return "";
            }
        }
        var resultObj = pObj.Execute();
        pObj = null;
        return resultObj;
    }
    catch (e) {
        // Patch per versioni di DSSU precedenti alla 2.6.0
        debug("Execute su versione 2.6.0+ fallito, provo versioni precedenti");
        try {
            var pObj = new ActiveXObject("DealerStation.DSLibrary.StartUp");
            var resultObj = null;
            if (Config.Context() == DS_CONTEXT) {
                resultObj = pObj.Run(location.host, scName, window.PcCode, window.DealerCode, skipDownload, aSync, xmlParameters);
            }
            else {
                var server = location.host.toLowerCase().replace("open.vodafone.it", "open.vodafoneomnitel.it");
                resultObj = pObj.Run(server, scName, window.OmnipointID, window.OmnipointID, skipDownload, aSync, xmlParameters);
            }
            if (scName == "DSSU" && (isDealerOtO() || isDealerOC())) {
                alert(GetErrorMsg(350, "", "DSLIB").Description);
                disableSmartClient = true;
                return "";
            }
            else
                return resultObj;

        }
        catch (e) {
            alert(DSLIB[16]);
            debug("runSmartClient.Exception: " + e.description);
        }
    }

    //	se fallisce provo con osal (NB: solo x DS - open fallisce sicuramente)
    try {
        var appName = "C:\\Vodafone\\SC\\dslib.scstartup.exe";
        var appArgs = location.host + " " + scName + " " + window.PcCode + " " + window.DealerCode + " /Username:" + Config.UserName() + " /Password:" + Config.UserPwd();
        RunExeFile(true, appName, appArgs, 0, 0);
    }
    catch (e) { }

}

/***********************************************************************************************************/

var _DocFwkCallback = null;
var _DocFwkObj = null;

function DocFwkCreateTextToLocation(location, filename, content)
{
	try
	{
		if(_DocFwkObj == null)
			_DocFwkObj = new ActiveXObject("DealerStation.DSLibrary.DocFwkPrx");
		return _DocFwkObj.CreateTextToLocation(location, filename, content);
	}
	catch(e)
	{
		debug( "DocFwkCreateTextToLocation.Exception: " + e.description );
		_DocFwkObj = null;
		return false;	
	}
	
}

function DocFwkCreateTextFile(folderpath, filename, content)
{
	try
	{
		if(_DocFwkObj == null)
			_DocFwkObj = new ActiveXObject("DealerStation.DSLibrary.DocFwkPrx");
		return _DocFwkObj.CreateTextFile(folderpath, filename, content);
	}
	catch(e)
	{
		debug( "DocFwkCreateTextFile.Exception: " + e.description );
		_DocFwkObj = null;
		return false;	
	}
	
}

function runDocFwk(XmlDoc, aSync, Callback, Username, Password, Domain)
{
	try
	{
		_DocFwkObj = new ActiveXObject("DealerStation.DSLibrary.DocFwkPrx");

		var isacookievalue = "";
		if (isDealerOtO() || isDealerOC()) {
		    isacookievalue = CookieManager.SecureFind("O2OSSCD");
		    if (isacookievalue == null || isacookievalue == "")
            {
		        alert(GetErrorMsg(349, "", "DSLIB").Description);
		        return "";
		    }
		}
		
		if (aSync)
		{
			_DocFwkCallback = Callback;
			_DocFwkObj.Async(true);
			if(Username != null && Password != null)
			{
				_DocFwkObj.RunAuthenticated(XmlDoc, Username, Password, Domain, isacookievalue);
			}
			else
			{
				_DocFwkObj.Run(XmlDoc);
			}
			if ( Callback != null ) setTimeout("_waitDocFwk();", 1000);
			return _DocFwkObj.Result();
		}
		else
		{
			if(Username != null && Password != null)
			{
				return _DocFwkObj.RunAuthenticated(XmlDoc, Username, Password, Domain, isacookievalue);
			}
			else
			{
				return _DocFwkObj.Run(XmlDoc);
			}
			_DocFwkObj = null;
		}
	}
	catch(e)
	{
		debug( "runDocFwk.Exception: " + e.description );
		alert( DSLIB[12] );
		_DocFwkCallback("");
		_DocFwkObj = null;
		return "";
	}
}

function _waitDocFwk()
{
	var res;
	try
	{	
		res = _DocFwkObj.Result();	
		if ( _DocFwkObj.Status() != "Running" )
		{
			_DocFwkObj = null;
			_DocFwkCallback(res);
		}
		else setTimeout("_waitDocFwk();", 1000);
	}
	catch(e)
	{
		debug( "waitDocFwk.Exception: " + e.description );
		_DocFwkCallback(res);
		return;
	}
}

/***********************************************************************************************************/

function BuildFiscalCode(pFamilyname, pName, pSex, pBirthdate, pCountry, pProvince, pCity )
{
	var familyname = pFamilyname.value.toUpperCase();
	var name = pName.value.toUpperCase();
	var sex = DDLManager.GetSelection(pSex).toUpperCase();
	var birthdate = CheckDate(pBirthdate.value);
	var citycode="";
	var fiscalcode = "";
	var i, tmp;
	
	//	check data
	if ( familyname.length == 0 || name.length == 0 || birthdate == null || pProvince.selectedIndex <= 0 )
		return fiscalcode;

	// verify city
	if ( DDLManager.GetSelection(pProvince) == "EE" )
	{
		if ( !dbIF.CheckCity(null,pCountry,null,null,dbIF.BirthAddress) )
			return fiscalcode;
			
		citycode = pCountry.citycode;
	}
	else
	{
		if ( !dbIF.CheckCity(pProvince,pCity,null,null,dbIF.BirthAddress) )
			return fiscalcode;
		citycode = pCity.citycode;
	}

	//	char 0..2 (familyname)
	for (tmp = "",i=0; i<familyname.length && tmp.length <3; i++) 
		if ( CheckCharSet(familyname.charAt(i),"BCDFGHLMNPQRSTVZWYJKX") )
			tmp += familyname.charAt(i);
	for (i=0; i<familyname.length && tmp.length <3; i++) 
        if ( CheckCharSet(familyname.charAt(i),"AEIOU") )
			tmp += familyname.charAt(i);
    for (i=0;  tmp.length<3; i++) 
        tmp +="X";
    fiscalcode += tmp;

	//	char 3..5 (name)	
	for (tmp = "",i=0; i<name.length; i++) 
		if ( CheckCharSet(name.charAt(i),"BCDFGHLMNPQRSTVZWYJKX") )
			tmp += name.charAt(i);
	if ( tmp.length > 3 )
		tmp = tmp.substring(0,1) + tmp.substring(2,4);
	for (i=0; i<name.length && tmp.length<3; i++) 
		if ( CheckCharSet(name.charAt(i),"AEIOU") )
			tmp += name.charAt(i);
    for (i=0;  tmp.length<3; i++) 
        tmp +="X";
    fiscalcode += tmp.substr(0,3);

	//	char 6..10 (birthdate-sex)
	var monthcode = " ABCDEHLMPRST";
	tmp = birthdate.getFullYear().toString().substr(2);
	tmp += monthcode.charAt(birthdate.getMonth()+1);
	fiscalcode += tmp;
	tmp = birthdate.getDate() + (sex == "M" ? 0 : 40);
	fiscalcode += (tmp<10 ? "0" : "")+tmp;
	
	//	char 11..14 (citycode)
	fiscalcode += citycode;
	
	//	char 15 (checkdigit)
	var sum = 0;
	var encode = "BAKPLCQDREVOSFTGUHMINJWZYX";
	tmp = 0;
	for( i = 0; i < 15; i++ )
	{
		var ch = fiscalcode.charAt(i);		
		if( i % 2 )
			tmp += CheckCharSet(ch,_CharSet_alpha) ? Number(ch.charCodeAt(0)-65) : parseInt( ch );
		else
			tmp += encode.indexOf( CheckCharSet(ch,_CharSet_alpha) ? ch :  _CharSet_alpha.charAt(26+parseInt(ch)) );
	}
	fiscalcode += _CharSet_alpha.charAt(26+(tmp % 26));
	
	//	the end...
	return fiscalcode;
}

/***********************************************************************************************************/

function MD5String(str)
{
	try
	{
		var obj = new ActiveXObject("DSCRYPTCOM.CHashing.1");
		return obj.HashMD5(str);
	}
	catch(e)
	{
		return "";
	}
}

/***********************************************************************************************************/

/*const*/ var MON_NULL_MSG		= ""
/*const*/ var MON_TIMEOUT_MSG	= "TIMEOUT_CLIENT"
/*const*/ var MON_TIMEOUTSERVER_MSG	= "TIMEOUT_SERVER"
/*const*/ var MON_KO_VER_MSG	= "KO_VER"
/*const*/ var MON_WARN_VER_MSG	= "WARN_VER"
/*const*/ var MON_KO_ATT_MSG	= "KO_ATT"
/*const*/ var MON_WARN_ATT_MSG	= "WARN_ATT"
/*const*/ var MON_OK_MSG		= ""

var Mon_TransactionID = null;
var Mon_ConnectionSpeed = null;
var Mon_FunctionID = null;
function Mon_CreateTransactionID(functionID,/*optional*/ prvTransactionID)
{
	if ( Config.Monitoring() )
	{
		if ( Mon_TransactionID == null )
		{
			if ( document.all("_MonServiceObj") == null )
				document.body.insertAdjacentHTML('beforeEnd', '<div id="_MonServiceObj" style="BEHAVIOR: url(/dslib.webservices/behavior/webservice.htc)"></div>');
				
			Mon_FunctionID = functionID;
			
			if ( prvTransactionID != null && prvTransactionID != "" )
			{
				Mon_TransactionID = prvTransactionID;			
				debug( "Monitoring transactionID: " + Mon_TransactionID );
			}
			else Mon_ResetTransactionID();

			try
			{
				var pObj = new GetKernelObj();
				Mon_ConnectionSpeed = pObj.VerifyConnection() == "H" ? "F" : "L";
				debug( "Monitoring ConnectionSpeed: " + Mon_ConnectionSpeed );
			}
			catch(e)
			{
				Mon_ConnectionSpeed = "L";
				debug( "Monitoring ConnectionSpeed Error: assuming" + Mon_ConnectionSpeed );
			}
		}
	}
	else debug( "Monitoring OFF" );
	
	return Mon_TransactionID;
}
function Mon_ResetTransactionID()
{
	if ( Config.Monitoring() )
	{
		var t = new Date();	
		var Y = String(t.getFullYear());
		var M = String(t.getMonth()+1);		if (M.length < 2) M = "0"+M;
		var D = String(t.getDate());		if (D.length < 2) D = "0"+D;
		var h = String(t.getHours());		if (h.length < 2) h = "0"+h;
		var m = String(t.getMinutes());		if (m.length < 2) m = "0"+m;
		var s = String(t.getSeconds());		if (s.length < 2) s = "0"+s;
		var P = "000000"+Config.PcCode();	P = P.substr(P.length-6);
		Mon_TransactionID = Y+M+D+h+m+s+P;

		debug( "Monitoring new transactionID: " + Mon_TransactionID );
		return Mon_TransactionID;
	}
}
function Mon_UpdateTransactionID()
{
	if ( Config.Monitoring() )
	{
		var i=Mon_TransactionID.indexOf("_");
		
		if ( i > 0 )
		{
			var n = Number( Mon_TransactionID.substr(i+1) )+1;
			n = n < 10 ? ("_0"+n) : ("_"+n);
			Mon_TransactionID = Mon_TransactionID.substr(0,i) + n;
		}
		else Mon_TransactionID += "_01";
		
		debug( "Monitoring new transactionID: " + Mon_TransactionID );
		return Mon_TransactionID;
	}
}
function Mon_SignalBegin()
{	
	if ( Config.Monitoring() && Mon_TransactionID != null )
		Mon_SignalOperation(Mon_GetXmlBegin());
}
function Mon_SignalEnd(errorDesc)
{
	if ( Config.Monitoring() && Mon_TransactionID != null )
		Mon_SignalOperation(Mon_GetXmlEnd(errorDesc));
}
function Mon_GetXmlBegin()
{
	var xml = "";
	if ( Config.Monitoring() && Mon_TransactionID != null )
	{
		xml = Mon_GetXml("TCS",null);					
		debug( "Mon_GetXmlBegin=" + xml );
	}
	return xml;
}
function Mon_GetXmlEnd(errorDesc)
{
	var xml = "";
	if ( Config.Monitoring() && Mon_TransactionID != null )
	{
		xml = Mon_GetXml("TCE",errorDesc);
		debug( "Mon_GetXmlEnd=" + xml );
	}
	return xml;
}
/*private*/ function Mon_GetXml(rowType,errorDesc)
{
	var xml = "";
	if ( Config.Monitoring() && Mon_TransactionID != null )
	{
		if ( errorDesc == null )
			errorDesc = "";
		
		var t = new Date();	
		var Y = String(t.getFullYear());
		var M = String(t.getMonth()+1);		if (M.length < 2) M = "0"+M;
		var D = String(t.getDate());		if (D.length < 2) D = "0"+D;
		var h = String(t.getHours());		if (h.length < 2) h = "0"+h;
		var m = String(t.getMinutes());		if (m.length < 2) m = "0"+m;
		var s = String(t.getSeconds());		if (s.length < 2) s = "0"+s;
		var ts= Y+M+D+h+m+s;	
				
		xml = 	"<Monitoring>"+
					"<Timestamp>"+ts+"</Timestamp>"+
					"<RowType>"+rowType+"</RowType>"+
					"<TransactionId>"+Mon_TransactionID+"</TransactionId>"+
					"<FunctionId>"+Mon_FunctionID+"</FunctionId>" +
					"<DealerCode>"+Config.DealerCode()+"</DealerCode>"+
					"<PcCode>"+Config.PcCode()+"</PcCode>"+
					"<FlagConnection>"+Mon_ConnectionSpeed+"</FlagConnection>"+
					"<Server/>"+
					"<Method/>"+
					"<ErrorDesc>"+errorDesc+"</ErrorDesc>"+
				"</Monitoring>";
	}

	return xml;
}

/*private*/ var Mon_SignalOpXML = null;
/*private*/ var Mon_SignalOpRetry = 3;
/*private*/ function Mon_SignalCallback(pResult)
{
	if ( pResult != null && !pResult.error )
	{
		debug( "Monitoring call result: OK" );
	}
	else
	{
		debug( "Monitoring call result: KO" );
		if ( Mon_SignalOpRetry > 0 )
		{
			debug( "Monitoring retry left: " + Mon_SignalOpRetry );
			Mon_SignalOpRetry--;
			setTimeout( "Mon_SignalOperation(null)", 1500 );
			return;
		}
		else
		{
			debug( "Monitoring no more retry." );
		}
	}
	Mon_SignalOpXML = null;
	Mon_SignalOpRetry = 3;
}
/*private*/ function Mon_SignalOperation(xmlIn)
{
	if ( Mon_SignalOpXML != null && xmlIn != null )
	{
		// NB: con l'architettura attuale non si verifica xche' lato client parte solo il TCE
		debug( "Monitoring call Error: call already in progress, cannot send data." ); 
		return;
	}

	try 
	{
		debug( "Monitoring call in progress: "+location.protocol+"//"+location.hostname+"/dslib.webservices/DSMonitoring.asmx?WSDL");
		if ( xmlIn != null )
			Mon_SignalOpXML = xmlIn;
		else
			xmlIn = Mon_SignalOpXML;
		var server = document.all("_MonServiceObj");
		server.useService(location.protocol+"//"+location.hostname+"/dslib.webservices/DSMonitoring.asmx?WSDL", "svcApp"); 
		server.async = true; 
		server.svcApp.callService(Mon_SignalCallback, "Log", "<![CDATA["+xmlIn+"]]>" ); 
	}
	catch(e)
	{
		debug( "Monitoring call exception: " + e.description);
		Mon_SignalCallback(null);
	}
}


function CryptCreditCard(ccn)
{
	var k, ret = "";
	var end = ccn.length-4;
	
		
	for( k=0; k<end; k++ )
		ret += "*";
		
	for( k=end; k<ccn.length; k++ )
		ret += ccn.charAt(k);		

	return ret;
}

function CryptCC(ccn)
{		
	
	var k, ret = "";	
	var end;		
	var countzero=0;
	
	for( k=0; k<ccn.length-1; k++ )
		if (ccn.charAt(k) == "0") 
			countzero++;					
		else
			break;

	ccn = ccn.substring(countzero, ccn.length);
	

	if (ccn.length <= 4) 
		end = ccn.length-1;
	else if (ccn.length == 5) 
		end = ccn.length-2;
	else if (ccn.length == 6) 
		end = ccn.length-3;
	else if (ccn.length >= 7) 
		end = ccn.length-4;
	
	
	for( k=0; k<end; k++ )
		ret += "*";
		
	for( k=end; k<ccn.length; k++ )
		ret += ccn.charAt(k);		

	return ret;
}

// Feb09. rcianni
function isDealerOtO()
{
	try
	{
	if ( (Config.Context() == DS_CONTEXT) && (Config.DealerChannel() == "O9") )
		return true;
	else 
			return false;
			}
	catch(e)
	{
		return false;
	}
}

// Nov09. MGROSSO
function isDealerOC()
{
	try
	{
	if ( (Config.Context() == DS_CONTEXT) && (Config.DealerChannel() == "OC") )
		return true;
	else 
			return false;
			}
	catch(e)
	{
		return false;
	}
}





/**************************************************************************************************************
	stefano guagnini
	1/6/2007
 **************************************************************************************************************
 
	base64 encoding

 ***************************************************************************************************************/

var keyStrOTO = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

//**************************************************************************************************************

function encode64OTO(inp)
{
	var out = ""; //This is the output
	var chr1, chr2, chr3 = ""; //These are the 3 bytes to be encoded
	var enc1, enc2, enc3, enc4 = ""; //These are the 4 encoded bytes
	var i = 0; //Position counter

	do 
	{ 
		chr1 = inp.charCodeAt(i++); //Grab the first byte
		chr2 = inp.charCodeAt(i++); //Grab the second byte
		chr3 = inp.charCodeAt(i++); //Grab the third byte

		enc1 = chr1 >> 2;
		enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
		enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
		enc4 = chr3 & 63;

		if (isNaN(chr2)) 
			enc3 = enc4 = 64;
		else if (isNaN(chr3)) 
			enc4 = 64;

		//Lets spit out the 4 encoded bytes
		out += keyStrOTO.charAt(enc1) + keyStrOTO.charAt(enc2) + keyStrOTO.charAt(enc3) + keyStrOTO.charAt(enc4);

		// OK, now clean out the variables used.
		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";
	} 
	while (i < inp.length);

	return out;
}

//*************************************************************************************************************/

function decode64OTO(inp)
{
	var out = ""; //This is the output
	var chr1, chr2, chr3 = ""; //These are the 3 decoded bytes
	var enc1, enc2, enc3, enc4 = ""; //These are the 4 bytes to be decoded
	var i = 0; //Position counter

	var base64test = /[^A-Za-z0-9\+\/\=]/g;
	if (base64test.exec(inp))
	{ 
		return null; 
		//There were invalid base64 characters in the input text.\n" +
		//Valid base64 characters are A-Z, a-z, 0-9, +, /, =
	}
	
	//inp = inp.replace(/[^A-Za-z0-9\+\/\=]/g, "");

	do 
	{ 
		//Grab 4 bytes of encoded content.
		enc1 = keyStrOTO.indexOf(inp.charAt(i++));
		enc2 = keyStrOTO.indexOf(inp.charAt(i++));
		enc3 = keyStrOTO.indexOf(inp.charAt(i++));
		enc4 = keyStrOTO.indexOf(inp.charAt(i++));

		//Heres the decode part. There’s really only one way to do it.
		chr1 = (enc1 << 2) | (enc2 >> 4);
		chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
		chr3 = ((enc3 & 3) << 6) | enc4;

		out = out + String.fromCharCode(chr1);

		if (enc3 != 64) out = out + String.fromCharCode(chr2);
		if (enc4 != 64) out = out + String.fromCharCode(chr3);

		//now clean out the variables used
		chr1 = chr2 = chr3 = "";
		enc1 = enc2 = enc3 = enc4 = "";

	} 
	while (i < inp.length);
	return out;
}

//*************************************************************************************************************/







