$(document).ready(function() {
	schedule_jq();
	window.fetch_schedule = fetch_schedule;
	
	$('#ajax_test').click(function() {
		window.fetch_participants();
	});
	
	$("#id_participant_id").change(function() {
		if($(this).val() != 'all') {
			document.participant_filter.submit();
		}else{
			window.location= '/customer/calendar/';
		};
	});
});

// Functions called by other modules
function participant_data(element) {
	var result;
	if(element) {
		/*var li = $(element).parent('li');*/
		var ul = $(element).parents('.participant');
	} else {
		var ul = $('.participant');
	}
	
	if(ul.length == 0) {
		result = null;
	} else {
		result = {
			id: parseInt(ul.children('.id').val())
		};
	}
	return result;
}

function schedule_line_data(element) {
	var props = $(element).parent('.class_information');
	
	var result = {
		id: parseInt(props.children('.class_name').children('.id').val()),
		activity_id: parseInt(props.children('.class_name').children('.activity_id').val()),
		title: props.children('.class_name').children('.title').val(),
		is_pending: props.hasClass('pending'),
		is_waitlist_alternative: props.hasClass('waitlist_alternative'),
		cancellation_policy: props.children('.class_name').children('.cancelation_policy').val(),
		skill_assessment: props.hasClass('skill_assessment')
	};
	
	return result;
}

	
function fetch_schedule(element) {
	//var id = $('#participant_id').val();
	var participant = participant_data();
    $.get('/participant/ajax/schedule/' + participant.id + '/', 
        function(data) {
            $(element).empty(); //.html(data);
            schedule_jq();
            init_tooltips();
        }
    );
	return false;
};

function schedule_refresh_or_error(element, XMLHttpRequest, textStatus) {
	//try {
		data = JSON.decode(XMLHttpRequest.responseText);
		if(data.result != 1) {
			alert(data.result + ' ' + data.error);
		}
		//alert(data.registration_allowed);
		if(data.registration_allowed) {
			// If registration is allowed, show the add to cart button
			$('.add_to_cart').show();
		}
		fetch_schedule(element);
		
		return data;
	//} catch(e){
	//	alert('Error parsing response');
	//}
	return false;
}


function schedule_jq() {
	$('.minimize_link').unbind('click').click(function() {
		var participant = participant_data(this);
		var schedule = $(this).parents('div.participant').find('ul.schedule');
		var data = {
			id: participant.id,
			state: 0
		}
		
		if(schedule.hasClass('hidden')) {
			schedule.removeClass('hidden');
			$(this).removeClass('collapsed');
			$(this).text('Minimize');
			data.state = 0;
		} else {
			schedule.addClass('hidden');
			$(this).addClass('collapsed');
			$(this).text('Expand');
			data.state = 1;
		}
		
		// Save state so it is shown on refresh
		$.ajax({type: 'POST', url: '/participant/ajax/set_collapsed/',
			   data: JSON.encode(data), processData: false, dataType: 'json'});
		
		return false;
	});
	$('.class_manage_link').unbind('click').click(function() {
		var item = schedule_line_data(this);
		var participant = participant_data(this);
		var schedule_element = $(this).parents('div.schedule_wrapper');
		var cancellation_policy = item.cancellation_policy;
		if(cancellation_policy.trim() == '') {
			cancellation_policy = 'You will be subject to the provider\'s cancellation policy.';
		}
		
		thickbox.confirm("You are attempting to cancel a registration.",
			"<div class=\"intro\">Activity provider's cancellation policy:</div>" + cancellation_policy,
			"Are you sure you want to cancel this registration?",
			function(button) {
				switch(button) {
					case 'no_button':
						break;
					case 'yes_button':
						data = JSON.encode({
							participant_id: participant.id,
							id: item.id
						});
						
						$.ajax({type: 'POST', url: '/participant/ajax/remove_registration/',
							data: data, processData: false, dataType: 'json',
							complete: function(XMLHttpRequest, textStatus) {
								window.location.reload();
								//schedule_refresh_or_error(schedule_element, XMLHttpRequest, textStatus);
							}
						});
						break;
				}
			}, ["no_button", "yes_button"], 720, 260);
		
		/*if(item.id > 0 && confirm(lang_msg['CONFIRM_REMOVE_REG'] + "\n\n" + item.title + "\n\n" + lang_msg['NO_UNDO_REG'])) {
		}*/
	});
	
	$('li.cart .delete, li.pending .cancel').unbind('click').click(function() {
		var item = schedule_line_data(this);
		var msg;
		if($(this).hasClass('delete'))
			msg = lang_msg['CONFIRM_REMOVE_CART'];
		else
			msg = lang_msg['CONFIRM_REMOVE_PENDING'];
			
		var schedule_element = $(this).parents('div.participant');
		
		var activity_id = parseInt($('#activity_id').val());
		if(item.id > 0 && confirm(msg + "\n\n" + item.title + "\n\n" + lang_msg['NO_UNDO_CART'])) {
			data = JSON.encode({
				id: item.id
			});
			
			$.ajax({type: 'POST', url: '/shoppingcart/ajax/remove/',
				data: data, processData: false, dataType: 'json',
				complete: function(XMLHttpRequest, textStatus) {
						window.location.reload();
					/*var data = schedule_refresh_or_error(schedule_element, XMLHttpRequest, textStatus);
					if(data && activity_id == parseInt(data['object_id'])) {
						if(data['registration_allowed']) {
							// If registration is allowed, show the add to cart button
							$('.add_to_cart').show();
						}
						$('.activity_added').hide();
					}*/
				}
			});
		}
		
		return false;
	});
	
	if(typeof(cart_jq) != 'undefined')
		cart_jq();
};

/*
This function is used in iframe mode to control the navigation of participants from a select ddown control
*/
function change_participant(location){
	//if going to management of participants, be sure to break the frameset and open a new window.
	if(location == "/customer/participants/"){
		window.open(location,"_blank");
	}else{
		window.location = location;
	}
}
