]> code.delx.au - comingnext/blobdiff - comingNext/index.html
added enableLogging setting, made logging optional (might improve speed)
[comingnext] / comingNext / index.html
index 4af8b92430c68a6f5523491291b4406aa5bea57c..2dd85d774b2fcfc8b6515d92378694cd1f36200d 100644 (file)
 .description { }\r
 .icon { }\r
 .overdue {}\r
+.calendar1 {}\r
+.calendar2 {}\r
+.calendar3 {}\r
+.calendar4 {}\r
+.calendar5 {}\r
+.calendar6 {}\r
 </style>\r
 \r
 <script type="text/javascript" src="localizedTextStrings.js" charset="utf-8" />\r
 \r
 <script>\r
-// valid types for the config object are 'Int', 'Bool', 'String', 'Enum', 'UID'\r
+// valid types for the config object are 'Int', 'Bool', 'String', 'Enum', 'UID', 'Array'\r
 var config = {\r
        monthRange: { Type: 'Int', Default: 2, Value: 2,},\r
        includeTodos: { Type: 'Bool', Default: true, Value: true,},\r
@@ -47,7 +53,11 @@ var config = {
        showNothingText: { Type: 'Bool', Default: true, Value: true,},\r
        nothingText: { Type: 'String', Default: getLocalizedText('settings.default.nothingText'), Value: getLocalizedText('settings.default.nothingText'),},\r
        enableDaylightSaving: { Type: 'Bool', Default: true, Value: true,},\r
+       daylightSavingOffset: { Type: 'Int', Default: 1, Value: 1,},\r
        hideWidgetOnCalendarOpen: { Type: 'Bool', Default: false, Value: false,},\r
+       showCalendarIndicator: { Type: 'Bool', Default: true, Value: true,},\r
+       excludedCalendars: { Type: 'Array', Default: [], Value: [],},\r
+       enableLogging: { Type: 'Bool', Default: false, Value: false,},
        cssStyle_background: { Type: 'String', Default: 'color:#ffffff; background-color:#000000', Value: 'color:#ffffff; background-color:#000000',},\r
        cssStyle_backgroundFullscreen: { Type: 'String', Default: 'color:#ffffff; background-color:#000000', Value: 'color:#ffffff; background-color:#000000',},\r
        cssStyle_weekDay: { Type: 'String', Default: '', Value: '',},\r
@@ -59,6 +69,12 @@ var config = {
        cssStyle_description: { Type: 'String', Default: '', Value: '',},\r
        cssStyle_icon: { Type: 'String', Default: 'width:15px; height:15px', Value: 'width:15px; height:15px',},\r
        cssStyle_overdue: { Type: 'String', Default: 'color:#ffff00', Value: 'color:#ffff00',},\r
+       cssStyle_calendar1: { Type: 'String', Default: 'background-color:#0757cf', Value: 'background-color:#0757cf',},\r
+       cssStyle_calendar2: { Type: 'String', Default: 'background-color:#579f37', Value: 'background-color:#579f37',},\r
+       cssStyle_calendar3: { Type: 'String', Default: 'background-color:#ff9f07', Value: 'background-color:#ff9f07',},\r
+       cssStyle_calendar4: { Type: 'String', Default: 'background-color:#af8fef', Value: 'background-color:#af8fef',},\r
+       cssStyle_calendar5: { Type: 'String', Default: 'background-color:#57afbf', Value: 'background-color:#57afbf',},\r
+       cssStyle_calendar6: { Type: 'String', Default: 'background-color:#9fdf57', Value: 'background-color:#9fdf57',},\r
 }\r
 \r
 \r
@@ -67,7 +83,7 @@ var config = {
 // Nothing of interest from here on...\r
 //-------------------------------------------------------\r
 var panelNum = 0; // use 1 for second panel\r
-var version = "1.28";\r
+var version = "1.31";\r
 var versionURL = "http://comingnext.sourceforge.net/version.xml";\r
 var calendarService = null;\r
 var cacheEntriesHtml = [];\r
@@ -78,13 +94,31 @@ var mode = 0; // 0 = homescreen, 1 = fullscreen, 2 = settings, 3 = about, 4 = ch
 var reqV = null; \r
 var settingsCalEntryId = null;\r
 var settingsCache = null;\r
-var notificationRequest1;\r
-var notificationRequest2;\r
+var notificationRequests = new Array();\r
+var calendarList = [];\r
+var calendarColors = [];\r
+var updateTimer = null;\r
+var screenRotationTimer = null;\r
+var lastUpdateTime = now;\r
+var errorOccured = false;\r
 \r
 // vars for daylight saving time\r
-var daylightsavingWinter = 0;\r
-var daylightsavingSummer = 0;\r
-var summertime = false;\r
+var summertime = false; // true, if current date is in summer, false if in winter\r
+var daylightSavingDates = new Object(); // caches calculated DST winter and summer time shift dates\r
+\r
+// this is a list of data fields a calendar event can have\r
+var entryFields = [\r
+       "id",\r
+       "Type",\r
+       "CalendarName",\r
+       "Summary",\r
+       "Location",\r
+       "Status",\r
+       "StartTime",\r
+       "EndTime",\r
+       "InstanceStartTime",\r
+       "InstanceEndTime"\r
+];\r
 \r
 window.onload = init;\r
 window.onresize = updateScreen;\r
@@ -113,49 +147,57 @@ function subToSunday(myDate, year, days, prevMonthDays)
        days = isLeapYear(year) ? --days : days;\r
        return days;\r
 }\r
-       \r
-function calcDaylightSaving()\r
+\r
+function isSummertime(curDate)\r
 {\r
-       var thisYearS = new Date(now.getFullYear(),  3, 0, 0, 0, 0 );\r
-       var thisYearW = new Date(now.getFullYear(), 10, 0, 0, 0, 0 );\r
-       var nextYearS = new Date(now.getFullYear() + 1,  3, 0, 0, 0, 0 );\r
-       var nextYearW = new Date(now.getFullYear() + 1, 10, 0, 0, 0, 0 );\r
        var summer = false;\r
        var winter = false;\r
-       \r
-       thisYearSDays = nextYearSDays = 90;\r
-       thisYearWDays = nextYearWDays = 304;\r
-       \r
-       thisYearSDays = calcLeapYear(now.getFullYear(), thisYearSDays);\r
-       thisYearWDays = calcLeapYear(now.getFullYear(), thisYearWDays);\r
-       nextYearSDays = calcLeapYear(now.getFullYear() + 1, nextYearSDays);\r
-       nextYearWDays = calcLeapYear(now.getFullYear() + 1, nextYearWDays);\r
-       \r
-       thisYearSDays = subToSunday(thisYearS, now.getFullYear(), thisYearSDays, 59);\r
-       thisYearWDays = subToSunday(thisYearW, now.getFullYear(), thisYearWDays, 273);\r
-       nextYearSDays = subToSunday(nextYearS, now.getFullYear() + 1, nextYearSDays, 59);\r
-       nextYearWDays = subToSunday(nextYearW, now.getFullYear() + 1, nextYearWDays, 273);\r
-       \r
-       daylightsavingSummer = new Date (now.getFullYear(), 03-1, thisYearSDays, 2, 0, 0);\r
-       daylightsavingWinter = new Date (now.getFullYear(), 10-1, thisYearWDays, 2, 0, 0);\r
-       if (daylightsavingSummer < now) {\r
-               daylightsavingSummer = new Date (now.getFullYear()+1, 03-1, nextYearSDays, 2, 0, 0);\r
-               var summer = true;\r
-       }\r
-       if (daylightsavingWinter < now) {\r
-               daylightsavingWinter = new Date (now.getFullYear()+1, 10-1, nextYearWDays, 2, 0, 0);\r
-               var winter = true;\r
+\r
+       // if we already calculated DST summer and winter time dates for this year, use cached values\r
+       var dst = daylightSavingDates[curDate.getFullYear()];\r
+       if (!dst) {\r
+               var thisYearS = new Date(curDate.getFullYear(),  3, 0, 0, 0, 0 );\r
+               var thisYearW = new Date(curDate.getFullYear(), 10, 0, 0, 0, 0 );\r
+               var nextYearS = new Date(curDate.getFullYear() + 1,  3, 0, 0, 0, 0 );\r
+               var nextYearW = new Date(curDate.getFullYear() + 1, 10, 0, 0, 0, 0 );\r
+               \r
+               thisYearSDays = nextYearSDays = 90;\r
+               thisYearWDays = nextYearWDays = 304;\r
+               \r
+               thisYearSDays = calcLeapYear(curDate.getFullYear(), thisYearSDays);\r
+               thisYearWDays = calcLeapYear(curDate.getFullYear(), thisYearWDays);\r
+               nextYearSDays = calcLeapYear(curDate.getFullYear() + 1, nextYearSDays);\r
+               nextYearWDays = calcLeapYear(curDate.getFullYear() + 1, nextYearWDays);\r
+               \r
+               thisYearSDays = subToSunday(thisYearS, curDate.getFullYear(), thisYearSDays, 59);\r
+               thisYearWDays = subToSunday(thisYearW, curDate.getFullYear(), thisYearWDays, 273);\r
+               nextYearSDays = subToSunday(nextYearS, curDate.getFullYear() + 1, nextYearSDays, 59);\r
+               nextYearWDays = subToSunday(nextYearW, curDate.getFullYear() + 1, nextYearWDays, 273);\r
+               \r
+               dst = {\r
+                       Summer: new Date (curDate.getFullYear(), 03-1, thisYearSDays, 2, 0, 0),\r
+                       Winter: new Date (curDate.getFullYear(), 10-1, thisYearWDays, 2, 0, 0),\r
+               }\r
+               daylightSavingDates[curDate.getFullYear()] = dst;\r
        }\r
+\r
+       if (dst.Summer < curDate)\r
+               summer = true;\r
+       if (dst.Winter < curDate)\r
+               winter = true;\r
        if (summer && !winter)\r
-               summertime = true;\r
+               return true;\r
        else\r
-               summertime = false;\r
+               return false;\r
 }\r
 \r
 function error(message)\r
 {\r
        console.info('Error: ' + message);\r
        document.getElementById("calendarList").innerHTML = 'Error: ' + message;\r
+       document.getElementById("fullscreenCalendarList").innerHTML = 'Error: ' + message;\r
+       errorOccured = true;\r
+       document.onclick = null;\r
 }\r
 \r
 function areDatesEqual(date1, date2)\r
@@ -249,7 +291,7 @@ function collectLocales()
                                month = tmp;\r
                        }\r
 \r
-                       console.info(entry.StartTime + ' -> ' + month + ' ' + counter);\r
+                       log(entry.StartTime + ' -> ' + month + ' ' + counter);
                        ids[counter] = entry.id;\r
                        months_translated[month] = counter + 1;\r
                        counter++;\r
@@ -258,7 +300,7 @@ function collectLocales()
                error(e + ', line ' + e.line);\r
                return;\r
        }\r
-       console.info(ids);\r
+       log(ids);
        try {\r
                var criteria = new Object();\r
                criteria.Type = "CalendarEntry";\r
@@ -279,13 +321,17 @@ function requestNotification()
 {\r
        var criteria = new Object();\r
        criteria.Type = "CalendarEntry";\r
-\r
-       try {\r
-               notificationRequest1 = calendarService.IDataSource.RequestNotification(criteria, callback);\r
-               if (notificationRequest1.ErrorCode)\r
-                       error('requestNotification failed with error code ' + notificationRequest1.ErrorCode);\r
-       } catch (e) {\r
-               error("requestNotification: " + e + ', line ' + e.line);\r
+       criteria.Filter = new Object();\r
+       for(var i=0; i < calendarList.length; i++) {\r
+               criteria.Filter.CalendarName = calendarList[i];\r
+               try {\r
+                       var notificationRequest = calendarService.IDataSource.RequestNotification(criteria, callback);\r
+                       if (notificationRequest.ErrorCode)\r
+                               error('requestNotification failed with error code ' + notificationRequest.ErrorCode);\r
+                       notificationRequests.push(notificationRequest);\r
+               } catch (e) {\r
+                       error("requestNotification: " + e + ', line ' + e.line);\r
+               }\r
        }\r
 \r
        var criteria2 = new Object();\r
@@ -293,25 +339,38 @@ function requestNotification()
        criteria2.Filter = new Object();\r
        criteria2.Filter.LocalIdList = new Array();\r
        criteria2.Filter.LocalIdList[0] = settingsCalEntryId;\r
-\r
        try {\r
-               notificationRequest2 = calendarService.IDataSource.RequestNotification(criteria2, settingsCallback);\r
-               if (notificationRequest2.ErrorCode)\r
-                       error('requestNotification failed with error code ' + notificationRequest2.ErrorCode);\r
+               var notificationRequest = calendarService.IDataSource.RequestNotification(criteria2, settingsCallback);\r
+               if (notificationRequest.ErrorCode)\r
+                       error('requestNotification failed with error code ' + notificationRequest.ErrorCode);\r
+               notificationRequests.push(notificationRequest);\r
        } catch (e) {\r
                error("requestNotification: " + e + ', line ' + e.line);\r
        }\r
 }\r
 \r
+function cancelNotification()\r
+{\r
+       for(var i=0; i < notificationRequests.length; i++) {\r
+               try {\r
+                       var result = calendarService.IDataSource.Cancel(notificationRequests[i]);\r
+                       if (result.ErrorCode)\r
+                               error('cancelNotification failed with error code ' + result.ErrorCode);\r
+               } catch (e) {\r
+                       error("cancelNotification: " + e + ', line ' + e.line);\r
+               }\r
+       }\r
+}\r
+\r
 function callback(transId, eventCode, result)\r
 {\r
-       console.info("callback(): panelNum: %d  transId: %d  eventCode: %d result.ErrorCode: %d", panelNum, transId, eventCode, result.ErrorCode);\r
+       log("callback(): panelNum: %d  transId: %d  eventCode: %d result.ErrorCode: %d", panelNum, transId, eventCode, result.ErrorCode);
        updateData();\r
 }\r
 \r
 function settingsCallback(transId, eventCode, result)\r
 {\r
-       console.info("settingsCallback(): panelNum: %d  transId: %d  eventCode: %d result.ErrorCode: %d", panelNum, transId, eventCode, result.ErrorCode);\r
+       log("settingsCallback(): panelNum: %d  transId: %d  eventCode: %d result.ErrorCode: %d", panelNum, transId, eventCode, result.ErrorCode);
        loadSettings();\r
 }\r
 \r
@@ -368,18 +427,26 @@ function parseDate(dateString)
        if (dateArr.length == 6 && dateArr[5].toLowerCase() == 'am' && hours == 12)\r
                hours = 0;\r
 \r
-       console.info('year=' + year + ' month=' + month + ' day=' + day + ' hours=' + hours + ' minutes=' + minutes+ ' seconds=' + seconds);\r
-\r
+       var result = new Date(year, month - 1, day, hours, minutes, seconds);\r
+       \r
        // take care of daylight saving time\r
        if (config['enableDaylightSaving'].Value) {\r
-               var date = new Date(year, month - 1, day, hours, minutes, seconds);\r
-               if (summertime && date > daylightsavingWinter && date < daylightsavingSummer)\r
-                       hours -= 1;\r
-               else if (!summertime && date > daylightsavingSummer && date < daylightsavingWinter)\r
-                       hours += 1;\r
+               \r
+               // determine if date is in summer or winter time\r
+               var dateSummerTime = isSummertime(result);\r
+\r
+               // work around bug in Nokias calendar api resulting in dates within a different DST to be off by 1 hour\r
+               if (summertime && !dateSummerTime) {\r
+                       result = new Date(result.getTime() - 1000 * 60 * 60 * config['daylightSavingOffset'].Value); // -1 hour\r
+                       log('parseDate(): fixing time -1h: ' + result);
+               }\r
+               else if (!summertime && dateSummerTime) {\r
+                       result = new Date(result.getTime() + 1000 * 60 * 60 * config['daylightSavingOffset'].Value); // +1 hour\r
+                       log('parseDate(): fixing time +1h: ' + result);
+               }\r
        }\r
 \r
-       return new Date(year, month - 1, day, hours, minutes, seconds);\r
+       return result;\r
 }\r
 \r
 // returns a short date as string ("31.12" or "12.31") based on the format string which should look like "Wednesday,  26 August, 2009 12:00:00 am"\r
@@ -452,37 +519,70 @@ function formatTime(date)
 \r
 function updateData()\r
 {\r
-       console.info('updateData()');\r
-       calcDaylightSaving();\r
+       log('updateData()');
+       if (errorOccured) {\r
+               return;\r
+       }\r
+\r
+       // check if we got additional or less calendars since our last update\r
+       var newCalendarList = listCalendars();\r
+       if (newCalendarList.length != calendarList.length) {\r
+               calendarList = newCalendarList;\r
+               updateCalendarColors();\r
+               cancelNotification();\r
+               requestNotification();\r
+       }\r
+       \r
        try {\r
                // meetings have time\r
                // note: anniveraries have a start time of 12:00am. So since we want to include them, we have to query the whole day and check if events have passed later\r
                now = new Date();\r
-               var meetingListFiltering = {\r
-                       Type:'CalendarEntry',\r
-                       Filter:{\r
-                               StartRange: (new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)),\r
-                               EndRange: (new Date(now.getFullYear(), now.getMonth() + config['monthRange'].Value, now.getDate(), 0, 0, 0))\r
+               summertime = isSummertime(now); // cache summer time info for today\r
+               var meetingList = [];\r
+               for(var i=0; i < calendarList.length; i++) {\r
+                       // ignore excluded calendars\r
+                       if (config['excludedCalendars'].Value.indexOf(calendarList[i]) != -1)\r
+                               continue;\r
+                       var meetingListFiltering = {\r
+                               Type:'CalendarEntry',\r
+                               Filter:{\r
+                                       CalendarName: calendarList[i],\r
+                                       StartRange: (new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0)),\r
+                                       EndRange: (new Date(now.getFullYear(), now.getMonth() + config['monthRange'].Value, now.getDate(), 0, 0, 0))\r
+                               }\r
                        }\r
+                       var meetingResult = calendarService.IDataSource.GetList(meetingListFiltering);\r
+                       if (meetingResult.ErrorCode != 0)\r
+                               throw("Error fetching calendar data: " + meetingResult.ErrorCode + ': ' + meetingResult.ErrorMessage);\r
+                       var list = meetingResult.ReturnValue;\r
+                       meetingList = meetingList.concat(listToArray(list, calendarList[i]));\r
                }\r
-               var meetingResult = calendarService.IDataSource.GetList(meetingListFiltering);\r
-               if (meetingResult.ErrorCode != 0)\r
-                       throw("Error fetching calendar data: " + meetingResult.ErrorCode + ': ' + meetingResult.ErrorMessage);\r
-               var meetingList = meetingResult.ReturnValue;\r
+               console.info("updateData(): meetingList.sort()");\r
+               meetingList.sort(sortCalendarEntries);\r
 \r
                // todos don't, they start on 00:00 hrs., but should be visible anyway\r
                // this will generate a list of passed todos. We have to check if they have been marked as "done" yet\r
                if (config['includeTodos'].Value) {\r
-                       var todayTodoListFiltering = {\r
-                               Type:'CalendarEntry',\r
-                               Filter:{\r
-                                       Type: 'ToDo',\r
-                                       StartRange: (new Date(now.getFullYear() - 1, now.getMonth(), now.getDate(), 0, 0, 0)),\r
-                                       EndRange: (new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 1))\r
+                       var todayTodoList = [];\r
+                       for(var i=0; i < calendarList.length; i++) {\r
+                               // ignore excluded calendars\r
+                               if (config['excludedCalendars'].Value.indexOf(calendarList[i]) != -1)\r
+                                       continue;\r
+                               var todayTodoListFiltering = {\r
+                                       Type:'CalendarEntry',\r
+                                       Filter:{\r
+                                               CalendarName: calendarList[i],\r
+                                               Type: 'ToDo',\r
+                                               StartRange: (new Date(now.getFullYear() - 1, now.getMonth(), now.getDate(), 0, 0, 0)),\r
+                                               EndRange: (new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 1))\r
+                                       }\r
                                }\r
+                               var todayTodoResult = calendarService.IDataSource.GetList(todayTodoListFiltering);\r
+                               var list = todayTodoResult.ReturnValue;\r
+                               todayTodoList = todayTodoList.concat(listToArray(list, calendarList[i]));\r
                        }\r
-                       var todayTodoResult = calendarService.IDataSource.GetList(todayTodoListFiltering);\r
-                       var todayTodoList = todayTodoResult.ReturnValue;\r
+                       console.info("updateData(): todayTodoList.sort()");\r
+                       todayTodoList.sort(sortCalendarEntries);\r
                        var entryLists = [todayTodoList, meetingList];\r
                } else {\r
                        var entryLists = [meetingList];\r
@@ -522,34 +622,42 @@ function updateData()
                else\r
                        max = 30; // we can display a lot more events in fullscreen mode\r
 \r
+               var listinfo = "";\r
+               for (var i=0; i < entryLists.length; i++) {\r
+                       listinfo = listinfo + " " + entryLists[i].length;\r
+                       var entrieslist = "";\r
+                       for (var j=0; j < entryLists[i].length; j++) {\r
+                               entrieslist += entryLists[i][j].Summary + ", ";\r
+                       }\r
+                       console.info("updateData(): entrieslist: " + entrieslist);\r
+               }\r
+               console.info("updateData(): inner loop, " + entryLists.length + " lists, [" + listinfo + "] entries");\r
+               \r
                // the first outer loop iteration is for passed ToDos, the second loop is for all upcomming events (may also include ToDos)\r
                for (var i=0; counter < max && i < entryLists.length; i++) {\r
-                       while (counter < max && (entry = entryLists[i].getNext()) != undefined) {\r
+                       for (var j=0; (counter < max) && (j < entryLists[i].length); j++) {\r
+                               entry = entryLists[i][j];\r
                                counter++;\r
 \r
                                // output event info for debugging\r
-                               console.info(\r
-                                       'event: Id=' + entry.id + \r
-                                       ',Type=' + entry.Type + \r
-                                       ',Summary=' + entry.Summary + \r
-                                       ',Location=' + entry.Location + \r
-                                       ',Status=' + entry.Status + \r
-                                       ',StartTime=' + entry.StartTime +\r
-                                       ',EndTime=' + entry.EndTime +\r
-                                       ',InstanceStartTime=' + entry.InstanceStartTime +\r
-                                       ',InstanceEndTime=' + entry.InstanceEndTime\r
-                               );\r
+                               var entryInfo = "event: ";\r
+                               for(var k=0; k < entryFields.length; ++k) {\r
+                                       if (entry[entryFields[k]] != undefined) {\r
+                                               entryInfo += entryFields[k] + "=" + entry[entryFields[k]] + ",";\r
+                                       }\r
+                               }\r
+                               log(entryInfo);
 \r
                                // we don't want ToDos when includeTodos == false or when they are completed\r
                                if (entry.Type == 'ToDo' && (entry.Status == "TodoCompleted" || !config['includeTodos'].Value)) {\r
-                                       console.info('skipping ' + entry.id );\r
+                                       log('skipping ' + entry.id );
                                        counter--;\r
                                        continue;\r
                                }\r
 \r
                                // make sure that we don't include an event twice (useful for ToDos that might come up twice)\r
                                if (eventIds[entry.id] == 1 && entry.Type == 'ToDo') {\r
-                                       console.info('skipped (already included) ' + entry.id);\r
+                                       log('skipped (already included) ' + entry.id);
                                        counter--;\r
                                        continue;\r
                                } else\r
@@ -572,15 +680,15 @@ function updateData()
 \r
                                // Convert date/time string to Date object\r
                                var date = parseDate(entryDate);\r
-                               console.info('date: ' + date);\r
+                               log('date: ' + date);
                                var endDate = ((entryEndTime == null) ? null : parseDate(entryEndTime));\r
-                               console.info('endDate: ' + endDate);\r
+                               log('endDate: ' + endDate);
 \r
                                // check if meeting event has already passed\r
                                if (entry.Type == 'Meeting') {\r
                                        var compareTime = ((endDate == null) ? date.getTime() : endDate.getTime());\r
                                        if (now.getTime() > compareTime) {\r
-                                               console.info('skipping Meeting (already passed) ' + entry.id);\r
+                                               log('skipping Meeting (already passed) ' + entry.id);
                                                counter--;\r
                                                eventIds[entry.id] = 0;\r
                                                continue;\r
@@ -591,7 +699,7 @@ function updateData()
                                if (entry.Type == 'Anniversary') {\r
                                        var tmp = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0,0,0);\r
                                        if (date.getTime() < tmp.getTime()) {\r
-                                               console.info('skipping Anniversary (already passed) ' + entry.id);\r
+                                               log('skipping Anniversary (already passed) ' + entry.id);
                                                counter--;\r
                                                eventIds[entry.id] = 0;\r
                                                continue;\r
@@ -601,9 +709,9 @@ function updateData()
                                // fix DayEvents end time. End times are off by 1 Second. It's possible that the event has already passed\r
                                if (entry.Type == 'DayEvent' && endDate != null) {\r
                                        endDate.setMinutes(endDate.getMinutes() - 1);\r
-                                       console.info('fixing DayEvent endDate: ' + endDate);\r
+                                       log('fixing DayEvent endDate: ' + endDate);
                                        if (now.getTime() > endDate.getTime()) {\r
-                                               console.info('event already passed ' + entry.id);\r
+                                               log('event already passed ' + entry.id);
                                                counter--;\r
                                                eventIds[entry.id] = 0;\r
                                                continue;\r
@@ -615,13 +723,13 @@ function updateData()
                                        // check if we are between start and endtime\r
                                        if ((date.getTime() < now.getTime()) && (now.getTime() < endDate.getTime())) {\r
                                                date = now; // change appointment date/time to now\r
-                                               console.info('event is currently taking place: ' + date);\r
+                                               log('event is currently taking place: ' + date);
                                        }\r
                                }\r
 \r
                                // skip events for the first panel in case this is the second one and we're not in fullscreen mode\r
                                if (mode == 0 && panelNum > 0 && counter < panelNum * config['eventsPerWidget'].Value + 1) {\r
-                                       console.info('skipping (already in first widget) ' + entry.id);\r
+                                       log('skipping (already in first widget) ' + entry.id);
                                        continue;\r
                                }\r
                                \r
@@ -636,7 +744,11 @@ function updateData()
                                }\r
 \r
                                // generate html output\r
-                               entriesHtml += '<tr><td><img class="icon" src="' + entry.Type + '.png" /></td>';\r
+                               entriesHtml += '<tr>';\r
+                               if (config['showCalendarIndicator'].Value && calendarList.length - config['excludedCalendars'].Value.length > 1) {\r
+                                       entriesHtml += '<td><span class="calendar' + calendarColors[entry.CalendarName] + '">&nbsp;</span></td>';\r
+                               }\r
+                               entriesHtml += '<td><img class="icon" src="' + entry.Type + '.png" /></td>';\r
                                if(date == null) {\r
                                        // some languages have very strange locale date formats, can't parse all those. Also some todos don't have dates at all.\r
                                        entriesHtml += '<td colspan="4"><span class="date">' + entryDate + '</span> ';\r
@@ -683,6 +795,8 @@ function updateData()
                                document.getElementById('fullscreenCalendarList').innerHTML = entriesHtml;\r
                        cacheEntriesHtml = entriesHtml;\r
                }\r
+               \r
+               lastUpdateTime = new Date();\r
        } catch(e) {\r
                error('displaying list:' + e + ', line ' + e.line);\r
                return;\r
@@ -708,6 +822,14 @@ function updateScreen()
                updateHomescreen();\r
        else if (mode == 1)\r
                updateFullscreen();\r
+       \r
+       var time = new Date();\r
+       if (time.getTime() - lastUpdateTime.getTime() > config['updateDataInterval'].Value * 60 * 1000) {\r
+               log('updateScreen(): force updateData() because last update was too long ago (' + (time.getTime() - lastUpdateTime.getTime()) / 1000 + 's)');
+               clearUpdateTimer();\r
+               updateData();\r
+               setUpdateTimer(); // reinitialize update timer\r
+       }\r
 }\r
 \r
 function launchCalendar()\r
@@ -724,7 +846,7 @@ function launchCalendar()
 \r
 function init()\r
 {\r
-       console.info('New widget instance starting up...');\r
+       log('New widget instance starting up...');
        \r
        try {\r
                // call calendar service\r
@@ -733,22 +855,46 @@ function init()
                else\r
                        throw('device object does not exist');\r
        } catch(e) {\r
-               error('loading Calendar service: ' + e + ', line ' + e.line);\r
-               return;\r
+               error('loading Calendar service: ' + e + ', line ' + e.line + '<br /><a onclick="widget.openURL(\'http://comingnext.sf.net/help\'); return false;" href="http://comingnext.sf.net/help">' + getLocalizedText('menu.help') + '</a>');\r
+               //return;\r
        }\r
 \r
+       calendarList = listCalendars();\r
        loadSettings();\r
+       updateCalendarColors();\r
        collectLocales();\r
        //updateData();\r
        requestNotification();\r
-       window.setInterval('updateData()', 1000 * 60 * config['updateDataInterval'].Value);\r
-\r
-       mode = 0;\r
-       showHomescreen();\r
+       document.getElementById("settingsTitle").innerHTML = getLocalizedText('menu.settings');\r
+       setUpdateTimer();\r
+       if (window.innerHeight > 91) {\r
+               mode = 0; // we're starting fullscreen, we set mode to homescreen in order to let updateScreen() do all the work for us\r
+       }\r
+       else {\r
+               mode = 1;\r
+       }\r
+       log("init(): updateScreen()");
        updateScreen();\r
        if (config['useBackgroundImage'].Value)\r
                // check for screen rotation every 1 secs\r
-               window.setInterval('updateScreen()', 1000 * 1);\r
+               screenRotationTimer = window.setInterval('updateScreen()', 1000 * 1);\r
+       log("init(): finished...");
+}\r
+\r
+function setUpdateTimer()\r
+{\r
+       updateTimer = window.setInterval('updateTimerCallback()', 1000 * 60 * config['updateDataInterval'].Value);\r
+}\r
+\r
+function clearUpdateTimer() \r
+{\r
+       window.clearInterval(updateTimer);\r
+}\r
+\r
+function updateTimerCallback()\r
+{\r
+       log("updateTimerCallback()");
+       updateData();\r
 }\r
 \r
 function createMenu()\r
@@ -758,15 +904,18 @@ function createMenu()
        var id = 0;\r
        var menuSettings = new MenuItem(getLocalizedText('menu.settings'), id++);\r
        var menuCallApp = new MenuItem(getLocalizedText('menu.openCalendarApp'), id++);\r
+       var menuHelp = new MenuItem(getLocalizedText('menu.help'), id++);\r
        var menuUpdate = new MenuItem(getLocalizedText('menu.update'), id++);\r
        var menuAbout = new MenuItem(getLocalizedText('menu.about'), id++);\r
        menuSettings.onSelect = showSettings;\r
        menuAbout.onSelect = showAbout;\r
        menuCallApp.onSelect = launchCalendar;\r
        menuUpdate.onSelect = showUpdate;\r
+       menuHelp.onSelect = showHelp;\r
        window.menu.clear();\r
        window.menu.append(menuCallApp);\r
        window.menu.append(menuSettings);\r
+       window.menu.append(menuHelp);\r
        window.menu.append(menuUpdate);\r
        window.menu.append(menuAbout);  \r
 }\r
@@ -797,6 +946,16 @@ function showSettings()
                                if (config[key].ValidValues.indexOf(config[key].Value) == -1)\r
                                        config[key].Value = config[key].Default;\r
                        }\r
+                       else if (config[key].Type == 'Array') {\r
+                               if (key == 'excludedCalendars') {\r
+                                       config[key].Value = new Array();\r
+                                       for(var i=0; i < calendarList.length; i++) {\r
+                                               var element = document.forms[0].elements["settings." + key + "." + calendarList[i]];\r
+                                               if (element != null && element.checked == false)\r
+                                                       config[key].Value.push(calendarList[i]);\r
+                                       }\r
+                               }\r
+                       }\r
                }\r
                                \r
                updateCssClasses();\r
@@ -814,8 +973,12 @@ function showSettings()
        \r
        var settingsHtml = '<form>';\r
        for (var key in config) {\r
-               if (config[key].Type == 'String')\r
-                       settingsHtml += '<table><tr><td>' + getLocalizedText('settings.name.' + key) + '<br /><input class="textInput" name="settings.' + key + '" type="text" value="' + config[key].Value + '" /></td>' + printHintBox(getLocalizedText('settings.info.' + key)) + '<hr />';\r
+               if (config[key].Type == 'String') {\r
+                       var prefix = "";\r
+                       if (key.substring(0,9) == "cssStyle_")\r
+                               prefix = getLocalizedText('settings.cssStyle_prefix');\r
+                       settingsHtml += '<table><tr><td>' + prefix + getLocalizedText('settings.name.' + key) + '<br /><input class="textInput" name="settings.' + key + '" type="text" value="' + config[key].Value + '" /></td>' + printHintBox(getLocalizedText('settings.info.' + key)) + '<hr />';\r
+               }\r
                else if (config[key].Type == 'Int')\r
                        settingsHtml += '<table><tr><td>' + getLocalizedText('settings.name.' + key) + '<br /><input class="textInput" name="settings.' + key + '" type="text" value="' + config[key].Value + '" /></td>' + printHintBox(getLocalizedText('settings.info.' + key)) + '<hr />';\r
                else if (config[key].Type == 'Bool')\r
@@ -828,6 +991,18 @@ function showSettings()
                                settingsHtml += '<option value="' + config[key].ValidValues[i] + '"' + (config[key].Value == config[key].ValidValues[i] ? ' selected="selected"' : '') + '>' + getLocalizedText('settings.validValues.' + key + '.' + config[key].ValidValues[i]) + '</option>';\r
                        settingsHtml += '</select></div></td>' + printHintBox(getLocalizedText('settings.info.' + key)) + '<hr />';\r
                }\r
+               else if (config[key].Type == 'Array') {\r
+                       settingsHtml += '<table><tr><td>' + getLocalizedText('settings.name.' + key) + '<br />';\r
+                       if (key == 'excludedCalendars') {\r
+                               for(var i=0; i < calendarList.length; i++) {\r
+                                       var checked = 'checked="checked"';\r
+                                       if (config[key].Value.indexOf(calendarList[i]) != -1)\r
+                                               checked = '';\r
+                                       settingsHtml += '<input name="settings.' + key + '.' + calendarList[i] + '" type="checkbox" value="' + calendarList[i] + '" ' + checked + '/> ' + calendarList[i] + '<br />';\r
+                               }\r
+                       }\r
+                       settingsHtml += '</td>' + printHintBox(getLocalizedText('settings.info.' + key)) + '<hr />';\r
+               }\r
        }\r
        settingsHtml += '<input name="reset" type="button" value="' + getLocalizedText('settings.restoreDefaults') + '" onclick="javascript:restoreDefaultSettings();showSettings();" />';\r
        settingsHtml += '</form>';\r
@@ -875,7 +1050,7 @@ function getSettingsCalEntryId()
                var entry = list.getNext();\r
                if (entry != undefined) {\r
                        settingsCalEntryId = entry.LocalId;\r
-                       console.info("settingsCalEntryId=" + settingsCalEntryId);\r
+                       log("settingsCalEntryId=" + settingsCalEntryId);
                }\r
                else { // create settings item\r
                        var item = new Object();\r
@@ -922,6 +1097,7 @@ function loadSettings()
        }\r
        var entry = result.ReturnValue.getNext();\r
        if (entry != undefined) {\r
+               log("Loading Settings...");
                // only reload settings if they chanced since the last reload\r
                if (settingsCache != entry.Summary)\r
                {\r
@@ -932,7 +1108,7 @@ function loadSettings()
                                var pair = stringlist[i].split('=');\r
                                var key = pair[0];\r
                                var value = pair[1];\r
-                               console.info('stringlist: ' + key + '=\'' + value + '\'');\r
+                               log('stringlist: ' + key + '=\'' + value + '\'');
                                if (config[key].Type == 'Int')\r
                                        config[key].Value = Number(value);\r
                                else if (config[key].Type == 'String')\r
@@ -943,10 +1119,19 @@ function loadSettings()
                                        config[key].Value = value;\r
                                else if (config[key].Type == 'UID')\r
                                        config[key].Value = Number(value);\r
+                               else if (config[key].Type == 'Array') {\r
+                                       config[key].Value = value.split("^");\r
+                                       if (config[key].Value.length == 1 && config[key].Value[0] == "") {\r
+                                               config[key].Value = [];\r
+                                       }\r
+                               }\r
                        }\r
                        settingsCache = entry.Summary;\r
                        updateCssClasses();\r
                }\r
+               else {\r
+                       log("Settings already cached and did not change");
+               }\r
        }\r
        else {\r
                error("Failed to load settings, calendar entry could not be found");\r
@@ -973,6 +1158,8 @@ function saveSettings()
                        item.Summary += key + "=" + config[key].Value + "|";\r
                else if (config[key].Type == 'UID')\r
                        item.Summary += key + "=" + config[key].Value.toString() + "|";\r
+               else if (config[key].Type == 'Array')\r
+                       item.Summary += key + "=" + config[key].Value.join("^") + "|";\r
        }\r
        settingsCache = item.Summary;\r
        \r
@@ -980,7 +1167,7 @@ function saveSettings()
        criteria.Type = "CalendarEntry";\r
        criteria.Item = item;\r
 \r
-       console.info("Saving settings to calendar entry: " + item.Summary);\r
+       log("Saving settings to calendar entry: " + item.Summary);
        try {\r
                var result = calendarService.IDataSource.Add(criteria);\r
                if (result.ErrorCode)\r
@@ -988,6 +1175,9 @@ function saveSettings()
        } catch (e) {\r
                error("saveSettings: " + e + ', line ' + e.line);\r
        }\r
+       \r
+       clearUpdateTimer();\r
+       setUpdateTimer();\r
 }\r
 \r
 function toggleVisibility(elementId)\r
@@ -1024,22 +1214,30 @@ function showAbout()
        document.getElementById("name").innerHTML = "Coming Next " + version;\r
 }\r
 \r
+function showHelp() {\r
+       widget.openURL('http://comingnext.sf.net/help');\r
+}\r
+\r
 function updateFullscreen()\r
 {\r
 }\r
 \r
 function showFullscreen()\r
 {\r
+       log("showFullscreen()");
        hideViews();\r
        document.getElementById("fullscreenView").style.display = "block";\r
        document.getElementById('body').className = "backgroundFullscreen";\r
-       document.onclick = launchCalendar;\r
+       if (!errorOccured)\r
+               document.onclick = launchCalendar;\r
        createMenu();\r
        updateData();\r
 }\r
 \r
 function getBackgroundImage()\r
 {\r
+       if (errorOccured)\r
+               return '';\r
        var bgImage;\r
        if (config['backgroundImageLocation'].Value == config['backgroundImageLocation'].ValidValues[0]) // internal\r
                bgImage = 'background_' + orientation + '.png';\r
@@ -1074,6 +1272,7 @@ function updateHomescreen()
 \r
 function showHomescreen()\r
 {\r
+       log("showHomescreen()");
        hideViews();\r
        document.getElementById("homescreenView").style.display = "block";\r
        document.getElementById('body').className = "background";\r
@@ -1153,9 +1352,174 @@ function hideViews()
        document.getElementById("settingsView").style.display = "none";\r
        document.getElementById("updateView").style.display = "none";\r
 }\r
+\r
+function listCalendars()\r
+{\r
+       try {\r
+               var criteria = {\r
+                       Type:'Calendar', \r
+                       Filter:{\r
+                               DefaultCalendar: false\r
+                       }\r
+               }\r
+               \r
+               var calendarsResult = calendarService.IDataSource.GetList(criteria);\r
+               if (calendarsResult.ErrorCode != 0)\r
+                       throw("Error fetching list of calendars: " + calendarsResult.ErrorCode + ': ' + calendarsResult.ErrorMessage);\r
+               var calendarListIterator = calendarsResult.ReturnValue;\r
+               \r
+               var calendars = [];\r
+               var count = 0;\r
+               var item;\r
+               while (( item = calendarListIterator.getNext()) != undefined ) {\r
+                       calendars[count++] = item;\r
+               }\r
+               log("Available Calendars: " + calendars.join(", "));
+               return calendars;\r
+       } catch(e) {\r
+               error('listing calendars:' + e + ', line ' + e.line);\r
+               return null;\r
+       }\r
+}\r
+\r
+// Copies all objects and their properties to an array. Data is copied so nothing gets lost when the reference is removed\r
+// Note: this will also set the "CalendarName" property of every entry to the name specified by the calendarName parameter if it has not been defined already\r
+function listToArray(list, calendarName)\r
+{\r
+       var array = new Array();\r
+       var item;\r
+       var txt = "";\r
+       while (( item = list.getNext()) != undefined ) {\r
+               var itemCopy = new Object();\r
+               for(var i=0; i < entryFields.length; i++) {\r
+                       itemCopy[entryFields[i]] = item[entryFields[i]];\r
+               }\r
+               // for some reason, the CalendarName property is never correctly queried, so we assign it manually here\r
+               if (!itemCopy['CalendarName']) {\r
+                       itemCopy['CalendarName'] = calendarName;\r
+               }\r
+               array.push(itemCopy);\r
+               txt += array[array.length - 1].Summary + ", ";\r
+       }\r
+       log("listToArray(): " + txt);
+       return array;\r
+}\r
+\r
+function sortCalendarEntries(a, b)\r
+{\r
+       var atime, btime;\r
+       log("sortCalendarEntries(" + a.Summary + "," + b.Summary + ")");
+       \r
+       if (a.InstanceStartTime != null) {\r
+               atime = a.InstanceStartTime;\r
+       }\r
+       else if (a.StartTime != null) {\r
+               atime = a.StartTime;\r
+       }\r
+       else if (a.InstanceEndTime != null) {\r
+               atime = a.InstanceEndTime;\r
+       }\r
+       else if (a.EndTime != null) {\r
+               atime = a.EndTime;\r
+       }\r
+       \r
+       if (b.InstanceStartTime != null) {\r
+               btime = b.InstanceStartTime;\r
+       }\r
+       else if (b.StartTime != null) {\r
+               btime = b.StartTime;\r
+       }\r
+       else if (b.InstanceEndTime != null) {\r
+               btime = b.InstanceEndTime;\r
+       }\r
+       else if (b.EndTime != null) {\r
+               btime = b.EndTime;\r
+       }\r
+       \r
+       if (atime && btime) {\r
+       \r
+               atime = parseDate(atime);\r
+               btime = parseDate(btime);\r
+       \r
+               // sort by date & time\r
+               if (atime < btime) {\r
+                       return -1;\r
+               }\r
+               else if (atime > btime) {\r
+                       return 1;\r
+               }\r
+               // sort by type\r
+               else if (a.Type != b.Type) {\r
+                       if (a.Type < b.Type) {\r
+                               return -1;\r
+                       }\r
+                       else if (a.Type > b.Type) {\r
+                               return 1;\r
+                       }\r
+               }\r
+               // sort by description\r
+               else if (a.Summary && b.Summary && a.Summary != b.Summary) {\r
+                       if (a.Summary < b.Summary) {\r
+                               return -1;\r
+                       }\r
+                       else if (a.Summary > b.Summary) {\r
+                               return 1;\r
+                       }\r
+               }\r
+       }\r
+       // NOTE: events my have no date information at all. In that case, we list events without date first\r
+       else if (atime && !btime) {\r
+               return 1;\r
+       }\r
+       else if (!atime && btime) {\r
+               return -1;\r
+       }\r
+       else if (!atime && !btime) {\r
+               // sort by type\r
+               if (a.Type != b.Type) {\r
+                       if (a.Type < b.Type) {\r
+                               return -1;\r
+                       }\r
+                       else if (a.Type > b.Type) {\r
+                               return 1;\r
+                       }\r
+               }\r
+               // sort by description\r
+               else if (a.Summary && b.Summary && a.Summary != b.Summary) {\r
+                       if (a.Summary < b.Summary) {\r
+                               return -1;\r
+                       }\r
+                       else if (a.Summary > b.Summary) {\r
+                               return 1;\r
+                       }\r
+               }\r
+       }\r
+\r
+       return 0;\r
+}\r
+\r
+function updateCalendarColors()\r
+{\r
+       var maxColors = 6;\r
+       calendarColors = [];\r
+       if (calendarList.length > maxColors) {\r
+               log("updateCalendarColors(): Warning: more calendars than available indicator colors");
+       }\r
+       for(var i=0; i < calendarList.length; i++) {\r
+               calendarColors[calendarList[i]] = (i % maxColors) + 1;\r
+       }\r
+}\r
+\r
+function log(message) {
+       if (config['enableLogging'].Value) {
+               console.info(message);
+       }
+}
+
 </script>\r
 \r
 <style type="text/css">\r
+a { color:#aaccff }\r
 table { margin:0px; padding:0px; border-spacing:0px; }\r
 td { padding:0px 5px 0px 0px; white-space:nowrap; overflow:hidden; }\r
 hr { color:#ffffff; background-color:#ffffff; height:1px; text-align:left; border-style:none; }\r
@@ -1164,7 +1528,7 @@ hr { color:#ffffff; background-color:#ffffff; height:1px; text-align:left; borde
 .textInput { width:90%; }\r
 .credits { margin-left:40px; text-indent: -20px; margin-bottom:0px; }\r
 #homescreenView { width: 315px; height:91px; overflow:hidden; }\r
-#calendarList { position:absolute; left:10px; top:4px; width:295px; height:75px; overflow:hidden; }\r
+#calendarList { position:absolute; left:5px; top:4px; width:295px; height:75px; overflow:hidden; }\r
 #name { text-align:center; }\r
 #appicon { display: block; margin-left: auto; margin-right: auto; margin-top: 10px; }\r
 #smallappicon { width:22px; height:22px; margin-right:10px; float:left; }\r
@@ -1184,7 +1548,7 @@ hr { color:#ffffff; background-color:#ffffff; height:1px; text-align:left; borde
 </div>\r
 <div id="settingsView" style="display:none">\r
        <img src="Icon.png" id="smallappicon">\r
-       <h1 class="title">Settings</h1>\r
+       <h1 id="settingsTitle" class="title">Settings</h1>\r
        <hr />\r
        <div id="settingsList"></div>\r
 </div>\r
@@ -1196,10 +1560,13 @@ hr { color:#ffffff; background-color:#ffffff; height:1px; text-align:left; borde
        <p>Contributions:</p>\r
                <p class="credits">Paul Moore (bug fixes, new features and code cleanup)</p>\r
                <p class="credits">Manfred Hanselmann (DST support)</p>\r
-               <p class="credits">Christophe Milsent (translation support & french translation</p>\r
-               <p class="credits">Flavio Nathan (portuguese-brazilian translation</p>\r
+               <p class="credits">Christophe Milsent (translation support & french translation)</p>\r
+               <p class="credits">Flavio Nathan (portuguese-brazilian translation)</p>\r
+               <p class="credits">Tokeda (russian translation)</p>\r
+               <p class="credits">Marcella Ferrari (italian translation)</p>\r
+               <p class="credits">Venos (italian translation)</p>\r
        <p>This software is open source and licensed under the GPLv3.</p>\r
-       <p>Visit sourceforge.net/projects/comingnext for free updates.</p>\r
+       <p>Visit <a onclick="widget.openURL('http://comingnext.sf.net/'); return false;" href="http://comingnext.sf.net/">comingnext.sf.net</a> for free updates.</p>\r
        <hr />\r
 </div>\r
 <div id="updateView" style="display:none">\r