//JavaScript modification T. Dacre 1999
//based on a BASIC program MOON EFFECTS by Bradley E. Schaefer

//   This program helps anyone who needs to know the Moon's 
//   phase (age) on
//   any date within several thousand years in the past or future.
//   To illustrate its application, Bradley Schaefer applied it 
//   to a number of famous events influenced by the Moon in 
//   World War II.  His article appeared in Sky & Telescope for
//   April 1994, page 86.
 
function daysInMonth(iMonth, iYear)
{
	var count=32 - new Date(iYear, iMonth, 32).getDate();
	var i=0;
	var phase=new Array();
	var message="";
	var calString="";
	var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
   calString= '<table>';
  for(i=0;i<days.length;i++){
    calString += '<th class="dayHeader">' + days[i].substring(0,3) + '</th>';
  }
  //write the body of the calendar
  calString += '</tr>';
	/*for(i=1;i<=count;i++)
	{
		//alert(i);
		
	}
  */
  //alert(iMonth);
  //create 6 rows so that the calendar doesn't resize
 

 /* for(j=0;j<42;j++){
	  
   /* if(j<firstDay){      //write the leading empty cells
      calString += '<td class="empty">&nbsp;</td>';
    }else if(displayNum==j){
      calString += '<td id="' + iMonth +'selected" class="date">' + displayNum +  im + '</td>';
    }else if(displayNum > count){
      //Empty cells at bottom of calendar
      calString += '<td>&nbsp;</td>';
    }else{
      //the rest of the numbered cells
      calString += '<td id="" class="days">' + displayNum + im + '</td>';
    }
    if(j%7==6){
      calString += '</tr><tr>';
    }
  
  }
  //close the last number row
  calString += '</tr>';
  //write the nav row
   
  calString += '</table>';
document.getElementById('dmessages').innerHTML=calString;*/
	var day_one = new Date(iYear,iMonth,count);
	    day_one.setDate(1);			// set to first of this month
	var wday = day_one.getDay();
	var d=1-wday;
	var im="";
	var ms="";
 while ( d <= count )
    {
		
	//var displayNum=1-firstDay;
	
		calString = calString + '<tr>\n';       
    	    
		for ( i = 0; i < 7; i++ )
		{
			ms="";
			message=displayCalc(new Date(iYear,iMonth,d));
			if(message=="full" || message=="new")
			ms="<br />"+message;
			if(message=="first_quarter")
			ms="<br />1st Qtr";
			if(message=="last_quarter")
			ms="<br />3rd Qtr";
			im="<br /><img width=30px src='moonitems/moon_"+message+".png' name='moonimg'>"
			//im="<span style=background-image:moonitems/moon_"+message+".png'>"+ms+"</span>"

			//im=showMoon(new Date(iYear,iMonth,d));
			
	 // var firstDay=new Date(iYear,iMonth,j).getDay();
		/*if(message!=""){
		im="<br /><img width=30px src='moonitems/moon_"+message+".png' name='moonimg'>"
		}*/
			var class_def = ( d == new Date().getDate() && iMonth==new Date().getMonth()) ? 'id="' + iMonth +'selected" class="date"' : 'class="days"';
			if(d <= 0 || d > count )
			class_def='class="empty"';
			calString = calString + '<td ' + class_def + '  align="center">';
			if ( d > 0 && d <= count )
			{
				calString = calString +"<span class=headernew>"+ d+"</span>"+im+"<span class=orange>"+ms+"</span>";
				//calString = calString +"<span class=headernew>"+ d+"</span>"+im;
			}
			else {
				
				calString = calString + '&nbsp;';
			}
			calString = calString + '</td>\n';     
			d++;
		}
		calString = calString + '</tr>\n';
	}
	calString += '</table>';
document.getElementById('dmessages').innerHTML=calString;
}
function showMoon(date) {
var height=1
var size = 50
var i
var message="";
var currentDate  = date;
// Convert it to GMT
	currentDate.setTime(currentDate.getTime() + (currentDate.getTimezoneOffset()*60000))
// Get Date (GMT) for recent full moon
// NOTE: months, hours, and minutes are 0 based
var blueMoonDate = new Date(96, 1, 3, 16, 15, 0)
// Compute length of lunar period -- source: World Almanac
var lunarPeriod  = 29*(24*3600*1000) + 12*(3600*1000) + 44.05*(60*1000)
var moonPhaseTime = (currentDate.getTime() - blueMoonDate.getTime()) % lunarPeriod
// alert("Moon phase in days = "+moonPhaseTime/(24*3600*1000))
// Compute various percentages of lunar cycle
var percentRaw = (moonPhaseTime / lunarPeriod)
	// alert("% = "+percentRaw)
var percent    = Math.round(100*percentRaw) / 100
	// alert("% = "+percent)
var percentBy2 = Math.round(200*percentRaw)
var left  = (percentRaw >= 0.5) ? "moonitems/black.gif" : "moonitems/white.gif"
var right = (percentRaw >= 0.5) ? "moonitems/white.gif" : "moonitems/black.gif"
//document.write("<center>")
	if (percentBy2 > 100) {
		percentBy2 = percentBy2 - 100
		}
	for (i = -(size-1); i < size; ++i) {
		var wid=2*parseFloat(Math.sqrt((size*size)-(i*i)));
		if (percentBy2 != 100)
			//document.write ("<img src="+left +" height=1 width="+(wid*((100-percentBy2)/100))+">")
			message="<img src="+left +" height=1 width="+(wid*((100-percentBy2)/100))+">";
		if (percentBy2 != 0)
			//document.write ("<img src="+right+" height=1 width="+(wid*((percentBy2)/100))+">")
			message="<img src="+right+" height=1 width="+(wid*((percentBy2)/100))+">";
		//document.write ("<br>")
	} // for
/*document.write(	"</center>",
              "<BR>",
 				"<font size=4 face=Arial>",
 				"Next full moon in about ",
 				Math.round((lunarPeriod-moonPhaseTime)/(24*3600*1000)),
				" day",
				Math.round((lunarPeriod-moonPhaseTime)/(24*3600*1000)) != 1 ? "s" : "",
				"")*/
return message;
}
function displayCalc(date)
{
	today = date;  
	var message="";
	var phaseArray="";
var c// initialize to current date
hh = today.getHours();          // goes from 0 to 23
var ampm = "am"
        var NoLoops = hh        // this variable is also used for the cuckoo clock
                if(hh == 0) { NoLoops = 12};
                if(hh > 12) { NoLoops = hh - 12; ampm = "pm" }
                if(hh == 12) { ampm = "pm" }
var dd = today.getDate();
var mm = today.getMonth() + 1;  // Jan is 0, Feb is 1, etc., hence the +1
var dow = today.getDay();
MonNames = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
var ThisMonth = MonNames[mm];

// var yy = today.getYear();
// browser Y2K bug fix -- convert from msec to years because getYear() doesn't work right
    var millisec = today.getTime();            // this gives msecs
    var yy = ((((millisec / 1000) / 3600) / 24) / 365.25);
    yy = Math.floor(yy);
    yy +=1970;

var txtDate = "" + ((dd < 10) ? "0" : "") + dd;   // add 0 if less than 10 so displays right
txtDate += "&nbsp;" + ThisMonth;
txtDate += "&nbsp;" + yy;
var mn = today.getMinutes();        // goes from 0 to 59
var txtTime = "" + ((NoLoops < 10) ? "0" : "") + NoLoops;
txtTime += ((mn<10) ? ":0" : ":") + mn;

// here's where the calculations from the book start
var moondate = today;
tzone = moondate.getTimezoneOffset() / 60               // in min so convert to hours
var moonmsec = moondate.getTime();                      // this gives msecs
GMtime = moonmsec + (tzone * 60 * 60 * 1000)            // GMT in msec
// adapted from my VB code
var startDate = new Date(89, 11, 31, 00, 00, 00);       // equivalent of the book's 0 Jan 90
var startMsec = startDate.getTime();
var dmsec = GMtime - startMsec;
D = ((((dmsec /1000) /60) /60) /24);
var n = D * (360 / 365.242191);                         //no 46-3
if (n > 0) {
        n = n - Math.floor(Math.abs(n / 360)) * 360;    //no 46-3
} else {
        n = n + (360 + Math.floor(Math.abs(n / 360)) * 360);  //no 46-3
}
var Mo = n + 279.403303 - 282.768422;                   //no 46-4;
if(Mo < 0) { Mo = Mo + 360 }                         //no 46-4
var Ec = 360 * .016713 * Math.sin(Mo * 3.141592654 / 180) / 3.141592654;        //no 46-5
var lamda = n + Ec + 279.403303;                        //no 46-6
if(lamda > 360) { lamda = lamda - 360 }              //no 46-6
var l = 13.1763966 * D + 318.351648;                    //no 65-4
if (l > 0) {
        l = l - Math.floor(Math.abs(l / 360)) * 360;    //no 65-4
} else {
        l = l + (360 + Math.floor(Math.abs(l / 360)) * 360);  //no 65-4
}
var Mm = l - .1114041 * D - 36.34041;                   //no 65-5
if (Mm > 0) {
        Mm = Mm - Math.floor(Math.abs(Mm / 360)) * 360; //no 65-5
} else {
        Mm = Mm + (360 + Math.floor(Math.abs(Mm / 360)) * 360); //no 65-5
}
var N65 = 318.510107 - .0529539 * D;                    //no 65-6
if (N65 > 0) {
        N65 = N65 - Math.floor(Math.abs(N65 / 360)) * 360;      //no 65-6
} else {
        N65 = N65 + (360 + Math.floor(Math.abs(N65 / 360)) * 360);      //no 65-6
}
var Ev = 1.2739 * Math.sin((2 * (l - lamda) - Mm) * 3.141592654 / 180); //no 65-7
var Ae = .1858 * Math.sin(Mo * 3.141592654 / 180);      //no 65-8
var A3 = .37 * Math.sin(Mo * 3.141592654 / 180);        //no 65-8
var Mmp = Mm + Ev - Ae - A3;                            //no 65-9
var Ec = 6.2886 * Math.sin(Mmp * 3.141592654 / 180);    //no 65-10
var A4 = .214 * Math.sin((2 * Mmp) * 3.141592654 / 180);        //no 65-11
var lp = l + Ev + Ec - Ae + A4;                         //no 65-12
var V = .6583 * Math.sin((2 * (lp - lamda)) * 3.141592654 / 180);       //no 65-13
var lpp = lp + V;                                       //no 65-14
var D67 = lpp - lamda;                                  //no 67-2
Ff = .5 * (1 - Math.cos(D67 * 3.141592654 / 180));      //no 67-3
Xx = (Math.sin(D67 * 3.141592654 / 180));
//alert (Ff);
// figure out what phase the moon is in and what icon to use to go with it
var MoonPhaseMsg = "Just for fun, the moon is ";
if(Ff < .02) {
       message="<br /> <b>New Moon</b>, "+date;
	   phaseArray="new";
}
if((Ff > .45) && (Ff < .55) && (Xx > 0)) {
		message="<br /> <b>First Quarter</b>, "+date;
		 phaseArray="first_quarter";
}
if((Ff > .45) && (Ff < .55) && (Xx < 0)) {
       message="<br /> <b>Last Quarter</b>, "+date;
	    phaseArray="last_quarter";
}                
if(Ff > .98) {
            message="<br /> <b>Full Moon</b>, "+date;
			 phaseArray="full";

}
if((Ff > .02) && (Ff < .45) && (Xx > 0)) {
      			 phaseArray="waxing_crescent";

}
if((Ff > .02) && (Ff < .45) && (Xx < 0)) {
          phaseArray="waning_crescent";

}
if((Ff > .55) && (Ff < .98) && (Xx > 0)) {
		 phaseArray="waxing_gibbous";
}
if((Ff > .55) && (Ff < .98) && (Xx < 0)) {
     
		 phaseArray="waning_gibbous";
}
if(message!="")
{
//document.getElementById('messages').innerHTML=document.getElementById('messages').innerHTML+message;
}
return phaseArray;
}
function calendar(id,d,p){
  this.id = id;
  this.dateObject = d;
  this.pix = p;
  this.write = writeCalendar;
  this.length = getLength;
  this.month = d.getMonth();
  this.date = d.getDate();
  this.day = d.getDay();
  this.year = d.getFullYear();
  this.getFormattedDate = getFormattedDate;
  //get the first day of the month's day
  d.setDate(1);
  this.firstDay = d.getDay();
  //then reset the date object to the correct date
  d.setDate(this.date);
}


function getFormattedDate(){
  return days[this.day] + ', ' + months[this.month] + ' ' + this.date + ', ' + this.year;
  //return this.month + '/' + this.date + '/' + this.year;
}

function writeCalendar(){
 
  
  for(i=0;i<days.length;i++){
    calString += '<th class="dayHeader">' + days[i].substring(0,3) + '</th>';
  }
  
  //write the body of the calendar
  calString += '</tr><tr>';
  //create 6 rows so that the calendar doesn't resize
  for(j=0;j<42;j++){
	  var im="";
    var displayNum = (j-this.firstDay+1);	
	if(phaseArray['new']==displayNum)
	{
		im="<img src='moonitems/moon_new.jpg' name='moonimg'>"
	}
    if(j<this.firstDay){
      //write the leading empty cells
      calString += '<td class="empty">&nbsp;</td>';
    }else if(displayNum==this.date){
      calString += '<td id="' + this.id +'selected" class="date">' + displayNum +  im + '</td>';
    }else if(displayNum > this.length()){
      //Empty cells at bottom of calendar
      calString += '<td>&nbsp;</td>';
    }else{
      //the rest of the numbered cells
      calString += '<td id="" class="days">' + displayNum + im + '</td>';
    }
    if(j%7==6){
      calString += '</tr><tr>';
    }
  }
  //close the last number row
  calString += '</tr>';
  //write the nav row
   
  calString += '</table>';
  return calString;
}

function doCalc(){
var i,month,year;
for (i=0;i<document.form1.a.options.length;i++){if (document.form1.a.options[i].selected){month=document.form1.a.options[i].value}};
for (i=0;i<document.form1.b.options.length;i++){if (document.form1.b.options[i].selected){year=document.form1.b.options[i].value}};
document.getElementById('dmessages').innerHTML="";
daysInMonth(month,year);
}

