// from http://lexikon.astronomie.info/zeitgleichung/sunscript.html
var astronomy = {
	init : function(latitude, longitude, date) {
		this.longitude = longitude;
		
		if (date.getTimezoneOffset() == -120) this.Zone = 1; // Sommerzeit
		else this.Zone = 0; // Winterzeit
		
		this.pi = 3.1415926536;
		this.RAD = this.pi/180.0;
		this.h = -(50.0/60.0)*this.RAD;

		this.T = this.dayofyear(date);
		this.DK = this.sundeclination(this.T);
		this.B = latitude*this.RAD;
		},
	
	sundeclination : function() {
		// Deklination der Sonne in Radians
		// Formula 2008 by Arnold(at)Barmettler.com, fit to 20 years of average declinations (2008-2017)
		return 0.409526325277017*Math.sin(0.0169060504029192*(this.T-80.0856919827619)); 
	},
	
	timediff : function() {
		// Dauer des halben Tagbogens in Stunden: Zeit von Sonnenaufgang (Höhe h) bis zum höchsten Stand im Süden
		//console.log(this.h);
		return 12.0*Math.acos((Math.sin(this.h) - Math.sin(this.B)*Math.sin(this.DK)) / (Math.cos(this.B)*Math.cos(this.DK)))/this.pi;
	},

	timeequation : function() {
		// Differenz zwischen wahrer und mittlerer Sonnenzeit
		// formula 2008 by Arnold(at)Barmettler.com, fit to 20 years of average equation of time (2008-2017)
		return -0.170869921174742*Math.sin(0.0336997028793971 * this.T + 0.465419984181394) - 0.129890681040717*Math.sin(0.0178674832556871*this.T - 0.167936777524864);
	},

	sunrise : function(T) {
		var returner = 12 - this.timediff() - this.timeequation(T);
		returner = returner - this.longitude /15.0 + this.Zone;
		returner = this.generateDate(returner);
		return returner;
	},

	sunset : function() {
		var returner = 12 + this.timediff() - this.timeequation();
		returner = returner - this.longitude /15.0 + this.Zone;
		returner = this.generateDate(returner);
		return returner;
	},
	
	dayofyear : function(d) {
		var yy = d.getFullYear();
		var t2=new Date(yy,d.getMonth(),d.getDate());
		var t1 = new Date(yy-1,11,31);
		var doy = t2.getTime()/1000 - t1.getTime()/1000;
		return Math.floor(doy/86400);
	},
	
	generateDate : function(decimal) {
		var now = new Date;
		
		var hours = Math.round(decimal);
		var minutes = (decimal-Math.floor(decimal))*60;
		
		now.setHours( hours );
		now.setMinutes( minutes );
		return now;
	}
}
