﻿/**
 * static object that handles page logic
 * @class 
 * @constructor
 * @param {jQuery} $ Reference to the jQuery object
 */
var AccoMain = function($) {

	var config = {

		/**
		* maximum number of reviews to show initially
		* @private
		*/
		maxReviews: 10,

		/**
		* maximum number of tips to show initially
		* @private
		*/
		maxTips: 10,

		/**
		* amount of ms that hte favoritesAnimation stays visible after the animation
		* @private
		*/
		favoritesAnimHideTime: 3500,

		/**
		* jquery reference of the favorites button html object
		* @private
		*/
		favoriteTrigger: "#favorite",

		carRentalTableElement: 'table.acco-carrental-table',

		reviewsBlockElement: '#content div.testimonials',

		tipsBlockElement: '#content div.tip-box',

		emailLinkElement: '#content div.meta a.ico-emaildeprecated',

		bestPriceTagElement: '#content div.description-block div.price-box',

		bestPriceContentTagElement: '#content div.description-block div.holder div.column02',

		weatherBlockElement: '#content div.weather-promo',

		galleryInitialized: false,

		searchTerms: '#content div.nav-box a.searchterms',

		galleryIndex: 0
	};

	/**
	* @namespace Private methods and variables
	*/
	var priv = {

		/**
		* holds the name for the current sub-page (tab)
		* @private
		*/
		currentTab: null,

		/**
		* holds the name for the current sub-sub-page (subtab)
		* @private
		*/
		currentSubTab: null,

		/**
		* The Id of the current accommodation
		* @type Integer
		* @private
		*/
		accoId: -1,

		/**
		* 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();
		},

		favoriteAnimationEndOfLife: false,
		/**
		* Void, handles the animation when a user hits "Save" to favorites button
		* @private
		*/
		addFavoriteAnimation: function() {
			Log.Debug("accomain, addFavoriteAnimation: start");
			//do animation here
			//only if this is the first saved item favorite (count = 1)
			//if (PersonalItems.GetItemCount("favorites") > 1) {
			//	return;
			//}

			//if the element already exists simply blink it to draw attention to it
			if ($("div.save-animation").get(0)) {
				Log.Debug("accomain, addFavoriteAnimation: blink element");
				$("div.save-animation").stop(true, true)
					.fadeOut(200).fadeIn(200).fadeOut(200).fadeIn(200)
					.delay(config.favoritesAnimHideTime).fadeOut(200, function() { $(this).remove() });
				return;
			}

			var animObj = document.createElement("DIV");
			var startOffset = $(config.favoriteTrigger).offset();
			$(animObj)
				.addClass("save-animation")
				.css({ "position": "absolute", "top": startOffset.top, "left": startOffset.left })
				.hide()
				.text(Resource.GetText("FAVORITES_VIEW_HERE"));
			/*
			var closeLink = document.createElement("A");
			$(closeLink)
			.addClass("close")
			.attr("href", "#")
			.text("x")
			.bind("click", function() {
			$(animObj).hide();
			});
			$(animObj).append(closeLink);
			*/
			$("body").append(animObj);

			//preload the image before doing the animation
			var image = $(animObj).css("background-image");
			//strip "url()" if required (IE browsers)
			if (image.indexOf("url(\"") != -1) {
				image = image.substring(5);
				image = image.substring(0, image.length - 2);
			}
			var imagePreloader = new ImagePreloader([image], function() {
				Log.Debug("accomain, addFavoriteAnimation: animating");
				var targetOffset = $("#my-favorites-items").offset();
				$(animObj)
					.show()
					.animate({
						"top": targetOffset.top - 10,
						"left": targetOffset.left + $("#my-favorites-items").width() + 20
					}, "slow", "swing")
					.delay(config.favoritesAnimHideTime).fadeOut(200, function() { $(this).remove() });
			});

			//}
		},

		/**
		* Void, fills the property currentTab with the correct value
		* @private
		*/
		setCurrentTab: function() {
			priv.currentTab = $.query.get('view').toLowerCase();
			if (priv.currentTab.length < 1) {
				priv.currentTab = $('body').attr('class');
			}
			Log.Debug("AccoMain: currentTab is '" + priv.currentTab + "'");
		},

		/**
		* Void, fills the property currentTab with the correct value
		* @private
		*/
		setCurrentSubTab: function() {
			priv.currentSubTab = $.query.get('sub').toLowerCase();
			if (priv.currentSubTab.length < 1) {
				priv.currentSubTab = $('body').attr('class');
			}
			Log.Debug("AccoMain: currentSubTab is '" + priv.currentSubTab + "'");
		},

		/**
		* Binds the events, sets the classes for the personal item logic
		* makes sure to update the alreadyviewed list, and adds logic to the favorites button
		* @private
		*/
		personalItemsLogic: function() {
			//bind event to the page load, to update the "alreadyviewed" items
			$(window).bind("load",
                function() {
                	PersonalItems.Add("alreadyviewed", priv.accoId);
                	PersonalItems.ShowItemLinks();
                }
            );

			//test wether this is a favorite
			if (PersonalItems.Contains("favorites", priv.accoId)) {
				$(config.favoriteTrigger).addClass("is-favorite");
				$(config.favoriteTrigger + " span").html(Resource.GetText('is_favorite'));
			}

			//bind the click event for the trigger
			$(config.favoriteTrigger).bind("click",
                function(evt) {
                	Log.Debug(config.favoriteTrigger);
                	//animation from button to the Personal items in left menu
                	priv.addFavoriteAnimation();

                	//check for add or removal of the favo
                	if (!$(this).hasClass("is-favorite")) {
                		$(this).addClass("is-favorite");
                		$(this).find("span").html(Resource.GetText('is_favorite'));
                		PersonalItems.Add("favorites", priv.accoId);

                		//update the personal item links
                		PersonalItems.ShowItemLinks();
                	}
                	else {
                		//do nothing
                	}

                	//prevent event bubbling
                	return false;
                }
            );
		},

		/**
		* Binds the events, sets the classes for gallery logic
		* @private
		*/
		galleryLogic: function() {
			$('.gallery a').bind('click', function(e) {
				priv.galleryIndex = 0;
				priv.showGallery();
			});
			$('.gallery-nav a').bind('click', function(e) {
				priv.galleryIndex = $(this).parent().index() + 1;
				priv.showGallery();
			});
		},

		showGallery: function() {
			priv.openLightbox('pCarousel', {
				container: document.getElementById('pCarousel'),
				clone: false,
				onShowCallback: function() {
					if (!priv.galleryInitialized) {
						Carousel.init('#pCarousel ul', priv.galleryIndex, 5);
						$('#main-photo').bind('click', function(e) {
							Carousel.nextPhoto();
						});
						priv.galleryInitialized = true;
					}
					else {
						Carousel.pagePhoto(priv.galleryIndex);
					}
				},
				height: 600,
				width: 624
			});
		},

		printLogic: function() {
			//Get the anchor print button and add an click event
			$('.ico-print').bind('click', function() {
				priv.ShowPrintOptions();
			});

			$('div.print-options').find(".printoption").bind("click", function() {
				return false;
			}).find('.printoptionCheck:not(.disabled)').bind('click', function() {
				if ($(this).hasClass("checked")) {
					$(this).removeClass("checked");

					var printOption = $(this).attr("id");

					if ($('div.print-submit a.submit').attr("href").indexOf(printOption) != -1) {

						var optionToRemove = "," + printOption;
						var newhref = $('div.print-submit a.submit').attr("href").replace(optionToRemove, "");

						$('div.print-submit a.submit').attr("href", newhref);
					}
				}
				else {
					$(this).addClass("checked");

					var printOption = $(this).attr("id");
					var hrefnew = $('div.print-submit a.submit').attr("href") + "," + printOption;

					$('div.print-submit a.submit').attr("href", hrefnew);
				}
				return false;
			});
		},

		ShowPrintOptions: function() {
			priv.openLightbox('pPrintOptions', {
				container: document.getElementById('pPrintOptions'),
				clone: false,
				onShowCallback: function() { },
				width: 280
			});
		},

		orderedAccoListLogic: function() {
			//The container to work with
			var container = 'sorted-list-wrapper';

			//calculate the max height for this container according top the highest ul
			var height = 0;

			$("#" + container + " .inner-wrapper div").each(function(i) {
				if (height < $(this).height()) {
					height = $(this).height();
				}
			});

			$("#" + container).css("height", height);

			//make the first ul tag active on startup
			priv.moveOrderedAccoList(0);

			//bind click events for the navigation
			$("#sidebar .residence-box .sort-box ul li a").each(function(index) {
				$(this).bind("click", function() {
					if (!$(this).hasClass("active")) {
						priv.moveOrderedAccoList(index);
					}
				});
			});

			priv.bindAccommodationHover();
		},

		moveOrderedAccoList: function(newIndex) {
			//The container to work with
			var container = 'sorted-list-wrapper';

			var previousActiveIndex = -1;

			var slidingOffset = '182'; // total width of .residence-box ul (width + padding left + padding right) + margin-right of sorted-list-block

			//Reset the navigation items css styles
			$("#sidebar .residence-box .sort-box ul li a").each(function(i) {
				if ($(this).hasClass("active")) {
					previousActiveIndex = i;
					$(this).removeClass("active");
				}
			});

			//Make the specified navigation item active
			$("#sidebar div.residence-box .sort-box ul li:eq(" + newIndex + ") a").addClass("active");

			//Calculate whether to slide left or right
			var newLeft = 0;

			if (previousActiveIndex == -1) {
				previousActiveIndex = 0;
			}

			newLeft = slidingOffset * newIndex;

			$("#" + container + " .inner-wrapper").animate({ left: '-' + newLeft + 'px' }, 500);
		},

		bindAccommodationHover: function() {
			var path = Resource.GetText("path_prefix");
			var ttOptions = {
				trigger: "hover",
				autoClose: true,
				source: "ajax",
				type: "GET",
				loadingText: "",
				loadingImg: "",
				url: path + "/_html/popups/acco-hover-block.aspx",
				onShowCallback: Main.showHoverCallback
			};

			$('#sorted-list-wrapper div.sorted-list-block ul li').each(function() {
				var $this = $(this).find('a');
				ttOptions["data"] = "id=" + $this.attr("rel") + "&theme=accommodation";
				ttOptions["locationId"] = $this.attr("rel");
				$(this).jHelperTip(ttOptions);

				$(this).bind('click', function(e) {
					location.href = $this.attr('href');
					return false;
				});
			});
		},

		tabsLogic: function() {
			//tab specific logic
			if (priv.currentTab == "reviews") {
				if (priv.currentSubTab == "tips") {
					priv.tipsTab();
				}
				else {
					priv.reviewsTab();
				}
			}

			if (priv.currentSubTab == "car") {
				priv.carSubTab();
			}
			else if (priv.currentSubTab == "weather") {
				if (typeof (WeatherMain) != "undefined" && WeatherMain) {
					WeatherMain.AddEvenOddClasses();
				}
			}
		},

		/**
		*  Logic for reviews tab
		*/
		reviewsTab: function() {
			Main.hideItems(config.maxReviews, "reviews", "#review-count");
		},

		/**
		*  Logic for tips tab
		*/
		tipsTab: function() {
			Main.hideItems(config.maxTips, "tips", "#tips-count");
		},

		buildSearchTermsTooltip: function() {
			var $searchTerms = $(config.searchTerms);
			if ($searchTerms.get(0) && $searchTerms.attr('rel').length > 0) {
				$searchTerms.jHelperTip({
					trigger: 'hover',
					source: 'attribute',
					opacity: 1.0,
					attrName: 'rel',
					ttC: '#searchterms-tooltip'
				});
			}
		},

		carSubTab: function() {
			//AccoMain.AddStylesToCarRentalTableRows();

			// TEMP FIX	FOR UGLY CARRENTAL TABLES IN DESK, see WS-5062
			$("#carrentalDiv table").appendTo($("#carrentalPopupContent"));
			$("#carrentalDiv").append("<a class='carrent-info' href='javascript:void(0);'>Autohuur prijzen en voorwaarden</a>");

			// Bind methods to show popups for questions in main area
			$('a.carrent-info').bind("click", function() {
				//strip CMS styles from table
				$("#pCarrentalPopup table").css("border-collapse", "collapse");
				$("#pCarrentalPopup tr, #pCarrentalPopup td").width("auto");
				priv.openLightbox('pCarrentalPopup', {
					container: document.getElementById('pCarrentalPopup'),
					width: '1000px',
					clone: false
				});
			});

		},

		addObjectIndex: function() {
			// look if there is an objectindex in the url
			var objectIndex = $.query.get('objectIndex');

			// get the current url
			var url = document.location.href;
			var lastIndex = url.indexOf('?');
			if (lastIndex == -1) {
				lastIndex = url.length;
			}
			var startIndex = url.lastIndexOf('/');
			url = url.substring(startIndex, lastIndex);

			// look if there are links to the current url without the objectindex

			var objectIndexSetterTimer = new Timer();
			$("#content a").not("#prices table a, #favorite a, #pPrintOptions a, [id*='AvailableDurationAction']").each(function(i) {
				if (this.href.indexOf(url) != -1) {
					if (objectIndex != null && objectIndex !== '' && this.href.indexOf('objectIndex') == -1) {
						if (this.href.indexOf('?') > -1) {
							this.href = this.href + '&objectIndex=' + objectIndex;
						} else {
							this.href = this.href + '?objectIndex=' + objectIndex;
						}
					}

					if (this.href.indexOf('view=prices') != -1) {
						if (this.href.indexOf('#') == -1)
							this.href += "#dur-x";
						$(this).click(function() {
							if (this.href != location.href) {
								priv.showLoader();
							}
						});
					}
				}
			});

			//preload waiter images
			var images = new Array();
			images[images.length] = Resource.GetText("path_prefix") + "/images/ajax-loader.gif";
			images[images.length] = Resource.GetText("path_prefix") + "/images/price-loader.png";

			var imagePreloader = new ImagePreloader(images, function() { });

			Log.Info("AccoMain: Adding objectIndices took : " + (objectIndexSetterTimer.Stop()) + " ms", -1);
		},

		getTotalMarginPadding: function(element) {
			return $(element).outerHeight(true) - $(element).innerHeight();
		},

		bindEvents: function() {
			priv.bindReviewsEvents();
			priv.bindTipsEvents();
			priv.bindToolboxEvents();
			priv.bindRatingsEvents();
			priv.bindBestPriceTagEvents();
			priv.bindWeatherblockEvent();
		},

		bindReviewsEvents: function() {
			$(config.reviewsBlockElement).bind('click', function(e) {
				var url = $(this).find('a').attr('href');
				document.location.href = url;

				return true;
			});
		},

		bindWeatherblockEvent: function() {
			$(config.weatherBlockElement).bind('click', function(e) {
				var url = $(this).find('a').attr('href');
				document.location.href = url;

				return true;
			});
		},

		bindTipsEvents: function() {
			$(config.tipsBlockElement).bind('click', function(e) {
				var url = $(this).find('a').attr('href');
				document.location.href = url;

				return true;
			});
		},

		bindToolboxEvents: function() {
			$(config.emailLinkElement).bind("click", function() {
				priv.showSendAccoPopup();
				return false;
			});
		},

		bindRatingsEvents: function() {
			$('#img-rating-info').bind("click", function() {
				priv.showRatingPopup(this);
				return false;
			});
		},

		bindBestPriceTagEvents: function() {

			var linkUrl = $('span.lmonth').text();

			$(config.bestPriceTagElement).bind("click", function() {
				location.href = linkUrl;
			});

			$(config.bestPriceContentTagElement).find('p').bind("click", function() {
				location.href = linkUrl;
			});

			$(config.bestPriceContentTagElement).find('p').hover(
                function() {
                	$(this).addClass("lmonthcontenthover");
                	$(config.bestPriceContentTagElement).find('ul').addClass("lmonthcontenthover");
                },
                function() {
                	$(this).removeClass("lmonthcontenthover");
                	$(config.bestPriceContentTagElement).find('ul').removeClass("lmonthcontenthover");
                }
            );

			$(config.bestPriceContentTagElement).find('ul').bind("click", function() {
				location.href = linkUrl;
			});

			$(config.bestPriceContentTagElement).find('ul').hover(
                function() {
                	$(this).addClass("lmonthcontenthover");
                	$(config.bestPriceContentTagElement).find('p').addClass("lmonthcontenthover");
                },
                function() {
                	$(this).removeClass("lmonthcontenthover");
                	$(config.bestPriceContentTagElement).find('p').removeClass("lmonthcontenthover");
                }
            );
		},

		showSendAccoPopup: function() {
			$('#sendAccoContent').show();
			$('#sendAccoMessage').hide();
			//			priv.openLightbox('pSendAcco', {
			//				container: document.getElementById('pSendAcco'),
			//				clone: false,
			//				width: 560
			//			});
		},



		showRatingPopup: function(el) {
			var id = 'pRating';
			var config = null;

			if ($('#' + id).html().trim() == '') {
				config = {
					container: document.getElementById(id),
					width: '410px'
				};
				if (typeof (el) != "undefined" && el) {
					config.contentUrl = $(el).attr('href') + " #popup";
				}
			}

			priv.openLightbox(id, config);
		},
		
		showLoader: function() {
			if ($('#wait').length == 0) {
				$("body").append(
						$("<div id='wait'><img class='bg' src='" + Resource.GetText("path_prefix") +
						"/images/price-loader.png'><img class='loader' src='" + Resource.GetText("path_prefix") +
						"/images/ajax-loader.gif'><span>" + Resource.GetText("loading_prices") + "</span></div>")
					);
			}
		}
	};

	/** @scope AccoMain */
	return {
		showLoader: function(){
			priv.showLoader();
		},
		
		showAddReviewPopup: function() {
			$('#addreview-content').show();
			$('#addreview-send').hide();
			priv.openLightbox('add-review-lightbox', {
				container: document.getElementById('add-review-lightbox'),
				clone: false,
				width: 560
			});
		},

		/**
		* Initializes the logic for the current page
		* to be called on $(document).ready
		*/
		OnReady: function() {
			Log.Info("AccoMain: Called OnReady");

			//determine the current accoId
			priv.accoId = $("#accoId").val();

			//determine the current tab
			priv.setCurrentTab();

			//determine the current subtab, only for destinations and description main tabs
			if (priv.currentTab == "destination" || priv.currentTab == "descriptions" || priv.currentTab == "reviews") {
				priv.setCurrentSubTab();
			}

			//do favorite logic (bind events, set classes)
			priv.personalItemsLogic();

			//do gallery logic (bind events, set active thumbnail etc)
			priv.galleryLogic();

			//do print logic (bind the events, shows print options light box
			priv.printLogic();

			//do ordered accommodation list logic (bind events, set classes etc)
			priv.orderedAccoListLogic();

			priv.buildSearchTermsTooltip();

			// Moved criteo block from document.write() in the masterpagedetail.master file, to this place, we set it from the javascript instead.
			if (document.location.protocol != "https:") {
				$("#criteoHolder").append('<div id="cto_se_7709485_ac" style="display:none"><div class="ctoWidgetServer">http://sunweb.widget.criteo.com/psu/</div><div class="ctoDataType">sendEvent</div><div class="ctoParams">wi=7709485&amp;pt1=2&amp;i=' + priv.accoId + '</div></div>');
			}

			priv.tabsLogic();

			priv.addObjectIndex();
			priv.bindEvents();

			if (typeof (AccoPrices) != "undefined") {
				var accoPricesTime = new Timer();
				AccoPrices.OnReady();
				Log.Info("AccoMain: AccoPrices Javascript load time was: " + (accoPricesTime.Stop()) + " ms", -1);
			}
		},

		AddStylesToCarRentalTableRows: function() {
			$(config.carRentalTableElement).find('tr:even').addClass('even');
			$(config.carRentalTableElement).find('tr:odd').addClass('odd');
			$(config.carRentalTableElement).find('td:even').addClass('even');
			$(config.carRentalTableElement).find('td:odd').addClass('odd');
		}
	};
} (jQuery);



