if (self == top) {
	var maxheight = 400;
	var room_limit = 4;
	var room_count = 1;

	var room_1_primary_count = 0;
	var room_1_secondary_count = 0;
	var room_2_primary_count = 0;
	var room_2_secondary_count = 0;
	var room_3_primary_count = 0;
	var room_3_secondary_count = 0;
	var room_4_primary_count = 0;
	var room_4_secondary_count = 0;

	$(document).ready(function(){

	// tabs
		// i am lost as to why this isn't working
		//$("ul.tp_tabs").tabs('.tp_panes .pane');
		//$("ul.tp_tabs").tabs();

		$('ul.tp_tabs li a.1').click(function() {
			$('ul.tp_tabs li a').removeClass('current');
			$(this).addClass('current');
			$('.pane').hide();
			$('.panes .1').show();
			$('#active_tab').val('1');
			tp_update();
			return false;
		});

		$('ul.tp_tabs li a.2').click(function() {
			$('ul.tp_tabs li a').removeClass('current');
			$(this).addClass('current');
			$('.pane').hide();
			$('.panes .2').show();
			$('#active_tab').val('2');
			tp_update();
			return false;
		});

		$('ul.tp_tabs li a.3').click(function() {
			$('ul.tp_tabs li a').removeClass('current');
			$(this).addClass('current');
			$('.pane').hide();
			$('.panes .3').show();
			$('#active_tab').val('3');
			//$('#plan_started').val('1')
			tp_update();
			return false;
	/* 
			if ($('#plan_started').val() == '1') {
				tp_update();
				return false;
			} else {
				// probably a better way to do this, just need to reset all trip plan links' hrefs to their respective ids from #get_started
				$('#plan_started').val('1')
				tp_update();
				window.location.reload();
			}
	*/
		});

		$('ul.tp_tabs li a.4').click(function() {
			$('ul.tp_tabs li a').removeClass('current');
			$(this).addClass('current');
			$('.pane').hide();$('ul.tp_tabs li a').removeClass('current');
			$(this).addClass('current');
			$('.pane').hide();
			$('.panes .3').show();
			$('#active_tab').val('3');
			//$('#plan_started').val('1')
			tp_update();
			$('.panes .4').show();
			$('#active_tab').val('4');
			tp_update();
			return false;
		});

	// show / hide
		$('#view').click(function(){
			if ($(".trip_planner").css('bottom').indexOf('0') != 0 && $('div.panes').is(':visible')) return false;
				$(this).toggleClass("active",0);
				$('.tp_tabs').toggleClass("active_tabs",0);
				$('div.panes').toggle();
				if ($('#view').hasClass('active')) {
					$('#view_hide').val('view');
					//$('#plan_started').val('1')
					tp_update();
					//$('.panes').jScrollPane();
				} else {
					$('#view_hide').val('hide');
					tp_update();
					//$('.panes').jScrollPaneRemove();
				}
			return false;
		});

	// datepicker
		if (self == top) 
			$('.datepicker').datepicker({ minDate: "+1" });
			
			
			
			$("#arrival_date").change(function(){
				$("#departure_date").datepicker( "option", "minDate", $("#arrival_date").datepicker( "getDate" ) );
			})

	// continue buttons
		$('.pane.1 .continue_b').click(function() {
			$('ul.tp_tabs li a.2').click();
			return false;
		});

		$('.pane.2 .continue_b').click(function() {
			$('ul.tp_tabs li a.3').click();
			return false;
		});

		$('.pane.3 .continue_b').click(function() {
			$('ul.tp_tabs li a.4').click();
			return false;
		});


	// update trip plan on every input change
		$('.trip_plan_form input').change(function() {
			tp_update($(this));
		});

	// submit trip plan form
		$('.trip_plan_form').submit(function() {
			return false;
		});

		$('#submit_trip_plan').click(function() {
			submitTripPlan();
			$('#submit_trip_plan').fadeOut(200, function() {
				$('#after_submit').fadeIn(600);
			});
			return false;
		});

	// print trip plan
		$('#trip_plan_print').click(function() {
			printView=window.open('');
			printView.document.write(printHTMLTripPlan());
			printView.print();
			return false;
		});

	// add rooms
		$('.add_room').click(function() {
			room_count++;
			$('#number_of_rooms').val(room_count);
			tp_update();

			return false;
		});

	// remove rooms
		$('.remove_room').click(function() {
			room_count--;
			$('#number_of_rooms').val(room_count);
			tp_update();

			return false;
		});

	// hide N/A dates
		$('.selected_date').each(function() {
			if ($(this).html() == 'N/A') {
				$(this).hide();
			}
		});

	/*
	// get started popup
		$("#new_plan_info_link").fancybox({
			padding: 0,
			frameWidth: 280,
			frameHeight: 1,
			overlayShow: true,
			hideOnOverlayClick: false,
			hideOnContentClick: false,
			callbackOnShow: function() {
				$('#fancy_bg').height($('#fancy_div .add_pop').height() + 20);	// fix drop shadow
			}
		});

	// add items is in request_to_book.tpl custom tag template in order to utilize ezpub vars

	// start now link
		$("#get_started_link").fancybox({
			padding: 0,
			frameWidth: 280,
			frameHeight: 1,
			overlayShow: true,
			hideOnOverlayClick: false,
			hideOnContentClick: false,
			callbackOnShow: function() {
				$('#fancy_div #start_trip_plan').click(function() {
					$('#fancy_close').click();
					$('#view').click();
					return false;
				});
				$('#fancy_bg').height($('#fancy_div .add_pop').height() + 20);	// fix drop shadow
			}
		});
	*/

	// get started
		if ($.cookie('trip_plan')) {
			tp_load();
		} else {
			tp_initialize();
		}

	/*
			// get started popup
			if(		(room_1_primary_count == 0)
				&&	($('#get_started_popup_shown').val() == '0')
				&&	($('#plan_started').val() == '0')
			) {
				$('#get_started_popup_shown').val('1');
			}
	*/

	// open planner on planning your stay page
		if (($('#container').is('.current_node_id_187')) && (!$('a#view').is('.active'))) {	// if trip planner is not open
			$('a#view').click();		// open it
		}

	});
}

function tp_update() {
	tp_save();
	tp_load();
}

function tp_initialize() {
	$('ul.tp_tabs li a.1').click();
	tp_update();
}

function tp_save() {
	$.cookie('trip_plan', $('#trip_plan form.trip_plan_form').serialize(), {'path':'/'});
}

function tp_loadAttempt() {

	// reset trip plan first
	room_1_primary_count = 0;
	room_1_secondary_count = 0;
	room_2_primary_count = 0;
	room_2_secondary_count = 0;
	room_3_primary_count = 0;
	room_3_secondary_count = 0;
	room_4_primary_count = 0;
	room_4_secondary_count = 0;
	room_count = 1;
	

	//var hideElements = '.room, .room_guest_info, .secondary_guest_info, .room_as, .primary_selected_as_nonbookable, .secondary_selected_as_nonbookable, .secondary_selected_as, .secondary_lbl, .room_lbls, .room_sendto, .room_print';
	var hideElements = '.room, .room_guest_info, .secondary_guest_info, .room_as, .secondary_selected_as, .secondary_lbl, .room_lbls, .room_sendto, .room_print, #no_activities';

	$(hideElements).hide();
	$(hideElements, top.document).hide();
	
	$('.added_item', top.document).remove();

	// this is hidden if no activities are selected (end of this function), so assume it's shown first
	$('.pane.3 .right_pane_col', top.document).show();
	$('.pane.3 .left_wide_pane_col', top.document).css({ 'width': '704px' });

	/* start by getting plan from cookie */

	var serializedPlan = decodeURIComponent($.cookie('trip_plan').replace(/\+/g, ' '));	// the (decoded) serialized form stored by tp_save()

	var unserializedPlan = serializedPlan.split('&');		// an array of strings, each one consisting of a key value pair

	var type, room, guest, name, date, price, first_time, second_time, gender;

	var debug = '';

	for (var x=0; x<unserializedPlan.length; x++) {
		var pair = unserializedPlan[x].toString().split('=');

		var key = pair[0];
		var value = pair[1];

		debug += key + ' = ' + value + '<br />';

		var element = "[name=" + key + "]";	// jquery selector

		var ready = false;				// is a single trip item complete (have all necessary fields been processed)?

		var trip_item_info = key.split('_');		// naming convention for trip item form names gives info

		if (($(element, top.document).length > 0)
		&&  (trip_item_info[5] != 'bookable')
		&&  (trip_item_info[5] != 'nonbookable')
		&&  (trip_item_info[5] != 'spaservice')) {	// populate regular form inputs
			$(element, top.document).val(value);
		} else	{					// populate trip planner table
			room = trip_item_info[1];
			guest = trip_item_info[2];
			type = trip_item_info[5];
			if (type == 'spaservice') {
					switch (trip_item_info[4]) {
						case 'name':
							name = value;
							break;
						case 'date':
							date = value;
							break;
						case 'first-time':
							first_time = value;
							break;
						case 'second-time':
							second_time = value;
							break;
						case 'gender':
							gender = value;
							break;
						case 'price':
							price = value;
							ready = true;		// price is the last field, one item is ready
							break;
					}
					if (ready) {					// all values are set for one trip item, add it and reset
						top.addItem(type, room, guest, name, date, price, first_time, second_time, gender);
					}
			} else { // type is bookable or nonbookable
					switch (trip_item_info[4]) {
						case 'name':
							name = value;
							break;
						case 'date':
							date = value;
							break;
						case 'price':
							price = value;
							ready = true;		// price is the last field, one item is ready
							break;
					}
					if (ready) {					// all values are set for one trip item, add it and reset
						top.addItem(type, room, guest, name, date, price);
					}
			}
		}

	}

	switch ($('#active_tab', top.document).val()) {					//restore active tab
		/*
			this is the same functionality as clicking on the tabs, but without tp_update to prevent infinite recursion
		*/
		case '1':
			$('ul.tp_tabs li a', top.document).removeClass('current');
			$('ul.tp_tabs li a.1', top.document).addClass('current');
			$('.pane', top.document).hide();
			$('.panes .1', top.document).show();
			$('#active_tab', top.document).val('1');
			break;
		case '2':
			$('ul.tp_tabs li a', top.document).removeClass('current');
			$('ul.tp_tabs li a.2', top.document).addClass('current');
			$('.pane', top.document).hide();
			$('.panes .2', top.document).show();
			$('#active_tab', top.document).val('2');
			break;
		case '3':
			$('ul.tp_tabs li a', top.document).removeClass('current');
			$('ul.tp_tabs li a.3', top.document).addClass('current');
			$('.pane', top.document).hide();
			$('.panes .3', top.document).show();
			$('#active_tab', top.document).val('3');
			break;
		case '4':
			$('ul.tp_tabs li a', top.document).removeClass('current');
			$('ul.tp_tabs li a.4', top.document).addClass('current');
			$('.pane', top.document).hide();
			$('.panes .4', top.document).show();
			$('#active_tab', top.document).val('4');
			break;
	}
	// show or hide based on previous state
	if (($('#view_hide', top.document).val() == 'view') && (!$('#view', top.document).hasClass('active'))) {	// if last state was open and it's not already open, open it
		$('#view', top.document).click();
	}


	// add room selections
	room_count = parseInt($('#number_of_rooms', top.document).val());
	switch (room_count) {
		case room_limit:
			$('.add_room', top.document).hide();
			$('.remove_room', top.document).show();
			break;
		case 1:
			$('.add_room', top.document).show();
			$('.remove_room', top.document).hide();
			break;
		default:
			$('.add_room', top.document).show();
			$('.remove_room', top.document).show();
			break
	}
	for (var x=1; x<=room_count; x++) {
		// show room selections
		$('#room_' + x, top.document).show();

		// show controls and labels for this room
		$('#room_' + x + '_guest_info', top.document).show();
		$('.room_' + x + '_lbls').show();
		$('.room_' + x + '_lbls', top.document).show();
		$('#room_' + x + '_print', top.document).show();
		$('#room_' + x + '_sendto', top.document).show();
		$('#room_' + x + '_as', top.document).show();

		// show controls and labels for selected guests
		if ($('#room_' + x + '_number_of_guests', top.document).val() == '2 adults') {
			$('#room_' + x + '_guest_info .secondary_guest_info', top.document).show();
			$('#room_' + x + '_as .secondary_selected_as', top.document).show();
			$('.room_' + x + '_lbls .secondary_lbl').show();
			$('.room_' + x + '_lbls .secondary_lbl', top.document).show();
			$('#room_' + x + '_print .secondary_lbl', top.document).show();
			$('#room_' + x + '_sendto .secondary_lbl', top.document).show();
		}

		// update labels
		
		var primary_name = $('#room_' + x + '_primary_first_name', top.document).val() + ' ' + $('#room_' + x + '_primary_last_name', top.document).val();
		var secondary_name = $('#room_' + x + '_secondary_first_name', top.document).val() + ' ' + $('#room_' + x + '_secondary_last_name', top.document).val();

		var primary_count = eval('room_' + x + '_primary_count', top.document);
		var secondary_count = eval('room_' + x + '_secondary_count', top.document);

		var primary_email = $('#room_' + x + '_primary_email', top.document).val();
		var secondary_email = $('#room_' + x + '_secondary_email', top.document).val();

		// fill in name spans
		$('.room_' + x + '_lbls .primary_name').html(primary_name);
		$('.room_' + x + '_lbls .secondary_name').html(secondary_name);
		$('.room_' + x + '_lbls .primary_name', top.document).html(primary_name);
		$('.room_' + x + '_lbls .secondary_name', top.document).html(secondary_name);
		$('#room_' + x + '_print .primary_name', top.document).html(primary_name);
		$('#room_' + x + '_print .secondary_name', top.document).html(secondary_name);
		$('#room_' + x + '_sendto .primary_name', top.document).html(primary_name);
		$('#room_' + x + '_sendto .secondary_name', top.document).html(secondary_name);
		$('#room_' + x + '_as .primary_name', top.document).html(primary_name);
		$('#room_' + x + '_as .secondary_name', top.document).html(secondary_name);

		// fill in count spans
		$('.room_' + x + '_lbls .primary_count').html(primary_count);
		$('.room_' + x + '_lbls .secondary_count').html(secondary_count);
		$('.room_' + x + '_lbls .primary_count', top.document).html(primary_count);
		$('.room_' + x + '_lbls .secondary_count', top.document).html(secondary_count);
		$('#room_' + x + '_print .primary_count', top.document).html(primary_count);
		$('#room_' + x + '_print .secondary_count', top.document).html(secondary_count);
		$('#room_' + x + '_as .primary_count', top.document).html(primary_count);
		$('#room_' + x + '_as .secondary_count', top.document).html(secondary_count);

		// fill in email spans
		$('.room_' + x + '_lbls .primary_email', top.document).html(primary_email);
		$('.room_' + x + '_lbls .secondary_email', top.document).html(secondary_email);
		$('#room_' + x + '_sendto .primary_email', top.document).html(primary_email);
		$('#room_' + x + '_sendto .secondary_email', top.document).html(secondary_email);
		$('#room_' + x + '_as .primary_email', top.document).html(primary_email);
		$('#room_' + x + '_as .secondary_email', top.document).html(secondary_email);
	}

	//$('#trip_plan_debug').html(debug);

	// display 'you haven't selected any activites' message if needed
	if (room_1_primary_count == 0) {
		$('#room_1_as', top.document).hide();
		$('#room_2_as', top.document).hide();
		$('#room_3_as', top.document).hide();
		$('#room_4_as', top.document).hide();
		$('#no_activities', top.document).show();
		$('.pane.3 .right_pane_col', top.document).hide();
		$('.pane.3 .left_wide_pane_col', top.document).css({ 'width': 'auto' });
	}

	// scroll if needed
	$('.panes', top.document).height('auto');
	if ($('.panes', top.document).height() > maxheight) {
		var height = parseInt(maxheight) + 'px';
		$('.panes', top.document).css({'height':height,'overflow-y':'scroll'});
	} else {
		$('.panes', top.document).css({'height':'auto','overflow-y':'hidden'});
	}

	// fix trip_plan_links
	if ($('#room_1_primary_first_name', top.document).val() != '') {
		$('.request_to_book', top.document).each(function(){
			$(this).attr('href', $(this).attr('rel'))
		});
	}

	// hide empty sections
	$('.primary_selected_as, .secondary_selected_as', top.document).each(function() {
		if (!$(this).is('.bookable')) {
			$(this).show();
			if ($(this).find('tr').length < 2) {
				$(this).hide();
			}
		}
	});
}

function tp_load() {

	// reset trip plan first
	room_1_primary_count = 0;
	room_1_secondary_count = 0;
	room_2_primary_count = 0;
	room_2_secondary_count = 0;
	room_3_primary_count = 0;
	room_3_secondary_count = 0;
	room_4_primary_count = 0;
	room_4_secondary_count = 0;
	room_count = 1;
	

	//var hideElements = '.room, .room_guest_info, .secondary_guest_info, .room_as, .primary_selected_as_nonbookable, .secondary_selected_as_nonbookable, .secondary_selected_as, .secondary_lbl, .room_lbls, .room_sendto, .room_print';
	var hideElements = '.room, .room_guest_info, .secondary_guest_info, .room_as, .secondary_selected_as, .secondary_lbl, .room_lbls, .room_sendto, .room_print, #no_activities';

	$(hideElements).hide();
	
	$('.added_item').remove();

	// this is hidden if no activities are selected (end of this function), so assume it's shown first
	$('.pane.3 .right_pane_col').show();
	$('.pane.3 .left_wide_pane_col').css({ 'width': '704px' });

	/* start by getting plan from cookie */

	var serializedPlan = decodeURIComponent($.cookie('trip_plan').replace(/\+/g, ' '));	// the (decoded) serialized form stored by tp_save()

	var unserializedPlan = serializedPlan.split('&');		// an array of strings, each one consisting of a key value pair

	var type, room, guest, name, date, price, first_time, second_time, gender;

	var debug = '';

	for (x=0; x<unserializedPlan.length; x++) {
		var pair = unserializedPlan[x].toString().split('=');

		var key = pair[0];
		var value = pair[1];

		debug += key + ' = ' + value + '<br />';

		var element = "[name=" + key + "]";	// jquery selector

		var ready = false;				// is a single trip item complete (have all necessary fields been processed)?

		var trip_item_info = key.split('_');		// naming convention for trip item form names gives info

		if (($(element).length > 0)
		&&  (trip_item_info[5] != 'bookable')
		&&  (trip_item_info[5] != 'nonbookable')
		&&  (trip_item_info[5] != 'spaservice')) {	// populate regular form inputs
			$(element).val(value);
		} else	{					// populate trip planner table
			room = trip_item_info[1];
			guest = trip_item_info[2];
			type = trip_item_info[5];
			if (type == 'spaservice') {
					switch (trip_item_info[4]) {
						case 'name':
							name = value;
							break;
						case 'date':
							date = value;
							break;
						case 'first-time':
							first_time = value;
							break;
						case 'second-time':
							second_time = value;
							break;
						case 'price':
							price = value;
							break;
						case 'gender':
							gender = value;
							ready = true;		// gender is the last field, one item is ready
							break;
					}
					if (ready) {					// all values are set for one trip item, add it and reset
						addItem(type, room, guest, name, date, price, first_time, second_time, gender);
					}
			} else { // type is bookable or nonbookable
					switch (trip_item_info[4]) {
						case 'name':
							name = value;
							break;
						case 'date':
							date = value;
							break;
						case 'price':
							price = value;
							ready = true;		// price is the last field, one item is ready
							break;
					}
					if (ready) {					// all values are set for one trip item, add it and reset
						addItem(type, room, guest, name, date, price);
					}
			}
		}

	}

	switch ($('#active_tab').val()) {					//restore active tab
		/*
			this is the same functionality as clicking on the tabs, but without tp_update to prevent infinite recursion
		*/
		case '1':
			$('ul.tp_tabs li a').removeClass('current');
			$('ul.tp_tabs li a.1').addClass('current');
			$('.pane').hide();
			$('.panes .1').show();
			$('#active_tab').val('1');
			break;
		case '2':
			$('ul.tp_tabs li a').removeClass('current');
			$('ul.tp_tabs li a.2').addClass('current');
			$('.pane').hide();
			$('.panes .2').show();
			$('#active_tab').val('2');
			break;
		case '3':
			$('ul.tp_tabs li a').removeClass('current');
			$('ul.tp_tabs li a.3').addClass('current');
			$('.pane').hide();
			$('.panes .3').show();
			$('#active_tab').val('3');
			break;
		case '4':
			$('ul.tp_tabs li a').removeClass('current');
			$('ul.tp_tabs li a.4').addClass('current');
			$('.pane').hide();
			$('.panes .4').show();
			$('#active_tab').val('4');
			break;
	}
	// show or hide based on previous state
	if (($('#view_hide').val() == 'view') && (!$('#view').hasClass('active'))) {	// if last state was open and it's not already open, open it
		$('#view').click();
	}


	// add room selections
	room_count = parseInt($('#number_of_rooms').val());
	switch (room_count) {
		case room_limit:
			$('.add_room').hide();
			$('.remove_room').show();
			break;
		case 1:
			$('.add_room').show();
			$('.remove_room').hide();
			break;
		default:
			$('.add_room').show();
			$('.remove_room').show();
			break
	}
	for (x=1; x<=room_count; x++) {
		// show room selections
		$('#room_' + x).show();

		// show controls and labels for this room
		$('#room_' + x + '_guest_info').show();
		$('.room_' + x + '_lbls').show();
		$('#room_' + x + '_print').show();
		$('#room_' + x + '_sendto').show();
		$('#room_' + x + '_as').show();

		// show controls and labels for selected guests
		if ($('#room_' + x + '_number_of_guests').val() == '2 adults') {
			$('#room_' + x + '_guest_info .secondary_guest_info').show();
			$('#room_' + x + '_as .secondary_selected_as').show();
			$('.room_' + x + '_lbls .secondary_lbl').show();
			$('#room_' + x + '_print .secondary_lbl').show();
			$('#room_' + x + '_sendto .secondary_lbl').show();
		}

		// update labels
		
		var primary_name = $('#room_' + x + '_primary_first_name').val() + ' ' + $('#room_' + x + '_primary_last_name').val();
		var secondary_name = $('#room_' + x + '_secondary_first_name').val() + ' ' + $('#room_' + x + '_secondary_last_name').val();

		var primary_count = eval('room_' + x + '_primary_count');
		var secondary_count = eval('room_' + x + '_secondary_count');

		var primary_email = $('#room_' + x + '_primary_email').val();
		var secondary_email = $('#room_' + x + '_secondary_email').val();

		// fill in name spans
		$('.room_' + x + '_lbls .primary_name').html(primary_name);
		$('.room_' + x + '_lbls .secondary_name').html(secondary_name);
		$('#room_' + x + '_print .primary_name').html(primary_name);
		$('#room_' + x + '_print .secondary_name').html(secondary_name);
		$('#room_' + x + '_sendto .primary_name').html(primary_name);
		$('#room_' + x + '_sendto .secondary_name').html(secondary_name);
		$('#room_' + x + '_as .primary_name').html(primary_name);
		$('#room_' + x + '_as .secondary_name').html(secondary_name);

		// fill in count spans
		$('.room_' + x + '_lbls .primary_count').html(primary_count);
		$('.room_' + x + '_lbls .secondary_count').html(secondary_count);
		$('#room_' + x + '_print .primary_count').html(primary_count);
		$('#room_' + x + '_print .secondary_count').html(secondary_count);
		$('#room_' + x + '_as .primary_count').html(primary_count);
		$('#room_' + x + '_as .secondary_count').html(secondary_count);

		// fill in email spans
		$('.room_' + x + '_lbls .primary_email').html(primary_email);
		$('.room_' + x + '_lbls .secondary_email').html(secondary_email);
		$('#room_' + x + '_sendto .primary_email').html(primary_email);
		$('#room_' + x + '_sendto .secondary_email').html(secondary_email);
		$('#room_' + x + '_as .primary_email').html(primary_email);
		$('#room_' + x + '_as .secondary_email').html(secondary_email);
	}

	//$('#trip_plan_debug').html(debug);

	// display 'you haven't selected any activites' message if needed
	if (room_1_primary_count == 0) {
		$('#room_1_as').hide();
		$('#room_2_as').hide();
		$('#room_3_as').hide();
		$('#room_4_as').hide();
		$('#no_activities').show();
		$('.pane.3 .right_pane_col').hide();
		$('.pane.3 .left_wide_pane_col').css({ 'width': 'auto' });
	}

	// scroll if needed
	$('.panes').height('auto');
	if ($('.panes').height() > maxheight) {
		var height = parseInt(maxheight) + 'px';
		$('.panes').css({'height':height,'overflow-y':'scroll'});
	} else {
		$('.panes').css({'height':'auto','overflow-y':'hidden'});
	}

	// fix trip_plan_links
	if ($('#room_1_primary_first_name').val() != '') {
		$('.request_to_book').each(function(){
			$(this).attr('href', $(this).attr('rel'))
		});
	}

	// hide empty sections
	$('.primary_selected_as, .secondary_selected_as').each(function() {
		if (!$(this).is('.bookable')) {
			$(this).show();
			if ($(this).find('tr').length < 2) {
				$(this).hide();
			}
		}
	});
}

function startPlan() {

	$('ul.tp_tabs li a.3').click(function() {
		$.mask.close();
		if ('0win' in top.autoclick) {
			top.autoclick_triggers.push('0win');
			if ('1win' in top.autoclick) top.autoclick_triggers.push('1win');
		}
	});

	return false;
}

function addItem(type, room, guest, name, date, price, first_time, second_time, gender) {
	switch (type) {
		case 'bookable':
			var element = '#room_' + room + '_as .' + guest + '_as.bookable';	// jquery selector
			var before = $(element).html();
			var after = before + printBookableItem(room, guest, name, date, price);
			$(element).html(after);
			break;
		case 'nonbookable':
			var element = '#room_' + room + '_as .' + guest + '_as.nonbookable';	// jquery selector
			var before = $(element).html();
			var after = before + printNonBookableItem(room, guest, name, date, price);
			$(element).html(after);
			break;
		case 'spaservice':
			var element = '#room_' + room + '_as .' + guest + '_as.spaservice';	// jquery selector
			var before = $(element).html();
			var after = before + printSpaServiceItem(room, guest, name, date, price, first_time, second_time, gender);
			$(element).html(after);
			break;
	}


	// add remove items functionality
	$('.remove_item').click(function() {
		var id = $(this).attr('id');
		var trip_item = id.split('_');
		var room = trip_item[0];
		var guest = trip_item[1];
		var count = trip_item[2];
		removeItem(type, room, guest, count);
		return false;
	});
}

function afterAdd() {
	$('#fancy_close').click();
	$('ul.tp_tabs li a.3').click();
	if (!$('#view').hasClass('active')) {
		$('#view').click();
	}
}

function removeItem(type, room, guest, count) {
	switch (type) {
		case 'bookable':
			var element = '#room_' + room + '_as .' + guest + count + 'bookable';	// jquery selector
			break;
		case 'nonbookable':
			var element = '#room_' + room + '_as .' + guest + count + 'nonbookable';	// jquery selector
			break;
		case 'spaservice':
			var element = '#room_' + room + '_as .' + guest + count + 'spaservice';	// jquery selector
			break;
	}

	$(element).fadeOut(400, function() {
		$(this).remove();
		tp_update();
	});
}

function printBookableItem(room, guest, name, date, price) {
	var thiscount;

	eval('room_' + room + '_' + guest + '_count++;');
	eval('thiscount = room_' + room + '_' + guest + '_count;');

	var row =		'<tr class="added_item ' + guest + thiscount + 'bookable">'
			+		'<td class="item_name>'
			+			'<span class="add_remove_item">'
			+				'<a href="#" class="remove_item" id="' + room + '_' + guest + '_' + thiscount + '"></a>'
			+				thiscount + '. ' + name
			+			'</span>'
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_name_bookable" id="room_' + room + '_' + guest + '_' + thiscount + '_name_bookable" value="' + name + '" />'
			+		'</td>'
			+		'<td class="item_date">'
			+			date
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_date_bookable" id="room_' + room + '_' + guest + '_' + thiscount + '_date_bookable" value="' + date + '" />'
			+		'</td>'
			+		'<td class="item_price">'
			+			'<span class="sa_price">$' + price + '</span> USD (plus tax)'
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_price_bookable" id="room_' + room + '_' + guest + '_' + thiscount + '_price_bookable" value="' + price + '" />'
			+		'</td>'
			+		'<td class="item_gender"></td>'
			+	'</tr>';
	return row;
}

function printNonBookableItem(room, guest, name, date, price) {
	var thiscount, priceout;

	// we want price bold with a $ if it isn't N/A
	if (price != 'N/A') {
		priceout = '<span class="sa_price">$' + price + '</span> USD (plus tax)';
	} else {
		priceout = price
	}


	eval('room_' + room + '_' + guest + '_count++;');
	eval('thiscount = room_' + room + '_' + guest + '_count;');

	var row =		'<tr class="added_item ' + guest + thiscount + 'nonbookable">'
			+		'<td class="item_name>'
			+			'<span class="add_remove_item">'
			+				'<a href="#" class="remove_item" id="' + room + '_' + guest + '_' + thiscount + '"></a>'
			+				thiscount + '. ' + name
			+			'</span>'
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_name_nonbookable" id="room_' + room + '_' + guest + '_' + thiscount + '_name_nonbookable" value="' + name + '" />'
			+		'</td>'
			+		'<td class="item_date">'
			+			date
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_date_nonbookable" id="room_' + room + '_' + guest + '_' + thiscount + '_date_nonbookable" value="' + date + '" />'
			+		'</td>'
			+		'<td class="item_price">'
			+			priceout
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_price_nonbookable" id="room_' + room + '_' + guest + '_' + thiscount + '_price_nonbookable" value="' + price + '" />'
			+		'</td>'
			+		'<td class="item_gender"></td>'
			+	'</tr>';
	return row;
}

function printSpaServiceItem(room, guest, name, date, price, first_time, second_time, gender) {
	var thiscount, priceout;

	// we want price bold with a $ if it isn't N/A
	if (price != 'N/A') {
		priceout = '<span class="sa_price">$' + price + '</span> USD (plus tax)';
	} else {
		priceout = price
	}

	eval('room_' + room + '_' + guest + '_count++;');
	eval('thiscount = room_' + room + '_' + guest + '_count;');

	var row =		'<tr class="added_item ' + guest + thiscount + 'spaservice">'
			+		'<td class="item_name>'
			+			'<span class="add_remove_item">'
			+				'<a href="#" class="remove_item" id="' + room + '_' + guest + '_' + thiscount + '_spaservice"></a>'
			+				thiscount + '. ' + name
			+			'</span>'
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_name_spaservice" id="room_' + room + '_' + guest + '_' + thiscount + '_name_spaservice" value="' + name + '" />'
			+		'</td>'
			+		'<td class="item_date">'
			+			'<b>' + date + '</b> ' + first_time + ' (' + second_time + ')'
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_date_spaservice" id="room_' + room + '_' + guest + '_' + thiscount + '_date_spaservice" value="' + date + '" />'
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_first-time_spaservice" id="room_' + room + '_' + guest + '_' + thiscount + '_first_time_spaservice" value="' + first_time + '" />'
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_second-time_spaservice" id="room_' + room + '_' + guest + '_' + thiscount + '_second_time_spaservice" value="' + second_time + '" />'
			+		'</td>'
			+		'<td class="item_price">'
			+			priceout
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_price_spaservice" id="room_' + room + '_' + guest + '_' + thiscount + '_price_spaservice" value="' + price + '" />'
			+		'</td>'
			+		'<td class="item_gender">'
			+			gender
			+			'<input type="hidden" name="room_' + room + '_' + guest + '_' + thiscount + '_gender_spaservice" id="room_' + room + '_' + guest + '_' + thiscount + '_gender_spaservice" value="' + gender + '" />'
			+		'</td>'
			+	'</tr>';
	return row;
}

function printTimeSelectOptions() {
	var selectOptions = '';
	var startTime = 9;
	var endTime = 8;

	for (x=startTime; x<12; x++) {
		selectOptions += '<option>' + x + ':00 AM</option>';
	}

	selectOptions += '<option>12:00 PM</option>';

	for (x=1; x<=endTime; x++) {
		selectOptions += '<option>' + x + ':00 PM</option>';
	}
	
	//alert(selectOptions);
	return selectOptions;
}

function printDateSelectOptions() {
	var month=new Array(12);
	month[0]="January";
	month[1]="February";
	month[2]="March";
	month[3]="April";
	month[4]="May";
	month[5]="June";
	month[6]="July";
	month[7]="August";
	month[8]="September";
	month[9]="October";
	month[10]="November";
	month[11]="December";

	var start =  $('#arrival_date').val().split('/')
	var startYear = start[2];
	var startMonth = start[0];
	var startDay = start[1];

	var end = $('#departure_date').val().split('/')
	var endYear = end[2];
	var endMonth = end[0];
	var endDay = end[1];

	var thisDate = new Date(startYear, startMonth, startDay);
	var arrival = new Date(startYear, startMonth, startDay);
	var departure = new Date(endYear, endMonth, endDay);

	var duration = ((departure - arrival) / (24 * 60 * 60 * 1000));		// number of days between arrival and departure

	var selectOptions = '';

	for (x=0; x<duration; x++) {
		thisDate.setDate(thisDate.getDate() + 1); // first day doesn't count, so go ahead and increment
		selectOptions +=		'<option>'
					+		month[thisDate.getMonth() - 1] + ' ' + thisDate.getDate() + ', ' + thisDate.getFullYear()
					+	'</option>';
	}

	//alert(selectOptions);
	return selectOptions;
}

function printHTMLTripPlan() {
/*
	returns an html view of selected activites and services
*/
	var html = '';	// this will become the complete print view page
	for (var x=1; x<=room_count; x++) {
		if ($('#room_' + x + '_print .primary_lbl .cb').attr('checked')) {
			var guest = 'primary';
			html += $('.pane.3 .left_wide_pane_col #room_' + x + '_as .' + guest + '_selected_as').html();
			html += $('.pane.3 .left_wide_pane_col #room_' + x + '_as .' + guest + '_selected_as.nonbookable').html();
			html += $('.pane.3 .left_wide_pane_col #room_' + x + '_as .' + guest + '_selected_as.spaservice').html();
		}
		if ($('#room_' + x + '_print .secondary_lbl .cb').attr('checked')) {
			var guest = 'secondary';
			html += $('.pane.3 .left_wide_pane_col #room_' + x + '_as .' + guest + '_selected_as').html();
			html += $('.pane.3 .left_wide_pane_col #room_' + x + '_as .' + guest + '_selected_as.nonbookable').html();
			html += $('.pane.3 .left_wide_pane_col #room_' + x + '_as .' + guest + '_selected_as.spaservice').html();
		}
	}
	return html.replace(/tbody/g, 'table');
}

function printHTMLTripPlanEmail() {
	var serializedPlan = decodeURIComponent($.cookie('trip_plan').replace(/\+/g, ' '));	// the (decoded) serialized form stored by tp_save()

	var unserializedPlan = serializedPlan.split('&');		// an array of strings, each one consisting of a key value pair


	var output = '';

	output +=	'<html>'
		+	'<body style="padding:15px;background-color:#F9F2EA;color:#817871;font-size:.9em;font-family:Arial,Verdana,Helvetica,sans-serif">'
		+	'<img src="http://www.miravalresorts.com/extension/site/design/site/images/miraval_logo.gif" alt="MIRAVAL" />';

	var saoutput = '';	// activities and services are special

	var guest_info = new Array('first', 'last', 'email', 'phone');	// guest info values have one of these in the key

	var TI_header = false;
	var GI_header = false;
	var SA_header = false;

	var sectionDone = false;	// are we ready to print a guest/item?
	var ready = false;	// are we ready to print a guest/item?

	var guest, fname, lname, email, phone;	// guest info variables
	var name, date, price, first_time, second_time, gender;	// trip plan item variables

	for (var x=0; x<unserializedPlan.length; x++) {
		var pair = unserializedPlan[x].toString().split('=');

		var key = pair[0];
		var value = pair[1];

		// these conditions will be met chronologically going through x, starting with the dates and ending with the trip items

		if (key.split('_')[1] == 'date') {	// arrival and departure dates
			if (!TI_header) {	// print header if it hasn't been printed
				output += "<h2>Trip Information</h2>"
				TI_header = true;
			}

			// there are only two possibilities
			switch (key.split('_')[0]) {
				case 'arrival':
					output += "<p>Arrival Date: " + value + "</p>";
					break;
				case 'departure':
					output += "<p>Departure Date: " + value + "</p>";
					break;
			}
		} else if (key == 'number_of_rooms') {	// number of rooms
			// only one variable here
			output += "<p>Number of rooms: " + value + "</p>";
			sectionDone = true;
		} else if (($.inArray(key.split('_')[3], guest_info)) >= 0) {	// guest info ( >=0 because inArray returns array index )
			if (sectionDone && !GI_header ) {	// print header if it hasn't been printed
				output += "<h2>Guest Information</h2>"
				GI_header = true;
				sectionDone = false;
			}

			// gather up info then print one guest at a time
			switch (key.split('_')[3]) {
				case 'first':
					fname = value;
					break;
				case 'last':
					lname = value;
					break;
				case 'email':
					email = value;
					break;
				case 'phone':
					phone = value;
					ready = true;	// phone is the last value, one guest is ready
					break;
			}

			if (ready && (fname != '')) {	// print one guest
				output += "<p>Room " + key.split('_')[1] + ":\t" + fname + " " + lname + "\r\n\t\t" + email + " " + phone + "</p>";
				ready = false;
			}
		} else if (parseInt(key.split('_')[3]) > 0) {	// trip plan items
			if (!SA_header ) {	// print header if it hasn't been printed
				output += "<h2>Selected Activities and Services</h2>"
				SA_header = true;
				ready = false;
			}
		}
	}

	// style trip plan table
	styledTable = printHTMLTripPlan();

	styledTable = styledTable.replace(/<table/g, '<table width="100%"');
	styledTable = styledTable.replace(/<th/g, '<th width="25%" style="text-align:left"');
	styledTable = styledTable.replace(/<td/g, '<td width="25%"');

	output += styledTable;

	if ($('#already_have_reservation').val() == 'on') {
		output += "<p>This planner already has a room reservation.</p>";
	} else {
		output += "<p>This planner does not already have a room reservation.</p>";
	}

	output +=	'</body>'
		+	'</html>'
	
	return output;
}

function printPlainTextTripPlan() {
/*
	returns a plain text view of the complete plan
	pretty good looking plain text printout, before i attempt to change to match html
*/
	var serializedPlan = decodeURIComponent($.cookie('trip_plan').replace(/\+/g, ' '));	// the (decoded) serialized form stored by tp_save()

	var unserializedPlan = serializedPlan.split('&');		// an array of strings, each one consisting of a key value pair

/*
	var noshow = new Array('view_hide', 'active_tab', 'plan_started', 'get_started_popup_shown', 'finished');	// we don't want these fields

	for (x=4; x>room_count; x--) {
		noshow.push('room_' + x + '_number_of_guests');
	}
*/

	var output = '';

	var guest_info = new Array('first', 'last', 'email', 'phone');	// guest info values have one of these in the key

	var TI_header = false;
	var GI_header = false;
	var SA_header = false;

	var sectionDone = false;	// are we ready to print a guest/item?
	var ready = false;	// are we ready to print a guest/item?

	var guest, fname, lname, email, phone;	// guest info variables
	var name, date, price, first_time, second_time, gender;	// trip plan item variables

	for (x=0; x<unserializedPlan.length; x++) {
		var pair = unserializedPlan[x].toString().split('=');

		var key = pair[0];
		var value = pair[1];

		// these conditions will be met chronologically going through x, starting with the dates and ending with the trip items

		if (key.split('_')[1] == 'date') {	// arrival and departure dates
			if (!TI_header) {	// print header if it hasn't been printed
				output += "Trip Information\r\n\r\n"
				TI_header = true;
			}

			// there are only two possibilities
			switch (key.split('_')[0]) {
				case 'arrival':
					output += "Arrival Date: " + value + "\r\n";
					break;
				case 'departure':
					output += "Departure Date: " + value + "\r\n";
					break;
			}
		} else if (key == 'number_of_rooms') {	// number of rooms
			// only one variable here
			output += "Number of rooms: " + value + "\r\n";
			sectionDone = true;
		} else if (($.inArray(key.split('_')[3], guest_info)) >= 0) {	// guest info ( >=0 because inArray returns array index )
			if (sectionDone && !GI_header ) {	// print header if it hasn't been printed
				output += "\r\n\r\nGuest Information\r\n\r\n"
				GI_header = true;
				sectionDone = false;
			}

			// gather up info then print one guest at a time
			switch (key.split('_')[3]) {
				case 'first':
					fname = value;
					break;
				case 'last':
					lname = value;
					break;
				case 'email':
					email = value;
					break;
				case 'phone':
					phone = value;
					ready = true;	// phone is the last value, one guest is ready
					break;
			}

			if (ready && (fname != '')) {	// print one guest
				output += "Room " + key.split('_')[1] + ":\t" + fname + " " + lname + "\r\n\t\t" + email + " " + phone + "\r\n";
				ready = false;
			}
		} else if (parseInt(key.split('_')[3]) > 0) {	// trip plan items
			if (!SA_header ) {	// print header if it hasn't been printed
				output += "\r\n\r\nSelected Activities and Services\r\n\r\n"
				SA_header = true;
				ready = false;
			}

			type = key.split('_')[5];
			switch (key.split('_')[2]) {
				case 'primary':
					guest = '1';
					break;
				case 'secondary':
					guest = '2';
					break;
			}
			switch (type) {
				case 'bookable': case 'nonbookable':
					switch (key.split('_')[4]) {
						case 'name':
							name = value;
							break;
						case 'date':
							date = value;
							break;
						case 'price':
							if (value == 'N/A') {
								price = value;
							} else {
								price = "$" + value;
							}
							ready = true;		// price is the last field, one item is ready
							break;
					}
					if (ready) {					// all values are set for one trip item, add it and reset
						output += "Room " + key.split('_')[1] + ", Guest " + guest + ":\r\n\tName: " + name + "\r\n\tDate: " + date + "\r\n\tPrice: " + price + "\r\n";
						ready = false;
					}
					break;
				case 'spaservice':
					switch (key.split('_')[4]) {
						case 'name':
							name = value;
							break;
						case 'date':
							date = value;
							break;
						case 'first-time':
							first_time = value;
							break;
						case 'second-time':
							second_time = value;
							break;
						case 'gender':
							gender = value;
							break;
						case 'price':
							if (value == 'N/A') {
								price = value;
							} else {
								price = "$" + value;
							}
							ready = true;		// price is the last field, one item is ready
							break;
					}
					if (ready) {					// all values are set for one trip item, add it and reset
						output += "Room " + key.split('_')[1] + ", Guest " + guest + ":\r\n\tName: " + name + "\r\n\tDate: " + date + "\r\n\tPrice: " + price + "\r\n\tTime Preferences: " + first_time + " (" + second_time + ")\r\n\tGender Preference: " + gender + "\r\n";
						ready = false;
					}
					break;
			}
		}

/*
// original output, now debug
		if (($.inArray(key, noshow) == -1) && (value != '')) { // as long as the current key is a value we want and value isn't empty
			output += key + ' : ' + value + "\n";
		}
*/

	}

	if ($('#already_have_reservation').val() == 'on') {
		output += "\r\nThis planner already has a room reservation.";
	} else {
		output += "\r\nThis planner does not already have a room reservation.";
	}
	
	return output;
}

function submitTripPlan() {
/*
-Once a user submits the trip planner form, where should it go and in what format?
 
Behind the scenes: It should be emailed to someone at Miraval in a plain text type format (this will include all the data the guest has filled in with the headers, Trip Information, Guest Inforamtion, and Selected Activities. We would like that email to have a link to see it in the admin. We would also like to save these in the admin database for the admin to retrieve.
 
To the end user- The same plain text email (with the headers, Trip Information, Guest Inforamtion, and Selected Activities  and the pertinent info the user filled out below each) will be sent to the person who created the Trip Plan as well as anyone else they designates it be sent to via email in the Guest info tab.



need to also create an ezpublish object, 4 fields - ezp name, contact name, contact email, plain text plan printout
*/

	// prepare data
	var nodeID = 1282;
	var objectID = 1337;
	var email_data = new Array();

	//email_data.push('message=' + encodeURIComponent(printPlainTextTripPlan()));
	email_data.push('message=' + encodeURIComponent(printHTMLTripPlanEmail()));

	for (x=0; x<(room_count*2); x++) {
		var room = (Math.floor(x / 2) + 1);

		if (x%2) {
			var contact = 'secondary';
		} else {
			var contact = 'primary';
		}

		if ($('#room_1_' + contact + '_first_name').val() != '') {	// if this contact is checked
			email_data.push('name_' + x + '=' + $('#room_' + room + '_' + contact + '_first_name').val() + ' ' + $('#room_' + room + '_' + contact + '_last_name').val());
			email_data.push('email_' + x + '=' + $('#room_' + room + '_' + contact + '_email').val());
		} else {
			break;
		}
	}

	email_data.push('additional_email=' + $('#additional_email').val());

	// email plan
	$.ajax({
		url: '/moduletools/mailer',
		type: 'POST',
		data: email_data.join('&'),
		success: function() {
			// create object
			var ezp_data = new Array(	'ContentObjectAttribute_ezstring_data_text_16150=' + $('#room_1_primary_first_name').val() + ' ' + $('#room_1_primary_last_name').val(),
							'ContentObjectAttribute_ezstring_data_text_16151=' + encodeURIComponent($('#room_1_primary_email').val()),
							'ContentObjectAttribute_data_text_16216=' + encodeURIComponent(printPlainTextTripPlan()),
							'ContentNodeID=' + nodeID,
							'ContentObjectID=' + objectID,
							'ViewMode=full',
							'ActionCollectInformation=Send form');

			$.ajax({
				url: '/content/action',
				type: 'POST',
				data: ezp_data.join('&')
			});
		}
	});
}

function submitTripPlanNew() {
	// prepare data
	var nodeID = 1282;
	var objectID = 1337;
	var email_data = new Array();

	email_data.push('message=' + encodeURIComponent(printHTMLTripPlanEmail()));

	for (x=0; x<(room_count*2); x++) {
		var room = (Math.floor(x / 2) + 1);

		if (x%2) {
			var contact = 'secondary';
		} else {
			var contact = 'primary';
		}

		if ($('#room_1_' + contact + '_first_name').val() != '') {	// if this contact is checked
			email_data.push('name_' + x + '=' + $('#room_' + room + '_' + contact + '_first_name').val() + ' ' + $('#room_' + room + '_' + contact + '_last_name').val());
			email_data.push('email_' + x + '=' + $('#room_' + room + '_' + contact + '_email').val());
		} else {
			break;
		}
	}

	email_data.push('additional_email=' + $('#additional_email').val());

	// email plan
	$.ajax({
		url: '/moduletools/mailer',
		type: 'POST',
		data: email_data.join('&')
	});
}