﻿/**
* static object that handles page logic for the accommodation prices page
* @class 
* @constructor
* @param {jQuery} $ Reference to the jQuery object
*/
var AccoPrices = function($) {

	/**
	* @namespace Private methods and variables
	*/
	var priv = {
		progressTimer: 200,
		accoId: null,
		bindEvents: function() {
			priv.bindQuestionPopups();
			priv.bindRoomtypeInfoPopups();
			priv.bindLastminuteTooltip();
			priv.bindNoAvailablePrices();
		},
		/**
		* Bind events on the links to questions popups, both in the left sidebar and in the main content area.
		* @private
		*/
		bindRoomtypeInfoPopups: function() {
			// add container for roomtype info popups
			$('body').append("<div id=\"roomtypeinfoPopup\"></div>");

			// Bind method to show roomtype info
			$("#prices .itje").mouseenter(function(e) {
				var popupId = $(this).siblings(".popup")[0].id.replace('pRoomtypeinfoPopup', '');
				var lightbox = priv.openLightbox('pRoomtypeinfoPopup' + popupId, {
					container: document.getElementById('pRoomtypeinfoPopup' + popupId),
					clone: true,
					mode: 'hover',
					hoverEvent: e
				});
				$(this).mouseleave(function() {
					lightbox.Close();
				});
			});
		},

		/**
		* Bind events on the links to questions popups, both in the left sidebar and in the main content area.
		* @private
		*/
		bindQuestionPopups: function() {
			// add container for question popups
			$('body').append("<div id=\"questionPopup\"></div>");

			// Bind methods to show popups for questions in main area
			$("#questions li a").not("[options='nobind']").bind('click', function() {
				return priv.loadInLightbox(this, "questionPopup");
			});

			// Bind methods to show popups for questions in left sidebar
			$("#questions-left li a").not("[target='_blank']").bind('click', function() {
				return priv.loadInLightbox(this, "questionPopup");
			});

			// Open faq in new window
			$("#questions-left li a[target='_blank']").bind('click', function() {
				Utils.newWindow(this, 800, 640);
				return false;
			});

			// Bind methodsto show legend info
			$("#legenda span.itje").bind('click', function() {
				priv.openLightbox('pLegendaPopup', {
					container: document.getElementById('pLegendaPopup'),
					width: '623px',
					clone: false
				});
			});
		},

		$wrapperDataContainer: null,

		$wrapperDataPointers: null,

		initializeWrappers: function() {
			if (pricesWrapper) {
				priv.$wrapperDataContainer = pricesWrapper.newDataConfiguration();
				priv.$wrapperDataPointers = pricesWrapper.newPointerConfiguration();
				priv.$wrapperDataPointers.mealplan.afterEventCallback = function() {
					priv.setMealPlanToQueryString();
				}
				priv.$wrapperDataPointers.airport.afterEventCallback = function() {
					priv.setAirportToQueryString();
				}
			}
		},

		sincronizeWrappers: function() {
			if (pricesWrapper) {
				pricesWrapper.configure(priv.$wrapperDataContainer, priv.$wrapperDataPointers);
			}
		},

		/**
		* Actions to do when price table is loaded through ajax
		* @private
		*/
		onTableLoaded: function() {
			priv.initializeWrappers();
			priv.sincronizeWrappers();
		},

		setMealPlanToQueryString: function() {
			priv.seValueToQueryString('mealplan', priv.$wrapperDataPointers.mealplan);
		},

		setAirportToQueryString: function() {
			priv.seValueToQueryString('airport', priv.$wrapperDataPointers.airport);
		},

		seValueToQueryString: function(paramKey, dataPointer) {
			if (dataPointer && dataPointer.selectedPointer && $(dataPointer.selectedPointer) && $(dataPointer.selectedPointer).val())
				location.href = $.query.SET(paramKey, $(dataPointer.selectedPointer).val());
		},

		adjustLastminutesPopup: function($listItem, $lastminutePopup) {
			var top = $listItem.position().top;
			var topOffset = $listItem.offset().top;
			var winheight = $(window).height();
			var height = $lastminutePopup.height();
			if (topOffset - $(window).scrollTop() + height > winheight) {
				if (winheight > height) {
					$lastminutePopup.css('top', (top - $lastminutePopup.height() + 10) + 'px');
				}
				else {
					// default behaviour
				}
			}
			else {
				$lastminutePopup.css('top', (top + 10) + 'px');
			}
		},

		bindLastminuteTooltip: function() {
			$("td.lastminute-trip").hover(
				function() {
					var $listItem = $(this);
					var $lastminutePopup = $("div.lastminuteTooltip", this);

					var $informationBlock = $("#lastminute-tooltip-popup");
					$informationBlock.css({ 'height': 'auto', 'border': 'none', 'padding': '5px' })
					$informationBlock.height($informationBlock.get(0).offsetHeight + 20);
					priv.adjustLastminutesPopup($listItem, $lastminutePopup);
					$lastminutePopup.html($informationBlock.html());

					$lastminutePopup.show();

					return false;
				},
				function() {
					var $lastminutePopup = $("div.lastminuteTooltip", this);
					$lastminutePopup.hide();
					$lastminutePopup.css('top', ($(this).position().top + $(this).height() + 2) + 'px');
					return false;
				}
			)
		},

		/**
		* Generic way to open a new lightbox: the contents of the container identified by the supplied id
		* are loaded in a lightbox. Also, the lightbox is cached and thus only has to be initialized once.
		* @param {String} id The id of the container to show in the lightbox
		* @param {Object} options (Optional) Several options can be supplied to override default behavior of just
		* loading the contents of the container. When supplied, these options will be used to initialize the lightbox.
		* @private
		*/
		openLightbox: function(id, options) {
			var lightbox = Lightbox.CreateCached(id, options);
			lightbox.Show();
			return lightbox;
		},

		initExtraScroll: function() {
			// set table width
			$('table.pricegrid').width($('table.pricegrid tr:first td.day').length * 32);

			// set rightpane/extra-scoll width (subtract with some offset to make sure fits in all browsers)
			var width = $('#prices div.table-box').width() - $('div.leftpane').width() - 2;
			$('#extra-scroll').width(width);
			$('div.rightpane').width(width);

			// set scrollbar
			$('#extra-scroll div').width($('table.pricegrid').width());

			$('#extra-scroll').bind("mouseenter", function() {
				$('#extra-scroll').bind("scroll", function() {
					$("div.rightpane").get(0).scrollLeft = this.scrollLeft;
				});
			});
			$('#extra-scroll').bind("mouseleave", function() {
				$('#extra-scroll').unbind("scroll");
			});
			$('div.rightpane').bind("mouseenter", function() {
				$('div.rightpane').bind("scroll", function() {
					$("#extra-scroll").get(0).scrollLeft = this.scrollLeft;
				});
			});
			$('div.rightpane').bind("mouseleave", function() {
				$('div.rightpane').unbind("scroll");
			});

			if ($('table.pricegrid').width() <= $('div.rightpane').width()) {
				$('#extra-scroll').css('overflow-x', 'auto');
				$('div.rightpane').css('overflow-x', 'auto');
			}
		},

		bindNoAvailablePrices: function() {
			if (pricesWrapper) {
				var element = $("[id*='AvailableDurationAction']");
				if (element && element.length > 0) {
					element.each(function() {
						$(this).bind('click', function() {
							priv.showLoader();
							Occupancy.deleteCookie();
						});
					});
				}
			}
		},

		showLoader: function() {
			if (AccoMain) {
				AccoMain.showLoader();
			}
		},

		/**
		* Load the contents of the href of the anchor in a lightbox, wrapped in custom popup markup
		* @param {HTMLElement} anchor The anchor
		* @param {String} id ID to set on the popup container
		* @return {Boolean} false, to use in event handler and stop browser default behavior
		* @private
		*/
		loadInLightbox: function(anchor, id) {
			var $anchor = $(anchor);

			var options = {
				container: document.getElementById(id),
				literal: true,
				title: $anchor.text(),
				contentUrl: $anchor.attr('href'),
				width: '1000px',
				onShowCallback: function() {
					if ($anchor.hasClass('carrental')) {
						AccoMain.AddStylesToCarRentalTableRows();
					}
					//Hack for tables from CMS, see WS-5062
					$("#carrental table").css("border-collapse", "collapse");
					$("#carrental tr, #carrental td").width("auto");
				}
			};
			var lightbox = Lightbox.CreateCached($anchor.attr('href'), options);
			lightbox.Show();
			return false;
		},

		setFocus: function() {
			var endPricesFocus = $('#endPrices');
			if (endPricesFocus.length > 0) {
				$(endPricesFocus).focus();
			}
		}
	};

	/** @scope AccoPrices */
	return {

		reloadPriceTab: function(input) {
			var values = {
				month: $('div.month-box ul li strong.selected a').attr('rel'),
				airport: $('input:radio[name=airport]:checked').val(),
				vtype: $('div.time-box ul li.selected a').attr('rel'),
				durationtrips: priv.getDurationsRequestString()
			};
			$.extend(values, input);

			var timer = new Timer();
			timer.Start();
			$('#priceloader').hide();
			$('#priceTableMessage').show();

			$("#priceloader").load(Resource.GetText("path_prefix") + '/js/ajax/getcontrol.aspx' +
				'?accoid=' + $('#accoId').val() +
				'&loadControl=' + encodeURIComponent('~/controls/accommodation/prices.ascx') +
				'&month=' + values.month +
				'&transport=' + $('#transportCode').val() +
				'&vtype=' + values.vtype +
				'&airport=' + values.airport +
				'&durationtrips=' + values.durationtrips,
				 null,
				 function() {
				 	$('table.pricegrid tr.months td').each(function() {
				 		if ($('span', this).length > 1) {
				 			$('span:first', this).css({ paddingRight: '290px' });
				 		}
				 	});
				 	setTimeout('AccoPrices.showPriceTable()', Math.max((priv.progressTimer - timer.Stop()), 0));
				 }
			);
		},

		afterPricesUpdate: function() {
			if ($('div.noprices').length) {
				$('div.legend').hide();
				$('div.notes').hide();
			} else {
				$('div.legend').show();
				$('div.notes').show();
			}
			if (typeof (PricesSunwebTooltip) != "undefined") {
				PricesSunwebTooltip.InitTooltips();
			}
			if (SearchMain) {
				SearchMain.OnReady();
			}
			priv.bindEvents();
			priv.onTableLoaded();
			priv.initExtraScroll();
			priv.setFocus();
		},

		/**
		* Initializes the logic for the current page
		* to be called on $(document).ready
		*/
		OnReady: function() {
			priv.accoId = $('#accoId').val();
			if (typeof (PricesSunwebTooltip) != "undefined") {
				PricesSunwebTooltip.OnReady();
			}
			priv.bindEvents();
			priv.initExtraScroll();
			Basket.OnReady();

			if (pricesWrapper) {
				pricesWrapper.setAfterPricesUpdateCallback(function() { AccoPrices.afterPricesUpdate(); });
				priv.onTableLoaded();
			}

			$("#legenda").fixate({
				minTop: isNaN(parseInt($("#legenda").css('top'))) ? 0 : parseInt($("#legenda").css('top')),
				maxTop: $('#content').height() - $('#legenda').height()
			});
			// space of legenda is not reserved when using absolute position; use dummy empty div and set height
			$('#legenda-area').height($("#legenda").height());
			priv.setFocus();
		},

		FollowAirportAlternativeLink: function(airport) {
			var airportAlternativeLink = '';
			airportAlternativeLink = $.query.SET('airport', airport);
			airportAlternativeLink = $.query.SET('prev', '');
			airportAlternativeLink = $.query.SET('next', '');
			location.href = airportAlternativeLink;
		},

		FollowMonthAlternativeLink: function(month, vtype, airport) {
			var monthAlternativeLink = '';
			monthAlternativeLink = $.query.SET('month', month);
			monthAlternativeLink = $.query.SET('vtype', vtype);
			monthAlternativeLink = $.query.SET('airport', airport);
			monthAlternativeLink = $.query.SET('prev', '');
			monthAlternativeLink = $.query.SET('next', '');
			location.href = monthAlternativeLink;
		},

		FollowVTypeAlternativeLink: function(vtype) {
			var vTypeAlternativeLink = '';
			vTypeAlternativeLink = $.query.SET('vtype', vtype);
			vTypeAlternativeLink = $.query.SET('prev', '');
			vTypeAlternativeLink = $.query.SET('next', '');
			location.href = vTypeAlternativeLink;
		},

		/**
		* Add a newly selected price to the basket. Several parameters are used.
		*/
		AddToBasket: function(packageid, packagecode, duration, roomtype, departuredate, transportcode, airportcode, price, accommodationid, mealplancode, $curobj, evt) {
			if (typeof (evt) != "undefined") {
				Basket.AddToBasket(packageid, packagecode, duration, roomtype, departuredate, transportcode, airportcode, price, accommodationid, mealplancode, $curobj, evt, undefined, 227);
			}
			else {
				//ugly hack, should be solved correctly as soon as possible
				Basket.AddToBasket(packageid, packagecode, duration, roomtype, departuredate, transportcode, airportcode, price, accommodationid, '', mealplancode, $curobj, undefined, 227);
			}
		},

		/*
		* Redraw the basket box. There are 2 possible situations:
		* 1. A price has been selected from the table, it will be added to the box
		* 2. The user closed the box. All parameters and previously selected prices will be cleared and the basket will be removed.
		* @param {Integer} height (Optional) The offset height of the basket. Used to determine whether to close or expand the basket.
		*/
		ReDraw: function(height) {
			Basket.ReDraw(height);
		},

		/**
		* Remove the basket; clear all parameters
		*/
		RemoveBasket: function() {
			Basket.RemoveBasket();
			$('#basket-container').slideUp();
		},

		/**
		* Get whether it is currently possible to open the tooltip
		* @return {Boolean} True if nothing prevents the tooltip from showing
		*/
		CanShowTooltip: function() {
			return !Basket.IsAnimating();
		},

		/**
		* Perform certain actions when starting animation of the basket
		*/
		StartingAnimation: function() {
			if (typeof (PricesSunwebTooltip) != "undefined") {
				PricesSunwebTooltip.Hide();
			}
		}
	};
} (jQuery);
