//------------------------------------------------------------------
// Funzioni di utilità
//------------------------------------------------------------------

/**
 * Restituisce true se il combo box è selezionato.
 */
function Is_Select(theSel){
  if(theSel.options[theSel.selectedIndex].value == "")
    return false
  return true;
}

/**
 * Controlla se il campo è una data ed in caso
 * contrario restituisce un messaggio esplicativo.
 */
function Is_Date(theElement) {
  var DayArray =new Array(31,28,31,30,31,30,31,31,30,31,30,31);
  var MonthArray = new Array("01","02","03","04","05","06","07","08","09","10","11","12");
  var thisYear = null;
  var thisMon = null;
  var thisDay = null;
  var today = null;
  inpDate = theElement;
  if (inpDate.length == 0 ) return "";
  thisDay = inpDate.substr(0,2);
  thisMonth = inpDate.substr(3,2);
  thisYear = inpDate.substr(6,4);
  var filter=/^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
  if (! filter.test(inpDate))
    return ("deve essere inserito con il formato GG/MM/AAAA");
  var filter=/01|02|03|04|05|06|07|08|09|10|11|12/ ;
  if (! filter.test(thisMonth))
    return ("deve essere specificato con un mese corretto");
  N=Number(thisYear);
  if ( ( N%4==0 && N%100 !=0 ) || ( N%400==0 ) )
    DayArray[1]=29;
  for(var ctr=0; ctr<=11; ctr++){
    if (MonthArray[ctr]==thisMonth){
      if (thisDay<= DayArray[ctr] && thisDay >0 )
        return("");
      else
        return ("deve essere specificato con un giorno valido");
    }
  }
}

/**
 * Controlla la correttezza della stringa
 */
function checkStringNumber(checkStr) {
	
	var checkOK = "0123456789qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
	var allValid = true;
	var decPoints = 0;
	var allNum = "";

	for (i = 0;  i < checkStr.length;  i++)	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
				break;

		if (j == checkOK.length) {
			allValid = false;
			break;
		}
		allNum += ch;
	}
	if (!allValid) {
		return (false);
	}
	return true;
}

/**
 * Restituisce true se il campo è numerico.
 */
function checkNumber(checkElem) {
  var checkStr = checkElem.value;
  return checkNumberv(checkStr);
}

/**
 * Restituisce true se il campo è numerico.
 */
function checkNumberv(checkStr) {
	var checkOK = "0123456789";
	var allValid = true;
	var decPoints = 0;
	var allNum = "";

	for (i = 0;  i < checkStr.length;  i++)	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++)
			if (ch == checkOK.charAt(j))
				break;

		if (j == checkOK.length) {
			allValid = false;
			break;
		}
		allNum += ch;
	}
	if (!allValid) {
		return (false);
	}
	return true;
}

function checkReal(elem){
  ok = true;
  elem.value = elem.value.replace(/\,/g,".");
  if((elem.value != "")&&(parseFloat(elem.value) != elem.value)) {
    ok = false;
  }
  elem.value = elem.value.replace(/\./g,",");
  return ok;
}

// formatta la valuta in formato javascript
function formatNumerico(val) {
  val=val.toString();	
  return (val.replace(/\./g,",")).replace(/\,/g,".").replace(/ /g,"");
}

// controlla il formato di un numero  
// ritorna un messaggio esplicativo in presenza di errori
function checkNumberFormat(srField,isMandatory,format,lMin,lMax){
  var msg="";
  if(srField == "" || srField == null) {
	if(isMandatory)
		return " non può essere nullo";
  } else {
		s1Field = srField.replace(/./gi/"");
		sField="";
		for(i=0;i<s1Field.length;i++) {
			ch=s1Field.charAt(i);
			if(ch==',')
				sField+='.';
			else {
				if (ch!='.')
					sField+=ch;
			}
		}
		if(isNaN(sField))
			return " non è di tipo numerico";
		ind = format.indexOf(".");
		if(ind > 0) {
			iFDecim  = parseInt(format.substring(ind + 1));
			iFInteg = parseInt(format.substring(0, ind)) - iFDecim;
		} else {
			iFInteg = parseInt(format);
			iFDecim = 0;
		}
		ind = sField.indexOf(".");
		if(ind > 0) {
			integ = sField.substring(0, ind);
			decim  = sField.substring(ind + 1);
			iField = parseFloat(sField);
		} else {
			decim  = 0;
			integ = sField;
			iField = parseInt(sField);
		}
		if(integ.length > iFInteg || decim.length > iFDecim)
			return " ha un formato non valido ";
		if(iField < lMin || iField > lMax)
			return " non è nell'intervallo stabilito";
  }
  return "";
}

// formatta la valuta in stile italiano 
// con numint cifre intere e numfraz decimali
function formatImportoExt(valore,numint,numfraz) {
  negativo=false;
	if (!isNaN(valore)){
		valore=valore.toString();
		if (valore.substr(0,1) == "-") {
			valore=valore.substr(1);
			negativo=true;
		}

    var conversione = 1;
    if(numfraz > 0)
      conversione = Math.pow(10,numfraz);

	  valore = (parseInt(Math.round(valore*conversione))/conversione).toString();
	  valore = valore.replace(/\./g,",");

    dp = valore.indexOf(",")!=-1? valore.substring(0,valore.indexOf(",")).length:valore.length;
    if(dp != numint)
      for (i=dp; i<numint; i++) 
        valore="0"+valore;

        // separatore delle migliaia
		for (i=dp-3;i>0;i-=3)
			valore=valore.substring(0,i)+"."+valore.substr(i);
 
		valore=valore.replace(/-,/,"-");

    decimali = "";
    if(valore.indexOf(",")==-1){
      for(i=0;i<numfraz;i++)
        decimali+="0";
        valore+=","+decimali;    
    }else{
      decimali = valore.substr(valore.indexOf(",")+1);
      if(decimali.length != numfraz)
        for(i=decimali.length;i<numfraz;i++)
          valore+="0";
    }
    
    if (negativo)
      valore="-"+valore;
      
	return valore;
  }
}

// Controlla se il campo contiene un valore numerico 
// formattandolo nello stile  ##,@@@ 
// dove ## è stabilito da numint
// e   @@@ è stabilito da numfraz
// sono permessi valori negativi
// car rappresenta l'eventuale carattere ammesso
function isNumExt(field, numint, numfraz, car){
  var theVal = field.value;
  if (theVal == '')
    return "";

  var found = 0;
  if ((car != '')&&(theVal.indexOf(car) != -1)){
    theVal = theVal.slice(0,theVal.indexOf(car));
    found = 1;
  }

  var m;
  if (theVal.substr(0,1) == "-") {
    m = checkNumberFormat(theVal.substr(1),false,'16.3',0,9999999999999.999);
	}else{
    m = checkNumberFormat(theVal,false,'16.3',0,9999999999999.999);
  }

  if (m.length==0) {
    theVal = formatImportoExt(formatNumerico(theVal),numint,numfraz);
    if(found == 1)
	  field.value= theVal+car;
    else
      field.value = theVal;
    return "";
  } else {
	return " deve essere numerico!" ;
  }
  
}

/**
 * Restituisce true se il campo è un'email
 */
function Is_Email(sDato)
{
 if (sDato != "")
 {
  var s = sDato;
  var localPartfilter1 = /^[^<>()\[\]\x5C.,;:@" ]+(\.[^<>()\[\]\x5C.,;:@" ]+)*@$/;
  var localPartfilter2 = /^"[^\r\n]+"@$/;
  var domainfilter = /^([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9])(\.([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9]))(\.([a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]|[a-zA-Z0-9]))*$/;
  var sepPos = 0;
  var localPart;
  var domain;
  var localPartOk = false;
  var domainOk    = false;
  sepPos = s.lastIndexOf("@");
  localPart = s.substring(0,sepPos+1);
  domain    = s.substring(sepPos+1,s.length);
  if  (localPartfilter1.test(localPart))
    localPartOk = true;
  else if (localPartfilter2.test(localPart))
    localPartOk = true;
  else
    localPartOk = false;
  if (domainfilter.test(domain))
    domainOk = true;
  else
    domainOk = false;
  if (localPartOk != true || domainOk != true)
    return false;
  return true;
 }
}

/**
 * Restituisce true se il campo 
 * è nel formato nnn,nnn,nnn,nnn 
 */
function Is_Coord(sDato)
{
  var coords = sDato.split(",");
  
  if (coords.length != 4)
    return false;
  
  return checkNumberv(coords[0])&& 
         checkNumberv(coords[1])&&
         checkNumberv(coords[2])&&
         checkNumberv(coords[3]);
    
}

/**
 * Esegue il submit dopo aver settato i campi base
 */
function doSubmit(theForm, operation){
  theForm.path.value=window.top.location.pathname;
  theForm.operation.value=operation;
  theForm.submit();
}

/**
 * Apre una popup con stato e dimensioni fisse
 */
function WopenFixStatus(dest, nome,largh, alt) {
  opzioni = 'width='+largh+',height='+alt+',toolbar=no,directories=no,menubar=no,status=yes,scrollbars=yes,resizable=no';
  wingame = window.open (dest, nome, opzioni);
}

/**
 * Apre una popup con stato e dimensioni fisse
 */
function WopenStatus(dest, nome,largh, alt) {
  opzioni = 'width='+largh+',height='+alt+',toolbar=no,directories=no,menubar=no,status=yes,scrollbars=yes,resizable=yes';
  wingame = window.open (dest, nome, opzioni);
}

/**
 * Apre una popup non modificabile
 */
function WopenFix(dest, nome) {
  opzioni = 'width=5,height=5,left=0,top=0,toolbar=no,directories=no,menubar=no,status=no,scrollbars=no,resizable=no,alwaysLowered=yes';
  wingame = window.open (dest, nome, opzioni);
}

/**
 * Apre una popup
 */
function Wopen(dest) {
  var width = 800
  var height = 440
  var top = 0 // (screen.height - height) / 2
  var left = 0 //(screen.width - width) / 2

  window.open(dest,'info','scrollbars=yes, resizable=yes, width=' + width +', height=' + height + ', left=' +left + ',top=' + top)
}

/****
Il campo columns indica quante colonne aspettarsi dalla query
Il campo indexHidden specifica fino a quale colonna dell'array String[] 
risultante dalla query tenere hidden

Il campo "campi" deve contenere una stringa del tipo:
	c1=X&c2=Y&..&cN=Z
	
con numCampi=N

Il campo "titoli" deve contenere una stringa del tipo:
	t1=X&t2=Y&..&tN=Z
	
con N=numCampi-indexHidden
*****/

function openLovColumns(tipo,numCampi,campi,indexHidden,titoli) {
  opzioni = 'width=400,height=400,toolbar=no,directories=no,menubar=no,scrollbars=no,resizable=no';
  win=window.open ("jsp/common/Lov.jsp?type="+tipo+"&numCampi="+numCampi+"&indexHidden="+indexHidden+"&"+campi+"&"+titoli,'WinLov',opzioni);
  win.focus();
}

/**
 * Permette di testare le coordinate inviate
 * generando dinamicamente la mappa.
 */
function genMap(coord) {
  opzioni = 'width=930,height=904,toolbar=no,directories=no,menubar=no,scrollbars=yes,resizable=yes';
  var pop = window.open("","testMap",opzioni);
  
  pop.document.open();
  pop.document.write("<html>\n<head><title>Test Coordinate</title></head>\n");
  pop.document.write("<body>\n<img src=\"images/CARTINASUCCURS.jpg\" width=\"930\" height=\"904\" border=\"1\" usemap=\"#Map\">\n");
  pop.document.write("<map name=\"Map\">\n<area shape=\"rect\" coords=\""+coord+"\" href=\"javascript:;\" onClick=\"alert('Test!')\" alt=\"Test\">\n</map>");
  pop.document.write("</body></html>");
  pop.document.close();
}

/**
 *
 */
function hilite(param) {
	theTab = param.parentNode;
	for(i=0;i<theTab.rows.length;i++){
		if(theTab.rows[i].id == param.id)
			theTab.rows[i].style.background = '#E7F3FF';
		else
			theTab.rows[i].style.background = 'white';
	}
}

/**
 *
 */
function offlite(param) {
	theRows = param.getElementsByTagName('TR');
	for(i=1;i<theRows.length;i++){
		theRows[i].style.background = 'white';
	}	
}

/**
 * Move elements between select.
 */
var NS4 = (navigator.appName == "Netscape" && parseInt(navigator.appVersion) < 5);
 
function addOption(theSel, theText, theValue) {
	var newOpt = new Option(theText, theValue);
	var selLength = theSel.length;
	theSel.options[selLength] = newOpt;
}

function deleteOption(theSel, theIndex) {	
	var selLength = theSel.length;
	if(selLength>0) {
		theSel.options[theIndex] = null;
	}
}

function moveOptions(theSelFrom, theSelTo) {
	var selLength = theSelFrom.length;
	var selectedText = new Array();
	var selectedValues = new Array();
	var selectedCount = 0;
	
	var i;
	
	// Find the selected Options in reverse order
	// and delete them from the 'from' Select.
	for(i=selLength-1; i>=0; i--) {
		if(theSelFrom.options[i].selected) {
			selectedText[selectedCount] = theSelFrom.options[i].text;
			selectedValues[selectedCount] = theSelFrom.options[i].value;
			deleteOption(theSelFrom, i);
			selectedCount++;
		}
	}
	
	// Add the selected text/values in reverse order.
	// This will add the Options to the 'to' Select
	// in the same order as they were in the 'from' Select.
	for(i=selectedCount-1; i>=0; i--) {
		addOption(theSelTo, selectedText[i], selectedValues[i]);
	}
	
	if(NS4) history.go(0);
}

function moveAll(theSelFrom, theSelTo) {
	var selLength = theSelFrom.length;
	var selectedText = new Array();
	var selectedValues = new Array();
	var selectedCount = 0;
	
	var i;

	for(i=selLength-1; i>=0; i--) {
		selectedText[selectedCount] = theSelFrom.options[i].text;
		selectedValues[selectedCount] = theSelFrom.options[i].value;
		deleteOption(theSelFrom, i);
		selectedCount++;
	}
					
	for(i=selectedCount-1; i>=0; i--) {
		addOption(theSelTo, selectedText[i], selectedValues[i]);
	}
	
	if(NS4) history.go(0);
}

// La funzione seleziona tutte le opzioni
// di una select multipla
function seleziona(theSel) {
  for (i=0; i<theSel.options.length; i++)
    theSel.options[i].selected=true;
}

// escape() encodes most of the stuff you need to encode. 
// It misses single and double quotes, so you should replace those manually
function URLencode(sStr) {
  return escape(sStr).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27');
}

// Copia Clipboard
function clipBoard(theElId){
  if (!document.all){
    alert("Funzionalità disponibile solo in IE");
    return; // IE only 
  } 
  var otext = document.getElementById(theElId);
  otext.focus();
  otext.select();
  var trange = otext.createTextRange();
  copyRange = trange.execCommand("Copy");
}

// Copia Clipboard per campo hidden
function clipBoardHid(theElId){
  if (!document.all){
    alert("Funzionalità disponibile solo in IE");
    return false; // IE only 
  } 
  var otext = document.getElementById(theElId);
  otext.select();
  var trange = otext.createTextRange();
  copyRange = trange.execCommand("Copy");
  return true;
}


/* 
function zeriDavanti(): metto gli zeri davanti alle stringhe 
                        per portarle alla lunghezza voluta 	  
  stringa è la stringa da modificare
  dimensione è quella alla quale la stringa deve arrivare
*/
function zeriDavanti(stringa,dimensione) {
  stringaOk=stringa;
  if(stringaOk.length!=dimensione) 
	for(i=stringaOk.length; i<dimensione; i++) 
	  stringaOk="0"+stringaOk;
  return stringaOk;
}