/* script per il calcolo del sorgere e del tramontare del sole dati lat (latitudine) e long (longitudine).  

   Al momento i dati si riferiscono a Venezia-Tessera. L'errore stimato è di circa 2 min. */


/* calcolo anno bisestile: 0 se anno normale, 1, se bisestile */

function bisestile(a){

   if ((a % 4 == 0) && (a % 100 != 0) || (a % 400 == 0))
   return 1;
   else
   return 0;
}

/* ritorna i giorni che mancano (numero negativo) all'equinozio di primavera o che sono trascorsi (numero positivo) */

function dif_equinozio(g,m,a){
   
   var equinozio = Date.UTC(a,3,21);
   var data      = Date.UTC(a,m,g);

   return (data-equinozio)/86400000;
 
}

/* ritorna i giorni che mancano (numero negativo) o che sono trascorsi (numero positivo) dal perielio */

function dif_perielio(g,m,a){

   var perielio = Date.UTC(a,1,2);
   var data     = Date.UTC(a,m,g);

   return (data-perielio)/86400000;

}

function converti(num){

   var ore = parseInt(num * 1440 / 60);
   var min = parseInt(((num * 1440 / 60) - ore)*60);

   if (min<10)
     return (ore+":0"+min);
   else
     return (ore+":"+min);
}

function arrotonda(val,num_dec){

   var m = Math.pow(10,num_dec);
   var n = m * val;
   var n2= Math.round(m*val); 
   
   return (n2/m);      
}

function alba_tramonto(param,g,m,a){
 
   var      lat = 45.5;
   var     long = 12.33;
   var teta_rad = arrotonda(dif_equinozio(g,m,a)*6.28/(365+bisestile(a)),2);
   var    v_rad = arrotonda(dif_perielio(g,m,a)*6.28/(365+bisestile(a)),2);
   var      ant = arrotonda(10 * Math.sin(2*teta_rad),1);
   var  rit_ell = arrotonda(7.8* Math.sin(v_rad),1);
   var  rit_tot = Math.round(rit_ell - ant);
   var   mezzog = 0.5 + (long+rit_tot)/1440;
   var declinaz = arrotonda(Math.asin(Math.sin(teta_rad)*0.4),2);
   var     di_2 = arrotonda(Math.acos(- Math.tan(declinaz)*Math.tan(lat*3.14/180))/6.28,2);

   if (param=="alba")
     return converti(mezzog-di_2);
   else
     return converti(mezzog+di_2);
}
