jQuery(function ($) {
	var container; //jQuery dom element
	var events; 
	var monthNames = ['January','February','March','April','May','June','July','August','September','October','November','December'];
	var popup;
	var now; //use server timestamp if available

	function createPopup(){
		popup = {};
		popup.background = document.createElement("div");
		popup.container = document.createElement("div");
		popup.hd = popup.container.appendChild(document.createElement("div"));
		popup.close = popup.hd.appendChild(document.createElement("span"));
		popup.close.innerHTML = 'close';
		$(popup.close).css('cursor','pointer');
		$(popup.close).click(closePopup);
		popup.title = popup.container.appendChild(document.createElement("div"));
		popup.body = popup.container.appendChild(document.createElement("div"));
		popup.container.setAttribute('id','js-sp-calendar-popup-container');
		popup.hd.setAttribute('id','js-sp-calendar-popup-hd');
		popup.title.setAttribute('id','js-sp-calendar-popup-title');
		popup.body.setAttribute('id','js-sp-calendar-popup-body');
		$(popup.background).css({'opacity':'0','z-index':'1003','position':'fixed','display':'none','top':'0','left':'0','width':'100%','height':'100%','background-color':'black'});
		$(popup.container).css({'z-index':'1005','position':'fixed','display':'none','width':'300px','border':'4px solid #ABCBFC','background-color':'white'});
		$(popup.hd).css({'background-color':'#ABCBFC','text-align':'right'});
		container.css('z-index','1004');
		$("body").append(popup.background);
		$("body").append(popup.container);
		//alternative closing popup
		$(popup.background).click(closePopup);
		//ESC key
		$(document).keypress(function(e){if(e.keyCode == 27 && ($(popup.container).css('display') != 'none'))closePopup();});
		
	}
	function centerPopup(){
		var windowHeight = $(window).height();
		var windowWidth = $(window).width();
		var objectHeight = $(popup.container).height();
		var objectWidth = $(popup.container).width();
		$(popup.container).css({'top':(windowHeight-objectHeight)/2,'left':(windowWidth-objectWidth)/2});
	}
	function closePopup(){
		$(popup.container).hide();
		$(popup.background).fadeTo(400,0,function(){$(popup.background).hide();});
		container.css('position','relative');
	}

	function showEventDetail(e){
		var s = '<div>'+e.data.details +'</div>';
		if(e.data.location) s+= '<div><b>Location</b>: '+e.data.location+'</div>';
		//are we dealing with dates or date+time
		var start = (e.data.when[0].start);
		var end = (e.data.when[0].end);
		var justDatePart = (start.length == 10 && end.length == 10);
		start = parseDateTime(start);
		end = parseDateTime(end);
		var format = function(d){return d.toLocaleDateString();};
		if(justDatePart)end.setDate(end.getDate()-1);
		else format = function(d){return d.toLocaleDateString() + ' ' +d.toLocaleTimeString();};
		s+= '<div><b>'+format(start)+'</b>';
		if(end && end.valueOf() != start.valueOf()){
			if(end.toLocaleDateString() == start.toLocaleDateString()) s+= ' to <b>'+end.toLocaleTimeString()+'</b>';
			else s += ' to <b>'+format(end)+'</b>';
		}
		s+='</div>'; 
		if(!popup)createPopup();
		popup.title.innerHTML = e.data.title;
		popup.body.innerHTML = s;
		centerPopup();
		$(popup.background).show();
		$(popup.background).fadeTo(400,0.7);
		$(popup.container).show();
		container.css('position','absolute');
	}

	//day of month (0-6) %7 = number of empty cells in first row.
	function createCalendarMonth(oStart,oEnd){
		var oToday = new Date(now.toDateString());
		var oDate = new Date(oStart.toDateString());
		var tbody = document.createElement("tbody"),tr,td;
		for(var column = 0,currentMonth = ''; oDate.valueOf() < oEnd.valueOf() || column != 0; column = ++column % 7){
			if(column == 0) tr = tbody.appendChild(document.createElement("tr"));
			if(oDate.getMonth() != currentMonth){
				//complete current row with empty cells
				for( ; column !=0; column = ++column % 7) td = tr.appendChild(document.createElement("td"));
				//write row with month name
				tr = tbody.appendChild(document.createElement("tr"));
				td = tr.appendChild(document.createElement("td"));
				td.setAttribute("class","month");
				td.setAttribute("colspan","7");
				td.appendChild(document.createTextNode(monthNames[oDate.getMonth()]));
				tr = tbody.appendChild(document.createElement("tr"));
				currentMonth = oDate.getMonth();
				//write empty td when month day does not start on 0 (Sunday)
				for( ; column < oDate.getDay(); column = ++column % 7) td = tr.appendChild(document.createElement("td"));
			}
			td = tr.appendChild(document.createElement("td"));
			td.appendChild(document.createTextNode(oDate.getDate()));
			if(oDate.valueOf() < oToday.valueOf()){
				td.setAttribute("class","past");
				var img = td.appendChild(document.createElement("img"));
				img.setAttribute('src','/sites/all/themes/cvusc/images/x.gif');
			}else{
				var evt = events[oDate.toDateString()];
				if(evt){
					td.setAttribute("class","event");
					for(var k = evt.length - 1; k >= 0 ; k--){
						var span = td.appendChild(document.createElement("span"));
						span.appendChild(document.createTextNode(evt[k].title));
						$(span).bind('click',evt[k],showEventDetail);
					}
				}
			}
			oDate.setDate(oDate.getDate()+1);
		}
		return tbody;
	}
	function parseDate(s){
		//"2011-02-03T21:00:00.000-08:00" returned by google
		var a = s.match(/(\d{4})-(\d{2})-(\d{2})(T((\d{2}):(\d{2}):(\d{2})))?/);
		return new Date(a[1],a[2]-1,a[3]);
	}
	function parseDateTime(s){
		//"2011-02-03T21:00:00.000-08:00" returned by google
		var a = s.match(/(\d{4})-(\d{2})-(\d{2})(T((\d{2}):(\d{2}):(\d{2})))?/);
		return (typeof a[6] == 'string')?new Date(a[1],a[2]-1,a[3],a[6],a[7],a[8]):new Date(a[1],a[2]-1,a[3]);
	}
	function processItems(o){
		if(o.error){
			render(o.error.message,'text');
			return;
		}
		var items = o.data.items;
		events = {};
		for(var i=0; i<items.length; i++){
			var key =(parseDate(items[i].when[0].start)).toDateString();
			if(!events[key]) events[key] = [];
			events[key].push(items[i]);
		}
	}

	// get starting date (default 1st of current month)
	function get(){
		var url = 'https://www.google.com/calendar/feeds/cheri.tilley%40gmail.com/public/full-noattendees?v=2&alt=jsonc&orderby=starttime&futureevents=true';
		$.ajax({
			dataType: 'jsonp',
			url: url,
			success: function(data,textStatus,jqXHR){
				window.data = data;
				processItems(data);
				window.evts = events;
				render(data);
			},
			error: function(jqXHR,textStatus,errorThrown){
				render(textStatus,'text');
			}
		});
	}
	// render
	function render(o,type){
		if(type == 'text'){
			container.append(o);
		}else{
			var items = o.data.items;
			var oToday = new Date(now.toString());
			var oEndDate = new Date(now.toString());
			oEndDate.setMonth(oEndDate.getMonth()+1);
			var table = document.createElement("table");
			table.appendChild(createCalendarMonth(oToday,oEndDate));
			container.append(table);
		}
		$('#block-block-12').show();
	}
	if(typeof sp_str_server_date == 'string') now = new Date(sp_str_server_date);
	else now = new Date();
	container = $("#sp-js-calendar");
	if(container) get();
	});
;

