﻿/**
 * @class Result list logic and functionallity
 * depends on jQuery, jQuery-cookie, and sunweb static "logic" object
 */
var accoDetails = function($) {

	/**
	* @namespace Private methods and properties
	*/
	var priv = {

		/**
		* @private
		*/
		accoId: null,

		/**
		* @private
		*/
		extendedTabs: "ul#extended-tabs", //tabs element-id

		/**
		* @private
		*/
		extendedTabsWidth: 530,

		/**
		* @private
		*/
		mapTabs: "ul#map-tabs",

		/**
		* @private
		*/
		maxReviews: 10,

		/**
		* @private
		*/
		photoCurrentIndex: 0,

		/**
		* @private
		*/
		photoTotalItems: 0,

		/**
		* @private
		*/
		photoAnimateTimeout: null,

		/**
		* 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();
		},

		/**
		* Check the name length, and adjust the font size to keep the name on one line
		* @private
		*/
		adjustAccoName: function() {
			var $accoName = $("#detail-info h1.acco-name");
			var $accoLocation = $("#detail-info h2.acco-location");
			var $accoDetails = $accoName.parent();
			var $starRating = $("#detail-info span.star-rating");

			//the height of the $accoName plus $accoLocation should add up to the height of their parent element
			//if not the stars are wrapping on a new line. If this happens, make the $accoName fontsize smaller
			var parentHeight = $accoDetails.get(0).offsetHeight - 5;
			var addedHeight = $accoName.height() + $accoLocation.height() + parseInt($accoLocation.css("margin-bottom"));

			//make the font-size smaller as long as the lines wrap
			while (parseInt($accoName.css("font-size")) > 14 && addedHeight < parentHeight) {
				Log.Debug("accoName fontSize: " + $accoName.css("font-size"));
				var newFontSize = (parseInt($accoName.css("font-size")) - 1);
				$accoName.css({ "font-size": newFontSize + "px", "line-height": newFontSize + 2 + "px" });
				$starRating.height(newFontSize);

				addedHeight = $accoName.height() + $accoLocation.height() + parseInt($accoLocation.css("margin-bottom"));
				parentHeight = $accoDetails.get(0).offsetHeight - 5;
				Log.Debug("accoDetails height: " + parentHeight + "\n addedHeight: " + addedHeight);
			}
		},

		/**
		* helps older browsers with modern CSS 
		*/
		highlightTabs: function() {
			Log.Debug("correcting tabs");
			var $mapTabs = $(priv.mapTabs);
			//for the map tabs
			$mapTabs.find("li:last-child").css({ "background-image": "none" });
			$mapTabs.find("li.selected:first-child a").css({ "border-width": "0px 1px 0px 0px;" });
			$mapTabs.find("li.selected:only-child a").css({ "border-width": "0px 0px 0px 0px" });

		},

		/**
		* Recalculate the padding for the extended-tabs, to make sure the total width
		* of the tabs stays the same, regardless of how many tabs there are.
		* @private
		*/
		paddingTabs: function() {
			Log.Debug("correcting tab padding");
			var $extendedTabs = $(priv.extendedTabs);
			var UL_WIDTH = priv.extendedTabsWidth;
			if (typeof (prices) != "undefined" && prices != null)
				UL_WIDTH += 5;

			$extendedTabs.find("li:last-child a").css("padding-right", "0px");

			//recalculate the width of the menu
			var menuItemsWidth = 0;
			$extendedTabs.find("li").each(
                function(i) {
                	menuItemsWidth += ($(this).width());
                }
            );

			Log.Debug("menuItemsWidth: " + menuItemsWidth);

			//calculate the new padding
			var nrItems = $(priv.extendedTabs + " li").length;
			var itemPadding = Math.floor(((UL_WIDTH - menuItemsWidth) / 2) / nrItems);
			var padLeft = Math.floor(itemPadding);
			var padRight = Math.ceil(itemPadding);

			Log.Debug("padLeft: " + padLeft);
			Log.Debug("padRight: " + padRight);

			//now calculate the restpadding after correction
			var restPadding = UL_WIDTH - menuItemsWidth - nrItems * (padLeft + padRight);
			Log.Debug("restPadding: " + restPadding);
			var restPaddingLeft = Math.ceil(restPadding / 2);
			var restPaddingRight = Math.floor(restPadding / 2);


			//correct the padding for all the items
			var $links = $extendedTabs.find("li a");
			$links.each(
                function(i) {
                	//for the first item, add the correctionpadding
                	if (i == 0) {
                		$(this).css({ "padding-left": (restPaddingLeft + padLeft + parseInt($(this).css("padding-left"))) + "px" });
                	}
                	else {
                		$(this).css({ "padding-left": (padLeft + parseInt($(this).css("padding-left"))) + "px" });
                	}
                }
            );
			$links.find("span").each(
                function(i) {
                	if (i == 0) {
                		$(this).css({ "padding-right": (restPaddingRight + padRight + parseInt($(this).css("padding-right"))) + "px" });
                	}
                	else {
                		$(this).css({ "padding-right": (padRight + parseInt($(this).css("padding-right"))) + "px" });
                	}
                }
            );
		},

		/*
		* Binds the click events for the photos on the overview page
		*/
		bindPhotoEvents: function() {
			$("ul.photo-carousel>li").each(
                function(i) {
                	$(this).bind("click",
                        function(evt) {
                        	var newUrl = document.location.pathname;
                        	if (document.location.search.length > 1) {
                        		newUrl += "?view=photos&photoIndex=" + i + "&" + document.location.search.substr(1);
                        	}
                        	else {
                        		newUrl += "?view=photos&photoIndex=" + i;
                        	}
                        	Log.Debug("redirecting to : " + newUrl);
                        	document.location.href = newUrl;
                        }
                    );
                }
            );
		},

		initFavoriteLogic: function() {
			//test wether this is a favorite
			//            if (personalItems.Contains("favorites", priv.accoId)) {
			//                $(priv.favoriteTrigger).addClass("is-favorite");
			//                $(priv.favoriteTrigger + " span").html(resources.is_favorite);
			//            }

			//bind the click event for the trigger
			//            $(priv.favoriteTrigger).bind("click",
			//                function(evt) {
			//                    //test for add or removal of the favo
			//                    if ($(this).hasClass("is-favorite")) {
			//                        //add a new item
			//                        $(this).removeClass("is-favorite");
			//                        $(this).find("span").html(resources.add_favorite);
			//                        personalItems.Remove("favorites", priv.accoId);
			//                    }
			//                    else {
			//                        $(this).addClass("is-favorite");
			//                        $(this).find("span").html(Resource.GetText('is_favorite'));
			//                        personalItems.Add("favorites", priv.accoId);
			//                    }

			//                    //update the personal item links
			//                    //personalItems.ShowItemLinks();

			//                    //prevent event bubbling
			//                    return false;
			//                }
			//            );
		},

		bindMonthEvents: function() {
			$("#months .month-tabs li a").bind("click",
                function(evt) {
                	$(this).attr("href", $(this).attr("href") + "&sh=" + $("html").get(0).scrollTop);
                }
            );
		},

		processReviews: function() {
			var $reviews = $('ul.reviews li');
			// hide all reviews that are more than the maximum
			if ($reviews.length > priv.maxReviews) {
				for (var i = priv.maxReviews; i < $reviews.length; i++) {
					$($reviews[i]).css("display", "none");
				}

				// set the total number of reviews
				$('#review-count').html('(' + ($reviews.length - priv.maxReviews) + ')');

				// bind the show all reviews event to show all reviews link
				$('div.show-reviews a').bind("click",
                    function() {
                    	priv.showAllReviews();
                    }
                );
			} else {
				$('div.show-reviews').hide();
			}

			//finnaly show the ul
			$('ul.reviews').show();
		},

		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
			$("a").not("#prices table.head-table a").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) {
								if ($('#wait').length == 0) {
									$("body").append(
                                        $("<div id='wait'><img src='" + Resource.GetText("path_prefix") + "/images/ajax-loader.gif'>" + Resource.GetText("loading_prices") + "</div>")
                                    );
								}
							}
						});
					}
				}
			});
		},

		prevPhoto: function(carousel) {
			Log.Debug("prevPhoto - index: " + priv.photoCurrentIndex);
			priv.pagePhoto((priv.photoCurrentIndex - 1), carousel);
		},

		nextPhoto: function(carousel) {
			Log.Debug("current photoindex: " + priv.photoCurrentIndex);
			priv.pagePhoto((priv.photoCurrentIndex + 1), carousel);
		},

		pagePhoto: function(index, carousel) {
			$('#mycarousel li').removeClass('sel');
			if (index >= 0 && index < priv.photoTotalItems) {

				if (index >= (priv.photoTotalItems - 3)) {
					//alert("n");
					carousel.next();
				} else if (index < priv.photoCurrentIndex && index == (priv.photoTotalItems - 4)) {
					carousel.prev();
					//alert("p");
				} else {
					carousel.scroll(index);
					// alert("s");
				}

				priv.photoCurrentIndex = index;
				priv.showCurrentImage();

			}
			Log.Debug("new photoindex: " + priv.photoCurrentIndex);
			priv.setNextPrevButtonState();
		},

		showCurrentImage: function() {
			var $newSrc = $("img", 'li.jcarousel-item:eq(' + priv.photoCurrentIndex + ')').attr("src");
			$newSrc = $newSrc.replace("_115", "_400");
			$newSrc = $newSrc.replace("_80", "_266");
			$('.show-photo').attr("src", $newSrc);
			$('#curImageNr').html((priv.photoCurrentIndex + 1));
		},

		setNextPrevButtonState: function() {
			if (priv.photoCurrentIndex > 0) {
				$('.jcarousel-prev').removeClass('jcarousel-prev-disabled');
				$('.jcarousel-prev').removeClass('jcarousel-prev-disabled-horizontal');
			} else {
				$('.jcarousel-prev').addClass('jcarousel-prev-disabled');
				$('.jcarousel-prev').addClass('jcarousel-prev-disabled-horizontal');
			}
			if (priv.photoCurrentIndex == (priv.photoTotalItems - 1)) {
				$('.jcarousel-next').addClass('jcarousel-next-disabled');
				$('.jcarousel-next').addClass('jcarousel-next-disabled-horizontal');
			} else {
				$('.jcarousel-next').removeClass('jcarousel-next-disabled');
				$('.jcarousel-next').removeClass('jcarousel-next-disabled-horizontal');
			}
			$('.jcarousel-container li:eq(' + priv.photoCurrentIndex + ')').addClass('sel');
		},

		photoHover: function($liOjbect) {
			if (priv.photoAnimateTimeout != null) {
				window.clearTimeout(priv.photoAnimateTimeout);
			}
			var image = $('img', $liOjbect).get(0);
			var x = (document.layers) ? $liOjbect.get(0).x : $liOjbect.get(0).offsetLeft;
			var y = (document.layers) ? $liOjbect.get(0).y : $liOjbect.get(0).offsetTop;
			var width = (image.width / 2);
			var height = (image.height / 2);
			var offSetLeft = 0;
			if ($('#mycarousel').get(0).offsetLeft < 0) {
				offSetLeft = $('#mycarousel').get(0).offsetLeft;
			}
			$('#photoitem-hover').css({ 'top': (y + 22) + 'px', 'left': (x + 20 + offSetLeft) + 'px', 'background-image': 'url(' + image.src + ')', 'display': '' });
			$('#photoitem-hover').show();

			priv.photoAnimateTimeout = setTimeout("$('#photoitem-hover').animate({'top':'" + (y + 12) + "px','left':'" + (x + 10 + offSetLeft) + "px','width':'143px','height':'102px'});", 50);
		},

		promotionBlockLogic: function() {
			//bind forum-block click event
			$("#forum-block, #weather-block").bind("click",
                function(evt) {
                	//find the link in the element, and use its Href
                	var Href = $(this).find("a").attr("href");
                	if (Href) {
                		document.location.href = Href;
                	}
                	return false;
                }
            );

			$("#offers-block tr.promorow").bind("click",
                function(evt) {
                	//find the link in the element, and use its Href
                	var Href = $(this).find("a").attr("href");
                	if (Href) {
                		document.location.href = Href;
                	}
                	return false;
                }
            );

			//for the promotion offerlist
			$("#offers-block td:last-child").addClass("price");
			$('#offers-block tr.promorow').hover(
                 function(evt) {
                 	$(this).addClass("hover");
                 	return false;
                 },
                function(evt) {
                	$(this).removeClass("hover");
                	return false;
                }
            );

			$("#forum-block .list-head, #forum-block li").hover(
                function(evt) {
                	$(this).css('text-decoration', 'underline');
                	return false;
                },
                function(evt) {
                	$(this).css('text-decoration', 'none');
                	return false;
                }
            );
		},

		/**
		* Show the element matching the supplied ID in a lightbox. Used on the offers page.
		* @param {HTMLElement} anchor The anchor element referencing the popup contents.
		* @param {String} id The id of the popup container
		* @return {Boolean} Returns false to allow event handlers to easily stop default browser behavior
		* @private
		*/
		showOfferInfoInLightbox: function(anchor, id) {
			priv.openLightbox(id, {
				container: document.getElementById(id),
				contentUrl: $(anchor).attr('href'),
				width: '500px'
			});
			return false;
		}
	};

	/**
	* @scope accoDetails
	*/
	return {

		showRatingPopup: function(el) {
			var id = 'pRating';
			var config = null;

			if ($('#' + id).html() == '') {
				config = {
					container: document.getElementById(id),
					width: '410px'
				};
				if (typeof (el) != "undefined" && el) {
					config.contentUrl = $(el).attr('href') + " #popup";
				}
			}

			priv.openLightbox(id, config);
		},

		showSendAccoPopup: function() {
			$('#sendAccoContent').show();
			$('#sendAccoMessage').hide();
//			priv.openLightbox(id, {
//				container: document.getElementById('pSendAcco'),
//				width: '623px',
//				clone: false
//			});
		},

		showAddReviewPopup: function() {
			$('#addreview-content').show();
			$('#addreview-send').hide();
			priv.openLightbox('add-review-lightbox', {
				container: document.getElementById('add-review-lightbox'),
				width: '623px',
				clone: false
			});
		},

		/**
		* should be triggered on $(document).ready
		*/
		OnReady: function() {
			// set mainsearchtab to searchquery
			var searchQuery = $('.back a', 'div.breadcrumb').attr('href');

			if (typeof searchQuery != 'undefined') {
				if (Resource.GetText('isofferspage') == 'true') {
					$('#ctl00_lioffers a').attr('href', searchQuery);
				} else {
					$('#ctl00_lisearch a').attr('href', searchQuery);
				}
			}

			priv.accoId = $("#accoId").attr("value"); //get the accommodation id
			var currentTab = $.query.get('view').toLowerCase();
			if (currentTab.length < 1) {
				currentTab = $('body').attr('class') || location.href.match(/([a-zA-Z]+)\.aspx/)[1];
			}

			priv.initFavoriteLogic();

			var Timer1 = new Timer();
			priv.adjustAccoName();
			Log.Debug("adjustAccoName time was: " + (Timer1.Stop()) + "ms ", -1);

			Timer1.Start();
			//huge performance gain for IE6 on prices
			if (currentTab == 'prices' && $.browser.msie && $.browser.version == "6.0") {
				$(window).bind("load",
                    function() {
                    	priv.paddingTabs(); //correct the padding for the tabs
                    	priv.addObjectIndex(); // make sure the objectIndex is remembered
                    }
                );
			}
			else {
				//other browser can do this onready
				priv.paddingTabs(); //correct the padding for the tabs
				priv.addObjectIndex(); // make sure the objectIndex is remembered
			}
			Log.Debug("paddingTabs time was: " + (Timer1.Stop()) + "ms ", -1);

			Timer1.Start();
			priv.highlightTabs(); //correct the CSS for older browsers
			Log.Debug("highlightTabs time was: " + (Timer1.Stop()) + "ms ", -1);

			Timer1.Start();
			priv.bindPhotoEvents(); //binds the events for the photocarousel on the overview page			
			Log.Debug("bindPhotoEvents time was: " + (Timer1.Stop()) + "ms ", -1);

			if (currentTab != 'prices') {
				Timer1.Start();
				priv.promotionBlockLogic();
				Log.Debug("promotionBlockLogic time was: " + (Timer1.Stop()) + "ms ", -1);
			}

			Timer1.Start();
			if ($('a.searchterms').get(0) && $('a.searchterms').attr('rel').length > 0) {
				$('a.searchterms').jHelperTip({
					trigger: 'hover',
					source: 'attribute',
					opacity: 1.0,
					attrName: 'rel',
					ttC: '#searchterms-tooltip'
				});
			}

			$('#img-rating-info').bind("click", function() {
				accoDetails.showRatingPopup(this);
				return false;
			});

			//binds the add to already viewed cookie to the onload
			$(window).bind("load", function() {
				PersonalItems.Add("alreadyviewed", priv.accoId);
				PersonalItems.ShowItemLinks();
			});

			//hide the location image if it is not available
			$("#accoCityDescriptionPhoto img").bind("error", function(evt) {
				$(this).parent().hide();
			});

			Log.Debug("other meantime was: " + (Timer1.Stop()) + "ms ", -1);

			Timer1.Start();
			// limit the number of reviews initialy shown

			if (currentTab == 'reviews') {
				priv.processReviews();
			}
			else if (currentTab == 'offers') {
				$("body").append("<div id=\"offersDepartureUnknownPopup\"></div>");
				$("body").append("<div id=\"offersDepartureKnownPopup\"></div>");
				$('a.moreinfo').bind("click", function() { return priv.showOfferInfoInLightbox(this, "offersDepartureKnownPopup"); });
				$('a.moreinfounknown').bind("click", function() { return priv.showOfferInfoInLightbox(this, "offersDepartureUnknownPopup"); });
			}

			Log.Debug("Tabspecific time was: " + (Timer1.Stop()) + "ms ", -1);

			$('div.pricetag span.price').bind("click", function() {
				var url = $('a.lowestprice-url').attr('href');
				location.href = url;
			});
		}
	};
} (jQuery);

