//****************************************************
//  CC_JCommonLibrary_2_0_0.js
//****************************************************
//****************************************************

//  GLOBAL CONST *************************************
var QUERYSTRPARAM_SEPCHAR="&";

var STRBIND_BindChar="?";
var STRBIND_FmtStart = "[";
var STRBIND_FmtEnd = "]";

var ITEM_EQUALTO_CHAR = "=";
var ITEM_DELIMITER_CHAR = "[]";
var ITEM_SEPARATOR_CHAR = ";";

//  CLASSES ******************************************
var CLASS_Field_Number = "Field_Number";
var CLASS_Field_Text = "Field_Text";
var CLASS_Field_DateTime = "Field_DateTime";

//****************************************************
//****************************************************

// Legge un cookie 
function CC_ReadCookie(sCookieName){
	var iNumOfCookies; 
	var sTmpName;      
	var iCookieLen;    
	var iX; 
	var iY; 

    iNumOfCookies = document.cookie.length;
    sTmpName = sCookieName + "=";
    iCookieLen = sTmpName.length;
    iX = 0;

    while (iX <= iNumOfCookies){
		iY = (iX + iCookieLen);
		
		if (document.cookie.substring(iX, iY) == sTmpName) return(CC_ExtractCookieValue(iY));
		iX = document.cookie.indexOf(" ", iX) + 1;
		if (iX == 0) break;
    }
    return "";
}

// Crea/Aggiona un cookie 
function CC_CreateCookie(sName, sValue, iExpireDays){
	document.cookie=sName + "=" + sValue + ";" + "expires=" + CC_ReturnExpiry(iExpireDays) + ";";
	return;
}

// Crea/Aggiona un cookie valido solo per la sessione corrente del browser
function CC_CreateTmpCookie(sName,sValue){
	document.cookie = sName + "=" + sValue + ";";
	return;
}

// Elimina un cookie facendolo scadere
function CC_DeleteCookie(sName){
	document.cookie = sName + "=" + " " + ";" + "expires=" + CC_ReturnExpiry(-1) + ";";
	return;
}

// Calcola la data distante n o -n giorni da oggi
function CC_ReturnExpiry(iExpireDays){
	var dtTodayDate = new Date();  
	dtTodayDate.setDate(dtTodayDate.getDate() + iExpireDays);
	return (dtTodayDate.toGMTString());
}

// Estrae il cookie numero iPos
function CC_ExtractCookieValue(iPos){
	var iEndOfCookie;
	if ((iEndOfCookie = document.cookie.indexOf(";",iPos))==-1) iEndOfCookie = document.cookie.length;
		return unescape(document.cookie.substring(iPos,iEndOfCookie));  
}

//****************************************************
//****************************************************

function CC_CStr(vValue){
	if (typeof(vValue)=="undefined" || vValue == null)
		return "";
	else
		return ("" + vValue);
}

function CC_CInt(vValue){
	var iNumber = 0;
	var sNumber = "";

	sNumber = CC_CStr(vValue);
	sGroupSep = CC_GetLocaleGroupSep();
	sDecSep = CC_GetLocaleDecimalSep();

	sNumber = CC_ReplaceSubString(sNumber,sGroupSep,"");
	sNumber = CC_ReplaceSubString(sNumber,sDecSep, ".");
	iNumber = parseInt(sNumber);
	if (isNaN(iNumber)) iNumber = 0;

	return iNumber;
}

function CC_CDbl(vValue){
	var sNumber = "";
	var dNumber = 0;

	sNumber = CC_CStr(vValue);
	sGroupSep = CC_GetLocaleGroupSep();
	sDecSep = CC_GetLocaleDecimalSep();

	sNumber = CC_ReplaceSubString(sNumber,sGroupSep,"");
	sNumber = CC_ReplaceSubString(sNumber,sDecSep, ".");
	dNumber = parseFloat(sNumber);
	if (isNaN(dNumber)) dNumber = 0;

	return dNumber;
}

function CC_Trim(sString){
    return CC_CStr(sString.replace(/(^\s*)|(\s*$)/g, ""));
}

function CC_Left(vValues,vPos){
  //Questa funzione elabora anche i valori di un vettore
	
	var lIndex = 0; // As Long
	var iPos = 0; //As Integer
	var avResult = new Array();
	var sSubstr = "" // as String
	
	if (typeof(vValues)=="object"){
		avResult.length = vValues.length
		
		for (lIndex=0;lIndex<avResult.length;lIndex++)
			avResult[lIndex] = CC_Left(vValues[lIndex],vPos);
		
		return avResult;
	}
	else{
		if (typeof(vPos)=="string"){
		// il secondo parametro è una stringa
			iPos = vValues.indexOf(vPos);
			return vValues.substring(0,iPos)
		}
		else{
		// il secondo parametro è un numero
			return vValues.substring(0,CC_CInt(vPos))
		}
	}
}

function CC_Right(vValues,vPos){
  //Questa funzione elabora anche i valori di un vettore
	
	var lIndex = 0; // As Long
	var iPos = 0; //As Integer
	var avResult = new Array();
	var sSubstr = "" // as String
	
	if (typeof(vValues)=="object"){
		avResult.length = vValues.length
		
		for (lIndex=0;lIndex<avResult.length;lIndex++)
			avResult[lIndex] = CC_Right(vValues[lIndex],vPos);
		
		return avResult;
	}
	else{
		if (typeof(vPos)=="string"){
		// il secondo parametro è una stringa
			iPos = vValues.indexOf(vPos);
			if (iPos>=0)
				return vValues.substring(iPos+1,vValues.length);
			else
				return "";
		}
		else{
		// il secondo parametro è un numero
			return vValues.substring(vValues.length - CC_CInt(vPos),vValues.length)
		}
	}
}

function CC_Round(dValue,iDecPlace) {
	return Math.round(dValue*Math.pow(10,iDecPlace))/Math.pow(10,iDecPlace);
}

function CC_EmptyToChr(sStr,sChar){
	var sRetStr = CC_CStr(sStr);
	
	if (sRetStr == "")
		return sChar;
	else	
		return sRetStr;
}

function CC_Format(vValue,sFmt){
	alert ("Funzione da Implementare Format('" + vValue + "')");
	return vValue;
}

function CC_StrBindParam(sStr,sParams,sSep){
	var iNumParm;//  As Integer
	var sParam;//    As String
	var iLenOfStr;// As Integer
	var sNewStr;//   As String
	var iStart;//    As Integer
	var iFound;//    As Integer
	var iStartFmt;// As Integer
	var iEndFmt;//   As Integer
	
	iNumParm = 0;
	iLenOfStr = sStr.length;

	sNewStr = "";	
	iStart = 0;
	while (iStart <= iLenOfStr){
		iFound = sStr.indexOf(STRBIND_BindChar,iStart)
		if (iFound == -1) break;
		iNumParm = iNumParm + 1
		
		sParam = CC_GetSubStringFromMultiText(iNumParm,sParams,sSep)
		
		if (sParam.length == 0) break;
		sNewStr = sNewStr + sStr.substring(iStart,iFound)
		
		iStartFmt = iFound + 1 + STRBIND_FmtStart.length
		if (sStr.substring(iFound + 1,iStartFmt) == STRBIND_FmtStart){
			iEndFmt = sStr.indexOf(STRBIND_FmtEnd,iStartFmt)
			if (iEndFmt!=-1)
				sNewStr = sNewStr + CC_Format(sParam, sStr.substring(iStartFmt,iEndFmt))
			else {
				alert("CC_StrBindParam: Missing Format End Character in string" + sStr);
				return "";
			}
			iStart = iEndFmt + 1;
		}
		else {
			sNewStr = sNewStr + sParam;
			iStart = iFound + 1;
		}
	}
	return sNewStr + sStr.substring(iStart,sStr.length);
}

function CC_GetSubStringFromMultiText(iSubNumber, sText, sSubSeparator){
	var iPosStart; //As Integer
	var iPosEnd;   //As Integer
	var iSubCount; //As Integer
	var sStr; //As Integer
	
	iSubCount = 0
	iPosStart = 0

	while(true){
		sStr = sText + sSubSeparator
		iPosEnd = sStr.indexOf(sSubSeparator,iPosStart)
		
		iSubCount = iSubCount + 1
		
		if (iSubCount >= iSubNumber) break;
		
		if (sText.substring(iPosEnd,iPosEnd + sSubSeparator.length) == sSubSeparator)
			iPosStart = iPosEnd + sSubSeparator.length
		else
			iPosStart = iPosEnd;
	}
	
	if (iSubCount == iSubNumber && iPosEnd > 0)
		return sText.substring(iPosStart, iPosEnd)
	else
		return "";
	
}

function CC_Str2URL(sStr){
	sStr=CC_ReplaceSubString(sStr, "\\", "/");
	sStr=CC_ReplaceSubString(sStr, " ", "%20");
	return sStr;
}

function CC_URL2Str(sStr){
	sStr=CC_ReplaceSubString(sStr, "/", "\\");
	sStr=CC_ReplaceSubString(sStr, "%20", " ");
	return sStr;
}

// Ritorna la sottostringa individuata dal suffisso sSuffix
function CC_GetStringItem(s,sSuffix){
// N.B. Questa funzione ritorna la sottostringa individuata dal suffisso sSuffix
//   all'interno della stringa data s.
// ES.1  s = "FMT=####", sSuffix = "FMT", output = "####"
// ES.2  s = "FMT=[#;#;0]", sSuffix = "FMT", output= "#;#;0"

	var iStart; 
	var iEnd; 
	var sStr; 

	sStr = s.toUpperCase();
	sStr.indexOf(STRBIND_BindChar,iStart);
	iStart = sStr.indexOf(sSuffix.toUpperCase() + ITEM_EQUALTO_CHAR);
	
	if (iStart > -1){
		iStart = iStart + sSuffix.length + ITEM_EQUALTO_CHAR.length;
		
		if (s.substring(iStart, iStart + 1) == ITEM_DELIMITER_CHAR.charAt(0)){
			iStart = iStart + 1;
			iEnd = s.indexOf(ITEM_DELIMITER_CHAR.charAt(ITEM_DELIMITER_CHAR.length - 1),iStart);
		}
		else
			iEnd = s.indexOf(ITEM_SEPARATOR_CHAR,iStart);
		
		if (iEnd > 0)
			return s.substring(iStart,iEnd);
		else
			return s.substring(iStart,s.length);
	}
	return "";
}

// Questa funzione permette di sostituire una sottostringa di una stringa data
function CC_ReplaceSubString(sStr,sOldStr,sNewStr){
	var sRetStr=""+sStr;
	sOldStr=""+sOldStr;
	sNewStr=""+sNewStr;
	
	if (sOldStr.length == 0) return sRetStr;

	for (var iIndex=0; iIndex<sRetStr.length; iIndex++){ 
		//alert("sRetStr="+sRetStr + " sOldStr=" +sOldStr + " sNewStr=" + sNewStr);
		if (sRetStr.substring(iIndex,iIndex+sOldStr.length) == sOldStr){
			sRetStr = sRetStr.substring(0,iIndex) + sNewStr +sRetStr.substring(iIndex +	sOldStr.length,sRetStr.length);
			iIndex = iIndex + sNewStr.length - 1;
		}
	} 
	return sRetStr;
}

// Conta il numero di occorrenze di una sottostringa in una stringa
function CC_InStrCount(sStr,sFind){
	var iCount=0;
	for (var iIndex=0; iIndex < sStr.length; iIndex++){ 
		if (sStr.substring(iIndex,iIndex + sFind.length) == sFind) 
			iCount = iCount + 1;
	}
	return iCount;
}

/* Converte in una stringa separata da separatore sSep in un array di valori */
function CC_StringToArray(sStr, sSep){
	
	var vArray = new Array();
	vArray.length = 0;
	var iLastStrPos = 0;
	var sRetStr=sStr + sSep
	
	if (CC_CStr(sSep) == "")
		vArray[0] = sStr;
	else
		for (var iIndex=0; iIndex<sRetStr.length; iIndex++) {
			if (sRetStr.substring(iIndex,iIndex + 1) == sSep){
				vArray.length++;
				vArray[vArray.length - 1] = CC_Trim(sRetStr.substring(iLastStrPos,iIndex));
				iLastStrPos = iIndex + 1;
			}
		} 
	
	return vArray;
}

/* Converte in una stringa separata da separatore sSep in un array di valori */
function CC_ArrayToString(vArray, sSep){
	var sRetStr = "";
	
	if (typeof(vArray.length) == "undefined")
		return "";

	for (var iIndex=0; iIndex < vArray.length; iIndex++){
		if (iIndex > 0) sRetStr=sRetStr + sSep;				
			sRetStr = sRetStr + CC_CStr(vArray[iIndex]);
	}

	return sRetStr;
}

function CC_GetArrayElementIdx(vArray,vElement,lStart){
	var lIndex = 0; //As Integer
	
	for (lIndex = lStart; lIndex < vArray.length; lIndex ++){
		if (vArray[lIndex] == vElement) return lIndex;
	}
	
	return -1;	
}

function CC_RemoveArrayElement(vArray,lElementIdx){
	//0 Based Array
	var vRetArray = new Array();
	vRetArray.length = 0;
	
	for (var lIndex = 0; lIndex<vArray.length; lIndex++){
		if (lIndex!=lElementIdx) {
			vRetArray.length ++;
			vRetArray[vRetArray.length -1] = vArray[lIndex];
		}
	}
	return	vRetArray;
}

// restituisce il carattere utilizzato come separatore decimale secondo le impostazioni locali.
function CC_GetLocaleDecimalSep(){
	var dNum = 0.1;
	var sNum =dNum.toLocaleString()
	return sNum.charAt(1);
}

// restituisce il carattere utilizzato come separatore per le migliaia secondo le impostazioni locali.
function CC_GetLocaleGroupSep(){
	//Attendiamo una funzione che faccia questo.
	return ".";
}

//****************************************************
//****************************************************

// imposta il valore di un campo da passare nella query_string
function CC_SetQueryStrParam(sStr,sParamName,sParamValue){
//se il parametro è vuoto, non viene riportato		
	var bFound=false;
  	var sRetStr=	(typeof(sStr) != "string" ? "" : sStr);
	var sParam=sParamName + "=";

	for (var iIndex=0; iIndex < sRetStr.length; iIndex++) { 
		if (sRetStr.substring(iIndex,iIndex+sParam.length) == sParam){
			for (var lIndex=iIndex+sParam.length; lIndex<sRetStr.length; lIndex++) 
			    if (sRetStr.substring(lIndex,lIndex+1) == QUERYSTRPARAM_SEPCHAR) break;
			
			if (typeof(sParamValue)!="undefined" && sParamValue.length!=0)
				sRetStr = sRetStr.substring(0,iIndex) + sParam + CC_Str2URL(sParamValue) + 	
				sRetStr.substring(lIndex,sRetStr.length);		
			else
				sRetStr = sRetStr.substring(0,iIndex) + sRetStr.substring(lIndex,sRetStr.length);
			
			bFound=true;
			break;
		}
	}
	
	if (!bFound && typeof(sParamValue)!="undefined" && sParamValue.length!=0){
		if (sRetStr.length!=0) sRetStr=sRetStr + QUERYSTRPARAM_SEPCHAR;
		sRetStr=sRetStr + sParam + CC_Str2URL(sParamValue);
	}
	return sRetStr;
}

// ritorna il valore di un campo passato nella query_string
function CC_GetQueryStrParam(vLocation,sParamName){
	var bFound=false;
	var sParam=sParamName + "=";		
	var sLocation = "";

	switch (typeof(vLocation)) { 
		case null: sLocation = window.location.href; break;
		case "object": 
			if (vLocation==null)
				sLocation = window.location.href
			else
				sLocation = vLocation.href;
		break;

		case "string": sLocation = vLocation; break;
		default:	 sLocation = window.location.href;
	}

	for (var iIndex=0; iIndex < sLocation.length; iIndex++){ 
		if (sLocation.substring(iIndex,iIndex+sParam.length) == sParam){

			for (var lIndex=iIndex+sParam.length; lIndex<sLocation.length; lIndex++) 
			    if (sLocation.substring(lIndex,lIndex+1) == QUERYSTRPARAM_SEPCHAR) break;
			
			return CC_URL2Str(sLocation.substring(iIndex + sParam.length,lIndex));
		}
	}
	
	return "";
}

// Questa funzione serve per avere i parametri dell'URL in una struttura
function CC_GetLocation(vLocation){
	var objStruct = new Object();
	var asList;
	var sLocation;
	/*
	Espressione regolare che definisce i token per l'URL
	reProtocol:   ((\w+):\/\/)
	reServer:     ([^\/:]*)
	rePort:       :?(\d*);
	reDBPath:     \/([^.]+\.\w+)
	reObjectName: \/?([^?]*)
	reOperation:  \??([^&]*)?
	reParams =    &?(.*)

	*/
	var reURL= /((\w+):\/\/)?(([^@:]*):?([^@]*)@)?([^\/:]*):?(\d*)\/([^.]+\.\w+)\/?([^?]*)\??([^&]*)?&?(.*)/;
	
	if (vLocation == null) vLocation = window.location;

	switch (typeof(vLocation)) 
	{ 
		case "object":
			if (vLocation==null)
				sLocation = window.location.href
			else
				sLocation = vLocation.href;
		break;

		case "string": sLocation = vLocation; break;
		default:	sLocation = window.location.href;
	}

	sLocation = CC_Str2URL(sLocation);

	asList = reURL.exec(sLocation); 	

	//alert( CC_ArrayToString(asList, '\'\n\'') );
	
 	objStruct.sProtocol = CC_CStr( asList[2] );
	objStruct.sUserName = CC_CStr( asList[4] );
	objStruct.sPassword = CC_CStr( asList[5] );
	objStruct.sServer =   CC_CStr( asList[6] );
	objStruct.sPort =     CC_CStr( asList[7] );
	objStruct.sDBPathName = CC_CStr( asList[8] );
	objStruct.sObjectName = CC_CStr( asList[9] );
	objStruct.sOperation=   CC_CStr( asList[10] );
	objStruct.sParams =     CC_CStr( asList[11] );
	return objStruct;
}

// Questa funzione serve per cambiare i parametri relativi all'URL corrente
function CC_ChangeLocation(vOldLocation, sServer, sDBPathName, sOperation, sObjectName, sParams,sProtocol,sPort,sUserName,sPassword){
//Se i parametri sono null mantengono il valore precedente
// se sono vuoti ("") sostituiscono il valore precedente con ""
	var objStruct;
	var sNewProtocol;
	var sNewUserName;
	var sNewPassword;
	var sNewServer;
	var sNewPort;
	var sNewDBPath;
	var sNewObjectName;
	var sNewOperation;
	var sNewParams;

	objStruct = CC_GetLocation(vOldLocation);

 	if (sProtocol   != null) objStruct.sProtocol = sProtocol;
	if (sUserName   != null) objStruct.sUserName = sUserName;
	if (sPassword   != null) objStruct.sPassword = sPassword;
	if (sServer     != null) objStruct.sServer = sServer;
	if (sPort       != null) objStruct.sPort = sPort;
	if (sDBPathName != null) objStruct.sDBPathName = sDBPathName;
	if (sObjectName != null) objStruct.sObjectName = sObjectName;
	if (sOperation  != null) objStruct.sOperation = sOperation;
	if (sParams     != null) objStruct.sParams = sParams;
	
	var sLocation = 
	(objStruct.sProtocol   == "" ? "" : objStruct.sProtocol + "://")  +
	(objStruct.sUserName   == "" ? "" : objStruct.sUserName) +
	(objStruct.sUserName   == "" | objStruct.sPassword == "" ? "" : ":" + objStruct.sPassword) +
	(objStruct.sUserName   == "" ? "" : "@") +
	(objStruct.sServer     == "" ? "" : objStruct.sServer) +
	(objStruct.sPort       == "" ? "" : ":" + objStruct.sPort) +
	(objStruct.sDBPathName == "" ? "" : "/" + objStruct.sDBPathName) +
	(objStruct.sObjectName == "" ? "" : "/" + objStruct.sObjectName) +
	(objStruct.sOperation  == "" ? "" : "?" + objStruct.sOperation) +
	(objStruct.sParams     == "" ? "" : "&" + objStruct.sParams);

	sLocation=CC_Str2URL(sLocation)
	return sLocation;
}

//****************************************************
//****************************************************

function CC_HasItem(ndoc,sField){
	return (typeof(ndoc.forms[0].elements[sField])!="undefined" && ndoc.forms[0].elements[sField]!=null);
}

function CC_GetItemValue(ndoc,sField,sSep){
	var iNumOfItemSelected=0,iIndex=0;
	var vValues = new Array();
	var sCurrentValue = new String();
	
	vValues.length=1;
	vValues[0] = ""; //Anche Notes ritorna sempre un elemento vuoto se il campo non esiste

	if (!CC_HasItem(ndoc,sField)) return vValues;
    //with (ndoc.forms[0]) {
	switch (ndoc.forms[0].elements[sField].type){			
		case "password":
		case "text":
		case "file":
			// entrano in questo case i controlli Notes che sono a valore singolo text/hidden/password/<file>
			// ritorno un array di un elemento passando a CC_StringToArray saparatore nullo
			vValues = CC_StringToArray(CC_CStr(ndoc.forms[0].elements[sField].value),"");
			break;

		case "hidden":
		case "textarea": 
			// entrano in questo case i controlli Notes hidden a valore singolo o multiplo elementi 
			// entrano in questo case i controlli Notes che sono multivalore e anche i controlli a 
			// valore singolo come rich text. ritorno un array di più elementi o, se viene passato sSep="", di un elemento 
			vValues = CC_StringToArray(CC_CStr(ndoc.forms[0].elements[sField].value),sSep);
			break;

		case "select-one":
			// entrano in questo case i controlli Notes ComboBox  
			// ritorno un array di un elemento, che corrisponde a quello selezionato
			sCurrentValue = CC_CStr(ndoc.forms[0].elements[sField].value);
			if (sCurrentValue!="")
				vValues = CC_StringToArray(sCurrentValue,"");
			else
				vValues = CC_StringToArray(ndoc.forms[0].elements[sField][ndoc.forms[0].elements[sField].selectedIndex].text,"");
			break;

		case "select-multiple": 
			// entrano in questo case i controlli Notes listbox che permettono la selezione multipla
			// ritorno un array di più elementi corrispondenti agli elementi selezionati
			for (iIndex=0;iIndex < ndoc.forms[0].elements[sField].length;iIndex++){
				if ( ndoc.forms[0].elements[sField][iIndex].selected ){
					sCurrentValue = CC_CStr(ndoc.forms[0].elements[sField][iIndex].value);
					if(sCurrentValue!="")
						vValues[iNumOfItemSelected++] = CC_CStr(sCurrentValue);
					else
						vValues[iNumOfItemSelected++] = CC_CStr(ndoc.forms[0].elements[sField][iIndex].text);
				}
			}
			vValues.length = iNumOfItemSelected;
			break;

		default: 
			// in Notes i campi <checkbox> e <radio button> vengono portati in HTML come più campi con lo stesso nome.
			// sField è quindi il nome di tutte le scelte del radio/checkbox. 
			// ndoc.forms[0].elements[sField] risulta quindi una collezione e il suo tipo è "undefined".
			// allora bisogna testare gli elementi (almeno il primo)!!!
			if (ndoc.forms[0].elements[sField].length > 0){
			  switch(ndoc.forms[0].elements[sField][0].type){

				case "radio":
					// ritorno un array di un elemento
					iIndex=0;
					while (iIndex<ndoc.forms[0].elements[sField].length && !ndoc.forms[0].elements[sField][iIndex].checked) 
						iIndex++;
					if (iIndex<ndoc.forms[0].elements[sField].length)
						vValues = CC_StringToArray(CC_CStr(ndoc.forms[0].elements[sField][iIndex].value,""));
					break;

				case "checkbox":
					// ritorno un array di più elementi corrispondenti agli elementi selezionati
					for (iIndex=0;iIndex < ndoc.forms[0].elements[sField].length;iIndex++)
						if ( ndoc.forms[0].elements[sField][iIndex].checked )
							vValues[iNumOfItemSelected++] = CC_CStr(ndoc.forms[0].elements[sField][iIndex].value);
					vValues.length = iNumOfItemSelected;
					break;
				
			  }
			}
			else {
			// potrebbe essercene uno solo allora

				if(ndoc.forms[0].elements[sField].type=="checkbox"){
					// ritorno un array di un elemento corrispondente al elemento se selezionato			

					if ( ndoc.forms[0].elements[sField].checked )
						vValues[0] = CC_CStr(ndoc.forms[0].elements[sField].value);
					vValues.length = 1;
				}
				if(ndoc.forms[0].elements[sField].type=="radio"){
					// ritorno un array di un elemento corrispondente al elemento se selezionato			

					if ( ndoc.forms[0].elements[sField].checked )
						vValues[0] = CC_CStr(ndoc.forms[0].elements[sField].value);
					vValues.length = 1;
				}

			}
			break;
	}
  //}
  return vValues;
}

function CC_ReplaceItemValue(ndoc,sField,vpValues,sSep){
	var i,ivValueIndex,iIndex;
	// se non è un array ne creo uno. NB: typeof(<array>) = object
	var vValue = new Array();
	if (typeof(vpValues)!="object")
		vValue = CC_StringToArray(vpValues);
	else
		vValue = vpValues;

	if (!CC_HasItem(ndoc,sField)) return;
	//with (ndoc.forms[0]) {	
/*	var 	sAlert='CC_ReplaceItemValue:\n\n'
			sAlert +='sField=' + sField + '\n' + '\ntype= ' + ndoc.forms[0].elements[sField].type +
					 '\nvValue.length=' + vValue.length + ' vValue= ' + vValue +
					 '\nSeparatore =\'' +sSep+'\'\n';
			for(i=0;i<vValue.length;i++)
				sAlert+='\nvValue['+i+']=' + vValue[i];
			alert(sAlert);	*/
	switch (ndoc.forms[0].elements[sField].type){			
 		case "file":
		case "password":
		case "text":
		case "hidden":
		case "textarea": 
			ndoc.forms[0].elements[sField].value = CC_ArrayToString(vValue,sSep);
			break;

		case "select-one":
			// seleziona l'ultimo sul value o sul text			
			for(iIndex=0;iIndex<ndoc.forms[0].elements[sField].length;iIndex++){
			  if ( ndoc.forms[0].elements[sField][iIndex].value == vValue[vValue.length-1] || 
				ndoc.forms[0].elements[sField][iIndex].text == vValue[vValue.length-1] )
					ndoc.forms[0].elements[sField][iIndex].selected = true;
			}
			break;

		case "select-multiple": 
			// seleziona tutti sul value o sul text
			ivValueIndex = 0;
			while (ivValueIndex < vValue.length){
  			  for(iIndex=0;iIndex<ndoc.forms[0].elements[sField].length;iIndex++)
			    if ( ndoc.forms[0].elements[sField][iIndex].value == vValue[ivValueIndex] || 
				  ndoc.forms[0].elements[sField][iIndex].text == vValue[ivValueIndex] )
					ndoc.forms[0].elements[sField][iIndex].selected = true;
			  ivValueIndex++;
			}
			break;

		default: 

			if (ndoc.forms[0].elements[sField].length >= 0){
			  switch(ndoc.forms[0].elements[sField][0].type){

				case "radio":
					// seleziona il primo sul value
					for(iIndex=0;iIndex<ndoc.forms[0].elements[sField].length;iIndex++){
						if ( ndoc.forms[0].elements[sField][iIndex].value == vValue[0] )
							ndoc.forms[0].elements[sField][iIndex].checked = true;
					}
					break;

				case "checkbox":
					// seleziona sul value
					ivValueIndex = 0;
					for(iIndex=0;iIndex<ndoc.forms[0].elements[sField].length;iIndex++)
					    ndoc.forms[0].elements[sField][iIndex].checked = false;
					while (ivValueIndex < vValue.length){
						for(iIndex=0;iIndex<ndoc.forms[0].elements[sField].length;iIndex++){
							if ( ndoc.forms[0].elements[sField][iIndex].value == vValue[ivValueIndex] )
								ndoc.forms[0].elements[sField][iIndex].checked = true;
						}
						ivValueIndex++;
					}
					break;
				
			  }
			}//if
			else {
				if(ndoc.forms[0].elements[sField].type=="checkbox")
					if ( ndoc.forms[0].elements[sField].value == vValue[0] )
						ndoc.forms[0].elements[sField].checked = true;	
					else			
						ndoc.forms[0].elements[sField].checked = false;
			}
			break;
	}

	//}
}

function CC_AppendToTextList(ndoc,sFieldName,sValue,sSep){
	var sNewValue = CC_GetItemValue(ndoc,sFieldName)[0];

	if (sNewValue.length) sNewValue += sSep;
	sNewValue += sValue;

	CC_ReplaceItemValue(ndoc,sFieldName,sNewValue);	
}

function CC_GetFieldType(ndoc,sField){
	/*Questa funzione restituisce il tipo di un campo notes, 
		ndoc: documento contenente il campo
		sField: nome del campo	
		per i valori di ritorno possibili 
		consultare la documentazione relativa all'attributo "Type" della classe NotesItem.	
		in aggiunta questa funzione ritorna -1 se il campo non viene trovato.*/
	// Attenzione da Client Web è impossibile stabilire il tipo di campo Notes,
	// E' necessario quindi aggiungere al campo l'attributo DATAFLD = tipocampo
	// Nella sezione HTML/other delle proprietà del campo
	
	if (!CC_HasItem(ndoc,sField)) return -1;
	
	var sItemType = ndoc.forms[0].elements[sField].className;

	if (!(typeof(sItemType)=="undefined"))
		return sItemType;
	else
		return -1;
	
}

//****************************************************
//****************************************************

function CC_GotoField(ndoc, sFieldName){
	var objElement;

	//with (ndoc.forms[0]){
	if (ndoc.forms[0].elements[sFieldName].length >= 0)
		objElement = ndoc.forms[0].elements[sFieldName][0];
	else
		objElement = ndoc.forms[0].elements[sFieldName];

	//}
	try{
		if (typeof(tab) != "undefined") CC_GotoTab(tab);
		if (typeof(section) != "undefined") CC_OpenSection(section);
		objElement.focus();
	}
	catch(e){
		return;
	}	
}

function CC_GotoTab(sTabName){
	var tabID = "";
	var tagsColl = document.all.tags("DIV");

	//Rilevo la categoria relativa al tab selezionato.
	for (var iIndex = 0;iIndex<tagsColl.length;iIndex++){
		if (tagsColl[iIndex].dataFld == sTabName){
			tabID = tagsColl[iIndex].id;
			break;
 		}
	}
	
	//Imposto la visibilita dei tabs della categoria selezionata.
	var tabColl = document.all(tabID);
	if (typeof(tabColl) == "undefined") return;

	for (iIndex = 0;iIndex<tabColl.length;iIndex++){
		if (tabColl[iIndex].dataFld == sTabName){
   			tabColl[iIndex].style.display = "inline";
   			document.all('CurrentTab_' + tabID).value = tabColl[iIndex].dataFld;
		}
		else{
			if (CC_Right(tabColl[iIndex].dataFld,2) == "_D"){
				if (tabColl[iIndex].dataFld != sTabName + "_D")
					tabColl[iIndex].style.display = "inline";
				else
					tabColl[iIndex].style.display = "none";
			}
			else
   			tabColl[iIndex].style.display = "none";
 		}
	}	
} 

function CC_SaveFrameLocation(sFrameName){
	try{
		CC_CreateTmpCookie(sFrameName, this.parent.frames(sFrameName).location);
	}
	catch(e){
		CC_DeleteCookie(sFrameName);
	}	
}

function CC_LoadFrameLocation(sFrameName){
	var sLocation="";
	sLocation =	CC_ReadCookie(sFrameName)

	if (sLocation.length)
		this.parent.frames(sFrameName).location.href = sLocation;
}

function CC_SaveScrollPos(obj){
	try{
		CC_CreateTmpCookie(obj.name + "ScrollTop",obj.scrollTop);
		CC_CreateTmpCookie(obj.name + "ScrollLeft",obj.scrollLeft);
	}
	catch(e){
		CC_DeleteCookie(obj.name + "ScrollTop");
		CC_DeleteCookie(obj.name + "ScrollLeft");
	}	
}

function CC_LoadScrollPos(obj){
	lTopScroll =	CC_ReadCookie(obj.name + "ScrollTop")
	lLeftScroll =	CC_ReadCookie(obj.name + "ScrollLeft")
	
	obj.scrollTop = lTopScroll;
	obj.scrollLeft = lLeftScroll;
}

function CC_OpenSection(sSectName){
	var tabColl = document.all(sSectName);
	
	//Imposto la visibilita delle sezioni della categoria selezionata.
	if (typeof(tabColl) == "undefined") return;

	for (var iIndex = 0;iIndex<tabColl.length;iIndex++){
		if (tabColl[iIndex].dataFld == "open")
   			tabColl[iIndex].style.display = "inline";
		else
   			tabColl[iIndex].style.display = "none";

		document.all('CurrentStatus_' + sSectName).value = "1";
 	}
} 

function CC_CloseSection(sSectName){
	var tabColl = document.all(sSectName);
	
	//Imposto la visibilita delle sezioni della categoria selezionata.
	if (typeof(tabColl) == "undefined") return;

	for (var iIndex = 0;iIndex<tabColl.length;iIndex++){
		if (tabColl[iIndex].dataFld != "open")
   			tabColl[iIndex].style.display = "inline";
		else
   			tabColl[iIndex].style.display = "none";

		document.all('CurrentStatus_' + sSectName).value = "0";
 	}
} 

function CC_SetSection(sSectName){
	//imposto lo stato della sezione dopo un reload della pagina
	if (document.all('CurrentStatus_' + sSectName).value == "1")
		CC_OpenSection(sSectName);
	else
		CC_CloseSection(sSectName);		
} 

//****************************************************
//****************************************************

function CC_OpenHelp(sKey){
	//questa funzione necessita di una vista "HelpTopics" 
	var objWin;
	var sHelpURL = CC_ChangeLocation(null,null,null,"","","");

  sHelpURL += '/HelpTopics/' + sKey;
	
 // objWin = self.open( sHelpURL,'help','height=200,width=500,scrollbars=yes,resizable=yes');
	CC_OpenWin(self,sHelpURL,'help','scrollbars=yes,resizable=yes',500,200);
}

function CC_OpenWin(objParentWin,sUrl,sWindowName,sWindowAppearance,iWidth,iHeight){
	var iNewLeft = 0;
	var iNewTop = 0;
	var sNewAppearance = "";
	
	iNewLeft = (screen.availWidth - iWidth)/2
	iNewTop = (screen.availHeight - iHeight)/2
	if (iNewLeft<0) iNewLeft=0;
	if (iNewTop<0) iNewTop=0;
	
	sNewAppearance = CC_CStr(sWindowAppearance);
	if (sNewAppearance.length) sNewAppearance += ", ";
	sNewAppearance += 
		"left=" + iNewLeft + 
		",top=" + iNewTop + 
		",width=" + iWidth + 
		",height=" + iHeight;

	//alert(sNewAppearance);
		
	objParentWin.open(sUrl,sWindowName,sNewAppearance);
//	var WinObj = objParentWin.open(sUrl,sWindowName,sNewAppearance);
//	return WinObj;
}

/* Genera una picklist*/
function CC_wPickList(sServer,sDBPathName,sViewName,sKey,bExact,sTitle,sPrompt,sCallBackFunc,bMultiSel,sRestrictToCategory){
	/*sServer:			nome del server dove risiede il database
		sDBPathName: percorso e nome del database
		sViewName:   nome della vista
		sKey:					chiave da ricercare nella vista
		bExact:				non utilizzato (per versioni future)
		sTitle:				titolo della finestra
		sPrompt:				messaggio visualizzato in testa alla vista
		sCallBack:		funzione o istruzione che viene chiamata alla pressione del tasto OK
										questa funzione potrà avere un parametro particolare $RET$ che sarà 										sostituito con	gli ids dei documenti selezionati
		bMultiSel:		se true permette la selezione di più valori.
		sRestrictToCategory:		Categoria con cui filtrare i documenti in vista
	*/

	var sParams;
	var sDocID;
	var objWin;
		
	self.retDocID = "";
	sParams = CC_SetQueryStrParam(sParams, "ViewName",sViewName);
	sParams = CC_SetQueryStrParam(sParams, "Exact",bExact);
	sParams = CC_SetQueryStrParam(sParams, "Title",sTitle);
	sParams = CC_SetQueryStrParam(sParams, "Prompt",sPrompt);
	sParams = CC_SetQueryStrParam(sParams, "Count",100);
	sParams = CC_SetQueryStrParam(sParams, "StartKey",sKey);
	sParams = CC_SetQueryStrParam(sParams, "CallBackFunc",sCallBackFunc);
	sParams = CC_SetQueryStrParam(sParams, "MultiSelection",(bMultiSel?1:0));
	sParams = CC_SetQueryStrParam(sParams, "RestrictToCategory",sRestrictToCategory);

	//sLocation = 	CC_ChangeLocation(self.location,	null, sDBPathName,
	//																			"OpenForm","CC_wPickListMsgBox",
	//																			sParams);	
	sLocation = 	CC_ChangeLocation(self.location,	sServer, sDBPathName,
																				"OpenView",sViewName, sParams);	
	if (POPUP_width)
		CC_OpenWin(self,sLocation,"","resizable=0",POPUP_width, POPUP_height);
	else
		CC_OpenWin(self,sLocation,"","resizable=0",560,450);
}

function CC_WaitForWin(objWin){
// questa funzione blocca l'esecuzione finché la finestra non viene chiusa
	while (!objWin.closed){}
}

//****************************************************
//****************************************************

function CC_wUploadFile(sTitle,sPrompt,sCallBackFunc){
/*sDBPathName: 	percorso e nome del database
	sTitle:		titolo della finestra
	sPrompt:	messaggio visualizzato in testa alla vista
	sCallBack:	funzione o istruzione che viene chiamata alla pressione del tasto OK
				questa funzione potrà avere un parametro particolare $RET$ che sarà sostituito con 															il nome del file temporaneo già scaricato sul server
*/
	var sParams;
		
	sParams = CC_SetQueryStrParam(sParams, "Title",sTitle);
	sParams = CC_SetQueryStrParam(sParams, "Prompt",sPrompt);
	sParams = CC_SetQueryStrParam(sParams, "CallBackFunc",sCallBackFunc);
	sLocation = 	CC_ChangeLocation(self.location, null, null,"OpenForm","wFileUpload", sParams);	

	CC_OpenWin(self,sLocation,"","resizable=1",230,100)
}

function CC_wSignDocument(sTitle,sPrompt,sFieldName,sDocUNID,sCallBackFunc){
/*sDBPathName: 	percorso e nome del database
	sTitle:		titolo della finestra
	sPrompt:	messaggio visualizzato in testa alla vista
	sCallBack:	funzione o istruzione che viene chiamata alla pressione del tasto OK
				questa funzione potrà avere un parametro particolare $RET$ che sarà sostituito con 															il nome del file temporaneo già scaricato sul server contenente il documento in formato XML firmato 
*/
	var objUrl;
	var sParams;
	objStruct =	CC_GetLocation();	
	alert (objStruct.sObjectName);
	sParams = CC_SetQueryStrParam(sParams, "Title",sTitle);
	sParams = CC_SetQueryStrParam(sParams, "Prompt",sPrompt);
	sParams = CC_SetQueryStrParam(sParams, "DocUNID",sDocUNID);
	sParams = CC_SetQueryStrParam(sParams, "Field",sFieldName);
	sParams = CC_SetQueryStrParam(sParams, "CallBackFunc",sCallBackFunc);
	sLocation = 	CC_ChangeLocation(self.location, null, null, "OpenForm", "wSignDocument", sParams);	
	CC_OpenWin(self,sLocation,"","resizable=0",230,100);
}

function CC_CommandEditDocument(){
	var sCurrentUrl = self.location.href;
	var bIsReadMode = sCurrentUrl.search(/\?OpenDocument/) != -1;

	if (bIsReadMode)
		self.location = CC_ChangeLocation(sCurrentUrl, null, null,"EditDocument");
}
function CC_CommandOpenDocument(){
	var sCurrentUrl = self.location.href;
	var bIsEditMode = sCurrentUrl.search(/\?EditDocument/) != -1;

	if (bIsEditMode)
		self.location = CC_ChangeLocation(sCurrentUrl, null, null,"OpenDocument");
}
// questa funzione permette di verificare se la stringa data è un indirizzo e-mail valido
function CC_IsMailAddress(sValue){
	var iPosAt  = sValue.indexOf("@",1);
	var iPosDot = sValue.indexOf(".",iPosAt+1);
  	
	if (iPosAt == -1 | iPosDot == -1) 
		return false;
	else
		return true;
}

// imposta la visualizzazione dell'action bar
function CC_SetActionBarProperies(bView, moveBeforeElementID) {
	var FORMObj, VIEWDIVObj, VIEWTABLEObj , TABLEObj, TRObj, TDObjs, TDObj, iIndex;
	if(document.getElementsByTagName){
		TABLEObj = document.getElementsByTagName('table').item(0);
		TABLEObj.setAttribute("id","actionBar");
		TABLEObj.setAttribute("name","actionBar");
		TABLEObj.setAttribute("border","0");
		TABLEObj.setAttribute("className","actionBar"); // IE
		TABLEObj.setAttribute("class","actionBar");  	// Others
		//
		TRObj = TABLEObj.getElementsByTagName('tr').item(0);
		TDObjs = TRObj.getElementsByTagName('td')
		for(iIndex=0;iIndex<TDObjs.length;iIndex++){			
			TDObj = TDObjs.item(iIndex);
			TDObj.setAttribute("nowrap","true");
		}
		//
		TDObj = document.createElement("td"); 
		TDObj.setAttribute("id","actionBarSpacer");
		TDObj.setAttribute("name","actionBarSpacer");
		TDObj.setAttribute("width","100%"); // IE & Others
		TRObj.appendChild(TDObj);		
		
		if (bView){
    		// sposto l'action bar sopra la vista
    		FORMObj = TABLEObj.parentNode;
    		FORMObj.removeChild(TABLEObj);
    		if (moveBeforeElementID!=null){
	    		var Obj = document.getElementById(moveBeforeElementID);
	    		var ParentObj = Obj.parentNode;
	    		ParentObj.insertBefore(TABLEObj,Obj);
	    		ParentObj.setAttribute("width","100%"); // IE & Others
			}
			else {
	    		VIEWDIVObj = document.getElementById('view');
	   			//VIEWTABLEObj = VIEWDIVObj.getElementsByTagName('table').item(0);
	    		VIEWTABLEObj = VIEWDIVObj.firstChild;
	    		VIEWDIVObj.insertBefore(TABLEObj,VIEWTABLEObj);
			}
		}

	}
}
// aggiunge lo switch delle viste 
function CC_ActionBarAppendViewSwitcher(sViewNames, sViewLabels) {
	var TDObj, SELECTObj, OPTIONObj, iIndex, sLocation;
	
	var Change = function (){ 
		var sUrl = this.options[this.selectedIndex].value;
		if (sUrl.length!=0) location.assign(sUrl); 
	};	
	
	if (typeof(sViewNames)=="string") sViewNames = CC_StringToArray(sViewNames, "");
	if (typeof(sViewLabels)=="string") sViewLabels = CC_StringToArray(sViewLabels, "");
	
	//if(document.getElementsById){
	TDObj = document.getElementById('actionBarSpacer');	
	TDObj.setAttribute("align", "right")
	//
	SELECTObj = document.createElement("select"); 
	CC_SwitchCSSClass(SELECTObj, "actionBarViewSwitcher");
	
	// aggiungo il testo "cambia vista"
	OPTIONObj = document.createElement("option");
	//OPTIONObj.innerHTML = "Cambia Vista";
	OPTIONObj.text = "Cambia Vista";
	OPTIONObj.value = "";	
	SELECTObj.options.add(OPTIONObj);
	
	for(iIndex=0; iIndex<sViewNames.length; iIndex++){
		OPTIONObj = document.createElement("option");			
		//OPTIONObj.innerHTML = sViewLabels[iIndex];
		OPTIONObj.text = sViewLabels[iIndex];
		sLocation = CC_ChangeLocation(self.location, null, null, "OpenView", sViewNames[iIndex], null);	
		OPTIONObj.value = sLocation;
		SELECTObj.options.add(OPTIONObj);
	}
	SELECTObj.onchange = Change;
	//
	TDObj.appendChild(SELECTObj);		
	//}
}


//serve per fare lo switch della classe CSS 
function CC_SwitchCSSClass(Obj, sClass){
	Obj.setAttribute("className",sClass); // IE
	Obj.setAttribute("class",sClass);     // Other
}

//imposta gli eventi della tabella view
function CC_SetViewEvents(TABLEObj, bDblClick){
	var TRObjs, TRObj, node, iIndex;

	var mouseOver = function (){ CC_SwitchCSSClass(this, 'selected'); };
	var mouseOut  = function (){ CC_SwitchCSSClass(this, ''); };	
	var mouseDblClick = function (){
		//var TDObj = this.getElementsByTagName('td').item(0);
		//var AObj = TDObj.getElementsByTagName('a').item(0);
		var AObj = this.getElementsByTagName('a').item(0);
		//alert( AObj.href );
		if (AObj.href.search(/\?OpenDocument/)==-1) AObj = this.getElementsByTagName('a').item(1);
		location.assign( AObj.href );		
	}

	if(TABLEObj && TABLEObj.getElementsByTagName){
		TRObjs = TABLEObj.getElementsByTagName('tr');
		for(iIndex=1; iIndex<TRObjs.length; iIndex++){
			TRObj = TRObjs.item(iIndex);
			//queste commentate funzionano solo con mozilla
			//TRObj.setAttribute("onMouseOver", "CC_SwitchCSSClass(this,'selected');"); 
			//TRObj.setAttribute("onMouseOut",  "CC_SwitchCSSClass(this,'');");
			TRObj.onmouseover = mouseOver;
			TRObj.onmouseout  = mouseOut;
			if(bDblClick==true) TRObj.ondblclick  = mouseDblClick;
		}
	}
}


// TEST
function moveAttachmentTable() {
	var TABLEObjs, TABLEObj;
	if(document.getElementsByTagName){
		try {
			TABLEObjs = document.getElementsByTagName('table');
			TABLEObj = TABLEObjs.item(TABLEObjs.length-1);
/*			TABLEObj.setAttribute("className","dev"); // IE
			TABLEObj.setAttribute("class","dev");  	// Others*/
			var Obj = document.getElementById('attachments_placement');
			var ParentObj = Obj.parentNode;
			ParentObj.insertBefore(TABLEObj,Obj);
		}
		catch(e){
			return;
		}
	}
}

/*******************************************************************************
/*******************************************************************************
#scrollingContainer{
  position: relative;
  overflow: hidden;
  
  width:  200px;    
  height: 200px;  
/ ** /   
  background: #FFFFFF;
  border:  3px solid #FF0000;
  padding: 2px 2px 2px 4px;
}
*******************************************************************************/
var scrolling_Obj;
/******************************************************************************/
function cc_scrolling_doScroll(){
  //if scroller hasn't reached the end of its height
	if (parseInt(scrolling_Obj.style.top)>(scrolling_Obj.currentHeight*(-1)+8)) 
     //move scroller upwards
     scrolling_Obj.style.top = parseInt(scrolling_Obj.style.top) - scrolling_Obj.currentSpeed+"px"; 
	else //else, reset to original position
		 scrolling_Obj.style.top = parseInt(scrolling_Obj.maxHeight)+8+"px";
}
/******************************************************************************/
function cc_scrolling_initialize( scrollingId, delay, speed, pause){  

  scrolling_Obj = document.getElementById(scrollingId);
  scrolling_Obj.style.top = 0;
    
  scrolling_Obj.maxHeight     = scrolling_Obj.parentNode.offsetHeight;
  scrolling_Obj.currentHeight = scrolling_Obj.offsetHeight;
  
  scrolling_Obj.delay = delay;  
  scrolling_Obj.pause = pause;

  scrolling_Obj.maxSpeed     = speed;  
  scrolling_Obj.currentSpeed = speed;
  scrolling_Obj.pauseSpeed   = (scrolling_Obj.pause)? 0: scrolling_Obj.currentSpeed;
  
  //eventi
 	var mouseOver = function (){ scrolling_Obj.currentSpeed = scrolling_Obj.pauseSpeed; };
	var mouseOut  = function (){ scrolling_Obj.currentSpeed = scrolling_Obj.maxSpeed; };	
	scrolling_Obj.parentNode.onmouseover = mouseOver;
	scrolling_Obj.parentNode.onmouseout  = mouseOut;
  
	//if Opera or Netscape 7x, add scrollbars to scroll and exit  
  if (window.opera || navigator.userAgent.indexOf("Netscape/7")!=-1){ 
    scrollingObj.style.height   = scrolling_Obj.actualHeight + "px";
    scrollingObj.style.overflow = "scroll";
    return
  }
  
  if(!scrolling_Obj.maxHeight)
  	// se non ha ancora caricato i div le proprietà risultano nulle -> aspetto
 	 	setTimeout("cc_scrolling_initialize('"+scrollingId+"',"+delay+","+speed+","+pause+")",30);
  else
	  setTimeout('setInterval("cc_scrolling_doScroll()",30)', scrolling_Obj.delay);
}
/*******************************************************************************
cc_scrolling_initialize( <id>, 2000, 2, true)
*******************************************************************************/

