--
			--FILE: interface.lua
--
--  SERVICES: Provides data from the datastore if available in a presentable
--            format or intitiates a request if data is unavailable.
--
--  ========================================================================
--  ========================================================================
--
--               Copyright  1999-2006 QUALCOMM Incorporated
--                     All Rights Reserved.
--                   QUALCOMM Proprietary/GTDR
--
--  ========================================================================
--  ========================================================================

			require("datastore.lua")
			require("interfacetables.lua")
			loadlib("lsys")
			loadlib("lfile")
			loadlib("limage")
			loadlib("lnet")

			require("fetch.lua")

			-- Create a package
			--local P = {}

			--interface = P


			--ensure that I still have access to global env before I change
			--the env to this package

			--setmetatable(P, {__index = _G})


			--setting environment to this package
			--setfenv(1,P)

            local _intclsId = 0x0102e0f1
			local _strclsId = 0x102e0f2
			local _imageclsId = 0x01013110

			local _prevdata  = nil
			--****************************************************************************************
			--Functions to return the preset values to callers.
			--****************************************************************************************
			local function getTheatreId() 
				return interfacePresetEventsTable["theatre"]
			end

			local function getMovieId() 
				return interfacePresetEventsTable["movie"]
			end

			local function getDayId() 
				return interfacePresetEventsTable["dayId"]
			end

			local function getMovieId() 
				return interfacePresetEventsTable["movie"]
			end

			local function getPresetCityId()
				return interfacePresetEventsTable["city"]
			end

			--Default city for the weather.
			local function getDefaultCityId()
				local defloc  = datastore.getDefaultWeatherLocation()

				if (defloc == nil) or ((datastore.weather.locations ~= nil) and (datastore.weather.locations[defloc] == nil)) then
					for k,v in pairs(datastore.weather.locations) do
						return k
					end
				end

				return defloc
			end

			local function createNameToDOWMapping() 

				interfaceDOWTable = {};


				interfaceDOWTable["Sun"] = "Sunday";
				interfaceDOWTable["Mon"] = "Monday";
				interfaceDOWTable["Tue"] = "Tuesday";
				interfaceDOWTable["Wed"] = "Wednesday"
				interfaceDOWTable["Thu"] = "Thursday";
				interfaceDOWTable["Fri"] = "Friday";
				interfaceDOWTable["Sat"] = "Saturday";
		       end

			--Default category id 
			local function getDefaultCategoryId()
				local defcat = datastore.getDefaultNewsCategory()
				if defcat == nil then
				   for k,v in pairs(datastore.news.categories) do
				     return k
				   end
				end
				return defcat
			end

			--****************************************************************************************
			--End of functions to return user set values section.
			--****************************************************************************************

			--**************************************************************************************
			--Utility functions 
			--**************************************************************************************
			--
			--
			--==============================================================================
			--This function sort the table by keys
			--==============================================================================
  			function pairsByKeys (t, f)
      				local a = {}
      				for n in pairs(t) do table.insert(a, n) end
      					table.sort(a, f)
  	    				local i = 0      -- iterator variable
      					local iter = function ()   -- iterator function
       		 			i = i + 1
       		 			if a[i] == nil then return nil
       			 			else return a[i], t[a[i]]
       		 			end
     				 end
    				  return iter
  			 end
			

			function idToDay(id) 
				local _id = tonumber(id)
				if _id == 0 then
				   return "Sunday" 
			   	elseif _id == 1 then
				   return "Monday" 
			   	elseif _id == 2 then
				   return "Tuesday" 
			   	elseif _id == 3 then
				   return "Wednesday" 
			   	elseif _id == 4 then
				   return "Thursday" 
			   	elseif _id == 5 then
				   return "Friday" 
			   	elseif _id == 6 then
				   return "Saturday" 
				end
			end

			function getDOW(_ts,_dayNumber,_weather)
				local _start,_sizeStr,_key,key1
				local _httptimeStr, _err = net.utc_to_http(addLocalTime(_ts))
				_start,_sizeStr,_key = string.find(_httptimeStr,"(%a+)%s*")
			   	local _subString = string.sub(_httptimeStr,_sizeStr+2,-1)
				_start,_sizeStr,_key1 = string.find(_subString,"(%w+)")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)
				_start,_sizeStr,_key2 = string.find(_subString,"(%a+)%s*")

				local _format = ""

				if _weather ~= true then
--print("Zero based Day Number is :::",getZeroBasedDay(addLocalTime(_ts)))
					if getZeroBasedDay(addLocalTime(_ts)) == 0 then
						_format = string.format("Today, %s. %s %s",_key,_key2,_key1)
					else
						_format = string.format("%s. %s %s",_key,_key2,_key1)
					end
				else
					if _dayNumber == 0 then
						_format = "Today"
					else 
						_format = interfaceDOWTable[_key]
					end
				end
				if _interfaceDebug then
					print("Interface:Returning DOW:",_format)
					print("Interface:Day Number :",_dayNumber)
				end
				return _format
			end

			function addLocalTime(_gmtTimeStamp) 

				local _offset, daylight = sys.get_localtimeoffset();
				return _gmtTimeStamp + _offset;
			end

			
			function getFormattedLocalTime() 
				if interfaceConfigTable["channelupdatetime"] ~= nil then
				   return interfaceConfigTable["channelupdatetime"]	
				end

				if datastore.get_last_update_time() then
				   local _httptimeStr, _err = net.utc_to_http(addLocalTime(datastore.get_last_update_time()))
				   local _start, _end = string.find(_httptimeStr,"[0-9][0-9]:[0-9][0-9]",1,false)
				   local _hour   = tonumber(string.sub(_httptimeStr, _start, _start + 1))
				   local _minute = tonumber(string.sub(_httptimeStr, _end - 1, _end))
				   local _ampm   = "AM"
                                   local _minuteStr

				   if (_hour >= 12) then
				      _ampm = "PM"
				   end

				   if (_hour > 12) then
				      _hour = _hour - 12
                                   elseif (_hour == 0) then
                                      _hour = 12
                                   end

				   if (_minute <= 9) then
				      _minuteStr = "0"..tostring(_minute)
                                   else
				      _minuteStr = tostring(_minute)
                                   end

				   interfaceConfigTable["channelupdatetime"] = tostring(_hour)..":".._minuteStr.._ampm
				   return interfaceConfigTable["channelupdatetime"]
				end
				return ""
			end

			function changeSymbol(_sym) 

				if string.lower(_sym) == "djx" then
				   return "DJIA"
			   	elseif string.lower(_sym) == "snp500" then
				   return "S&P 500"
			   	elseif string.lower(_sym) == "nasdaq" then
				   return "NASDAQ"
				end
			 end


			function getZeroBasedDay(cdmaTimeStamp)
			   
			   -- This is the difference between server timestamp and 
			   -- local unixToCDMATimeDiff = 315964800
			   -- local nUnixTimeStamp = tonumber(unixTimeStamp)
			   -- local cdmaTimeStamp = nUnixTimeStamp - unixToCDMATimeDiff
			   local nCdmaTimeStamp = tonumber(cdmaTimeStamp)

			   --Add local offset to this timestamp because this is a GMT 
			   --time stamp.
			   nCdmaTimeStamp = nCdmaTimeStamp 
			   --print ("CDMAtimestampentered is " .. cdmaTimeStamp)
			   local currentCDMATimeStamp = addLocalTime(net.getutctime())
			   --print ("currentCDMATimeStamp is " .. currentCDMATimeStamp)
			   --current no of days since the CDMA epoch 
			   --local currentNoOfDays = (currentCDMATimeStamp - (currentCDMATimeStamp % 86400)) / 86400
			   --local inputNoOfDays = (cdmaTimeStamp - (cdmaTimeStamp % 86400)) / 86400
			   local currentNoOfDays = currentCDMATimeStamp / 86400
			   --print ("currentNoOfDays is " .. currentNoOfDays)
			   local inputNoOfDays = nCdmaTimeStamp / 86400
			   --print ("inputNoOfDays is " .. inputNoOfDays)
 
			   return (inputNoOfDays - currentNoOfDays)
 
 
			end

			--This function will force the datastore to persist.
			local function interfacePersistDataStore() 
				datastore.setPersist();
			end

			local function decrementday(_day) 
				local _dayId = tonumber(_day);
				_dayId = _dayId - 1
				return tostring(_dayId);
			end

			local function incrementString(_num) 

				local retNum = tonumber(_num);
				retNum = retNum + 1;
				print("Returning number:",retNum)
				return tostring(retNum);
			end

	
			-- gets a string and transforms it into a lower case and no space converted string
			local function lower_no_spaces(_str)
			
				_str = string.lower(_str)
				
				local _start = 0
				local _end = 0				
				local _word = ""
				
				while true do
					_start,_end,_key = string.find(_str,"(%w+)",_end+1)					   
					if _start == nil then break end				
					_word = _word.._key
				end
				
				return _word
			end
	
			local function mymodulus(_num1, _num2) 

				local _remainder = 0
				if (_num2 > 0) then
					local _quot = math.abs(_num1 / _num2)
					_remainder = _num1 - (_quot * _num2)
				end
				return _remainder;
			end


			--==============================================================================

			-- gets CDMA timestamp of  certain GID referring from Scores/Schedules Sport table
			local function get_timestamp_for_gid(gid, table_name)
			
			    if ( (table_name == "schedules") or (table_name == "all") ) then
					-- search timestamp in schedules
					local _local_gid = ""
					for tid,_table_ in pairs(datastore.sports.schedules) do
	                    for time,_gid_table in pairs(_table_) do
							for _gid_,v in pairs(_gid_table) do
								_local_gid =_gid_
								break
							end

	                        if (gid == _local_gid) then
						    	local info = debug.getinfo(1, "Sl")
					 	    	print ( string.format("[%s]:%d Sched Time Gid FOUND [%d][%s]", info.short_src, info.currentline, time,gid) )
	                            return time
	                        end
	                    end
					end
				end

			    if ( (table_name == "scores") or (table_name == "all") ) then
					-- search timestamp in scores
                local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]
			    if datastore.sports.scores[_DATASTORE_SID] then
				for k,v in pairs(datastore.sports.scores[_DATASTORE_SID]) do
				    -- k = timestamp, v = table with gids
					if v[gid] ~= nil then
					    	local info = debug.getinfo(1, "Sl")
					 	    	print ( string.format("[%s]:%d Score Time Gid FOUND [%d][%s]", info.short_src, info.currentline, k,gid) )
								return k -- gid found then return associate timestamp
					    end
					end
				end
			    end

                	    	local info = debug.getinfo(1, "Sl")
		    	print ( string.format("[%s]:%d timestamp for gid() NOT FOUND [0][%s]", info.short_src, info.currentline, gid) )
				return 0 --  default timestamp

			end

			-- returns the utc # of days offset (from the CDMA epoch) of "dayID"
			function getutcDayOffset(dayID)
			   return ((addLocalTime(net.getutctime())/86400) + tonumber(dayID))
			end


			function DSMovieTableExists(day_id, theatre_id, movie_id)
			  
			   --utcDayOffset = getutcDayOffset(day_id)
			   if _interfaceDebug then
			   	print("Interface:Enter DSMovieTableExists",day_id,theatre_id,movie_id)
			   	--print("Interface:utcDayOffset is " .. utcDayOffset)
			   end
			   if not datastore.movies.movie_tickets_per_movie_and_theatre or
			      not datastore.movies.movie_tickets_per_movie_and_theatre[movie_id] or
			      not datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theatre_id] then
			      	return false,nil
			    end
			    
			    for dayTS,v in pairs(datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theatre_id]) do

			      		-- dayTS is the CDMA timestamp in seconds - 
			      		-- divide by # of seconds in a day, to get CDMA timestamp in days
			    
			      if  (getZeroBasedDay(addLocalTime(tonumber(dayTS))) == tonumber(day_id)) then
			   	   if _interfaceDebug then
				      print("Inteface:Found a day_id")
				      
				     --dayTS is returned as the CDMA timestamp that matches day_id in the table
				     --
				     print("Interface: : DSMovieTableExist: Found table exists, returning dayTS " .. dayTS)
				   end
				     return true,dayTS
			     end -- end if getUTCDayOffset

			  end -- end for dayTS..

			  --nthe dayID does not exist in datastore - return false
			   return false,nil
			   

			end

			local function constructURL(_requestType,_valForURL) 
				local url
				local firsttime = 1
				print("Interface:Enter: Construct URL ..request type and value",_requestType,_valForURL)

    				local server_name = sys.get_config_string(CFGI_OD_SERVER_NAME)
				
				url = string.format("http://%s/od2/",server_name)

				--In case of channels _valForURL is a table else 
				--string.
				if _requestType == "help" then
				    url = string.format("%shelp",url)
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "help"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL

				elseif _requestType == "channels" then
					for k,v in pairs(_valForURL) do 
					   if firsttime == 1 then
					     url = string.format("%schannels?id=%s",url,v)
					     interfaceHTTPStatusTable["channelName"] = v
					     firsttime = 0
					   else
					     url = string.format("%s,%s",url,v)
					     interfaceHTTPStatusTable["channelName"] = interfaceHTTPStatusTable["channelName"]..","..v
					   end
					end
				        interfaceHTTPStatusTable["eventName"] = "update"
				elseif _requestType == "detailedstory" then
				    url = string.format("%sstory?id=%s&full=1",url,_valForURL)
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "detailedstory"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL

				elseif _requestType == "weatherweek" then -- here id is the location id.
				    url = string.format("%sweather/week?id=%s",url,_valForURL)
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "weatherweek"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL
				elseif _requestType == "weatherdetails" then -- here id is the location id.
				    url = string.format("%sweather/detail?%s",url,_valForURL)
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "weatherdetails"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL

				elseif _requestType == "sports" then 
				    url = string.format("%ssports",url);

				    interfaceHTTPStatusTable["eventName"] = "foregroundRequest";
				    interfaceHTTPStatusTable["foregroundrequestType"] = "sports"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL; -- NIL


				elseif _requestType == "sportsstandings" then 
				    url = string.format("%ssports/standings?id=%s",url,_valForURL);

				    interfaceHTTPStatusTable["eventName"] = "foregroundRequest";
				    interfaceHTTPStatusTable["foregroundrequestType"] = "sportsstandings"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL;

				elseif _requestType == "sportsscores" then 
				    url = string.format("%ssports/scores?id=%s",url,_valForURL);

				    interfaceHTTPStatusTable["eventName"] = "foregroundRequest";
				    interfaceHTTPStatusTable["foregroundrequestType"] = "sportsscores"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL;

				elseif _requestType == "sportsschedules" then 
				    url = string.format("%ssports/schedules?id=%s",url,_valForURL);

				    interfaceHTTPStatusTable["eventName"] = "foregroundRequest";
				    interfaceHTTPStatusTable["foregroundrequestType"] = "sportsschedules"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL;

				elseif _requestType == "sportsteams" then 
				    url = string.format("%ssports/teams?id=%s",url,_valForURL);

				    interfaceHTTPStatusTable["eventName"] = "foregroundRequest";
				    interfaceHTTPStatusTable["foregroundrequestType"] = "sportsteams"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL;

				elseif _requestType == "sportsgames" then 
				    url = string.format("%ssports/game?id=%s",url,_valForURL);

				    interfaceHTTPStatusTable["eventName"] = "foregroundRequest";
				    interfaceHTTPStatusTable["foregroundrequestType"] = "sportsgames"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL;
				    
				elseif _requestType == "moviestheatre" then 
				    url = string.format("%smovies?theater=%s",url,_valForURL)
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "moviestheatre"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL
				elseif _requestType == "moviesmovie" then 
				    url = string.format("%smovies?movie=%s",url,_valForURL)
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "moviesmovie"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL
				elseif _requestType == "movieurl" then 
				    url = string.format("%smovies?movie=%s&theater=%s",url,_valForURL[1],_valForURL[2])
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "movieurl"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL

				elseif _requestType == "stockdetails" then
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "stockdetails"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL
				    url = string.format("%sstocks/detail?id=%s",url,_valForURL)
				 elseif _requestType == "getzipcode" then
				    interfaceHTTPStatusTable["eventName"] = "update"
				    interfaceHTTPStatusTable["foregroundrequestType"] = "getzipcode"
				    interfaceHTTPStatusTable["foregroundrequestid"] = _valForURL
				    url = string.format("%sregister",url)

				end

				print("Interface:Exit: Construct URL ..request type and value",url)
				return url

			end

			local function loadImage(_fspath)
				print("Loading Image for the fspath ::",_fspath)

				interfacePresetEventsTable["imgptr"] = nil

				if _fspath ~= nil then
				   local imgPtr, err = image.new(_fspath)

				   interfacePresetEventsTable["imgptr"] = imgPtr
				end 

				return interfacePresetEventsTable["imgptr"]
			end
			--**************************************************************************************
			--End of Utility functions section
			--**************************************************************************************

			--*****************************************************************************************
			--Interface table creation functions sections
			--*****************************************************************************************
			
			--==============================================================================
			--This function constructs the interface config table.
			--This table is created when user sets the zip code for the first time also
			--check if the table is existing then dont create it as user may change the
			--zipCode after setting it once.
			--Status is updated on receiving the response back from fetch of the register request.
			--==============================================================================
			local function createInterfaceConfigTable() 
				interfaceConfigTable = {}
				interfaceConfigTable["zipcode"] = ""
				interfaceConfigTable["status"] =  ""
				interfaceConfigTable["updating"] =  "_false"
			        interfaceConfigTable["requestfired"] =  "_false"
				interfaceConfigTable["isactive"] =  "_false"
				interfaceConfigTable["updatestatus"] =  ""
				interfaceConfigTable["channelupdatetime"] = nil
				interfaceConfigTable["hotlined"] =  "_false"
				interfaceConfigTable["help"] =  ""
				interfaceConfigTable["autoupdateenable"] =  "_true"
				interfaceConfigTable["datastoreerror"] =  false
				if datastore.getZipCode() then
					interfaceConfigTable["zipcodestatus"] =  "success"
				else
					interfaceConfigTable["zipcodestatus"] =  ""
				end	
		        end

			--==============================================================================
			--This function will create a generic table for values and status of all the 
			--http foreground requests, actor's data pointer registered for callback.
			--==============================================================================
			local function createGenericTableForCallbacks() 

				interfaceHTTPStatusTable = {}

				--This field is filled when dataActor registers for the callback.
				interfaceHTTPStatusTable["dataActorPtr"] = ""

				--This field is filled whenever foreground request is fired or 
				--whenever the foreground request is initiated by the interface 
				--layer the eventName will be "update".
				interfaceHTTPStatusTable["eventName"] = ""

				--Name of the channel for the foreground request.
				interfaceHTTPStatusTable["channelName"] = ""

				--This will be dataStoretableName set by the interface layer when
				--foreground request is initialed.
				--Interface will use this name when the response is received from the 
				--fetch layer.
				--This value is reset once the data is updated into the dataStore.
				interfaceHTTPStatusTable["foregroundrequestType"] = ""

				--Unique id set by the interface layer when firing a foreground request
				--which is used by setting the values into dataStore after the response
				--is received from the fetch layer.
				--This value is reset once the data is updated into the dataStore.
				interfaceHTTPStatusTable["foregroundrequestid"] = ""


				interfaceHTTPStatusTable["url"] = ""

				--This field will contain the day number for which the details request is fired.
				interfaceHTTPStatusTable["weatherday"] = ""

				--This field will contain the cid for which the details request is fired.
				interfaceHTTPStatusTable["weathercid"] = ""

			end
			--==============================================================================
			--This function creates a category table when TrigML request for a category count.
			--==============================================================================
			local function createinterfacecattable()

				interfaceCatTable =  {}
				local count = 0

				for k,v in pairs(datastore.news.categories) do
				   if getDefaultCategoryId() ~= k then
					interfaceCatTable[tostring(count)] = k
					count = count + 1
				   end
				end
				for k,v in pairs(datastore.news.categories) do
				   if getDefaultCategoryId() == k then
					interfaceCatTable[tostring(count)] = k
					count = count + 1
				end
				end

				if _interfaceDebug then
					print "interfaceCatTable = "
					for k,v in pairs(interfaceCatTable) do
						print ("[\"" .. k .. "\"] = " .. v)   
					end
				end

			end	
		
			--==============================================================================
			--This function creates a cities table when TrigML request for a cities count.
			--==============================================================================
			local function createinterfacecitiestable()

				interfacecitiesTable =  {}
				local count = 0
	
				for k,v in pairs(datastore.weather.locations) do
					interfacecitiesTable[tostring(count)] = k
					count = count + 1
				end

				if _interfaceDebug then
					print "interfacecitiesTable = "
					for k,v in pairs(interfacecitiesTable) do
						print ("[\"" .. k .. "\"] = " .. v)  
					end
				end

			end
			--==============================================================================
			--This function creates an alerts table when TrigML request for a cities count.
			--This table is a mapping of weather.alerts table for all the non-viewed alerts
			--and its created when TrigML requests for Alert Count

			--This table is also updated on the new alerts
			--==============================================================================
			local function createinterfacealertstable()

				interfaceNewAlertsTable =  {}
				local count = 1
				local cidcount = 0
	
				local interfaceCIDBasedAlerts = {}

				for _cid,v in pairs(datastore.weather.locations) do
					interfaceCIDBasedAlerts[_cid] = {} --Create a table for city.
					for k1,v1 in pairs(datastore.weather.locations[_cid].alerts) do
					  if datastore.weather.alerts[v1] ~= nil then
					     --Check if this is a new alert then only add to the table.
					     if datastore.weather.alerts[v1].flag == true then
					       interfaceCIDBasedAlerts[_cid][datastore.weather.alerts[v1].timestamp] = v1;
				  	     end
				  	  end
					end
				end


				--Now we have all the alerts per city basis. We need to sort
				--them on the timestamp basis.
				for k,v in pairs(interfaceCIDBasedAlerts) do
				  table.sort(interfaceCIDBasedAlerts[k]);
				end


				for k,v in pairs(interfaceCIDBasedAlerts) do
				   local alertcount = 1;
				   for k1,v1 in pairs(interfaceCIDBasedAlerts[k]) do
				   	interfaceNewAlertsTable[count] = {};
				   	interfaceNewAlertsTable[count].alert = v1;
				   	interfaceNewAlertsTable[count].cid = k;
				   	local _txt = string.format("Alert %d - %s",
				      	alertcount,datastore.weather.alerts[v1].text)
				   	interfaceNewAlertsTable[count].text = _txt;
					    count = count + 1
					    alertcount = alertcount + 1
				    end
				end

				--table.sort(interfaceNewAlertsTable);

				  
				if _interfaceDebug then

			        	print "interfaceCIDBasedAlerts = "

					for k,v in pairs(interfaceCIDBasedAlerts) do
				    		print ("[\"" .. k .. "\"] = " )  
						for k1,v1 in pairs(interfaceCIDBasedAlerts[k]) do
					   		print(k1..":"..v1)
						end
					end

					print "interfaceNewAlertsTable = "
					for k,v in pairs(interfaceNewAlertsTable) do
						print ("[\"" .. k .. "\"] = ")  
						print ("alertNumber = "..interfaceNewAlertsTable[k].alert)  
						print ("alertCity = "..interfaceNewAlertsTable[k].cid)  
						print ("AlertText = "..interfaceNewAlertsTable[k].text)  
					end

				end
			end

			--==============================================================================
			--This function creates a theatres table when TrigML request for a theatre count.
			--==============================================================================
			local function createinterfacetheatrestable()

				interfacetheatresTable =  {}
				local count = 0
				for k,v in pairs(datastore.movies.theatres) do
					interfacetheatresTable[tostring(count)] = k
					count = count + 1
				end


				if _interfaceDebug then
					print "interfacetheatresTable = "
					for k,v in pairs(interfacetheatresTable) do
						print ("[\"" .. k .. "\"] = " .. v)  
					end
				end
			end


			--==============================================================================
			--This function creates a money table when TrigML request for a money count.
			--==============================================================================
			local function createinterfacemoneytable()

				interfaceMoneyTable =  {}
				local count = 0
			
				for k,v in pairs(datastore.money.markets) do
					if string.lower(k) == "djx" then
					  count = 0;
				  	elseif string.lower(k) == "nasdaq" then
					  count = 1;
				  	elseif string.lower(k) == "snp500" then
					  count = 2;
					end
					interfaceMoneyTable[tostring(count)] = k
				end

				count = 3;
				for k,v in pairs(datastore.money.portfolio) do
					interfaceMoneyTable[tostring(count)] = k
					count = count + 1
				end

				if _interfaceDebug then
					print "interfaceMoneyTable = "
					for k,v in pairs(interfaceMoneyTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end
			end

			--==============================================================================
			--This function creates a 1 based mapping for weather summary timestamp
			--==============================================================================
			local function createInterface7DaySummaryTable(loc_id) 

				if datastore.weather.summary[loc_id] == nil then
					print("Interface:Unable to create weather 7 day TS mapping because no data")
					return;
				end
				local cnt = 1;
				local t_weatherTSMapping= {}
				weatherTSMapping= {}
				for ts,v in pairs(datastore.weather.summary[loc_id]) do
					t_weatherTSMapping[cnt] = ts
					cnt = cnt + 1;
				  end
	
				cnt = 0;
				
				--sorting the table for timestamp
				table.sort(t_weatherTSMapping);

				cnt = 0;
				for k,v in ipairs(t_weatherTSMapping) do
					weatherTSMapping[tostring(cnt)] = v;
					cnt = cnt + 1;
				end

				t_weatherTSMapping= nil;

				--sort this table
				if _interfaceDebug then
					print "weatherTSMapping = "
					for k,v in pairs(weatherTSMapping) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

			end
			--==============================================================================
			--This function creates an alerts table for a preset cityId
			--==============================================================================
			local function createInterfaceAlertsTableByCid(_cid)
				interfaceAlertsByCityTable =  {}
				local count = 0

				for k,v in pairs(datastore.weather.locations[_cid].alerts) do
					interfaceAlertsByCityTable[tostring(count)] = v
					count = count + 1
				end

				if _interfaceDebug then
					print "interfaceAlertsByCityTable = "
					for k,v in pairs(interfaceAlertsByCityTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end
			end

			--==============================================================================
			--This function creates a movies table when TrigML request for a allMovies count.
			--==============================================================================
			local function createinterfaceallmoviestable()

				interfaceAllMoviesTable =  {}
				local count = 0

				for k,v in pairs(datastore.movies.movielist) do
					interfaceAllMoviesTable[tostring(count)] = k
					count = count + 1
				end

				if _interfaceDebug then
					print "interfaceAllMoviesTable = "
					for k,v in pairs(interfaceAllMoviesTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end
			end



				--==============================================================================
	    			--This table is created when user sets a theatre,day  and the movie is already selected
				--==============================================================================

				function createinterfaceTheatreMovieTimeURLTable(day_id,theatre_id,movie_id)

			   	   	if _interfaceDebug then
  						print("Interface:In createTheatreMovieTimeURLTable: DayId, TID and MID",day_id,theatre_id,movie_id)
					end
  					interfaceTheatreMovieTimeURLTable = {}
  					timeCount = 0
  					dayCount = 0
					local fireURL = false
					local utcDayID = 0;


					local count = 1;
					local ts,ret
					interfaceTheatreMovieTimeURLTable = {} 

				--if any of these values are nil then fire a foreground request for the
				--theatre times and url.
					if datastore.movies.movie_tickets_per_movie_and_theatre == {} then
			   	   		if _interfaceDebug then
							print("Interface:Datastore table is empty - firing request")
						end
						fireURL = true
					else
					  --Check if day_id is noDayAvailable that means its from chooserDetails
					  --and for that there is a different kind of check.
					   if day_id ~= "noDayAvailable" then

					   	ret,ts = DSMovieTableExists(day_id, theatre_id, movie_id)

					   	if not ret then
						   fireURL = true
					   	end -- end of ret if
					   else
						if datastore.movies.movie_tickets_per_movie_and_theatre == nil or 
				      		   datastore.movies.movie_tickets_per_movie_and_theatre[movie_id] == nil or
				      		   datastore.movies.movie_tickets_per_movie_and_theatre[movie_id].details == nil then

						    fireURL = true;
				   		end

				   	   end --end of day_id=noDayAvailable if
				       end -- end of "datastore.movies.movie_tickets_per_movie_and_theatre" if
					
				       if fireURL then 
			   	   	      if _interfaceDebug then
					      	print("Interface:Firing foreground request for movie URL table");
					      end
					      local _urltable = {};
					      _urltable[1] = movie_id
					      _urltable[2] = theatre_id
					      _urltable[3] = day_id
					      handleStartForeground(constructURL("movieurl",_urltable))
					      interfacePresetEventsTable["last_request_table_key"] = _urltable

					      return;
					end
					   
					
--if day_id is noDayAvailable then dont create the table because its from chooserDetails.
if day_id ~= "noDayAvailable" then
for k,v in pairs(datastore.movies.movie_tickets_per_movie_and_theatre[movie_id][theatre_id][ts]) do
					for k1,v1 in pairs(v) do

						interfaceTheatreMovieTimeURLTable[count] = {};
						interfaceTheatreMovieTimeURLTable[count].time = k1;
						interfaceTheatreMovieTimeURLTable[count].url = v1;
						count = count + 1;
					end

end
	

					--table.sort(interfaceTheatreMovieTimeURLTable)
					if _interfaceDebug then
						for k,v in ipairs( interfaceTheatreMovieTimeURLTable) do
	   	    				    print ("[" .. k .. "\"] = {")
	   	    				    print ("time = \"" .. interfaceTheatreMovieTimeURLTable[k].time .. "\",")
	   	    				    print ("url = \"" .. interfaceTheatreMovieTimeURLTable[k].url .. "\",")

					    	end
						print("}")
					end
end

			     end

				--==============================================================================
	    			--This table is created when user sets a movie and looks for the theatre list
				--and timeSummary
				--==============================================================================
			        function createTheatreListForPresetMovie(mid)

					local count = 1;
					local firsttime = 1;
					interfaceTheatreListForPresetMovie = {}

					--first convert the zero-based day-id into the number of days since the CDMA epoch
				
					--local utcDayID = getutcDayOffset(day)
					
					if datastore.movies.theatreshowsbymovie == nil or
					   datastore.movies.theatreshowsbymovie[mid] == nil then
					   	print("Interface:Theatreshowsbymovie does not have entry. Firing FG request")
					        interfacePresetEventsTable["last_request_table_key"] = mid
						handleStartForeground(constructURL("moviesmovie",mid))
						return;
					end
			local tempTableForSorting = {}
			for k,v in pairs(datastore.movies.theatreshowsbymovie[mid]) do
				tempTableForSorting[tonumber(k)] = v
			end
			table.sort(tempTableForSorting)
			if _interfaceDebug then
   				print ("tempTableForSorting = {")
  				for k,v in pairs(tempTableForSorting) do
  					print ("[\"" .. k .. "\"] = " .. "\"" )
  					print ("Value of v is:",v)
				end
			end


			local strdayid = 1
			for k,v in pairsByKeys(tempTableForSorting) do
			   -- here k is the CDMA timestamp (as a day-id)
			   -- this needs to be converted into a zero-based dayID (0 being today)
  			        local day_id = getZeroBasedDay(addLocalTime(k))
		   	   	if _interfaceDebug then
			   		print("Interface:CDMA time = " .. k .. " and day id " .. (day_id or "none"))
			   	end
				if day_id >= 0 then
				local count = 0
				   interfaceTheatreListForPresetMovie[strdayid] = {}
	    			for k2,v2 in pairs(v) do  -- here k2 = movie id
				      interfaceTheatreListForPresetMovie[strdayid][tostring(count)] = {}
				      interfaceTheatreListForPresetMovie[strdayid][tostring(count)].tid = k2
				      interfaceTheatreListForPresetMovie[strdayid][tostring(count)].ts = k --storing timestamp
				      interfaceTheatreListForPresetMovie[strdayid][tostring(count)].timeSummary = ""
		   			for k3,v3 in pairs(v2) do --this loop is for time summary
					 interfaceTheatreListForPresetMovie[strdayid][tostring(count)].timeSummary = v3
				      end -- end of k3 v3 for loop
	    
	       				count = count + 1
	   			end -- end of k2 v2 for loop
				strdayid = strdayid + 1
				end -- if day_id >= 0
    			end --end of k,v for loop

				if  _interfaceDebug then
   					print ("interfaceTheatreListForPresetMovie = {")
					for k,v in pairs(interfaceTheatreListForPresetMovie) do
   					    print ("[" .. k .. "\"] = {")
   			  		  for k1,v1 in pairs(v) do 
  		   				print ("[\"" .. k1 .. "\"] = {")
     						print ("ts = \"" .. interfaceTheatreListForPresetMovie[k][k1].ts .. "\"")
     						print ("tid = \"" .. interfaceTheatreListForPresetMovie[k][k1].tid .. "\"")
     						print ("timeSummary = \"" .. interfaceTheatreListForPresetMovie[k][k1].timeSummary .. "\"")
     						print ("},")
   			  		  end
   			 		   print ("},")
					end
  					print ("}")
				end
			end


			
			--==============================================================================
			--This table will contain the list of movies for a specific theatre 
			--on a per day basis
			--==============================================================================

			function createinterfaceMovieListTablePresetTheatreTable(theatre_id)

			interfaceMovieListForAPresetTheatre = {}
	
			--Foreground request for list of movies for a specific theatre.
			if datastore.movies.movieshowsbytheatre == nil or 
			   datastore.movies.movieshowsbytheatre[theatre_id] == nil then
			   print("Interface:No data!(): Firing foreground request, theatre_id = " .. theatre_id)
				interfacePresetEventsTable["last_request_table_key"] = theatre_id
				handleStartForeground(constructURL("moviestheatre",theatre_id))
				return;
			end

			local tempTableForSorting = {}
			for k,v in pairs(datastore.movies.movieshowsbytheatre[theatre_id]) do
				tempTableForSorting[tonumber(k)] = v
			end
			table.sort(tempTableForSorting)
			if _interfaceDebug then
   				print ("tempTableForSorting = {")
  				for k,v in pairs(tempTableForSorting) do
  					print ("[\"" .. k .. "\"] = " .. "\"" )
  					print ("Value of v is:",v)
				end
			end


			local strdayid = 1
			for k,v in pairsByKeys(tempTableForSorting) do
			   -- here k is the CDMA timestamp (as a day-id)
			   -- this needs to be converted into a zero-based dayID (0 being today)
  			        local day_id = getZeroBasedDay(addLocalTime(k))
		   	   	if _interfaceDebug then
			   		print("Interface:CDMA time = " .. k .. " and day id " .. (day_id or "none"))
				end
				if day_id >= 0 then 
				local count = 0
				   interfaceMovieListForAPresetTheatre[strdayid] = {}
	    			for k2,v2 in pairs(tempTableForSorting[k]) do  -- here k2 = movie id
				      interfaceMovieListForAPresetTheatre[strdayid][tostring(count)] = {}
				      interfaceMovieListForAPresetTheatre[strdayid][tostring(count)].mid = k2
				      interfaceMovieListForAPresetTheatre[strdayid][tostring(count)].ts = tostring(k) --storing timestamp
				      interfaceMovieListForAPresetTheatre[strdayid][tostring(count)].timeSummary = ""
		   			for k3,v3 in pairs(v2) do --this loop is for time summary
					 interfaceMovieListForAPresetTheatre[strdayid][tostring(count)].timeSummary = v3
				      end -- end of k3 v3 for loop
	    
	       				count = count + 1
	   			end -- end of k2 v2 for loop
			        strdayid = strdayid + 1
				end -- if day_id >= 0
    			end --end of k,v for loop

			if  _interfaceDebug then
   			print ("interfaceMovieListForAPresetTheatre = {")
			for k,v in pairs(interfaceMovieListForAPresetTheatre) do
   			    print ("[" .. k .. "\"] = {")
   			    for k1,v1 in pairs(v) do 
     				print ("[\"" .. k1 .. "\"] = {")
     				print ("ts = \"" .. interfaceMovieListForAPresetTheatre[k][k1].ts .. "\"")
     				print ("mid = \"" .. interfaceMovieListForAPresetTheatre[k][k1].mid .. "\"")
     				print ("timeSummary = \"" .. interfaceMovieListForAPresetTheatre[k][k1].timeSummary .. "\"")
     				print ("},")
   			    end
   			    print ("},")
			end
  			print ("}")
			end -- end of debug if

		
	end -- end of function

			--==============================================================================
			--This table is created when user sets the category.
			--==============================================================================
			function isNewsIDNotPresent(t, newsid)

			  for k,v in pairs(t) do
	 			if v == newsid then return false end
  			  end
  
  			  return true

			end
			

			--==============================================================================
			--This function takes a list of categories in a table and creates a story table
			--based on the categories passed to this table. If 2 or morecategories are passed 
			--to this table then story table will be interlaced 
			--==============================================================================
			function createNewsIDsTable( categoriesTable )

   			interfaceStoryTableCat1 = {}
   			interfaceStoryTableCat2 = {}
				interfaceStoryTable = {}
   			count1 = 1
  
   			-- there is hardcoding assuming that that categoriesTable will always
   			-- contain two sub-tables only
   			firstcategory = categoriesTable[1]
   			secondcategory = categoriesTable[2]

					for k,v in pairs(datastore.news.headlines) do -- go over all the headlines

					--verify that we don't already have this news ID in the table
      
      				if isNewsIDNotPresent(interfaceStoryTableCat1, k) then 
	
        			    --go over all the categories for news item "k" 
			    				for i1,category in ipairs(v.categories) do
	    
							-- if news item "k" is in the category we are interested in
	    
	    				if category == firstcategory then           
									-- add it to the table
	       				    interfaceStoryTableCat1[count1] = k
	       				    count1 = count1 + 1
	       				    break
	    				end -- end if category == catid
	    
	 			    end -- end for i1,category
	 
      				end -- end if isNewsIDNotPresent
	 
     			end  -- end for k,v in pairs

   			-- at the end of this loop, we have all the news ids that match 
			-- category1 in interfaceStoryTableCat1

  			count2 = 1
			if interfacePresetEventsTable["categorytype"] == "multiple" then
  			for k,v in pairs(datastore.news.headlines) do -- go over all the headlines again
	      
      			--verify that we don't already have this news ID in either of the tables
      
      			    if isNewsIDNotPresent(interfaceStoryTableCat1, k) and 
			       isNewsIDNotPresent(interfaceStoryTableCat2, k)  then 
	
        			--go over all the categories for news item "k" 
	 			for i1,category in ipairs(v.categories) do
	    
	    			     -- if news item "k" is in the category we are interested in
	    			     if category == secondcategory then           
					-- add it to the table
	       				interfaceStoryTableCat2[count2] = k
	       				count2 = count2 + 1
									break
	    			     end -- end if category == catid
	    
	 		        end -- end for i1,category
	 
                            end -- end if isNewsIDNotPresent
	 
                         end  -- end for k,v in pairs
  
			-- at the end of this loop, we have all the news ids that match 
			-- category2 in interfaceStoryTableCat2 (and are not duplicates from cat1)
				if count1 > 3 then
					interfacePresetEventsTable["categorycount1"] = 3
				else
					interfacePresetEventsTable["categorycount1"] = count1 - 1
				end
				if count2 > 3 then
					interfacePresetEventsTable["categorycount2"] = 3
				else
					interfacePresetEventsTable["categorycount2"] = count2 - 1
				end
      
				local _icount = 0
				if count1 > 1 and count2 > 1 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat1[1]
						_icount = _icount + 1
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat2[1]
						_icount = _icount + 1
					if count1 > 2 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat1[2]
					else
						interfaceStoryTable[tostring(_icount)] = "invalid"
					end
						_icount = _icount + 1
					if count2 > 2 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat2[2]
					else
						interfaceStoryTable[tostring(_icount)] = "invalid"
					end
					_icount = _icount + 1
					if count1 > 3 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat1[3]
					else
						interfaceStoryTable[tostring(_icount)] = "invalid"
					end
						_icount = _icount + 1
					if count2 > 3 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat2[3]
					else
						interfaceStoryTable[tostring(_icount)] = "invalid"
			    				end
				elseif count1 > 1 then
					interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat1[1]
						_icount = _icount + 1
					if count1 > 2 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat1[2]
						_icount = _icount + 1
			    	end
					if count1 > 3 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat1[3]
					end
				elseif count2 > 1 then
					interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat2[1]
						_icount = _icount + 1
					if count2 > 2 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat2[2]
						_icount = _icount + 1
					end
					if count2 > 3 then
						interfaceStoryTable[tostring(_icount)] = interfaceStoryTableCat2[3]
			    	end
			    end
			    else 
				local _catcount = 1
				while (_catcount < count1) do
					interfaceStoryTable[tostring(_catcount - 1)] = interfaceStoryTableCat1[_catcount]
					_catcount = _catcount + 1
						end
				end

			if _interfaceDebug then
   					print ("interfaceStoryTable = {")
  					for k,v in pairs(interfaceStoryTable) do
  						print ("[\"" .. k .. "\"] = " .. "\"" .. v .. "\",")
	 					print ("Story::"..datastore.news.headlines[v].label)
  					end
      				print ("}")
			end
   
   
		       end -- end of function


			--==============================================================================
			--This function creates an empty table for preset events. These values will be
			--filled as and when events are received.
			--==============================================================================
			local function createInterfacePresetEventsTable()

				interfacePresetEventsTable = {}

				interfacePresetEventsTable["category"] = ""
				interfacePresetEventsTable["multiplecategory1"] = ""
				interfacePresetEventsTable["multiplecategory2"] = ""
				interfacePresetEventsTable["categorycount1"] = 0
				interfacePresetEventsTable["categorycount2"] = 0
				interfacePresetEventsTable["categorytype"] = ""
				interfacePresetEventsTable["channel"] = ""
				interfacePresetEventsTable["city"] = ""
				interfacePresetEventsTable["sport"] = ""
				interfacePresetEventsTable["team"] = ""
				interfacePresetEventsTable["table"] = ""
				interfacePresetEventsTable["theatre"] = ""
				interfacePresetEventsTable["movie"] = ""
				interfacePresetEventsTable["dayId"] = "0"
				interfacePresetEventsTable["timestamp"] = 0
				interfacePresetEventsTable["purchasemovie"] = ""
				interfacePresetEventsTable["ticketquantity"] = ""
				interfacePresetEventsTable["updatechannel"] = ""
				interfacePresetEventsTable["sportsteamid"] = ""
				interfacePresetEventsTable["imgptr"] = nil
				interfacePresetEventsTable["previouscidagainstalert"] = nil

				interfacePresetEventsTable["sport_sid"] = "2"
				interfacePresetEventsTable["sport_datastore_sid"] = "0"

				interfacePresetEventsTable["last_request_table"] = ""
				interfacePresetEventsTable["last_request_table_key"] = ""
				interfacePresetEventsTable["last_request_table_msg_string"] = ""
				interfacePresetEventsTable["alertviewed_requested"] = false;
				interfacePresetEventsTable["defaultcategorycount"] = "0"

				if _interfaceDebug then
					print "interfacePresetEventsTable = "
					for k,v in pairs(interfacePresetEventsTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end
			end


			--*****************************************************************************************
			--end of interface table creation functions section
			--*****************************************************************************************
			

			--
			--****************************************************************************************
			--Callback functions section
			--****************************************************************************************
			
			--==============================================================================
			--This function is passed to the fetch for a call for updating the
			--status of the register request.
			--GLOBAL FUNCTION
			--==============================================================================
			function callbackFnDataStoreUpdate(_status, weatherAlertFlag)
	
				local _dataActorPtr = interfaceHTTPStatusTable["dataActorPtr"]
	
				print("Interface:Enter:I am in datastore callback after update status.",
				_status,weatherAlertFlag)

				if _status < 0 then
				  interfaceConfigTable["updatestatus"] = "500"
				  interfaceConfigTable["datastoreerror"] = true;
				  print("Interface:Datastore error occured during the update");
				  print("Interface:Sending update failed to actor")
				  bucket.CallBck(_dataActorPtr,"updateFailed","","")
				end

				if weatherAlertFlag then
					print("Interface:I am in datastore weather callback after update.")
					--Alerts table reconstruction
					createinterfacealertstable()
					
					--interfaceHTTPStatusTable["eventName"] = "weatherAlert"

					--Name of the channel for the foreground request.
					--interfaceHTTPStatusTable["channelName"] = ""

					--bucket.CallBck(_dataActorPtr,interfaceHTTPStatusTable["eventName"],
					--	"","")
					--return;

				end
				-- Reconstructing all the tables when datastore is updated.
				
				--alerts table needs to be updated in both the cases.
				createinterfacealertstable()
				if interfacePresetEventsTable["city"] ~= "" then
					createInterface7DaySummaryTable(interfacePresetEventsTable["city"]);
				end
				-- Money table
				createinterfacemoneytable()

				--Cities table
				createinterfacecitiestable()

				--Category table
    				createinterfacecattable()

				--Create a new story table after receiving the categories.
				--Making the story table blank
				interfaceStoryTable = {}
				local catTable = {}
				if interfacePresetEventsTable["categorytype"] == "single" and interfacePresetEventsTable["category"] ~= "" then 
					catTable[1] = interfacePresetEventsTable["category"]
				elseif interfacePresetEventsTable["categorytype"] == "multiple" and interfacePresetEventsTable["multiplecategory1"] then
					catTable[1] = interfacePresetEventsTable["multiplecategory1"]
					catTable[2] = interfacePresetEventsTable["multiplecategory2"]
				else
					interfacePresetEventsTable["categorytype"] = "single"
					interfacePresetEventsTable["category"] = getDefaultCategoryId()
					catTable[1] = interfacePresetEventsTable["category"]
				end
				createNewsIDsTable(catTable)
				if interfacePresetEventsTable["categorytype"] == "single" then
					if interfaceCatTable and (interfacePresetEventsTable["category"] == getDefaultCategoryId()) then
						local cnt = 0

						for k,v in pairs(interfaceStoryTable) do
							cnt = cnt+1
						end
						interfacePresetEventsTable["defaultcategorycount"] = tostring(cnt)
					end
				end

				--AllMovies table
    			createinterfaceallmoviestable()
				interfaceConfigTable["channelupdatetime"] = nil

			      if datastore.ota ~= nil then
				if datastore.ota.newUrl == true then
				   datastore.ota.newUrl = false
				   bucket.CallBck(_dataActorPtr,"launchUrl","url","ondemand:UpdateUI?id=ui")
				end
			      end

				if interfaceConfigTable["isactive"] ==  "_false" then
					bucket.CallBck(_dataActorPtr,"update","channel","all")
				end
			 	print("Interface:Exit:I am in datastore callback after update.")
		      end

			--==============================================================================
			--This function is called by the fetch layer to update with a status codes.
			--status -- HTTP status code.
			--Data  -- This value is filled by fetch only when the final data is received
			--from the server otherwise it will be nil.
			--==============================================================================
			local function callbackFnForegroundStatusUpdate(url,_status,data)
				print("Interface:Enter: I am in call back with _status and data",_status,data)

				--Check for the datastore error. If that occured then don't do anything
				--simply send update failed to actor.
				if interfaceConfigTable["datastoreerror"] == true then
					interfaceConfigTable["datastoreerror"] = false;
					_status =  "500"
				end

				interfaceConfigTable["updatestatus"] = _status
				--When the callback status is success
				--1. Update the dataStore for all the foreground request and when
				--channelName is nil because all the channels requests are directly
				--updated .
				--2. Once the update is done reset the channelName and eventName.
				--3. Data Actor pointer is never reset once registered.
				local _channelName = interfaceHTTPStatusTable["channelName"]
				local _foregroundreqId = interfaceHTTPStatusTable["foregroundrequestid"]
				local _dataActorPtr = interfaceHTTPStatusTable["dataActorPtr"]
				local _eventName = interfaceHTTPStatusTable["eventName"]

				interfaceConfigTable["channelupdatetime"] = nil

print("Interface:::::Data Received:",data)
print("Interface:::::Response for foreground request type:",interfaceHTTPStatusTable["foregroundrequestType"])
print("Interface:::::Response for foreground request type:",interfaceHTTPStatusTable["foregroundrequestType"])
print("Interface:::::Foreground Req Id:",_foregroundreqId)
print("Interface:::::Channel Name:",_channelName)
print("Interface:::::Event Name:",_eventName)


                

				--Channel Update
				if _status == 200 and _channelName ~= "" then

				   -- bucket.CallBck(_dataActorPtr,_eventName,"channel",_channelName)

				   -- Event names can be "update" for foreground request.
				   interfaceHTTPStatusTable["eventName"] = ""

				   --Nil if its a foreground request for a specific Id.
				   interfaceHTTPStatusTable["channelName"] = ""

				--Foreground request update. Data Store needs to be updated
				elseif _status == 200 and _foregroundreqId ~= "" then

				    if interfaceHTTPStatusTable["foregroundrequestType"] == "help" then

				      if data == nil or data == "" then
					print("Interface:Help:Since the data is nil, so mocking the status code")
					_status = 400
				      else
					    print("Interface:Setting help data::",data)
					    interfaceConfigTable["help"] = data
				      end

			            elseif interfaceHTTPStatusTable["foregroundrequestType"] == "detailedstory" then


			              _reqId = interfaceHTTPStatusTable["foregroundrequestid"]

				      if data == nil or data == "" then
					print("Interface:Detailed Story:Since the data is nil, so mocking the status code")
					_status = 400
				      else
				      ---DATASTORE UPDATED
				      	datastore.news.headlines[_reqId].story = data

				      	--Persist datastore.
				      	interfacePersistDataStore()
				      end

				    elseif interfaceHTTPStatusTable["foregroundrequestType"] == "stockdetails" then
					local _reqKey = interfacePresetEventsTable["last_request_table_key"] 
					if datastore.money.stockdetails[_reqKey] == nil then
						print("Interface:Requested stock details are nil, so reporting error")
						_status = 400;
					end
					
					-- This request will come as a zip file, so no special processing is required.
					-- Updated by JSWto add radar_content changes
				    elseif interfaceHTTPStatusTable["foregroundrequestType"] == "weatherdetails" then
				    
			              _reqId = interfaceHTTPStatusTable["foregroundrequestid"]
			              
						  local _dayid = interfaceHTTPStatusTable["weatherday"]
					      local _cidforrequest = interfaceHTTPStatusTable["cid"]

				    	  if (datastore.weather.details == nil) or
                             (datastore.weather.details[_cidforrequest] == nil) or
                             (datastore.weather.details[_cidforrequest][weatherTSMapping[_dayid]] == nil) or
						     (datastore.weather.details[_cidforrequest][weatherTSMapping[_dayid]].text == nil) then
						  		print("Interface: weather.details was not in data package")
								_status = 400
	  				      end

					 
				    elseif interfaceHTTPStatusTable["foregroundrequestType"] == "weatherweek" then
					    local _reqKey = interfacePresetEventsTable["last_request_table_key"] 
					    if  (datastore.weather.summary == nil) or (datastore.weather.summary[_reqKey] == nil) or 
						(datastore.weather.locations == nil) or (datastore.weather.locations[_reqKey] == nil) then
						    print("Requested 7 day summary is not received for cid:",_reqKey)
						    _status = 400;
					    else
						    createInterface7DaySummaryTable(_reqKey)
					    end
				    elseif interfaceHTTPStatusTable["foregroundrequestType"] == "moviestheatre" then
					    local _reqKey = interfacePresetEventsTable["last_request_table_key"] 
					    if datastore.movies.movieshowsbytheatre == nil or 
			   		       datastore.movies.movieshowsbytheatre[_reqKey] == nil then
						print("Interface:Requested movie shows by theatre are nil, so reporting error")
					         _status = 400;
					    end

					 --Once this response is received, recreate the movies table on a basis of 
					 --theatre.
					 createinterfaceMovieListTablePresetTheatreTable(getTheatreId())
				    elseif interfaceHTTPStatusTable["foregroundrequestType"] == "moviesmovie" then
					 --This request will stick the request directly into the datastore.
					 	local _reqKey = interfacePresetEventsTable["last_request_table_key"] 
						if datastore.movies.theatreshowsbymovie == nil or
					   	   datastore.movies.theatreshowsbymovie[_reqKey] == nil then
						   print("Interface:Requested theatre by movie are nil, so reporting error")
						     _status = 400;
						else
						    createTheatreListForPresetMovie(getMovieId())
						end
				    elseif interfaceHTTPStatusTable["foregroundrequestType"] == "movieurl" then
					 --This request will stick the request directly into the datastore.
					local _reqKey = interfacePresetEventsTable["last_request_table_key"] 
					print("Interface:Foreground request type is movieurl",_reqKey[1],_reqKey[2])
					 if datastore.movies.movie_tickets_per_movie_and_theatre[_reqKey[1]] == nil or
					    datastore.movies.movie_tickets_per_movie_and_theatre[_reqKey[1]][_reqKey[2]] == nil then
					    print("Interface:Movie foreground request for URL failed")
					    _status = 400;
				    	else
						if string.lower(_reqKey[3]) ~= "nodayavailable" then
							ret,ts = DSMovieTableExists(_reqKey[3], _reqKey[2], _reqKey[1])
							print("Interface:TS:from DS Movie Table ",ts)
						end
							
						if string.lower(_reqKey[3]) == "nodayavailable" then
							if datastore.movies.movie_tickets_per_movie_and_theatre[_reqKey[1]].details == nil then
					    			print("Interface:Movie foreground request for URL failed")
					    			_status = 400;
							end
						elseif datastore.movies.movie_tickets_per_movie_and_theatre[_reqKey[1]][_reqKey[2]][ts] == nil then
					    		print("Interface:Movie foreground request for URL failed")
					    		_status = 400;
						end
				      end

				    elseif  interfaceHTTPStatusTable["foregroundrequestType"] == "sports" or 
	   						interfaceHTTPStatusTable["foregroundrequestType"] == "sportsstandings" or
							interfaceHTTPStatusTable["foregroundrequestType"] == "sportsscores" or
							interfaceHTTPStatusTable["foregroundrequestType"] == "sportsschedules" or
							interfaceHTTPStatusTable["foregroundrequestType"] == "sportsteams" then

						local last_request_table = interfacePresetEventsTable["last_request_table"]  
						local last_request_table_key = interfacePresetEventsTable["last_request_table_key"] 

						if last_request_table ~= "" and last_request_table_key ~= "" then
						
							if last_request_table_key == "__count__table__" then

								local table_size = 0

								if last_request_table ~= nil then
									for k,v in pairs(last_request_table) do
	         							table_size = table_size + 1
									end
								end
								
								if (table_size == 0) and (last_request_table ~= datastore.sports.teams) and (last_request_table ~= datastore.sports.scores) then
								
									-- ERROR: EXPECTED INFO NOT RECEIVED
									_status = 404

                                    local _msg = interfacePresetEventsTable["last_request_table_msg_string"]
									local info = debug.getinfo(1, "Sl")
									print ( string.format("[%s]:%d ERROR: %s NOT RECEIVED",info.short_src, info.currentline,_msg) )

								end

								if (last_request_table == datastore.sports.teams) then
									last_request_table = datastore.sports.teams[interfacePresetEventsTable["sport_datastore_sid"]]
									table_size = 0
									if last_request_table ~= nil then
										for k,v in pairs(last_request_table) do
	         									table_size = table_size + 1
										end
									end
									if table_size == 0 then
										datastore.sports.teams[interfacePresetEventsTable["sport_datastore_sid"]] = {}
									end
									-- added to avoid update forever when "Teams" selected in a out of season sport
									-- in such a case data is nil which is caught and a 400 status error is sent back.
									if(table_size == 0) then
										    -- ERROR: EXPECTED INFO NOT RECEIVED
											--_status = 400
                                            local _msg = interfacePresetEventsTable["last_request_table_msg_string"]
											local info = debug.getinfo(1, "Sl")
											print ( string.format("[%s]:%d ERROR: %s NOT RECEIVED",info.short_src, info.currentline,_msg) )
									end
								elseif (last_request_table == datastore.sports.scores) then
									last_request_table = datastore.sports.scores[interfacePresetEventsTable["sport_datastore_sid"]]
									table_size = 0
									if last_request_table ~= nil then
										for k,v in pairs(last_request_table) do
	         									table_size = table_size + 1
										end
									end
									if table_size == 0 then
										datastore.sports.scores[interfacePresetEventsTable["sport_datastore_sid"]] = {}
									end
								end

							elseif ( (last_request_table == nil) or (last_request_table[last_request_table_key] == nil) ) then
								-- ERROR: EXPECTED INFO NOT RECEIVED
								_status = 404
	
                                local _msg = interfacePresetEventsTable["last_request_table_msg_string"]
								local info = debug.getinfo(1, "Sl")
								print ( string.format("[%s]:%d ERROR: %s NOT RECEIVED %s",info.short_src, info.currentline,_msg,last_request_table_key) )
							end
						end

						interfacePresetEventsTable["last_request_table"] = ""
						interfacePresetEventsTable["last_request_table_key"] = ""
						interfacePresetEventsTable["last_request_table_msg_string"] = ""


				    elseif interfaceHTTPStatusTable["foregroundrequestType"] == "sportsgames" then


						local last_request_table = {}
						last_request_table = interfacePresetEventsTable["last_request_table"]
						local last_request_table_key = tostring( interfacePresetEventsTable["last_request_table_key"] )
						
						if last_request_table ~= "" and last_request_table_key ~= "" then
						
							if ( (last_request_table[last_request_table_key] == nil) and (data == nil or data == "") ) then
			              _reqId = interfaceHTTPStatusTable["foregroundrequestid"];
								datastore.sports.games[_reqId] = {}
								datastore.sports.games[_reqId].label = "noinfo"; -- equals to "Check back" or "No Info"
								datastore.sports.games[_reqId].info_read = 0; -- store information if game info was read once
								
							else
			              _reqId = interfaceHTTPStatusTable["foregroundrequestid"];

				      if data ~= nil and type(data) == "string" then
				      ---DATASTORE UPDATED
				      datastore.sports.games[_reqId] = {}
				      datastore.sports.games[_reqId].label = data; -- equals to "Check back" or "No Info"
					      datastore.sports.games[_reqId].info_read = 0; -- store information if game info was read once
				      end
							end

						end

						interfacePresetEventsTable["last_request_table"] = ""
						interfacePresetEventsTable["last_request_table_key"] = ""
						interfacePresetEventsTable["last_request_table_msg_string"] = ""


				     elseif interfaceHTTPStatusTable["foregroundrequestType"] == "getzipcode" then

			     	     interfaceConfigTable["zipcodestatus"] = "success"

			   	     --Now fire the foreground request
				    	 --Special case for register
				    	interfaceConfigTable["updating"] =  "_false"
				    	interfaceConfigTable["requestfired"] =  "_false"
					interfaceHTTPStatusTable["foregroundrequestid"] = "" 
			        	interfaceHTTPStatusTable["foregroundrequestType"] = ""
			        	interfaceHTTPStatusTable["eventName"] = ""

					datastore.setZipCode(interfacezipcode)
			   	    	handleStartForeground(constructURL("channels",{id="all"}))
				    	return;
				    end


				end
				    
				-- handling No Info or Check Back for Game ID request
				if ( (_status == 204) and (interfaceHTTPStatusTable["foregroundrequestType"] == "sportsgames") ) then
				
					local currentCDMATimeStamp = net.getutctime()
                    _gid = interfaceHTTPStatusTable["foregroundrequestid"]
					local gid_CDMATimeStamp = get_timestamp_for_gid(_gid, "all")

					local last_request_table = {}
					last_request_table = interfacePresetEventsTable["last_request_table"]
					local last_request_table_key = tostring( interfacePresetEventsTable["last_request_table_key"] )

					if last_request_table ~= "" and last_request_table_key ~= "" then

                        if ( (last_request_table[last_request_table_key] == nil) and (data == nil or data == "") ) then
                        
                            if (gid_CDMATimeStamp >= currentCDMATimeStamp) then

								local info = debug.getinfo(1, "Sl")
								print ( string.format("[%s]:%d CHECKBACK Gid[%d] Curr[%d]", info.short_src, info.currentline,gid_CDMATimeStamp,currentCDMATimeStamp) )

				                _reqId = interfaceHTTPStatusTable["foregroundrequestid"];
								datastore.sports.games[_reqId] = {}
								datastore.sports.games[_reqId].label = "checkback";
								datastore.sports.games[_reqId].info_read = 0; -- store information if game info was read once
                            else

								local info = debug.getinfo(1, "Sl")
								print ( string.format("[%s]:%d NOINFO Gid[%d] Curr[%d]", info.short_src, info.currentline,gid_CDMATimeStamp,currentCDMATimeStamp) )

				                _reqId = interfaceHTTPStatusTable["foregroundrequestid"];
								datastore.sports.games[_reqId] = {}
								datastore.sports.games[_reqId].label = "noinfo";
								datastore.sports.games[_reqId].info_read = 0; -- store information if game info was read once
                            end
                            
                            _status = 200 -- as server code 204 was handled properly, then 200 code is assumed from this point
                        
                        end

					end

					interfacePresetEventsTable["last_request_table"] = ""
					interfacePresetEventsTable["last_request_table_key"] = ""
					interfacePresetEventsTable["last_request_table_msg_string"] = ""
					

				end

				--the updating flag.
				--Resetting all the values here irrespective of the status code.
				  print("Interface:Changing updating to false")
				interfaceConfigTable["updating"] =  "_false"
				interfaceConfigTable["requestfired"] =  "_false"

				if _status == 301 or _status == 302 then
				   if data ~= nil then
				        print("Interface:Sending a launch URL callback to actor with url",data);
					bucket.CallBck(_dataActorPtr,"launchUrl","url",data)
					bucket.CallBck(_dataActorPtr,"updateFailed","","")
				   else
				        --If data is then that means we received 301 but no
					--url, so this is a failure scenario and we need to
					--fake out the status code.
					print("Interface:Faking out the status code because no URL with 301")
					_status = 500;
				   end
				end

				--If _status is not 301/302 (because 301/302 needs special processing
				--and status is not success then send an update failed to 
				--Actor.
				if (_status ~= 301 or _status ~= 302 ) and _status ~= 200 then
print("Entering here with _status:",_status)
				    if interfaceHTTPStatusTable["foregroundrequestType"] == "getzipcode" then
				     	interfaceConfigTable["zipcodestatus"] = "failed"
				        bucket.CallBck(_dataActorPtr,"zipcodefailed","","")
				     else
				        print("Interface:Sending update failed to actor")
				        bucket.CallBck(_dataActorPtr,"updateFailed","","")
				     end
				end

    				--Inform dataActor and reinitialize everything.
				interfaceHTTPStatusTable["weatherday"] = ""
				interfaceHTTPStatusTable["cid"] = ""
			        interfaceHTTPStatusTable["foregroundrequestid"] = "" 
			        interfaceHTTPStatusTable["foregroundrequestType"] = ""
			        interfaceHTTPStatusTable["eventName"] = ""

				--Reset the URL.
				interfaceHTTPStatusTable["url"] = ""

				--If status is successful then sending a success update to actor.
				if _status == 200 then
					print("Interface:Sending update success to actor")
					bucket.CallBck(_dataActorPtr,_eventName,"","")
				end

				print("Interface:Exit:Interface Callback function from fetch")
		        end


			--==============================================================================
			--This function is called by the fetch layer to update with a status codes for 
			--background request.
			--==============================================================================
			local function callbackFnBackgroundStausUpdate(url,_status,data)
				print("Interface:Enter into background update callback from fetch")
				print("Interface:Exit into background update callback from fetch")
			end

			--****************************************************************************************
			--End of callback functions section
			--****************************************************************************************


			--==============================================================================
			--This function is used for handling weather requests.
			--==============================================================================
			local function handleWeather(_weatherString)


			   local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_weatherString,"(%a+)%s*")

			   local _subString = string.sub(_weatherString,_sizeStr+2,-1)
			   if string.lower(_key) == "data" then

				   --get the preset default cityId
				   cid = getPresetCityId()

				   local dayId = 0

				   _start,_sizeStr,dayId = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   print("Interface:CID:",cid)
				   print("Interface:DAY:",dayId)
				   if string.lower(dayId) == "count" then --/weather/data/cid[..]/count

					   --Before returning this count make sure that there is some data
					   --available for all the 7 days. If there is no 7 days data available
					   --then fire a foreground request.
					  if ((interfaceConfigTable["updating"] == "_false") and ((datastore.weather.summary == nil) or (datastore.weather.summary[cid] == nil))) then
						print("Interface:Firing foreground request for the 7 days weather")
						interfacePresetEventsTable["last_request_table_key"]  = cid
						handleStartForeground(constructURL("weatherweek",cid))
						return nil
					  end

					   createInterfaceAlertsTableByCid(cid);
					   local count = 0
					   for k,v in pairs(datastore.weather.locations[cid].alerts) do
						count = count + 1
					   end

					   -- if there are any alerts for the current city
					   -- then return 8 days otherwise 7 days
					   if count > 0 then 
						   return _strclsId, tostring("8")
					   else 
						   return _strclsId, tostring("7") 
					   end
				   end

				   --if the foreground request is fired for this section then
				   --dont return till the time response is received.
				   if (interfaceConfigTable["updating"] ~=  "_false") and ((datastore.weather.summary) == nil or  (datastore.weather.summary[cid] == nil)) then
					print("Interface:Callback is in progress. Nothing from weather/data section")
				       return nil
				   end

				   if string.lower(_key) == "hi" then
					--check if there are alert then for day 0 its a alert no hi temp
					local count = 0
					for k,v in pairs(datastore.weather.locations[cid].alerts) do
						count = count + 1
					end
					if count > 0 then 
					    if dayId == "0" then
						return _strclsId, ""
					    else
							local retval = datastore.weather.summary[cid]
							if retval == nil then
							else 
							   return _strclsId, datastore.weather.summary[cid][weatherTSMapping[decrementday(dayId)]].high
							end

						    end
						end
						return _strclsId, datastore.weather.summary[cid][weatherTSMapping[dayId]].high
					   elseif string.lower(_key) == "lo" then
						--check if there are alert then for day 0 its a alert no hi temp
						local count = 0
						for k,v in pairs(datastore.weather.locations[cid].alerts) do
							count = count + 1
						end
						if count > 0 then 
						    if dayId == "0" then
							return _strclsId, ""
						    else
							return _strclsId, datastore.weather.summary[cid][weatherTSMapping[decrementday(dayId)]].low
						    end
						end
						return _strclsId, datastore.weather.summary[cid][weatherTSMapping[dayId]].low
					   elseif string.lower(_key) == "alert" then
						--check if there are alert then for day 0 its a alert no hi temp
						 local count = 0
						 for k,v in pairs(datastore.weather.locations[cid].alerts) do
						     count = count + 1
						 end
						  if count > 0 then 
							if dayId == "0" then
								return _strclsId, "1"
							else 
							return _strclsId, "0"
					  	end
					  end
					  return _strclsId, "0"

				   elseif string.lower(_key) == "image" then
					local _imageNum
			   	  	_subString = string.sub(_subString,_sizeStr+2,-1)
				    	_start,_sizeStr,_imageNum = string.find(_subString,"(%w+)")

					local _imgNum = tonumber(incrementString(_imageNum))

					local count = 0

					for k,v in pairs(datastore.weather.locations[cid].alerts) do
					   count = count + 1
					end

			                if count > 0 then
			                   dayId = decrementday(dayId)
			                end

					local _shortname = 
					datastore.weather.summary[cid][weatherTSMapping[dayId]].images[_imgNum]
					return _imageclsId, loadImage(datastore.images[_shortname])
				   elseif string.lower(_key) == "details" then
					local count = 0
					local retval = 0
					for k,v in pairs(datastore.weather.locations[cid].alerts) do
						count = count + 1
					end

					if count > 0 then 
					    if dayId == "0" then
						   for k,v in pairs(datastore.weather.locations[cid].alerts) do
						      return _strclsId, "Alert "..datastore.weather.alerts[v].text
						   end
					     else
						return _strclsId, datastore.weather.summary[cid][weatherTSMapping[decrementday(dayId)]].summary
					     end
					end
					return _strclsId, datastore.weather.summary[cid][weatherTSMapping[dayId]].summary
					
				   -- ACTOR_NODE:
				   -- AUTH: Last updated by JSW 8/23/2006 - Add functionality for radar_content table
				   -- NODE: /actor/dataActor/weather/data/<DAY_ID>/forecast
				   -- TYPE: TEXT
				   -- DESC: This node returns the text resource of the day ID's forecast.  This info exists in the radar_content table referenced by the weather_summary table.
				   elseif string.lower(_key) == "forecast" then
				   		local count = 0
						local retval = nil

						for k,v in pairs(datastore.weather.locations[cid].alerts) do
							count = count + 1
						end

			            if count > 0 then
			             	dayId = decrementday(dayId)
			            end
                        
                        -- Data exists in datastore
                        if (datastore.weather.details ~= nil) and
                           (datastore.weather.details[cid] ~= nil) and
						   (datastore.weather.details[cid][weatherTSMapping[dayId]] ~= nil) and
						   (datastore.weather.details[cid][weatherTSMapping[dayId]].text ~= nil) then
			               	retval = datastore.weather.details[cid][weatherTSMapping[dayId]].text
						end
						
				     	--if no weather details then fire a foreground request
						if retval == nil then
						    
						    -- Construct the URL to be sent to the server
					    	local urlformat = string.format("id=%s&day=%s",
							cid,datastore.weather.summary[cid][weatherTSMapping[dayId]].id)

							-- Set weatherday and cid for request
							interfaceHTTPStatusTable["weatherday"] = dayId
							interfaceHTTPStatusTable["cid"] = cid
							
							-- Kick off update
							handleStartForeground(constructURL("weatherdetails",urlformat))
							
							-- If we are in update, we return nil until resource is received
							return nil
						end

						local _id = datastore.weather.summary[cid][weatherTSMapping[dayId]].id
						
						-- check for UTF-8 character encoding string returned before concatenating it
						if (string.byte(retval, 1) == 239) and (string.byte(retval, 2) == 187) and (string.byte(retval, 3) == 191) then
							retval = string.format("%s - %s",idToDay(_id),string.sub(retval, 4));
						else
							retval = string.format("%s - %s",idToDay(_id),retval);
						end
						
						-- Return the text string
						return _strclsId, retval;
				   elseif string.lower(_key) == "dow" then
						local count = 0
						local _cid = getPresetCityId()
						for k,v in pairs(datastore.weather.locations[cid].alerts) do
							count = count + 1
						end
						if count > 0 then 
						    if dayId == "0" then
						print("Interface: Returning nothing for dow because day-0 is an alert")
							return _strclsId, ""
						    else
							local _id = datastore.weather.summary[cid][weatherTSMapping[decrementday(dayId)]].id
							return _strclsId, idToDay(_id);
						    end
						end

						local _id = datastore.weather.summary[cid][weatherTSMapping[dayId]].id
						return _strclsId, idToDay(_id);
				   end
			   elseif string.lower(_key) == "alerts" then

				   local alertId = 0

				   _start,_sizeStr,alertId = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   if string.lower(alertId) == "count" then --/weather/alerts/count
					   --create alerts table before returning a count to the trigML

					    local cnt = 0
					    for k,v in pairs(interfaceNewAlertsTable) do
						 --This table will contain only new alerts
						 cnt = cnt+1
					    end
					    return _strclsId, tostring(cnt)
				   end
				   if string.lower(_key) == "cid" then
					local realcid = interfaceNewAlertsTable[tonumber(alertId)+1].cid

					for k,v in pairs(interfacecitiesTable) do
					   if v == realcid then
					   print("Interface:Returning CID::"..realcid.."interface cid:"..k)
					     return _strclsId, k;
					   end
					end

				   elseif string.lower(_key) == "counter" then
					return _strclsId, "noCounter"
				   elseif string.lower(_key) == "details" then
					 return _strclsId, interfaceNewAlertsTable[tonumber(alertId)+1].text
				   elseif string.lower(_key) == "viewed" then
					return _strclsId, tostring(datastore.weather.alerts[interfaceNewAlertsTable[tonumber(alertId)+1].alert].flag)
				   end

			   elseif string.lower(_key) == "alertsbycity" then

			 	   local alertId = 0

				   _start,_sizeStr,alertId = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   if string.lower(alertId) == "count" then --/weather/alertsByCity/count
					   --create alerts table before returning a count to the trigML
					    local cnt = 0
					    for k,v in pairs(interfaceAlertsByCityTable) do
						 cnt = cnt+1
					    end
					    return _strclsId, tostring(cnt)
				   end

				   if string.lower(_key) == "alertdetails" then
print("Real alertId is::",interfaceAlertsByCityTable[alertId]);
				    local _alertTxt = 
				    string.format("Alert %d - %s",
				    tonumber(alertId)+1, datastore.weather.alerts[interfaceAlertsByCityTable[alertId]].text);
				    return _strclsId, _alertTxt;
				   end
			  elseif string.lower(_key) == "alertcount" then
				local cnt = 0
				for k,v in pairs(interfaceAlertsByCityTable) do
				   cnt = cnt+1
				end
				return _strclsId, tostring(cnt)

			  elseif string.lower(_key) == "cities" then
			 	   local cid = 0

				   _start,_sizeStr,cid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

			    	   if string.lower(cid) == "count" then --/weather/cities/count

					   --create cities table first then return the count of 
					   --the cities.
					    local cnt = 0
					    for k,v in pairs(interfacecitiesTable) do
						 cnt = cnt+1
					    end
					    return _strclsId, tostring(cnt)
			  	    elseif string.lower(_key) == "alertcount" then
					createInterfaceAlertsTableByCid(interfacecitiesTable[cid]);
					local cnt = 0
					for k,v in pairs(interfaceAlertsByCityTable) do
				   		cnt = cnt+1
					end
					return _strclsId, tostring(cnt)
				   end

				   if _key == nil then
					   return _strclsId, interfacecitiesTable[cid]
			    	   elseif string.lower(_key) == "zip" then
					  return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].zipcode
			    	   elseif string.lower(_key) == "currenttemp" then
					  return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].current

				       -- ACTOR_NODE:
				   	   -- AUTH: Last updated by JSW 8/23/2006 - Remove "F" from temp string while in MI-UI
					   -- NODE: /actor/dataActor/weather/cities/<City_ID>/hi
				   	   -- TYPE: TEXT
				   	   -- DESC:	This node returns the high temperature for a city ID.  If MI-UI is active (OnDemand is not running) then the "F" is removed from the string before returning to the trig.  If an "F" DNE, then the string is returned as is.				  
			    	   elseif string.lower(_key) == "hi" then
			    	   		if (interfaceConfigTable["isactive"] == "_true") then
					  			return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].high
					  		else
					  			if string.find((string.lower(datastore.weather.locations[interfacecitiesTable[cid]].high)), "f") == nil then
					  		   		return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].high
					  		   	else
					  		   	    return _strclsId, string.sub(datastore.weather.locations[interfacecitiesTable[cid]].high, 1, string.len(datastore.weather.locations[interfacecitiesTable[cid]].high)-1) 
					  		   	end
					  		end
					  		
				       -- ACTOR_NODE:
				   	   -- AUTH: Last updated by JSW 8/23/2006 - Remove "F" from temp string while in MI-UI
					   -- NODE: /actor/dataActor/weather/cities/<City_ID>/lo
				   	   -- TYPE: TEXT
				   	   -- DESC:	This node returns the low temperature for a city ID.  If MI-UI is active (OnDemand is not running) then the "F" is removed from the string before returning to the trig.  If an "F" DNE, then the string is returned as is.				  		
			    	   elseif string.lower(_key) == "lo" then
			    	   		if (interfaceConfigTable["isactive"] == "_true") then
					  			return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].low
					  		else
					  			if string.find((string.lower(datastore.weather.locations[interfacecitiesTable[cid]].low)), "f") == nil then
					  		   		return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].low
					  		   	else
					  		   	    return _strclsId, string.sub(datastore.weather.locations[interfacecitiesTable[cid]].low, 1, string.len(datastore.weather.locations[interfacecitiesTable[cid]].low)-1) 
					  		   	end
					  		end			    	   

			    	   elseif string.lower(_key) == "image" then
					local _imageNumStr
			   	   	_subString = string.sub(_subString,_sizeStr+2,-1)
				    	_start,_sizeStr,_imageNumStr = string.find(_subString,"(%w+)")

					local _imgNum = tonumber(incrementString(_imageNumStr))

					local _shortname = 
					datastore.weather.locations[interfacecitiesTable[cid]].images[_imgNum]
print("Short name for cid and the image with a image num:::",interfacecitiesTable[cid],_shortname,_imgNum)
					   return _imageclsId, loadImage(datastore.images[_shortname])
			    	   elseif string.lower(_key) == "details" then
					   --Here day 0 is the current day
					   local dayId = "0"
					   return _strclsId, datastore.weather.summary[interfacecitiesTable[cid]][weatherTSMapping[dayId]].summary
					   
					   -- ACTOR_NODE:
					   -- AUTH: Last updated by JSW 8/23/2006 - Add functionality for radar_content table
					   -- NODE: /actor/dataActor/weather/cities/<CID>/satelliteImage
					   -- TYPE: IMAGE
					   -- DESC: This node returns the radar image for a specific city.  Even though each day may contain an image, the interface assumes one image for each city contained in the radar_content table for day 0 (day 1 if alerts exist).
			    	   elseif string.lower(_key) == "satelliteimage" then
					   		local _currentday = "0"

							-- If the details table exists, then return the image
							if (datastore.weather.details ~= nil) and
								(datastore.weather.details[interfacecitiesTable[cid]][weatherTSMapping[_currentday]] ~= nil) then
                        	
								local _shortname = datastore.weather.details[interfacecitiesTable[cid]][weatherTSMapping[_currentday]].radar
					   			return _imageclsId, loadImage(datastore.images[_shortname])
							else
							    --if table DNE, then return nil
								return _imageclsId, nil
					   		end
					   		
			    	   elseif string.lower(_key) == "cityname" then
					  return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].city
			    	   elseif string.lower(_key) == "state" then
					  return _strclsId, datastore.weather.locations[interfacecitiesTable[cid]].state
			    	   elseif string.lower(_key) == "citystate" then
					  return _strclsId, string.format("%s, %s",datastore.weather.locations[interfacecitiesTable[cid]].city, datastore.weather.locations[interfacecitiesTable[cid]].state)
				   end
			  elseif string.lower(_key) == "citycount" then
				local citycnt = 0
				for k,v in pairs(interfacecitiesTable) do
					citycnt = citycnt+1
				end
				return _strclsId, tostring(citycnt)

			  elseif string.lower(_key) == "defaultcityid" then
				  local _cid = getDefaultCityId()
				  for k,v in pairs(interfacecitiesTable) do

					  if _cid == v then 
					     return _strclsId, k 
				          end
				  end
			  elseif string.lower(_key) == "currentcityid" then
				  local _cid = getPresetCityId()
print("Current CITY ID is" .. _cid)
				  for k,v in pairs(interfacecitiesTable) do
					  if _cid == v then 
					     return _strclsId, k 
				          end
				  end
				  return _strclsId, nil 
			  elseif string.lower(_key) == "defaultweatherid" then
				  local _cid = getDefaultCityId()
				  for k,v in pairs(interfacecitiesTable) do

					  if _cid == v then 
					     return _strclsId, k 
				          end
				  end

			  elseif string.lower(_key) == "unreadalerts" then
				local alertcnt = 0
				--This logic is changed because we have 2 states now.
				--1. Is completely new.
				--2. New but viewed.
				--So if its new but viewed then it wont be a part of the
				--unread alert counting.
				

				for k,v in pairs(datastore.weather.alerts) do
					if datastore.weather.alerts[k].flag == true and
					   datastore.weather.alerts[k].alertviewed == nil then
						alertcnt = alertcnt+1
					end
				end

				--This flag is to avoid multiple alertviewed requests.
				interfacePresetEventsTable["alertviewed_requested"] = false;

				return _strclsId, tostring(alertcnt)

			  end

			end

			--==============================================================================
			--This function is used for handling news requests.
			--==============================================================================
			local function handleNews(_newsString)

			   local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_newsString,"(%a+)%s*")

			   local _subString = string.sub(_newsString,_sizeStr+2,-1)

			   
			   if string.lower(_key) == "defaultcategoryid" then
				   local catid = getDefaultCategoryId()
				   for k,v in pairs(interfaceCatTable) do 
					 if catid == v then 
				           --storing this value, so that it can be used for 
					   --comparining when trig is asking for an id..
				           return _strclsId, k
				   	end
				   end
			   elseif string.lower(_key) == "data" then
				   local sid = 0

				   _start,_sizeStr,sid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   if string.lower(sid) == "count" then --/news/data/count

					    local cnt = 0
					    local count = 1

					    if interfacePresetEventsTable["categorytype"] == "multiple" and interfacePresetEventsTable["categorycount1"] > 0 
                                               and interfacePresetEventsTable["categorycount2"] > 0 then
							cnt = 999999
				    	    else
					    for k,v in pairs(interfaceStoryTable) do
						 cnt = cnt+1
					    end
					    end
					    return _strclsId, tostring(cnt)
				    end
print("_Key is ::",_key)
				    if interfacePresetEventsTable["categorytype"] == "multiple" then
					if interfacePresetEventsTable["categorycount1"] > 0 and interfacePresetEventsTable["categorycount2"] > 0 then
						if (mymodulus(tonumber(sid), 2) == 0) then
							sid = tostring(mymodulus((tonumber(sid)/2), interfacePresetEventsTable["categorycount1"]) * 2)							
						else
							sid = tostring((mymodulus((tonumber(sid)-1)/2, interfacePresetEventsTable["categorycount2"]) * 2) + 1)
						end
					end
				    end
print("sid is ", sid)
				    if string.lower(_key) == "image" then
					local _imageNumStr
			   	   	_subString = string.sub(_subString,_sizeStr+2,-1)
				    	_start,_sizeStr,_imageNumStr = string.find(_subString,"(%w+)")

					local _imgNum = tonumber(incrementString(_imageNumStr))

					local _shortname = 
					datastore.news.headlines[interfaceStoryTable[sid]].images[_imgNum]
print("Short name for story id and the image with a image num:::",interfaceStoryTable[sid],_shortname,_imgNum)
					   return _imageclsId, loadImage(datastore.images[_shortname])

				    elseif string.lower(_key) == "title" then
						if datastore.news.headlines[interfaceStoryTable[sid]] ~= nil then
						   return _strclsId, datastore.news.headlines[interfaceStoryTable[sid]].label
						end
				    elseif string.lower(_key) == "story" then
						local story = datastore.news.headlines[interfaceStoryTable[sid]].story
						if story == nil then
						    handleStartForeground(constructURL("detailedstory",
							interfaceStoryTable[sid]))
						    return _strclsId, "   "
					  	else
						   return _strclsId, story
						end
				    elseif string.lower(_key) == "categoryid" then
						local categories = 
							datastore.news.headlines[interfaceStoryTable[sid]].categories
						if categories == nil then
							-- ERROR
							return nil 
				    end

						local count_categories = 0
						for _, _v in ipairs(categories) do 
							count_categories = count_categories + 1
						end
						if count_categories == 0 then
							-- ERROR
							return nil 
						end

						for _, _v_categories in ipairs(categories) do
					   	    if interfacePresetEventsTable["multiplecategory1"] == _v_categories then
							if interfacePresetEventsTable["multiplecategory1"] ~= "sports" then
								return _strclsId, "news"
							else
								return _strclsId, _v_categories
							end
						    end
					   	    if interfacePresetEventsTable["multiplecategory2"] == _v_categories then
							if interfacePresetEventsTable["multiplecategory2"] ~= "sports" then
								return _strclsId, "news"
							else
								return _strclsId, _v_categories
							end
						    end
						end

						return nil
					end -- end of if started at image
			    elseif string.lower(_key) == "count" then

				_start,_sizeStr,_key = string.find(_subString,"(%w+)")
				_subString = string.sub(_subString,_sizeStr+2,-1)

				if string.lower(_key) == "categorycount" then
					--categorycreateInterfaceCategory table
					if interfaceCatTable == nil then
						createinterfacecattable()
					end

					local cnt = 0
					for k,v in pairs(interfaceCatTable) do
					  cnt = cnt + 1
					end
					cnt = cnt - 1
					return _strclsId, tostring(cnt)
				else 
					if interfaceCatTable and (interfaceCatTable[_key] == getDefaultCategoryId()) then
						return _strclsId, interfacePresetEventsTable["defaultcategorycount"]
					end
					local cnt = 0

					for k,v in pairs(interfaceStoryTable) do
						cnt = cnt+1
					end
					return _strclsId, tostring(cnt)
				end


			    elseif string.lower(_key) == "categories" then

				local catId = 0

				_start,_sizeStr,catId = string.find(_subString,"(%w+)")
				_subString = string.sub(_subString,_sizeStr+2,-1)

				_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				if string.lower(catId) == "count" then --/news/categories/count

					--if the count is called before calling categoryCount then
					--create the categories table here.
					if interfaceCatTable == nil then
						createinterfacecattable()
					end
				
				    	local cnt = 0
					for k,v in pairs(interfaceCatTable) do
						cnt = cnt+1
					end
					cnt = cnt - 1
					return _strclsId, tostring(cnt)
				end

				if string.lower(_key) == "id" then
						return _strclsId, interfaceCatTable[catId]
				elseif string.lower(_key) == "details" then
					return _strclsId, datastore.news.categories[interfaceCatTable[catId]].label
				elseif string.lower(_key) == "image" then
					local _shortname = 
					datastore.news.categories[interfaceCatTable[catId]].image
print("Short name for category id and the image :::",interfaceCatTable[catId],_shortname)
					   if _shortname ~= nil and _shortname ~= "" then
					   return _imageclsId, loadImage(datastore.images[_shortname])
				end
					   return nil
				end
			    end


			end --end of function handleNews

			--==============================================================================

		local function setTeamhandler( tid )

			_TID = tostring(tid)
			
			interfacePresetEventsTable["sportsteamid"] = tostring(tid)

	   	   	if _interfaceDebug then
		    		local info = debug.getinfo(1, "Sl")
		    		print ( string.format("[%s]:%d setTeamhandler _TID = %s",info.short_src, info.currentline, _TID) )
			end


		end


			local function createinterfacesports_TYPES_table(sid)

				local datastore_sid = ""

				-----------------------------------------------------

				-- get sports types (sid) from datastore.sports.types

                interfaceSports_Types_Table = {}

				local count_sid = 0

				-----------------------------------------------------
			    local a = {}
			    for n in pairs(datastore.sports.types) do table.insert(a, n) end

				table.sort(a)

			    for k,v in ipairs(a) do

					interfaceSports_Types_Table[tostring(count_sid)] = v
					count_sid = count_sid + 1

				end

				a = nil

				-----------------------------------------------------

				datastore_sid = interfaceSports_Types_Table[tostring(sid)]


		   	   	if _interfaceDebug then
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d _DATASTORE_SID = %s",info.short_src, info.currentline, datastore_sid) )
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d interfaceSports_Types_Table = ",info.short_src, info.currentline) )
				end

				interfacePresetEventsTable["sport_datastore_sid"]  =  datastore_sid

				table.sort(interfaceSports_Types_Table)
		   	   	if _interfaceDebug then
					for k,v in pairs(interfaceSports_Types_Table) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

                return count_sid

			end


			--==============================================================================

		local function setSporthandler( sid )

			local _SID = tostring(sid)
			
			interfacePresetEventsTable["sport_sid"] = _SID
						
			createinterfacesports_TYPES_table(sid) 

			local _DATASTORE_SID = interfaceSports_Types_Table[_SID]
			
			interfacePresetEventsTable["sport_datastore_sid"] = _DATASTORE_SID 

		   	if _interfaceDebug then
		    		local info = debug.getinfo(1, "Sl")
		    		print ( string.format("[%s]:%d setSporthandler _SID = %s, _DATASTORE_SID = %s",info.short_src, info.currentline, _SID,_DATASTORE_SID) )
			end

		end


			--==============================================================================
			local function createinterfacesports_DATA_table(sid, table_view)

				-----------------------------------------------------

				interfaceSportsStandingsTable =  {}

				local count_standings = 0


                local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]
                
				if datastore.sports.standings[_DATASTORE_SID] then


					-----------------------------------------------------
				    local a = {}
				    for n in pairs(datastore.sports.standings[_DATASTORE_SID]) do table.insert(a, n) end

					table.sort(a)

				    for k,v in ipairs(a) do

						interfaceSportsStandingsTable[tostring(count_standings)] = v
						count_standings = count_standings + 1

					end

					a = nil

					-----------------------------------------------------

		   	   		if _interfaceDebug then
				    		local info = debug.getinfo(1, "Sl")
				    		print ( string.format("[%s]:%d _DATASTORE_SID = %s",info.short_src, info.currentline, _DATASTORE_SID) )
					end
				else
		   	   		if _interfaceDebug then
						local info = debug.getinfo(1, "Sl")
				    		print ( string.format("[%s]:%d NOT FOUND _DATASTORE_SID = NIL",info.short_src, info.currentline) )
					end
				end
				

				-----------------------------------------------------

	   	   		if _interfaceDebug then
		    			local info = debug.getinfo(1, "Sl")
		    			print ( string.format("[%s]:%d interfaceSportsStandingsTable = ",info.short_src, info.currentline) )
				end

				table.sort(interfaceSportsStandingsTable)
	   	   		if _interfaceDebug then
					for k,v in pairs(interfaceSportsStandingsTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

				return count_standings


			end

			--==============================================================================
			local function createinterfacesportsgamestable()

				interfaceSports_Timestamp_per_Games_Table =  {}
				
				local gid_timestamp = 0
				
				for k,v in pairs(datastore.sports.games) do

                    gid_timestamp = get_timestamp_for_gid(k,"all")
                    
                    while ( interfaceSports_Timestamp_per_Games_Table[gid_timestamp] ~= nil ) do
			    local info = debug.getinfo(1, "Sl")
					    print ( string.format("[%s]:%d CONFLICT gid_timestamp [%d][%s]",info.short_src, info.currentline,k,gid_timestamp) )

                        gid_timestamp = gid_timestamp + 1 -- (trick) adding 1 second to resolve gids with the same date/time
                    end

                    interfaceSports_Timestamp_per_Games_Table[gid_timestamp] = k

				end
				-----------------------------------------------------
				interfaceSportsGamesTable =  {}

				local count_games = 0

			    local a = {}
			    for n in pairs(interfaceSports_Timestamp_per_Games_Table) do table.insert(a, n) end

				table.sort(a) -- , function (_x, _y) return not (_x < _y) end) -- inverted sort

			    for k,v in ipairs(a) do

					interfaceSportsGamesTable[tostring(count_games)] = interfaceSports_Timestamp_per_Games_Table[v]
					count_games = count_games + 1

				end

				a = nil
				-----------------------------------------------------

	   	   	    	if _interfaceDebug then
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d interfaceSportsGamesTable = ",info.short_src, info.currentline) )
			    	end

				table.sort(interfaceSportsGamesTable)
	   	   		if _interfaceDebug then
					for k,v in pairs(interfaceSportsGamesTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

                -----------------------------------------------------
                
                
				return count_games

			end

			--==============================================================================

			local function createinterface_allsports_table()

				-----------------------------------------------------

			interfaceSportsAllSportsTable =  {}

				local count_sid = 0
				 
				-----------------------------------------------------
			    local a = {}
			    -- 	temp table is a maping of label(eg. Football) to sport code(nfl) used so that sports.types can be 
			    --	sorted alphabetically based on the labels(football,hocket etc) 
			    local tempTable={} 
			    for n,v in pairs(datastore.sports.types) do 
			    	table.insert(a,v.label) 
					tempTable[v.label] = n 
				end

				table.sort(a)
										   
			    for k,v in ipairs(a) do
					interfaceSportsAllSportsTable[tostring(count_sid)] = tempTable[v]
					count_sid = count_sid + 1
				end

				a = nil
				tempTable = nil
				-----------------------------------------------------

	   	   		if _interfaceDebug then
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d interfaceSportsAllSportsTable = ",info.short_src, info.currentline) )
				end

				table.sort(interfaceSportsAllSportsTable)

	   	   		if _interfaceDebug then
					for k,v in pairs(interfaceSportsAllSportsTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

				return count_sid

			end

			--==============================================================================

			local function createinterfacesports_team_table(sid_param)

				-----------------------------------------------------

				interfaceSports_Team_Table =  {}

				local count_team = 0

                if ( datastore.sports.teams[sid_param] == nil ) then

				    local info = debug.getinfo(1, "Sl")
				    print ( string.format("[%s]:%d NOT FOUND datastore.sports.teams[%s]",info.short_src, info.currentline,sid_param) )

                    return 0

                end


				-----------------------------------------------------

				interfaceSports_Team_Sorted_Table =  {}

				local team_conflict_num = 0
				local team_name = ""

				for k,v in pairs(datastore.sports.teams[sid_param]) do

                    team_name = v.name

					while ( interfaceSports_Team_Sorted_Table[team_name] ~= nil ) do
					    local info = debug.getinfo(1, "Sl")
						if team_name ~= nil then
							print ( string.format("[%s]:%d CONFLICT Team Name [%s]",info.short_src, info.currentline,team_name) )
						end

                        team_conflict_num = team_conflict_num + 1 -- (trick) resolving conflicting names
						team_name = team_name..tostring(team_conflict_num)
                    end


				    local info = debug.getinfo(1, "Sl")
					if team_name ~= nil then
						print ( string.format("[%s]:%d TEAM NAME [%s] k[%s]",info.short_src, info.currentline,team_name,k) )
					else
                    	print ( string.format("[%s]:%d ERROR TEAM NAME [NIL]",info.short_src, info.currentline) )
					end
					
					interfaceSports_Team_Sorted_Table[team_name] = k

				end


				
				-----------------------------------------------------

				local a = {}
			    for n in pairs( interfaceSports_Team_Sorted_Table ) do table.insert(a, n) end

				table.sort(a)

			    for k,v in ipairs(a) do

					interfaceSports_Team_Table[tostring(count_team)] = interfaceSports_Team_Sorted_Table[v]
					count_team = count_team + 1

				end

				a = nil

				-----------------------------------------------------

	   	   		if _interfaceDebug then
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d interfaceSports_Team_Table = ",info.short_src, info.currentline) )
				end

				table.sort(interfaceSports_Team_Table)
	   	   		if _interfaceDebug then
					for k,v in pairs(interfaceSports_Team_Table) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

				return count_team


			end

			--==============================================================================

			local function createinterfacesports_teamschedule_table(tid)

				-----------------------------------------------------
				interfaceSports_TeamSchedule_Table =  {}

				local datastore_tid = interfaceSports_Team_Table[tid]

				if ( datastore_tid == nil ) then

					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d - NOT FOUND tid[%s] = nil", info.short_src, info.currentline, tid) )

				   return 0

				end

				local info = debug.getinfo(1, "Sl")
				print ( string.format("[%s]:%d - FOUND tid[%s] = %s", info.short_src, info.currentline, tid, datastore_tid) )

				local count_schedule = 0

				if ( datastore.sports.schedules[datastore_tid] ) then

					-----------------------------------------------------
					interfaceSportsGamesTable =  {}

					local count_games = 0

				    local a = {}
				    for n in pairs(datastore.sports.schedules[datastore_tid]) do table.insert(a, n) end

					table.sort(a) -- , function (_x, _y) return not (_x < _y) end) -- inverted sort


				    for k,v in ipairs(a) do

						interfaceSports_TeamSchedule_Table[tostring(count_schedule)] = v -- timestamp


						for _gid_,value in pairs(datastore.sports.schedules[datastore_tid][tonumber(v)]) do

							interfaceSportsGamesTable[tostring(count_schedule)] =_gid_
							break
						end

						count_schedule = count_schedule + 1

					end

					a = nil


					-----------------------------------------------------
				else

					local info = debug.getinfo(1, "Sl")
     				print ( string.format("[%s]:%d - NOT FOUND Schedules for tid[%s] = %s", info.short_src, info.currentline, tid, datastore_tid) )

					return 0
				end

				-----------------------------------------------------

					local info = debug.getinfo(1, "Sl")
 					print ( string.format("[%s]:%d interfaceSports_TeamSchedule_Table =", info.short_src, info.currentline) )



				--table.sort(interfaceSports_TeamSchedule_Table)
				if _interfaceDebug then
					for k,v in pairs(interfaceSports_TeamSchedule_Table) do
					for _gid_,detail in pairs(datastore.sports.schedules[datastore_tid][tonumber(v)]) do
						print ("[\"" .. k .. "\"] = [" .. v.."] [".._gid_.."]")
						break
					end
				end
				end

				--===================================================
				-----------------------------------------------------

				if _interfaceDebug then
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d interfaceSportsGamesTable = ",info.short_src, info.currentline) )

					for k,v in pairs(interfaceSportsGamesTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

                -----------------------------------------------------
				--===================================================

				return count_schedule

			end

			--==============================================================================

			local function createinterfacesports_ScoreDays_table()

				-----------------------------------------------------

				interfaceSportsDaysTable =  {}

				local count_days = 0

				local _DATASTORE_SID = tostring(interfacePresetEventsTable["sport_datastore_sid"])

				if ( datastore.sports.scores[tostring(_DATASTORE_SID)] == nil ) then

					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d - NOT FOUND datastore.sports.scores[sid=%s]", info.short_src, info.currentline, _DATASTORE_SID) )

                    return 0

                end

				-----------------------------------------------------
			    local a = {}
			    for n in pairs(datastore.sports.scores[_DATASTORE_SID]) do table.insert(a, tonumber(n)) end

				table.sort(a) -- , function (_x, _y) return not (_x < _y) end) -- inverted sort
			    
			    for k,v in ipairs(a) do

					interfaceSportsDaysTable[tostring(count_days)] = v
					count_days = count_days + 1

				end
				
				a = nil

				-----------------------------------------------------

	   	   		if _interfaceDebug then
					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d interfaceSportsDaysTable = ", info.short_src, info.currentline) )
				end

				table.sort(interfaceSportsDaysTable)
	   	   		if _interfaceDebug then
					for k,v in pairs(interfaceSportsDaysTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

				return count_days

			end

			--==============================================================================

			local function createinterfacesports_ScoreGames_table(datastore_day)

				-----------------------------------------------------

				interfaceSportsScoreGamesTable =  {}

				local count_games = 0

                local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

				if ( (datastore.sports.scores[_DATASTORE_SID] == nil) or
				     (datastore.sports.scores[_DATASTORE_SID][datastore_day] == nil) ) then

				   local info = debug.getinfo(1, "Sl")
				   print ( string.format("[%s]:%d - NOT FOUND datastore.sports.SCORE[sid=%s][day=%s]", info.short_src, info.currentline, _DATASTORE_SID,datastore_day) )

				   return 0

				end

                interfaceSportsGamesTable =  {}
                
				-----------------------------------------------------
			    local a = {}
			    for n in pairs( datastore.sports.scores[_DATASTORE_SID][datastore_day] ) do table.insert(a, n) end

				table.sort(a)

			    for k,v in ipairs(a) do

					interfaceSportsScoreGamesTable[tostring(count_games)] = v
					interfaceSportsGamesTable[tostring(count_games)] = v
					count_games = count_games + 1

				end

				a = nil

				-----------------------------------------------------

	   	   		if _interfaceDebug then
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d interfaceSportsGamesTable = ", info.short_src, info.currentline) )
				end

				table.sort(interfaceSportsScoreGamesTable)
	   	   		if _interfaceDebug then
					for k,v in pairs(interfaceSportsScoreGamesTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

				--===================================================

	   	   		if _interfaceDebug then
			    		local info = debug.getinfo(1, "Sl")
			    		print ( string.format("[%s]:%d interfaceSportsGamesTable = ",info.short_src, info.currentline) )
				end

				table.sort(interfaceSportsGamesTable)
	   	   		if _interfaceDebug then
					for k,v in pairs(interfaceSportsGamesTable) do
						print ("[\"" .. k .. "\"] = " .. v)
					end
				end

                -----------------------------------------------------
				--===================================================
				
				
				return count_games

			end

			--==============================================================================
			--******************************************************************************

			--==============================================================================
			--This function is used for handling all the sports requests.
			--==============================================================================
			local function handleSports(_sportsString)

			local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_sportsString,"(%a+)%s*")

			   local _subString = string.sub(_sportsString,_sizeStr+2,-1)

			   -- sports/data

			   if string.lower(_key) == "data" then

			   -- _SID is previously set by setSport{sport}

				   local lid = 0;

			   local datastore_lid = ""
				   local datastore_sid = ""

				   -- sports/data/table/

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   -- sports/data/table/lid (league id)

				   _start,_sizeStr,lid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   if string.lower(lid) == "count" then

						local count_standings = 0

						-- verify current sports TYPE table to retrieve current _SID set by setSports

						local _SID = interfacePresetEventsTable["sport_sid"]
						
						local count_sid = createinterfacesports_TYPES_table(_SID)

						if (count_sid == 0) then

					        -- GET /od2/sports/sport

							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d FIRED Foreground /sports/", info.short_src, info.currentline) )
					        
							interfacePresetEventsTable["last_request_table"] = datastore.sports.types
							interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
							interfacePresetEventsTable["last_request_table_msg_string"] = "datastore.sports.types"
					        
							handleStartForeground(constructURL("sports","/"));
						    return nil

						end

						--Create Sports table before returning a count.
                        local _SID = interfacePresetEventsTable["sport_sid"]

						local count_standings = createinterfacesports_DATA_table(_SID, _TABLE_VIEW)

						if ( count_standings == 0 ) then

							-- GET /od2/sports/standings?id=_DATASTORE_SID
							
							local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d FIRED Foreground /sportsstandings/sid=%s", info.short_src, info.currentline,_DATASTORE_SID) )
							
							if datastore.sports.standings[_DATASTORE_SID] == nil then
								interfacePresetEventsTable["last_request_table"] = datastore.sports.standings
								interfacePresetEventsTable["last_request_table_key"] = string.format("%s",_DATASTORE_SID)
								interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.standings[%s]",_DATASTORE_SID)
							else
								interfacePresetEventsTable["last_request_table"] = datastore.sports.standings[_DATASTORE_SID]
								interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
								interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.standings[%s]",_DATASTORE_SID)
							end
							handleStartForeground(constructURL("sportsstandings",_DATASTORE_SID));
							
							return nil

						end

						return _strclsId, tostring(count_standings)

				   end

                   datastore_lid = interfaceSportsStandingsTable[tostring(lid)]

				   if (datastore_lid == nil) then

						-- ERROR
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d ERROR lid[%s]=nil", info.short_src, info.currentline,lid) )

						return _strclsId, nil

				   end

                   local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

				   if (datastore.sports.standings[_DATASTORE_SID] == nil) or
				      (datastore.sports.standings[_DATASTORE_SID][datastore_lid] == nil) then

					  -- GET /od2/sports/standings?id=_DATASTORE_SID
					  
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d FIRED Foreground /sportsstandings/sid=%s", info.short_src, info.currentline,_DATASTORE_SID) )
						
						if (datastore.sports.standings[_DATASTORE_SID] == nil) then
							interfacePresetEventsTable["last_request_table"] = datastore.sports.standings
							interfacePresetEventsTable["last_request_table_key"] = tostring(_DATASTORE_SID)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.standings[%s]",_DATASTORE_SID)
						else -- datastore.sports.standings[_DATASTORE_SID][datastore_lid] == nil
							interfacePresetEventsTable["last_request_table"] = datastore.sports.standings[_DATASTORE_SID]
							interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_lid)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.standings[%s][%s]",_DATASTORE_SID,datastore_lid)
						end

						handleStartForeground(constructURL("sportsstandings",_DATASTORE_SID));
					  return nil

				   end

                   local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

				   if string.lower(_key) == "title" then

						return _strclsId, datastore.sports.standings[_DATASTORE_SID][datastore_lid].picker_label

				   elseif string.lower(_key) == "subtitle" then

						return _strclsId, datastore.sports.standings[_DATASTORE_SID][datastore_lid].standings_label

				   elseif string.lower(_key) == "date" then

						return _strclsId, datastore.sports.standings[_DATASTORE_SID][datastore_lid].week

				   elseif string.lower(_key) == "details" then

						return _strclsId, datastore.sports.standings[_DATASTORE_SID][datastore_lid].details

				   end

			   elseif string.lower(_key) == "schedules" then
				local tid = 0
				local scheduleId = 0

				-- sport/schedules/{count|tid}
				_start,_sizeStr,tid = string.find(_subString,"(%w+)")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

				if string.lower(tid) == "count" then

					local count_tid = 0

					--Create DAYS Sports table before returning a count.
                    local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

					count_tid = createinterfacesports_team_table(_DATASTORE_SID)
					
					if (count_tid == 0) and (_DATASTORE_SID ~= nil) and (datastore.sports.teams[_DATASTORE_SID] == nil) then
					
					  -- GET /od2/sports/standings?id=_DATASTORE_SID
					  
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d FIRED Foreground /sportsteams/sid[%s]", info.short_src, info.currentline,_DATASTORE_SID) )

						datastore.sports.teams[_DATASTORE_SID] = {}

						interfacePresetEventsTable["last_request_table"] = datastore.sports.teams[_DATASTORE_SID]
						interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
						interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.teams[%s]",_DATASTORE_SID)
						
						handleStartForeground(constructURL("sportsteams",_DATASTORE_SID));
						return nil
					end

					return _strclsId, tostring(count_tid)
				end

				-- sport/schedules/tid/{today|count|sched}
				_start,_sizeStr,scheduleId = string.find(_subString,"(%w+)")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

				if ( (string.lower(scheduleId) == "count") or (string.lower(scheduleId) == "today") or (string.lower(scheduleId) == "dayoffset")) then

					local count_scheduleId = 0

					--Create DAYS Sports table before returning a count.
					count_scheduleId = createinterfacesports_teamschedule_table(tid)
					
                    local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

					if (count_scheduleId == 0) and (_DATASTORE_SID ~= nil) then
					
					  -- GET /od2/sports/schedules?id=tid
					  
					    local datastore_tid = interfaceSports_Team_Table[tostring(tid)]
					    
					    if datastore_tid then
					  
							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d FIRED Foreground /sportsschedules/tid[%s]", info.short_src, info.currentline,datastore_tid) )

							-- datastore.sports.schedules[datastore_tid]

                            
							interfacePresetEventsTable["last_request_table"] = datastore.sports.schedules
							interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_tid)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.schedules[%s]",datastore_tid)

							handleStartForeground(constructURL("sportsschedules",datastore_tid));
							return nil
					    
						end
					end

					if (string.lower(scheduleId) == "count") then
					return _strclsId, tostring(count_scheduleId)
					elseif (string.lower(scheduleId) == "dayoffset") then
						local currentCDMATime = net.getutctime()
						for i=0,(count_scheduleId-1) do
							if interfaceSports_TeamSchedule_Table[tostring(i)] > currentCDMATime then
print("Dayoffset: Returning count...", (count_scheduleId - i))
								return _intclsId, (count_scheduleId - i)
							end
						end

print("Dayoffset: Returning last count... 1")
						return _intclsId, 1
					else
						-- find the index which is closest to current handset time
						local currentCDMATime = net.getutctime()
						for i=0,(count_scheduleId-1) do
							if interfaceSports_TeamSchedule_Table[tostring(i)] > currentCDMATime then
print("Today: Returning count...", i)
								return _intclsId, i
							end
						end

print("Today: Returning last count...", (count_scheduleId-1))
					    return _intclsId, (count_scheduleId-1)
					
					end
				end


				local datastore_tid = interfaceSports_Team_Table[tostring(tid)]
				local datastore_timestamp = interfaceSports_TeamSchedule_Table[tostring(scheduleId)]

				local datastore_gid = ""
				for _gid_,v in pairs(datastore.sports.schedules[datastore_tid][tonumber(datastore_timestamp)]) do
					datastore_gid =_gid_
					break
				end

				if (datastore_tid == nil) then

					-- ERROR
					
					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d ERROR FIRED tid[%s] = nil", info.short_src, info.currentline,tid) )

					return _strclsId, nil

				end

				if (datastore_gid == nil) then

					-- ERROR
					
					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d ERROR FIRED scheduleId/gid[%s] = nil", info.short_src, info.currentline,scheduleId) )

					return _strclsId, nil

				end
				-- sport/schedules/tid/sched/{date|details|gid}
				_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				if ( datastore.sports.schedules[datastore_tid] == nil ) or
				   ( datastore.sports.schedules[datastore_tid][tonumber(datastore_timestamp)] == nil ) then

				    -- /od2/sports/schedules?id=datastore_tid
				    
					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d FIRED Foreground /sportsschedules/tid=%s", info.short_src, info.currentline,datastore_tid) )


                    
					if datastore.sports.schedules[datastore_tid] == nil then

							interfacePresetEventsTable["last_request_table"] = datastore.sports.schedules
							interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_tid)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.schedules[%s]",datastore_tid)

					else -- datastore.sports.schedules[datastore_tid][datastore_timestamp]

							interfacePresetEventsTable["last_request_table"] = datastore.sports.schedules[datastore_tid]
							interfacePresetEventsTable["last_request_table_key"] = tonumber(datastore_timestamp)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.schedules[%s][%d]",datastore_tid,datastore_timestamp)
					end

					handleStartForeground(constructURL("sportsschedules",datastore_tid));
				    return nil

				end

			   if string.lower(_key) == "date" then


					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d - tid %s gid %s",info.short_src, info.currentline, datastore_tid, datastore_gid) )

					return _strclsId, datastore.sports.schedules[datastore_tid][tonumber(datastore_timestamp)][datastore_gid]
			   end


			   if ( datastore_gid == nil ) then

					local info = debug.getinfo(1, "Sl")
    	            print ( string.format("[%s]:%d - sport/schedules/tid(%s)/sched(%s)/(%s) GID = NIL%s",info.short_src, info.currentline, tid,scheduleId,_key) )

			        -- ERROR
			        return _strclsId, nil


			   else

				local info = debug.getinfo(1, "Sl")
                print ( string.format("[%s]:%d - sport/schedules/tid(%s)/sched(%s)/(%s) GID = %s",info.short_src, info.currentline, tid,scheduleId,_key,datastore_gid) )

			   end


			   if ( datastore.sports.games[datastore_gid] == nil ) then

					local info = debug.getinfo(1, "Sl")
                    print ( string.format("[%s]:%d - NOT FOUND: sport/schedules/tid(%s)/sched(%s)/(%s)",info.short_src, info.currentline, tid,scheduleId,_key) )

					-- /od2/sports/game?datastore_gid
					-- server can return
						-- a Game table
						-- text with No Info or Check Back
						
					local info = debug.getinfo(1, "Sl")
					print ( string.format("[%s]:%d FIRED Foreground /sportsgames/gid=%s", info.short_src, info.currentline,datastore_gid) )

					interfacePresetEventsTable["last_request_table"] = datastore.sports.games
					interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_gid)
					interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.types[%s]",datastore_gid)

					handleStartForeground(constructURL("sportsgames",datastore_gid));
					return nil

			   end

			   if string.lower(_key) == "details" then

				    if string.lower( datastore.sports.games[datastore_gid].label ) == "preview" or
				       string.lower( datastore.sports.games[datastore_gid].label ) == "recap" then

						return _strclsId, datastore.sports.games[datastore_gid].details

					else

						return _strclsId, datastore.sports.games[datastore_gid].score1.." "..datastore.sports.games[datastore_gid].score2.." "..datastore.sports.games[datastore_gid].status

					end

			   elseif string.lower(_key) == "gid" then

					return _strclsId, datastore.sports.games[datastore_gid]

			   end



----------------------  SPORTS/SCORES

			   elseif string.lower(_key) == "scores" then
				local day = 0
				local gid = 0
				_start,_sizeStr,day = string.find(_subString,"(%w+)")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)


				if string.lower(day) == "count" then

					local count_days = 0

					--Create DAYS Sports table before returning a count.
					count_days = createinterfacesports_ScoreDays_table()
					
					local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]
					
			   		if ( count_days == 0 ) and(_DATASTORE_SID ~= nil) and (datastore.sports.scores[_DATASTORE_SID] == nil) then
						-- GET /od2/sports/scores?id=_DATASTORE_SID
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d NOT FOUND /scores/days - FIRED Foreground /sportsscores/sid=%s", info.short_src, info.currentline,_DATASTORE_SID) )
						interfacePresetEventsTable["last_request_table"] = datastore.sports.scores
						interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
						interfacePresetEventsTable["last_request_table_msg_string"] = "datastore.sports.scores"

						handleStartForeground(constructURL("sportsscores",_DATASTORE_SID));
						return nil
					end
					
					return _strclsId, tostring(count_days)
				end


				if string.lower(day) == "today" then
					local count_days = 0

					for k,v in pairs(interfaceSportsDaysTable) do
						count_days = count_days + 1
					end

					if count_days == 0 then
						return _intclsId, 0
					end

					-- find the index which is closest to current handset time
					local currentCDMATime = net.getutctime()
					for i=0,(count_days-1) do
						if getZeroBasedDay(addLocalTime(tonumber(interfaceSportsDaysTable[tostring(i)]))) >= 0 then
print("Today: Returning count...", i)
							return _intclsId, i
						end
					end
print("Today: Returning last count...", (count_days-1))
					return _intclsId, (count_days-1)

				elseif (string.lower(day) == "dayoffset") then
					local count_days = 0

					for k,v in pairs(interfaceSportsDaysTable) do
						count_days = count_days + 1
					end

					if count_days == 0 then
						return _intclsId, 0
					end

					-- find the index which is closest to current handset time
					local currentCDMATime = net.getutctime()
					for i=0,(count_days-1) do
						if getZeroBasedDay(addLocalTime(tonumber(interfaceSportsDaysTable[tostring(i)]))) >= 0 then
print("Dayoffset: Returning count...", i)
							return _intclsId, (count_days - i)
						end
					end
print("Dayoffset: Returning last count...", (count_days-1))
					return _intclsId, 1
				end

				_start,_sizeStr,gid = string.find(_subString,"(%w+)")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

				if string.lower(gid) == "date" then -- sports/scores/day[0..n]/date
				
				    local datastore_day = interfaceSportsDaysTable[tostring(day)]
				    
				    local info = debug.getinfo(1, "Sl")
				    print ( string.format("[%s]:%d datastore_day scores/day[%s]", info.short_src, info.currentline,datastore_day) )

					return _strclsId, tostring(datastore_day)
				    				
				
				elseif string.lower(gid) == "count" then

					local count_gid = 0

					local datastore_day = interfaceSportsDaysTable[tostring(day)]

					if ( datastore_day == nil ) then
					    -- ERROR
						local info = debug.getinfo(1, "Sl")
	    	            print ( string.format("[%s]:%d ERROR: scores/days[%s] == NIL",info.short_src, info.currentline, day) )
					    
					    return _strclsId, nil
					end

					--Create DAYS Sports table before returning a count.
					count_gid = createinterfacesports_ScoreGames_table(datastore_day)

					local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

					
					if count_gid == 0 then
				   		
						-- GET /od2/sports/scores?id=_DATASTORE_SID 				   		
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d NOT FOUND /scores/days/COUNT_GID - FIRED Foreground /sportsscores/sid=%s", info.short_src, info.currentline,_DATASTORE_SID) )

						if (datastore.sports.scores[_DATASTORE_SID] == nil) then

							interfacePresetEventsTable["last_request_table"] = datastore.sports.scores
							interfacePresetEventsTable["last_request_table_key"] = string.format("%s",_DATASTORE_SID)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.scores[%s]",_DATASTORE_SID)

						else -- (datastore.sports.scores[_DATASTORE_SID][datastore_day] == nil)
						
							interfacePresetEventsTable["last_request_table"] = datastore.sports.scores[_DATASTORE_SID]
							interfacePresetEventsTable["last_request_table_key"] = tonumber(datastore_day)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.scores[%s][%s]",_DATASTORE_SID,datastore_day)
						end

						handleStartForeground(constructURL("sportsscores",_DATASTORE_SID));
						return nil
					end

					return _strclsId, tostring(count_gid)
				end

				_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

					local datastore_day = interfaceSportsDaysTable[tostring(day)]
										
					local datastore_gid = interfaceSportsScoreGamesTable[tostring(gid)]

					if (datastore_day == nil) or (datastore_gid == nil) then

						-- ERROR
						local info = debug.getinfo(1, "Sl")
	    	            print ( string.format("[%s]:%d ERROR: scores/days[%s]/gid[%s] == NIL",info.short_src, info.currentline, day,gid) )
						
						return nil
					end


					local _DATASTORE_SID = interfacePresetEventsTable["sport_datastore_sid"]

				   if datastore.sports.scores[_DATASTORE_SID] == nil then

				   		-- /od2/sports/scores?id=_DATASTORE_SID
				   		
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d FIRED Foreground /sportsscores/sid=%s", info.short_src, info.currentline,_DATASTORE_SID) )

						interfacePresetEventsTable["last_request_table"] = datastore.sports.scores
						interfacePresetEventsTable["last_request_table_key"] = string.format("%s",_DATASTORE_SID)
						interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.scores[%s]",_DATASTORE_SID)

						handleStartForeground(constructURL("sportsscores",_DATASTORE_SID));
				   		return nil

				   end

				   if string.lower(_key) == "score" then

						return _strclsId, datastore.sports.scores[_DATASTORE_SID][datastore_day][tostring(datastore_gid)]

				   elseif string.lower(_key) == "date" then


						return _strclsId, datastore_day

				   end


----------------------  SPORTS/GAMES

			   elseif string.lower(_key) == "games" then
				   local gid = 0;

				   _start,_sizeStr,gid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   local datastore_gid = 0

				   if string.lower(gid) == "count" then

						local count_games = 0

						--Create Sports table before returning a count.
						count_games = createinterfacesportsgamestable()						
						if ( count_games == 0 ) then
							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d WARN - NO GAMES!", info.short_src, info.currentline) )
						end
						return _strclsId, tostring(count_games)
				   end

				   datastore_gid = interfaceSportsGamesTable[tostring(gid)]

				   if datastore_gid == nil then

				   		-- ERROR
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d NOT FOUND sports/gid[%s]", info.short_src, info.currentline,gid) )
				   		return nil

				   end

					if ( datastore.sports.games[datastore_gid] == nil ) then

				   		-- ERROR
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d NOT FOUND sports/gid[%s]=[%s]", info.short_src, info.currentline,gid,datastore_gid) )
					
						-- /od2/sports/game?datastore_gid
						-- server can return
							-- a Game table
							-- text with No Info or Check Back
							
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d FIRED Foreground /sportsgames/gid=%s", info.short_src, info.currentline,datastore_gid) )
						
						interfacePresetEventsTable["last_request_table"] = datastore.sports.games
						interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_gid)
						interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.types[%s]",datastore_gid)
						
						handleStartForeground(constructURL("sportsgames",datastore_gid));
						return nil
						
					end

                    local label = lower_no_spaces( datastore.sports.games[datastore_gid].label )
                    
				    if (label == "preview") or (label == "recap") then

						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d sports.games[%s].label[%s]", info.short_src, info.currentline,datastore_gid,label) )
						
						if string.lower(_key) == "title" then
						
							return _strclsId, datastore.sports.games[datastore_gid].summary
						
						elseif string.lower(_key) == "details" then
						
							return _strclsId, datastore.sports.games[datastore_gid].details

						elseif string.lower(_key) == "label" then

							return _strclsId, label

						elseif string.lower(_key) == "status" then
						
							return _strclsId, ""
						
						elseif string.lower(_key) == "scoreteama" then
						
							return _strclsId, ""
						
						elseif string.lower(_key) == "scoreteamb" then
						
							return _strclsId, ""
						
						end
				   
				   elseif (label == "checkback") or (label == "noinfo") then
					    -- equals to "Check back" or "No Info"				
						
						if (datastore.sports.games[datastore_gid].info_read and (datastore.sports.games[datastore_gid].info_read < 7)) then 

							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d sports.games[%s].label[%s] = %s", info.short_src, info.currentline,datastore_gid,label,label) )
							
							if (string.lower(_key) == "label") then
							    -- store information if game info was read once
							    datastore.sports.games[datastore_gid].info_read = datastore.sports.games[datastore_gid].info_read + 1							    
								return _strclsId, label
							else
							   return _strclsId, ""
							end
						   
						else
							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d FIRED Foreground /sportsgames/gid=%s after reading %s", info.short_src, info.currentline,datastore_gid, label) )
							
							datastore.sports.games[datastore_gid] = nil
							
							interfacePresetEventsTable["last_request_table"] = datastore.sports.games
							interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_gid)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.types[%s]",datastore_gid)
							
							handleStartForeground(constructURL("sportsgames",datastore_gid));
							return nil
						end
				   
				   else
				   
						
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d sports.games[%s].label = [%s]", info.short_src, info.currentline,datastore_gid,label) )
						
						
						if string.lower(_key) == "title" then
						
							return _strclsId, datastore.sports.games[datastore_gid].teams

						elseif string.lower(_key) == "label" then

							return _strclsId, "inprogress" -- string.lower( datastore.sports.games[datastore_gid].label )

						elseif string.lower(_key) == "details" then
						
							return _strclsId, string.format("%s\n\n%s\n\n%s\n%s\n\n%s",datastore.sports.games[datastore_gid].date,  datastore.sports.games[datastore_gid].teams, datastore.sports.games[datastore_gid].score1, datastore.sports.games[datastore_gid].score2, datastore.sports.games[datastore_gid].status)
						
						elseif string.lower(_key) == "status" then
						
							return _strclsId, (datastore.sports.games[datastore_gid].status or "")
						
						elseif string.lower(_key) == "scoreteama" then
						
							return _strclsId, (datastore.sports.games[datastore_gid].score1  or "")
						
						elseif string.lower(_key) == "scoreteamb" then
						
							return _strclsId, (datastore.sports.games[datastore_gid].score2  or "")
						
						end
				   
				   end



----------------------  SPORTS/ALLSPORTS

			   elseif string.lower(_key) == "allsports" then
				   local sid = 0;

				   _start,_sizeStr,sid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)


				   if string.lower(sid) == "count" then

						local count_sid = 0

						--Create Sports table before returning a count.
						count_sid = createinterface_allsports_table()

						-- ASSUMPTION - NO SPORTS - LET'S START REQUESTIGN SPORTS
						-- /od2/sports/

						if  (count_sid == 0) then
							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d FIRED Foreground /sports/", info.short_src, info.currentline) )

							interfacePresetEventsTable["last_request_table"] = datastore.sports.types
							interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
							interfacePresetEventsTable["last_request_table_msg_string"] = "datastore.sports.types"

							handleStartForeground(constructURL("sports","/"));
							return nil
						end
						
						-- NEED CLARIFY SINCE WE ARE NOT RETURNING NIL
						return _strclsId, tostring(count_sid)
					end

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

                   datastore_sid = interfaceSportsAllSportsTable[tostring(sid)]

				   if string.lower(_key) == "name" then

						return _strclsId, datastore.sports.types[datastore_sid].label

				   elseif string.lower(_key) == "inseason" then

						local inseason = datastore.sports.types[datastore_sid].in_season -- boolean

						if inseason then
							return _strclsId, "_true"
						else
                            return _strclsId, "_false"
						end

				   elseif string.lower(_key) == "id" then

						if ( datastore_sid ~= nil ) then

							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d FOUND AllSports/id[%s]", info.short_src, info.currentline,datastore_sid) )

							return _strclsId, datastore_sid
							
						else
					   		-- ERROR
							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d NOT FOUND AllSports/id[%s]", info.short_src, info.currentline,sid) )
					   		return nil
						end	

				   elseif string.lower(_key) == "image" then

	    				local datastore_sid = interfaceSportsAllSportsTable[tostring(sid)]
						local _shortname = datastore.sports.types[datastore_sid].image
                        image_vfs =  datastore.images[_shortname]

						if image_vfs then
							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d IMAGE: SID=%s IMG=%s", info.short_src, info.currentline,datastore_sid,image_vfs) )

							return _imageclsId, loadImage(image_vfs)
						else
							local info = debug.getinfo(1, "Sl")
							print ( string.format("[%s]:%d ERROR NO IMAGE: SID=%s shortname=%s", info.short_src, info.currentline,datastore_sid,_shortname) )

							return nil
						end

					end


			   elseif string.lower(_key) == "allteams" then
				local sid = 0
				local tid = 0
				_start,_sizeStr,sid = string.find(_subString,"(%w+)")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

				if string.lower(sid) == "count" then

					local count_sid = 0

					--Create Sports table before returning a count.
					count_sid = createinterface_allsports_table()

					-- ASSUMPTION - NO SPORTS - LET'S START REQUESTIGN SPORTS
					-- /od2/sports/

					if  (count_sid == 0) then
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d FIRED Foreground /sports/", info.short_src, info.currentline) )

						interfacePresetEventsTable["last_request_table"] = datastore.sports.types
						interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
						interfacePresetEventsTable["last_request_table_msg_string"] = "datastore.sports.types"

						handleStartForeground(constructURL("sports","/"));
						return nil
					end
						
					return _strclsId, tostring(count_sid)
				end

				local info = debug.getinfo(1, "Sl")
				print ( string.format("[%s]:%d datastore_sid = %s",info.short_src, info.currentline,datastore_sid) )

				_start,_sizeStr,tid = string.find(_subString,"(%w+)")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

                datastore_sid = interfaceSportsAllSportsTable[tostring(sid)]

				if string.lower(tid) == "count" then

					local count_tid = 0

					--Create Sports table before returning a count.
					count_tid = createinterfacesports_team_table(datastore_sid)

					if ((count_tid == 0) and (datastore.sports.teams[datastore_sid] == nil)) then

						-- /od2/sports/team?id=datastore_sid
						
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d FIRED Foreground /sportsteams/sid=%s", info.short_src, info.currentline,datastore_sid) )
						interfacePresetEventsTable["last_request_table"] = datastore.sports.teams
						interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
						interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.teams[%s]",datastore_sid)

						handleStartForeground(constructURL("sportsteams",datastore_sid));
                        			return nil
						
					end

					return _strclsId, tostring(count_tid)
				end

				datastore_tid = interfaceSports_Team_Table[tostring(tid)]

				local info = debug.getinfo(1, "Sl")
				print ( string.format("[%s]:%d datastore_tid = %s",info.short_src, info.currentline,datastore_tid) )


				_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")


				if string.lower(_key) == "name" then

					return _strclsId, datastore.sports.teams[datastore_sid][datastore_tid].name

			    elseif string.lower(_key) == "image" then

    				local datastore_sid = interfaceSportsAllSportsTable[tostring(sid)]
                    local _shortname = datastore.sports.teams[datastore_sid][datastore_tid].image
					local image_vfs = datastore.images[_image_name]
					
				    image_vfs =  datastore.images[_shortname]
					
					if image_vfs then
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d IMAGE: SID=%s TID=%s IMG=%s", info.short_src, info.currentline,datastore_sid,datastore_tid,image_vfs) )

						return _imageclsId, loadImage(image_vfs)
					else
						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d ERROR NO IMAGE: SID=%s TID=%s shortname=%s", info.short_src, info.currentline,datastore_sid,datastore_tid,_shortname) )

						return nil
					end


				end

			   end

			end --end of function handleSports


			--==============================================================================
			--This function is used for handling all the money requests.
			--==============================================================================
			local function handleMoney(_moneyString)
			   local sid = 0

			   local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_moneyString,"(%a+)%s*")

			   local _subString = string.sub(_moneyString,_sizeStr+2,-1)

			   if string.lower(_key) == "stocks" then
				   _start,_sizeStr,sid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

			            if string.lower(sid) == "count" then --/money/stocks/count
					--Create money table before returning a count.
					createinterfacemoneytable()
					local cnt = 0
					for k,v in pairs(interfaceMoneyTable) do
					  cnt = cnt + 1
					end
					return _strclsId, tostring(cnt)
				   end

				   if _key == nil and sid ~= nil then
				   	--return datastore.money.stockdetails
				   elseif string.lower(_key) == "symbol" then
					if sid ~= "0" and sid ~= "1" and sid ~= "2" then --0,1,2 is for DOW,NASDAQ,Snp500
					 	return _strclsId, datastore.money.portfolio[interfaceMoneyTable[sid]].label
					else
					   local _sym = interfaceMoneyTable[sid]
					   return _strclsId, changeSymbol(_sym)
					end
				   elseif string.lower(_key) == "symbolfull" then
					if sid ~= "0" and sid ~= "1" and sid ~= "2" then --0,1,2 is for DOW,NASDAQ,Snp500
					   local _name = 
					   string.format("(%s: %s)",datastore.money.stockdetails[interfaceMoneyTable[sid]].index,
					   datastore.money.portfolio[interfaceMoneyTable[sid]].label);
					   return _strclsId, _name;
					else
					   local _sym = interfaceMoneyTable[sid]
					   return _strclsId, changeSymbol(_sym)
					end
				   elseif string.lower(_key) == "fullname" then
					if sid ~= "0" and sid ~= "1" and sid ~= "2" then --0,1,2 is for DOW,NASDAQ,Snp500
					   return _strclsId, datastore.money.stockdetails[interfaceMoneyTable[sid]].name
					end
				   elseif string.lower(_key) == "value" then
					if sid ~= "0" and sid ~= "1" and sid ~= "2" then --0,1,2 is for DOW,NASDAQ,Snp500
					   return _strclsId, datastore.money.portfolio[interfaceMoneyTable[sid]].value
					else
					   return _strclsId, datastore.money.markets[interfaceMoneyTable[sid]].value
				        end
				   elseif string.lower(_key) == "change" then
					if sid ~= "0" and sid ~= "1" and sid ~= "2" then --0,1,2 is for DOW,NASDAQ,Snp500
					   return _strclsId, datastore.money.portfolio[interfaceMoneyTable[sid]].change
					else
					   return _strclsId, datastore.money.markets[interfaceMoneyTable[sid]].change
				        end

				   elseif string.lower(_key) == "direction" then
					if sid ~= "0" and sid ~= "1" and sid ~= "2" then --0,1,2 is for DOW,NASDAQ,Snp500
					   return _strclsId, datastore.money.portfolio[interfaceMoneyTable[sid]].direction
					else
					   return _strclsId, datastore.money.markets[interfaceMoneyTable[sid]].direction
				        end

				   elseif string.lower(_key) == "details" then
					   local _realsid = interfaceMoneyTable[sid]
					  if datastore.money.stockdetails == nil or 
						  datastore.money.stockdetails[_realsid] == nil  then
						--fire a foreground request and set the status updating.
						interfaceHTTPStatusTable["foregroundrequestid"] = _realsid
						interfaceHTTPStatusTable["foregroundrequestType"] = "stockdetails"
					        interfacePresetEventsTable["last_request_table_key"] = _realsid;
						handleStartForeground(constructURL("stockdetails",_realsid))
						return nil
					  end
					  return _strclsId, datastore.money.stockdetails[_realsid].details

				   end
			elseif string.lower(_key) == "stockcount" then
				local cnt = 0
				for k,v in pairs(datastore.money.portfolio) do
				   cnt = cnt + 1
				end
				return _strclsId, cnt
			end

			end --end of function handleMoney

			--==============================================================================
			--This function is used for handling all the movies requests.
			--==============================================================================
			local function handleMovies(_moviesString)
			   local tid = 0

			   local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_moviesString,"(%a+)%s*")

			   local _subString = string.sub(_moviesString,_sizeStr+2,-1)

			   if string.lower(_key) == "newmovies" then
				   local newMovieList = ""
				   for k,v in pairs(datastore.movies.movielist) do
					 if datastore.movies.movielist[k].newMovieFlag == "1" then
					      if newMovieList == "" then
					   	  newMovieList = datastore.movies.movielist[k].name
					       else
					   	  newMovieList = newMovieList..", "..datastore.movies.movielist[k].name
					       end
					 end
			           end
				   return _strclsId, newMovieList
			   elseif string.lower(_key) == "theatres" then
				   _start,_sizeStr,tid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   if tid == "count" then  --/movies/theatres/count
					 local cnt = 0
					--This function creates a table for all the theatres.
					createinterfacetheatrestable()
					for k,v in pairs(interfacetheatresTable) do
						cnt = cnt + 1
					end
					return _strclsId, tostring(cnt)
				   end

				   if _key == nil and tid ~= nil then
				   elseif string.lower(_key) == "name" then
					 return _strclsId, datastore.movies.theatres[interfacetheatresTable[tid]].name
				   elseif string.lower(_key) == "city" then
					 return _strclsId, datastore.movies.theatres[interfacetheatresTable[tid]].city
				   elseif string.lower(_key) == "state" then
					 return _strclsId, datastore.movies.theatres[interfacetheatresTable[tid]].state
				   elseif string.lower(_key) == "citystate" then
					 if ((datastore.movies.theatres[interfacetheatresTable[tid]].city == nil or datastore.movies.theatres[interfacetheatresTable[tid]].city == "") and 
					     (datastore.movies.theatres[interfacetheatresTable[tid]].state == nil or datastore.movies.theatres[interfacetheatresTable[tid]].state == "")) then
						return _strclsId, "Location not available"
					 else
						return _strclsId, string.format("%s, %s",(datastore.movies.theatres[interfacetheatresTable[tid]].city or ""),
									(datastore.movies.theatres[interfacetheatresTable[tid]].state or ""))
					 end
				   elseif string.lower(_key) == "details" then
					 local _tid = interfacetheatresTable[tid]
					 return _strclsId, string.format("%s\n%s\n%s\n%s\n%s\n%s",
					 	"Theater Details",
					 	datastore.movies.theatres[_tid].name,
						datastore.movies.theatres[_tid].address,
						datastore.movies.theatres[_tid].city,
						datastore.movies.theatres[_tid].state..","..datastore.movies.theatres[_tid].zipcode,
						datastore.movies.theatres[_tid].phone)
				   end

			   elseif string.lower(_key) == "allshowing" then

				   local dayId = 0
				   local mid = 0
				   local iid = 0

				   --Get the preset theatre id from the memory
				   mid = getMovieId()

				   _start,_sizeStr,dayId = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,iid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   print("Interface:dayId:",dayId)
				   print("Interface:IID:",iid)
				   print("Interface:_key:",_key)
				   if string.lower(iid) == "count" then --/movies/allshowing/day/count
					 --first create a table for a list of movies on a preselected theatre
					 --for any specific day

					 createTheatreListForPresetMovie(getMovieId())
					 interfacePresetEventsTable["dayId"] = dayId
					 if interfaceTheatreListForPresetMovie == nil or 
					    interfaceTheatreListForPresetMovie[tonumber(dayId)+1] == nil then
					     return _strclsId, 0;
					 end
					 local cnt = 0
					 --table.sort(interfaceTheatreListForPresetMovie);
					 for k,v in pairs(interfaceTheatreListForPresetMovie[tonumber(dayId)+1]) do
						cnt = cnt + 1
					 end
					 return _strclsId, tostring(cnt)
				   end

				   if string.lower(_key) == "tid" then
					 local realtheatreid = 
					 interfaceTheatreListForPresetMovie[tonumber(dayId)+1][iid].tid
print("Interface:Real theatre id is:",realtheatreid)
					 for k,v in pairs(interfacetheatresTable) do
				            if realtheatreid == v then
						print("Interface:Returning 0 based id for theatre is:",k)
						return _strclsId, k
					    end
					 end
				   elseif string.lower(_key) == "active" then
					 local realtheatreid = 
					 interfaceTheatreListForPresetMovie[tonumber(dayId)+1][iid].tid
					 local _mid = getMovieId();
					 print("Interface:Real Theatre id for the active is :",realtheatreid)
					 print("Interface:Real Movie id for the active is :",_mid)
					interfacePresetEventsTable["timestamp"] = interfaceTheatreListForPresetMovie[tonumber(dayId)+1][iid].ts
				  	createinterfaceTheatreMovieTimeURLTable(getZeroBasedDay(addLocalTime(interfacePresetEventsTable["timestamp"])),realtheatreid,_mid)

					local _bool = "_false";
					for k,v in ipairs(interfaceTheatreMovieTimeURLTable) do
					  if interfaceTheatreMovieTimeURLTable[k].url ~= nil and
					     interfaceTheatreMovieTimeURLTable[k].url ~= "" then
					     _bool = "_true";
					  end
					end

				   	return _strclsId, _bool
				   elseif string.lower(_key) == "timesummary" then
					 return _strclsId, 
					    interfaceTheatreListForPresetMovie[tonumber(dayId)+1][iid].timeSummary
				   end

			   elseif string.lower(_key) == "allmovies" then
			   local mid = 0

				 _start,_sizeStr,mid = string.find(_subString,"(%w+)")
			   	 _subString = string.sub(_subString,_sizeStr+2,-1)

				 _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				 if string.lower(mid) == "count" then --/movies/allMovies/count
					 --This function creates a table of all movies
					 if interfaceAllMoviesTable == nil then
					     createinterfaceallmoviestable()
					 end

					 local cnt = 0
					 for k,v in pairs(interfaceAllMoviesTable) do
						cnt = cnt + 1
					 end
					 return _strclsId, tostring(cnt)
				  end

				  --First extract the real movieId from the 0 based 
				  --movie table of preset theatre .
				  if string.lower(_key) == "title" then
					return _strclsId, datastore.movies.movielist[interfaceAllMoviesTable[mid]].name
				   elseif string.lower(_key) == "rating" then
					if datastore.movies.movielist[interfaceAllMoviesTable[mid]].rating == nil or datastore.movies.movielist[interfaceAllMoviesTable[mid]].rating == "" then
						return _strclsId, "?"
					else
						return _strclsId, datastore.movies.movielist[interfaceAllMoviesTable[mid]].rating
					end
				   elseif string.lower(_key) == "genre" then
					if datastore.movies.movielist[interfaceAllMoviesTable[mid]].genre == nil or datastore.movies.movielist[interfaceAllMoviesTable[mid]].genre == "" then
						return _strclsId, "Genre not available"
					else
						return _strclsId, datastore.movies.movielist[interfaceAllMoviesTable[mid]].genre
					end
				   elseif string.lower(_key) == "details" then
					return _strclsId, datastore.movies.movielist[interfaceAllMoviesTable[mid]].details
				   end
			   elseif string.lower(_key) == "showing" then
				   local day = 0
				   local iid = 0

				   tid = getTheatreId()
				   mid = getMovieId()

				   if (interfaceConfigTable["updating"] ==  "_true") and (datastore.movies.movieshowsbytheatre == nil or datastore.movies.movieshowsbytheatre[tid] == nil) then
					print("Interface:Movies:Nothing from showing/xx because foreground request under progress.")
					return nil
				   end

				   _start,_sizeStr,day = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   _start,_sizeStr,iid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   if string.lower(iid) == "count" then --/movies/showing/day[0..n]/count

					--Create this table while setting a theatre because
					--this table will contain a list of movies in a theatre
					--on a per day basis
				        createinterfaceMovieListTablePresetTheatreTable(getTheatreId())

					local cnt = 0
					if interfaceMovieListForAPresetTheatre == nil or 
					   interfaceMovieListForAPresetTheatre[tonumber(day)+1] == nil then
					    return _strclsId, 0;
					end
					for k,v in pairs(interfaceMovieListForAPresetTheatre[tonumber(day)+1]) do
						cnt = cnt + 1
					end
					return _strclsId, tostring(cnt) -- end of debug if
				   end

				   if _key == nil and day ~= nil and iid ~= nil then
				   elseif string.lower(_key) == "timesummary" then
				   	return _strclsId, interfaceMovieListForAPresetTheatre[tonumber(day)+1][iid].timeSummary
				   elseif string.lower(_key) == "mid" then
				   	local realMovieId = interfaceMovieListForAPresetTheatre[tonumber(day)+1][iid].mid
					print("Interface:realMovieId here is :::",realMovieId)
					for k,v in pairs(interfaceAllMoviesTable) do
						if realMovieId == v then
						   print("Interface:realMovieId 0 based index is :::",k)
						   return _strclsId, k
						end
					end
				   elseif string.lower(_key) == "active" then

					_mid = interfaceMovieListForAPresetTheatre[tonumber(day)+1][iid].mid;

					print("Interface:Real movie id here for active is:",_mid)
					print("Interface:Theatre id here for active is:",tid)
					interfacePresetEventsTable["timestamp"] = interfaceMovieListForAPresetTheatre[tonumber(day)+1][iid].ts
				  	createinterfaceTheatreMovieTimeURLTable(getZeroBasedDay(addLocalTime(interfacePresetEventsTable["timestamp"])),tid,_mid)

					local _bool = "_false";
					for k,v in ipairs(interfaceTheatreMovieTimeURLTable) do
					  if interfaceTheatreMovieTimeURLTable[k].url ~= nil and
					     interfaceTheatreMovieTimeURLTable[k].url ~= "" then
					     _bool = "_true";
					  end
					end

				   	return _strclsId, _bool
				   end

			   elseif string.lower(_key) == "times" then
				   local day = 0
				   local _timeId = 0
				   local mid = 0
				   local tid = 0

				  --Get the preset theatre and movie Id 
				  tid = getTheatreId()
				  mid = getMovieId()

				  --check whether foreground request is in progress or not. If
				  --yes then dont pass this point.
				  if (interfaceConfigTable["updating"] ==  "_true") and (datastore.movies.movie_tickets_per_movie_and_theatre == nil or
                                      datastore.movies.movie_tickets_per_movie_and_theatre[mid] == nil or datastore.movies.movie_tickets_per_movie_and_theatre[mid][tid] == nil) then
					print("Interface:Foreground request is in progress for tickets table")
					return nil;
				  end

				   _start,_sizeStr,day = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")

				   _start,_sizeStr,_timeId = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")


				   --Movies URL table is created here for whatever day is asked,
				   --so we dont have to pass the day while returning the time because
				   --that table is for a particular day.
				   if string.lower(_timeId) == "count" then --/movies/times/day[0..n]/count
					createinterfaceTheatreMovieTimeURLTable(getZeroBasedDay(addLocalTime(interfacePresetEventsTable["timestamp"])),tid,mid)
					local cnt = 0
					for k,v in ipairs(interfaceTheatreMovieTimeURLTable) do
						cnt = cnt + 1
					end
					return _strclsId, tostring(cnt)
				   end

				   if _key == nil and day ~= nil and _timeId ~= nil then
				   elseif string.lower(_key) == "time" then
					 return _strclsId, interfaceTheatreMovieTimeURLTable[tonumber(_timeId)+1].time
				   elseif string.lower(_key) == "url" then
					 return _strclsId,  interfaceTheatreMovieTimeURLTable[tonumber(_timeId)+1].url
				   end

			   elseif string.lower(_key) == "count" then --/movies/count/theatres
				   local theat = ""
   				   _start,_sizeStr,theat = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)
				  local cnt = 0

				--This function creates a table for all the theatres.
					createinterfacetheatrestable()
					for k,v in pairs(interfacetheatresTable) do
						cnt = cnt + 1
					end
				return _strclsId, tostring(cnt)
			   elseif string.lower(_key) == "daytextmovies" then
				   local _dayid  = ""
				   _start,_sizeStr, _dayid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
				
				   if string.lower(_dayid) == "count" then --/daytextmovies/count
					local cnt = 0
					local _mid = getMovieId()
					for k,v in pairs(interfaceTheatreListForPresetMovie) do
						cnt = cnt + 1
					end
					print("Interface:DayText:Returning count for day:::",cnt);
					return _strclsId, cnt
				   elseif string.lower(_key) == "details" then
					   local _cnt = "0"
					   return _strclsId, interfaceTheatreListForPresetMovie[tonumber(_dayid)+1][_cnt].ts;
				   elseif string.lower(_key) == "dow" then
					   createTheatreListForPresetMovie(getMovieId())
					   local _cnt = "0"
					   print("Day Id is ::",_dayid)
					   local _ts = interfaceTheatreListForPresetMovie[tonumber(_dayid)+1][_cnt].ts;
					   return _strclsId, getDOW(tonumber(_ts),tonumber(tonumber(_dayid)),false)
				   end
			   elseif string.lower(_key) == "daytexttheatres" then
				   local _dayid  = ""
				   _start,_sizeStr, _dayid = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
				
				   if string.lower(_dayid) == "count" then --daytexttheatres/count
					local cnt = 0
					for k,v in pairs(interfaceMovieListForAPresetTheatre) do
						cnt = cnt + 1
					end
					print("Interface:DayText:Returning count for day:::",cnt);
					return _strclsId, cnt
				   elseif string.lower(_key) == "details" then
					   local _cnt = "0"
					   return _strclsId, interfaceMovieListForAPresetTheatre[tonumber(_dayid)+1][_cnt].ts;
				   elseif string.lower(_key) == "dow" then
					   createinterfaceMovieListTablePresetTheatreTable(getTheatreId())
					   local _cnt = "0"
					   local _ts = interfaceMovieListForAPresetTheatre[tonumber(_dayid)+1][_cnt].ts;
					   print("TS:",interfaceMovieListForAPresetTheatre[tonumber(_dayid)+1][_cnt].ts)
					   return _strclsId, getDOW(tonumber(_ts),tonumber(tonumber(_dayid)),false)
				   end

			   elseif string.lower(_key) == "chooserdetails" then

				   local theatredetails, moviedetails, retstr
				   local _tid = getTheatreId()
				   local _mid = getMovieId()

				   createinterfaceTheatreMovieTimeURLTable("noDayAvailable",_tid,_mid);

				   if interfaceConfigTable["requestfired"] ==  "_true" then
				      print("Interface:No chooser details. Foreground request is in progress.");
				      return nil ;
				   end
			   
				   if datastore.movies.theatres[_tid].address == "" and datastore.movies.theatres[_tid].city == "" and datastore.movies.theatres[_tid].state == "" and 
				      datastore.movies.theatres[_tid].zipcode == "" and datastore.movies.theatres[_tid].phone == "" then
					   theatredetails = string.format("Theater details\n%s\nnot available\n\n",
					 	(datastore.movies.theatres[_tid].name or ""))
				   else
					   theatredetails = string.format("Theater details\n%s\n%s\n%s, %s %s\nPhone: %s\n\n",
					 	(datastore.movies.theatres[_tid].name or ""),
						(datastore.movies.theatres[_tid].address or ""),
						(datastore.movies.theatres[_tid].city or ""),
						(datastore.movies.theatres[_tid].state or ""),
						(datastore.movies.theatres[_tid].zipcode or ""),
						(datastore.movies.theatres[_tid].phone or ""))
				   end

				   if datastore.movies.movie_tickets_per_movie_and_theatre[_mid].details == nil or datastore.movies.movie_tickets_per_movie_and_theatre[_mid].details == "" then
					   moviedetails = string.format("Movie details\n%s", "not available")
				   else
					   moviedetails = string.format("Movie details\n%s",
						datastore.movies.movie_tickets_per_movie_and_theatre[_mid].details)
				   end

				   retstr = string.format("%s%s", theatredetails, moviedetails)
				   return _strclsId, retstr

			   end
			end --end of function handleMovies

			--==============================================================================
			--This function is used for handling all the general requests.
			--==============================================================================
			local function handleStatus(_statusRequests)

			   local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_statusRequests,"(%a+)%s*")

			   local _subString = string.sub(_statusRequests,_sizeStr+2,-1)

		
			   if string.lower(_key) == "ondemand" then
				return _strclsId, interfaceConfigTable["isactive"]
			   elseif string.lower(_key) == "updating" then
				return _strclsId, interfaceConfigTable["updating"]
			   elseif string.lower(_key) == "channels" then
				local _channel = ""
				local _key1
			   	_start,_sizeStr,_channel = string.find(_subString,"(%a+)%s*")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

			   	_start,_sizeStr,_key1 = string.find(_subString,"(%a+)%s*")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

				if string.lower(_key1) == "time" then
			     local _offset, daylight = sys.get_localtimeoffset();
				   return _strclsId, datastore.get_last_update_time()+_offset
				elseif string.lower(_key1) == "code" then 
				   return _strclsId, interfaceConfigTable["upd"]
				end
			   elseif string.lower(_key) == "homescreen" then

			   	_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   	_subString = string.sub(_subString,_sizeStr+2,-1)

				if string.lower(_key) ==  "help" then
					    print("Returning help string as ...",interfaceConfigTable["help"])
					    return _strclsId, interfaceConfigTable["help"]

				elseif string.lower(_key) ==  "marketing" then
			   		_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   		_subString = string.sub(_subString,_sizeStr+2,-1)
					if string.lower(_key) == "image" then
					local _shortname = datastore.marketing.image
					return _imageclsId, loadImage(datastore.images[_shortname])
					elseif string.lower(_key) == "imagehighlight" then
					   --local _shortname = datastore.marketing.imagehighlight
					   --return _imageclsId, loadImage(datastore.images[_shortname])
					elseif string.lower(_key) == "url" then
					    return _strclsId, datastore.marketing.target
					elseif string.lower(_key) == "text" then
					    return _strclsId, datastore.marketing.text;
				   	end
				elseif string.lower(_key) ==  "ticker" then
				   local tickerId = ""
				   _start,_sizeStr,tickerId = string.find(_subString,"(%w+)")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

                                      if string.lower(tickerId) == "count" then
					 if datastore.marketing.ticker == nil or datastore.marketing.ticker == ""  then
                                            return _strclsId, "1"
                                         else
                                            return _strclsId, "2"
                                         end
                                      else
 			   	        _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   	        _subString = string.sub(_subString,_sizeStr+2,-1)

					if string.lower(_key) == "text" then
					   if datastore.marketing.ticker == nil or datastore.marketing.ticker == ""  then
			         	      return _strclsId, "Last updated: "..getFormattedLocalTime()
					   else
					      return _strclsId, "     Last updated: "..getFormattedLocalTime().." - "..datastore.marketing.ticker
					   end
					end
				      end
				end
			   elseif string.lower(_key) == "hotlined" then
				return interfaceConfigTable["hotlined"]
			   elseif string.lower(_key) == "updatestatus" then
			        return _strclsId, interfaceConfigTable["updatestatus"]
			   elseif string.lower(_key) == "expired" then
			     if datastore.getZipCode() and datastore.IsEmpty() then
			        return _strclsId, "_true"
			     else
			        return _strclsId, "_false"
			     end   
			   elseif string.lower(_key) == "upgradeurl" then
			        return _strclsId, datastore.ota.url
			   end

			end --end of function handleStatus

			--==============================================================================
			--This function will handle all the requests related to setEvent.
			--==============================================================================
			local function handleSetEvent(_eventTable)

				local catTable = nil
				local firsttime = 1
				local channeltable = nil 
				local _foreground = nil
				local _mode = nil

				local cnt = 1
				for k,v in pairs(_eventTable) do 
					print("Interface:Event Name:",k)
					print("Interface:Event Value:",v)
					if v == nil then break end

					if string.lower(k) == "cleardatastore" then    --Datastore clear event

						if string.find(v, "all", 1, true) then
					        	print("Interface:Clearing datastore on clearDatastore setEvent")
					        -- Clear the data store	
							datastore.removeContent(true)
							
							-- JSW Clear config data (OnDemand is now in first time run mode)
							createInterfaceConfigTable()
						end
					elseif string.lower(k) == "persistdatastore" then    --Datastore persist setEvents
						--Calling the datastore function to persist datastore.
						print("Interface:Persisting data store")
						datastore.persist()
					elseif string.lower(k) == "setcategory" then    --News setEvents
					   if catTable == nil then
						   catTable = {}
					   end
					   --If trig is setting for default category then use interfaceCatTable
					   --otherwise use non-default category table.
					   print("Interface:Adding default category to the table where cnt and v is ::",
					   cnt,interfaceCatTable[v])

					   if string.lower(v) ~= "sports" then
						 	catTable[cnt] = interfaceCatTable[v]
							interfacePresetEventsTable["category"] = catTable[cnt];
					   else
						 	catTable[cnt] = v
							interfacePresetEventsTable["category"] = v;
					   end

					   cnt = cnt+1
					   interfacePresetEventsTable["categorytype"] = "single"

					elseif string.lower(k) == "setmultiplecategory1" then 
						--News setMultipleCategory, v = Category Name
					   if catTable == nil then
						   catTable = {}
					   end
					   --If trig is setting for default category then use interfaceCatTable
					   --otherwise use non-default category table.
					   local info = debug.getinfo(1, "Sl")
					   cnt = 1
	    	           		   print(string.format("[%s]:%d Interface:Adding default category to the table where cnt[%s] and v[%s] ",
					   	info.short_src, info.currentline, cnt,v) )

					   if  v == "news" then
						   v = getDefaultCategoryId()
					   end
					   print("Interface:Category used for news is :",v)
					   catTable[cnt] = v -- v = Category Name
					   interfacePresetEventsTable["multiplecategory1"] = v
					   interfacePresetEventsTable["categorytype"] = "multiple"

					elseif string.lower(k) == "setmultiplecategory2" then 
						--News setMultipleCategory, v = Category Name
					
					   if catTable == nil then
						   catTable = {}
					   end
					   --If trig is setting for default category then use interfaceCatTable
					   --otherwise use non-default category table.
					   local info = debug.getinfo(1, "Sl")

					   cnt = 2
	    	           		   print ( string.format("[%s]:%d Interface:Adding default category to the table where cnt[%s] and v[%s] "
					   ,
					   	info.short_src, info.currentline, cnt,v) )

					   if  v == "news" then
						   v = getDefaultCategoryId()
					   end
					   catTable[cnt] = v -- v = Category Name
					   interfacePresetEventsTable["multiplecategory2"] = v
					   interfacePresetEventsTable["categorytype"] = "multiple"

					elseif string.lower(k) == "setchannel" then

					   if catTable == nil then
						   catTable = {}
					   end


						local info = debug.getinfo(1, "Sl")
						print ( string.format("[%s]:%d SetChannel[%s]", info.short_src, info.currentline,v) )

					   -- assumption: string.lower(v) == "sports" 
					   catTable[cnt] = string.lower(v)
					   interfacePresetEventsTable["category"] = string.lower(v);

					elseif string.lower(k) == "alertviewed" then -- Weather setEvents

					     --This is to avoid multiple alertviewed request from the trigplayer.
					     --This flag is reset whenever the trig ask for the unread alerts.
					     if interfacePresetEventsTable["alertviewed_requested"] == false then
						 interfacePresetEventsTable["alertviewed_requested"] = true;
					     else
						 return;
					     end

					     for k,v in pairs(datastore.weather.alerts) do
					       --check to see if the flag is true.
					       --Then check whether it was previously viewed or not.
					       --If viewed then mark then change then flag. If not
					       --viewed then add the flag as viewed.
					       if datastore.weather.alerts[k].flag == true then
print("AlertViewed value::",datastore.weather.alerts[k].alertviewed);
						  if datastore.weather.alerts[k].alertviewed == nil then
print("Interface:Marking alert number:"..k.." as viewed alert");
							datastore.weather.alerts[k].alertviewed = "viewed"
						  else
print("Interface:Resetting the flag for alert number:"..k.." because it was previously viewed");
							datastore.weather.alerts[k].flag = false
						  end
						  interfacePersistDataStore()	
					       end
					     end
					     interfacePresetEventsTable["previouscidagainstalert"] = nil
					     createinterfacealertstable();
					elseif string.lower(k) == "setcity" then
						print("Interface:Setting city for alerts:",interfacecitiesTable[v])
						interfacePresetEventsTable["city"] = interfacecitiesTable[v]
						createInterfaceAlertsTableByCid(interfacecitiesTable[v]);
						createInterface7DaySummaryTable(interfacecitiesTable[v]);
					elseif string.lower(k) == "setsport" then -- Sports setEvents

                                               setSporthandler( v )

					elseif string.lower(k) == "setteam" then
					elseif string.lower(k) == "settable" then
					elseif string.lower(k) == "settheatre" then -- movie setEvents
						interfacePresetEventsTable["theatre"] = interfacetheatresTable[v]
						print("Interface:Setting theatre....id....",interfacePresetEventsTable["theatre"])
						print("Interface:Preset theatreId:",getTheatreId())
					elseif string.lower(k) == "setmovie" then
						print("Interface:Set movie eventwith mid::",interfaceAllMoviesTable[v])
						interfacePresetEventsTable["movie"] = interfaceAllMoviesTable[v]

					elseif string.lower(k) == "movieid" then
						interfacePresetEventsTable["movie"] = interfaceAllMoviesTable[v]
						local realmovieId = interfacePresetEventsTable["movie"]
						print("Interface:Creating theatre list table for a movieId:",realmovieId)
						createinterfacetheatrelisttable(realmovieId)
					--*********************************************************************
					--There is no real need of purchase movie and ticket quantity event to 
					--the data store as this will be used by the TML to launch browser
					--*********************************************************************
					elseif string.lower(k) == "purchasemovie" then  
						interfacePresetEvenetsTable["purchasemovie"] = v
					elseif string.lower(k) == "ticketquantity" then
						interfacePresetEvenetsTable["ticketquantity"] = v
					elseif string.lower(k) == "updatechannel" then --generic Setevents
						print("Interface:UPDATE CHANNEL EVENT and value of v",v)

						if string.lower(v) == "all" then
							interfacePresetEventsTable["categorytype"] = ""
						end
						--If there is no channel specified then return right away.

						if string.lower(v) ~= "none" then
						    if string.lower(v) == "help" then
							 interfaceConfigTable["help"] =  ""
							 print("Interface:Firing foreground request for help")
							 handleStartForeground(constructURL("help","help"))
							 return
						    elseif string.find(v, "stock/detail/", 1, true) then
							 local sid = string.sub(v, string.len("stock/detail/") + 1)
							 print("Interface:Firing foreground request for stock details", interfaceMoneyTable[sid])
					        	 interfacePresetEventsTable["last_request_table_key"] = interfaceMoneyTable[sid];
							 handleStartForeground(constructURL("stockdetails",interfaceMoneyTable[sid]))
							 return
						    elseif string.find(v, "movies/theatre/", 1, true) then
							-- ignore passed in theater id as it is already set
							 local tid = getTheatreId() 
							 print("Interface:Firing foreground request for movie theatres", tid)
							 interfacePresetEventsTable["last_request_table_key"] = tid
							 handleStartForeground(constructURL("moviestheatre" ,tid))
							 return
						    elseif string.find(v, "movies/movie/", 1, true) then
							local _start,_sizeStr,_mid
							--Now check whether this is only for movie or for a ticket table.
							local _substr = string.sub(v, string.len("movies/movie") + 1)
							_start,_sizeStr,_mid = string.find(_substr,"(%w+)")
			   				local _substr = string.sub(_substr,_sizeStr+2,-1)
							local _realmid = interfaceAllMoviesTable[_mid];

							if string.find(_substr,"theatre",1,true) then
								_start,_sizeStr,_tid = string.find(_substr,"(%w+)")
								local _URLParams = {}
								_URLParams[1] = _realmid
								_URLParams[2] = getTheatreId()
								_URLParams[3] = getDayId() 
							 	print("Interface:Firing foreground request for movie and theater", _URLParams[1], _URLParams[2], _URLParams[3])
					      			interfacePresetEventsTable["last_request_table_key"] = _URLParams
							 	handleStartForeground(constructURL("movieurl", _URLParams))
							 	return
							else
								-- no theatre available 
							 	print("Interface:Firing foreground request for movie movies", _realmid)
					        		interfacePresetEventsTable["last_request_table_key"] = _realmid
							 	handleStartForeground(constructURL("moviesmovie", _realmid))
							 	return
							end
						    elseif string.find(v, "weather/week/", 1, true) then
							local _start,_sizeStr,_loc_id
							local _substr = string.sub(v, string.len("weather/week")+ 1 )
							_start,_sizeStr,loc = string.find(_substr,"(%w+)")
							local _loc_id = interfacecitiesTable[loc];
							print("Interface:Loc id is :",_loc_id)
							if string.find(_substr,"day",1,true) then
			   					_substr = string.sub(_substr,_sizeStr+2,-1)
								local _day,_dayid
			   					_substr = string.sub(_substr,_sizeStr+2,-1)
								_start,_sizeStr,_day = string.find(_substr,"(%w+)")

								--check to see if there is an alert for the city
								--then decrement day
								local count = 0;
								for k,v in pairs(datastore.weather.locations[_loc_id].alerts) do
									count = count + 1
								end
								if count > 0 then
									_day = decrementday(_day)
								end

								local urlformat = string.format("id=%s&day=%s",_loc_id, datastore.weather.summary[_loc_id][weatherTSMapping[_day]].id)
								print("Interface:Firing foreground request for weather details", _loc_id, datastore.weather.summary[_loc_id][weatherTSMapping[_day]].id)
					      			interfacePresetEventsTable["last_request_table_key"]  = _loc_id
								interfaceHTTPStatusTable["weatherday"] = _day
								interfaceHTTPStatusTable["cid"] = _loc_id
							 	handleStartForeground(constructURL("weatherdetails", urlformat))
							 	return
							else
								--no day available this is for 7 day
							 	print("Interface:Firing foreground request for 7 day summary", _loc_id)
					      			interfacePresetEventsTable["last_request_table_key"]  = _loc_id
							 	handleStartForeground(constructURL("weatherweek", _loc_id))
							 	return
							end
						    elseif string.lower(v) == "sportstypes" then
							 print("Interface:Firing foreground request for sports types")
							 interfacePresetEventsTable["last_request_table"] = datastore.sports.types
							 interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
							 interfacePresetEventsTable["last_request_table_msg_string"] = "datastore.sports.types"

							 handleStartForeground(constructURL("sports","/"))
							 return
						    elseif string.find(v, "sports/scores/", 1, true) then
							local sid = string.sub(v, string.len("sports/scores/") + 1)
							local datastore_sid = interfaceSportsAllSportsTable[tostring(sid)]
		
							print("Interface:Firing foreground request for sports scores", datastore_sid)
							interfacePresetEventsTable["last_request_table"] = datastore.sports.scores[datastore_sid]
							interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.scores[%s]",datastore_sid)

							handleStartForeground(constructURL("sportsscores", datastore_sid))
							return
						    elseif string.find(v, "sports/teams/", 1, true) then
							local sid = string.sub(v, string.len("sports/teams/") + 1)
							local datastore_sid = interfaceSportsAllSportsTable[tostring(sid)]
		
							print("Interface:Firing foreground request for sports teams", datastore_sid)
							interfacePresetEventsTable["last_request_table"] = datastore.sports.teams[datastore_sid]
							interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.teams[%s]",datastore_sid)

							handleStartForeground(constructURL("sportsteams", datastore_sid))
							return
						    elseif string.find(v, "sports/standings/", 1, true) then
							local sid = string.sub(v, string.len("sports/standings/") + 1)
							local datastore_sid = interfaceSportsAllSportsTable[tostring(sid)]
		
							print("Interface:Firing foreground request for sports standings", datastore_sid)
							interfacePresetEventsTable["last_request_table"] = datastore.sports.standings[datastore_sid]
							interfacePresetEventsTable["last_request_table_key"] = "__count__table__"
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.standings[%s]",datastore_sid)

							handleStartForeground(constructURL("sportsstandings", datastore_sid))
							return
						    elseif string.find(v, "sports/schedules/", 1, true) then
							local tid = string.sub(v, string.len("sports/schedules/") + 1)
							local datastore_tid = interfaceSports_Team_Table[tostring(tid)]
		
							print("Interface:Firing foreground request for sports schedules", datastore_tid)
							interfacePresetEventsTable["last_request_table"] = datastore.sports.schedules
							interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_tid)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.schedules[%s]",datastore_tid)

							handleStartForeground(constructURL("sportsschedules",datastore_tid))
							return
						    elseif string.find(v, "sports/games/", 1, true) then
							local gid = string.sub(v, string.len("sports/games/") + 1)
							local datastore_gid = interfaceSportsGamesTable[tostring(gid)]

							print("Interface:Firing foreground request for sports games", datastore_gid)
							interfacePresetEventsTable["last_request_table"] = datastore.sports.games
							interfacePresetEventsTable["last_request_table_key"] = string.format("%s",datastore_gid)
							interfacePresetEventsTable["last_request_table_msg_string"] = string.format("datastore.sports.types[%s]",datastore_gid)

							handleStartForeground(constructURL("sportsgames",datastore_gid))
							return
					            end

						    if channeltable == nil then
						    	channeltable = {}
					            end
						    
						    channeltable[cnt] = v
						    --If its an foreground update channel event then set the 
						    --_foreground flag to 1.
						    _foreground = 1
						else
							return
						end
					elseif string.lower(k) == "updatechannelbackground" then --generic Setevents
						print("Interface:BACKGROUND UPDATE CHANNEL EVENT and value of v",v)

						if channeltable == nil then
						    channeltable = {}
					        end
						channeltable[cnt] = v
					elseif string.lower(k) == "mode" then
						if v == "automatic" then
						    _mode = 2
						else
						    _mode = 1
					        end
					elseif string.lower(k) == "setzipcode" then
					          -- set updating zip code to true
					          print("Interface:: I got setEvent() for zipcode, making FG request")
						  interfacezipcode = v
						  handleStartForeground(constructURL("getzipcode","register"))
					elseif string.lower(k) == "cancelupdate" then
					 
					   if interfaceHTTPStatusTable["url"] ~= "" then
					     print("Interface:Cancelling foreground request")
					     fetch_cancel_request(interfaceHTTPStatusTable["url"])
					     --once the cancel is done, update the status code.
					     interfaceConfigTable["updating"] =  "_false"
			        	     interfaceConfigTable["requestfired"] =  "_false"
					     interfaceHTTPStatusTable["url"] = ""
					     interfaceHTTPStatusTable["weatherday"] = ""
					     interfaceHTTPStatusTable["cid"] = ""
			        	     interfaceHTTPStatusTable["foregroundrequestid"] = "" 
			        	     interfaceHTTPStatusTable["foregroundrequestType"] = ""
			        	     interfaceHTTPStatusTable["eventName"] = ""
					   end
					elseif string.lower(k) == "setversionmiuibase" then
						print("Interface:Setting MIUI Base trig version",v);
						datastore.set_miui_base(v);
					elseif string.lower(k) == "setversionmiuitrig" then
						print("Interface:Setting MIUI Trig version",v);
						datastore.set_miui_triglet(v);
					elseif string.lower(k) == "setversionondemandtrig" then
						print("Interface:Setting MIUI onDemand Trig version")
						datastore.set_ondemand_triglet(v);
					end
				end

				if channeltable ~= nil then
				    if _foreground == 1 then
				    handleStartForeground(constructURL("channels",channeltable))
				    else
					handleStartBackground(constructURL("channels",channeltable), _mode)
				    end
				    channeltable = nil
				    _foreground = nil -- Reset the foreground flag.
				end
			--if there is any setCategory then reconstruct the news story table for the specified 
			--categories.

				if catTable ~= nil then
			    		createNewsIDsTable(catTable)

					if interfacePresetEventsTable["categorytype"] == "single" then
						if interfaceCatTable and (interfaceCatTable[_eventTable["setCategory"]] == getDefaultCategoryId()) then
							local cnt = 0

							for k,v in pairs(interfaceStoryTable) do
								cnt = cnt+1
							end
							interfacePresetEventsTable["defaultcategorycount"] = tostring(cnt)
						end
					end

			    		cattable = nil
				end
			end




			--==============================================================================
			--This function handles the zipCode request event from the 
			--TML and sends a register request to fetch along with the 
			--callback function for updating the status of the fetch.
			--==============================================================================
			local function handleVerifyEvent(_verifyTable)

				for k,v in pairs(_verifyTable) do 
					if string.lower(k) == "zipcode" then
					    if interfaceConfigTable == nil then  -- Check if this is the first time then
					       interfaceConfigTable["zipcode"] = v -- create the interfaceConfigtable.
					    end
					end
				end
		        end


			--==============================================================================
			--This function will handle the zipCode and status requests.
			--==============================================================================
			local function handleConfig(_configRequests)
			   local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_configRequests,"(%a+)%s*")

			   local _subString = string.sub(_configRequests,_sizeStr+2,-1)

			   if string.lower(_key) == "zipcode" then
				   _start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   	   _subString = string.sub(_subString,_sizeStr+2,-1)

				   if string.lower(_key) == "value" then
					   local zipcode = datastore.getZipCode()
					   if not zipcode then
						print("No zipcode found in data store")
						return _strclsId, ""
					   else
						print("Zipcode " .. zipcode .. " found in datastore")
						return _strclsId, zipcode
					   end	

				   elseif string.lower(_key) == "status" then
					return _strclsId, interfaceConfigTable["zipcodestatus"]
				   end
			   end
			end --end of handleConfig function


			--==============================================================================
			--This function will handle all the read/write nodes from trig.
			--==============================================================================
			local function handleSetdataEvent(_setdataTable)
				--/config/zipcode/status
				--/status/updating 
				--/status/hotlined 
				--/status/onDemand/isActive 
				--/status/autoUpdateEnable
				local _start,_sizeStr,_key

				for k,v in pairs(_setdataTable) do 
					print("Interface:Setdata event name:",k)
					print("Interface:Setdata event value:",v)
					if v == nil then break end

			   		local _start,_sizeStr,_key
			   		_start,_sizeStr,_key = string.find(k ,"(%a+)%s*")

			   		local _subString = string.sub(k,_sizeStr+2,-1)

			   		if string.lower(_key) == "config" then
				   		_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   	   		_subString = string.sub(_subString,_sizeStr+2,-1)

				   		if string.lower(_key) == "zipcode" then
				   			_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   	   			_subString = string.sub(_subString,_sizeStr+2,-1)

				   			if string.lower(_key) == "status" then
								interfaceConfigTable["zipcodestatus"] =  v
							end
						end
			   		elseif string.lower(_key) == "status" then
				   		_start,_sizeStr,_key = string.find(_subString,"(%a+)%s*")
			   	   		_subString = string.sub(_subString,_sizeStr+2,-1)

				   		if string.lower(_key) == "autoupdateenable" then
						   if v == 0 then
							interfaceConfigTable["autoupdateenable"] =  "_false"
							print("Interface:Sending false to fetch for automatic enable");
							fetch_automatic_enable(false);
						   elseif v == 1 then
							interfaceConfigTable["autoupdateenable"] =  "_true"
							print("Interface:Sending true to fetch for automatic enable");
							fetch_automatic_enable(true);
						   end
						elseif string.lower(_key) == "updating" then
						  if v == 0 then
						   interfaceConfigTable["updating"] =  "_false"
						  elseif v == 1 then
						   interfaceConfigTable["updating"] =  "_true"
						  end
						elseif string.lower(_key) == "hotlined" then
						  if v == 0 then
							interfaceConfigTable["hotlined"] =  "_false"
						  elseif v == 1 then
							interfaceConfigTable["hotlined"] =  "_true"
						  end
						elseif string.lower(_key) == "ondemand" then
						   if v == 1 then
							if interfaceConfigTable["isactive"] ==  "_false" then
							  --Inform fetch that now user is out of ondemand.
							print("Sending true to fetch because OnDemand is active.")
							  fetch_ui_active(true)
							end
							interfaceConfigTable["isactive"] =  "_true"
						   elseif v == 0  then
							if interfaceConfigTable["isactive"] ==  "_true" then
							  --Inform fetch that now user is out of ondemand.
							print("Sending false to fetch because OnDemand is not active.")
							  fetch_ui_active(false)
							end
							interfaceConfigTable["isactive"] =  "_false"
						   end
						end
					end
				end

			end

			--==============================================================================
			--This function will read the path for datastore image table and
			--call the limage to load the pointers. On receiving the pointers it
			--store the value in the image table using storeImage function.
			--==============================================================================
			local function readAndLoadImages()
			end

			--==============================================================================
			--This function will handle all the foreground requests to fetch
			--==============================================================================
			function handleStartForeground(url)

          		    local GET = 1
                            local _foreground = 1 

			    if interfaceConfigTable["hotlined"] == "_true" then
				    print("All Foreground requests are blocked because user is restricted by UI")
			    end
			    --set the updating flag to true, so that if TML checks for this flag they will
			    --know that the foreground request is still pending.

			    print("Interface:Request fired value::", interfaceConfigTable["requestfired"])
			    if interfaceConfigTable["requestfired"] ==  "_false" then
				local _err

			        interfaceConfigTable["requestfired"] =  "_true"

				--Informing actor about the request fired, so that trig can display the 
				--updating screen.
				local _dataActorPtr = interfaceHTTPStatusTable["dataActorPtr"]
				interfaceHTTPStatusTable["url"] = url
				if interfaceHTTPStatusTable["foregroundrequestType"] == "getzipcode" then
			       	   interfaceConfigTable["updating"] =  "_false"
			        end

				if interfaceHTTPStatusTable["foregroundrequestType"] ~= "getzipcode" then
				   print("Interface:CHANGING UPDATING TO TRUE::::")
			           interfaceConfigTable["updating"] =  "_true"
          		           _err = fetch_send_request(url, GET, _foreground, callbackFnForegroundStatusUpdate)
				else
			       	   interfaceConfigTable["updating"] =  "_false"
          		           _err = fetch_register(url, interfacezipcode, callbackFnForegroundStatusUpdate)
			       end
			       bucket.CallBck(_dataActorPtr,"foregroundrequestfired","","")
			       return _err
			    else
				print("Interface:FOREGROUND REQUEST NOT FIRED BECAUSE OF DUPLICATE URL:",url)
                            end
                        end

			--==============================================================================
			--This function will handle all the background requests to fetch
			--==============================================================================
			function handleStartBackground(url, mode)

          		    local GET = 1
		
			    local _dataActorPtr = interfaceHTTPStatusTable["dataActorPtr"]
			    interfaceHTTPStatusTable["url"] = url
			    --bucket.CallBck(_dataActorPtr,"backgroundrequestfired","","")
print("Firing background request with URL and mode : ", url, mode);
          		    return fetch_send_request(url, GET, mode, callbackFnBackgroundStausUpdate)
		       end
		

		--==============================================================================
			--This function is used to parse all the request from the actor.
			--==============================================================================
			local function parseRequest(_string)

			   print("Interface:Request:".._string)
			   if _string == nil then
			 	return nil
			   end

			   local _start,_sizeStr,_key
			   _start,_sizeStr,_key = string.find(_string,"(%a+)%s*")

			   local _subString = string.sub(_string,_sizeStr+2,-1)

			    if string.lower(_key) == "config" then
			    	return handleConfig(_subString)
			    elseif string.lower(_key) == "news" then
			    	return handleNews(_subString)
			    elseif string.lower(_key) == "sports" then
			    	return handleSports(_subString)
			    elseif string.lower(_key) == "weather" then
			    	return handleWeather(_subString)
			    elseif string.lower(_key) == "money" then
			    	return handleMoney(_subString)
			    elseif string.lower(_key) == "movies" then
			    	return handleMovies(_subString)
			    elseif string.lower(_key) == "status" then
				return handleStatus(_subString)
			    else
			    end

			end


			--==============================================================================
			--This function is called by the dataActor for every request and setEvent calls
			--to the interface layer.
			--This is a generic interface function between dataActor and interface layer.
			--==============================================================================
		        function _handleEvent(event, params)

				if string.lower(event) == "getdata" then
					local clsId, retvalue = parseRequest(params.path)
					if clsId == _strclsId then
						if retvalue  then
						print("Interface:String Return value is:"..retvalue)
						else
                            print("Interface:String Return value is: NIL")
						end
					end

					if retvalue ~= nil then
						return retvalue, clsId, 0
					else
						return nil, clsId, 2
					end
				elseif string.lower(event) == "setevent" then
				    handleSetEvent(params)
				elseif string.lower(event) == "verify" then
				    handleVerifyEvent(params)
				elseif string.lower(event) == "setdata" then
				    handleSetdataEvent(params)
			 	end

			end


			--==============================================================================
			--DataActor will call this function for registering the callback function pointer.
			--==============================================================================
			function registerActorCallbackFunction(dataPtr) 

			        --In interface most of the tables are created and initialized on demand
				--basis except the one for preset events.
				createGenericTableForCallbacks()

				interfaceHTTPStatusTable["dataActorPtr"] = dataPtr


			end
			--==============================================================================
			--This function is used for interface initialization
			--==============================================================================
			function interfaceInit()

				--Register the call back function with dataStore
				--for callbacks, so that dataStore can inform interface
				--whenever its updated because of any foreground request
				--or a regular update.
				print("Interface:DATA STORE REGISTER CALLBACK")
				datastore.registerInterfaceCallback(callbackFnDataStoreUpdate)

				--Interface config table
				createInterfaceConfigTable()

				-- Money table
				createinterfacemoneytable()

				--Alerts table reconstruction
				createinterfacealertstable()

				--Cities table
				createinterfacecitiestable()

				--Preset events table.
				createInterfacePresetEventsTable()

				--Category table
    				createinterfacecattable()

				--Create a new story table after receiving the categories.
				local catTable = {}
				if interfacePresetEventsTable["category"] ~= "" then
					catTable[1] = interfacePresetEventsTable["category"]
				else
					catTable[1] = getDefaultCategoryId()
				end
				interfacePresetEventsTable["categorytype"] = "single"
				createNewsIDsTable(catTable)

				--AllMovies table
    				createinterfaceallmoviestable()

				--DOW table
				createNameToDOWMapping()

			end

			--==============================================================================
			--This function is called by the dataActor for every request and setEvent calls
			--to the interface layer.
			--This is a generic interface function between dataActor and interface layer.
			--==============================================================================
            		function handleEvent(event, params)

				local pcall_err, retvalue_1, retvalue_2, retvalue_3 = pcall( _handleEvent, event, params )

			    if ( pcall_err ) then
                    			if string.lower(event) == "getdata" then
						return  retvalue_1, retvalue_2, retvalue_3
					elseif string.lower(event) == "setevent" then
				    		handleSetEvent(params)
					elseif string.lower(event) == "verify" then
				    		handleVerifyEvent(params)
					elseif string.lower(event) == "setdata" then
				    		handleSetdataEvent(params)
					end
			    else
					print ( string.format("ERROR handleEvent(getdata) : %s", retvalue_1) )

				    	if string.lower(event) == "getdata" then
						return nil, _strclsId, 2
					end

			    end

            end


	--]]

