/*------------------------- OPENING TIMES WIDGET JAVASCRIPT CODE. Copyright Neil Sandbach. www.nscreate.com -----------------------------------------*/

// FIRST, THE HELPER FUNCTIONS /////////////////////////////////////

// FUNCTION to convert total minutes back into "Hours and Minutes".
function minutesToHrsMins(minutes) {
	var Hours = Math.floor(minutes/60);
	var Minutes = minutes%60;
	var HoursString = "hour";
	var MinutesString = "minute";
	var Time;
	if (Hours > 1) {
		HoursString += "s"; // make plural
	}
	if (Minutes > 1 || Minutes == 0) {
		MinutesString += "s"; // make plural
	}
	if (Hours >= 1) {
		Time = Hours + " " + HoursString + " and " + Minutes + " " + MinutesString;
	} else { // just minutes
		var Time = Minutes + " " + MinutesString;
	}
	return Time;
}

function convertToMinutes(theTime) {
	var splitTime = theTime.split(":");
	var theHours = splitTime[0];
	var theMinutes = splitTime[1];
	var totalMinutes = eval(theHours * 60) + eval(theMinutes); //convert to total minutes for convenience
	//alert("totalMinutes = " + totalMinutes);
	return totalMinutes;
}

function isEven(value){
	if (value%2 == 0) {
		return true;
	} else {
		return false;
	}
}


// END OF HELPER FUNCTIONS. ////////////////////////////////////////

// DECLARE DATE+TIME VARIABLES
var currentMinutes;
var currentHour;
var currnetDayOfTheWeek;
var currentDate;
var currentMonth;
var currentYear;
var currentFullDate;
var daysInMS = 24*60*60*1000; // num of ms in  day

function jsonDateCallback(json) {
	currentMinutes = eval(json.dateData.minutes);
	currentHour = eval(json.dateData.hour);
	currentTotalMinutes = (currentHour * 60) + currentMinutes;
	currnetDayOfTheWeek = json.dateData.dayOfTheWeek;
	currentDate = eval(json.dateData.date);
	currentMonth = json.dateData.month;
	currentYear = eval(json.dateData.year);
	// Can actually just use the following currentMicroseconds by parsing it with the getDateFromMilliseconds function.
	currentMicroseconds = eval(json.dateData.timeMicroseconds)*1000;
	//alert("currentMicroseconds = " + currentMicroseconds); // NEEDS TO BE SOMETHING LIKE: 1258991322892
	
	/* FAKE THE DATE-TIME FOR TESTING PURPOSES */
	//currentMinutes = 00;
	//currentHour = 22;
	//currnetDayOfTheWeek = "Friday";

	//-----MAIN JSON DATA-----

	$.getJSON(timesPath);
}

function jsonLocationsCallback(json){
	
	function doLocation(locationObject, divID) {
		
		//First, reset the displayed html so we can append data without accumulating text!
		$("#"+divID).empty();
		
		var currentlyOpen;
		var noEventsToday;
		
		function getDateFromMilliseconds(daysAhead) {
			if (daysAhead == undefined) {daysAhead = 0;}
			var ms = currentMicroseconds + (24*60*60*1000*daysAhead);
			var newdate=new Date();// ok, to hold the future date based on the php-based microseconds time.
			newdate.setTime(ms);
			// get day of the week
			var daysOfTheWeek=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"];
			var today = daysOfTheWeek[newdate.getDay()];
			newdate = newdate.toLocaleString();
			newdate = newdate.split(" ");
			newdate.unshift(today); // add the day of the week to the beginning!
			return newdate; // RETURNS AN ARRAY eg ["Monday",25,"June",2009]. Use convertDateArrayToString to convert to my preferred type of string. ie "Monday 25 June 2009"
		}	
		function convertDateArrayToString(dateArray) {
			var theString = String(dateArray[0] + " " + dateArray[1] + " " + dateArray[2] + " " + dateArray[3]);
			return theString; // Convert to my preferred type of string. ie "Monday 25 June 2009"
		}
		
		todayDateArray = getDateFromMilliseconds(0);
		todayDateString = convertDateArrayToString(todayDateArray);
		//alert("todayDateString = " + todayDateString);	
		var tomorrowDateArray = getDateFromMilliseconds(1); // example
	
		/////////// PUT ALL JSON DATA IN ARRAY
		var timesArray = new Array(); // 	[    [ Day,[[Open,Close],[Open,Close],...[Open,Close]] ], [ Day,[[Open,Close],[Open,Close],...[Open,Close]] ]...   ]
		$.each(locationObject,function(i,item) {
												 
			var todayArray= new Array(); 	// [ Day,[[Open,Close],[Open,Close],...[Open,Close]] ]
			var dayOfTheWeek = i;			// eg "Monday" or exception: eg 22 November
			var openingTimes = new Array();	// [[Open,Close],[Open,Close],...[Open,Close]]
			for(var i=0; i<item.length; i++) {
				var openingPeriod = new Array();
				//if (i<2) {
					openingPeriod[0] = item[i].Open;
					openingPeriod[1] = item[i].Close;
				//}
				//openingPeriod[0] = item[i].Open;				
				//openingPeriod[1] = item[i].Close;
				openingTimes.push(openingPeriod);
			}
			
			todayArray.push(dayOfTheWeek);
			todayArray.push(openingTimes);
			timesArray.push(todayArray);
		
		});
		//alert(timesArray);
		
		// LET'S SEE IF THIS DAY IS AN EXCEPTION
		function checkForExceptionDay(dayToCheck) {
			var todayIsException;
			var exceptionDate;
			var todayAsIndex;
			var checkingDate = dayToCheck;
			var dayOftheWeek = dayToCheck[0];
			if (timesArray.length > 7) { // only check for exceptions if there are some listed for this location
				for (var i=7; i<timesArray.length; i++ ) { // only concerned with entries after the first 7!
					exceptionDate = timesArray[i][0];
					checkingDate = String(dayToCheck[1] + " " + dayToCheck[2]);
					//alert("exceptionDate: " + exceptionDate + "  ...   dayToCheck: " + checkingDate);
					if ((exceptionDate == checkingDate + " " + currentYear) || (exceptionDate == checkingDate)) {
						// YES, TODAY IS AN EXCEPTION
						todayIsException = true;
						//alert("This day is an exception day: " + exceptionDate);
						todayAsIndex = i;
						break;
					}else {
						// NO, TODAY IS A NORMAL DAY
						todayIsException = false;
					}
				}
			} else {
				// NO EXCEPTIONS LISTED
				todayIsException = false;
			}
			// IF NOT AN EXCEPTION, LET'S GET THE INDEX FOR REF
			if (todayIsException == false) {
				//alert("This day is normal day: " + dayOftheWeek);
				for (var i=0; i<7; i++ ) { // only concerned with first 7 entries!
					if (timesArray[i][0] == dayOftheWeek) {
						todayAsIndex = i;
						break;
					}
				}
			}
			//alert("TIMES ARE = " + timesArray[todayAsIndex]);			
			return todayAsIndex;
		};
		
		function findLastEvent(daysBefore) {
			//alert(daysBefore);
			var newDate = getDateFromMilliseconds(daysBefore);			
			var thisDatePosInArray = checkForExceptionDay(newDate); // see what day we are currently dealing with (by position in the timesArray ie main array). // same as todayAsIndex !
			var todaysOpeningPeriods = new Array();
			todaysOpeningPeriods = timesArray[thisDatePosInArray][1];
			//alert("thisDatePosInArray = " + thisDatePosInArray);
			var numOfOpeningPeriods;
			if (timesArray[thisDatePosInArray][1][0][0] === undefined) { // check for empty entry (first entry for this paricular day). Use strict === (otherwise null would also equal undefined).
				numOfOpeningPeriods = 0;
				// NOT OPEN TODAY. Check past days for very last open/close event.
				//alert("NO EVENT. CHECK DAY BEFORE");
				noEventsToday = true;
				daysBefore--; //
				findLastEvent(daysBefore); // Repeat function on day before until we find a day with events.
				return false;
			} else {
				if (daysBefore < 0) {
					// WE HAVE LOOPED - CHECKING A DAY BEFORE SO ONLY WANT VERY LAST OPENING PERIOD
					//alert("LOOPED");
					numOfOpeningPeriods = todaysOpeningPeriods.length;
					var numDaysAgo = daysBefore * -1;
					//ONLY WANT TO DEAL WITH LAST OPENING PERIOD
					var lastOpeningPeriod = timesArray[thisDatePosInArray][1];
					lastOpeningPeriod = lastOpeningPeriod[lastOpeningPeriod.length-1];
					var lastOpenEvent = lastOpeningPeriod[0];
					var lastCloseEvent = lastOpeningPeriod[1];
					if (lastCloseEvent == null) {
						// HAS NOT CLOSED YET (may be open 24 hours)
						currentlyOpen = true;
						//alert("currentlyOpen = " + currentlyOpen);
						//alert("OPENED " + numDaysAgo + " DAYS AGO ON " + convertDateArrayToString(newDate) + " at " + lastOpenEvent);
						$("#"+divID).append("<p class='currentlyOpen'>Open</p>");
						$("#"+divID).append("<hr />");
						if (noEventsToday == true) {$("#"+divID).append("<p class='openAllDay'>Open all day today / 24 hours</p>");}
						var daysString = "day";
						if (numDaysAgo > 1) {daysString+="s";}
						$("#"+divID).append("<p class='lastEvent'>Opened " + numDaysAgo + " "+ daysString + " ago on " + convertDateArrayToString(newDate) + " at <span class='lastEventTime'>" + lastOpenEvent + "</span></p>");
						return false; // TO DO -- return a value?
					} else {
						currentlyOpen = false;
						//alert("currentlyOpen = " + currentlyOpen);
						//alert("CLOSED " + numDaysAgo + " DAYS AGO ON " + convertDateArrayToString(newDate) + " at " + lastCloseEvent);
						$("#"+divID).append("<p class='currentlyClosed'>Closed</p>");
						$("#"+divID).append("<hr />");
						if (noEventsToday == true) {$("#"+divID).append("<p class='closedAllDay'>Closed all day today</p>");}
						var daysString = "day";
						if (numDaysAgo > 1) {daysString+="s";}
						$("#"+divID).append("<p class='lastEvent'>Closed " + numDaysAgo + " " + daysString + " ago on " + convertDateArrayToString(newDate) + " at <span class='lastEventTime'>" + lastCloseEvent + "</span></p>");
						return false; // TO DO -- return a value?
					}
				} else {
					// IS OPEN TODAY. Find most recent event of them all.
					//alert("Checking for most recent event of today.");					
					//alert("todaysOpeningPeriods = " + todaysOpeningPeriods);
					var minutesAgo = 60*24; // init to max number of minutes in a day.
					var now = (currentHour*60) + currentMinutes;
					for (var i=0; i<todaysOpeningPeriods.length; i++) {
						var thisOpeningPeriod = todaysOpeningPeriods[i];
						//alert("thisOpeningPeriod = " + thisOpeningPeriod);
						for (var j=0; j<thisOpeningPeriod.length; j++) {
							var thisEvent = thisOpeningPeriod[j];
							//alert("thisEvent = " + thisEvent);
							//alert("convertToMinutes(thisOpeningPeriod[j+1]) = " + convertToMinutes(thisOpeningPeriod[j+1]));
							if (thisEvent == null) {
								if (convertToMinutes(thisOpeningPeriod[j+1]) > now) {
									//alert("Nothing's happened yet, and the first event is NULL, so check the day before");
									daysBefore--; //
									findLastEvent(daysBefore); // Repeat function on day before until we find a day with events.
									return false;
									break;
								}else{
									// first null event already passed, set to zero for convenience
									thisEvent = 0;
								}
							} else {
								// NOT NULL !..
								thisEvent = convertToMinutes(thisEvent); // Convert this time string into real numbers and add up in total minutes.
							}
							//
							//alert("thisEvent (in mins) = " + thisEvent);
							
							// MAKE SURE AT LEAST ONE EVENT HAS OCCURRED SO FAR
							if (i==0 && j==0 && thisEvent>now) { // ie. very first event of the day hasn't happened yet
								// NO EVENT YET TODAY, CHECK DAY(S) BEFORE
								//alert("Nothing has happened yet today so check day(s) before for last event");
								daysBefore--; //
								findLastEvent(daysBefore); // Repeat function on day before until we find a day with events.
								return false;
								break;
							} else {
								// GET MOST RECENT
								var difference;
								var lastEvent;
								difference = now - thisEvent;
								//alert(difference);
								if (difference >=0 && difference < minutesAgo) {
									minutesAgo = difference;
									var checkOpen = isEven(j); // if i is even, we're dealing with open time, otherwise it's a close time.
									lastEvent = thisOpeningPeriod[j];
								}								
							}
						}
					}
					// FOUND MOST RECENT EVENT TODAY
					if (checkOpen == true) {
						//alert("CURRENTLY OPEN");
						currentlyOpen = true;
						//alert("OPENED " + minutesToHrsMins(minutesAgo) + " ago at " + lastEvent);
						$("#"+divID).append("<p class='currentlyOpen'>Open</p>");
						$("#"+divID).append("<hr />");
						$("#"+divID).append("<p class='lastEvent'>Opened " + minutesToHrsMins(minutesAgo) + " ago at <span class='lastEventTime'>" + lastEvent + "</span></p>");
					} else {
						//alert("CURRENTLY CLOSED");
						currentlyOpen = false;
						//alert("CLOSED " + minutesToHrsMins(minutesAgo) + " ago at " + lastEvent);
						$("#"+divID).append("<p class='currentlyClosed'>Closed</p>");
						$("#"+divID).append("<hr />");
						$("#"+divID).append("<p class='lastEvent'>Closed " + minutesToHrsMins(minutesAgo) + " ago at <span class='lastEventTime'>" + lastEvent + "</span></p>");
					}
				}
			}
		};
		
		
		
		var thirdEventTime; // use as a base for calculating "Will close/open again..." values.
		var thirdEventTimeAdd;
		
		function findNextEvent(daysAhead) {
			var newDate = getDateFromMilliseconds(daysAhead);			
			var thisDatePosInArray = checkForExceptionDay(newDate); // see what day we are currently dealing with (by position in the timesArray ie main array). // same as todayAsIndex !
			var todaysOpeningPeriods = new Array();
			todaysOpeningPeriods = timesArray[thisDatePosInArray][1];
			var numOfOpeningPeriods;			
			if (timesArray[thisDatePosInArray][1][0][0] === undefined) { // check for empty entry (first entry for this paricular day). Use strict === (otherwise null would also equal undefined).
				numOfOpeningPeriods = 0;
				// NOT OPEN TODAY. Check coming days for very next open/close event.
				//alert("NO EVENT. CHECK NEXT DAY.");
				daysAhead++; //
				findNextEvent(daysAhead); // Repeat function on day before until we find a day with events.
			} else {
				if (daysAhead > 0) {
					// WE HAVE LOOPED - CHECKING A DAY AHEAD SO ONLY WANT VERY FIRST OPENING PERIOD
					//alert("LOOPED");
					numOfOpeningPeriods = todaysOpeningPeriods.length;
					//var numDaysAhead = daysAhead * -1;
					//ONLY WANT TO DEAL WITH FIRST/NEXT OPENING PERIOD
					var nextOpeningPeriod = timesArray[thisDatePosInArray][1];
					nextOpeningPeriod = nextOpeningPeriod[0];
					var nextOpenEvent = nextOpeningPeriod[0];
					var nextCloseEvent = nextOpeningPeriod[1];
					var daysString = "day";
					if (daysAhead > 1) {
						daysString += "s"
					}
					if (currentlyOpen == true) {
						//alert("Get next close event.");
						//alert("CLOSES IN " + daysAhead + " DAYS ON " + convertDateArrayToString(newDate) + " at " + nextCloseEvent);
						$("#"+divID).append("<p class='closesIn'>Closes in " + daysAhead + " " + daysString + " on " + convertDateArrayToString(newDate) + " at <span class='nextEventTime'>" + nextCloseEvent + "</span></p>");
						thirdEventTime = convertToMinutes(nextCloseEvent) + (60*24*daysAhead);
						return false; // TO DO -- return a value?
					} else {
						//alert("Get next open event.");
						//alert("OPENS IN " + daysAhead + " DAYS ON " + convertDateArrayToString(newDate) + " at " + nextOpenEvent);
						$("#"+divID).append("<p class='opensIn'>Opens in " + daysAhead + " " + daysString + " on " + convertDateArrayToString(newDate) + " at <span class='nextEventTime'>" + nextOpenEvent + "</span></p>");
						thirdEventTime = convertToMinutes(nextOpenEvent) + (60*24*daysAhead);
						return false; // TO DO -- return a value?
					}
				} else {
					// IS OPEN TODAY. Find most recent event of them all.
					//alert("Checking for next event of today.");
					//alert(todaysOpeningPeriods);
					var minutesToGo = 60*24; // init to max number of minutes in a day.
					var now = (currentHour*60) + currentMinutes;
					for (var i=0; i<todaysOpeningPeriods.length; i++) {
						var thisOpeningPeriod = todaysOpeningPeriods[i];
						//alert("thisOpeningPeriod = " + thisOpeningPeriod);
						for (var j=0; j<thisOpeningPeriod.length; j++) {
							var thisEvent = thisOpeningPeriod[j];
							//alert("thisEvent = " + thisEvent);
							//alert("convertToMinutes(thisOpeningPeriod[j+1]) = " + convertToMinutes(thisOpeningPeriod[j+1]));
							if (thisEvent == null) {
								if (convertToMinutes(thisOpeningPeriod[j+1]) > now) {
									//alert("Nothing's happened yet, and the first event is NULL, so check the day before");
									daysAhead++; //
									findNextEvent(daysAhead); // Repeat function on day before until we find a day with events.
									return false;
									break;
								}else{
									// first null event already passed, set to zero for convenience
									thisEvent = 0;
								}
							} else {
								// NOT NULL !..
								thisEvent = convertToMinutes(thisEvent); // Convert this time string into real numbers and add up in total minutes.
							}
							//
							//alert("thisEvent (in mins) = " + thisEvent);
							//alert("thisEvent = " + thisEvent);
							// SEE IF THERE ARE ANY EVENTS LEFT TODAY
							if (i==todaysOpeningPeriods.length-1 && j==thisOpeningPeriod.length-1 && thisEvent<now) { // ie. very last event of the day has passed already
								// ALL EVENTS PASSED, CHECK NEXT DAY(S)
								//alert("No more events today. Check tomorrow.");
								daysAhead++; //
								findNextEvent(daysAhead); // Repeat function on day before until we find a day with events.
								return false;
								break;
							} else {
								// GET NEAREST
								var difference;
								var nextEvent;
								difference = thisEvent - now;
								//alert("difference = " + difference);
								var checkOpen = isEven(j); // if i is even, we're dealing with open time, otherwise it's a close time.
								if (difference > 0 && difference < minutesToGo) {
									minutesToGo = difference;
									nextEvent = thisOpeningPeriod[j];
									//alert("nextEvent = " + nextEvent);
								} else if(difference == 0 && checkOpen == false) {
									//alert("Check next");
									daysAhead++; //
									findNextEvent(daysAhead); // Repeat function on day before until we find a day with events.
									return false;
									break;
								}
							}
						}
					}
					// FOUND NEXT EVENT TODAY
					if (currentlyOpen == false) {// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<  checkOpen
						//alert("OPENS IN " + minutesToHrsMins(minutesToGo) + " at " + nextEvent);
						$("#"+divID).append("<p class='opensIn'>Opens in " + minutesToHrsMins(minutesToGo) + " at <span class='nextEventTime'>" + nextEvent + "</span></p>");
					} else {
						//alert("CLOSES IN " + minutesToHrsMins(minutesToGo) + " at " + nextEvent);
						$("#"+divID).append("<p class='closesIn'>Closes in " + minutesToHrsMins(minutesToGo) + " at <span class='nextEventTime'>" + nextEvent + "</span></p>");
					}
					thirdEventTime = convertToMinutes(nextEvent);
					thirdEventTimeAdd = minutesToGo;
					//alert("-- thirdEventTime = " + thirdEventTime);
				}
			}
		};
		
		
		

		function findThirdEvent(daysAhead) {
			//alert("Finding third event.");
			//alert("currentlyOpen = " + currentlyOpen);
			var newDate = getDateFromMilliseconds(daysAhead);
			//alert("newDate = " + newDate);
			var thisDatePosInArray = checkForExceptionDay(newDate); // see what day we are currently dealing with (by position in the timesArray ie main array). // same as todayAsIndex !
			var todaysOpeningPeriods = new Array();
			todaysOpeningPeriods = timesArray[thisDatePosInArray][1];
			var numOfOpeningPeriods;
			if (timesArray[thisDatePosInArray][1][0][0] === undefined) { // check for empty entry (first entry for this paricular day). Use strict === (otherwise null would also equal undefined).
				numOfOpeningPeriods = 0;
				// NOT OPEN TODAY. Check coming days for very next open/close event.
				//alert("NO EVENT. CHECK NEXT DAY.");
				daysAhead++; //
				findThirdEvent(daysAhead); // Repeat function on day before until we find a day with events.
			} else {
				if (daysAhead > 0) {
					// WE HAVE LOOPED - CHECKING A DAY AHEAD SO ONLY WANT VERY FIRST OPENING PERIOD
					//alert("LOOPED");
					numOfOpeningPeriods = todaysOpeningPeriods.length;
					//var numDaysAhead = daysAhead * -1;
					//ONLY WANT TO DEAL WITH FIRST/NEXT OPENING PERIOD
					var nextOpeningPeriod = timesArray[thisDatePosInArray][1];
					if (nextOpeningPeriod[0][0] != null) { //MAKE SURE WE SKIP THE EVENT IF THE EVENT IS null (ie location may have been open 24hr/day for past few days and so first open event would be null)
						nextOpeningPeriod = nextOpeningPeriod[0];
						//alert("a");
					} else {						
						if (numOfOpeningPeriods >= 2) { // if there is one, get the next opening period today
							nextOpeningPeriod = nextOpeningPeriod[1];
							//alert("b");
						}else{ // otherwise check tomorow.
							//alert("c");
							daysAhead++; //
							findThirdEvent(daysAhead); // Repeat function on day before until we find a day with events.
							return false;
						}
					}
					//alert("nextOpeningPeriod = " + nextOpeningPeriod);
					
					
					var nextOpenEvent = nextOpeningPeriod[0];
					
					var nextCloseEvent = nextOpeningPeriod[1];
					var daysString = "day";
					if (daysAhead > 1) {
						daysString += "s"
					}
					if (currentlyOpen == false) {
						//alert("Get next close event.");
						//alert("CLOSES IN " + daysAhead + " DAYS ON " + convertDateArrayToString(newDate) + " at " + nextCloseEvent);
						$("#"+divID).append("<p class='closesAgain'>Closes again in " + daysAhead + " " + daysString + " on " + convertDateArrayToString(newDate) + " at <span class='thirdEventTime'>" + nextCloseEvent + "</span></p>");
						return false; // TO DO -- return a value?
					} else {
						//alert("currentlyOpen = " + currentlyOpen);
						//alert("Get next open event.");
						//alert("OPENS IN " + daysAhead + " DAYS ON " + convertDateArrayToString(newDate) + " at " + nextOpenEvent);
						$("#"+divID).append("<p class='opensAgain'>Opens again in " + daysAhead + " " + daysString + " on " + convertDateArrayToString(newDate) + " at <span class='thirdEventTime'>" + nextOpenEvent + "</span></p>");
						return false; // TO DO -- return a value?
					}			
				} else {
					// IS OPEN TODAY. Find most recent event of them all.
					//alert("Checking for next event of today.");
					//alert(todaysOpeningPeriods);
					var minutesToGo = 60*24; // init to max number of minutes in a day.
					var now = thirdEventTime; // Must be the time of the secondEventTime (eg close if currently open, open if currently closed)
					var now2 = (currentHour*60) + currentMinutes;
					//alert("now = " + now);
					//alert("now2 = " + now2);
					for (var i=0; i<todaysOpeningPeriods.length; i++) {
						var thisOpeningPeriod = todaysOpeningPeriods[i];
						//alert("thisOpeningPeriod = " + thisOpeningPeriod);
						for (var j=0; j<thisOpeningPeriod.length; j++) {
							var thisEvent = thisOpeningPeriod[j];
							//alert("thisEvent = " + thisEvent);
							//alert("convertToMinutes(thisOpeningPeriod[j+1]) = " + convertToMinutes(thisOpeningPeriod[j+1]));
							if (thisEvent == null) {
								if (convertToMinutes(thisOpeningPeriod[j+1]) > now2) {
									//alert("Nothing's happened yet, and the first event is NULL, so check the day before");
									daysAhead++; //
									findThirdEvent(daysAhead); // Repeat function on day before until we find a day with events.
									return false;
									break;
								}else{
									// first null event already passed, set to zero for convenience
									thisEvent = 0;
								}
							} else {
								// NOT NULL !..
								thisEvent = convertToMinutes(thisEvent); // Convert this time string into real numbers and add up in total minutes.
							}
							//
							// SEE IF THERE ARE ANY EVENTS LEFT TODAY
							if (i==todaysOpeningPeriods.length-1 && j==thisOpeningPeriod.length-2 && thisEvent<now) { // ie. very last event of the day has passed already
								// ALL EVENTS PASSED, CHECK NEXT DAY(S)
								//alert("No more events today. Check tomorrow.");
								daysAhead++; //
								findThirdEvent(daysAhead); // Repeat function on day before until we find a day with events.
								return false;
								break;
							} else {
								// GET NEAREST
								var difference;
								var nextEvent;
								difference = thisEvent - now;
								//alert("difference = " + difference);
								//alert("thisEvent: " + thisEvent + "  " + "now: " + now);
								if (difference >0 && difference < minutesToGo) {
									//alert("Woo");
									minutesToGo = difference;
									//alert("minutesToGo = " + minutesToGo);
									//var checkOpen = isEven(j+1); // if i is even, we're dealing with open time, otherwise it's a close time.
									//alert("checkOpen = " + checkOpen);
								}
								if (difference >0 && difference < minutesToGo) {
									nextEvent = thisOpeningPeriod[j+1];
								}
							}
						}
					}
					// FOUND NEXT EVENT TODAY
					// ALTERNATIVE way of getting nextEvent
					var nextEventB = minutesToHrsMins(minutesToGo + thirdEventTimeAdd + now2);
					//alert("nextEventB = minutesToGo (" + minutesToGo + ") + thirdEventTimeAdd (" + thirdEventTimeAdd + ") + now2 (" + now2 + ") = " + nextEventB);
					nextEventB = nextEventB.split(" ");
					if (eval(nextEventB[3]) < 10) {nextEventB[3] = "0" + nextEventB[3]} // add leading "0" if necessary.
					nextEventB = nextEventB[0] + ":" + nextEventB[3];
					if (currentlyOpen == true) {
						if (thirdEventTimeAdd>-9999) {
							$("#"+divID).append("<p class='opensAgain'>Opens again in " + minutesToHrsMins(minutesToGo + thirdEventTimeAdd) + " at <span class='thirdEventTime'>" + nextEventB + "</span></p>");
						}
					} else {
						//alert("thirdEventTimeAdd = " + thirdEventTimeAdd); // -----------------------*************** UNDEFINED !!!!!!!-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
						if (thirdEventTimeAdd>-9999) {
							//alert("boo");
							$("#"+divID).append("<p class='opensAgain'>Closes again in " + minutesToHrsMins(minutesToGo + thirdEventTimeAdd) + " at <span class='thirdEventTime'>" + nextEventB + "</span></p>");
						}
					}
				}
			}
		};
				
		// LET'S DO IT! Calculate and display results for the current location (current itteration).////////////////////////////////////////
		$("#"+divID).addClass("openingTimesWidget");
		findLastEvent(0); // 0 = start with today
		findNextEvent(0); // 0 = start with today
		findThirdEvent(0);
		//$("#"+divID).animate({backgroundColor: '#000', color: '#fff'}, 1000).animate({backgroundColor: '#eee', color: '#000'}, 1000);
		//$("#"+divID).effect("pulsate", { times:1 }, 500);
		$("#"+divID+" .opensIn").effect("pulsate", { times:2 }, 500);
		$("#"+divID+" .closesIn").effect("pulsate", { times:2 }, 500);
		



		
	}; // end of doLocation function
	
	//
	
	function doALLlocations() {
		//doLocation(json.allMyData.location1); // hard-coded example
		// EXECUTE FUNCTION FOR ALL LOCATIONS !!!
		for (var i=0; i<allLocations.length; i++) {
			locationObj = new Object();
			locationObj = json.allMyData[allLocations[i]];
			divID = allLocations[i];
			doLocation(locationObj, divID);
		}
	};
	doALLlocations();
	// REVEAL ALL openingTimesWidget DIVs
	$(".openingTimesWidgetHeading").show();

}; // end of jsoncallback fn

/* --------------------------------------------------------------------------------------------------------------------------------------------------------------------- end of widget code --- */
