var cancelText = 'Add New';

function customRange(input) {
	minDate = new Date();
	maxDate = null;
	if(input.id == 'event_looseEnd' && $('#event_looseStart').val() != '') minDate = new Date(new Date($("#event_looseStart").val()).getTime());
	else if(input.id == 'tb_event_looseEnd' && $('#tb_event_looseStart').val() != '') minDate = new Date(new Date($("#tb_event_looseStart").val()).getTime());
	if(input.id == 'event_looseStart' && $('#event_looseEnd').val() != '') maxDate = new Date(new Date($('#event_looseEnd').val()).getTime());
	else if(input.id == 'tb_event_looseStart' && $('#tb_event_looseEnd').val() != '') maxDate = new Date(new Date($('#tb_event_looseEnd').val()).getTime());
	return {
		minDate: minDate,
		maxDate: maxDate
	};
}

function formatItem(data) {
	return data[1] + ( data[4]? ' (' + data[4] + ')' : '' ) + '<br />' + data[2] + '<br />' + data[3];
}

function changeFields(event, data, formatted) {
	if(data) {
		$('.step1 #person_id').val(jQuery.trim(data[0]));
		$('.step1 #person_full_name').val(jQuery.trim(data[1]));
		$('.step1 #person_email').val(jQuery.trim(data[2]));
		$('.step1 #person_phone').val(jQuery.trim(data[3]));
		$('.step1 #event_heads').focus();
	}
}

function dropEvent(event, props) {
	$.ajax({
		type: 'post',
		url: '/events/' + $(props.draggable).attr('id') + '/drop_update',
		data: {
			drop_id: $(this).attr("id"),
			qd: "<%= @base_date %>"
		},
		complete: function(data) {
			$('#cal_view').load('/events');
		}
	});
}

function tb_init(domChunk){
	$(domChunk).livequery('click',function(){
		var t = this.title || this.name || null;
		var a = this.href || this.alt;
		var g = this.rel || false;
		tb_show(t,a,g);
		this.blur();
		return false;
	});
}

function updateRange(value) {
	var rangeText = '1 day';
	if(value == '2') rangeText = '7 day';
	else if(value == '3') rangeText = '30 day';
	$('#range').val(rangeText);
}

function translateRange(value) {
	var rangeValue = '1';
	if(value == '7') rangeValue = '2';
	if(value == '30') rangeValue = '3';
	return rangeValue;
}

function resortTable(calendarId) {
	$('#' + calendarId + '_selected_resource_ids').attr('value', '');
	$('#' + calendarId + '_calendar_resource_table tr').each(function() {
		if(this.id != '') $('#' + calendarId + '_selected_resource_ids').attr('value', ($('#' + calendarId + '_selected_resource_ids').attr('value') ? ($('#' + calendarId + '_selected_resource_ids').attr('value') + ',') : '') + this.id.replace('resource_', ''));
	});
	$('#' + calendarId + '_calendar_resource_table tr:odd').removeClass('even').addClass('odd');
	$('#' + calendarId + '_calendar_resource_table tr:even').removeClass('odd').addClass('even');
}

$(document).ready(function() {
	
	$('.step1 #person_full_name').livequery(function() {
		$(this).autocomplete('/people/search?t=n', { formatItem: formatItem }).result(changeFields);
	});
	
	$('.step1 #person_email').livequery(function() {
		$(this).autocomplete('/people/search?t=e', { formatItem: formatItem }).result(changeFields);
	});
	
	$('.step1 #person_phone').livequery(function() {
		$(this).autocomplete('/people/search?t=p', { formatItem: formatItem }).result(changeFields);
	})
	
	$('.datepicker').livequery(function() {
		datepicker = $(this);
		datepicker.datepicker({
			showOn: 'button',
			buttonImage: '/images/calendar.gif',
			buttonImageOnly: true,
			constrainInput: false,
			beforeShow: customRange
		});
		datepicker.parent().append(' ');
		$('<img>').attr({
			src: '../images/clock.gif',
			'class': 'ui-timepicker-trigger'
		}).clockpick({
			starthour: 0,
			endhour: 23,
			valuefield: '#' + datepicker.attr('id')
			// selectTime: function(time) { datepicker.val($('#' + datepicker.attr('id')).val() + ' ' + time); }
		}).appendTo(datepicker.parent());
	});

	$('.nav_datepicker').livequery(function() {
		$(this).datepicker({
			showOn: 'button',
			buttonImage: '/images/calendar.gif',
			buttonImageOnly: true,
			constrainInput: false,
			dateFormat: 'yy-mm-dd',
			onSelect: function(dateText) { $('#change_calendar').submit(); }
		});
	});
	
	$('#change_calendar').livequery(function() {
		$(this).ajaxForm({
			target: '#cal_view',
			beforeSend: function() {
				$('#loadingStatus').show();
			},
			success: function() {
				$('#cal_view').show('slide', {direction: 'down'});
				$('#loadingStatus').hide();
			}
		});
	});
	
	$('#dialog .edit_event').livequery(function() {
		$(this).ajaxForm({
			beforeSend: function() {
				$('#loadingStatus').show();
			},
			success: function(data) {
				if(data.indexOf('<') == -1) {
					$('#dialog').dialog('close');
					window.location = data;
				}
				else {
					$('#dialog').html(data);
					$('#loadingStatus').hide();
				}
			}
		});
	});
	
	$('#dialog').livequery(function() {
		$(this).dialog({
			autoOpen: false,
			resizable: false,
			draggable: false,
			modal: true,
			width: 800,
			height: 450
		});
	});
	
	$('.thickbox').livequery('click', function(event) {
		event.preventDefault();
		var title = $(this).attr('title') ? $(this).attr('title') : 'Resengine';
		var url = $(this).attr('href');
		var dialog = $('<div id="dialog"></div>');
		if($('#dialog').length > 0) dialog = $('#dialog');
		else dialog.insertAfter('#container');
		$.ajax({
			url: url,
			beforeSend: function() {
				$('#loadingStatus').show();
			},
			success: function(data, text) { 
				dialog.html(data).dialog('option', 'title', title).dialog('open');
				$('#loadingStatus').hide();
			}
		});
	});

	$('.panel .step1').livequery(function() {
		$(this).ajaxForm({ target: '.panel' });
	});

	$('#earlier').livequery('click', function(event) {
		event.preventDefault();
	    $.ajax({
			url: $(this).attr('href'),
			beforeSend: function() {
				$('#loadingStatus').show();
			},
			success: function(data, textStatus) {
				$('#cal_view').html(data).show('slide', {direction: 'left'});
				$('#loadingStatus').hide();
			}
		});
	});
	
	$('#later').livequery('click', function(event) {
		event.preventDefault();
	    $.ajax({
			url: $(this).attr('href'),
			beforeSend: function() {
				$('#loadingStatus').show();
			},
			success: function(data, textStatus) {
				$('#cal_view').html(data).show('slide', {direction: 'right'});
				$('#loadingStatus').hide();
			}
		});
	});

	$('.reload').livequery('click', function(event) {
		event.preventDefault();
	    $.ajax({
			url: $(this).attr('href'),
			beforeSend: function() {
				$('#loadingStatus').show();
			},
			success: function(data, textStatus) {
				$('#cal_view').html(data).show('slide', {direction: 'down'});
				$('#loadingStatus').hide();
			}
		});
	});

	$('#calendarRangePicker').livequery(function() {
		$(this).slider({
			min: 1,
			max: 3,
			slide: function(event, ui) {
				updateRange(ui.value);
			},
			stop: function(event, ui) {
				var qv = 1;
				if(ui.value == '2') qv = 7;
				if(ui.value == '3') qv = 30;
				if(qv != $('#initialRange').val()) {
				    $.ajax({
						url: '/calendars/default?qv=' + qv,
						beforeSend: function() {
							$('#loadingStatus').show();
						},
						success: function(data, textStatus) {
							$('#cal_view').html(data).show('slide', {direction: 'down'});
							$('#loadingStatus').hide();
						}
					});
				}
			}
		});
		$(this).slider('value', translateRange($('#initialRange').val()));
		updateRange($(this).slider('value'));
	});
	
	$('#colorselector input:radio').livequery(function() {
		$(this).checkbox({
			cls: 'jquery-color-select',
			empty: '/images/empty.png'
		});
	});

	$('.calendar_resource_table').livequery(function() {
		calendarId = $(this).attr('id').replace('_calendar_resource_table', '');
		$(this).tableDnD({
			dragHandle: 'dragger',
			onDrop: function(table, row) {
				resortTable(calendarId);
			}
		}); 
	});
	
	$('.remove_resource').livequery('click', function(event) {
		event.preventDefault();
		parsedId = $(this).attr('id').replace('remove_resource_', '').split('-');
		removedResource = '#resource_' + parsedId[0];
		$('<option value="' + parsedId[0] + '">' + $(removedResource + ' .title').html() + '</option>').appendTo('#' + parsedId[1] + '_available_resource_ids');
		$(removedResource).remove();
		resortTable(parsedId[1]);
	});
	
	$('.add_resource').livequery('click', function(event) {
		event.preventDefault();
		calendarId = $(this).attr('id').replace('add_resource_', '');
		selectedValue = $('#' + calendarId + '_available_resource_ids option:selected').attr('value');
		selectedHtml = $('#' + calendarId + '_available_resource_ids option:selected').html();
		$('<tr id="resource_' + selectedValue + '" class="resource_' + selectedValue + '"><td class="dragger">&nbsp;</td><td class="title">' + selectedHtml + '</td><td><a href="#" id="remove_resource_' + selectedValue + '-' + calendarId + '" class="remove_resource">x</a></td></tr>').appendTo('#' + calendarId + '_calendar_resource_table');
        $('#' + calendarId + '_available_resource_ids').find('option:selected').remove();
		resortTable(calendarId);
		$('#' + calendarId + '_calendar_resource_table').tableDnD({
			dragHandle: 'dragger',
			onDrop: function(table, row) {
				resortTable(calendarId);
			}
		}); 
	});

	$('#group_table').livequery(function() {
		$(this).tableDnD({
			dragHandle: 'dragger',
			onDrop: function(table, row) {
				var order= $.tableDnD.serialize('id');
				$('#update_success').load('/settings/groups/order?' + order);
				$('#group_table tr:odd').removeClass('even').addClass('odd');
				$('#group_table tr:even').removeClass('odd').addClass('even');
			}
		}); 
	});
	
	$('.groupHeader a').livequery('click', function(event) {
		event.preventDefault();
		new_id = '#' + $(this).attr('id') + '_resources'
		$(new_id).toggle();
	})

	$('.open_panel').livequery('click', function(event) {
		event.preventDefault();
		$('.panel').toggle('blind', function() { $('.panel input:text:first').focus(); });
		if($(this).html() == 'Cancel') {
			$(this).html(cancelText);
			if($('.panel .step2').length > 0) $('.panel').load('/events/new');
			else $('.panel form').resetForm();
		}
		else {
			cancelText = $(this).html();
			$(this).html('Cancel');
		}
	});
 
	$('.open_panel_edit').livequery('click', function(event) {
		event.preventDefault();
		$('.panel').toggle('blind');
		if($(this).html() == 'Cancel') {
			$(this).html('Edit');
			$('.panel form').resetForm();
		}
		else $(this).html('Cancel');
	});
	
	$('.open_panel_edit_person').livequery('click', function(event) {
		event.preventDefault();
		$('.panel_person').toggle('blind');
		if($(this).html() == 'Hide Guest Details') {
			$(this).html('Show Guest Details');
		}
		else $(this).html('Hide Guest Details');
	});
	

	$('#loginTab a').livequery('click', function(event) {
		event.preventDefault();
		$('#loginWrapper').toggle('blind');
		if($(this).html() == 'Cancel') {
			$(this).html('Sign In');
			$('#loginWrapper form').resetForm();
		}
		else $(this).html('Cancel');
	});
	
	$('.pageTipLink, .closePageTip a').livequery('click', function(event) {
		event.preventDefault();
		$('#helpWrapper').toggle('blind');
		if($('.pageTipLink').html() == 'Close Page Tip') {
			$('.pageTipLink').html('Page Tip');
		}
		else $('.pageTipLink').html('Close Page Tip');
	});

	if($.url.param('qh')) $($.url.param('qh')).effect('highlight', {}, 2000);

	if($.browser.msie) {
		$('.roundedBox').livequery(function() { $(this).parent().css('padding', '2px'); });
		$('.roundedTop li h2, .roundedTop li h3').livequery(function() { $(this).corner('8px top').parent().css('padding', '2px 2px 0 2px').corner('10px top'); });
		$('.imageLeft, .imageMiddle, .imageRight').livequery(function() { $(this).parent().css('padding', '6px'); });
	}
	else {
		$('.roundedBox').livequery(function() { $(this).corner('8px').parent().css('padding', '2px').corner('10px'); });
		$('.roundedBottom').livequery(function() { $(this).corner('10px bottom'); });
		$('.roundedTop li h2, .roundedTop li h3').livequery(function() { $(this).corner('8px top').parent().css('padding', '2px 2px 0 2px').corner('10px top'); });
		$('.imageLeft, .imageMiddle, .imageRight').livequery(function() { $(this).parent().css('padding', '6px').corner('10px'); });
	}
	
	$('.reservationTooltip').livequery(function() {
		$(this).hover(function() { $('#reservationTooltip_'+$(this).attr('id')).show(); }, function() { $('#reservationTooltip_'+$(this).attr('id')).hide(); });
	});
	
	if(!$.browser.msie) {
		$('.resourceTooltip').livequery(function() {
			$(this).hover(function() { $('#resourceTooltip_'+$(this).attr('id')).show(); }, function() { $('#resourceTooltip_'+$(this).attr('id')).hide(); });
		}).livequery('click', function(event) {
			event.preventDefault();
		});
	}
	else {
		$('.resourceTooltip').livequery('click', function(event) {
			event.preventDefault();
			var title = $(this).attr('title') ? $(this).attr('title') : 'Resengine';
			var url = $(this).attr('href');
			var dialog = $('<div id="dialog"></div>');
			if($('#dialog').length > 0) dialog = $('#dialog');
			else dialog.insertAfter('#container');
			$.ajax({
				url: url,
				beforeSend: function() {
					$('#loadingStatus').show();
				},
				success: function(data, text) { 
					dialog.html(data).dialog('option', 'title', title).dialog('open');
					$('#loadingStatus').hide();
				}
			});
		});

	}
	
	$('#calendar_access').livequery(function() {
		if($(this).attr('value') != 'Private') $('#public_calendar_details').show();
		else $('#public_calendar_details').hide();
		$(this).change(function() {
			if($(this).attr('value') != 'Private') $('#public_calendar_details').show();
			else $('#public_calendar_details').hide();
		});
	});
	
	$('.newReservation').trigger('click');

});
