var hour_count = 1;
var phone_number_count = 1;

$(document).ready(function() {
	addDeleteLinks($(".hour_delete_link"));
	
	$(".hour_add_link").click(function() {
		var link = $(this);
		var tr = link.parents('tr');
		var tbody = tr.parents('table').children('tbody');
		
		if(tr.attr('id') == 'no_hours') {
			$('#no_hours').fadeOut('fast', function(data) {
				$('#yes_hours').fadeIn('fast');
			});
		}
		
		var row = $('#blank_hour').attr('innerHTML');
		row = row.replace(/blank_/g, '');
		row = row.replace(/new_\D/g, 'new_'+hour_count);
		hour_count++;
		row = '<tr style="display: none;">'+row+'</tr>';
		row = jQuery(row);
		row.appendTo(tbody);
		addDeleteLinks(row.find('.hour_delete_link'));
		row.fadeIn('fast');

		return false;
	});
	
	
	addPhoneDeleteLinks($(".phone_number_delete_link"));
	
	$(".phone_number_add_link").click(function() {
		var link = $(this);
		var tr = link.parents('tr');
		var tbody = tr.parents('table').children('tbody');
		
		if(tr.attr('id') == 'no_phone_numbers') {
			$('#no_phone_numbers').fadeOut('fast', function(data) {
				$('#yes_phone_numbers').fadeIn('fast');
			});
		}
		
		var row = $('#blank_phone_number').attr('innerHTML');
		row = row.replace(/blank_/g, '');
		row = row.replace(/new_\D/g, 'new_'+phone_number_count);
		phone_number_count++;
		row = '<tr style="display: none;">'+row+'</tr>';
		row = jQuery(row);
		row.appendTo(tbody);
		addPhoneDeleteLinks(row.find('.phone_number_delete_link'));
		row.fadeIn('fast');

		return false;
	});
});

function addDeleteLinks(things) {
	things.click(function() {
		var link = $(this);
		var sibs = link.parents('tr').siblings();
		var tbody = link.parents('tbody');
		
		if(confirm("Are you sure you want to do that?")) {
			$.post($(this).attr('href'), null, function(data) {
				if(sibs.length <= 1) {
					$('#yes_hours').fadeOut('fast', function() {
						$('#no_hours').fadeIn('fast');
					});
				}
				link.parents('tr').fadeOut('fast', function(data2) {
					link.parents('tr').remove();
				});
			});
		}
		
		return false;
	});
}

function addPhoneDeleteLinks(things) {
	things.click(function() {
		var link = $(this);
		var sibs = link.parents('tr').siblings();
		var tbody = link.parents('tbody');
		
		if(confirm("Are you sure you want to do that?")) {
			$.post($(this).attr('href'), null, function(data) {
				if(sibs.length <= 1) {
					$('#yes_phone_numbers').fadeOut('fast', function() {
						$('#no_phone_numbers').fadeIn('fast');
					});
				}
				link.parents('tr').fadeOut('fast', function(data2) {
					link.parents('tr').remove();
				});
			});
		}
		
		return false;
	});
}

