var customers_counter = 0;
var opened_windows = {};
if (window.jQuery) {
	$(document).ready(function() {
		// Course booking form
		if ($('#order-compose')) {
			// Admin button 'Add customer'
			if ($('#add-customer')) {
				customers_counter = $('#add-customer').attr('title');
				$('#add-customer').bind('click', function() {
					add_customer();
					return false;
				});
				bind_customer_removal();
			}
		}
		// Course details screen
		if ($('#course-summary')) {
			$('#course-summary .report a').click(function(){
				var width = 800;
				var win_id = $(this).parent().attr('id');
				if (opened_windows[win_id] && opened_windows[win_id].document) {
					opened_windows[win_id].focus();
				} else {
					opened_windows[win_id] = window.open($(this).attr('href'), win_id, 'width='+width+',height=700,scrollbars=yes');
				}
				return false;
			});
		}
	});
}

/**
 * Adds one more 'customer' group on course booking page
 */
function add_customer() {
	var customer_wrapper = $('#course-customers :first');
	var add_customer_url = add_customers_url +'/'+ customers_counter;
	$('#add-customer').parent().addClass('loading');
	$.ajax({
		complete : add_customer_complete,
		success : function(data) {
			$('#course-customers').append(data);
			$('#course-customers > :last').toggle();
			customers_counter++;
			bind_customer_removal();
			$('#course-customers > :last').slideDown();
		},
		url : add_customer_url
	});

}

function add_customer_complete() {
	$('#add-customer').parent().removeClass('loading');
}

function bind_customer_removal() {
	$('#course-customers .customer .remove a').bind('click', function() {
		$(this).parent().parent().slideUp('slow', function() {
			$(this).remove();
		});
		return false;
	});
}