/* ksun.js - Kaluach suntimes Javascript routines
 * Copyright (C) 5760-5763 (2000 - 2003 CE), by Abu Mami and Yisrael Hersch.
 *   All Rights Reserved.
 *   All copyright notices in this script must be left intact.
 * Based on:
 *   - PHP code that was translated by mattf@mail.com from the original perl
 *     module Astro-SunTime-0.01
 *	 - original version of ksun.js was based on the program SUN.C by Michael
 *     Schwartz, which was based on an algorithm contained in:
 *         Almanac for Computers, 1990
 *         published by Nautical Almanac Office
 *         United States Naval Observatory
 *         Washington, DC 20392
 * Permission will be granted to use this script on your web page
 *   if you wish. All that's required is that you please ask.
 *   (Of course if you want to send a few dollars, that's OK too :-)
 * website: http://www.kaluach.net
 * email: abumami@kaluach.org
 */

var MonthH = new Array("תשרי","חשון","כסליו","טבת","שבט","אדר (ראשון)","אדר שני","ניסן","אייר","סיון","תמוז","אב","אלול");
var MonthG = new Array ("ינואר","פברואר","מרץ","אפריל","מאי","יוני","יולי","אוגוסט","ספטמבר","אוקטובר","דצמבר");
var DateH = new Array ("א","ב","ג","ד","ה","ו","ז","ח","ט","י","יא","יב","יג","יד","טו","טז","יז","יח","יט","כ","כא","כב","כג","כד","כה","כו","כז","כח","כט","ל");
var DateG = new Array (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31);
function addOption(e,arr){
var objSelect=document.getElementsByName(e)[0];
var arrl= arr.length;var val = 1;
for (i=0;i<arrl;i++) {
var objOption = document.createElement("option");
objOption.text = arr[i];
objOption.value = val;
if(document.all && !window.opera)
  {objSelect.add(objOption);}
 else
  {objSelect.add(objOption, null);};
val++;}}
addOption('DateH',DateH);addOption('MonthH',MonthH);addOption('DateG',DateG);addOption('MonthG',MonthG);addOption('day',DateG);
function visible (vis,hid){ document.getElementById(vis).style.display="block"; document.getElementById(vis).style.visibility="visible"; document.getElementById(hid).style.display="none"; document.getElementById(hid).style.visibility="hidden"; } 

var monCount = new makeArray(1, 32, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366);

function makeArray() {
	this[0] = makeArray.arguments.length;
	for (i = 0; i < makeArray.arguments.length; i = i + 1)
		this[i+1] = makeArray.arguments[i];
}

function doy(d, m, y) {
	return monCount[m] + d + (m > 2 && leap(y));
}


function suntime(
	dy, mn, yr,
	sundeg, sunmin,
	londeg, lonmin, ew,
	latdeg, latmin, ns,
	timezone)
{
	var invalid = 0;	// start out as OK

	longitude = (londeg + lonmin/60.0) * ((ew == 0) ? -1 : 1);
	latitude  = (latdeg + latmin/60.0) * ((ns == 0) ? 1 : -1);

	var yday = doy(dy, mn, yr);

	var A = 1.5708; 
	var B = 3.14159; 
	var C = 4.71239; 
	var D = 6.28319;      
	var E = 0.0174533 * latitude; 
	var F = 0.0174533 * longitude; 
	var G = 0.261799 * timezone; 

	var R = Math.cos(0.01745 * (sundeg + sunmin/60.0));

	var J;

	// two times through the loop
	//    i=0 is for sunrise
	//    i=1 is for sunset
	for (i = 0; i < 2; i++) { 

		if(!i)
			J =  A;	// sunrise 
		else
			J = C;	// sunset

		var K = yday + ((J - F) / D); 
		var L = (K * .017202) - .0574039;              // Solar Mean Anomoly 
		var M = L + .0334405 * Math.sin(L);            // Solar True Longitude 
		M += 4.93289 + (3.49066E-04) * Math.sin(2 * L); 
		
		// Quadrant Determination 
		if (D == 0) {
			alert("Trying to normalize with zero offset...");
			exit;
		} 

		while(M < 0)
			M = (M + D);

		while(M >= D)
			M = (M - D);

		if ((M / A) - Math.floor(M / A) == 0)
			M += 4.84814E-06;

		var P = Math.sin(M) / Math.cos(M);                   // Solar Right Ascension 
		P = Math.atan2(.91746 * P, 1); 

		// Quadrant Adjustment 
		if (M > C)
			P += D;
		else {
			if (M > A)
				P += B;
		} 

		var Q = .39782 * Math.sin(M);      // Solar Declination 
		Q = Q / Math.sqrt(-Q * Q + 1);     // This is how the original author wrote it! 
		Q = Math.atan2(Q, 1); 

		var S = R - (Math.sin(Q) * Math.sin(E)); 
		S = S / (Math.cos(Q) * Math.cos(E)); 

		if(Math.abs(S) > 1)
			invalid = 1;	// uh oh! no sunrise/sunset

		S = S / Math.sqrt(-S * S + 1); 
		S = A - Math.atan2(S, 1); 

		if(!i)
			S = D - S;	// sunrise

		var T = S + P - 0.0172028 * K - 1.73364;  // Local apparent time 
		var U = T - F;                            // Universal timer 
		var V = U + G;                            // Wall clock time 
		
		// Quadrant Determination 
		if(D == 0) {
			alert("Trying to normalize with zero offset...");
			exit;
		} 
		
		while(V < 0)
			V = V + D;
		while(V >= D)
			V = V - D;
		V = V * 3.81972; 

		if(!i)
			sr = V;	// sunrise
		else
			ss = V;	// sunset
	} 

	var ret = new Object();
	ret[1] = invalid;
	ret[2] = sr;
	ret[3] = ss;
	return ret;
}


function timeadj(t, ampm) {
	var hour;
	var min;

	var time = t;

	var hour = Math.floor(time);
	var min  = Math.floor((time - hour) * 60.0 + 0.5);

	if(min >= 60) {
		hour += 1;
		min  -= 60;
	}

	if(hour < 0)
		hour += 24;

	if(ampm) {
		ampm_str = (hour > 11) ? ' PM' : ' AM';
		hour %= 12;
		hour = (hour < 1) ? 12 : hour;
	}
	else
		ampm_str = '';

	var str = hour + ':' + ((min < 10) ? '0' : '') + min + ampm_str;
//	var str = hour + ':' + min + ampm_str;
	return str;

}





/* kzman.js - Kaluach halachic times Javascript routines
 *   Version 0.01 (initial beta release)
 *   Version 0.02 (fixed bug in display of Shabbat times)
 *   Version 1.00 (fixed bug displaying locations at 0 deg lat/lon)
 *   Version 2.01 (handle invalid sunrise/set, different knissat shabbat times)
 * Copyright (C) 5760,5761 (2000 CE), by Abu Mami and Yisrael Hersch.
 *   All Rights Reserved.
 *   All copyright notices in this script must be left intact.
 * Acknowledgment given to scripts by:
 *   - P. Lutus <lutusp@arachnoid.com>
 *     available under the www.arachnoid.com CareWare program
 *	 - Tomer and Yehuda Shiran (docjs.com)
 *   - irt.org
 *   - javascripter.net
 * Permission will be granted to use this script on your web page
 *   if you wish. All that's required is that you please ask.
 *   (Of course if you want to send a few dollars, that's OK too :-)
 * website: http://www.kaluach.net
 * email: abumami@kaluach.org
 */


var month = 0, day = 0, year = 0;
var lat = 0, lng = 0;	// sun's location
var latd = -1, latm = 0;// lat on earth
var lngd = -1, lngm = 0;// long on earth
var ns = 'N', ew = 'E';	// hemisphere
var dst = 0;			// daylight saving time
var ampm = 0;			// am/pm or 24 hour display
var state = 0;


function display_m(m) {
state = m;
if (m == 0){
document.getElementById("israel").style.display="block";
document.getElementById("chul").style.display="none";
document.getElementById("spicel").style.display="none";
document.getElementById("wizard").style.height="140px";
}
else if (m == 1){
document.getElementById("chul").style.display="block";
document.getElementById("israel").style.display="none";
document.getElementById("spicel").style.display="none";
document.getElementById("wizard").style.height="140px";
}
else if (m == 2){
document.getElementById("spicel").style.display="block";
document.getElementById("israel").style.display="none";
document.getElementById("chul").style.display="none";
document.getElementById("wizard").style.height="170px";
man_pos();
var cooDate = new Date();
cooDate.setMonth(cooDate.getMonth() + 3);
document.cookie = "place=2=0;expires=" + cooDate;
}
}

function leap(y) {
	return ((y % 400 == 0) || (y % 100 != 0 && y % 4 == 0));
}

function civMonthLength(month, year) {
	if(month == 2)
		return 28 + leap(year);
	else if(month == 4 || month == 6 || month == 9 || month == 11)
	   return 30;
	else
		return 31;
}

function set_dst() {
	dst = document.data.dst.checked;
	doit("");
}


function change_year(num) {
	var y = parseInt(document.data.year.value);
	y += num;
	document.data.year.value = y;
	year = y;
	date_vars_doit();
}
function list_pos1(w) {

if (state == 0){
var cooDate = new Date();
cooDate.setMonth(cooDate.getMonth() + 3);
var city = document.data.israel_city.options.selectedIndex;
document.cookie = "place=" + state + "=" + city + "JJ;expires=" + cooDate;
}
list_pos(w);
}
function list_pos(w) {
var str, place, desc
	var i;

	i = w.options.selectedIndex;
	
	with(document.data) { // reset all prior selections
	israel_city.options[0].selected = 1;
	diaspora_city.options[0].selected = 1;
	}
	w.options[i].selected = 1; // restore current selection
	with (w) {
		desc = options[0].text;
		str = options[options.selectedIndex].value;
		place = options[options.selectedIndex].text;
		if(i == 0)
			document.data.placename.value = '';
	}

	i = str.indexOf(",");
	ns = str.substring(0, i);
	str = str.substring(i+1, str.length);

	i = str.indexOf(",");
	latd = eval(str.substring(0, i));
	str = str.substring(i+1, str.length);

	i = str.indexOf(",");
	latm = eval(str.substring(0, i));
	str = str.substring(i+1, str.length);

	i = str.indexOf(",");
	ew = str.substring(0, i);
	str = str.substring(i+1, str.length);

	i = str.indexOf(",");
	lngd = eval(str.substring(0, i));
	str = str.substring(i+1, str.length);

	i = str.indexOf(",");
	lngm = eval(str.substring(0, i));

	var tz = eval(str.substring(i+1, str.length));

	if((latd != -1) && (lngd != -1)) {
		document.data.tz.options[12+tz].selected = 1;
		doit("(" + desc + ") " + place);
	}

}

function man_pos() {

	latd = Math.abs(eval(document.data.latd.value));
	latm = Math.abs(eval(document.data.latm.value));
	ns = (document.data.lats[1].checked) ? 'S' : 'N';

	lngd = Math.abs(eval(document.data.lngd.value));
	lngm = Math.abs(eval(document.data.lngm.value));
	ew = (document.data.lngs[1].checked) ? 'E' : 'W';

	var tz = - (12 - document.data.tz.options.selectedIndex);
	document.data.tz.options[12+tz].selected = 1;
	doit("(manual entry)");
	return 1;
}

function doit(title) {

var path = window.location + ' ';
var fixpath = path.split(".info")
//alert(fixpath[0]);

if (fixpath[0] == 'http://hashabat') {
	var d, m, y;
	var nsi, ewi;
	var i;
 
	if(title != "")
		document.data.placename.value = title;
 
	document.data.latd.value = latd;
	document.data.latm.value = latm;
	i = ns.indexOf("N");
	nsi = (i != -1) ? 0 : 1;
	document.data.lats[nsi].checked = 1;
 
	document.data.lngd.value = lngd;
	document.data.lngm.value = lngm;
	i = ew.indexOf("W");
	ewi = (i != -1) ? 0 : 1;
	document.data.lngs[ewi].checked = 1;
 
	d = day + 1;
	m = month + 1;
	y = year;
 
	var adj = - (12 - document.data.tz.options.selectedIndex);
	adj += dst;

	var time;
	var sunrise, sunset;
	var shaa_zmanit;

	time = suntime(d, m, y, 90, 50, lngd, lngm, ewi, latd, latm, nsi, adj);
	if(time[1] == 0) {
		sunrise = time[2];
		sunset  = time[3];
		
		shaa_zmanit = (sunset - sunrise) / 12;
	}
	else {
		document.data.hanetz.value = "";
		document.data.shkia.value = "";
	}

	time = suntime(d, m, y, 106, 6, lngd, lngm, ewi, latd, latm, nsi, adj);
	time = suntime(d, m, y, 101, 0, lngd, lngm, ewi, latd, latm, nsi, adj);
	time = suntime(d, m, y, 96, 0, lngd, lngm, ewi, latd, latm, nsi, adj);
	

	

	var yom = new Date (y, m-1, d);
	if(yom.getDay() == 6) {

		// motzei shabbat (3 small stars)
		time = suntime(d, m, y, 98, 30, lngd, lngm, ewi, latd, latm, nsi, adj);
		if(time[1] == 0)
			document.getElementById("motzeiShabbat").innerHTML = timeadj(time[3], ampm);
		else
			document.getElementById("motzeiShabbat").innerHTML = "";

		// knissat shabbat (sunset from day before)
		var day_before = new Date(yom.getTime() - 86400000);
		db = day_before.getDate();
		mb = day_before.getMonth() + 1;
		yb = day_before.getYear();
		if(yb < 1900)
			yb += 1900;
		time = suntime(db, mb, yb, 90, 50, lngd, lngm, ewi, latd, latm, nsi, adj);
		if(document.data.placename.value == "(ישראל) ירושלים")
			document.getElementById("knissatShabbat").innerHTML = timeadj(time[3] - 40.0/60.0, ampm);
		else if(document.data.placename.value == "(ישראל) חיפה")
			document.getElementById("knissatShabbat").innerHTML = timeadj(time[3] - 30.0/60.0, ampm);
		else if(document.data.placename.value == "(ישראל) באר שבע")
			document.getElementById("knissatShabbat").innerHTML = timeadj(time[3] - 30.0/60.0, ampm);
		else if(document.data.placename.value == "(ישראל) קרני שומרון")
			document.getElementById("knissatShabbat").innerHTML = timeadj(time[3] - 22.0/60.0, ampm);
		else if(document.data.placename.value == "(ישראל) תל אביב")
			document.getElementById("knissatShabbat").innerHTML = timeadj(time[3] - 22.0/60.0, ampm);
		else if(document.data.placename.value == "(ישראל) קרני שומרון")
			document.getElementById("knissatShabbat").innerHTML = timeadj(time[3] - 22.0/60.0, ampm);
		else
			document.getElementById("knissatShabbat").innerHTML = timeadj(time[3] - 18.0/60.0, ampm);
	}
	else {
		document.data.motzeiShabbat.value = '';
		document.data.knissatShabbat.value = '';
	}

G2H(document.data.year.value, (document.data.month.selectedIndex+1), (document.data.day.selectedIndex+1));
    
	var makom = document.data.placename.value;
	var makomA = makom.split(" ");
	var makomB = makomA[1];
	if (makomA[2]) {
	makomB += ' ' + makomA[2];
	}
	if (makomB == 'entry)') {
	makomB = 'מקום בהתאמה אישית';
	}
	document.getElementById("makom").innerHTML = makomB;
	document.getElementById("year").innerHTML = document.data.year.value;
parsha();

}
}

function set_date_vars() {	

	var chekdate = new Date(document.data.year.value,document.data.month.selectedIndex,document.data.day.selectedIndex+1);
	 if (chekdate.getDay() != 6) {
while (chekdate.getDay() < 6) {
		chekdate= new Date (chekdate.valueOf()+(24*60*60*1000))
	}
	}
	var fixchekdate = chekdate.getDate();
	document.data.month.selectedIndex = chekdate.getMonth();
	document.data.day.selectedIndex = fixchekdate - 1;
	year = chekdate.getYear();
	if(year < 1900)
		year += 1900;
	document.data.year.value = year;
	
	month = document.data.month.selectedIndex;
	day   = document.data.day.selectedIndex;
	year  = document.data.year.value;

	var len = civMonthLength(month+1, year);
	if(day >= len) {
		day = len - 1;
		document.data.day.selectedIndex = day;
	}
	
}

function date_vars_doit() {
	set_date_vars();
auto_dst();
	doit("");
}

function set_default_date() {
	var now = new Date();
	if (now.getDay() != 6) {
while (now.getDay() < 6) {
		now = new Date (now.valueOf()+(24*60*60*1000))
	}
	}
	var d = now.getDate();
	var m = now.getMonth();
	year = now.getYear();
	if(year < 1900)
		year += 1900;
	document.data.month.selectedIndex = m;
	document.data.day.selectedIndex = d - 1;
	document.data.year.value = year;
auto_dst();
	set_date_vars("");
	
if (document.cookie.indexOf("place=") > -1){
var getCooBegin = document.cookie.indexOf("place=");
var getCooEND = document.cookie.indexOf("JJ");
var getCoo = document.cookie.substring(getCooBegin+6,getCooEND);
selPlace = getCoo.split("=");
document.data.mikum[selPlace[0]].checked = true;
display_m(selPlace[0]);
 cityPlace = selPlace[1];
if (selPlace[0] == 0){
document.data.israel_city.options[cityPlace].selected = 1; 
list_pos(document.data.israel_city);
}

}

}
function auto_dst() {
if (document.data.month.selectedIndex > 2 && document.data.month.selectedIndex < 8 ) {
	document.data.dst.checked = true; 
	dst = true;			// daylight saving time
	}
	else {
		document.data.dst.checked = false; 

	dst = 0;			// daylight saving time
}
	}

//spicel
//israel
//chul
////////////////////////////////////////////////////////
 // This function returns how many months there has been from the
  // first Molad until the beginning of the year nYearH
  function MonSinceFirstMolad(nYearH) {
    var nMonSinceFirstMolad
 
    // A shortcut to this function can simply be the following formula
    //   return Math.floor(((235 * nYearH) - 234) / 19)
    // This formula is found in Remy Landau's website and he
    // attributes it to Wolfgang Alexander Shochen. I will use a less
    // optimized function which I believe shows the underlying logic
    // better.
 
    // count how many months there has been in all years up to last
    // year. The months of this year hasn't happened yet.
    nYearH --
 
    // In the 19 year cycle, there will always be 235 months. That
    // would be 19 years times 12 months plus 7 extra month for the
    // leap years. (19 * 12) + 7 = 235.
 
    // Get how many 19 year cycles there has been and multiply it by
    // 235
    nMonSinceFirstMolad = Math.floor(nYearH / 19) * 235
    // Get the remaining years after the last complete 19 year cycle
    nYearH = nYearH % 19
    // Add 12 months for each of those years
    nMonSinceFirstMolad += 12 * nYearH
    // Add the extra months to account for the leap years
    if (nYearH >= 17) {
      nMonSinceFirstMolad += 6
    } else if  (nYearH >= 14) {
      nMonSinceFirstMolad += 5
    } else if  (nYearH >= 11) {
      nMonSinceFirstMolad += 4
    } else if  (nYearH >= 8) {
      nMonSinceFirstMolad += 3
    } else if  (nYearH >= 6) {
      nMonSinceFirstMolad += 2
    } else if  (nYearH >= 3) {
      nMonSinceFirstMolad += 1
    }
    return nMonSinceFirstMolad
  }
 
  // This function returns if a given year is a leap year.
  function IsLeapYear(nYearH) {
     var nYearInCycle
 
    // Find out which year we are within the cycle.  The 19th year of
    // the cycle will return 0
    nYearInCycle = nYearH % 19
    return ( nYearInCycle ==  3 ||
             nYearInCycle ==  6 ||
             nYearInCycle ==  8 ||
             nYearInCycle == 11 ||
             nYearInCycle == 14 ||
             nYearInCycle == 17 ||
             nYearInCycle == 0)
  }
 
  // This function figures out the Gregorian Date that corresponds to
  // the first day of Tishrei, the first month of the Hebrew
  // calendar, for a given Hebrew year.
  function Tishrei1(nYearH) {
    var nMonthsSinceFirstMolad
    var nChalakim
    var nHours
    var nDays
    var nDayOfWeek
    var dTishrei1
 
    // We want to calculate how many days, hours and chalakim it has
    // been from the time of 0 days, 0 hours and 0 chalakim to the
    // molad at the beginning of year nYearH.
    //
    // The period between one new moon to the next is 29 days, 12
    // hours and 793 chalakim. We must multiply that by the amount
    // of months that transpired since the first molad. Then we add
    // the time of the first molad (Monday, 5 hours and 204 chalakim)
    nMonthsSinceFirstMolad = MonSinceFirstMolad(nYearH)
    nChalakim = 793 * nMonthsSinceFirstMolad
    nChalakim += 204
    // carry the excess Chalakim over to the hours
    nHours = Math.floor(nChalakim / 1080)
    nChalakim = nChalakim % 1080
 
    nHours += nMonthsSinceFirstMolad * 12
    nHours += 5
 
    // carry the excess hours over to the days
    nDays = Math.floor(nHours / 24)
    nHours = nHours % 24
 
    nDays += 29 * nMonthsSinceFirstMolad
    nDays += 2
 
    // figure out which day of the week the molad occurs.
    // Sunday = 1, Moday = 2 ..., Shabbos = 0
    nDayOfWeek = nDays % 7
 
    // In a perfect world, Rosh Hashanah would be on the day of the
    // molad. The Hebrew calendar makes four exceptions where we
    // push off Rosh Hashanah one or two days. This is done to
    // prevent three situation. Without explaining why, the three
    // situations are:
    //   1) We don't want Rosh Hashanah to come out on Sunday,
    //      Wednesday or Friday
    //   2) We don't want Rosh Hashanah to be on the day of the
    //      molad if the molad occurs after the beginning of 18th
    //      hour.
    //   3) We want to limit years to specific lengths.  For non-leap
    //      years, we limit it to either 353, 354 or 355 days.  For
    //      leap years, we limit it to either 383, 384 or 385 days.
    //      If setting Rosh Hashanah to the day of the molad will
    //      cause this year, or the previous year to fall outside
    //      these lengths, we push off Rosh Hashanah to get the year
    //      back to a valid length.
    // This code handles these exceptions.
    if (!IsLeapYear(nYearH) &&
        nDayOfWeek == 3 &&
        (nHours * 1080) + nChalakim >= (9 * 1080) + 204) {
      // This prevents the year from being 356 days. We have to push
      // Rosh Hashanah off two days because if we pushed it off only
      // one day, Rosh Hashanah would comes out on a Wednesday. Check
      // the Hebrew year 5745 for an example.
      nDayOfWeek = 5
      nDays += 2
    }
    else if ( IsLeapYear(nYearH - 1) &&
              nDayOfWeek == 2 &&
              (nHours * 1080) + nChalakim >= (15 * 1080) + 589 ) {
      // This prevents the previous year from being 382 days. Check
      // the Hebrew Year 5766 for an example. If Rosh Hashanah was not
      // pushed off a day then 5765 would be 382 days
      nDayOfWeek = 3
      nDays += 1
    }
    else {
      // see rule 2 above. Check the Hebrew year 5765 for an example
      if (nHours >= 18) {
        nDayOfWeek += 1
        nDayOfWeek = nDayOfWeek % 7
        nDays += 1
      }
      // see rule 1 above. Check the Hebrew year 5765 for an example
      if (nDayOfWeek == 1 ||
          nDayOfWeek == 4 ||
          nDayOfWeek == 6) {
        nDayOfWeek += 1
        nDayOfWeek = nDayOfWeek % 7
        nDays += 1
      }
    }
 
    // Here we want to add nDays to creation
    //    dTishrie1 = creation + nDays
    // Unfortunately, Many languages do not handle negative years very
    // well. I therefore picked a Random date (1/1/1900) and figured out
    // how many days it is after the creation (2067025). Then I
    // subtracted 2067025 from nDays.
    nDays -= 2067025
    dTishrei1 = new Date(1900, 0, 1) // 2067025 days after creation
    dTishrei1.setDate(dTishrei1.getDate() + nDays)
 
    return dTishrei1
   }
 
 
  // This function gets the length of a Hebrew year.
  function LengthOfYear(nYearH) {
    var dThisTishrei1
    var dNextTishrei1
    var diff
 
    // subtract the date of this year from the date of next year
    dThisTishrei1 = Tishrei1(nYearH)
    dNextTishrei1 = Tishrei1(nYearH + 1)
    // Java's dates are stored in milliseconds. To convert it into days
    // we have to divide it by 1000 * 60 * 60 * 24
    diff = (dNextTishrei1 - dThisTishrei1) / ( 1000 * 60 * 60 * 24)
    return Math.round(diff)
  }
 
  // This function converts a Hebrew date into the Gregorian date
  // nYearH - is the Hebrew year
  // nMonth - Tishrei=1
  //          Cheshvan=2
  //          Kislev=3
  //          Teves=4
  //          Shevat=5
  //          Adar A=6 (only valid on leap years)
  //          Adar=7   (Adar B for leap years)
  //          Nisan=8
  //          Iyar=9
  //          Sivan=10
  //          Tamuz=11
  //          Av=12
  //          Elul=13
  function HebToGreg(nYearH, nMonthH, nDateH) {
    var nLengthOfYear
    var bLeap
    var dGreg
    var nMonth
    var nMonthLen
    var bHaser
    var bShalem
 
    bLeap = IsLeapYear(nYearH)
    nLengthOfYear = LengthOfYear(nYearH)
 
    // The regular length of a non-leap year is 354 days.
    // The regular length of a leap year is 384 days.
    // On regular years, the length of the months are as follows
    //   Tishrei (1)   30
    //   Cheshvan(2)   29
    //   Kislev  (3)   30
    //   Teves   (4)   29
    //   Shevat  (5)   30
    //   Adar A  (6)   30     (only valid on leap years)
    //   Adar    (7)   29     (Adar B for leap years)
    //   Nisan   (8)   30
    //   Iyar    (9)   29
    //   Sivan   (10)  30
    //   Tamuz   (11)  29
    //   Av      (12)  30
    //   Elul    (13)  29
    // If the year is shorter by one less day, it is called a haser
    // year. Kislev on a haser year has 29 days. If the year is longer
    // by one day, it is called a shalem year. Cheshvan on a shalem
    // year is 30 days.
 
    bHaser = (nLengthOfYear == 353 || nLengthOfYear == 383)
    bShalem = (nLengthOfYear == 355 || nLengthOfYear == 385)
 
    // get the date for Tishrei 1
    dGreg = Tishrei1(nYearH)
 
    // Now count up days within the year
    for (nMonth = 1; nMonth <= nMonthH - 1; nMonth ++) {
      if (nMonth == 1 ||
          nMonth == 5 ||
          nMonth == 8 ||
          nMonth == 10 ||
          nMonth == 12 ) {
        nMonthLen = 30
      } else if (nMonth == 4 ||
                 nMonth == 7 ||
                 nMonth == 9 ||
                 nMonth == 11 ||
                 nMonth == 13 ) {
          nMonthLen = 29
      } else if (nMonth == 6) {
          nMonthLen = (bLeap ? 30 : 0)
      } else if (nMonth == 2) {
          nMonthLen = (bShalem ? 30 : 29)
      } else if (nMonth == 3) {
          nMonthLen = (bHaser ? 29 : 30 )
      }
      dGreg.setDate(dGreg.getDate() + nMonthLen)
    }
    dGreg.setDate(dGreg.getDate() + nDateH - 1)
    return dGreg
  }
 
  // This function converts a Gregorian date into the Hebrew date.  The
  // function returns the hebrew month as a string in the format M/D/Y.
  // See function HebToGreg() for the definition of the month numbers.
  function GregToHeb(dGreg) {
    var nYearH
    var nMonthH
    var nDateH
    var nOneMolad
    var nAvrgYear
    var nDays
    var dTishrei1
    var nLengthOfYear
    var bLeap
    var bHaser
    var bShalem
    var nMonthLen
    var bWhile
    var d1900 = new Date(1900, 0, 1)
 
    // The basic algorythm to get Hebrew date for the Gregorian date dGreg.
    // 1) Find out how many days dGreg is after creation.
    // 2) Based on those days, estimate the Hebrew year
    // 3) Now that we a good estimate of the Hebrew year, use brute force to
    //    find the Gregorian date for Tishrei 1 prior to or equal to dGreg
    // 4) Add to Tishrei 1 the amount of days dGreg is after Tishrei 1
 
    // Figure out how many days are in a month.
    // 29 days + 12 hours + 793 chalakim
    nOneMolad = 29 + (12 / 24) + (793 / (1080 * 24))
    // Figure out the average length of a year. The hebrew year has exactly
    // 235 months over 19 years.
    nAvrgYear = nOneMolad * (235 / 19)
    // Get how many days dGreg is after creation. See note as to why I
    // use 1/1/1900 and add 2067025
    nDays = Math.round((dGreg - d1900) / (24 * 60 * 60 * 1000))
    nDays += 2067025 // 2067025 days after creation
    // Guess the Hebrew year. This should be a pretty accurate guess.
    nYearH = Math.floor(nDays / nAvrgYear) + 1
    // Use brute force to find the exact year nYearH. It is the Tishrei 1 in
    // the year <= dGreg.
    dTishrei1 = Tishrei1(nYearH)
 
    if (SameDate(dTishrei1, dGreg)) {
      // If we got lucky and landed on the exact date, we can stop here
      nMonthH = 1
      nDateH = 1
    }
    else  {
      // Here is the brute force.  Either count up or count down nYearH
      // until Tishrei 1 is <= dGreg.
      if (dTishrei1 < dGreg) {
        // If Tishrei 1, nYearH is less than dGreg, count nYearH up.
        while (Tishrei1(nYearH + 1) <= dGreg) {
          nYearH += 1
        }
      }
      else {
        // If Tishrei 1, nYearH is greater than dGreg, count nYearH down.
        nYearH -= 1
        while (Tishrei1(nYearH) > dGreg) {
          nYearH -= 1
        }
      }
 
      // Subtract Tishrei 1, nYearH from dGreg. That should leave us with
      // how many days we have to add to Tishrei 1
      nDays = (dGreg - Tishrei1(nYearH)) / (24 * 60 * 60 * 1000)
      nDays = Math.round(nDays)
      // Find out what type of year it is so that we know the length of the
      // months
      nLengthOfYear = LengthOfYear(nYearH)
      bHaser = nLengthOfYear == 353 || nLengthOfYear == 383
      bShalem = nLengthOfYear == 355 || nLengthOfYear == 385
      bLeap = IsLeapYear(nYearH)
 
      // Add nDays to Tishrei 1.
      nMonthH = 1
      do {
 
        switch (nMonthH) {
          case 1:
          case 5:
          case 6:
          case 8:
          case 10:
          case 12:
            nMonthLen = 30
            break
          case 4:
          case 7:
          case 9:
          case 11:
          case 13:
            nMonthLen = 29
            break
          case 6: // Adar A (6) will be skipped on non-leap years
            nMonthLen = 30
            break
          case 2: // Cheshvan, see note above
            nMonthLen = (bShalem ? 30 : 29)
            break
          case 3: // Kislev, see note above
            nMonthLen = (bHaser ? 29: 30)
            break
        }
 
        if (nDays >= nMonthLen) {
          bWhile = true
          if (bLeap || nMonthH != 5) {
            nMonthH ++
          }
          else {
            // We can skip Adar A (6) if its not a leap year
            nMonthH += 2
          }
          nDays -= nMonthLen
        }
        else {
          bWhile = false
        }
      } while (bWhile)
      //Add the remaining days to Date
      nDateH = nDays + 1
    }
    return nMonthH + "/" + number2hebrew(nDateH) + "/" + number2hebrew(nYearH)
  }
 
  function SameDate(d1, d2) {
    return (d1.getFullYear() == d2.getFullYear() && 
            d1.getMonth() == d2.getMonth() && 
            d1.getDate() == d2.getDate())
             
  } 
  
// Here are a few support functions for the sample web page
 
  function FormatDateH(cDate) {
    var aDate = new Array()
    var cFormatDate
 
    aDate = cDate.split("/")
    switch (Number(aDate[0])) {
      case 1:
        cFormatDate = "תשרי"
        break
      case 2:
        cFormatDate = "חשון"
        break
      case 3:
        cFormatDate = "כסליו"
        break
      case 4:
        cFormatDate = "טבת"
        break
      case 5:
        cFormatDate = "שבט"
        break
      case 6:
        cFormatDate = "אדר ראשון"
        break
      case 7:
        cFormatDate = (IsLeapYear(Number(aDate[2])) ? "אדר שני" : "אדר")
        break
      case 8:
        cFormatDate = "ניסן"
        break
      case 9:
        cFormatDate = "אייר"
        break
      case 10:
        cFormatDate = "סיון"
        break
      case 11:
        cFormatDate = "תמוז"
        break
      case 12:
        cFormatDate = "אב"
        break
      case 13:
        cFormatDate = "אלול"
        break
    }
    FixcFormatDate = aDate[1] + " " + cFormatDate + " " +  aDate[2]
    return FixcFormatDate
  }
 
  function FormatDate(dDate) {
    var sDate
    switch (dDate.getDay()) {
      case 0:
        sDate = "יום ראשון "
        break
      case 1:
        sDate = "יום שני "
        break
      case 2:
        sDate = "יום שלישי "
        break
      case 3:
        sDate = "יום רביעי "
        break
      case 4:
        sDate = "יום חמישי "
        break
      case 5:
        sDate = "יום שישי "
        break
      case 6:
        sDate = "שבת "
        break
     }
    sDate += dDate.getDate() + "/"
    sDate += (dDate.getMonth() + 1) + "/"
    sDate += dDate.getFullYear()
    return sDate
  }
var letters1 = 'אבגדהוזחטי';
var letters2 = 'יכלמנסעפצק';
var letters3 = 'קרשת';
var letters4 = 'אבגדה';
function number2hebrew(num) {
	heb = "";
	while (num > 1000) {
		heb += letters4.charAt((num / 1000) - 1);
			heb += "'";
		num %= 1000;
	}
	while (num > 400) {
		heb += "ת";
		num -= 400;
	}
	if (num >= 100) {
		heb += letters3.charAt((num / 100) - 1);
		num %= 100;
	}
	if (num >= 10) {
		if (num == 15) {
			heb += 'טו';
			num = 0;
		}
		else if (num == 16) {
			heb += 'טז';
			num = 0;
		}
		else {
			heb += letters2.charAt( (num / 10) - 1 );
			num %= 10;
			
		}
	}
	if (num >= 1) {
		heb += letters1.charAt( num - 1 );
	}
	if ( heb.length > 1 ) {
		
		heb = heb.slice( 0, heb.length - 1) + '"' + heb.charAt( heb.length-1 ) ;
 }
	if ( heb.length == 1 ) {
		
		heb += "'";
 }

 return heb;
	//document.getElementById("result1").innerHTML = heb;
}
 
 
 
function nextLetter(letter) {
	var num = hebrew2number(letter);
	return number2hebrew(num+1);
}
 
 
function previousLetter(letter) {
	var num = hebrew2number(letter);
	return num>1? number2hebrew(num-1): "";
}
  
  function G2H(nYearG, nMonthG, nDateG) {
    var nYearH
    var nMonthH
    var nDateH
    var dGreg
 
    nYearG  = Number(nYearG)
    nMonthG = Number(nMonthG)
    nDateG  = Number(nDateG)
    dGreg   = new Date(nYearG, nMonthG - 1, nDateG)
     
 
 
    //alert(FormatDate(dGreg) + " = " + FormatDateH(GregToHeb(dGreg)))
    document.getElementById("hdate").innerHTML = FormatDateH(GregToHeb(dGreg)) + ",";
   ("<p>")
  }
  
  
 function parsha() {
  //origenal code was made by Joel M. Hoffman from http://www.lashon.net/Parashah.html

var parshiyot = new Array(new Array(2005,9,08,'Vayeilech'),new Array(2009,6,18,'מטות-מסעי'),new Array(2009,6,25,'דברים'),new Array(2009,7,01,'ואתחנן'),new Array(2009,7,08,'עקב'),new Array(2009,7,15,'ראה'),
new Array(2009,7,22,'שופטים'),new Array(2009,7,29,'כי תצא'),new Array(2009,8,05,'כי תבוא'),new Array(2009,8,12,'נצבים-וילך'),new Array(2009,8,26,'האזינו'),new Array(2009,9,17,'בראשית'),new Array(2009,9,24,'נח'),
new Array(2009,9,31,'לך לך'),new Array(2009,10,07,'וירא'),new Array(2009,10,14,'חיי שרה'),new Array(2009,10,21,'תולדות'),new Array(2009,10,28,'ויצא'),new Array(2009,11,05,'וישלח'),new Array(2009,11,12,'וישב'),
new Array(2009,11,19,'מקץ'),new Array(2009,11,26,'ויגש'),new Array(2010,0,02,'ויחי'),new Array(2010,0,09,'שמות'),new Array(2010,0,16,'וארא'),new Array(2010,0,23,'בא'),new Array(2010,0,30,'בשלח'),new Array(2010,1,06,'יתרו'),
new Array(2010,1,13,'משפטים'),new Array(2010,1,20,'תרומה'),new Array(2010,1,27,'תצוה'),new Array(2010,2,06,'כי תשא'),new Array(2010,2,13,'ויקהל-פקודי (שבת החודש)'),new Array(2010,2,20,'ויקרא'),new Array(2010,2,27,'צו (שבת הגדול)'),new Array(2010,3,10,'שמיני'),new Array(2010,3,17,'תזריע-מצורע'),new Array(2010,3,24,'אחרי מות-קדושים'),new Array(2010,4,01,'אמור'),new Array(2010,4,08,'בהר-בחוקותי'),new Array(2010,4,15,'במדבר'),
new Array(2010,4,22,'נשא'),new Array(2010,4,29,'בהעלותך'),new Array(2010,5,05,'שלח'),new Array(2010,5,12,'קרח'),new Array(2010,5,19,'חוקת'),new Array(2010,5,26,'בלק'),new Array(2010,6,03,'פנחס'),new Array(2010,6,10,'מטות-מסעי'),new Array(2010,6,17,'דברים'),new Array(2010,6,24,'ואתחנן'),new Array(2010,6,31,'עקב'),new Array(2010,7,07,'ראה'),new Array(2010,7,14,'שופטים'),new Array(2010,7,21,'כי תצא'),new Array(2010,7,28,'כי תבוא'),
new Array(2010,8,04,'נצבים-וילך'),new Array(2010,8,11,'האזינו'),new Array(2010,8,18,'יום כיפור'),new Array(2010,8,25,'חול המועד סוכות'),new Array(2010,9,02,'בראשית'),new Array(2010,9,9,'נח'),new Array(2010,9,16,'לך-לך'),
new Array(2010,9,23,'וירא'),new Array(2010,9,30,'חיי שרה'),new Array(2010,10,06,'תולדות'),new Array(2010,10,13,'ויצא'),new Array(2010,10,20,'וישלח'),new Array(2010,10,27,'וישב'),new Array(2010,11,04,'מקץ'),
new Array(2010,11,11,'ויגש'),new Array(2010,11,18,'ויחי'),new Array(2010,11,25,'שמות'),new Array(2011,0,01,'וארא'),new Array(2011,0,08,'בא'),new Array(2011,0,15,'בשלח'),new Array(2011,0,22,'יתרו'),new Array(2011,0,29,'משפטים'),new Array(2011,1,05,'תרומה'),new Array(2011,1,12,'תצוה'),new Array(2011,1,19,'כי תשא'),new Array(2011,1,26,'ויקהל'),new Array(2011,2,05,'פקודי'),new Array(2011,2,12,'ויקרא'),
new Array(2011,2,19,'צו'),new Array(2011,2,26,'שמיני'),new Array(2011,3,02,'תזריע'),new Array(2011,3,09,'מצורע'),new Array(2011,3,16,'אחרי'),new Array(2011,3,23,'חול המועד פסח'),new Array(2011,3,30,'קדושים'),
new Array(2011,4,07,'אמור'),new Array(2011,4,14,'בהר'),new Array(2011,4,21,'בחוקותי'),new Array(2011,4,28,'במדבר'),new Array(2011,5,04,'נשא'),new Array(2011,5,11,'בהעלותך'),new Array(2011,5,18,'שלח'),
new Array(2011,5,25,'קרח'),new Array(2011,6,02,'חקת'),new Array(2011,6,09,'בלק'),new Array(2011,6,16,'פנחס'),new Array(2011,6,23,'מטות'),new Array(2011,6,30,'מסעי'),new Array(2011,7,06,'דברים'),new Array(2011,7,13,'ואתחנן'),
new Array(2011,7,20,'עקב'),new Array(2011,7,27,'ראה'),new Array(2011,8,03,'שופטים'),new Array(2011,8,10,'כי תצא'),new Array(2011,8,17,'כי תבוא'),new Array(2011,8,24,'נצבים וילך'),new Array(2011,9,01,'האזינו'),
new Array(2011,9,08,'יום כיפור'),new Array(2011,9,15,'חול המועד סוכות'),new Array(2011,9,22,'בראשית'),new Array(2011,9,29,'נח'),new Array(2011,10,05,'לך-לך'),new Array(2011,10,12,'וירא'),new Array(2011,10,19,'חיי שרה'),
new Array(2011,10,26,'תולדות'),new Array(2011,11,03,'ויצא'),new Array(2011,11,10,'וישלח'),new Array(2011,11,17,'וישב'),new Array(2011,11,24,'מקץ'),new Array(2011,11,31,'ויגש'),new Array(2012,0,07,'ויחי'),new Array(2012,0,14,'שמות'),new Array(2012,0,21,'וירא'),new Array(2012,0,28,'בא'),new Array(2012,1,04,'וישלח'),new Array(2012,1,11,'יתרו'),new Array(2012,1,18,'משפטים'),new Array(2012,1,25,'תרומה'),new Array(2012,2,03,'תצוה'),
new Array(2012,2,10,'כי תשא'),new Array(2012,2,17,'ויקהל-פקודי'),new Array(2012,2,24,'ויקרא'),new Array(2012,2,31,'צו'),new Array(2012,3,07,'פסח'),new Array(2012,3,14,'שמיני (ישראל)'),new Array(2012,3,21,'תזריע-מצורע (ישראל)'),
new Array(2012,3,28,'אחרי קדושים (ישראל)'),new Array(2012,4,05,'אמור (ישראל)'),new Array(2012,4,12,'בהר (ישראל)'),new Array(2012,4,19,'בחוקותי (ישראל)'),new Array(2012,4,26,'במדבר'),new Array(2012,5,02,'נשא'),new Array(2012,5,09,'בהעלותך'),new Array(2012,5,16,'שלח'),new Array(2012,5,23,'קרח'),new Array(2012,5,30,'חקת'),new Array(2012,6,07,'בלק'),new Array(2012,6,14,'פנחס'),new Array(2012,6,21,'מטות מסעי'),new Array(2012,6,28,'דברים'), new Array(2012,7,04,'ואתחנן'),new Array(2012,7,11,'עקב'),new Array(2012,7,18,'ראה'),new Array(2012,7,25,'שופטים'),new Array(2012,8,01,'כי תצא'),new Array(2012,8,08,'כי תבוא'),new Array(2012,8,15,'נצבים'),
new Array(2012,8,22,'וילך'),new Array(2012,8,29,'האזינו'),new Array(2012,9,06,'חול המועד סוכות'),new Array(2012,9,13,'בראשית'),new Array(2012,9,20,'נח'),new Array(2012,9,27,'לך-לך'),new Array(2012,10,03,'וירא'),
new Array(2012,10,10,'חיי שרה'),new Array(2012,10,17,'תולדות'),new Array(2012,10,24,'ויצא'),new Array(2012,11,01,'וישלח'),new Array(2012,11,08,'וישב'),new Array(2012,11,15,'מקץ'),new Array(2012,11,22,'ויגש'),
new Array(2012,11,29,'ויחי'),new Array(2013,0,05,'שמות'),new Array(0,0));

	var parshadate = new Date(document.data.year.value,document.data.month.selectedIndex,document.data.day.selectedIndex+1);
var t_date = parshadate.getDate();
var t_month = parshadate.getMonth();
var t_year = parshadate.getYear();
if (t_year < 1900) {
t_year += 1900
}
var fuldate = t_year+' '+t_month+' '+t_date;
var arr_length = parshiyot.length;
document.getElementById("parsha").innerHTML = ' ';
for (i=1; i<arr_length; i++) {
//alert(parshiyot[i][3]);
var par_loop = parshiyot[i][0]+' '+parshiyot[i][1]+' '+parshiyot[i][2];
if ( par_loop == fuldate ) {
document.getElementById("parsha").innerHTML = 'פרשת השבוע: ' + parshiyot[i][3];
i = arr_length+1;}}}

set_default_date();
list_pos(document.data.israel_city);
document.getElementById("wizard").style.border="1px solid #ccc";
document.getElementById("wizard").style.height="140px";
