<Module>
<ModulePrefs
height="26"
title=" Year with events desc"
description="__MSG_Labs_Gadget_Year_View_Description__"
author="sergentum"
author_email="sergentums@gmail.com">
<Require feature="views" />
<Require feature="google.calendar-0.5" />
<Require feature="google.calendar-0.5.read" />
    <Require feature="dynamic-height"/>
    <Locale messages="messages__en.xml"/>
  </ModulePrefs>
  <Content type="html" view="home,profile">
    <![CDATA[
             <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
             <html>
               <body>
                 <style>
                   body {
                   background-color: #fff;
                   margin: 0;
                   padding: 0;
                   overflow: hidden;
                   font-family:Arial;
                   font-size: 12.8px;
                   }
                 </style>
                 <script type="text/javascript">
                   function goToCanvas() {
                   var year = document.getElementById('year').value;
                   gadgets.views.requestNavigateTo('canvas', {'year': year});
                   return false;
                   };
                 </script>
                 <form style="display:block; text-align:center; margin:0; padding:0" onsubmit="return goToCanvas();">
                   <input maxlength="4" id="year" value="2009" style="width: 4em; margin:2px 0">
                     <input type=submit value="__MSG_Labs_Go_To_Year__">
                     </form>
                     <script type="text/javascript">
                       document.getElementById('year').value = (new Date()).getFullYear();
                       gadgets.window.adjustHeight();
                     </script>
                   </body>
                 </html>
                 ]]>
               </Content>
  <Content type="html" view="canvas">
    <![CDATA[
            <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
            <html>
              <body>
                <form style="margin:8px 0; display:block" onsubmit="return display(0);">
                  <button onmousedown="display(-1)">&nbsp;&laquo;&nbsp;</button>&nbsp;
                  <input id="yearInput" size="4" value="" style="width: 4em" maxlength="4">&nbsp;
                    <button onmousedown="display(1)">&nbsp;&raquo;&nbsp;</button>&nbsp;
                    <input type=submit value="__MSG_Labs_Go_To_Year__"
                            onmousedown="display(0)">&nbsp;
                      <button onmousedown="displayCurrentYear()">__MSG_Labs_This_Year_Button__
                      </button></form>
                    <div id=calDiv></div>
                    <script>
                      /** The full names of the months to use as titles */
                      var MONTH_NAMES = ["__MSG_January__", "__MSG_February__", "__MSG_March__",
                      "__MSG_April__", "__MSG_May__", "__MSG_June__", "__MSG_July__",
                      "__MSG_August__", "__MSG_September__", "__MSG_October__",
                      "__MSG_November__", "__MSG_December__"];
                      /** The VERY short names of the months to use as headings */
                      var DOW = ["__MSG_Short_Sunday__", "__MSG_Short_Monday__",
                      "__MSG_Short_Tuesday__", "__MSG_Short_Wednesday__",
                      "__MSG_Short_Thursday__", "__MSG_Short_Friday__",
                      "__MSG_Short_Saturday__"];
                      /** The lengths of the months */
                      var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
                      var SHOW_MONTH = "__MSG_Labs_Gadget_Month_View_Tooltip__";
                      /**
                      * Given a date, check if it is a leap year.
                      * @param {Date} date The date in question.
                      * @return {boolean} Whether it is a leap year.
                      */
                      function isLeapYear(date) {
                      var y = date.getFullYear();
                      if ((y % 4) == 0 && (y % 100) != 0) {
                      return true;
                      }
                      return (y % 400) == 0;
                      }
                      /**
                      * Get the number of days in a month.
                      * @param {Date} date The date in question.
                      * @return {number} The number of days in that month.
                      */
                      function getDaysInMonth(date) {
                      var days = DAYS_IN_MONTH[date.getMonth()];
                      return (days == 28 && isLeapYear(date)) ? 29 : days;
                      }
                      /**
                      * Get the text input for the year.
                      * @return {HTMLElement} The element.
                      */
                      function getYearInput() {
                      return document.getElementById('yearInput');
                      }
                      /**
                      * Display the current year.
                      * @param {string} opt_override An override year.
                      */
                      function displayCurrentYear(opt_override) {
						var year = opt_override || (new Date()).getFullYear();
						currentYear = year;
						getYearInput().value = year;
						showYear(year);
                      }
						var currentYear = (new Date()).getFullYear();
                      /**
                      * Display a year offset from the current one.
                      * @param {number} delta How many years to move.
                      */
                      function display(delta) {
                        var yearInput = getYearInput();
                        yearInput.value.replace(/[^0-9]/g, '');
                        var y = parseInt(yearInput.value, 10) + delta;
                        if (isNaN(y) || y > 9999 || y < 1){
                          yearInput.value = '?';
                        } else {
                          yearInput.value = y;
                          showYear(y);
                        }
                        return false;
                      }   
                      /**
                      * How many weeks does a given month overlap?
                      * @param {number} y The year.
                      * @param {number} m The month.
                      * @return {number} The number of weeks that the month overlap.
                      */
                      function getWeeksInMonth(y, m) {
                      var firstDate = new Date(y, m, 1);
                      var firstDayOfMonth = firstDate.getDay();
                      var daysInMonth = getDaysInMonth(firstDate);
                      return Math.ceil((firstDayOfMonth + daysInMonth) / 7)
                      }
                      /**
                      * Ask the calendar to go to a specific date
                      */
                      function showDate(y, m, opt_date) {
                      if (google && google.calendar) {
                      google.calendar.showDate(y, m, opt_date || 1);
                      }
                      }
                      /**
                      * Get the HTML for a specific month.
                      * @param {Array<string>} out The string buffer to append the output.
                        * @param {number} y The year.
                        * @param {number} m The month.
                        * @param {number} opt_weeks The minimum number of weeks to display.
                        */
                        function getMonthHtml(out, y, m, opt_weeks) {
                        var today = new Date();
                        var todayYear = today.getFullYear();
                        var todayMonth = today.getMonth();
                        var todayDate = today.getDate();
                        out.push('<table class="month" border=0 cellspacing=0>',
                          '<tr><td colspan=7 title="',
                                  SHOW_MONTH, '" class="monthHeader clickable" ',
                                  'onclick="showDate(', y, ',', m+1, ')">', MONTH_NAMES[m], ' ', y,
                              '<tr>');
                                for(var i = 0; i < DOW.length; ++i) {
                                  out.push('<td class="dow" style="color:black">', DOW[i]);
                                  }


                                  var firstDate = new Date(y, m, 1);
                                  var firstDayOfMonth = firstDate.getDay();
                                  var daysInMonth = getDaysInMonth(firstDate);
                                  var i = 0;
                                  var weeks = 0;
                                  var minWeeks = opt_weeks || Math.ceil(daysInMonth / 7);


                                  output = "month :"+(m+1) +"\n";
                                  for(var d = 1 - firstDayOfMonth; 1; ++d) {
                                    var dow = i++ % 7;
                                    if (minWeeks <= weeks && dow == 0) {
                                    break;
                                    }
                                    if (dow == 0) {




                                    out.push('<tr>');
                                    ++weeks;
                                    }
                                    out.push('<td');




                                    out.push(" id='"+ y + "-" + (m+1) + "-" + d + "' ");
                                    out.push('class="');
                                    var c = 'normal';
                                    if (y == todayYear && m == todayMonth && d == todayDate){
                                    c = 'today';
                                    }
                                    if ((d <= daysInMonth) && ((dow == 0) || (dow == 6))){
                                    c = 'weekend ';
                                    }
                                    //for(x in monthEvents) {
                                    //  if(x.toString() == d.toString()) {
                                    //    //output += d+ " Ok; ";
                                    //    c += ' busy ';
                                    //  }else {
                                    //  }
                                    //}
                                    out.push(c);
                                    if (d >= 1 && d <= daysInMonth) {
                                    out.push(' clickable" onclick="showDate(', y, ',', m+1, ',', d,
                                    ')">', d);
                                    } else {
                                    out.push('">&nbsp;');
                                    }
								//')">', d, '</td>');
							//out.push('</tr>');
						//i++;

                                  }
                                  //var output = "month: "+(m+1)+" ";
                                  //for(x in monthEvents) {
                                  //  output += x + " " + monthEvents[x] + "\n";
                                  //}
                                  //alert(output);


                                  out.push('</table>');
                        }
                        /**
                        * This is the main drawing function. It will display a specific year.
                        * @param {number} year The year to draw.
                        */
                        function showYear(y) {
                        var out = ['<table>'];
                          var weeks = 0;
                          for (var m = 0; m < 12; ++m) {
                          // Every 4 months, we start a new row.
                          if (m % 4 == 0) {
                          out.push('<tr>');
                          // Calculate the maximum number of weeks for the months in this row.
                          weeks = Math.max(getWeeksInMonth(y, m), getWeeksInMonth(y, m+1),
                          getWeeksInMonth(y, m+2), getWeeksInMonth(y, m+3));
                          }
                          out.push('<td class="outer">');
                          getMonthHtml(out, y, m, weeks);


                          }
                          out.push('</table>');
                        document.getElementById('calDiv').innerHTML = out.join('');
				month = 1;
				getMonthEvents();
		}
		var month = 1;
		function getMonthEvents() {
			if(month <= 12) {
				year = currentYear;
				nxtMonth = parseInt(month)+1;
				nxtYear = year;
				if(nxtMonth > 12) {
					nxtMonth = 1;
					nxtYear = parseInt(year)+1;
				}
				startDate = {year: year, month: month, date: 1, hour: 0, minute: 0, second: 0};
				endDate = {year: nxtYear, month: nxtMonth, date: 1, hour: 0, minute: 0, second: 0};
				google.calendar.read.getEvents(eventCallback, "selected", startDate, endDate);
				month = parseInt(month)+1;
			}
                        }
                        // Setup the style + buttons
                        var DARK_BLUE = '#112aba';
                        var LIGHT_BLUE = '#e8eef7';
                        var WEEKEND = '#eee';
                        var WHITE = '#fff';
                        var TODAY = '#557799';
                        var TODAY_BORDER_DARK = '#246';
                        var TODAY_BORDER_LIGHT = '#9bd';
                        var BORDER_GREY = '#a2bbd3';
                        var DIVIDER = '#c3d9ff';
                        /**
                        * @return {string} A string containing the styles.
                        */
                        function getStyles() {
                        var out = ['<style>'];
                          out.push(


						'.month td { white-space: nowrap; overflow: hidden; text-align: left; padding:2px 4px 1px}',
                          '.month,td.dow,td.monthHeader {background-color:', LIGHT_BLUE, '}',
                          'td.normal {background-color:', WHITE, '}',
                          'td.weekend {background-color:', WEEKEND, '}',
                          'td.outer {padding-right: 4px; padding-bottom: 4px; }',
                          'td.dow {max-width: 5px; border-width: 0 0 1px 0; border-style:solid;',
                          'border-color: ', DIVIDER, '}',
                          'td.today {padding: 1px 3px !important; background-color:', TODAY,
                          ';color:#fff !important; border-width: 1px; border-style:solid;',
                          'border-color: ', TODAY_BORDER_DARK, ' ', TODAY_BORDER_LIGHT, ' ',
                          TODAY_BORDER_LIGHT, ' ', TODAY_BORDER_DARK, '}',
                          'td.monthHeader {font-weight:bold}',
                          '.month {table-layout: fixed; width: 100%; background-color:', LIGHT_BLUE,
                          ';border: 1px solid ', BORDER_GREY, '}',
                          'body, td {font-family:Arial;font-size: 12.8px}',
                          'body {margin-left:10px; background-color:', WHITE, '}',
                          'td {vertical-align: top}',
                          '.clickable {cursor:pointer; color:', DARK_BLUE, '}',
                          '.clickable:hover {text-decoration: underline}', 

                          '.busy {color: red; }');
                          out.push('</style>');
                        return out.join('');
                        }
                        document.write(getStyles());
                        var tentativeYear = gadgets.views.getParams()['year'];
                        displayCurrentYear(tentativeYear);
                        // This is here to make it look nicer for gmail
                        gadgets.window.adjustHeight(2600);
                        //for(i=1; i<=12; i++ ) {
                          //year = tentativeYear;
                          //month = i;
                          //nxtMonth = month +1;
                          //nxtYear = year;
                          //if(nxtMonth > 12) {
                           // nxtMonth = 1;
                           // nxtYear = year + 1;


                          //}
                         // startDate = {year: year, month: month, date: 1, hour: 0, minute: 0, second: 0};
                         // endDate = {year: nxtYear, month: nxtYear, date: 1, hour: 0, minute: 0, second: 0};
                         // google.calendar.read.getEvents(eventCallback, "selected", startDate, endDate);
                        //}
		function eventCallback(response) {
			for(var cal = 0; cal < response.length; ++cal) {
				if ('error' in response[cal]) {
					alert('Something went wrong ' + response[cal]['error']);
					return;
				}
				var events = response[cal]['events'];
				var output = "";
				for(var i = 0; i < events.length; ++i) {
					var e = events[i];
					if ('title' in e) {
						var startDate = new Date(e.startTime.year, (e.startTime.month-1), e.startTime.date);
						var endDate = new Date(e.endTime.year, (e.endTime.month-1), e.endTime.date);
						var currentDate = startDate;//new Date(startDate.getTime());
						while(currentDate.getTime() <= endDate.getTime()) {
							id = currentDate.getFullYear() + "-" + (currentDate.getMonth()+1) + "-" + currentDate.getDate();
							// prevent double entries
							if((currentDate.getDate() == endDate.getDate() && e.allDay == true) || (currentDate.getMonth() + 2) != month) {
								currentDate.setDate(currentDate.getDate() + 1);
								continue;
							}
							document.getElementById(id).className += " busy ";
							document.getElementById(id).style.color = e.palette.medium;
							document.getElementById(id).title += e.title + "\n";
							document.getElementById(id).textContent += ": " + e.title.substr(0,21);
							currentDate.setDate(currentDate.getDate() + 1);
						}
					}
				}
			}
			getMonthEvents();
                        }
                      </script>
                    </body>
                  </html>
                  ]]>
  </Content>
</Module>