var events = {}

var key = null;

//date
var dateTime = {
		
	    getDatePieces : function  (date) {
			// date can be in msec or in a format recognized by Date.parse()
			var d = new Date(date);

			var dayOfWeek = d.getDay(); // zero based

			var year = d.getFullYear();
			var month = d.getMonth(); // zero based
			var day = d.getDate();

			var hours = d.getHours();
			var minutes = d.getMinutes();
			var seconds = d.getSeconds();
			var milliseconds = d.getMilliseconds();
			var amPm = 'am';

			if(hours == 0) {
				hours = 12;
			} else if (hours == 12) {
				amPm = 'pm';
			} else if (hours > 12) {
				hours -= 12;
				amPm = 'pm';
			}
			if(minutes < 10) { minutes = '0'+minutes; }

			return  {
				year: year,
				month :month,
				day: day,
				dayOfWeek: dayOfWeek,
				hours: hours,
				minutes: minutes,
				seconds: seconds,
				milliseconds: milliseconds,
				amPm: amPm
			};
		},
		

		getShortDateString : function (date) {
			var d = new Date(date);
			var year = d.getFullYear();
			var month = d.getMonth(); // zero based
			var day = d.getDate();
			var pieces = dateTime.getDatePieces(d);
			
			var dayOfWeek = pieces.dayOfWeek;

			return dateTime.getDayOfWeekTextLong(dayOfWeek ) +", " + dateTime.getMonthTextLong( month ) + " " + day  + ", " + year;
		},

		getMonthTextShort : function  (month) {
			var months = Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
			return months[month];
		},
		getMonthTextLong : function  (month) {
			var months = Array('January','February','March','April','May','June','July','August','September','October','November','December');
			return months[month];
		},

		getDayOfWeekTextLong : function (dayOfWeek) {
			var daysOfWeek = Array('Sunday', 'Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
			return daysOfWeek[dayOfWeek];
		}

		
	};





google.load("gdata", "1");

function addListItem(title,sDate,eDate)
{
	 
	return "<li><div class=\"eventTitle\"><a href=\"#\" onclick=\"loadEvent('"+title+"') \" >"+ title +"</a> -- </div><div class=\"eventDate\"><span>"+ dateTime.getShortDateString( sDate ) +" [ <a href=\"#\" onclick=\"loadEvent('"+title+"')\" style=\"text-decoration:underline;\" >details</a> ]</span></div></li>";
}

function init() {

	$('#modalLink').hide();
	
	$('#eventDetails').hide();
 
	  // init the Google data JS client library with an error handler
	  google.gdata.client.init(handleGDError);
	  // load the code.google.com developer calendar
	  loadDeveloperCalendar();

}

/**
 * Loads the Google Developers Event Calendar
 */
function loadDeveloperCalendar() {
  loadCalendarByAddress('ntkcalendar@yahoo.com');
}

/**
 * Adds a leading zero to a single-digit number.  Used for displaying dates.
 */
function padNumber(num) {
  if (num <= 9) {
    return "0" + num;
  }
  return num;
}

/**
 * Determines the full calendarUrl based upon the calendarAddress
 * argument and calls loadCalendar with the calendarUrl value.
 *
 * @param {string} calendarAddress is the email-style address for the calendar
 */ 
function loadCalendarByAddress(calendarAddress) {
  var calendarUrl = 'http://www.google.com/calendar/feeds/' +
                    calendarAddress + 
                    '/public/full';
  loadCalendar(calendarUrl);
}

/**
 * Uses Google data JS client library to retrieve a calendar feed from the specified
 * URL.  The feed is controlled by several query parameters and a callback 
 * function is called to process the feed results.
 *
 * @param {string} calendarUrl is the URL for a public calendar feed
 */  
function loadCalendar(calendarUrl) {
  var service = new 
      google.gdata.calendar.CalendarService('gdata-js-client-samples-simple');
  var query = new google.gdata.calendar.CalendarEventQuery(calendarUrl);
  query.setOrderBy('starttime');
  query.setSortOrder('ascending');
  query.setFutureEvents(true);
  query.setSingleEvents(true);
  query.setMaxResults(10);

  service.getEventsFeed(query, listEvents, handleGDError);
}

/**
 * Callback function for the Google data JS client library to call when an error
 * occurs during the retrieval of the feed.  Details available depend partly
 * on the web browser, but this shows a few basic examples. In the case of
 * a privileged environment using ClientLogin authentication, there may also
 * be an e.type attribute in some cases.
 *
 * @param {Error} e is an instance of an Error 
 */
function handleGDError(e) {
  document.getElementById('jsSourceFinal').setAttribute('style', 
      'display:none');
  if (e instanceof Error) {
    /* alert with the error line number, file and message */
    alert('Error at line ' + e.lineNumber +
          ' in ' + e.fileName + '\n' +
          'Message: ' + e.message);
    /* if available, output HTTP error code and status text */
    if (e.cause) {
      var status = e.cause.status;
      var statusText = e.cause.statusText;
      alert('Root cause: HTTP error ' + status + ' with status text of: ' + 
            statusText);
    }
  } else {
    alert(e.toString());
  }
}

/**
 * Callback function for the Google data JS client library to call with a feed 
 * of events retrieved.
 *
 * Creates an unordered list of events in a human-readable form.  This list of
 * events is added into a div called 'events'.  The title for the calendar is
 * placed in a div called 'calendarTitle'
 *
 * @param {json} feedRoot is the root of the feed, containing all entries 
 */ 
function listEvents(feedRoot) {
	 
  var entries = feedRoot.feed.getEntries();

  /* loop through each event in the feed */
  var len = entries.length;
  for (var i = 0; i < len; i++) {
    var entry = entries[i];
    
    
    var title = entry.getTitle().getText();
    var content = entry.getContent().getText();
    var startDateTime = null;
    var startJSDate = null;
    var times = entry.getTimes();
    if (times.length > 0) {
      startDateTime = times[0].getStartTime();
      startJSDate = startDateTime.getDate();
    }
   
    var endDateTime = null;
    var endJSDate = null;
    var times = entry.getTimes();
    if (times.length > 0) {
      endDateTime = times[0].getEndTime();
      endJSDate = startDateTime.getDate();
    }
    
    var listItem = addListItem(title,startJSDate,endJSDate)
    
    $('.eventList').append(listItem);
    
    events[title]=entry;
    
    //alert(events[title].getTitle().getText())
  }
  
}

function loadEvent(title)
{
	key = title;
	$('#modalLink').click();
}

function forMatTimeMM(sdate, edate)
{
	var pieces = dateTime.getDatePieces(sdate);
	var hour = pieces.hours;
	var min = pieces.minutes;
	var amPm = pieces.amPm;
	var start = hour + ":" + min + " " + amPm;
	
	
		
	pieces = dateTime.getDatePieces(edate);
	hour = pieces.hours;
	min = pieces.minutes;
	amPm = pieces.amPm;
	var end = hour + ":" + min + " " + amPm;
	
	if(start == end)
		return start;
    else
    	return start + " - " + end; 
			
	
}

google.setOnLoadCallback(init);

