<div id="mobile_calendar" data-role="page">

	<div data-role="header"	data-inset="true" data-position="fixed">
        <a class="btn-back" href="#"  data-transition="slide" data-rel="back">Back</a>
		<h1>Events</h1>
		<a href="#mobile_calendarcreate" class ="cal-button-add" data-transition="slide">&nbsp;</a>
	</div>

	<div data-role="content" data-inset="true">

		<ul	id="list_events" data-role="listview" data-split-theme="c">
		</ul>
		
		<div id="no_calendar"><p>No Calendar Events - Add by clicking the [+]</p></div>
		
	</div>


</div>


<script	type="text/javascript">
	var	calendar = {

		calendarhref : null,
		data : [],
		dataIndex : {},
		
		deleteId : function(id) {
			var index = this.dataIndex[id];
			
			if(index >= 0) {
				this.data.splice(index, 1);
			}
			
			delete this.dataIndex[id];
			
			this.render();
		},		

		list : function(isRevert) {

			this.loadData( function() {

				$.mobile.changePage('#mobile_calendar',	{transition:'slide', revert:isRevert});

			});

		},

		isDataValid : function() {
			return (this.data instanceof Array) && (this.data.length);
		},

		buildListData :	function() {

			var	listData = [];

			if(! this.isDataValid()	) {
				return listData;
			}

			var data = this.data;

			var	item = data[0];

			listData.push( {
				'date' : item.startDateTime.format('yyyy-mm-dd'),
				'event'	: [item]
			});

			this.dataIndex[item.id] = 0;

			for(var	i=1; i<data.length;	++i) {

				item = data[i];

				this.dataIndex[item.id] = i;

				var	lastNode = listData[listData.length-1];
				if(	item.startDateTime.format('yyyy-mm-dd') === lastNode.date	) {
					lastNode.event.push(item);
				}
				else {
					listData.push( {
						'date' : item.startDateTime.format('yyyy-mm-dd'),
						'event'	: [item]
					});
				}
			}

		    return listData;

		}, 

		showDetail : function(index) {

			calendarView.data = this.data[index];

			$.mobile.changePage('#mobile_calendardetail', {transition:'slide'});

		},
		
		parseDateTime : function(caldavDateTimeString) {
			date = caldavDateTimeString.split('T')[0];
			time = caldavDateTimeString.split('T')[1];
			
		
			var dateParts = date.split('-');
			var timeParts = time.split(':');
			
			var dt = new Date(dateParts[0], dateParts[1]-1, dateParts[2], timeParts[0], timeParts[1]);
			return dt;
		
		},		

		putHeader : function(item, $parent) {
		
			var $node = $('.cal-divider', '#template_calendar_list').clone(true);
			
			var date = item.startDateTime;
			
			var now = new Date;
			var dayString = date.format('dd/mm/yyyy') === now.format('dd/mm/yyyy')? date.format('ddd')+' - Today' : date.format('ddd');

			$('.cal-event-date', $node).html(date.format('dd/mm/yyyy'));
			$('.cal-event-day', $node).html(dayString);

			$parent.append($node).listview('refresh');
		},

		putItem : function(item, $parent) {
			var $node = $('.cal-item', '#template_calendar_list').clone(true);
			
			$('.cal-event-time', $node).html( item.startDateTime.format('h:mm TT') );
			$('.cal-event-name', $node).html( item.title );

			$node.attr('event-id', item.id);

			$node.bind('click', function(e) {
				var id=$(this).attr('event-id');
				var index = calendar.dataIndex[id];
				calendar.showDetail(index);
			});

			$parent.append($node).listview('refresh');

		},

		render : function()	{
		
			$('#no_calendar').hide();
			
			var $parent = $('#list_events');
			$parent.empty();
			
			if(! this.isDataValid() ) {
				$('#no_calendar').show();
				return;
			}

			var datalist = this.buildListData();

			for(var i=0; i<datalist.length; ++i) {
				
				this.putHeader(datalist[i].event[0], $parent);

				for(var j=0; j<datalist[i].event.length; ++j) {

					this.putItem(datalist[i].event[j], $parent);

				}

			}

		},

		loadData : function( callback ) {
		
			var param = {
				calendarhref : calendars.getCurHref(),
				extended : true
			}
			
			$mobile.listCalendar( param, function(res) {
				if(res instanceof Array) {

					res = res.sort(function(a,b) {
					
						return a.start > b.start;

					});
					
					for(var i=0; i<res.length; ++i) {
						res[i].startDateTime = calendar.parseDateTime( res[i].start );
						res[i].endDateTime = calendar.parseDateTime( res[i].end );
						delete res[i].start;
						delete res[i].end;
					}
					
					calendar.data = res;

					callback && callback();

				}
			});
		},
		
		safeRender : function() {
			if(this.isDataValid()) {
				this.render();
			}
			else {
				this.loadData( function() {
					calendar.render(); 		
				})
			}
		},
		
		toListPage : function() {
			$.mobile.changePage('#mobile_calendar', {transition : 'slide', reverse : true});
		}


	};

	$(document).delegate("#mobile_calendar", "pagebeforeshow", function() {
	
		calendar.safeRender();

	});


</script>
