var selectedAttendee = null;

function closePopup()
{
	if($('#Calendar').data("qtip"))
	{
		$(".qtip-contentWrapper").unblock();
		$('#Calendar').qtip("hide");
	}
}

function startEditCalendar(context, params)
{
	perform_binds(context, params);
	$(context).data('id', params['fullId']);
	if($('#caledit_allday', context).attr('checked'))
	{
		$('#caledit_allday', context).trigger('change');
	}
	
	$("#caledit_alertType", context).trigger('change');
	$('#repeat_freqency', context).trigger('change');
	$('#end_type', context).trigger('change');
	
	$('#caledit_startdate', context).datepicker(
	{
		showStatus: true, 
		rangeSelect: false, 
		defaultDate: 'today',
		dateFormat: 'yy-mm-dd',
		yearRange: '-10:+100',
		beforeShow: function(input, inst) { $('#ui-datepicker-div').css('z-index', 9000); },
		onSelect: function(dateText, inst) 
		{
			$('#caledit_enddate').datepicker( "option", "minDate", new Date($(this).val()) );
			if($('#caledit_allday').attr('checked'))
			{
				$('#caledit_allday').trigger('change');
			}
			checkTime();
		}

	});

	$('#caledit_enddate', context).datepicker(
	{
		showStatus: true, 
		rangeSelect: false, 
		defaultDate: 'today',
		dateFormat: 'yy-mm-dd',
		yearRange: '-10:+100',
		minDate: new Date($('#caledit_startdate', context).val()),
		beforeShow: function(input, inst) { $('#ui-datepicker-div').css('z-index', 9000); },
		onSelect: function(dateText, inst)
		{
			checkTime();
		}
	});
	
	$('#caledit_endbydate', context).datepicker(
	{
		showStatus: true, 
		rangeSelect: false, 
		defaultDate: 'today',
		dateFormat: 'yy-mm-dd',
		yearRange: '-10:+100',
		minDate: new Date($('#caledit_startdate', context).val()),
		beforeShow: function(input, inst) { $('#ui-datepicker-div').css('z-index', 9000); }
	});
}

function syncCals(startDate, endDate)
{
	if (	startDate === null 
		|| 	endDate === null)
	{
		return false;
	}

	$("#caledit_startdate").val(startDate.getFullYear() + "-" + (startDate.getMonth() + 1) + "-" + startDate.getDate());
	$("#caledit_enddate").val(endDate.getFullYear() + "-" + (endDate.getMonth() + 1) + "-" + endDate.getDate());
}

function saveAndExit(context, exit, popup)
{
	if (exit)
	{
		closePopup();
		return false;
	}
	$(".qtip-contentWrapper").block({ message: "<div id='loading-text'><span class='loading'></span></div>", overlayCSS: {backgroundColor: 'transparent', opacity: 0.4}, css: {backgroundColor: 'transparent',color: '#575757',border: '0'} });
	
	// ** start date ** //
	var startDate = new Date();
	indate = $("#caledit_startdate", context).attr("value").split("-");
	startDate.setUTCFullYear(indate[0], indate[1] - 1, indate[2]);
	startDate.setUTCHours($("#caledit_starthour", context).attr("value"), $("#caledit_startminute", context).attr("value"),0,0);

	// ** end date ** //
	var endDate = new Date();
	indate = $("#caledit_enddate", context).attr("value").split("-");
	endDate.setUTCFullYear(indate[0], indate[1] - 1, indate[2]);
	endDate.setUTCHours($("#caledit_endhour", context).attr("value"), $("#caledit_endminute", context).attr("value"),0,0);

	var params = {
		func: 'updatecal',
		id: $(context).data('id'),
		RecurrenceType: $("#repeat_freqency", context).val(),
		DateStart: Math.round(startDate.getTime() / 1000),
		DateEnd: Math.round(endDate.getTime() / 1000),
		relative_href: relativeHref,
		allday : $("#caledit_allday", context).attr("checked"),
		Category: $("#caledit_category", context).attr("value"),
		availablity: $("#caledit_availablity", context).attr("value"),
		alertTrigger: $("#caledit_alert", context).attr("value"),
		alertType: $("#caledit_alertType", context).attr("value"),
		alertPosition: $("#caledit_alertposition", context).attr("value"),
		timezone: $('#TimeZone', context).attr('value'),
		attendees: $('#attendeesInput', context).attr('value')
	};

	if (params['RecurrenceType'] > 0)
	{
		params['recurrenceEndType'] = $("#end_type", context).val();
		params['recurrenceEndByDate'] = $('#caledit_endbydate', context).val();
		params['recurrenceEndAfterX'] = $("input[name=end_after_occurrences]", context).val();
	}

	var title = $(".EventName", context).attr("value");
	if (title != "" || title != "New Event" || $(".EventName", context).data('modified'))
	{
		params['Title'] = title;
	}
	
	var location = $(".EventLocation", context).attr("value");
	if (location != "" || $(".EventLocation", context).data('modified'))
	{
		params['Location'] = location;
	}

	var details = $("#caledit_message", context).attr("value");
	if (details != "" || $("#caledit_message", context).data('modified'))
	{
		params['CalMessage'] = details;
	}
	attendeesString = $("#attendeesInput", context).attr("value")
	$.ajax(
	{
		type	: "POST",
		cache	: false,
		url		: siteBaseUrl + "index.php/mail/calendar/caldavglue",
		data	: params,
		complete: function(XMLHttpRequest, textstatus)
		{
			if (XMLHttpRequest.readyState == 4)
			{
				var ReturnData = XMLHttpRequest.responseXML;
				if (ReturnData && ReturnData.getElementsByTagName("Error"))
				{
					closePopup();
					$("#calendarInside").fullCalendar("refetchEvents");
					$("#eventsListBox", '#Calendar').data('quickview').refresh();

					if(params['alertType'] != 'None')
					{
						// update the alarms
						$.php(siteBaseUrl + "index.php/mail/calendar/alarms");
					}
				}
				
				//If saving was successful then also update attendees if any
				//Fetch Attendees
				$.ajax(
				{
					type	: "POST",
					cache	: false,
					cache:false, 
					url: siteBaseUrl + "index.php/mail/calendar/setattendees",
					data: {"id" : params.id , "href" : params.relative_href, "attendees" : attendeesString }, 
					dataType: 'json', 
					success: function(r) { if(r.message != undefined) if( r.message && r.message.length > 0 ) alert(r.message); }

				})
			}
		}
	});
}

function deleteEvent(fullId)
{
	var postData = {
		func: 'delete',
		id: fullId,
		relative_href: relativeHref
	};
	var startDate = new Date();
	indate = $("#caledit_startdate").attr("value").split("-");
	startDate.setUTCFullYear(indate[0], indate[1] - 1, indate[2]);

	$('#' + fullId, '#calendarInside', '#Calendar').hide();
	closePopup();

	$.ajax(
	{
		type	: "POST",
		cache	: false,
		url		: siteBaseUrl + "index.php/mail/calendar/caldavglue",
		data	: postData,
		complete: function(XMLHttpRequest, textstatus)
		{
			if (XMLHttpRequest.readyState == 4)
			{
				var ReturnData = XMLHttpRequest.responseXML;
				if (ReturnData && ReturnData.getElementsByTagName("Error"))
				{
					$("#miniCalendar", '#Calendar').monthCal("removeEventHint", startDate);
					$("#miniCalendar", '#Calendar').monthCal("renderEventHints");

					$("#calendarInside").fullCalendar("refetchEvents");
					$("#eventsListBox", '#Calendar').data('quickview').remove({id: fullId});

				}
			}
		}
	});
}

function checkTime()
{
	// make sure the events finish time is at least +1 min from start

	if(	$('#caledit_startdate').val() == $('#caledit_enddate').val() )
	{
		if( parseInt($('#caledit_starthour').val()) > parseInt($('#caledit_endhour').val()))
		{
			$('#caledit_endhour').val($('#caledit_starthour').val());
		}
		if (parseInt($('#caledit_starthour').val()) == parseInt($('#caledit_endhour').val()))
		{
			if( parseInt($('#caledit_startminute').val()) > parseInt($('#caledit_endminute').val()))
			{
				var newVal = parseInt($('#caledit_startminute').val());
				var newHour = parseInt($('#caledit_endhour').val());
				if(newVal == 59)
				{
					newHour ++;
					newVal = 0;
				}
				else
				{
					newVal ++;
				}
				$('#caledit_endminute').val(newVal);
				$('#caledit_endhour').val(newHour);
			}
		}
	}
}

function perform_binds(context, in_params)
{
	var params = in_params;
	
	$('.EventName', context).data('OriginalText', $('.EventName').val());
	$('.EventName', context).bind('focus', function() { $(this).select() });
	$('.EventName', context).bind('change', function() { if ($(this).text() != $(this).data('OriginalText')) $(this).data('modified', true); });

	$('.EventLocation', context).data('OriginalText', $('.EventLocation').val());
	$('.EventLocation', context).bind('focus', function() { $(this).select() });
	$('.EventLocation', context).bind('change', function() { if ($(this).val() != $(this).data('OriginalText')) $(this).data('modified', true); });

	$('#caledit_message', context).data('OriginalText', $('#caledit_message').val());
	$('#caledit_message', context).bind('focus', function() { $(this).select() });
	$('#caledit_message', context).bind('change', function() { if ($(this).val() != $(this).data('OriginalText')) $(this).data('modified', true); });
	$('#caledit_starthour', context).bind('change', checkTime);
	$('#caledit_endhour', context).bind('change', checkTime);
	$('#caledit_startminute', context).bind('change', checkTime);
	$('#caledit_endminute', context).bind('change', checkTime);

	$('#caledit_allday', context).bind('change', function()
	{
		if($(this).attr('checked'))
		{
			$("#caledit_starthour option[value='0']", context).attr('selected', 'selected');
			$('#caledit_starthour', context).disable();
			$("#caledit_startminute option[value='0']", context).attr('selected', 'selected');
			$('#caledit_startminute', context).disable();
			$("#caledit_endhour option[value='0']", context).attr('selected', 'selected');
			$('#caledit_endhour', context).disable();
			$("#caledit_endminute option[value='0']", context).attr('selected', 'selected');
			$('#caledit_endminute', context).disable();
			if($('#caledit_startdate').val() == $('#caledit_enddate').val())
			{
				var newDate = new Date();
				newDate.setDate( $('#caledit_startdate').datepicker('getDate').getDate() + 1);				
				$('#caledit_enddate').datepicker('setDate', newDate);
			}
		}
		else
		{
			$('#caledit_starthour', context).attr('disabled', '').css('opacity', '');
			$('#caledit_startminute', context).attr('disabled', '').css('opacity', '');
			$('#caledit_endhour', context).attr('disabled', '').css('opacity', '');
			$('#caledit_endminute', context).attr('disabled', '').css('opacity', '');
			$('#caledit_enddate').datepicker('setDate', $('#caledit_startdate').datepicker('getDate'));
			$("#caledit_starthour", context).val(9);
			$("#caledit_startminute", context).val(0);
			$("#caledit_endhour", context).val(10);
			$("#caledit_endminute", context).val(0);
		}
	});
	$('#caledit_alertType', context).bind('change', function()
	{
		var alertType = $(this).val();
		var originalAlertType = params['alertType'] != undefined ? params['alertType'] : 'None';
		if(alertType == "Date")
		{
			$('#caledit_alert', context).removeClass('caledit_alert_num');
			// enable date mode
			if(!$('#caledit_alert', context).is('datepicker'))
			{
				$('#caledit_alert', context).addClass('datepicker');
				$('#caledit_alert', context).enable( function() { } );
			//$('#caledit_alert', context).css('opacity', '');		
				$('#caledit_alert', context).datepicker(
				{
						showStatus: true,
						initStatus: 'fieldBoxEndDate',
						rangeSelect: false,
						defaultDate: "today",
						dateFormat: 'yy-mm-dd',
						yearRange: '-10:+100',
						beforeShow: function() { $('#ui-datepicker-div').css('z-index', 9000); }
				});
			}
			if(originalAlertType == "Date")
			{
				$('#caledit_alert').val((params['alertTrigger'] == 0 ? 15 : params['alertTrigger']));
			}
			else
			{
				// use the current time +1 hour
				$('#caledit_alert').val(params['nowdate']);
			}
			$('#caledit_alertposition', context).hide();
		}
		else if (alertType == "None")
		{
			$('#caledit_alert', context).addClass('caledit_alert_num');

			// nothing selected
			$('#caledit_alert', context).removeClass('datepicker');
			$('#caledit_alert', context).val("15").disable();
			$('#caledit_alert', context).datepicker('destroy');
			$('#caledit_alertposition', context).hide();
			$('#caledit_alarmtime', context).css('display', 'none');
		}
		else
		{
			$('#caledit_alert', context).addClass('caledit_alert_num');

			// time mode
			if(originalAlertType == "Date" || originalAlertType == "None")
			{
				$('#caledit_alert', context).val("15");
			}
			else
			{
				if(params['alertTrigger'] == "")
				{
					$('#caledit_alert').val("15");
				}
				else
				{
					$('#caledit_alert').val(params['alertTrigger']);
				}
			}
			$('#caledit_alert', context).removeClass('datepicker');
			$('#caledit_alert', context).attr('disabled', '');
			$('#caledit_alert', context).css('opacity', '');
			$('#caledit_alert', context).datepicker('destroy');
			$("#caledit_alertposition option[value='" + params['alertPosition'] + "']", context).attr('selected', 'selected');
			$('#caledit_alertposition', context).show();
			$('#caledit_alarmtime', context).css('display', 'none');
		}

	});

	$('#end_type', context).bind('change', function()
	{
		switch(parseInt($(this).val()))
		{
		case 0:
			{
				$('#end_after', context).hide();
				$('#end_by', context).hide();
			} break;
		case 1:
			{
				$('#end_after', context).show();		
				$('#end_by', context).hide();
			} break;
		case 2:
			{
				$('#end_after', context).hide();
				$('#end_by', context).show();
			} break;
		}
	});
	$('#repeat_freqency', context).bind('change', function()
	{
		switch(parseInt($(this).val()))
		{
			case 0 :
			{
				$('#end_type', context).val(0);
				$('#end_type', context).trigger('change');
				$('#end_type', context).disable();
			}
			break;
			case 10 :
			case 11 :
			case 12 :
			case 13 :
			{
				$('#end_type', context).enable( function () { $(this).trigger('change'); } );
			}
			break;
		}
	});
}
