﻿/**
 * static object that handles page logic
 * @class 
 * @constructor
 * @param {jQuery} $ Reference to the jQuery object
 */
var Main = function($) {

	/**
	* @namespace Private methods and variables
	*/
	var priv = {
		/**
		* Sets the debug level
		* @private
		*/
		debugSeverity: 0, //level of error logging
		msie6: ($.browser.msie && typeof (XMLHttpRequest) == "undefined" && (/MSIE 6\.0/i.test(window.navigator.userAgent)) && !(/MSIE 7\.0/i.test(window.navigator.userAgent)) && !(/MSIE 8\.0/i.test(window.navigator.userAgent))),
		mozff2: ($.browser.mozilla && (parseFloat($.browser.version) < 1.9)),
		examCookieId: 'exampage-cookie',
		compareCookieId: 'compare',
		compareMaximum: 5,

		markFavoriteAndCompareItems: function() {
			var listerItems = $('#content .block-post .post, #main .acco-item, aside.information-aside');
			if (listerItems.length) {
				$('div.area-btn').not(".print").bind('click', function() {
					return false;
				});
				
				var items = PersonalItems.Load("favorites");
				var compareItems = PersonalItems.Load(priv.compareCookieId);
				listerItems.each(function() {
					var thisId = $(this).attr("id");
					//check whether this is a valid list-item
					if (!thisId) {
						return true;
					}
					thisId = thisId.substring(thisId.lastIndexOf("-") + 1);

					var favoriteButton = $('.btn-favorite', this);
					favoriteButton.bind('click', function() {
						//check for add or removal of the favo
						if ($(this).hasClass("is-favorite")) {
							favoriteButton.removeClass("is-favorite");
							favoriteButton.find("span").html(Resource.GetText('add_favorite'));
							PersonalItems.Remove("favorites", thisId);
							PersonalItems.ShowItemLinks();
						}
						else {
							favoriteButton.addClass("is-favorite");
							favoriteButton.find("span").html(Resource.GetText('is_favorite'));
							PersonalItems.Add("favorites", thisId);
							PersonalItems.ShowItemLinks();
						}

						//prevent event bubbling
						return false;
					});

					for (var j = 0; j < items.length; j++) {
						if (thisId == items[j].id) {
							favoriteButton.addClass('is-favorite');
							favoriteButton.find("span").html(Resource.GetText('is_favorite'));
							break;
						}
					}

					var compareButton = $('.btn-compare', this);
					compareButton.bind('click', function() {
						//check for add or removal of the favo
						if ($(this).hasClass("is-compare")) {
							compareButton.removeClass("is-compare");
							PersonalItems.Remove(priv.compareCookieId, thisId);
							PersonalItems.ShowItemLinks();
						}
						else {
							var itemCount = PersonalItems.GetItemCount(priv.compareCookieId);
							if (itemCount < priv.compareMaximum) {
								compareButton.addClass("is-compare");
								PersonalItems.Add(priv.compareCookieId, thisId);
								PersonalItems.ShowItemLinks();
							} else {
								alert(Resource.GetText("COMPARE_MAXIMUM", priv.compareMaximum));
							}
						}

						//prevent event bubbling
						return false;
					});

					for (var j = 0; j < compareItems.length; j++) {
						if (thisId == compareItems[j].id) {
							compareButton.addClass('is-compare');
							break;
						}
					}
				});
			}
		},

		setExamCookie: function() {
			var bodyClass = $('body').attr('class');
			if (bodyClass == 'destination-exam') {
				// set cookie exam page is visited
				$.cookie(priv.examCookieId, location.href, { expires: null, path: '/' });
			} else if (bodyClass.indexOf('accommodation-') == 0) {
				// set results link to exam page
				var examCookieValue = $.cookie(priv.examCookieId);
				if (examCookieValue != null && examCookieValue != '') {
					$('.paging-area .link-info').attr('href', $.cookie(priv.examCookieId));
				}
			} else {
				// remove cookie, not on exam page and not on acco page
				$.cookie(priv.examCookieId, '', { expires: -1, path: '/' });
			}
		},

		loadResultList: function() {
			// logic for result list (list of accommodations, like on search page)
			if (typeof (ResultList) != "undefined") {
				var resultListTime = new Timer();

				ResultList.OnReady({ compareLinkElement: "#not-used",
					compareCheckHolderElement: "#not-used",
					compareCheckElement: "#not-used",
					resultListElements: "#main .acco-item, #content .post",
					resultListAnchorElement: '.post-holder>a'
				});
				Log.Info("Main: ResultList Javascript load time was: " + (resultListTime.Stop()) + " ms", -1);
			}
		}
	};

	/** @scope Main */
	return {

		GoToComparePage: function() {
			var compareItems = PersonalItems.Load(priv.compareCookieId);
			if (compareItems.length < 2) {
				alert(Resource.GetText("COMPARE_MINIMUM"));
			} else {
				var compareIds = '';
				for (var j = 0; j < compareItems.length; j++) {
					compareIds += compareIds == '' ? compareItems[j].id : ',' + compareItems[j].id;
				}
				location.href = Resource.GetText('path_prefix') + '/_search/compare.aspx?personal=compare&id=' + compareIds;
			}
			return false;
		},

		/**
		* Initializes the logic for the current page
		* to be called on $(document).ready
		*/
		OnReady: function() {
			//overal js timer
			var overallTime = new Timer();

			//show oldbrowser notification when using old browsers
			if (priv.msie6 || priv.mozff2) {
				if (typeof (OldBrowser) != "undefined" && OldBrowser) {
					var oldBrowserTime = new Timer();
					OldBrowser.OnReady();
					Log.Info("Main: OldBrowser Javascript load time was: " + (oldBrowserTime.Stop()) + "ms ", -1);
				}
			}

			//enable/disable debugging
			Log.SetDebugging(Resource.GetText("js-debug-enabled") == 'true');
			Log.SetLevel(priv.debugSeverity);

			if (typeof (Utils) != "undefined" && Utils) {
				Utils.OnReady();
			}

			//load PersonalItems logic
			var personalItemsTimer = new Timer();
			//load and show the personal item links
			PersonalItems.Load("alreadyviewed");
			PersonalItems.Load("favorites");
			PersonalItems.Load("compare");
			PersonalItems.ShowItemLinks();
			Log.Info("Main: PersonalItems script time was: " + (personalItemsTimer.Stop()) + " ms", -1);

			priv.markFavoriteAndCompareItems();

			priv.setExamCookie();

			// load the travelers
			if (typeof (Occupancy) != "undefined") {
				var occupancyTime = new Timer();
				Occupancy.OnReady({ filterSearch: 0, autorefresh: false });
				Log.Info("Main: Occupancy Javascript load time was: " + (occupancyTime.Stop()) + " ms", -1);
			}

			//load CarRentals
			if (typeof (CarRental) != "undefined") {
				CarRental.OnReady();
			}

			// load the resource info
			if (typeof (ResourceInfo) != "undefined") {
				var resourceInfoTime = new Timer();
				ResourceInfo.OnReady();
				Log.Info("Main: ResourceInfo Javascript load time was: " + (resourceInfoTime.Stop()) + " ms", -1);
			}

			priv.loadResultList();

			//load homepage specific logic
			if (typeof (HomeMain) != "undefined" && HomeMain) {
				var homeMainTime = new Timer();
				HomeMain.OnReady();
				Log.Info("Main: HomeMain Javascript load time was: " + (homeMainTime.Stop()) + "ms ", -1);
			}

			//load accommodation specific logic
			if (typeof (AccoMain) != "undefined" && AccoMain) {
				var accoMainTime = new Timer();
				AccoMain.OnReady();
				Log.Info("Main: AccoMain Javascript load time was: " + (accoMainTime.Stop()) + "ms ", -1);
			}

			//load search specific logic
			if (typeof (SearchMain) != "undefined" && SearchMain) {
				var searchMainTime = new Timer();
				SearchMain.OnReady();
				Log.Info("Main: SearchMain Javascript load time was: " + (searchMainTime.Stop()) + "ms ", -1);
			}

			//load participant logic
			if (typeof (ParticipantConfig) != "undefined" && ParticipantConfig) {
				var participantTime = new Timer();
				ParticipantConfig.OnReady();
				Log.Info("Main: ParticipantConfig Javascript load time was: " + (participantTime.Stop()) + "ms ", -1);
			}

			//load reservation logic            
			if (typeof (Reservation) != "undefined" && Reservation) {
				var reservationTime = new Timer();
				Reservation.OnReady();
				Log.Info("Main: Reservation Javascript load time was: " + (reservationTime.Stop()) + "ms ", -1);
			}

			//load confirmation logic
			if (typeof (Confirmation) != "undefined" && Confirmation) {
				var confirmationTime = new Timer();
				Confirmation.OnReady();
				Log.Info("Main: Confirmation Javascript load time was: " + (confirmationTime.Stop()) + "ms ", -1);
			}

			//load destination/location specific logic
			if (typeof (LocationMain) != "undefined" && LocationMain) {
				var locationMainTime = new Timer();
				LocationMain.OnReady();
				Log.Info("Main: LocationMain Javascript load time was: " + (locationMainTime.Stop()) + "ms ", -1);
			}

			// logic for static pages
			if (typeof (StaticMain) != "undefined" && StaticMain) {
				var staticMainTime = new Timer();
				StaticMain.OnReady();
				Log.Info("Main: StaticMain Javascript load time was: " + (staticMainTime.Stop()) + "ms ", -1);
			}

			//load compare specific logic
			if (typeof (CompareMain) != "undefined" && CompareMain) {
				var compareMainTime = new Timer();
				CompareMain.OnReady();
				Log.Info("Main: CompareMain Javascript load time was: " + (compareMainTime.Stop()) + "ms ", -1);
			}

			if (Resource.GetText("show_ribbon_tag") == "true") {
				var userOpinionTime = new Timer();

				var pathPrefix = Resource.GetText('path_prefix');
				var userOpinion = new UserOpinion({
					handler: pathPrefix + "/js/ajax/sendreaction.ashx",
					popupContent: pathPrefix + "/documents/html/popups/send_reaction.htm"
				});

				Log.Info("Main: UserOpinion Javascript init time was: " + (userOpinionTime.Stop()) + "ms ", -1);
			}

			//end overallTimer
			Log.Info("Main: Overall Javascript load time was: " + (overallTime.Stop()) + "ms ", -1);
		},

		BindSearchEvents: function() {
			priv.loadResultList();
			priv.markFavoriteAndCompareItems();
		}
	};
} (jQuery);


// The supplied function is executed when dom is ready. In this case,
// we execute the Main.OnReady function, which will execute all functions
// necessary for the page to work correctly
$(document).ready(function($){
    Main.OnReady();
});


var OldBrowser = function($) {
    var priv = {
        oldBrowserCookieId: 'oldbrowser-popup-shown'
    };

    return {
        /**
        * Initializes the logic for the current page
        * to be called on $(document).ready
        */
        OnReady: function() {
            var isAlreadyShown = $.cookie(priv.oldBrowserCookieId);
            if (isAlreadyShown == null || !isAlreadyShown) {
                var lightbox = Lightbox.CreateCached('oldbrowser-popup', {
                    closeText: null,
                    contentUrl: Resource.GetText("path_prefix") + '/_html/popups/oldbrowser.aspx',
                    clone: false,
                    height: 614,
                    width: 402
                });
                lightbox.Show();
                $.cookie(priv.oldBrowserCookieId, true, { expires: null, path: '/' });
            }
        }
    }
} (jQuery);

