﻿	/********************************/
/* hotelResults.js				*/
/*	- Requires ticketDialog.js	*/
/*		or TicketDialog.ascx	*/
/********************************/

/**********************/
/* Abstract Functions */
/**********************/

// function loadHotelListing(subsetIndex, reloadTickets);
// function refreshTicketListing(voucherPricing);

/************/
/* On Ready */
/************/

//$(document).ready(function() {
//	hotelresults_initialize();
//	//sys.webforms.pagerequestmanager.getinstance().add_endrequest(hotelresults_initialize);
//});

$(document).ready(function () {
});

function hotelResults_initialize() {
	hotelResults_getContainer().each(function () {
		var $hotelGroups = hotelResults_getHotelGroups(this);

		var resultLength = $('input[id$="hdnResultSize"]').val();

		// If we have enough records to make multiple pages, initialize the nagivation and hide the records following the first 10
		if (resultLength > 10) { //$hotelGroups.length > 10) {
			hotelResults_initializeNavigation(hotelResults_getContent(this), $hotelGroups, hotelResults_getNavigation(this), 1, Math.ceil(resultLength / 10)); //$hotelGroups.length / 10));
			$hotelGroups.slice(10).slideUp(600);
		}

		hotelResults_getLoading(this).slideUp(600);

		if ($hotelGroups.length == 0)
			$('#noResultsMessage').show();
	});

	setupRotator();
	checkForRequiresTickets();
}

function hotelResults_collapse() {
	hotelResults_getContent(hotelResults_getContainer()).slideUp(600);
	hotelResults_getNavigation(hotelResults_getContainer()).slideUp(600);
}

function hotelResults_refresh($hotelResults, subsetIndex, reloadTickets) {
	// Get containers
	var $content = hotelResults_getContent($hotelResults);
	var $loading = hotelResults_getLoading($hotelResults);
	var $navigation = hotelResults_getNavigation($hotelResults);

	// Load attributes
	var type = parseInt($hotelResults.attr('result-type'));
	var serviceCall = $hotelResults.attr('service-call');
	var parameters = $hotelResults.attr('service-parameters');

	// Hide navigation and content
	$navigation.slideUp(600);
	$content.slideUp(600, function () {
		// If we're loading by location (type == 1), include subset index as parameter
		if (type == 1) {
			if (subsetIndex != null) {
				parameters = subsetIndex + ', ' + parameters;
			}
			else {
				parameters = '1, ' + parameters;
			}
		}

		// If we have an explicit value for reloading tickets, use it, else default to true
		if (reloadTickets) {
			parameters = parameters + ', ' + reloadTickets;
		}
		else {
			parameters = parameters + ', true';
		}

		// Call function for loading results from subset
		$loading.slideDown(600, function () {
			hotelResults_displaySubset($content, $loading, $navigation, serviceCall, parameters);
		});
	});
}

/**************/
/* Call Backs */
/**************/

var hotelResultsTemplate;

// Call WCF Service that returns subset to call back function for populating container
function hotelResults_displaySubset($content, $loading, $navigation, serviceCall, parameters) {
	// Evaulate service call and its parameters dynamically, then pass results to anonymous call back function
	eval(serviceCall + '(' + parameters + ', ' + function (subset) {
		planVacation_initializeButtonToggling();
		$content.html('');

		if (subset.Results.length == 0) {
			$('#noResultsMessage').show();
		}
		else {
			$('#noResultsMessage').hide();

			// Populate results
			var template = $("#hotelResultTemplate").html();

			$content.setTemplate(template);
			$content.processTemplate(subset);

			window.setTimeout(function () {
				setupRotator();
				checkForRequiresTickets();
			}, 250);

			var $hotelGroups = hotelResults_getHotelGroups($content);
			//			if (subset.CurrentSubset > 0)
			//				$hotelGroups.hide().slice((subset.CurrentSubset - 1) * 10, subset.CurrentSubset * 10).show();
			if (getMapsLink() != null)
				getMapsLink().slideDown(300);

			// Calculate and refresh selectable tickets if available
			if (subset.SelectableVouchers && subset.SelectableVouchers.length > 0) {
				refreshTicketListing(subset.SelectableVouchers);
			}
		}

		$loading.slideUp(600, function () {
			planVacation_getActionButton().siblings('img').remove();
			$content.slideDown(600);

			// If applicable, initialize navigation
			if (subset.TotalSubsets > 0) {
				hotelResults_initializeNavigation($content, $hotelGroups, $navigation, subset.CurrentSubset, subset.TotalSubsets);
			}
		});
	} + ', ' + hotelResults_displayError + ', ' + hotelResults_displayError + ');');
}

function setupRotator() {

	var nightCount = planVacation_getNightCount();

	if (nightCount > 3) {
		$('div.next').show();
		$('div.prev').show();

		$('.priceRotator').serialScroll({
			target: '.priceContent',
			items: 'li',
			prev: 'div.prev',
			next: 'div.next',
			axis: 'xy',
			duration: 700,

			step: 3,
			onBefore: function (e, elem, $pane, $items, pos) {
				e.preventDefault();
				if (this.blur)
					this.blur();
			}
		});
	}
	else {
		$('div.next').hide();
		$('div.prev').hide();
	}
}

function checkForRequiresTickets() {
	$('.hotelRow').each(function () {
		var isAvailable = $(this).children('#isAvailableFlag').html(); // == 'False';

		if (isAvailable == 'False' || isAvailable == 'false')
			$(this).children('.priceBlock').addClass("disabled");

		isAvailable = 'false';
	});
}

// Callback function for displaying WCF Service error
function hotelResults_displayError(error, context, methodName) {
	alert(error.get_message());
}

// used to generate the daily pricing table
function buildDailyPricing(dailyPricings, averagePrice) {

	var table = $('<table></table>');
	var zeroString = '$0.00';
	var headerRow = $('<tr class="perDayHeadRow"></tr>');
	var contentRow = $('<tr class="perDayPriceRow"></tr>');

	for (var i = 0; i < dailyPricings.length; i++) {
		if (i > 0 && i % 7 == 0) {
			table.append(headerRow);
			table.append(contentRow);

			headerRow = $('<tr class="perDayHeadRow"></tr>');
			contentRow = $('<tr class="perDayPriceRow"></tr>');
		}

		var cell = $('<td></td>');
		cell.html(dailyPricings[i].DateString);
		headerRow.append(cell);

		cell = $('<td></td>');
		cell.html(dailyPricings[i].PriceString);
		if (dailyPricings[i].PriceString == zeroString)
			cell.addClass('priceHighlight');

		contentRow.append(cell);
	}

	// always append the last set
	table.append(headerRow);
	table.append(contentRow);

	// add "missing" columns on final row
	headerRow = $('tr', table).eq($('tr', table).length - 2);
	contentRow = $('tr:last', table);
	if ($('tr', table).length > 2 && $('td', contentRow).length < 7) {
		var iterations = 7 - $('td', contentRow).length;
		for (var i = 0; i < iterations; i++) {
			headerRow.append('<td>&nbsp;</td>');
			contentRow.append('<td>&nbsp;</td>');
		}
	}

	// add average daily price
	headerRow = $('tr:first', table);
	contentRow = $('tr:nth-child(2)', table);

	headerRow.append('<td>Avg/Night</td>');
	contentRow.append('<td class="priceAvg" rowspan="' + ($('tr', table).length - 1) + '">' + averagePrice + '</td>');

	var html = $('<div></div').append(table).html();
	return html;
}

/**************/
/* Navigation */
/**************/

function hotelResults_initializeNavigation($content, $hotelGroups, $navigation, subsetIndex, pageCount) {
	// Remove existing navigation and replace it according to passed parameters
	$navigation.children().remove();
	$navigation.html('').append(hotelResults_generateNavigation(subsetIndex, pageCount)).slideDown(600);

	$('a', $navigation).click(function (event) {
		// Prevent default and get the subset index of the navigation item clicked
		event.preventDefault();
		subsetIndex = parseInt($(this).attr('tag'));

		// TODO: RTA call service
		hotelResults_refresh(hotelResults_getContainer(), subsetIndex, false);

		//		$navigation.slideUp(600);
		//		$content.slideUp(600, function() {
		//			// If the selected index is valid, load a slice of records accordingly, else load all records

		//			if (subsetIndex > 0) {
		//				$hotelGroups.hide().slice((subsetIndex - 1) * 10, subsetIndex * 10).show();
		//			}
		//			else {
		//				$hotelGroups.show();
		//			}

		// Initialize the new navigation according to the new selection
		//			hotelResults_initializeNavigation($content, $hotelGroups, $navigation, subsetIndex, pageCount);
		//			$content.slideDown(600);
		//		});
	});
}

function hotelResults_generateNavigation(subsetIndex, pageCount) {
	var contents;

	if (subsetIndex > 0) {
		contents = hotelResults_generateNavigationItem(subsetIndex - 1, 'Previous', subsetIndex > 1)
			+ ' | ';

		for (var index = 1; index <= pageCount; index++)
			contents += hotelResults_generateNavigationItem(index, index, index != subsetIndex);

		contents += ' | '
			+ hotelResults_generateNavigationItem(subsetIndex + 1, 'Next', subsetIndex < pageCount)
			+ '&nbsp;&nbsp;&nbsp;'
			+ hotelResults_generateNavigationItem(0, '(Show All)', true);
	}
	else
		contents = hotelResults_generateNavigationItem(1, 'Show Pages', true);

	return contents;
}

function hotelResults_generateNavigationItem(index, label, isActiveLink) {
	var contents = '<span>';

	if (isActiveLink)
		contents += '&nbsp;<a href="javascript:{}" tag="' + index + '">' + label + '</a>&nbsp;';
	else
		contents += '&nbsp;' + label + '&nbsp;';

	return contents + '</span>';
}

/*************/
/* Accessors */
/*************/

function hotelResults_getContainer() {
	return $('.hotelResults');
}

function hotelResults_getContent(parent) {
	return $('.hotelResults_content', parent);
}

function hotelResults_getHotelGroups(parent) {
	return $('.hotelGroup', parent);
}

function hotelResults_getLoading(parent) {
	return $('.hotelResults_loading', parent);
}

function hotelResults_getNavigation(parent) {
	return $('.hotelResults_navigation', parent);
}

function getMapsLink() {
	return $('#maps');
}


function initializeRequiresTicketsDialog(title, room, price, link) {
	$('#requiresTicketsDialog').dialog({
		autoOpen: false,
		resizable: false,
		modal: true,
		title: title,
		width: 550,
		buttons: {
			'Select': function () {
				window.location.href = link;
			},
			'Cancel': function () {
				$(this).dialog('close');
			}
		}
	});

	$('#requiresTicketsDialog').html(function (i, html) {
		return html.replace('{room}', '<span id=\'room\'></span>');
	});

	$('#requiresTicketsDialog #room').html(room);

	$('#requiresTicketsDialog').html(function (i, html) {
		return html.replace('{price}', '<span id=\'price\'></span>');
	});

	$('#requiresTicketsDialog #price').html(price);

	$('#requiresTicketsDialog').dialog('open');
}
