/*
 * FullCalendar v1.5.2 Google Calendar Plugin
 *
 * Copyright (c) 2011 Adam Shaw
 * Dual licensed under the MIT and GPL licenses, located in
 * MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
 *
 * Date: Sun Aug 21 22:06:09 2011 -0700
 *
 */
 
 
 
(function($) {


function krEncodeEntities(s){
                return $("<div/>").text(s).html();
        }
        function krDencodeEntities(s){
                return $("<div/>").html(s).text();
        }
		
		
function htmlEscape(s) {
	return s.replace(/&/g, '&amp;')
		//.replace(/</g, '&lt;')
		//.replace(/>/g, '&gt;')
		//.replace(/'/g, '&#039;')
		//.replace(/"/g, '&quot;')
		.replace(/\n/g, '<br />');
}

var fc = $.fullCalendar;
var formatDate = fc.formatDate;
var parseISO8601 = fc.parseISO8601;
var addDays = fc.addDays;
var applyAll = fc.applyAll;


fc.sourceNormalizers.push(function(sourceOptions) {
	if (sourceOptions.dataType == 'gcal' ||
		sourceOptions.dataType === undefined &&
		(sourceOptions.url || '').match(/^(http|https):\/\/www.google.com\/calendar\/feeds\//)) {
			sourceOptions.dataType = 'gcal';
			if (sourceOptions.editable === undefined) {
				sourceOptions.editable = false;
			}
		}
});


fc.sourceFetchers.push(function(sourceOptions, start, end) {
	if (sourceOptions.dataType == 'gcal') {
		return transformOptions(sourceOptions, start, end);
	}
});


function transformOptions(sourceOptions, start, end) {
//alert("Sheela: " + "This is from transform options...");
	var success = sourceOptions.success;
	var data = $.extend({}, sourceOptions.data || {}, {
		'start-min': formatDate(start, 'u'),
		'start-max': formatDate(end, 'u'),
		'singleevents': true,
		'max-results': 9999
	});
	
	var ctz = sourceOptions.currentTimezone;
	if (ctz) {
		data.ctz = ctz = ctz.replace(' ', '_');
	}

	return $.extend({}, sourceOptions, {
		url: sourceOptions.url.replace(/\/basic$/, '/full') + '?alt=json-in-script&callback=?',
		dataType: 'jsonp',
		data: data,
		startParam: false,
		endParam: false,
		success: function(data) {
			var events = [];
			if (data.feed.entry) {
				
				
				/* sheela code - updated the events array so that it holds the formatted date and time info */
				
				$.each(data.feed.entry, function(i, entry) {
					var startStr = entry['gd$when'][0]['startTime'];
					var start = parseISO8601(startStr, false); //SHEELA - IMP***** This has to be set to be false to consider time zones if not dates will be displayed with an offset ******/
					var end = parseISO8601(entry['gd$when'][0]['endTime'], false); //SHEELA - IMP***** This has to be set to be false to consider time zones if not dates will be displayed with an offset ******/
					var allDay = startStr.indexOf('T') == -1;
					
					//alert("Start str: " + startStr + ", " + start);
					
					/* start: sheela - formatting date and time */
					var regex1 = /([a-zA-Z]+)\s([a-zA-Z]+)\s(\d+)\s(\d+)/gi; //regex to match the day and the date
					var regexTime = /(\d+):(\d+)/gi; //regex to match time
					var timeFormatted = regexTime.exec(start);
					
					//converting 24-hour date format to 12-hour format
					/*if(timeFormatted[1] > 12){
						timeFormatted[1] = timeFormatted[1] - 12;
					}*/
					
					if(timeFormatted[1] >= 12){
						if(timeFormatted[1] > 12){
							timeFormatted[1] = timeFormatted[1] - 12;
						}
						timeFormatted[0] = timeFormatted[1] + ":" + timeFormatted[2] + "pm";
					}
					else{
						timeFormatted[0] += "am";
					}
						//alert(timeFormatted);

					var startFormatted = regex1.exec(start)[0] + "@" + timeFormatted[0];
					//var matchj = regexj.exec(events[j].start);
					/* end: sheela - formatting date and time */
					
					var url;
					$.each(entry.link, function(i, link) {
						if (link.type == 'text/html') {
							url = link.href;
							if (ctz) {
								url += (url.indexOf('?') == -1 ? '?' : '&') + 'ctz=' + ctz;
							}
						}
					});
					if (allDay) {
						addDays(end, -1); // make inclusive
					}
					
					//alert("Sheela-Before: " + entry['content']['$t']);
					events.push({
						id: entry['gCal$uid']['value'],
						title: entry['title']['$t'],
						url: url,
						start: start,
						end: end,
						allDay: allDay,
						location: entry['gd$where'][0]['valueString'],
						dateTimeInfo: startFormatted, //sheela - pushing the formatted date into the events array
						description: htmlEscape(entry['content']['$t']) //***VERY IMP***don't remove htmlEscape -- if this is removed the formatting of the description will be gone and the content will be displayed as one single block of content****/
					});
					
					//alert("Sheela-After: " + htmlEscape(entry['content']['$t']));
					
					//alert("time is: " + start);
					
					
					////alert("This is events: " + events.id +", " + events.title + ", " + events.url + ", " + events.start + ", " + events.end + ", " + events.allDay + ", " + events.location + ", " + events.description + ", " + entry['content']['$t']);
					////alert("myObject is " + events.toSource());
					
					
				});
				
				/* sheela code starts here - for grouping calendar events of a single day  is done here*/
				
				var msg = '';
				var temp=[];
				for(var i=0; i<events.length; ++i)
				{
					////alert(events[i].start);
					for(var j=i+1; j<events.length; ++j){
						var regexi = /([a-zA-Z]+)\s(\d+)\s(\d+)/gi;
						var regexj = /([a-zA-Z]+)\s(\d+)\s(\d+)/gi;

						var matchi = regexi.exec(events[i].start);
						//alert("match i: " + matchi[0]);
						var matchj = regexj.exec(events[j].start);
						//alert("match j: " + matchj[0]);
						
						//var start1 = '';
						if((i != j) && (matchi[0] == matchj[0]))
						{
							////alert(matchj);
							////alert("Equal = " + i + "," + j + "::" + matchi[0] + "," + matchj[0]);
							temp.push(j);
							events[i].title += "<hr>" + events[j].title;
							events[i].description += "<br>-------------<br>" + events[j].title + "<br>" + events[j].description;
							//var start1 += events[i].start.toString();
							//var start2 = events[j].start.toString();
							//events[i].start 
							//events[i].start = events[i].start.toString();
							//events[i].start += events[i].start.toString() + "------" + events[j].start.toString();
							events[i].dateTimeInfo += "<hr>" + events[i].dateTimeInfo;
							events[i].location += "<hr>" + events[j].location;
							
							//events.splice(j,1);
						}
						
					}
				}
				
				//alert("Before splice: " + events.length + ", " + temp);
				events1 = [];
				for(var i=0; i<events.length; ++i)
				{
					var matches = 0;
					for(var j=0;j<temp.length;++j){
						if(i == temp[j]){
							++matches;
						}
					}
					if(!matches){
						events1.push(events[i]);
					}
				}
				events = events1;
				//$.each(events, function(i, ev){

					//msg += ev.start + "\n";
					////alert(ev.start + ", " + ev.description);
										//});
				////alert(msg);
				/* sheela code ends here */
			}
			var args = [events].concat(Array.prototype.slice.call(arguments, 1));

			var res = applyAll(success, this, args);
			if ($.isArray(res)) {
				return res;
			}
			return events;
		}
	});
	
}


// legacy
fc.gcalFeed = function(url, sourceOptions) {
	return $.extend({}, sourceOptions, { url: url, dataType: 'gcal' });
};


})(jQuery);

