﻿/**
 * static object that handles page logic
 * @class
 * @constructor
 * @param {jQuery} $ Reference to the jQuery object
 */
var SearchMain = function($) {

	/**
	* @namespace Private methods and variables
	*/
	var priv = {
		freeTextInputElement: "div.search-form input[type=text]",
		searchbarSelectElement: "form.form select",
		searchbarInputElement: "form.form input",
		freeTextSubmitElement: "div.search-form input[type=submit]",
		favoriteTrigger: ".btn-favorite",
		selectedDateNValue: "",
		selectedDateParam: "",


		/**
		* Container object, holding references to the lightboxes that have been initialized in this page.
		* Using this each lightbox only has to be instantiated once, when it is first called.
		* @type {Lightbox}
		* @private
		*/
		lightboxes: {},

		/**
		* 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) {
			if (typeof (options) == 'undefined' || !options) {
				options = { container: document.getElementById(id) };
			}
			var lightbox = Lightbox.CreateCached(id, options);
			lightbox.Show();
		},

		/**
		* 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;
		},

		/**
		* Bind general events for this page
		* @private
		*/
		bindEvents: function() {
			if (location.href.indexOf('personal=') != -1) {
				$('body').addClass('search-personal');
				priv.setCompareChecked();
			} else {
				priv.bindTextSearch();
			}

			// autocomplete functionality
			$(priv.freeTextInputElement).autocomplete(Resource.GetText('path_prefix') + "/js/ajax/get_searchsuggestions.ashx", {
				selectFirst: false,
				delay: 10,
				width: 200,
				max: 15,
				matchSubset: false
			}).result(function(event, item) {
				priv.textSearch();
			});

			$('.no-result #restart_search').click(function() {
				Occupancy.saveTotalTravelers(0);
				window.location = Resource.GetText('path_prefix') + '/' + Resource.GetText('searchpage');
			});
			$('.to-available a').live('click', function() {
				Occupancy.saveTotalTravelers(0);
				if (document.location == this.href) {
					document.location.reload();
				}
				else {
					document.location = this.href
				}
			});

			$('.selectArea').css('cursor', 'pointer').click(function() {
				var link = $(this).find('a');
				if (link) {
					window.location = link.get(0).href;
				}
			});

			priv.bindOccupancyEvents();
		},

		/**
		* Bind events for the occupancy popup. Will only show the popup once or when the occupancy has changed.
		* @private
		*/
		bindOccupancyEvents: function() {
			if (!$('#occupancy-popup').get(0)) {
				return;
			}

			var popup = $('#occupancy-popup');
			popup.appendTo($('body'));

			Occupancy.bindTravelerSelectors();
			priv.checkShowOccupancyPopup(popup);

			popup.find('a.btn').click(function() {
				popup.hide();
				if ($('#chkFilter').attr('checked') != priv.getCurrentFilterSearch()) {
					Occupancy.saveTravelers();
					priv.searchbarChange();
				}
			});

			//remove the popup if someone clicks on a select box
			$("a.selectButton").live("click",
				function() {
					popup.hide();
				}
			);
		},

		getCurrentFilterSearch: function() {
			var currentFilterSearch = false;
			var cookieStr = $.cookie(Resource.GetTextForCookie('cookie-prefix') + 'occupancy');
			if (!(cookieStr == null || cookieStr == '' || cookieStr.indexOf('<OCCUPANCY') == -1)) {
				try {
					var xmlDoc = null;
					if (window.ActiveXObject) {
						// code for IE
						xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
						xmlDoc.async = "false";
						xmlDoc.loadXML(cookieStr);
					}
					else {
						// code for Mozilla, Firefox, Opera, etc.
						var parser = new DOMParser();
						xmlDoc = parser.parseFromString(cookieStr, "text/xml");
					}
					var root = xmlDoc.documentElement;

					// set values from cookie; keep defaults if the values are unreadable
					var searchSetting = parseInt(root.getAttribute("USEFORSEARCH"));
					if (searchSetting === 0 || searchSetting === 1) {
						currentFilterSearch = (searchSetting == 1);
					}
				} catch (err) {
					Log.Debug(err);
				}
			}
			return currentFilterSearch;
		},

		checkShowOccupancyPopup: function(popup) {
			if (popup == null) popup = $('#occupancy-popup');
			var occupancy = Occupancy.getNrAdults();
			if (occupancy >= 3 && priv.shouldShowOccupancyPopup()) {
				popup.show();

				var destinationOffset = $('#occupancy').parent().offset();
				var newTop = destinationOffset.top + $('#occupancy').parent().height() + 5;
				var newLeft = destinationOffset.left - 20;
				popup.offset({ top: newTop, left: newLeft });
				Log.Debug(popup.offset());

				popup.find('.head span.mark').html(occupancy);
				priv.setOccupancyPopupShown();
			}
		},

		getCookieName: function() {
			return Resource.GetTextForCookie('cookie-prefix') + 'occupancy-popup';
		},

		shouldShowOccupancyPopup: function() {
			return $.cookie(priv.getCookieName()) == null;
		},

		setOccupancyPopupShown: function() {
			$.cookie(priv.getCookieName(), true, { expires: 1, path: '/' });
		},

		resetOccupancyPopupShown: function() {
			$.cookie(priv.getCookieName(), '', { expires: -1, path: '/' });
		},

		/**
		* 
		* @private
		*/
		setCompareChecked: function() {
			var checkIds = $.query.get("id");
			if (checkIds != "" && checkIds.indexOf(",") != -1) {
				checkIds = checkIds.split(",");

				$('div.compareCheck').each(
                    function(i) {
                    	var id = $(this).attr("id").substring($(this).attr("id").indexOf("_") + 1);
                    	for (j = 0; j < checkIds.length; j++) {
                    		if (id == checkIds[j]) {
                    			$(this).addClass("checked");
                    			break;
                    		}
                    	}
                    }
                );
			}
		},

		/**
		* bind free text search action
		* @private
		*/
		bindTextSearch: function() {
			if ($(priv.freeTextInputElement).length) {
				if ($.query.get('searchtext').toString() != '') {
					$(priv.freeTextInputElement).val($.query.get('searchtext'));
				}
				$(priv.freeTextSubmitElement).bind("click", priv.textSearch);
				if ($(priv.freeTextInputElement).val() != Resource.GetText('home_searchfor_example')) {
					$(priv.freeTextSubmitElement).get(0).disabled = false;
				}
				$(priv.freeTextInputElement).bind("focus", function() {
					$(priv.freeTextSubmitElement).get(0).disabled = false;
					if (this.value == Resource.GetText('home_searchfor_example')) {
						this.value = '';
					}
					else {
						this.select();
					}
				});
				$(priv.freeTextInputElement).bind("keydown", function(evt) {
					if (evt.keyCode == 13) {
						priv.textSearch();
					}
				});
			}
		},

		/**
		* Redirects the page with the correct free text search parameter
		* @private
		*/
		textSearch: function() {
			$input = $(priv.freeTextInputElement);
			if ($input.val() != '' && $input.val() != Resource.GetText('home_searchfor_example')) {
				location.href = Resource.GetText('path_prefix') + '/' + Resource.GetText('searchpage') + "?searchtext=" + encodeURIComponent($input.attr("value"));
			}
		},

		/**
		* @private
		*/
		buildDepartureCalendar: function() {
			$('.departure-selector input.text').bind('click', function(e) {
				$(this).blur();
				e.preventDefault();
			});

			$('div.result-selected .remove').each(function(i) {
				if (this.href.indexOf('daterange=-1') != -1) {
					this.href = 'javascript:void(0);';
					$(this).click(function() {
						SearchMain.changeDateRange('-1');
					});
				}
			});

			// get the number of days to select before and after the selected date
			//var daterange = $.query.get('daterange').toString();
			var daterange = $.query.load(priv.getSearchBarQueryString()).get('daterange').toString();
			var addDays = 0;
			if (daterange == '2') {
				addDays = 3;
			} else if (daterange == '3') {
				addDays = 7;
			} else if (daterange != '1') {
				SearchMain.changeDateRange();
			}

			// get the selected date and get the mindate and maxdate in the range
			var curMinDate = 0;
			var curMaxDate = 0;
			var curSelDate = $.query.load(priv.getSearchBarQueryString()).get('seldate').toString();
			if (curSelDate != '') {
				var dtCurSelDate = Date.fromString(curSelDate.substring(6, 8) + '/' + curSelDate.substring(4, 6) + '/' + curSelDate.substring(0, 4));
				curMinDate = parseInt(dtCurSelDate.addDays(addDays * -1).asString2());
				curMaxDate = parseInt(dtCurSelDate.addDays(addDays * 2).asString2());
			}
			// build the departure calendar
			$('#start-date').datePicker({
				inline: true,
				createButton: false,
				showYearNavigation: false,
				year: curYear,
				month: curMonth,
				startDate: firstDate,
				endDate: lastDate,
				renderCallback: function($td, thisDate, month, year) {
					// set the dates selected inside the range
					if (thisDate.asString2() == curSelDate) {
						$td.addClass('selected');
						$td.addClass('click');
					} else if (thisDate.asString2() >= curMinDate && thisDate.asString2() <= curMaxDate) {
						$td.addClass('selected');
					}

					// disable the dates the aren't departuredays
					if (departDates['d' + thisDate.asString2()] == null ||
                            departDates['d' + thisDate.asString2()] == '') {
						$td.addClass('disabled');
					}
				}
			});

			// bind the action when a date is clicked
			$('#start-date').bind('dateSelected', function(e, selectedDate, $td) {
				// get the selected daterange
				var minDate = parseInt(selectedDate.addDays(addDays * -1).asString2());
				var maxDate = parseInt(selectedDate.addDays(addDays * 2).asString2());
				selectedDate = selectedDate.addDays(addDays * -1);

				var selectQuery = '';
				var selNValues = '';
				// loop through the date range and build the string with the nvalues to select
				// - and build the string with all the querystrings
				for (var i = minDate; i <= maxDate; i++) {
					if (departDates['d' + i] != null && departDates['d' + i] != '') {
						var queryString = departDates['d' + i].split(',')[1];
						var nValue = departDates['d' + i].split(',')[2];
						selNValues += selNValues == '' ? nValue : '+' + nValue;

						var startIndex = queryString.indexOf('N=');
						if (startIndex != -1) {
							var endIndex = queryString.indexOf('&', startIndex);
							if (endIndex == -1) {
								endIndex = queryString.length + 1;
							}
							selectQuery += '||' + queryString.substring(startIndex + 2, endIndex).replace(/\+/g, '||');
						}
					}
				}
				selectQuery += '|';

				// remove the departuredays nvalues, so only the other nvalues are left over
				for (var key in departDates) {
					var nValue2 = departDates[key].split(',')[2];
					if (selectQuery.indexOf('|' + nValue2 + '|') != -1) {
						selectQuery = selectQuery.replace(new RegExp('/|' + nValue2 + '|/', 'g'), '');
					}
				}

				// combine the to selected departuredays nvalues with the other selected nvalues
				var splitOtherNvalues = selectQuery.split('|');
				for (var j = 0; j < splitOtherNvalues.length; j++) {
					if (splitOtherNvalues[j] != '' && ('+' + selNValues + '+').indexOf('+' + splitOtherNvalues[j] + '+') == -1) {
						selNValues += '+' + splitOtherNvalues[j];
					}
				}

				// submit the selected date range
				var newUrl = $.query.load(priv.getSearchBarQueryString()).SET('N', selNValues).SET('seldate', selectedDate.asString2()).REMOVE('No');
				priv.searchbarChange(decodeURIComponent(newUrl.toString()));
			});
		},


		/**
		* @private
		*/
		buildCalendar: function() {
			if ($('a.btnSelectDate').length) {
				$('a.btnSelectDate, span.departure-selector').bind('click', function(e) {
					if ($(this).closest('.row').hasClass('disabled')) {
						// no departure days available
						$('#jHelperTipContainer').addClass('disabled');
						return false;
					} else {
						$('#jHelperTipContainer').removeClass('disabled');
					}

					$('a.btnSelectDate').css({
						color: '#ccc'
					});
					if (reloadDates == 'True') {
						$('#start-date').css({
							'height': '154px',
							'width': '157px'
						});
						priv.reloadCalendar();
						reloadDates = 'False';
					}
				}).jHelperTip({
					trigger: "click",
					dC: "#date-popup",
					//ttC: "#calendarContainer",
					initializeOnce: true,
					autoClose: true
				});
			}
			if (typeof (curYear) != "undefined") {
				priv.buildDepartureCalendar();
			}
		},

		reloadCalendar: function() {
			$('#start-date').html('');
			var type = 'type=search&';
			if (location.href.indexOf('aanbiedingen.aspx') != -1) {
				type = 'type=offers&';
			}
			$.getJSON(Resource.GetText('path_prefix') + '/js/ajax/departure-dates.aspx', type + priv.getSearchBarQueryString(false), function(data) {
				firstDate = data.firstDate;
				lastDate = data.lastDate;
				departDates = data.departDates;
				priv.buildDepartureCalendar();
			});
		},

		bindSearchbarEvents: function() {
			$('#quicksearch .disabled').live('click', function() {
				if ($(this).find('#destination').length) {
					$('#error-countryfirst').removeClass('hide');
				}
				return false;
			});

			$(priv.searchbarSelectElement).bind('change', function(event, oldvalue) {
				if (!$(this).closest('.row').hasClass('disabled')) {
					if (this.id == 'daterangeSelection') {
						SearchMain.changeDateRange();
					} else if (this.id == 'occupancy') {
						priv.resetOccupancyPopupShown();
						priv.searchbarChange();
						priv.checkShowOccupancyPopup();
					} else {
						if (this.id == 'country') {
							// also remove region
							priv.searchReplaceNValue($('#destination').val(), '-1', null, true);
						}
						priv.searchReplaceNValue(oldvalue, $(this).val());
					}
				}
			});
			$(priv.searchbarInputElement).bind('change', function(event, oldvalue) {
				if (!$(this).closest('.row').hasClass('disabled')) {
					priv.searchReplaceNValue(oldvalue, $(this).val());
				}
			});

			// 'wis' button events
			$('#quicksearch .remove-selection').bind('click', function() {
				var selName = $(this).attr('rel');
				if (selName == 'occupancy') {
					Occupancy.saveTotalTravelers(0);
					$('#' + selName).val('-1');
					priv.searchbarChange();
				} else if (this.id == 'remove-date') {
					SearchMain.changeDateRange('-1', 'True');
				} else {
					if (selName == 'country') {
						// also remove region
						priv.searchReplaceNValue($('#destination').val(), '-1', null, true);
					}
					var oldValue = null;
					if ($('#' + selName).length == 0) {
						oldValue = $("input[name='radio-" + selName + "']:checked").val();
					} else {
						oldValue = $('#' + selName).val();
					}
					priv.searchReplaceNValue(oldValue, '-1', selName);
				}
			});

			priv.buildCalendar();
		},

		searchReplaceNValue: function(oldValue, newValue, selName, noRefresh) {
			if (newValue == "on") {
				newValue = "";
			}
			// get the current nvalue
			var nValueQueryString = "" + $.query.load(priv.getSearchBarQueryString()).get('N');
			if (nValueQueryString == null || nValueQueryString == '') {
				nValueQueryString = "0";
			}
			// remove the old value
			if (oldValue != null) {
				var oldQueryString = ('+' + nValueQueryString.replace(/ /g, '+') + '+');
				nValueQueryString = oldQueryString.replace('+' + oldValue + '+', '+');
				nValueQueryString = nValueQueryString.replace('+' + oldValue + '+', '+'); // do twice, location values can exist twice
				nValueQueryString = nValueQueryString.substring(1, nValueQueryString.length - 1);
			}
			if (/^[\+]+$/.test(nValueQueryString)) {
				// value only contains +
				nValueQueryString = "0";
			}
			// add the new value
			if (newValue != '-1' && newValue != '') {
				nValueQueryString += '+' + newValue;
			}
			if (selName != null && $('#' + selName).length) {
				$('#' + selName).val(newValue);
			}
			// update the searchbar with the new value
			var newQueryString = $.query.load(priv.getSearchBarQueryString()).set('N', nValueQueryString);
			if (noRefresh) {
				$('#hidQueryString').val(newQueryString);
			} else {
				priv.searchbarChange(newQueryString.toString());
			}

		},

		searchbarLock: false,
		setSearchbarLock: function() {
			priv.searchbarLock = true;
			//do some loading animation here
			$(priv.searchbarSelectElement).attr("disabled", "disabled");
			var overlay = document.createElement("DIV");
			var loader = document.createElement("DIV");
			var fullHeight = $('#quicksearch').height();
			var fullWidth = $('#quicksearch').width();
			$(overlay).css({ "z-index": 4, "opacity": 0.75, "position": "absolute", "top": 0, "left": -20, "background-color": "#F5F5F5" }).height(fullHeight).width(fullWidth);
			$(loader).css({ "position": "absolute", "top": 0, "left": 0, "z-index": 5, "background": "transparent url(" + Resource.GetText("path_prefix") + "/images/ajax-loader-02.gif) no-repeat center" }).height(fullHeight).width(fullWidth);
			$("#quicksearch fieldset").css("position", "relative").append(overlay).append(loader);
		},

		searchbarChange: function(changeToQueryString) {
			if (priv.searchbarLock) {
				return;
			}
			priv.setSearchbarLock();

			var occupancy = $('#occupancy').val();
			if (occupancy != null && occupancy != Occupancy.getOccupancy()) {
				if (occupancy > 0 && occupancy <= 2) {
					$('#chkFilter').attr("checked", "checked");
					Occupancy.saveTravelers();
				}
				Occupancy.saveTotalTravelers(occupancy, false);
			}

			var queryString = null;
			if (changeToQueryString == null) {
				changeToQueryString = $('#hidQueryString').val();
			}
			if (changeToQueryString.indexOf('?') != 0)
				changeToQueryString = '?' + changeToQueryString;
			queryString = $.query.load(changeToQueryString).REMOVE('loadControl').toString().replace('?', '');

			var loadcontrol = "~/controls/common/searchbar.ascx";
			var currentpage = "&currentpage=" + (location.href.indexOf("aanbiedingen.aspx") != -1 ? "offers" : "search");
			$.ajax({
				// hack (Alexander): make a sync AJAX request.
				// Under some conditions an unknown handler executes right after this $.ajax call, 
				// but before result is received and parsed, and redirects to the wrong page.
				// The bug is that in FF on test server when on search page you filter by date with datePicker,
				// after filtering by e.g. destination, search result is incorrect
				// and query string in browser is ?unknown instead of ?N=0+... which probably corresponds to the line below:
				// location.href = currentLocation + '?' + $("#queryString").val();
				// async: false helps, because in this case that evil handler does not get an opportunity to execute.
				// As soon as race condition is fixed, async: false should be removed.
				async: true,
				url: Resource.GetText('path_prefix') + "/js/ajax/getcontrol.aspx",
				data: queryString + "&loadControl=" + encodeURI(loadcontrol) + currentpage,
				cache: false,
				success: function(result) {
					$('#quicksearch').replaceWith(result);
					$('span.info-text').hide().slideDown('1');

					$actionButton = $(".block-slide .footer .info");
					var originalCss = {
						"background-color": $actionButton.css("background-color"),
						//"background-image"	: $actionButton.css("background-image"),
						"color": $actionButton.css("color")
					}
					Log.Debug(originalCss);
					$actionButton.css({ "background-image": "none" });
					$actionButton
						.animate({ "background-color": "#fff", "color": "#ccc" }, 200)
						.animate({ "background-color": "#ffce22", "color": "#333" }, 1000,
							function() {
								$(this).attr("style", "");
							}
						);

					initPage();
					$('#jHelperTipContainer').removeClass('initialized');
					$('#jHelperTipContainer').html('');
					priv.bindSearchbarEvents();
					priv.reloadCalendar();

					//unlock
					priv.searchbarLock = false;
					priv.fadeSearchBar();
				}
			});
		},

		fadeSearchBar: function() {
			$(window).bind("ui-loaded",
				function() {
					$(".fadein").css({ "opacity": 0, "visibility": "visible" }).animate({ "opacity": 1 }, 200);
				}
			);
		},

		getSearchBarQueryString: function(includeQuestionMark) {
			var prepend = includeQuestionMark == null || includeQuestionMark ? '?' : '';
			return prepend + $('#hidQueryString').val();
		}
	};

	/** @scope SearchMain */
	return {

		changeDateRange: function(parDaterange, reloadDates) {
			if (reloadDates == 'True') {
				var type = 'type=search&';
				if (location.href.indexOf('aanbiedingen.aspx') != -1) {
					type = 'type=offers&';
				}
				var querystring = priv.getSearchBarQueryString(false);
				if (parDaterange == '-1') {
					querystring = 'N=0';
				}
				$.getJSON(Resource.GetText('path_prefix') + '/js/ajax/departure-dates.aspx?' + type + querystring, function(data) {
					firstDate = data.firstDate;
					lastDate = data.lastDate;
					departDates = data.departDates;
					SearchMain.doChangeDateRange(parDaterange);
				});
				reloadDates = 'False';
			} else {
				SearchMain.doChangeDateRange(parDaterange);
			}
		},

		doChangeDateRange: function(parDaterange, reloadDates) {
			var daterangeVal = parDaterange;
			if (daterangeVal == null)
				daterangeVal = $('#daterangeSelection').val();
			var nValues = $.query.load(priv.getSearchBarQueryString()).get('N').toString();
			if (daterangeVal == '-1') {
				priv.searchbarChange(SearchMain.getQueryStringWithoutDates());
			} else {
				if (priv.getSearchBarQueryString(false) == '') {
					priv.searchbarChange('?daterange=' + daterangeVal);
				} else {
					var curSelDate = $.query.load(priv.getSearchBarQueryString()).get('seldate').toString();
					if (curSelDate != '' && nValues != '') {
						var addDays = 0;
						if (daterangeVal == '2') {
							addDays = 3;
						} else if (daterangeVal == '3') {
							addDays = 7;
						}
						// get the selected date and get the mindate and maxdate in the range
						var minDate = 0;
						var maxDate = 0;
						if (curSelDate != '') {
							var dtCurSelDate = Date.fromString(curSelDate.substring(6, 8) + '/' + curSelDate.substring(4, 6) + '/' + curSelDate.substring(0, 4));
							minDate = parseInt(dtCurSelDate.addDays(addDays * -1).asString2());
							maxDate = parseInt(dtCurSelDate.addDays(addDays * 2).asString2());
						}
						var newNvalues = '';
						var selectQuery = '';
						var selNValues = '';
						// loop through the date range and build the string with the nvalues to select
						// - and build the string with all the querystrings
						for (var i = minDate; i <= maxDate; i++) {
							if (departDates['d' + i] != null && departDates['d' + i] != '') {
								var queryString = departDates['d' + i].split(',')[1];
								var nValue = departDates['d' + i].split(',')[2];
								selNValues += selNValues == '' ? nValue : '+' + nValue;

								var startIndex = queryString.indexOf('N=');
								if (startIndex != -1) {
									var endIndex = queryString.indexOf('&', startIndex);
									if (endIndex == -1) {
										endIndex = queryString.length + 1;
									}
									selectQuery += '||' + queryString.substring(startIndex + 2, endIndex).replace(/\+/g, '||');
								}
							}
						}
						selectQuery += '|';

						// remove the departuredays nvalues, so only the other nvalues are left over
						for (var key in departDates) {
							var nValue2 = departDates[key].split(',')[2];
							if (selectQuery.indexOf('|' + nValue2 + '|') != -1) {
								selectQuery = selectQuery.replace(new RegExp('/|' + nValue2 + '|/', 'g'), '');
							}
						}

						// combine the to selected departuredays nvalues with the other selected nvalues
						var splitOtherNvalues = selectQuery.split('|');
						for (var j = 0; j < splitOtherNvalues.length; j++) {
							if (splitOtherNvalues[j] != '' && ('+' + selNValues + '+').indexOf('+' + splitOtherNvalues[j] + '+') == -1) {
								selNValues += '+' + splitOtherNvalues[j];
							}
						}

						newNvalues = selNValues;
						if (newNvalues == '') {
							newNvalues = '0';
						}
						var newUrl = $.query.load(priv.getSearchBarQueryString()).REMOVE('No').REMOVE('ndp').REMOVE('Ndp').set('N', newNvalues).set('daterange', daterangeVal);
						priv.searchbarChange(decodeURIComponent(newUrl.toString()));
					} else {
						priv.searchbarChange($.query.empty().set('N', nValues).set('daterange', daterangeVal).toString());
					}
				}
			}
		},

		getQueryStringWithoutDates: function() {
			var nValues = $.query.load(priv.getSearchBarQueryString()).get('N').toString().replace(/ /gi, '+');

			if (priv.getSearchBarQueryString(false) != '') {
				// undo departure filter
				var queryString = priv.getSearchBarQueryString(false);
				var arrnValues = nValues.split('+');
				var newNvalues = '';
				for (var key in departDates) {
					var nValue = departDates[key].split(',')[2];
					for (var i = 0; i < arrnValues.length; i++) {
						if (nValue == arrnValues[i]) {
							arrnValues[i] = '';
						}
					}
				}
				for (var j = 0; j < arrnValues.length; j++) {
					if (arrnValues[j] != '') {
						// Do not use '+' as the separator which gets url encoded, use '_' instead.
						newNvalues += newNvalues == '' ? arrnValues[j] : '_' + arrnValues[j];
					}
				}
				if (newNvalues == '') {
					newNvalues = '0';
				}
				var newUrl = $.query.load(queryString).REMOVE('seldate').REMOVE('No').REMOVE('ndp').REMOVE('Ndp').set('N', newNvalues);
				// Replace back above separator by the normal nValue separator +

				return newUrl.toString().replace(/_/gi, '+');
			}
		},

		removeDateSelection: function() {
			var page = (Resource.GetText('issearchpage') == 'true') ? Resource.GetText('searchpage') : Resource.GetText('offerspage');
			window.location = Resource.GetText('path_prefix') + '/' + page + SearchMain.getQueryStringWithoutDates();
		},

		clearNdp: function(newSearchText) {
			var newUrl = $.query.REMOVE('ndp').REMOVE('Ndp');

			if (typeof (newSearchText) != 'undefined') {
				$.query.SET('searchtext', newSearchText);
			}

			location.href = decodeURIComponent(newUrl.toString() == '' ? '?' : newUrl.toString());
		},

		bindSearchbarEvents: function() {
			priv.bindSearchbarEvents();
		},

		followLink: function(url) {
			location.href = url;
			return false;
		},

		/**
		* Initializes the logic for the current page
		* to be called on $(document).ready
		*/
		OnReady: function() {
			priv.bindEvents();
			priv.bindSearchbarEvents();
			priv.fadeSearchBar();
		}
	};
} (jQuery);
