﻿engMonths=["January","February","March","April","May","June","July","August","September","October","November","December"];
engDatePat = /^(\d{1,2})(\/)(\d{1,2})\2(\d{4})$/;
hebDatePat = /^(\d{1,2})\s([a-zA-Z]*(?: I+)?)\s(\d{4})$/;
	
// global javascript variables
var engMonth, engYear, engMonth_w, engMonth_t;
var hebrewMonthNum = new Array();
hebrewMonthNum["Nisan"] = 1;
hebrewMonthNum["Iyar"] = 2;
hebrewMonthNum["Sivan"] = 3;
hebrewMonthNum["Tamuz"] = 4;
hebrewMonthNum["Av"] = 5;
hebrewMonthNum["Elul"] = 6;
hebrewMonthNum["Tishrei"] = 7;
hebrewMonthNum["Cheshvan"] = 8;
hebrewMonthNum["Kislev"] = 9;
hebrewMonthNum["Tevet"] = 10;
hebrewMonthNum["Shevat"] = 11;
hebrewMonthNum["Adar"] = 12;
hebrewMonthNum["AdarI"] = 12;
hebrewMonthNum["AdarII"] = 13;
hebrewMonthNum["Adar I"] = 12;
hebrewMonthNum["Adar II"] = 13;
var currDateStrForLocation;  // format MM/DD/YYYY
var tabID;  // the selected tab in the tabbed table (starts at 1)
var gVisitedCellsArray = new Array();
// the English day in month of the cell which is currently "expanded" - default 0
var gExpandedCellDayInMonth = 0;
// a comma-separated list of the English day in month for the cells in MonthView 
// that were "visited" by user and now show partial zmanim info
var gVisitedCellsDaysInMonth = "";  
var former_selected_DateCell;
var monthViewDataUpdated = false;

var monthDisplayUpdated = false;

var curr_city = "";
var curr_region = "";
var curr_country = "";
var location_string = "";

// global arrays storing JSON response of holiday dates for two-yr period
var holCalData;
var holDateYr1;
var holDateYr2;
var holLevel;
var dayInMonthInfo = new Array();  // global array - JSON data for each date in month
var location_cnt = 0;
var location_data = null;
var fDisplayDailyZmanim = "true";

var tabIDMonth = 1;

var tabName = new Array();
tabName[1] = "month";

function LocData(city, region, country, lat, long, community_id, timezone) {
	this.city = city;
	this.region = region;
	this.country = country;
	this.lat = lat;
	this.long = long;
	this.community_id = community_id;
	this.timezone = timezone;
}
// global object storing location data
var locData; 

function getDataURL(requestType, updateType, i_engDate) {
	//dataURL =  "http://www.ou.org.php5-3.websitetestlink.com/ou_services/getCalendarData2.php";
	dataURL =  "http://www.ou.org/ou_services/getCalendarData.php";
	startDate = engMonth + "/1/" + engYear;
	if (requestType == "monthView") {
		mode="month";
		numberOfResults= engMonth_t+6;
		zmanim = "none";
	} else if (requestType == "singleDayInMonth"){
		mode="day";
		numberOfResults= 1;
		zmanim = "all";
		startDate = i_engDate;
	} else if (requestType == "holidayCal"){	
		dataURL = "http://www.ou.org/holidays/getHolidayCalData2" + "?year=" + yearForHolidayCal;
		return dataURL;
	}
	dataURL +=  "?mode=" + mode;

	dataURL += "&startDate=" + startDate +  "&numberOfResults=" + numberOfResults + "&lat=" + locData.lat + "&long=" + locData.long + "&timezone=" + locData.timezone + "&zmanim=" + zmanim;
	if (locData.city == "Jerusalem")
		dataURL += "&candles_offset=40";
	if (locData.country == "IL")
		dataURL += "&holidays=israel";
	if (requestType == "monthView" && gExpandedCellDayInMonth != "0"){
		//alert("selDay= " + gExpandedCellDayInMonth + ", visitedDays=" + gVisitedCellsDaysInMonth);
		dataURL += "&selectedDay=" +gExpandedCellDayInMonth;
	}
	if (requestType == "monthView" && gVisitedCellsDaysInMonth != ""){	
		dataURL = dataURL + "&visitedDays="+gVisitedCellsDaysInMonth;
	}

	if (requestType == "monthView") {
		var currDateStrParsed = currDateStrForLocation.split("/");
		if (currDateStrParsed[0] == engMonth && currDateStrParsed[2] == engYear)
			dataURL = dataURL + "&today=" + currDateStrForLocation;
	}
	//alert(dataURL);
	return dataURL;
}

function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	//alert('Query Variable ' + variable + ' not found');
	return "";
} 
function js_trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // ends js_trim

function clearCalendar(updateType) {
	// contract the cell in monthView that was expanded, if type is switchMonth
	if (updateType == "switchMonth" && oldTD != null) {resizeThis(oldTD);}	

	// clear the HTML elements
	$jq(".standardCalDay").html('-');
	
	// clear the array of visited Cells, for switchMonth
	if (updateType == "switchMonth") {
		gVisitedCellsArray = new Array();
		$jq(".currCalDay").removeClass("currCalDay");
	}
	
	// clear stored calendar info for month, for both switchMonth and switchLocation
	dayInMonthInfo = new Array();
	
	// clear the global status flags
	monthViewDataUpdated = false;
	
	monthDisplayUpdated = false;
}
function getTDEnglishDate(row, col) {
	//return "row="+ row + ",col=" + col;
	var tdDate = new Date();
	tdDate.setDate(1);
	tdDate.setMonth(engMonth - 1);
	tdDate.setFullYear(engYear);
	var dateInMonth = (7 * parseInt(row)) + parseInt(col) - engMonth_w + 1;
	tdDate.setDate(dateInMonth);
	return (tdDate.getMonth() + 1) + "/" + tdDate.getDate() + "/" + tdDate.getFullYear();
}
function js_convert_time(str_time, show_ampm) {
	var retval;
	retval = str_time;

	var ampm = "";
	var str_array = new Array();
	str_array = str_time.split(':');
	var hval = parseInt(str_array[0], 10);
	var mval = parseInt(str_array[1], 10);
	var sval = parseInt(str_array[2], 10);
	var mval_str;
	//retval = hval;

	if (sval >= 30) {
		mval = mval + 1;
		if (mval >= 60) {
			mval = mval - 60;
			hval = hval + 1;
		}
	}
	var mval_str = mval;
	if (mval < 10) {
		mval_str = '0' + mval_str;
	}
        
	if (hval >= 12) {
	    ampm = "pm";
		if (hval >= 13) {
	            hval = hval - 12;
	        }
	} else {
		ampm = "am";
        }
        
	retval = hval + ":" + mval_str + (show_ampm != "n" ? ampm : "");

	return retval;
}
function getDayInMonth(someID) {
	var row = someID.split("_")[1];
	var col = someID.split("_")[2];
	return 7 * parseInt(row) + parseInt(col) - engMonth_w + 1;
}

function getTDId(engDateInMonthAsStr) {
	var locInGrid;
	if (parseInt(data_engMonth) = parseInt(engMonth)) {
		locInGrid = engMonth_w + parseInt(engDateInMonthAsStr) - 1;
		}
	else {
		locInGrid = engMonth_w + entMonth_t + parseInt(engDateInMonthAsStr) -1;
		}
	var col = locInGrid % 7;
	var row = Math.floor(locInGrid / 7);
	return "#dayTD_" + row + "_" + col;
}

function getJSONCellData(someID) {
	// parse the id to get the row and column of the cell
	var row = someID.split("_")[1];
	var col = someID.split("_")[2];
	var thisDaysInfo = dayInMonthInfo[7 * parseInt(row) + parseInt(col) - engMonth_w];
	
	// if the full zmanim already exist for this cell, don't fetch them   
	if (thisDaysInfo.zmanim  != null && thisDaysInfo.zmanim.alos_gra != null) {
		// if the non-basic zmanim are already in the DOM for this date, just display them
		if ($jq("#"+someID).find(".nonBasicZmanInDateCell").length >0) {
			$jq("#"+someID).find(".nonBasicZmanInDateCell").css("display", "block");
		} else {
			$jq("#"+someID).find(".zmanimInDateCell").html(buildDOMtoDisplayFullZmanimInCell(row, col));
		}
	} else {
		// fetch the full zmanim for the single date
		var engDate = getTDEnglishDate(row,col);
    	request = new XssHttpRequest();
		var url_cell = getDataURL("singleDayInMonth", "", engDate);
    	request.open("GET", url_cell, true);
    	request.onreadystatechange=function() {
        	if(request.readyState==4) {
            	alert('Completed request: ' + request.responseText);
            	eval('processJSONSingleCellData(' + request.responseText + ')'); 
        	}
    	}
    	request.send(null);
	}
}
function processJSONSingleCellData(r) {
	var myDayInfo = r.days[0];

        //alert("in function processJSONSingleCellData");
	var engDateStr = myDayInfo.engDateString;
    // the date string returned in the JSON has format MM/DD/YYYY
	if (engDateStr == null)
		return;
	var engMatchArray = engDateStr.match(engDatePat);
	var data_engMonth = engMatchArray[1];
	var data_engDateInMonth = engMatchArray[3];
	var data_year = engMatchArray[4];
	dayInMonthInfo[parseInt(data_engDateInMonth) - 1] = myDayInfo;	
	
	var locInGrid = engMonth_w + parseInt(data_engDateInMonth) - 1;
	var col = locInGrid % 7;
	var row = Math.floor(locInGrid / 7);
	var dayTD = $jq("#dayTD_" + row + "_" + col);
	if (former_selected_DateCell) {
		former_selected_DateCell.find(".nonBasicZmanInDateCell").css("display", "none");
	}
	former_selected_DateCell = dayTD;
	
	dayTD.find(".zmanimInDateCell").html(buildDOMtoDisplayFullZmanimInCell(row, col));
}

function buildDOMtoDisplayFullZmanimInCell(row, col) {
	var myDayInfo = dayInMonthInfo[(7 * parseInt(row)) + parseInt(col) - engMonth_w];
	var dayTD = $jq("#dayTD_" + row + "_" + col);
	var divZmanimInDateCell = dayTD.find(".zmanimInDateCell");
	//divZmanimInDateCell.css("color", "red");

	zmanimHTML = '<div class="nonBasicZmanInDateCell">Alos:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.alos_ma) + '</div>' +
	'<div class="nonBasicZmanInDateCell">Talis:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.talis_ma) + '</div>' +
	'<div class="zmanInDateCell">Sunrise:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.sunrise) + '</div>' +
	'<div class="zmanInDateCell">Sof zman Shema:<br />' + 
	js_convert_time(myDayInfo.zmanim.sof_zman_shema_ma) + '   MA<br/>' +
	js_convert_time(myDayInfo.zmanim.sof_zman_shema_gra) + '  GRA' + '</div>' +
	'<div class="zmanInDateCell">Sof zman Tefila:<br />' + 
	js_convert_time(myDayInfo.zmanim.sof_zman_tefila_ma) + '</div>' +
	'<div class="nonBasicZmanInDateCell">Chatzos:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.chatzos) + '</div>' +
	'<div class="nonBasicZmanInDateCell">Mincha Gedola:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.mincha_gedola_ma) + '</div>' +
	'<div class="nonBasicZmanInDateCell">Mincha Ketana:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.mincha_ketana_ma) + '</div>' +
	'<div class="nonBasicZmanInDateCell">Plag Mincha:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.plag_mincha_ma) + '</div>' +
	'<div class="zmanInDateCell">Sunset:<br />' + 
	js_convert_time(myDayInfo.zmanim.sunset) + '</div>' +
	'<div class="nonBasicZmanInDateCell">Tzeis 42 min:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.tzeis_42_minutes) + '</div>' +
	'<div class="nonBasicZmanInDateCell">Tzeis 72 min:<br /> ' + 
	js_convert_time(myDayInfo.zmanim.tzeis_72_minutes) + '</div>';
	
	zmanimHTML += '<img class="zmanim_more_less" src="http://www.ou.org/images/calendar/zmanim_fewer_.gif">';

	return zmanimHTML;
	//divZmanimInDateCell.html(zmanimHTML);
}

var onShowTab = function(clicked) {
        //var lastTab = $jq(clicked).parents('ul').find('li').index(clicked.parentNode) + 1;
		$jq(".contentView").addClass("donotprint");
        if ($jq(clicked).parents('li').attr("id") == "monthViewLI") {
			// TBD - check if flag is set for showing zmanim to set mode properly
			createCookie("activeTab", "month", 7);
			//window.location.hash="calendar";
			tabID = tabIDMonth;
			// if we haven't yet fetched the grid view with all zmanim,
			// then fetch the month view data
			// do we need to fetch month view data
            if (monthDisplayUpdated) {
				$jq(".cdivEngMYSelector").css("visibility","visible");
				$jq("#calendar").removeClass("donotprint");
			} else {populateMonthView();}
			$jq("#cal-legend").css("display", "none");
		}
        return true;
}

$jq(document).ready(function() {
	//if (window.location.hash != "") window.location.hash = "";
	initializeContext();
         initTabs();         // on new header, set up multiple tabs for searches
	$jq('#container').tabs(tabID, {onShow: onShowTab});
	$jq(".contentView").removeClass("contentInitiallyHidden");
	//$jq("div#cal-top .tips").fadeIn("slow");
	$jq("div#cal-top .tips").fadeTo(5000, 1.0);	
	
	$jq("#location").autocomplete(
		"http://www.ou.org/autocomplete_location_encode.php",
		{
			delay:10,
			minChars:3,
			matchSubset:1,
			//matchContains:1,
			cacheLength:10,
			maxItemsToShow:10,
			//onItemSelect:selectItem,
			//onFindValue:findValue,
			//formatItem:formatItem,
			autoFill:false
		}
	);
	$jq("#currLocation").html(location_string);

	$jq(".contentView").addClass("donotprint");
	populateActiveTab();
	
	if (fDisplayDailyZmanim == "true") {
		$jq("#showZmanim").attr("checked", "checked");
	} else {$jq("#showZmanim").removeAttr("checked");}
	$jq("#hideTips").click(function() {
			$jq(".tips").css("display", "none");
		});
    $jq(".cbtnSwitchMonthPrev").click(function() {
		// first, remove the data all tab pages
		clearCalendar("switchMonth");
		
        var datePrevMonth= new Date();		
        datePrevMonth.setFullYear(engYear);
	    datePrevMonth.setDate(1);
	    datePrevMonth.setMonth(engMonth - 2);
        dateLastInPrevMonth = new Date(engYear, engMonth - 1, 0);
        // set the global variables to reflect the new date
		engMonth = datePrevMonth.getMonth() + 1;
		engYear = datePrevMonth.getFullYear();
		engMonth_w = datePrevMonth.getDay();
		engMonth_t = dateLastInPrevMonth.getDate();
		createCookie("date", serializeDateData(), 0);
		populateActiveTab();
	});
	$jq(".cbtnSwitchMonthNext").click(function() {
		// first, remove the data all tab pages
		clearCalendar("switchMonth");
				
        var dateStartNextMonth= new Date();
        dateStartNextMonth.setFullYear(engYear);
	    dateStartNextMonth.setDate(1);
	    dateStartNextMonth.setMonth(engMonth);
		dateLastInNextMonth = new Date(engYear, engMonth+1, 0);
		// set the global variables to reflect the new date
		engMonth = dateStartNextMonth.getMonth() + 1;
		engYear = dateStartNextMonth.getFullYear();
		engMonth_w = dateStartNextMonth.getDay();
		engMonth_t = dateLastInNextMonth.getDate();
		//alert(engMonth + "/" + engYear + ", " + engMonth_t + " days");
		createCookie("date", serializeDateData(), 0);
		populateActiveTab();
	});
	
	$jq("#showZmanim").click(function() {
		// toggle the div of zmanim in each TD_i_j
		if ($jq("#showZmanim").attr('checked') == undefined) {
			$jq(".zmanimInDateCell").css("display", "none");
			$jq("#clickForZmanimMsg").css("visibility", "hidden");
			fDisplayDailyZmanim = "false";
			createCookie("displayDailyZmanim", "false", 7);
		} else {
			$jq(".zmanimInDateCell").css("display", "block");
			$jq("#clickForZmanimMsg").css("visibility", "visible");
			fDisplayDailyZmanim = "true";
			createCookie("displayDailyZmanim", "true", 7);
		}
	});
	
	// switch the selected Location
	$jq("#location").parents("form").submit( function() {
		var new_location = $jq("#location").val();
		// validation on the string entered by the user
		if (new_location.length == 0) {
			alert("To switch location, type name of city and click Submit");
			$jq("#location").get(0).focus();
			return;
		}
		// parse new location to yield new_city, new_region, new_country_short
		// if there is no comma in the location, treat the entire location as the city
		var new_city="", new_region="", new_country_short="";
		if (new_location.indexOf(",") == -1) {
			new_city = new_location;
		} else {
			new_city = new_location.split(",")[0];
			var rest = js_trim(new_location.split(",")[1]);
			if (rest.indexOf(" ") == -1) {
				// there was no space, the rest is either region or country
				// should both possibilities be tried in the SQL in the php program?
				new_country_short = rest;
			} else {
				new_region = rest.split(" ")[0];
				new_country_short = rest.split(" ")[1];
			} 
		}
		
		// make a synchronous call to get all matching city/region/country records
		// if exactly one match, then proceed with location switch, 
		// otherwise, display list of matches in thickbox dialog box

		var matching_location_url = "http://www.ou.org/auto_matching_location.php";
		var queryParts = new Array();
		if (new_city != "") {
			queryParts[0] = "city=" + escape(new_city);
		}
		if (new_region != "") {
			queryParts[1] = "region=" + escape(new_region);
		}
		if (new_country_short != "") {
			queryParts[2] = "country=" + escape(new_country_short);
		}
		queryString = queryParts.join("&").toLowerCase();
		queryString = queryString.replace(/&&/g, "&");
		matching_location_url = matching_location_url + '?' + queryString;
		// check the cities database to make sure we have exactly one city to proceed with
		// if there are too many cities that match, tell user to refine the search
		// if more than one but several match, give the user a list of cities to choose from

		$jq.get(matching_location_url, function(data){processMatchingLocationsUponSubmit(data);});
	return false;
	});  // end of switchLocation	
	

		
});  // end of ready function

function initTabs() {
	//console.log('got here');
	$jq('.tabset, .tablist, .tabs, .tabtab, .searchtab').each(function(){
		var _list = $jq(this);
		var _links = _list.find('a.tab');

		_links.each(function() {
			var _link = $jq(this);
			var _href = _link.attr('href');
			var _tab = $jq('.'+_href);
			if(_link.hasClass('active')) 
				_tab.show();
			else 
				_tab.hide();

			_link.click(function(){
				_links.filter('.active').each(function(){
					$jq('.'+ $jq(this).attr('href')).hide();
				});
				_links.removeClass('active');
				_link.addClass('active');
				_tab.show();
				return false;
			});
		});
	});
}

			

function getMonthW(month, year) {
	// this function returns the day of the weeek (0 - 6) of first day of month
	// input: month is integer (1 - 12), year has format YYYY
	var dateStartMonth= new Date(year, month - 1, 1);		
	return dateStartMonth.getDay();
}
	
function getMonthT(month, year) {
	// this function returns the number of days in the month
	// input: month is integer (1 - 12), year has format YYYY
	dateEndMonth = new Date(year, month, 0);
	return dateEndMonth.getDate();
}

function processMatchingLocationsUponSubmit(myData) {

		if (myData == null || myData == "") {
			location_cnt = 0;
		} else {
			location_data=parseData(myData);
			location_cnt = location_data.length;							
		}

			
		if (location_cnt == 0) {
			alert ("no location found - please reenter city, state country");
			return;
		} 	else if (location_cnt > 1) {
			locations_html="<span>Multiple matches were found.  Choose one of these cities:</span><br><input type='button' onclick='tb_remove();' value='Cancel'><ul>";
			for (i = 0; i < location_data.length; i++) {
				locations_html = locations_html + "<li><a onclick=\"tb_remove();doSwitchLocation('" + location_data[i] + "');\">" + unescape(location_data[i]) + "</a></li>";
			}
			locations_html = locations_html + "</ul>";
			$jq("#multipleLocationsDiv").html(locations_html);
			$jq("#multipleLocationsDiv a").css("cursor", "pointer");
			$jq("#launchMultLocThickbox").click();
			return;			
		} else {
			// one location found
			doSwitchLocation(location_data[0]);	
		}
}

function doSwitchLocation(location_str) {
		$jq("#location").val("");
		new_city = location_str.split(",")[0];
		
		var rest = js_trim(location_str.split(",")[1]);
		
		if (rest.indexOf(" ") == -1) {
			new_region = "";
			new_country_short = rest;
		} else {
			new_region = rest.split(" ")[0];
			new_country_short = rest.split(" ")[1];
		}  
		// make a synchronous call to get the location data for new location		
		var req = createNewRequest();
		
		var new_location_str = unescape(new_city);
		
		var location_url = 'http://www.ou.org/holidays/get_location_data2?city=' + new_city;
		if (new_region != "") {
			location_url = location_url + '&region=' + new_region;
			new_location_str = new_location_str + ", " + new_region;
		}
		if (new_country_short != "") {
			location_url = location_url + '&country=' + new_country_short;
		}
		
		// create the string to display the new location
		if (new_country_short == "US") {
			new_location_str = new_location_str + " " + new_country_short;
		} else {
			new_location_str = new_location_str + ", " + new_country_short;
		}
		//alert("New location url = " + location_url);
		$jq("#currLocation").html(new_location_str);
		// store the new location in the global variables
		curr_city = unescape(new_city);
		curr_region = "";
		if (new_region != "")
			curr_region = new_region;
		curr_country = new_country_short;
		req.open('GET', location_url, false);
		req.send(null);
		if(req.status == 200) {
			//alert(req.responseText);
			// convert the response JSON into js object
			resp = eval('(' + req.responseText + ')');

			// update global location data with data for
			// new city/state/country
			var lat = resp.latitude;
			locData = new LocData(curr_city, curr_region, curr_country, resp.latitude,resp.longitude,resp.community_id,resp.timezone);
			// write the location cookie
			createCookie("location", serializeLocData(), 0);
			var formerLocation_currDateStr = currDateStrForLocation;
			currDateStrForLocation = resp.today;
			
			// refresh the map of shuls that are proximate to new location
			shulsMap.map = null;
			
			// parse the currDateStrForLocation MM/DD/YYYY for the new location
			
			var currDateNewMatchArray = currDateStrForLocation.match(engDatePat);
			var currDateNew_engMonth = currDateNewMatchArray[1];
			var currDateNew_engDateInMonth = currDateNewMatchArray[3];
			var currDateNew_engYear = currDateNewMatchArray[4];
			var currDateOldMatchArray = formerLocation_currDateStr.match(engDatePat);
			var currDateOld_engMonth = currDateOldMatchArray[1];
			var currDateOld_engYear = currDateOldMatchArray[4];			
			if ((currDateNew_engYear != currDateOld_engYear || 	currDateNew_engMonth != currDateOld_engMonth) && (currDateOld_engYear == engYear) && (currDateOld_engMonth == engMonth)) {
				// if current-month/year has changed for new location vs. old location
				// and the old month/year contained the current date for old location,
				// then update the global variables engMonth and engYear etc.
				engMonth = currDateNew_engMonth;
				engYear = currDateNew_engYear;
				engMonth_w = getMonthW(engMonth, engYear);
				engMonth_t = getMonthT(engMonth, engYear);
			}		
			
			// use a local array to assemble comma-separated list 
			// of day-of-month of 
			// cells in MonthView that were "visited" by the user
			visitedCellsDaysInMonth = new Array();
			for (i=0; i < engMonth_t; i++) {
				if (gVisitedCellsArray[i] != null)
					visitedCellsDaysInMonth.push(i+1);
			}
			gExpandedCellDayInMonth = 0;
			if (oldTD != null) {
				gExpandedCellDayInMonth = getDayInMonth(oldTD.id);
			}
			gVisitedCellsDaysInMonth = visitedCellsDaysInMonth.join(",");
			//alert("visited cells days: " + visitedCellsDaysInMonth.join(",") + ", expanded cell = " + gExpandedCellDayInMonth);
			
			clearCalendar("switchLocation");
			populateActiveTab("switchLocation");	
		}
} 

function parseData(data) {
	if (!data) return null;
	var parsed = [];
	var rows = data.split("\n");
	for (var i=0; i < rows.length; i++) {
		var row = $jq.trim(rows[i]);
		if (row) {
			//parsed[parsed.length] = row.split(options.cellSeparator);
			parsed[parsed.length] = row;
		}
	}
	return parsed;
};


function populateActiveTab(updateType) {
	var selectedTabNum = $jq("#container").activeTab();
	//$jq("#cal-legend").css("display", "none");
	if (selectedTabNum == tabIDMonth ) {
		populateMonthView(updateType);
		$jq("#calendar").removeClass("donotprint");
		$jq("#cal-legend").css("display", "none");
	}
}

function populateAndDisplayEngMYSelector() {
	// first, populate the options in the select element for month, year
	var htmlStr = '<select class="cselNewMonth" onchange="switchMonthYearNew()">';
	for (month = 0; month < 12; month++) {
		htmlStr += '<option value="' + month + '"';
		if (month == (engMonth-1)) {
			htmlStr += ' selected="selected">' + engMonths[month] + '</option>';
			}
		else {
			htmlStr += '>' + engMonths[month] + '</option>';
			}
		}
	htmlStr += '</select>';
	var startYear = (engYear * 1) - 10;
	var endYear = (engYear * 1) + 10;
	htmlStr += '<select class="cselNewYear" onchange="switchMonthYearNew()">';
	for (var year = startYear; year <= endYear; year++) {
		htmlStr += '<option value="' + year + '"' +
			(year == engYear ? ' selected="selected"' : '') + '>' +
			year + '&nbsp;</option>';
	}
	htmlStr += '</select>';
	$jq(".cspanEngMYSelector").html(htmlStr);
	// fudge to fix IE Internet Explorer - first option is always selected
	$jq(".cspanEngMYSelector .cselNewMonth").each(function(){
		this.options[engMonth-1].selected = true;
	});
	$jq(".cspanEngMYSelector .cselNewYear").each(function(){
		this.options[10].selected = true;
	});	

	// second, populate the Hebrew months span
	var str = js_getHebMonthSpanForMonth("single_line");
	$jq(".cspanHebMY").html(str);
	// third, make the entire div visible
	$jq(".cdivEngMYSelector").css("visibility","visible");	
}

function switchMonthYearNew() {
	// based upon which tab we are viewing, get the new values of M, Y 
	// from the correct select elements within 
	// <span id="prefix_EngMYSelector">
	var selectedTabNum = $jq("#container").activeTab();
	var prefix;
	switch (selectedTabNum) {
		case 1:
			prefix = "mon";
			break;
		case 3:
			prefix = "hol";
			break;
	}		
	clearCalendar("switchMonth");
	engMonth = parseInt($jq("#" + prefix + "_EngMYSelector .cselNewMonth").val()) + 1;
	engYear = parseInt($jq("#" + prefix + "_EngMYSelector .cselNewYear").val());	
		
	var dateStartNewMonth= new Date();		
	dateStartNewMonth.setFullYear(engYear);
	dateStartNewMonth.setDate(1);
	dateStartNewMonth.setMonth(engMonth - 1);
	
	dateEndNewMonth = new Date(engYear, engMonth, 0);
	// set the global variables to reflect the new date
	engMonth_w = dateStartNewMonth.getDay();
	engMonth_t = dateEndNewMonth.getDate();
	createCookie("date", serializeDateData(), 0);
	populateActiveTab();
}


function getJSONMonthViewData(updateType) {	
    request = new XssHttpRequest();
	var url_monthView = getDataURL("monthView", updateType);
    request.open("GET", url_monthView, true);
    request.onreadystatechange=function() {
        if(request.readyState==4) {
            alert('Completed request: ' + request.responseText);
            eval('processJSONCalendarData(' + request.responseText + ')'); 
        }
    }
    request.send(null);
}

function processJSONCalendarData(r) {
	for (key = 0; key < r.days.length; key++) {
		var engDateStr = r.days[key].engDateString;
		var engMatchArray = engDateStr.match(engDatePat);
		var data_engMonth = engMatchArray[1];
		var data_engDateInMonth = engMatchArray[3];
		// TBD - when GridData was imported, then MonthData, we are wiping out the grid data!
		if (data_engMonth == engMonth) {
			dayInMonthInfo[data_engDateInMonth-1] = r.days[key];
			}
		else {
			dayInMonthInfo[data_engDateInMonth-1 + engMonth_t] = r.days[key];
			}
		}
	monthViewDataUpdated = true;
		doPopulateMonthView();
}

function populateMonthView(updateType) {
	if (monthViewDataUpdated) {doPopulateMonthView();} else {getJSONMonthViewData(updateType);}
}
function doPopulateMonthView() {
	var currDateStrForLocation = engMonth + '/' + engDay + '/' + engYear;
	var row, col, locInGrid;
	if (!monthViewDataUpdated)
		getJSONMonthViewData();
    // hide the rows that are not needed to display this month's days	
	var numRows = Math.floor((engMonth_w + engMonth_t - 1) / 7) + 1;
	for (i = 0; i < numRows; i++) {
		$jq("#dayTR_" + i).removeClass("dayTR_hidden");
	}
	for (i = numRows; i < 6; i++) {
		$jq("#dayTR_" + i).addClass("dayTR_hidden");
	}
    // blank out contents of unused cells in the first and last row of the calendar
	// fill in English and Hebrew month spans
	populateAndDisplayEngMYSelector();	
	// clear the designation of currCalDay in its cell (if exists), will be set in loop
	$jq(".currCalDay").removeClass("currCalDay");

	//alert("in doPopulateMonthView - gExpandedCellDayInMonth = " + gExpandedCellDayInMonth + ", gVisitedCellsArray = " + gVisitedCellsArray.join(","));
	// populate each data cell in the month View
	for (key = 0; key < engMonth_t+6; key++) {
		var dayInfo = dayInMonthInfo[key];
		var engDateStr = dayInfo.engDateString;
		var engMatchArray = engDateStr.match(engDatePat);
		var data_engMonth = engMatchArray[1];
		var data_engDateInMonth = engMatchArray[3];
		var data_engYear = engMatchArray[4];
		var TDId;
		var locInGrid;
		if (data_engMonth == engMonth) {
			locInGrid = engMonth_w + parseInt(data_engDateInMonth) - 1;	
			}
		else {
			locInGrid = engMonth_w + engMonth_t + parseInt(data_engDateInMonth) - 1;
			}
		var col = locInGrid % 7;
		var row = Math.floor(locInGrid / 7);
		TDId = "#dayTD_" + row + "_" + col;
		var id_parts = TDId.split("_");
		row = id_parts[1];
		col = id_parts[2];

		var engWeekDay;
		switch(locInGrid % 7) {
			case 0:
				engWeekDay = "Sunday<br>";
				break;
			case 1:
				engWeekDay = "Monday<br>";
				break;
			case 2:
				engWeekDay = "Tuesday<br>";
				break;
			case 3:
				engWeekDay = "Wednesday<br>";
				break;
			case 4:
				engWeekDay = "Thursday<br>";
				break;
			case 5:
				engWeekDay = "Friday<br>";
				break;
			case 6:
				engWeekDay = "Saturday<br>";
				break;
			}
		
		var engMonthString;
		switch(parseInt(data_engMonth)) {
			case 1:
				engMonthString = "January";
				break;
			case 2:
				engMonthString = "February";
				break;
			case 3:
				engMonthString = "March";
				break;
			case 4:
				engMonthString = "April";
				break;
			case 5:
				engMonthString = "May";
				break;
			case 6:
				engMonthString = "June";
				break;
			case 7:
				engMonthString = "July";
				break;
			case 8:
				engMonthString = "August";
				break;
			case 9:
				engMonthString = "September";
				break;
			case 10:
				engMonthString = "October";
				break;
			case 11:
				engMonthString = "November";
				break;
			case 12:
				engMonthString = "December";
				break;
			}
		
		var hebDateStr = dayInfo.hebDateString;
		var hebMatchArray = hebDateStr.match(hebDatePat);
		var data_hebMonth = hebMatchArray[2];
		if (data_hebMonth.indexOf("AdarI") >= 0) {
			data_hebMonth = "Adar " + data_hebMonth.substr(4);
		}
		var data_hebDateInMonth = hebMatchArray[1];		
		var data_hebYear = hebMatchArray[3];
		var holidays = dayInfo.holidays;
		var holidayHTML = "";
		if (holidays != null) {
			var holidayNameText = holidays[0].holiday.holidayName;
			// split into 2 lines after 1stDay or 2ndDay
			var idx;
			if ((idx = holidayNameText.indexOf("Day")) >= 0) {
				holidayNameText = holidayNameText.substr(0, idx + 3) + "<br>" + holidayNameText.substr(idx+3);
			}
			holidayHTML = '<div class="holidayInDateCell">' + holidayNameText + '</div>';
		}
		var parshaHTML = "";
		if (dayInfo.parsha != null && dayInfo.parsha.length > 0) {
			parshaHTML = '<div class="parshaInDateCell"><img src="/zmanim/icon16_torahportion.gif" ALT="Torah Icon" style="vertical-align:middle;">&nbsp;Parshat ' + dayInfo.parsha + '</div>';
			}
        var specialShabbosHTML = "";
		if (dayInfo.specialShabbos != null && dayInfo.specialShabbos != false) {
			specialShabbosHTML = '<div class="specialShabbosInDateCell">&nbsp;Shabbat ' + dayInfo.specialShabbos + '</div>';
			}
		else if (dayInfo.parsha != null && dayInfo.parsha.length > 0 && dayInfo.parsha == 'Beshalach') {
			specialShabbosHTML = '<div class="specialShabbosInDateCell">&nbsp;Shabbat Shirah</div>';
			}
		else if (hebDateStr == '14 Nisan ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '13 Nisan ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '12 Nisan ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '11 Nisan ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '10 Nisan ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '9 Nisan ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '8 Nisan ' + data_hebYear && locInGrid % 7 == 6) {
			specialShabbosHTML = '<div class="specialShabbosInDateCell">&nbsp;Shabbat ha-Gadol</div>';
			}
		else if (hebDateStr == '8 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '7 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '6 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '5 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '4 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '3 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '2 Av ' + data_hebYear && locInGrid % 7 == 6) {
			specialShabbosHTML = '<div class="specialShabbosInDateCell">&nbsp;Shabbat Hazon</div>';
			}
		else if (hebDateStr == '10 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '11 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '12 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '13 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '14 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '15 Av ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '16 Av ' + data_hebYear && locInGrid % 7 == 6) {
			specialShabbosHTML = '<div class="specialShabbosInDateCell">&nbsp;Shabbat Nahamu</div>';
			}
		else if (hebDateStr == '3 Tishri ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '4 Tishri ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '5 Tishri ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '6 Tishri ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '7 Tishri ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '8 Tishri ' + data_hebYear && locInGrid % 7 == 6 || hebDateStr == '9 Tishri ' + data_hebYear && locInGrid % 7 == 6) {
			specialShabbosHTML = '<div class="specialShabbosInDateCell">&nbsp;Shabbat Shuvah</div>';
			}
		cellHTML = '';
		cellHTML += '';
		//cellHTML += holidayHTML;
		//cellHTML += '<div class="zmanimInDateCell">';
			// if this cell is the cell that is expanded
		//if (data_engDateInMonth == gExpandedCellDayInMonth) {
		//	cellHTML = cellHTML + buildDOMtoDisplayFullZmanimInCell(row, col);
		//} else if (gVisitedCellsArray[data_engDateInMonth -1] == 1) {
		//	cellHTML += 
		//		'<div class="zmanInDateCell">Sunrise: ' + js_convert_time(dayInfo.zmanim.sunrise) + '</div>' +
        //                       '<div class="zmanInDateCell">Sof zman Shema:<br />' + js_convert_time(dayInfo.zmanim.sof_zman_shema_ma) + ' MA<br/>' +
	    //                          js_convert_time(dayInfo.zmanim.sof_zman_shema_gra) + ' GRA' + '</div>' +
		//		'<div class="zmanInDateCell">Sof zman Tefila: ' + js_convert_time(dayInfo.zmanim.sof_zman_tefila_ma) + '</div>' +
		//		'<div class="zmanInDateCell">Sunset: ' + js_convert_time(dayInfo.zmanim.sunset) + '</div><img src="http://www.ou.org/images/calendar/zmanim_more_.gif" class="zmanim_more_less">';
		//} else {
		//	cellHTML += '<img src="http://www.ou.org/images/calendar/zmanim_show_84.gif" class="zmanim_more_less" alt="click to show zmanim" />';
		//}
		//cellHTML += '</div>';
		cellHTML +=  '';
		var otherHolidays = '';
		switch (hebDateStr) {
			case '14 AdarI ' + data_hebYear:
				otherHolidays = '<br>Purim Katan';
				break;
			case '16 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 1';
				break;
			case '17 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 2';
				break;
			case '18 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 3';
				break;
			case '19 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 4';
				break;
			case '20 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 5';
				break;
			case '21 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 6';
				break;
			case '22 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 7';
				break;
			case '23 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 8';
				break;
			case '24 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 9';
				break;
			case '25 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 10';
				break;
			case '26 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 11';
				break;
			case '27 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 12';
				break;
			case '28 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 13';
				break;
			case '29 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 14';
				break;
			case '30 Nisan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 15';
				break;
			case '1 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 16';
				break;
			case '2 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 17';
				break;
			case '3 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 18';
				break;
			case '4 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 19';
				break;
			case '5 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 20';
				break;
			case '6 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 21';
				break;
			case '7 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 22';
				break;
			case '8 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 23';
				break;
			case '9 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 24';
				break;
			case '10 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 25';
				break;
			case '11 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 26';
				break;
			case '12 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 27';
				break;
			case '13 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 28';
				break;
			case '14 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Pesach Sheni<br>Omer, Day 29';
				break;
			case '15 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 30';
				break;
			case '16 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 31';
				break;
			case '17 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 32';
				break;
			case '18 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 33';
				break;
			case '19 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 34';
				break;
			case '20 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 35';
				break;
			case '21 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 36';
				break;
			case '22 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 37';
				break;
			case '23 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 38';
				break;
			case '24 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 39';
				break;
			case '25 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 40';
				break;
			case '26 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 41';
				break;
			case '27 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 42';
				break;
			case '28 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Yom Yerushalayim<br>Omer, Day 43';
				break;
			case '29 Iyyar ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 44';
				break;
			case '1 Sivan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 45';
				break;
			case '2 Sivan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 46';
				break;
			case '3 Sivan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 47';
				break;
			case '4 Sivan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 48';
				break;
			case '5 Sivan ' + data_hebYear:
				otherHolidays = '<br>Omer, Day 49';
				break;
			}
		var candlesHavdalahHTML = '';
		if (dayInfo.candle_lighting != null) {
			candlesHavdalahHTML = '<div class="candlelightingInDateCell"> <img src="/zmanim/zmanim_candles_icon.gif" ALT="Candles Icon" style="vertical-align:middle;"> Candles: ' + js_convert_time(dayInfo.candle_lighting) + '</div>';
		}

		if (dayInfo.havdala_42_minutes != null) {
			candlesHavdalahHTML = parshaHTML + specialShabbosHTML + '<div class="havdalahInDateCell">&nbsp;Havdalah: ' + js_convert_time(dayInfo.havdala_42_minutes) + '</div>';
		}
		var yiwhHTML = '';
		if (dayInfo.candle_lighting != null || dayInfo.havdala_42_minutes != null || holidays != null) {
			yiwhHTML = '<div class="engDayInDateCell">' + engWeekDay + '</div><div class="engDateInDateCell">' + engMonthString + '&nbsp;' + data_engDateInMonth + ',&nbsp;' + engYear + '<br><div class="hebDateInDateCell">' + dayInfo.hebDateString + '</div>' + otherHolidays + holidayHTML + candlesHavdalahHTML + '<br>';
		}
		cellHTML += yiwhHTML;
		$jq(TDId).html(cellHTML);
		if ((parseInt(data_engMonth)-1) + '/' + (parseInt(data_engDateInMonth)+engMonth_t-4) + '/' + parseInt(data_engYear) == currDateStrForLocation || engDateStr == currDateStrForLocation || parseInt(data_engMonth) + '/' + (parseInt(data_engDateInMonth)-1) + '/' + parseInt(data_engYear) == currDateStrForLocation || parseInt(data_engMonth) + '/' + (parseInt(data_engDateInMonth)-2) + '/' + parseInt(data_engYear) == currDateStrForLocation || parseInt(data_engMonth) + '/' + (parseInt(data_engDateInMonth)-3) + '/' + parseInt(data_engYear) == currDateStrForLocation || parseInt(data_engMonth) + '/' + (parseInt(data_engDateInMonth)-4) + '/' + parseInt(data_engYear) == currDateStrForLocation || parseInt(data_engMonth) + '/' + (parseInt(data_engDateInMonth)-5) + '/' + parseInt(data_engYear) == currDateStrForLocation || parseInt(data_engMonth) + '/' + (parseInt(data_engDateInMonth)-6) + '/' + parseInt(data_engYear) == currDateStrForLocation || (parseInt(data_engMonth)-1) + '/' + (parseInt(data_engDateInMonth)+engMonth_t-6) + '/' + parseInt(data_engYear) == currDateStrForLocation || (parseInt(data_engMonth)-1) + '/' + (parseInt(data_engDateInMonth)+engMonth_t-5) + '/' + parseInt(data_engYear) == currDateStrForLocation || (parseInt(data_engMonth)-1) + '/' + (parseInt(data_engDateInMonth)+engMonth_t-4) + '/' + parseInt(data_engYear) == currDateStrForLocation || (parseInt(data_engMonth)-1) + '/' + (parseInt(data_engDateInMonth)+engMonth_t-3) + '/' + parseInt(data_engYear) == currDateStrForLocation || (parseInt(data_engMonth)-1) + '/' + (parseInt(data_engDateInMonth)+engMonth_t-2) + '/' + parseInt(data_engYear) == currDateStrForLocation || (parseInt(data_engMonth)-1) + '/' + (parseInt(data_engDateInMonth)+engMonth_t-1) + '/' + parseInt(data_engYear) == currDateStrForLocation) {
			$jq(TDId).addClass("currCalDay");
			}
		else {
			$jq(TDId).addClass("no");
			}
	}
	$jq("#calendar").removeClass("donotprint");
	if (fDisplayDailyZmanim == "true") {
		$jq(".zmanimInDateCell").css("display", "block");
	} else {
		$jq(".zmanimInDateCell").css("display", "none");
	}
	monthDisplayUpdated = true;
}

function js_getHebMonthSpanForMonth(formatStr) {
	var startHebDate = dayInMonthInfo[0].hebDateString;
	var endHebDate = dayInMonthInfo[engMonth_t - 1].hebDateString;
	var startHebDateMatchArray = startHebDate.match(hebDatePat);
	var startHebMonth = startHebDateMatchArray[2];
	if (startHebMonth.indexOf("AdarI") >= 0) {
		startHebMonth = "Adar " + startHebMonth.substr(4);
	}
	var startHebYear = startHebDateMatchArray[3];
	var endHebDateMatchArray = endHebDate.match(hebDatePat);
	var endHebMonth = endHebDateMatchArray[2];
	if (endHebMonth.indexOf("AdarI") >= 0) {
		endHebMonth = "Adar " + endHebMonth.substr(4);
	}	
	var endHebYear = endHebDateMatchArray[3];
	if (formatStr == "monthnum_range") {
		return "hmstart=" + hebrewMonthNum[startHebMonth] + "&hmend=" + hebrewMonthNum[endHebMonth];
	}
	if (endHebYear == startHebYear) {
		if (formatStr == "split_line") {
			return startHebMonth + " - " + endHebMonth + "<br>" + startHebYear;
		} else {
			return startHebMonth + " - " + endHebMonth + ", " + startHebYear;
		}
	} else {
		if (formatStr == "split_line") {
			return startHebMonth + ", " + startHebYear + " -<br>" + endHebMonth + ", " + endHebYear;
		} else {
			return startHebMonth + ", " + startHebYear + " - " + endHebMonth + ", " + endHebYear;
		}
	}
	
}

function createNewRequest() {
	var req;
	if(window.XMLHttpRequest && !(window.ActiveXObject)) {
		try {
			req = new XMLHttpRequest();
		} catch(e) {
			req = false;
		}
	// branch for IE/Windows ActiveX version
	} else if(window.ActiveXObject) {
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				req = false;
			}
		}
	}
	return req;
}

function serializeLocData() {
		return '{"city":"' + locData.city + '", "region":"' + locData.region + '", "country":"' + locData.country + '", "lat":"' + locData.lat + '", "long":"' + locData.long + '", "community_id":"' + locData.community_id + '", "timezone":"' + locData.timezone + '"}';
}

function serializeDateData() {
		return '{"month":"' + engMonth + '", "year":"' + engYear + '"}';
}

function initializeContext() {
	var d = new Date();
	var month=new Array(12);
		month[0]="1";
		month[1]="2";
		month[2]="3";
		month[3]="4";
		month[4]="5";
		month[5]="6";
		month[6]="7";
		month[7]="8";
		month[8]="9";
		month[9]="10";
		month[10]="11";
		month[11]="12";
		engMonth = month[d.getMonth()];
		engYear = d.getYear();
        engDay = d.getDate();
    currDateStrForLocation = engMonth + '/' + engDay + '/' + engYear;
	var is_date_in_query_string = "false";
	if (is_date_in_query_string == "true") {
		engMonth = month[d.getMonth()];
		engYear = d.getYear();
        engDay = d.getDate();
        //gExpandedCellDayInMonth = parseInt("25");
        gVisitedCellsDaysInMonth = d.getDate();
        gVisitedCellsArray[gVisitedCellsDaysInMonth - 1] = 1;  
	} else {	
		var dateDataFromCookie = readCookie("date");
		if (dateDataFromCookie != null) {
			dateData = eval('(' + dateDataFromCookie + ')');
			engMonth = dateData.month;
			engYear = dateData.year;
		} else {
			engMonth = month[d.getMonth()];
			engYear = d.getFullYear();
		}
	}
	// day of week that English month starts on
	engMonth_w = getMonthW(engMonth, engYear);
	// number of days in the English month  
	engMonth_t = getMonthT(engMonth, engYear);
	//alert(engMonth + "/" + engYear + " has " + engMonth_t + " days");

        var is_location_in_query_string = "false";
        if (is_location_in_query_string == 'true') {
		curr_city = "West Hartford";
		curr_region = "CT";
		curr_country = "US";
		locData = new LocData('West Hartford', 'CT', 'US', '41.786159', '-72.741451', '28501', 'America/New_York');
		// write the location cookie
		createCookie("location", serializeLocData(), 0);
        } else {
	    var locDataFromCookie = readCookie("location");
	    if (locDataFromCookie != null) {
		locData = eval('(' + locDataFromCookie + ')');
		curr_city = locData.city;
		curr_region = locData.region;
		curr_country = locData.country;
		//alert (locData.city + ", " + locData.region + " " + locData.country);
	    } else {	
		curr_city = "West Hartford";
		curr_region = "CT";
		curr_country = "US";
		locData = new LocData('West Hartford', 'CT', 'US', '41.786159', '-72.741451', '28501', 'America/New_York');
		// write the location cookie
		createCookie("location", serializeLocData(), 0);
	    }
        }
	if (locData.country == "US") {
		location_string = locData.city + ", " + locData.region + " " + locData.country;
	} else {
		location_string = locData.city + ", " + locData.country;
	}
	fDisplayDailyZmanim = readCookie("displayDailyZmanim");
	if (fDisplayDailyZmanim == null) {
		createCookie("displayDailyZmanim", "true", 7);
		fDisplayDailyZmanim = "true";
	}
	tabID = tabIDMonth;
	var modeFromQueryStr = getQueryVariable("mode");	
	if (modeFromQueryStr != "") {
		var activeTabName = modeFromQueryStr;	
		switch (modeFromQueryStr) {
			case "zmanim":
				tabID = tabIDMonth;
				activeTabName="month";
				fDisplayDailyZmanim = "true";
				createCookie("displayDailyZmanim", "true", 7);
				break;			
		}
		
	} else {
		// if mode was not specified on query string in URL,
		// check for activeTab in the hash, then the cookie, 
		var activeTabNameFromHash = window.location.hash.substr(1);
		var activeTabNameFromCookie = readCookie("activeTab"); 
		activeTabNameFromCookieOrHash = activeTabNameFromHash || activeTabNameFromCookie;
		if (activeTabNameFromCookieOrHash != null) {
			switch (activeTabNameFromCookieOrHash) {
				case "month":
					tabID = tabIDMonth;
					break;
				default:
					tabID = tabIDMonth;
					activeTabNameFromCookieOrHash = "month";
			}
			activeTabName = activeTabNameFromCookieOrHash;
		}

	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {createCookie(name,"",-1);}

/**
 * Author: Andrew Hedges, andrew@hedges.name
 * License: free to use, alter, and redistribute without attribution
 */

/**
 * Truncate a string to the given length, breaking at word boundaries and adding an ellipsis
 * @param string str String to be truncated
 * @param integer limit Max length of the string
 * @return string
 */
var truncate = function (str, limit) {
	var bits, i;
	if ("string" !== typeof str) {
		return '';
	}
	bits = str.split('');
	if (bits.length > limit) {
		for (i = bits.length - 1; i > -1; --i) {
			if (i > limit) {
				bits.length = i;
			}
			else if (' ' === bits[i]) {
				bits.length = i;
				break;
			}
		}
		bits.push('...');
	}
	return bits.join('');
}
// END: truncate

