/*
----------------------------------------------------------------------------
    funzioni generiche
----------------------------------------------------------------------------
*/
function trimblanks( sx )
{
/*
  Elimina dalla stringa s tutti gli eventuali blanks in testa ed in coda
  ritornando la stringa risultante.
*/
	sx = sx.replace( /^ */, "" );
	sx = sx.replace( / *$/, "" );
	return sx;
}

function fCountObj(sx)
{ // conta il numero di elementi dell'array di oggetti INPUT
  var i = 0;
  var bFlag = true;
  while(bFlag)
  {
    i++;
	  var el = eval("document.forms[0]." + sx + i);
	  if (typeof(el) == "undefined")
      bFlag = false;
  }
  return i;
}

function fDictionary(sx)
{ // Associa al nome di oggetto in sx il relativo testo da restituire all'operatore
	switch(sx)
	{
  	case "cbCitta":
      return "città";
  	break;
  	case "txGiorno":
      return "giorno";
  	break;
  	case "txUser":
      return "User";
  	break;
  	case "txPasswd":
      return "password";
  	break;
	}
	return "undefined";
}

/*
----------------------------------------------------------------------------
    funzioni delle pagine di ricerca 1a_ricerca_semplice, 1b_ricerca_avanzata
----------------------------------------------------------------------------
*/
function fSetParam(bInit)
{ // Setta i campi nascosti per le varie tipologie di oggetti utilizzati per la ricerca
  // Ritorna il numero di elementi che compongono l'insieme richiesto
 
  if ( bInit )
  {
	  document.f0.hfTipoAccessori.value = '0';
	  document.f0.hfTipoServizi.value = '0';
	  document.f0.hfTipoSpecialita.value = '0';
	  document.f0.hfTipoCarte.value = '0';
	  document.f0.hfTipoAmbienti.value = '0';
	  document.f0.hfTicket.value = '0';
  }
  else
  {
	  document.f0.hfTipoAccessori.value = fCountObj('cktipoaccessori');
	  document.f0.hfTipoServizi.value = fCountObj('cktiposervizi');
	  document.f0.hfTipoSpecialita.value = fCountObj('cktipospecialita');
	  document.f0.hfTipoCarte.value = fCountObj('cktipocarte');
	  document.f0.hfTipoAmbienti.value = fCountObj('cktipoambienti');
	  document.f0.hfTicket.value = fCountObj('ckticket');
  }
}

function fCheckPage(act, sx)
{
  var elTmp = sx.split("|");
  var bCheck = true;
  if (parseInt(act) > 0)
  {
	  for(var i = 0; i < elTmp.length; i++)
	  {
	    if (bCheck)
	    {
	      var el = document.getElementById(elTmp[i]);
	      switch(el.type)
	      {
	        case "select-one":
	          bCheck = ((parseInt(el.selectedIndex) > 0)? true : false);
	        break;
	        case "text":
	          bCheck = ((trimblanks(el.value) == "")? false : true);
	        break;
	        case "check":
	          bCheck = ((el.checked)? true : false);
	        break;
	      }
	    }
	  }
	}
  if ( bCheck )
  {
   	document.forms[0].hfAction.value = act;
    document.forms[0].submit();
//    return true;
  }
  else
  {
    alert('il campo ' + fDictionary(el.name) + ' non è stato riempito correttamente');
    el.focus();
  //  return false;
  }
}

function fLogon(bLogin,sUrl)
{
  var bCheck;
  var sAction;
   //alert("dentro logon");
  if (bLogin)
  {
	  if (trimblanks(document.getElementById('txUser').value) == '' || trimblanks(document.getElementById('txPwd').value) == '' )
	  {
	    alert('Attenzione! Inserire nome utente e password');
	    bCheck = false;
	  }
	  else
    {
	    bCheck = true;
    	sAction = "10";
  	}
  }
  else
  {
  	bCheck = true;
  	sAction = "11";
  }
  if(bCheck)
  {
//	   alert("dentro if");
//  	document.getElementById('hfAction').value = sAction;
/*
  	document.forms[0].hfAction.value = sAction;
  	document.forms[0].action = '../Tavolata/logon.php';
  	document.forms[0].submit();
*/
	document.frmLogin.hfAction.value = sAction;
	//  alert("1");
  	document.frmLogin.action = sUrl;
	// alert("2");
  	document.frmLogin.submit();
  }
}

function fSondaggio()
{
 	//document.frmLogin.hfAction.value = sAction;
  	document.frmLogin.action = '../Tavolata/salva_sondaggio.php';
  	document.frmLogin.submit();
  
}



function cbTipologia_onChange(el)
{ // in base alla selezione del conenuto del campo cbTipologia, determina se attivare
	// o disattivare la combo relativa al tipo etnico
  var nClasse;
  nClasse = el[el.selectedIndex].getAttribute('_VAL1');
  if ( parseInt(nClasse) > 0 )
  {
    var el1 = document.getElementById('cbTipoEtnico');
    for (var i = 0; i < el1.length; i++)
    {
    	if (el1[i].getAttribute("_VAL1") == nClasse)
      	el1[i].disabled = true;
      else
      	el1[i].disabled = false;
    }
  	document.getElementById('cosa_etnico').style.visibility = "visible";
  }
  else
	{
    document.getElementById('cbTipoEtnico').selectedIndex = 0;
  	document.getElementById('cosa_etnico').style.visibility = "hidden";
	}
}

function fSetQuartieri(el)
{ // Seleziona ed attiva i quartieri in base al contenuto di el
	var sHTML;
	sHTML = 'quartiere<br/>';
	sHTML += '<select name="cbQuartiere" id="cbQuartiere">';
	sHTML += '<option value="0">-------------------------</option>';
  sHTML += '';
	sHTML += '</select>';

	return sHTML;
}

function fCheck_onBlur(el1, sEl2, sLbl)
{ // nella ricerca avanzata, quando il campo del piatto è pieno aggiorno
	// l'etichetta del campo COSTO per rendere evidente che la ricerca è sul piatto
	var el2 = document.getElementById(sEl2);
   
  switch (el1.type)
  {
  	case "text": // il secondo oggetto è la combo-box
	    if (el1.value != "" && parseInt(el2.value) > -1 )
	    {
	        document.getElementById(sLbl).innerHTML = 'riferito al piatto ricercato';
	    }
	    else
	    {
	        document.getElementById(sLbl).innerHTML = 'costo medio';
	    }
         break;
         case "select-one": // il secondo elemento è la text
	    if (el2.value != "" && parseInt(el1.value) > -1 )
	    {
               document.getElementById(sLbl).innerHTML = 'riferito al piatto ricercato';
	    }
	    else
	    {
	       document.getElementById("sLbl").innerHTML = 'costo medio';
	    }
	 break;

  }
}

function fCheckPiatto(el)
{ // gestisce la scelta del radio button per la scelta del piatto o del menù
//  el.checked = true;

  if (el.id == "optMenu")
  {
	
    document.getElementById('costopiattotext').style.visibility = "hidden";
    document.getElementById('costopiattoinput').style.visibility = "hidden";
    document.getElementById('cbCostoPiatto').selectedIndex = 0;
    document.getElementById('cbCostoPiatto').selectedIndex = 0;
    document.getElementById('lbCosto').innerHTML = "";
    document.getElementById('prezzofissotext').style.visibility = "visible";
    document.getElementById('prezzofissoinput').style.visibility = "visible";
    document.getElementById('nomepiattoinput').style.visibility = "hidden";
    document.getElementById('txPiatto').value = "";
  }
  else
  {
	
    document.getElementById('costopiattotext').style.visibility = "visible";
    document.getElementById('costopiattoinput').style.visibility = "visible";
    document.getElementById('prezzofissotext').style.visibility = "hidden";
    document.getElementById('prezzofissoinput').style.visibility = "hidden";
    document.getElementById('cbPrezzoFisso').selectedIndex = 0;
    document.getElementById('nomepiattoinput').style.visibility = "visible";
  }
	return true;
}
/*
----------------------------------------------------------------------------
    funzioni della pagina 1c0_risultati
----------------------------------------------------------------------------
*/
function fSetTotali()
{ // Reimposta i totali dei locali estratti
  var sx;
  var el;
  var sTpSearch = document.f0.hfTpSearch.value;
  var aTot = document.f0.hfTotali.value.split("|");
  //alert document.f0.hfTotali.value;

  sx = aTot[0] + ' locali ';
  if (parseInt(aTot[1]) > 0)
  {
  	sx += '<a id="numero_esatti" href="1c0_risultati.php?bFrom=1&np=1&nt=1">';

 /* 	if (sTpSearch == '1')
    {
        sx += 'di cui ' + aTot[1];
    	sx += ' offrono lo sconto ';
    }  */
  //	sx += ' rispondono esattamente ai criteri impostati';
  	sx += '</a>';
  }
  else
  {
  	sx += '<a id="numero_esatti">';

  /*	if (sTpSearch == '1')
    {
        sx += 'di cui ' + aTot[1];
    	sx += ' offrono lo sconto ';
 // 	sx += ' rispondono esattamente ai criteri impostati';
    }   */
  	sx += '</a>';
  }
  sx += '<div>&nbsp;</div>';
  /*if (parseInt(aTot[2]) > 0)
  {
	  sx += '<a id="numero_parziali" href="1c0_risultati.php?bFrom=1&np=1&nt=2">';
	  sx += 'e ' + aTot[2] + ' rispondono solo parzialmente ai criteri impostati';
	  sx += '</a>';
  }
  else
	{
	  sx += '<a id="numero_parziali">';
	  sx += 'e ' + aTot[2] + ' rispondono solo parzialmente ai criteri impostati';
	  sx += '</a>';
  }          */
  document.getElementById("numero_risultati").innerHTML = sx ;

}

function fSubmit(fDirect, nType)
{
  document.getElementById('hfType').value = nType;
  if (fDirect.toString() == '' )
  { // richiesta pagina senza numero
  	alert('inserire il numero di pagina desiderato');
  	return false;
  }
  if (fDirect < 1 || fDirect > parseInt(document.getElementById('hfTotPagine').value))
  {
  	alert('il numero di pagina richiesta non esiste');
  	return false;
  }
	if (isNaN(fDirect) && fDirect.toString() != 'UP' && fDirect.toString() != 'DOWN')
	{
		alert('il numero di pagina richiesta non esiste');
		return false;
	}
  switch (fDirect)
  {
  	case 'UP' : // Avanti
			document.getElementById('hfPagina').value = parseInt(document.getElementById('hfPagina').value) +1;
  	break;
	  case 'DOWN' : // Indietro
			document.getElementById('hfPagina').value = parseInt(document.getElementById('hfPagina').value) -1;
  	break;
	  default : // vai a pagina definita
			document.getElementById('hfPagina').value = fDirect;
  	break;
  }
	location.href="1c0_risultati.php?bFrom=1&np=" + document.getElementById('hfPagina').value + "&nt=" + nType;
}

function fChangeOrder(el)
{
	document.getElementById('hfOrder').value = el.value;
	document.f0.submit();
}

function fSetOrdine()
{
  var i;
  if (document.getElementById('hfType').value == "1")
  	i = 1;
  else if (document.getElementById('hfType').value == "2")
  	i = 2;
  else if (document.getElementById('hfType').value == "3")
  	i = 3;
	else
		i = 0;
//  if (parseInt(document.getElementById('hfTotali').value.split("|")[1]) > 0)
//  { // se i risultati totali sono a 0 non visualizzo subito i parziali ma un messaggio
	  if (i > 0 && (parseInt(document.getElementById('hfTotali').value.split("|")[i]) > 0))
	    document.getElementById('cbOrdine').selectedIndex = document.getElementById('hfOrder').value;
  }
// }
/*
----------------------------------------------------------------------------
    funzioni delle pagine di dettaglio dei locali
----------------------------------------------------------------------------
*/
function fInsVoti(id, nf)
{
  var url;
  url = '1e_valutazioni.php?id=' + id + '&nf=' + nf;
  window.open(url,'','resizable=no,scrollbars=no,width=500,height=300,top=100,left=100');
}
function fViewSconti(UserId, idLoc)
{
	if (UserId == 0)
	{
		alert('Per visualizzare la tabella degli sconti devi essere registrato alla "TAVOLATA"!');
	}
	else
   	window.open('1d_orari_e_sconti.php?id=' + idLoc,'','Width=500px, Height=250px,resizable=no,scrollbars=no,top=200,left=200');
}
/*
----------------------------------------------------------------------------
    funzioni delle pagine di dettaglio dei commenti
----------------------------------------------------------------------------
*/
function fSubmitPosts(fDirect, id)
{
//  document.getElementById('hfType').value = nType;
  if (fDirect.toString() == '' )
  { // richiesta pagina senza numero
  	alert('inserire il numero di pagina desiderato');
  	return false;
  }
  if (fDirect < 1 || fDirect > parseInt(document.getElementById('hfTotPagine').value))
  {
  	alert('il numero di pagina richiesta non esiste');
  	return false;
  }
	if (isNaN(fDirect) && fDirect.toString() != 'UP' && fDirect.toString() != 'DOWN')
	{
		alert('il numero di pagina richiesta non esiste');
		return false;
	}
  switch (fDirect)
  {
  	case 'UP' : // Avanti
			document.getElementById('hfPagina').value = parseInt(document.getElementById('hfPagina').value) +1;
  	break;
	  case 'DOWN' : // Indietro
			document.getElementById('hfPagina').value = parseInt(document.getElementById('hfPagina').value) -1;
  	break;
	  default : // vai a pagina definita
			document.getElementById('hfPagina').value = fDirect;
  	break;
  }
	location.href="1c4_avanzata_commenti.php?id="+id+"&np=" + document.getElementById('hfPagina').value ;
}

function fWriteFlash(sMsg)
{ // funzione per la scrittura dei messaggi scroll
	//nIndex è globale alla pagina
	var el = document.getElementById('txFlash');
	var s = el.size;
	var sx = unescape(sMsg);
	el.value = sx.substr(0,nIndex);
	nIndex++;
	if (nIndex == sx.length + 30)
		nIndex = 1;
}

/*
----------------------------------------------------------------------------
    funzioni delle pagine di registrazione dell'utente
----------------------------------------------------------------------------
*/

function fCheckDatiUser()
{
	if (document.getElementById('first_name').value == '')
  {
  	alert('inserire il nome');
    document.getElementById('first_name').focus();
    return false;
  }
	if (document.getElementById('last_name').value == '')
  {
  	alert('inserire il cognome');
    document.getElementById('last_name').focus();
    return false;
  }
	if (document.getElementById('email').value == '')
  {
  	alert('inserire indirizzo di posta elettronica ');
    document.getElementById('email').focus();
    return false;
  }
	if (document.getElementById('user_name').value == '')
  {
  	alert('inserire il "nik-name"');
    document.getElementById('user_name').focus();
    return false;
  }
	if (document.getElementById('password1').value == '')
  {
  	alert('inserire la password');
    document.getElementById('password1').focus();
    return false;
  }
	if (document.getElementById('password2').value == '')
  {
  	alert('inserire la conferma della password');
    document.getElementById('password2').focus();
    return false;
  }
	if (document.getElementById('cbCitta').value == '0')
  {
  	alert('inserire la città di residenza');
    document.getElementById('cbCitta').focus();
    return false;
  }
  if (document.getElementById('nascita_giorno').value == '' || document.getElementById('nascita_mese').value == '' || document.getElementById('nascita_anno').value == '')
  {
  	alert('inserire la data di nascita');
    document.getElementById('nascita_giorno').focus();
    return false;
  }
  if (!document.getElementById('ckRegolamento').checked )
  {
  	alert('per proseguire nella registrazione deve essere accettato il regolamento');
  	return false;
  }
  if (!document.getElementById('ckPrivacy').checked )
  {
  	alert('per proseguire nella registrazione deve essere accettata la clausola sulla privacy');
  	return false;
  }
  return true;
}





var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary(year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Il formato della data deve essere : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Inserire un mese valido")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Inserire un giorno valido")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Inserire un anno compreso tra  "+minYear+" e "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Per favore inserire una data corretta")
		return false
	}
return true
}


function isDateTp(dtStr,tpStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Il formato della data deve essere : mm/dd/yyyy in "+tpStr)
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Inserire un mese valido in "+tpStr)
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Inserire un giorno valido in "+tpStr)
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Inserire un anno compreso tra  "+minYear+" e "+maxYear+" in "+tpStr)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Per favore inserire una data corretta in "+tpStr)
		return false
	}
return true
}
function disable(id)
{
	//alert("dentro dissable");
	for (var i=1; i<6; i++)
	{
	   if(id!=i)
	      document.getElementById('radiobutton'+i).checked=false; 
	}
}

