//----global vars --------
var rootPanel;
var superRootPanel;
var current;
var calendar;
var preferencePanel;
var indexOfSelected;
var resultsButton;
var segmentedButton;
var infoPopup;
var calendarButton;

var settings = {
	units: 'miles',
	Lat:43.26361111111111,
	Lon: -86.02361111111111
}
var settingsOJ;
var store;
var dUnitsSelc;
var prefForm;

var dateBox;
var	LonField;
var	LatField;

var yearPicker;
var yearPrePicker;
var ABTable;

var moonBox;
var infoPopupTxt;
var calc = {
    year: 2000,
    month: 10,
    day: 12
}
var moonRise;
var moonSet;
var year;
var month; 

var zodiac;
var phase;
var percent;

var todayDate = new Date();
var Lat = 43.26361111111111;
var Lon = -86.02361111111111;


//--------- funtion to update the info------------------------           
var update = function() {
    setToday();
    calculate();
    setMoon();
    setGrowIndicator();
    calcMoonSet();
    nextFull();
};
  
//--------- funtion to fill load Prefs------------------------           
var getPrefs = function() {
    if(typeof(Storage)!=="undefined")
	  {
	  	 if(localStorage.units)
			{
				settings.units = localStorage.units;
			}
		if(localStorage.Lat)
			{
				settings.Lat = localStorage.Lat;
				settings.Lon = localStorage.Lon;
				Lat = localStorage.Lat;
				Lon = localStorage.Lon;
			}
	  }
	else
	  {
	  // Sorry! No web storage support..
	  }
};

//--------- setToday funtion------------------------           
var setToday = function() {
    var year = (todayDate.getFullYear());
    var month = (todayDate.getMonth());
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    month = months[month];
    
    var weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";
    
    var day = (todayDate.getDay());
    day = weekday[day];
    
    var date = (todayDate.getDate());
    
    var theDate = day + " " + month + " " + date + ", " + year;
	
	document.getElementById('date').innerHTML = theDate;
    
};          

//--------- funtion calculate------------------------           
var calculate = function(day1, month1, year1) {
    var n0 = parseInt("0");
    var f0 = parseFloat("0.0");
    var AG = f0; // Moon's age
    var DI = f0; // Moon's distance in earth radii
    var LA = f0; // Moon's ecliptic latitude
    var LO = f0; // Moon's ecliptic longitude
    var Phase = " ";
    var Zodiac = " ";
    
    
    var d = this.todayDate;
    
	
	if(day1 && month1 && year1){
		calc.year = year1;
	    calc.month = month1;
	    calc.day = day1;
	}
	else{
		calc.year = d.getFullYear();
    	calc.month = d.getMonth() + 1;
    	calc.day = d.getDate();
	}
    
    
    var year = parseInt(calc.year, 10);
    var month = parseInt(calc.month, 10);
    var day = parseInt(calc.day, 10);
    
    moon_posit(year, month, day);
    
    calc.age = round2(AG);
    calc.dst = round2(DI);
    calc.faz = Phase;
    calc.lat = round2(LA);
    calc.lon = round2(LO);
    calc.sgn = Zodiac;
    
    var n28 = parseInt("28");
    var n30 = parseInt("30");
    var n31 = parseInt("31");
    var dim = new Array(n31, n28, n31, n30, n31, n30, n31, n31, n30, n31, n30, n31);
    
    function isdayofmonth(y, m, d){
        if (m != 2) {
            if (1 <= d && d <= dim[m - 1]) 
                return true;
            else 
                return false;
        }
        
        var feb = dim[1];
        
        if (isleapyear(y)) 
            feb += 1; // is leap year
        if (1 <= d && d <= feb) 
            return true;
        
        return false;
    }
    
    function isleapyear(y){
        var x = Math.floor(y - 4 * Math.floor(y / 4));
        var w = Math.floor(y - 100 * Math.floor(y / 100));
        var z = Math.floor(y - 400 * Math.floor(y / 400));
        
        if (x == 0) // possible leap year
        {
            if (w == 0 && z != 0) 
                return false; // not leap year
            else 
                return true; // is leap year
        }
        
        return false;
    }
    
    
    // compute moon position and phase
    function moon_posit(Y, M, D){
        var YY = n0;
        var MM = n0;
        var K1 = n0;
        var K2 = n0;
        var K3 = n0;
        var JD = n0;
        var IP = f0;
        var DP = f0;
        var NP = f0;
        var RP = f0;
        
        // calculate the Julian date at 12h UT
        YY = Y - Math.floor((12 - M) / 10);
        MM = M + 9;
        if (MM >= 12) 
            MM = MM - 12;
        
        K1 = Math.floor(365.25 * (YY + 4712));
        K2 = Math.floor(30.6 * MM + 0.5);
        K3 = Math.floor(Math.floor((YY / 100) + 49) * 0.75) - 38;
        
        JD = K1 + K2 + D + 59; // for dates in Julian calendar
        if (JD > 2299160) 
            JD = JD - K3; // for Gregorian calendar
        // calculate moon's age in days
        IP = normalize((JD - 2451550.1) / 29.530588853);
        AG = IP * 29.53;
        
        if (AG < 1.84566) 
            Phase = "New Moon";
        else 
            if (AG < 5.53699) 
                Phase = "Evening crescent";
            else 
                if (AG < 9.22831) 
                    Phase = "First quarter";
                else 
                    if (AG < 12.91963) 
                        Phase = "Waxing gibbous";
                    else 
                        if (AG < 16.61096) 
                            Phase = "Full Moon";
                        else 
                            if (AG < 20.30228) 
                                Phase = "Waning gibbous";
                            else 
                                if (AG < 23.99361) 
                                    Phase = "Last quarter";
                                else 
                                    if (AG < 27.68493) 
                                        Phase = "Morning crescent";
                                    else 
                                        Phase = "New Moon";
        
        IP = IP * 2 * Math.PI; // Convert phase to radians
        // calculate moon's distance
        DP = 2 * Math.PI * normalize((JD - 2451562.2) / 27.55454988);
        DI = 60.4 - 3.3 * Math.cos(DP) - 0.6 * Math.cos(2 * IP - DP) - 0.5 * Math.cos(2 * IP);
        
        // calculate moon's ecliptic latitude
        NP = 2 * Math.PI * normalize((JD - 2451565.2) / 27.212220817);
        LA = 5.1 * Math.sin(NP);
        
        // calculate moon's ecliptic longitude
        RP = normalize((JD - 2451555.8) / 27.321582241);
        LO = 360 * RP + 6.3 * Math.sin(DP) + 1.3 * Math.sin(2 * IP - DP) + 0.7 * Math.sin(2 * IP);
        
        if (LO < 33.18) 
            Zodiac = "Pisces";
        else 
            if (LO < 51.16) 
                Zodiac = "Aries";
            else 
                if (LO < 93.44) 
                    Zodiac = "Taurus";
                else 
                    if (LO < 119.48) 
                        Zodiac = "Gemini";
                    else 
                        if (LO < 135.30) 
                            Zodiac = "Cancer";
                        else 
                            if (LO < 173.34) 
                                Zodiac = "Leo";
                            else 
                                if (LO < 224.17) 
                                    Zodiac = "Virgo";
                                else 
                                    if (LO < 242.57) 
                                        Zodiac = "Libra";
                                    else 
                                        if (LO < 271.26) 
                                            Zodiac = "Scorpio";
                                        else 
                                            if (LO < 302.49) 
                                                Zodiac = "Sagittarius";
                                            else 
                                                if (LO < 311.72) 
                                                    Zodiac = "Capricorn";
                                                else 
                                                    if (LO < 348.58) 
                                                        Zodiac = "Aquarius";
                                                    else 
                                                        Zodiac = "Pisces";
        
        // so longitude is not greater than 360!
        if (LO > 360) 
            LO = LO - 360;
    }
    
    // round to 2 decimal places    
    function round2(x){
        return (Math.round(100 * x) / 100.0);
    }
    
    // normalize values to range 0...1    
    function normalize(v){
        v = v - Math.floor(v);
        if (v < 0) 
            v = v + 1;
        
        return v;
    }
    
    zodiac = Zodiac;
    phase = Phase;
    
    //this.percent = (this.calc.age * 100)/29.530588853;
    //this.calc.age = 
    //this.calc.dst =
    // this.calc.faz = 
    //this.calc.lat =;
    // this.calc.lon ;
    // this.calc.sgn 
    
    percent = (.5 + (.5 * Math.cos((2 * (Math.PI) / 29.530588853) * (this.calc.age + 14.7652944265)))) * 100;
    
    
    var percentFull = this.phase + " " + this.percent.toFixed(1) + "% Full";
	document.getElementById('percentFull').innerHTML = percentFull;

};

//--------- funtion setMoon------------------------           
var setMoon = function() {
    var phasePic;
    //this will set the phase picture 25 of them to cover 29.5 days...
    if (calc.age <= 1.8) {
        phasePic = "00moon_phases.png";
    }
    if (calc.age <= 2.9) {
        phasePic = "01moon_phases.png";
    }
    else 
        if (calc.age <= 4) {
            phasePic = "02moon_phases.png";
        }
        else 
            if (calc.age <= 5) {
                phasePic = "03moon_phases.png";
            }
            else 
                if (calc.age <= 6) {
                    phasePic = "04moon_phases.png";
                }
                else 
                    if (calc.age <= 7) {
                        phasePic = "05moon_phases.png";
                    }
                    
                    else 
                        if (calc.age <= 8) {
                            phasePic = "06moon_phases.png";
                        }
                        else 
                            if (calc.age <= 9) {
                                phasePic = "07moon_phases.png";
                            }
                            else 
                                if (calc.age <= 10) {
                                    phasePic = "08moon_phases.png";
                                }
                                else 
                                    if (calc.age <= 11) {
                                        phasePic = "09moon_phases.png";
                                    }
                                    else 
                                        if (calc.age <= 12) {
                                            phasePic = "10moon_phases.png";
                                        }
                                        else 
                                            if (calc.age <= 13) {
                                                phasePic = "11moon_phases.png";
                                            }
                                            else 
                                                if (calc.age <= 14) {
                                                    phasePic = "12moon_phases.png";
                                                }
                                                else 
                                                    if (calc.age <= 15.5) { //fullest
                                                        phasePic = "13moon_phases.png";
                                                    }
                                                    else 
                                                        if (calc.age <= 16.6) {
                                                            phasePic = "14moon_phases.png";
                                                        }
                                                        else 
                                                            if (calc.age <= 17.3) {
                                                                phasePic = "15moon_phases.png";
                                                            }
                                                            else 
                                                                if (calc.age <= 18.6) {
                                                                    phasePic = "16moon_phases.png";
                                                                }
                                                                else 
                                                                    if (calc.age <= 19.9) {
                                                                        phasePic = "17moon_phases.png";
                                                                    }
                                                                    else 
                                                                        if (calc.age <= 21.2) {
                                                                            phasePic = "18moon_phases.png";
                                                                        }
                                                                        else 
                                                                            if (calc.age <= 22.5) {
                                                                                phasePic = "19moon_phases.png";
                                                                            }
                                                                            else 
                                                                                if (calc.age <= 23.8) {
                                                                                    phasePic = "20moon_phases.png";
                                                                                }
                                                                                else 
                                                                                    if (calc.age <= 25.1) {
                                                                                        phasePic = "21moon_phases.png";
                                                                                    }
                                                                                    else 
                                                                                        if (calc.age <= 26.4) {
                                                                                            phasePic = "22moon_phases.png";
                                                                                        }
                                                                                        else 
                                                                                            if (calc.age <= 27.7) {
                                                                                                phasePic = "23moon_phases.png";
                                                                                            }
                                                                                            
                                                                                            else {
                                                                                                phasePic = "24moon_phases.png";
                                                                                            }

  	var picPath = 'url(./images/' + phasePic + ') center center';
	document.getElementById("moon").style.background=picPath; 

    
};

//--------- funtion setGrowIndicator------------------------           
var setGrowIndicator = function() {
    if (calc.age < 15) {
		var picPath = 'url(./images/bottomGrowing1.png) center center';
		document.getElementById("growing").style.background=picPath; 
    }
    else {
		var picPath = 'url(./images/bottomShrinking1.png) center center';
		document.getElementById("growing").style.background=picPath;
    }
};

//--------- funtion calcMoonSet------------------------           
var calcMoonSet = function() {
   	var PI = Math.PI;
    var DR = PI / 180;
    var K1 = 15 * DR * 1.0027379
    
    var Moonrise = false;
    var Moonset = false;
    
    var Rise_time = [0, 0];
    var Set_time = [0, 0];
    var Rise_az = 0.0;
    var Set_az = 0.0;
    
    var Sky = [0.0, 0.0, 0.0];
    var RAn = [0.0, 0.0, 0.0];
    var Dec = [0.0, 0.0, 0.0];
    var VHz = [0.0, 0.0, 0.0];
    
    var Now = todayDate;
    var calc = [];
    var lat = Lat;
    var lon = Lon;
    
    
    showdate(Now);
    compute();
    
    
    
    moonRise = calc.moonrise;
    moonSet = calc.moonset;
    
    
    
    
    // display the date
    function showdate(d){
        var winter = new Date(2001, 11, 30); // for northern hemisphere
        var summer = new Date(2001, 5, 30);
        
        var summer_tz = summer.getTimezoneOffset();
        var winter_tz = winter.getTimezoneOffset();
        var Local_dst = (summer_tz == winter_tz) ? false : true;
        
        if (summer_tz > winter_tz) // in southern hemisphere
        {
            var tz = summer_tz; // swap
            summer_tz = winter_tz;
            winter_tz = tz;
        }
        
        calc.month = d.getMonth() + 1;
        calc.day = d.getDate();
        calc.year = d.getFullYear();
    }
    
    
    
    // compute ...
    function compute(){
    
        var year = parseInt(calc.year, 10);
        var month = parseInt(calc.month, 10) - 1;
        var day = parseInt(calc.day, 10);
        
        Now = new Date(year, month, day, 0, 0, 0);
        
        calc.moonrise = "";
        calc.moonset = "";
        riseset(lat, lon);
        
    }
    
    
    
    // calculate moonrise and moonset times
    function riseset(lat, lon){
        var i, j, k;
        var zone = Math.round(Now.getTimezoneOffset() / 60);
        var jd = julian_day() - 2451545; // Julian day relative to Jan 1.5, 2000
        var mp = new Array(3); // create a 3x3 array
        for (i = 0; i < 3; i++) {
            mp[i] = new Array(3);
            for (j = 0; j < 3; j++) 
                mp[i][j] = 0.0;
        }
        
        lon = lon / 360;
        var tz = zone / 24;
        var t0 = lst(lon, jd, tz); // local sidereal time
        jd = jd + tz; // get moon position at start of day
        for (k = 0; k < 3; k++) {
            moon(jd);
            mp[k][0] = Sky[0];
            mp[k][1] = Sky[1];
            mp[k][2] = Sky[2];
            jd = jd + 0.5;
        }
        
        if (mp[1][0] <= mp[0][0]) 
            mp[1][0] = mp[1][0] + 2 * PI;
        
        if (mp[2][0] <= mp[1][0]) 
            mp[2][0] = mp[2][0] + 2 * PI;
        
        RAn[0] = mp[0][0];
        Dec[0] = mp[0][1];
        
        Moonrise = false; // initialize
        Moonset = false;
        
        for (k = 0; k < 24; k++) // check each hour of this day
        {
            ph = (k + 1) / 24;
            
            RAn[2] = interpolate(mp[0][0], mp[1][0], mp[2][0], ph);
            Dec[2] = interpolate(mp[0][1], mp[1][1], mp[2][1], ph);
            
            VHz[2] = test_moon(k, zone, t0, lat, mp[1][2]);
            
            RAn[0] = RAn[2]; // advance to next hour
            Dec[0] = Dec[2];
            VHz[0] = VHz[2];
        }
        
        // display results
        calc.moonrise = zintstr(Rise_time[0], 2) + ":" + zintstr(Rise_time[1], 2) +
        ", az = " +
        frealstr(Rise_az, 5, 1) +
        "&deg;";
        calc.moonset = zintstr(Set_time[0], 2) + ":" + zintstr(Set_time[1], 2) +
        ", az = " +
        frealstr(Set_az, 5, 1) +
        "&deg;";
        special_message();
    }
    
    // Local Sidereal Time for zone
    function lst(lon, jd, z){
        var s = 24110.5 + 8640184.812999999 * jd / 36525 + 86636.6 * z + 86400 * lon;
        s = s / 86400;
        s = s - Math.floor(s);
        return s * 360 * DR;
    }
    
    // 3-point interpolation
    function interpolate(f0, f1, f2, p){
        var a = f1 - f0;
        var b = f2 - f1 - a;
        var f = f0 + p * (2 * a + b * (2 * p - 1));
        
        return f;
    }
    
    // test an hour for an event
    function test_moon(k, zone, t0, lat, plx){
        var ha = [0.0, 0.0, 0.0];
        var a, b, c, d, e, s, z;
        var hr, min, time;
        var az, hz, nz, dz;
        
        if (RAn[2] < RAn[0]) 
            RAn[2] = RAn[2] + 2 * PI;
        
        ha[0] = t0 - RAn[0] + k * K1;
        ha[2] = t0 - RAn[2] + k * K1 + K1;
        
        ha[1] = (ha[2] + ha[0]) / 2; // hour angle at half hour
        Dec[1] = (Dec[2] + Dec[0]) / 2; // declination at half hour
        s = Math.sin(DR * lat);
        c = Math.cos(DR * lat);
        
        // refraction + sun semidiameter at horizon + parallax correction
        z = Math.cos(DR * (90.567 - 41.685 / plx));
        
        if (k <= 0) // first call of function
            VHz[0] = s * Math.sin(Dec[0]) + c * Math.cos(Dec[0]) * Math.cos(ha[0]) - z;
        
        VHz[2] = s * Math.sin(Dec[2]) + c * Math.cos(Dec[2]) * Math.cos(ha[2]) - z;
        
        if (sgn(VHz[0]) == sgn(VHz[2])) 
            return VHz[2]; // no event this hour
        VHz[1] = s * Math.sin(Dec[1]) + c * Math.cos(Dec[1]) * Math.cos(ha[1]) - z;
        
        a = 2 * VHz[2] - 4 * VHz[1] + 2 * VHz[0];
        b = 4 * VHz[1] - 3 * VHz[0] - VHz[2];
        d = b * b - 4 * a * VHz[0];
        
        if (d < 0) 
            return VHz[2]; // no event this hour
        d = Math.sqrt(d);
        e = (-b + d) / (2 * a);
        
        if ((e > 1) || (e < 0)) 
            e = (-b - d) / (2 * a);
        
        time = k + e + 1 / 120; // time of an event + round up
        hr = Math.floor(time);
        min = Math.floor((time - hr) * 60);
        
        hz = ha[0] + e * (ha[2] - ha[0]); // azimuth of the moon at the event
        nz = -Math.cos(Dec[1]) * Math.sin(hz);
        dz = c * Math.sin(Dec[1]) - s * Math.cos(Dec[1]) * Math.cos(hz);
        az = Math.atan2(nz, dz) / DR;
        if (az < 0) 
            az = az + 360;
        
        if ((VHz[0] < 0) && (VHz[2] > 0)) {
            Rise_time[0] = hr;
            Rise_time[1] = min;
            Rise_az = az;
            Moonrise = true;
        }
        
        if ((VHz[0] > 0) && (VHz[2] < 0)) {
            Set_time[0] = hr;
            Set_time[1] = min;
            Set_az = az;
            Moonset = true;
        }
        
        return VHz[2];
    }
    
    // test an hour for an event
    function test_sun(k, zone, t0, lat){
        var ha = new Array(3);
        var a, b, c, d, e, s, z;
        var hr, min, time;
        var az, dz, hz, nz;
        
        ha[0] = t0 - RAn[0] + k * K1;
        ha[2] = t0 - RAn[2] + k * K1 + K1;
        
        ha[1] = (ha[2] + ha[0]) / 2; // hour angle at half hour
        Dec[1] = (Dec[2] + Dec[0]) / 2; // declination at half hour
        s = Math.sin(lat * DR);
        c = Math.cos(lat * DR);
        z = Math.cos(90.833 * DR); // refraction + sun semidiameter at horizon
        if (k <= 0) 
            VHz[0] = s * Math.sin(Dec[0]) + c * Math.cos(Dec[0]) * Math.cos(ha[0]) - z;
        
        VHz[2] = s * Math.sin(Dec[2]) + c * Math.cos(Dec[2]) * Math.cos(ha[2]) - z;
        
        if (sgn(VHz[0]) == sgn(VHz[2])) 
            return VHz[2]; // no event this hour
        VHz[1] = s * Math.sin(Dec[1]) + c * Math.cos(Dec[1]) * Math.cos(ha[1]) - z;
        
        a = 2 * VHz[0] - 4 * VHz[1] + 2 * VHz[2];
        b = -3 * VHz[0] + 4 * VHz[1] - VHz[2];
        d = b * b - 4 * a * VHz[0];
        
        if (d < 0) 
            return VHz[2]; // no event this hour
        d = Math.sqrt(d);
        e = (-b + d) / (2 * a);
        
        if ((e > 1) || (e < 0)) 
            e = (-b - d) / (2 * a);
        
        time = k + e + 1 / 120; // time of an event
        hr = Math.floor(time);
        min = Math.floor((time - hr) * 60);
        
        hz = ha[0] + e * (ha[2] - ha[0]); // azimuth of the sun at the event
        nz = -Math.cos(Dec[1]) * Math.sin(hz);
        dz = c * Math.sin(Dec[1]) - s * Math.cos(Dec[1]) * Math.cos(hz);
        az = Math.atan2(nz, dz) / DR;
        if (az < 0) 
            az = az + 360;
        
        if ((VHz[0] < 0) && (VHz[2] > 0)) {
            Rise_time[0] = hr;
            Rise_time[1] = min;
            Rise_az = az;
            Moonrise = true;
        }
        
        if ((VHz[0] > 0) && (VHz[2] < 0)) {
            Set_time[0] = hr;
            Set_time[1] = min;
            Set_az = az;
            Moonset = true;
        }
        
        return VHz[2];
    }
    
    // check for no moonrise and/or no moonset
    function special_message(){
        if ((!Moonrise) && (!Moonset)) // neither moonrise nor moonset
        {
            if (VHz[2] < 0) 
                calc.moonrise = "Moon down all day";
            else 
                calc.moonrise = "Moon up all day";
            
            calc.moonset = "";
        }
        else // moonrise or moonset
        {
            if (!Moonrise) 
                calc.moonrise = "No moonrise this date";
            else 
                if (!Moonset) 
                    calc.moonset = "No moonset this date";
        }
    }
    
    // moon's position using fundamental arguments 
    // (Van Flandern & Pulkkinen, 1979)
    function moon(jd){
        var d, f, g, h, m, n, s, u, v, w;
        
        h = 0.606434 + 0.03660110129 * jd;
        m = 0.374897 + 0.03629164709 * jd;
        f = 0.259091 + 0.0367481952 * jd;
        d = 0.827362 + 0.03386319198 * jd;
        n = 0.347343 - 0.00014709391 * jd;
        g = 0.993126 + 0.0027377785 * jd;
        
        h = h - Math.floor(h);
        m = m - Math.floor(m);
        f = f - Math.floor(f);
        d = d - Math.floor(d);
        n = n - Math.floor(n);
        g = g - Math.floor(g);
        
        h = h * 2 * PI;
        m = m * 2 * PI;
        f = f * 2 * PI;
        d = d * 2 * PI;
        n = n * 2 * PI;
        g = g * 2 * PI;
        
        v = 0.39558 * Math.sin(f + n);
        v = v + 0.082 * Math.sin(f);
        v = v + 0.03257 * Math.sin(m - f - n);
        v = v + 0.01092 * Math.sin(m + f + n);
        v = v + 0.00666 * Math.sin(m - f);
        v = v - 0.00644 * Math.sin(m + f - 2 * d + n);
        v = v - 0.00331 * Math.sin(f - 2 * d + n);
        v = v - 0.00304 * Math.sin(f - 2 * d);
        v = v - 0.0024 * Math.sin(m - f - 2 * d - n);
        v = v + 0.00226 * Math.sin(m + f);
        v = v - 0.00108 * Math.sin(m + f - 2 * d);
        v = v - 0.00079 * Math.sin(f - n);
        v = v + 0.00078 * Math.sin(f + 2 * d + n);
        
        u = 1 - 0.10828 * Math.cos(m);
        u = u - 0.0188 * Math.cos(m - 2 * d);
        u = u - 0.01479 * Math.cos(2 * d);
        u = u + 0.00181 * Math.cos(2 * m - 2 * d);
        u = u - 0.00147 * Math.cos(2 * m);
        u = u - 0.00105 * Math.cos(2 * d - g);
        u = u - 0.00075 * Math.cos(m - 2 * d + g);
        
        w = 0.10478 * Math.sin(m);
        w = w - 0.04105 * Math.sin(2 * f + 2 * n);
        w = w - 0.0213 * Math.sin(m - 2 * d);
        w = w - 0.01779 * Math.sin(2 * f + n);
        w = w + 0.01774 * Math.sin(n);
        w = w + 0.00987 * Math.sin(2 * d);
        w = w - 0.00338 * Math.sin(m - 2 * f - 2 * n);
        w = w - 0.00309 * Math.sin(g);
        w = w - 0.0019 * Math.sin(2 * f);
        w = w - 0.00144 * Math.sin(m + n);
        w = w - 0.00144 * Math.sin(m - 2 * f - n);
        w = w - 0.00113 * Math.sin(m + 2 * f + 2 * n);
        w = w - 0.00094 * Math.sin(m - 2 * d + g);
        w = w - 0.00092 * Math.sin(2 * m - 2 * d);
        
        s = w / Math.sqrt(u - v * v); // compute moon's right ascension ...  
        Sky[0] = h + Math.atan(s / Math.sqrt(1 - s * s));
        
        s = v / Math.sqrt(u); // declination ...
        Sky[1] = Math.atan(s / Math.sqrt(1 - s * s));
        
        Sky[2] = 60.40974 * Math.sqrt(u); // and parallax
    }
    
    // determine Julian day from calendar date
    // (Jean Meeus, "Astronomical Algorithms", Willmann-Bell, 1991)
    function julian_day(){
        var a, b, jd;
        var gregorian;
        
        var month = Now.getMonth() + 1;
        var day = Now.getDate();
        var year = Now.getFullYear();
        
        gregorian = (year < 1583) ? false : true;
        
        if ((month == 1) || (month == 2)) {
            year = year - 1;
            month = month + 12;
        }
        
        a = Math.floor(year / 100);
        if (gregorian) 
            b = 2 - a + Math.floor(a / 4);
        else 
            b = 0.0;
        
        jd = Math.floor(365.25 * (year + 4716)) +
        Math.floor(30.6001 * (month + 1)) +
        day +
        b -
        1524.5;
        
        return jd;
    }
    
    // returns value for sign of argument
    function sgn(x){
        var rv;
        if (x > 0.0) 
            rv = 1;
        else 
            if (x < 0.0) 
                rv = -1;
            else 
                rv = 0;
        return rv;
    }
    
    // format a positive integer with leading zeroes
    function zintstr(num, width){
        var str = num.toString(10);
        var len = str.length;
        var intgr = "";
        var i;
        
        for (i = 0; i < width - len; i++) // append leading zeroes
             intgr += '0';
        
        for (i = 0; i < len; i++) // append digits
             intgr += str.charAt(i);
        
        return intgr;
    }
    
    // format an integer
    function cintstr(num, width){
        var str = num.toString(10);
        var len = str.length;
        var intgr = "";
        var i;
        
        for (i = 0; i < width - len; i++) // append leading spaces
             intgr += ' ';
        
        for (i = 0; i < len; i++) // append digits
             intgr += str.charAt(i);
        
        return intgr;
    }
    
    // format a real number
    function frealstr(num, width, fract){
        var str = num.toFixed(fract);
        var len = str.length;
        var real = "";
        var i;
        
        for (i = 0; i < width - len; i++) // append leading spaces
             real += ' ';
        
        for (i = 0; i < len; i++) // append digits
             real += str.charAt(i);
        
        return real;
    }
 
};

//--------- funtion nextFull------------------------           
var nextFull = function() {
    if (calc.age < 14.75) {
        var till = 14.75 - calc.age;
		till = parseFloat(till.toFixed(0));
        var tillFull = till;
        till = till + " Days to FULL";
		document.getElementById('aboveArrow').innerHTML = till;

        
        var from = calc.age.toFixed(0) + " Days from NEW";
		document.getElementById('belowArrow').innerHTML = from;
        
    }
    else {
        var till = (29.5 - calc.age);
        var tillFull = till + 14.75;
		tillFull = parseFloat(tillFull.toFixed(0));
        till = till.toFixed(0) + " Days to NEW";
		document.getElementById('aboveArrow').innerHTML = till;
        
        var from = calc.age - 14.75
        from = from.toFixed(0) + " Days from FULL";
        document.getElementById('belowArrow').innerHTML = from;
    }
	
	var date= (todayDate.getDate());
    var year = (todayDate.getFullYear());
    var month = (todayDate.getMonth());
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    
	   var fullDate = new Date();
	fullDate.setFullYear(year);
	fullDate.setMonth(month);
	fullDate.setDate(date);
	fullDate.setDate(fullDate.getDate()+ tillFull);
    date = fullDate.getDate();
	month = fullDate.getMonth();
	year = fullDate.getFullYear();
	var day = fullDate.getDay();
	
	month = months[month];
    
    var weekday = new Array(7);
    weekday[0] = "Sunday";
    weekday[1] = "Monday";
    weekday[2] = "Tuesday";
    weekday[3] = "Wednesday";
    weekday[4] = "Thursday";
    weekday[5] = "Friday";
    weekday[6] = "Saturday";
    
  
    day = weekday[day];
 
    
    var theDate = day + " " + month + " " + date;
    
    var nextFull = "Fullest next on " + theDate;
	document.getElementById('nextFull').innerHTML = nextFull;

    
};

//--------- funtion callDialogBox------------------------           
var callDialogBox = function(day1, month1, year1) {
	var year = (todayDate.getFullYear());
    var month = (todayDate.getMonth());
    var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    month = months[month];
    
    var weekday = new Array(7);
    weekday[0] = "Sun";
    weekday[1] = "Mon";
    weekday[2] = "Tue";
    weekday[3] = "Wed";
    weekday[4] = "Thu";
    weekday[5] = "Fri";
    weekday[6] = "Sat";
    
    var day = (todayDate.getDay());
    day = weekday[day];
    
    var date = (todayDate.getDate());
    
    var theDate = day + " " + month + " " + date + ", " + year;
	
	var distance = 0;
	var unit ='Earth Radii';
	if(settings.units=='radii'){
		distance = parseFloat(calc.dst);
		unit ='Earth Radii';
	}
	else if(settings.units=='miles'){
		distance = (parseFloat(calc.dst)*3960).toFixed(1);
		unit ='Miles';
	}
	else if(settings.units=='kilometers'){
		distance = (parseFloat(calc.dst)*6371).toFixed(1);
		unit ='Kilometers';
	}
	//Ext.getCmp("infoBoxHeader").setTitle ("Details for "+theDate);
	document.getElementById('infoBoxHeader').innerHTML = "Details for "+theDate;
	document.getElementById('infoBoxMessage').innerHTML = "<font size='4'><b>Moon's age from new: </b>" + calc.age +" Days<br><b>Illumination: </b>"+ percent.toFixed(1) + "%<br><b>Current Phase: </b>" + calc.faz + "<br><b>Zodiac Sign: </b>" + calc.sgn + " <br><b>Distance: </b>" + distance + " "+ unit +" <br><b>Ecliptic latitude: </b>" + calc.lat + "&deg;<br><b>Ecliptic longitude: </b>" + calc.lon + "&deg;<br><b>Moon Rise: </b>" + moonRise + "<br><b>Moon Set: </b>" + moonSet +"</font>";
	//infoPopupTxt.getEl().setHTML( "<font size='4'><b>Moon's age from new: </b>" + calc.age +" Days<br><b>Illumination: </b>"+ percent.toFixed(1) + "%<br><b>Current Phase: </b>" + calc.faz + "<br><b>Zodiac Sign: </b>" + calc.sgn + " <br><b>Distance: </b>" + distance + " "+ unit +" <br><b>Ecliptic latitude: </b>" + calc.lat + "&deg;<br><b>Ecliptic longitude: </b>" + calc.lon + "&deg;<br><b>Moon Rise: </b>" + moonRise + "<br><b>Moon Set: </b>" + moonSet +"</font>");
    
    
};

//--------- funtion showDialogBox------------------------           
var showDialogBox = function(title, discription) {
    
};

//--------- funtion dealWithDialog------------------------           
var dealWithDialog = function() {
    
};

//--------- funtion updateCalander------------------------           
var updateCalander = function() {
    year = (todayDate.getFullYear());
	month = (todayDate.getMonth() + 1);

	printCalendar(month, year);
};

//--------- funtion printCalendar------------------------           
var printCalendar = function(month, year) {
    calculate(1, month, year);
    
    var xHolder = 0;
    var moonDay = calc.age.toFixed(0);
    var moonImage = '';
    var calendarCode = buildCal(month, year, "main", "month", "daysofweek", "days", 1);
    document.getElementById('calendarBox').innerHTML = calendarCode;
//calandarBox.getEl().setHTML(calendarCode);
    function buildCal(m, y, cM, cH, cDW, cD, brdr){
        var mn = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
        var dim = [31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
        
        var oD = new Date(y, m - 1, 1); //DD replaced line to fix date bug when current day is 31st
        oD.od = oD.getDay() + 1; //DD replaced line to fix date bug when current day is 31st
        var todaydate = new Date() //DD added
        var scanfortoday = (y == todaydate.getFullYear() && m == todaydate.getMonth() + 1) ? todaydate.getDate() : 0 //DD added
        dim[1] = (((oD.getFullYear() % 100 != 0) && (oD.getFullYear() % 4 == 0)) || (oD.getFullYear() % 400 == 0)) ? 29 : 28;
        var t = '<div class="' + cM + '" ><table class="' + cM + '" cols="7" cellpadding="0" border="' + brdr + '" cellspacing="0"><tr align="center">';
        t += '<td colspan="7" align="center" class="' + cH + '">' + mn[m - 1] + ' - ' + y + '</td></tr><tr align="center">';
        for (s = 0; s < 7; s++) 
            t += '<td class="' + cDW + '">' + "SMTWTFS".substr(s, 1) + '</td>';
        t += '</tr><tr align="center">';
        for (i = 1; i <= 42; i++) {
            
            
            var x = ((i - oD.od >= 0) && (i - oD.od < dim[m - 1])) ? i - oD.od + 1 : '&nbsp;';
			if(x=='&nbsp;'){
				
			}
			else{
				xHolder = x;
				if (moonDay < 30) {
                moonImage = "moon" + moonDay + ".gif";
                ++moonDay;
           		 }
           		 else {
               		 moonImage = "moon1.gif";
               		 moonDay = 1;
           		 }
				 if (x == scanfortoday) //DD added
                x = '<span id="today">' + x + '</span>';//DD added
           		x = x + '<img id="'+xHolder+'" src="images/' + moonImage + '"  /> ';
				x = '<div id="'+xHolder+'">'+ x + '</div>';
			}
           
            
            t += '<td class="' + cD + '">' + x + '</td>';
            if (((i) % 7 == 0) && (i < 36)) 
                t += '</tr><tr align="center">';
        }
        return t += '</tr></table></div>';
    }
};
//--------- funtion genTable to make apo and perigee table LOOONG one------------------------    
var genTable = function(myYear) {
	function jyear(td) {
    var z, f, a, alpha, b, c, d, e, mm;

    td += 0.5;
    z = Math.floor(td);
    f = td - z;

    if (z < 2299161.0) {
        a = z;
    } else {
        alpha = Math.floor((z - 1867216.25) / 36524.25);
        a = z + 1 + alpha - Math.floor(alpha / 4);
    }

    b = a + 1524;
    c = Math.floor((b - 122.1) / 365.25);
    d = Math.floor(365.25 * c);
    e = Math.floor((b - d) / 30.6001);
    mm = Math.floor((e < 14) ? (e - 1) : (e - 13));

    return new Array(
                     Math.floor((mm > 2) ? (c - 4716) : (c - 4715)),
                     mm,
                     Math.floor(b - d - Math.floor(30.6001 * e) + f)
                    );
}

/*  JHMS  --  Convert Julian time to hour, minutes, and seconds,
              returned as a three-element array.  */

function jhms(j) {
    var ij;

    j += 0.5;                 /* Astronomical to civil */
    ij = (j - Math.floor(j)) * 86400.0;
    return new Array(
                     Math.floor(ij / 3600),
                     Math.floor((ij / 60) % 60),
                     Math.floor(ij % 60));
}

/*  DTR  --  Degrees to radians.  */

function dtr(d)
{
    return (d * Math.PI) / 180.0;
}

/*  FIXANGLE  --  Range reduce angle in degrees.  */

function fixangle(a)
{
        return a - 360.0 * (Math.floor((a) / 360.0));
}

/*  SUMSER  --  Sum the series of periodic terms.  */

function sumser(trig, D, M, F, T, argtab, coeff, tfix, tfixc)
{
    var i, j = 0, n = 0, sum = 0, arg, coef;

    D = dtr(fixangle(D));
    M = dtr(fixangle(M));
    F = dtr(fixangle(F));

    for (i = 0; coeff[i] != 0.0; i++) {
        arg = (D * argtab[j]) + (M * argtab[j + 1]) + (F * argtab[j + 2]);
        j += 3;
        coef = coeff[i];
        if (i == tfix[n]) {
            coef += T * tfixc[n++];
        }
        sum += coef * trig(arg);
    }

    return sum;
}

/*  We define the perigee and apogee period term arrays statically to
    avoid re-constructing them on every invocation of moonpa.  */

    var periarg = new Array(
    /*  D,  M,  F   */
        2,  0,  0,
        4,  0,  0,
        6,  0,  0,
        8,  0,  0,
        2, -1,  0,
        0,  1,  0,
       10,  0,  0,
        4, -1,  0,
        6, -1,  0,
       12,  0,  0,
        1,  0,  0,
        8, -1,  0,
       14,  0,  0,
        0,  0,  2,
        3,  0,  0,
       10, -1,  0,
       16,  0,  0,
       12, -1,  0,
        5,  0,  0,
        2,  0,  2,
       18,  0,  0,
       14, -1,  0,
        7,  0,  0,
        2,  1,  0,
       20,  0,  0,
        1,  1,  0,
       16, -1,  0,
        4,  1,  0,
        9,  0,  0,
        4,  0,  2,

        2, -2,  0,
        4, -2,  0,
        6, -2,  0,
       22,  0,  0,
       18, -1,  0,
        6,  1,  0,
       11,  0,  0,
        8,  1,  0,
        4,  0, -2,
        6,  0,  2,
        3,  1,  0,
        5,  1,  0,
       13,  0,  0,
       20, -1,  0,
        3,  2,  0,
        4, -2,  2,
        1,  2,  0,
       22, -1,  0,
        0,  0,  4,
        6,  0, -2,
        2,  1, -2,
        0,  2,  0,
        0, -1,  2,
        2,  0,  4,
        0, -2,  2,
        2,  2, -2,
       24,  0,  0,
        4,  0, -4,
        2,  2,  0,
        1, -1,  0 
    );

    var pericoeff = new Array(
        -1.6769,
         0.4589,
        -0.1856,
         0.0883,
        -0.0773,
         0.0502,
        -0.0460,
         0.0422,
        -0.0256,
         0.0253,
         0.0237,
         0.0162,
        -0.0145,
         0.0129,
        -0.0112,
        -0.0104,
         0.0086,
         0.0069,
         0.0066,
        -0.0053,
        -0.0052,
        -0.0046,
        -0.0041,
         0.0040,
         0.0032,
        -0.0032,
         0.0031,
        -0.0029,
         0.0027,
         0.0027,

        -0.0027,
         0.0024,
        -0.0021,
        -0.0021,
        -0.0021,
         0.0019,
        -0.0018,
        -0.0014,
        -0.0014,
        -0.0014,
         0.0014,
        -0.0014,
         0.0013,
         0.0013,
         0.0011,
        -0.0011,
        -0.0010,
        -0.0009,
        -0.0008,
         0.0008,
         0.0008,    
         0.0007,
         0.0007,
         0.0007,
        -0.0006,
        -0.0006,
         0.0006,
         0.0005,
         0.0005,
        -0.0004,

        0
    );

    var peritft = new Array(
        4,
        5, 
        7,
        -1
    );

    var peritfc = new Array(
         0.00019,
        -0.00013,
        -0.00011
    );

    var apoarg = new Array(
    /*  D,  M,  F   */
        2,  0,  0,
        4,  0,  0,
        0,  1,  0,
        2, -1,  0,
        0,  0,  2,
        1,  0,  0,
        6,  0,  0,
        4, -1,  0,
        2,  0,  2,
        1,  1,  0,
        8,  0,  0,
        6, -1,  0,
        2,  0, -2,
        2, -2,  0,
        3,  0,  0,
        4,  0,  2,

        8, -1,  0,
        4, -2,  0,
       10,  0,  0,
        3,  1,  0,
        0,  2,  0,
        2,  1,  0,
        2,  2,  0,
        6,  0,  2,
        6, -2,  0,
       10, -1,  0,
        5,  0,  0,
        4,  0, -2,
        0,  1,  2,
       12,  0,  0,
        2, -1,  2,
        1, -1,  0
    );

    var apocoeff = new Array(
         0.4392,
         0.0684,
         0.0456,
         0.0426,
         0.0212,
        -0.0189,
         0.0144,
         0.0113,
         0.0047,
         0.0036,
         0.0035,
         0.0034,
        -0.0034,
         0.0022,
        -0.0017,
         0.0013,

         0.0011,
         0.0010,
         0.0009,
         0.0007,
         0.0006,
         0.0005,
         0.0005,
         0.0004,
         0.0004,
         0.0004,
        -0.0004,
        -0.0004,
         0.0003,
         0.0003,
         0.0003,
        -0.0003,

        0
    );

    var apotft = new Array(
        2,
        3, 
        -1
    );

    var apotfc = new Array(
        -0.00011,
        -0.00011
    );

    var periparg = new Array(
    /*  D,  M,  F   */
        0,  0,  0,
        2,  0,  0,
        4,  0,  0,
        2, -1,  0,
        6,  0,  0,
        1,  0,  0,
        8,  0,  0,
        0,  1,  0,
        0,  0,  2,
        4, -1,  0,
        2,  0, -2,
       10,  0,  0,
        6, -1,  0,
        3,  0,  0,
        2,  1,  0,
        1,  1,  0,
       12,  0,  0,
        8, -1,  0,
        2,  0,  2,
        2, -2,  0,
        5,  0,  0,
       14,  0,  0,

       10, -1,  0,
        4,  1,  0,
       12, -1,  0,
        4, -2,  0,
        7,  0,  0,
        4,  0,  2,
       16,  0,  0,
        3,  1,  0,
        1, -1,  0,
        6,  1,  0,
        0,  2,  0,
       14, -1,  0,
        2,  2,  0,
        6, -2,  0,
        2, -1, -2,
        9,  0,  0,
       18,  0,  0,
        6,  0,  2,
        0, -1,  2,
       16, -1,  0,
        4,  0, -2,
        8,  1,  0,
       11,  0,  0,
        5,  1,  0,
       20,  0,  0
    );

    var peripcoeff = new Array(
      3629.215,
        63.224,
        -6.990,
         2.834,
         1.927,
        -1.263,
        -0.702,
         0.696,
        -0.690,
        -0.629,
        -0.392,
         0.297,
         0.260,
         0.201,
        -0.161,
         0.157,
        -0.138,
        -0.127,
         0.104,
         0.104,
        -0.079,
         0.068,

         0.067,
         0.054,
        -0.038,
        -0.038,
         0.037,
        -0.037,
        -0.035,
        -0.030,
         0.029,
        -0.025,
         0.023,
         0.023,
        -0.023,
         0.022,
        -0.021,
        -0.020,
         0.019,
         0.017,
         0.014,
        -0.014,
         0.013,
         0.012,
         0.011,
         0.010,
        -0.010,

        0
    );

    var periptft = new Array(
        3,
        7,
        9,
        -1
    );

    var periptfc = new Array(
        -0.0071,
        -0.0017,
         0.0016
    );

    var apoparg = new Array(
    /*  D,  M,  F   */
        0,  0,  0,
        2,  0,  0,
        1,  0,  0,
        0,  0,  2,
        0,  1,  0,
        4,  0,  0,
        2, -1,  0,
        1,  1,  0,
        4, -1,  0,
        6,  0,  0,
        2,  1,  0,
        2,  0,  2,
        2,  0, -2,
        2, -2,  0,
        2,  2,  0,
        0,  2,  0,
        6, -1,  0,
        8,  0,  0
    );

    var apopcoeff = new Array(
      3245.251,
        -9.147,
        -0.841,
         0.697,
        -0.656,
         0.355,
         0.159,
         0.127,
         0.065,

         0.052,
         0.043,
         0.031,
        -0.023,
         0.022,
         0.019,
        -0.016,
         0.014,
         0.010,

        0
    );

    var apoptft = new Array(
        4,
        -1
    );

    var apoptfc = new Array(
         0.0016,
         -1
    );


/*  MOONPA  --  Calculate perigee or apogee from index number.  */

function moonpa(k)
{
    var t, t2, t3, t4, JDE, D, M, F, par, apogee,
        EarthRad = 6378.14;


    t = k - Math.floor(k);
    if (t > 0.499 && t < 0.501) {
        apogee = true;
    } else if (t > 0.999 || t < 0.001) {
        apogee = false;
    } else {
        return; //abort();
    }

    t = k / 1325.55;
    t4 = t * (t3 = t * (t2 = t * t));

    /* Mean time of perigee or apogee */
    JDE = 2451534.6698 + 27.55454989 * k
                       - 0.0006691 * t2
                       - 0.000001098 * t3
                       + 0.0000000052 * t4;

    /* Mean elongation of the Moon */
    D = 171.9179 + 335.9106046 * k
                 - 0.0100383 * t2
                 - 0.00001156 * t3
                 + 0.000000055 * t4;

    /* Mean anomaly of the Sun */
    M = 347.3477 + 27.1577721 * k
                 - 0.0008130 * t2
                 - 0.0000010 * t3;

    /* Moon's argument of latitude */
    F = 316.6109 + 364.5287911 * k
                 - 0.0125053 * t2
                 - 0.0000148 * t3;

    JDE += sumser(Math.sin, D, M, F, t,
            apogee ? apoarg : periarg, apogee ? apocoeff : pericoeff,
            apogee ? apotft : peritft, apogee ? apotfc : peritfc);
    par = sumser(Math.cos, D, M, F, t,
            apogee ? apoparg : periparg, apogee ? apopcoeff : peripcoeff,
            apogee ? apoptft : periptft, apogee ? apoptfc : periptfc);

    par = dtr(par / 3600.0);
    return new Array(JDE, par, EarthRad / Math.sin(par));
}

/*  PAD  --  Pad a string to a given length with a given fill character.  */

function pad(str, howlong, padwith) {
    var s = str.toString();

    while (s.length < howlong) {
        s = padwith + s;
    }
    return s;
}

/*  EDATE  --  Edit date and time to application specific format.  */

var Months = new Array( "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
                      );

function edate(j) {
    var date, time;

    j += (30.0 / (24 * 60 * 60));     // Round to nearest minute
    date = jyear(j);
    time = jhms(j);

    return Months[date[1] - 1] + " " + pad(date[2], 2, " ") + " " +  
           pad(time[0], 2, " ") + ":" + pad(time[1], 2, "0");
}

/*  TRUEPHASE  --  Given a K value used to determine the mean phase of
                   the new moon, and a phase selector (0.0, 0.25, 0.5,
                   0.75), obtain the true, corrected phase time.  */

function dsin(x) {
    return Math.sin(dtr(x));
}

function dcos(x) {
    return Math.cos(dtr(x));
}

function truephase(k, phase)
{
    var t, t2, t3, pt, m, mprime, f,
        SynMonth = 29.53058868;     /* Synodic month (mean time from new to next new Moon) */

    k += phase;                     /* Add phase to new moon time */
    t = k / 1236.85;                /* Time in Julian centuries from
                                       1900 January 0.5 */
    t2 = t * t;                     /* Square for frequent use */
    t3 = t2 * t;                    /* Cube for frequent use */
    pt = 2415020.75933              /* Mean time of phase */
         + SynMonth * k
         + 0.0001178 * t2
         - 0.000000155 * t3
         + 0.00033 * dsin(166.56 + 132.87 * t - 0.009173 * t2);

    m = 359.2242                    /* Sun's mean anomaly */
        + 29.10535608 * k
        - 0.0000333 * t2
        - 0.00000347 * t3;
    mprime = 306.0253               /* Moon's mean anomaly */
        + 385.81691806 * k
        + 0.0107306 * t2
        + 0.00001236 * t3;
    f = 21.2964                     /* Moon's argument of latitude */
        + 390.67050646 * k
        - 0.0016528 * t2
        - 0.00000239 * t3;
    if ((phase < 0.01) || (Math.abs(phase - 0.5) < 0.01)) {

       /* Corrections for New and Full Moon */

       pt +=     (0.1734 - 0.000393 * t) * dsin(m)
                + 0.0021 * dsin(2 * m)
                - 0.4068 * dsin(mprime)
                + 0.0161 * dsin(2 * mprime)
                - 0.0004 * dsin(3 * mprime)
                + 0.0104 * dsin(2 * f)
                - 0.0051 * dsin(m + mprime)
                - 0.0074 * dsin(m - mprime)
                + 0.0004 * dsin(2 * f + m)
                - 0.0004 * dsin(2 * f - m)
                - 0.0006 * dsin(2 * f + mprime)
                + 0.0010 * dsin(2 * f - mprime)
                + 0.0005 * dsin(m + 2 * mprime);
    } else if ((abs(phase - 0.25) < 0.01 || (abs(phase - 0.75) < 0.01))) {
       pt +=     (0.1721 - 0.0004 * t) * dsin(m)
                + 0.0021 * dsin(2 * m)
                - 0.6280 * dsin(mprime)
                + 0.0089 * dsin(2 * mprime)
                - 0.0004 * dsin(3 * mprime)
                + 0.0079 * dsin(2 * f)
                - 0.0119 * dsin(m + mprime)
                - 0.0047 * dsin(m - mprime)
                + 0.0003 * dsin(2 * f + m)
                - 0.0004 * dsin(2 * f - m)
                - 0.0006 * dsin(2 * f + mprime)
                + 0.0021 * dsin(2 * f - mprime)
                + 0.0003 * dsin(m + 2 * mprime)
                + 0.0004 * dsin(m - 2 * mprime)
                - 0.0003 * dsin(2 * m + mprime);
       if (phase < 0.5)
          /* First quarter correction */
          pt += 0.0028 - 0.0004 * dcos(m) + 0.0003 * dcos(mprime);
       else
          /* Last quarter correction */
          pt += -0.0028 + 0.0004 * dcos(m) - 0.0003 * dcos(mprime);
    }
    return pt;
}

/*  NEARPHASE  --  Find closest new or full Moon to an apogee or
                   perigee passage and edit the time difference.  */

function nearphase(jd, phaset) {
    var i, closest, dt = Number.MAX_VALUE, rs;

    for (i = 0; i < phaset.length; i++) {
        if (Math.abs(jd - Math.abs(phaset[i])) < dt) {
            dt = Math.abs(jd - Math.abs(phaset[i]));
            closest = i;
        }
    }
    rs = (phaset[closest] < 0) ? "N" : "F";
    rs += (jd > Math.abs(phaset[closest])) ? "+" : "-";
    if (dt >= 1) {
        rs += Math.floor(dt) + "d";
        dt -= Math.floor(dt);
    } else {
        rs += "  ";
    }
    dt = Math.floor((dt * 86400) / 3600);
    if (dt < 10) {
        rs += " ";
    }
    rs += dt + "h";
    return rs;
}

//  GEN  --  Update the tables when an action button is pressed

function gen() {
    var v, sk, kr, l, perigee, s, Itemlen = 36,
        dat, evt, m = 0, epad, pchar, phnear,
        pmin = Number.MAX_VALUE, pminx = 0,
        pmax = Number.MIN_VALUE, pmaxx = 0,
        yrange, centile, TOLERANCE = 0.01, k1, mtime, minx, phaset,
        Pitemlen = 25;
	
	
   
    calc.results = "";
    year = calc.year;
	var myCounter =0;
    v = "<table border='1'><tr><td>Perigee</td><td>Apogee</td></tr><tr>           "; 
        
    s = "";

    sk = Math.floor((year - 1999.97) * 13.2555);
    dat = new Array();
    evt = new Array();
    phaset = new Array();

    //  Tabulate perigees and apogees for the year

    for (l = 0; true; l++) {
        kr = moonpa(sk);
        date = jyear(kr[0]);
        perigee = (sk - Math.floor(sk)) < .25;

        if (date[0] == year) {
            if (kr[2] < pmin) {
                pmin = kr[2];
                pminx = m;
            } else if (kr[2] > pmax) {
                pmax = kr[2];
                pmaxx = m;
            }
            dat[m] = sk;
            evt[m++] = kr;
        }
        if (date[0] > year) {
            break;
        }
        sk += 0.5;
    }
    yrange = pmax - pmin;

    //  Tabulate new and full moons surrounding the year

    k1 = Math.floor((year - 1900) * 12.3685) - 4;
    minx = 0;
    for (l = 0; true; l++) {
        mtime = truephase(k1, (l & 1) * 0.5);
        date = jyear(mtime);
        if (date[0] >= year) {
            minx++;
        }
        phaset[minx] = mtime * ((l & 1) == 0 ? -1 : 1);
        if (date[0] > year) {
            minx++;
            break;
        }
        k1 += l & 1;
    }

    //  Generate perigee and apogee table

    for (l = 0; l < m; l++) {
        sk = dat[l];
        kr = evt[l];

        date = jyear(kr[0]);
        time = jhms(kr[0]);
        perigee = (sk - Math.floor(sk)) < .25;
        if (!perigee && s.length == 0) {
            s = pad("", Itemlen, " ");
        }
        phnear = nearphase(kr[0], phaset);
        pchar = phnear.charAt(0) == "F" ? "+" : "-";
        if (l == pminx || l == pmaxx) {
            epad = pchar + pchar;
        } else {
            centile = (kr[2] - pmin) / yrange;
            if (centile <= TOLERANCE || centile >= (1 - TOLERANCE)) {
                epad = pchar + " ";
            } else {
                epad = "  ";
            }
        }
        s += "<td>"+edate(kr[0]) + " " + Math.round(kr[2]) + " km " + epad + " " +
             phnear+"</td>";
		++myCounter;
		if(myCounter==2){
			myCounter = 0;
			 s += "</tr><tr>";
		}
        if (s.length < Itemlen) { 
            while (s.length < Itemlen) {
                s += " ";
            }
        } else {
            v += s + "";
            s = "";
        }
    }
    if (s.length > 0) {
        v += s ;
    }
    calc.results = v+"</tr></table>";

    //  Generate Moon phase table

    v = "           New                      Full\n";
    s = "";
    for (l = 0; l < minx; l++) {
        mp = phaset[l];
        if (mp < 0) {
            mp = - mp;
        } else {
            if (s.length == 0) {
                s = pad(s, Pitemlen, " ");
            }
        }
        s += "   " + jyear(mp)[0] + " " + edate(mp);
        if (s.length < Pitemlen) { 
            while (s.length < Pitemlen) {
                s += " ";
            }
        } else {
            v += s + "\n";
            s = "";
        }
    }
    if (s.length > 0) {
        v += s + "\n";
    }
    calc.phases = v;

  
	}
	var calc=[];
	calc.year=myYear;
	gen();
	document.getElementById('ABTable').innerHTML = calc.results;
}

//--------- funtion backMonth------------------------           
var backMonth = function() {
   	todayDate.setMonth(todayDate.getMonth()-1);
	updateCalander(); 
};

//--------- funtion nextMonth------------------------           
var nextMonth = function() {
    todayDate.setMonth(todayDate.getMonth()+1);
	updateCalander();
};

var leftButtonTap = function() {
		todayDate.setDate(todayDate.getDate() - 1);
	    update();
};
var rightButtonTap = function() {
		todayDate.setDate(todayDate.getDate() + 1);
	    update();
};
var installer = function() {
	// Install app
	if (navigator.mozApps) {
	    var checkIfInstalled = navigator.mozApps.getSelf();
	    checkIfInstalled.onsuccess = function () {
	        if (checkIfInstalled.result) {
	            // Already installed
	        }
	        else {
	            var install = document.querySelector("#install"),
	                manifestURL = location.href.substring(0, location.href.lastIndexOf("/")) + "/package.manifest";
	                alert(manifestURL);
	            //install.parentNode.className = "show-install";
				install.style.display = "block";
	            install.onclick = function () {
	                var installApp = navigator.mozApps.installPackage("http://coolate.com/firefox/lunarPalHTML5/package.manifest");
	                installApp.onsuccess = function(data) {
	                    install.style.display = "none";
	                };
	                installApp.onerror = function() {
	                    alert("Install failed\n\n:" + installApp.error.name);
	                };
	            };
	        }
	    };
	}
	else {
	    console.log("Open Web Apps not supported");
	}
		
};

//=====================DOCUMENT READY!!!  ===============================================================================  
$(document).ready(function() {
  	//time to load, lets go!
//	installer();
	getPrefs();
	update();
	
	//set up dialogs
	$( "#menuPopUp1" ).popup();
	$( "#dialog1" ).popup(); 
	//$( "#aboutD" ).popup();

//-------Event listeners -------------------------------	
	$('#leftButton').tap(function() {
	  leftButtonTap();
	});
	
	$('#rightButton').tap(function() {
	  rightButtonTap();
	});
	
	$('#calendarButton').tap(function() {
	  updateCalander();
	});
	
	$('#currentButton').tap(function() {
	  	todayDate = new Date();
		update();
	});
	
	$('#prevMonthButton').tap(function() {
	  	backMonth();
	});
	$('#nextMonthButton').tap(function() {
	  	nextMonth();
	});
	$('#moon').tap(function() {
	  	callDialogBox();
		$( "#dialog1" ).popup( "open" );
	});
	$('#growing').tap(function() {
	  	callDialogBox();
		
		$( "#dialog1" ).popup( "open" );
	});
	$('#menuButton').tap(function() {
		$( "#menuPopUp1" ).popup( "open" );
	});
	
	
	$('#menuButton1').tap(function() {
		$( "#menuPopUp1" ).popup( "open" );
	});
	
	//$('#aboutButton').tap(function() {
	
	//	$( "#menuPopUp1" ).popup( "close" );
	//	$( "#aboutD" ).popup( "open" );
//});
	$('#perigeeButton').tap(function() {	
		var tempToday = new Date();
		var tempTodayYear = tempToday.getFullYear();
		$("#perigeeYearSel").val(tempTodayYear);
		genTable(tempTodayYear);
	});
	$('#perigeeYearSel').change(function() {		
		var value = $("#perigeeYearSel").val();
		genTable(value);
	});
	
	$('#calendar').tap(function(e) {
	  	var evt = e || window.event; // this assign evt with the event object
		var current = evt.target || evt.srcElement; // this assign current with the event target
		var element = current.id;      //old way->  e.srcElement.id;

		if (element >0 && element < 32){
			calculate(element, month, year);
			todayDate.setDate(element);
			calcMoonSet();
			callDialogBox();
			$( "#dialog1" ).popup();
			$( "#dialog1" ).popup( "open" );
		}
	});
	
	$('#useGPSButton').tap(function() {	
		if ("geolocation" in navigator) {
		  /* geolocation is available */
			$.mobile.loading( 'show' ,{ theme: "b", text: "Searching for Location", textVisible: true});
			navigator.geolocation.getCurrentPosition(function(position) {
				$("#long").val(position.coords.longitude);
				$("#lati").val(position.coords.latitude);
				$.mobile.loading( 'hide');
			 // do_something(position.coords.latitude, position.coords.longitude);
			});
		} else {
		  alert("I'm sorry, but geolocation services are not supported by your browser or device.");
			$.mobile.loading( 'hide');
		}
	});
	
	$('#setLocationPageButton').tap(function() {	
		$("#long").val(settings.Lat);
		$("#lati").val(settings.Lon);
	});
	
	$('#saveLocationButton').tap(function() {	
		if($("#lati").val()){
			settings.Lat = $("#lati").val();
			settings.Lon = $("#long").val();
			if(typeof(Storage)!=="undefined")
			  {
				localStorage.Lat = settings.Lat;
				localStorage.Lon = settings.Lon;
				}
			Lat = settings.Lat;
			Lon = settings.Lon;
		}	
		
	});
	$('#prefButton').tap(function() {	
		$("#prefUnits").val(settings.units);
	});
	$('#prefSaveButton').tap(function() {	
		settings.units = $("#prefUnits").val();
		if(typeof(Storage)!=="undefined")
		  {
			localStorage.units = settings.units;
			}
		
	});
	
});







