/**
 * Result list logic and functionallity
 * depends on jQuery, jQuery-cookie, and sunweb static "logic" object
 */
var resultList = function($){
	var priv = {
		resultListElements	: "#result-list>li",
		resultListCountryIds : "#result-list a.country-id",
		sortDropDownElement	: "#sort-field",
		freeTextInputElement	: "#text-search input",
		freeTextSubmitElement	: "#text-search .submitbutton",
		alreadyViewedTrigger	: "", //expects a sub item of resultListElements, empty string for same element
		lastViewedTimestamp	: "span.last-viewed-timestamp",
		resultListAnchorElement	: ".acco-name a",
		promoBlocks			: "#promotion-blocks",
		promoBlockAnchor   : ".promo-acco-name a",
		
		tooltipText     : null,
				
		/**
		 * marks items from the given array with the given className if they are found in the cookie
		 * @param {Array} items, cookieItems
		 * @param {String} activeClassName, className to give when active
		 * @param {String} (optional) string that represents the html element that can hold the date (jQuery syntax) 
		 * @param {Bool} useAnimate (optional) determine whether to use the fadein on the date elements
		 */
		markItems	: function(items, activeClassName, dateElement, useAnimate){
			logic.writeDebug("setting " + activeClassName, 0);
			
			//loop through the pageElements and set according class
			$(priv.resultListElements).each(
				function(i){
					thisId = $(this).attr("id");
					
					//check whether this is a valid list-item
					if(!thisId){
					    return true;
					}
					thisId = thisId.substring(thisId.lastIndexOf("-") + 1);
					
					//set default
					$(this).removeClass(activeClassName);
					
					//loop through array items, to test if thisId is stored in the array, set activeClassName if matched
					for(j=0; j<items.length; j++){
						if(thisId == items[j].id){
							
							//prepare for the animate for showing of the already-viewed tags, to make the user experience better
							$tagElement = $(this).find("div." + activeClassName + "-tag");
							$tagElement.css("opacity", "0");
							
							//set the active class
							$(this).addClass(activeClassName);
							
							//now animate the fade-in
							$tagElement.animate({"opacity": "1"}, 1000);
														
							//if dateElement parameter is provided write date to element
							if(typeof(dateElement) != "undefined"){
								//prepare the correct date format
								var currentDate = new Date();
								var itemDate = personalItems.GetDate(items[j].date);
								var oneDay = 1000*60*60*24; //day in millisecs
								
								var $dateElement = $("#" + this.id + " " + dateElement);
								
								// Calculate the difference in milliseconds
							    var difference_ms = Math.abs(currentDate.getTime() - items[j].date);
							    // Convert back to days and return
							    diffDays = Math.round(difference_ms/oneDay);
																
								//count days, and write accordingly
								if(diffDays == 0){
								    // today, write from resource "today"
								    $dateElement.html(resources.date_today);
									//today, write timestamp hh:mm
									//hours = (itemDate.getHours() < 10 ? ("0" + itemDate.getHours()) : itemDate.getHours());
									//mins = (itemDate.getMinutes() < 10 ? ("0" + itemDate.getMinutes()) : itemDate.getMinutes());
									//$("#" + this.id + " " + dateElement).html(hours + ":" + mins);
								}
								else if(diffDays == 1){
									//yesterday, write from resource "yesterday"
									$dateElement.html(resources.date_yesterday);
								}
								else {
									//older than yesterday write datestamp d MMM
									$dateElement.html(itemDate.getDate() + " " + resources.date_months_short[itemDate.getMonth()]);
								}
								$dateElement.parent().css("opacity", "0");
								$dateElement.parent().css({"visibility" : "visible"});																
								
								//animate the text (fadein)
								$dateElement.parent().animate({"opacity" : "1"}, 1000);
								
								logic.writeDebug(diffDays, 0);
							}
							break;
						}
					}
				}
			);
			
			//recalculate and show the counters on the personal item links
            personalItems.ShowItemLinks();
		},
		
		
		/**
		 * Reloads the page with the correct sort parameter
		 * @param {Object} dropdown element with new sort information
		 */
		changeSorting : function(obj){
			document.location.href = document.location.pathname + "?" + obj.options[obj.selectedIndex].value;
		},
		
		/**
		 * Redirects the page with the correct free text search parameter
		 */
		textSearch	: function(){
		    $input = $(priv.freeTextInputElement);
		    if($input.val() != '' && $input.val() != resources.emptysearch){
		        //build new url with additional free text parameter
//		        var url = "";
//		        if(document.location.href.indexOf("?") != -1){
//		            var qs = document.location.href.split("?")[1];
//		            var qsArr = qs.split("&");
//    		        
//				    //loop through the querystring to build up the new one, 
//				    //ignoring previous searchtext parameter and page count parameter
//				    for(i=0; i<qsArr.length; i++){
//		                var keyPair = qsArr[i].split("=");
//		                if(keyPair[0] != "" && keyPair[0] != "searchtext" && keyPair[0] != "No"){
//		                    url += keyPair[0] + "=" + keyPair[1] + "&";
//		                }
//		            }
//		        }
//			    //if no existing querystring add N=0
//		        else {
//		            url += "N=0&";
//		        }
//    		    
//		        var searchTerm = new String();
//		        searchTerm = $input.attr("value");
//		        //trim the string
//		        if(searchTerm){
//		            searchTerm = searchTerm.trim();
//		        }
//		        //if user has made input, add the searchtext parameter
//		        if(searchTerm){
//		            url += "searchtext=" + encodeURI($input.attr("value"));
//		        }
//		        else {
//		            //trim trailing "&"
//		            url = url.substring(0, url.length - 1)
//		        }
    		    
			    //make the redirect
		        //document.location.href = document.location.pathname + "?" + url;
		        document.location.href = document.location.pathname + "?searchtext=" + encodeURI($input.attr("value"));
		    }
		},
		
		/**
		 * Shows and formats the promotion blocks on the search page
		 * @param {Int} listPosition, position in the list where the current blocks should appear
		 */
		showPromoBlocks : function(listPosition){
		    //first make sure we have the promotion blocks available
			if($(priv.promoBlocks).length == 0){
				return false;
			}
			logic.writeDebug("doing logic for promo blocks");
			
			//get the PromoItems
			$promoItems = $(priv.promoBlocks + ">li");
			
			//create the new list to insert halfway the page
			$newList = $("<ul class='promotion-blocks'>");
			
			//make sure we have at least one itemm otherwise exit the method
			if($promoItems.length == 0){
			    return false;
			}
			
			var position = 1;
			var maxBlockItems = 3;
			var infloop = 0;
			
			//show maximum of 2 other random items for curent block
			while($promoItems.length > 0 && $newList.find("li").length < maxBlockItems && infloop < 25){
                infloop++;
                //pool from which to grab depends on position (and style)
                $currPool = $promoItems.parent().find(".promo-type-" + position);
                position = (position < maxBlockItems ? parseInt(position + 1) : 1);
                
                if($currPool.length == 0){
                    //if we do not have any items left in the current pool, go to next
                    continue;
                }
                
                //get the new random index
			    var rnd = Math.round(Math.random() * ($currPool.length - 1));
			    logic.writeDebug(rnd);
    			$newList.append($currPool[rnd]);
    			
    			//rebind list to keep the counters in order
			    $promoItems = $(priv.promoBlocks + ">li");
			}
			
			//remove right-margin of the most right visible element
			$newList.children("li:nth-child(3)").css("margin-right", "0px");
			
			//now append the $newList to the list page
			//write the block at the 3rd position if not empty
			if($newList.length > 0){
			    $(priv.resultListElements + ":nth-child(" + listPosition + ")").before(
				    $("<li>").addClass("promotion-container").append($newList)
			    );
			}
            
            //bind events
            $newList.children("li").hover(
                function(){$(this).addClass("hover");},
		        function(){$(this).removeClass("hover");}
            ).bind("click",
                function(){
                    //redirect to the correct page
                    var url = $(this).find(priv.promoBlockAnchor).attr("href");
                    
                    document.location.href = url;
                    //prevent event bubbling
                    return false;
                }
            );
            
            //show the $newList
            $newList.show();
            
            //finnaly make sure all blocks have the same height
			//images stretch the height and additional correction is needed after the body has loaded
			$(window).bind("load",
				function() {
					priv.setPromoBlockHeights();
				}
			);
			
		},
				
		/**
		 * (re)sets the heights of the promotion blocks, so they have teh same height.
		 */
		setPromoBlockHeights	: function(){		
			logic.writeDebug("(re)setting the height of the promotion blocks");
			var maxHeight = 0;			
			$("ul.promotion-blocks li:visible").each(
				function(i){
					//wobble the height a bit... so the browser recalculates its actual height...
					$(this).height($(this).height() + 1);
					$(this).height($(this).height() - 1);
					
					maxHeight = Math.max(maxHeight, $(this).height());
				}
			);
			$("ul.promotion-blocks li:visible").height(maxHeight);
		},
		
		/**
		* Checks the available countryIds on the list to determine the country background image
		**/
		setCountryImage : function(){
		    if(logic.getURLParam("personal") != ""){
		        $('.result-info').css('color','#16aa16');
		        $("#result-properties").css("background-image", "url(" + resources.skin_path + "images/my_sunweb_bg.jpg)");
		    } else {
		        var $items = $(priv.resultListCountryIds);
		        var countryId = 0;
		        var uniform = true;
		        //check if there are items
		        if($items.length > 0){		        
		            countryId = $items[0].name;
		        }
		        //loop throught the available items to see if the ids are similar
		        for(i=1; i<$items.length; i++){
		            if($items[i].name != '0' && countryId != $items[i].name){
		                uniform = false;
		                break;
		            }
		        }
    		    
		        //if the ids are similar: overwrite the generic image
		        if(uniform){
		            //$("#header").css("background-image", "url(" + resources.skin_path + "images/countrieslst/result-properties-bg-" + countryId + ".jpg)");
		        }
		    }
		},
		
		/**
		 * binds the events for the list
		 */
		bindEvents	: function(){
		    resultList.selectDirectTo();
		
			/**
			 * Item Click events:
			 */
			$(priv.resultListElements + " " + priv.alreadyViewedTrigger).bind("click", 
				function(){
					//get the current id
					thisId	= (priv.alreadyViewedTrigger == "" ? $(this).attr("id") : $(this).parents("li").attr("id"));
					
					//check if we have a valid list-item
					if(!thisId){
					    return false;
					}
					thisId	= thisId.substring(thisId.lastIndexOf("-") + 1);
					
					//adding to the alreadyviewed array
					personalItems.Add("alreadyviewed", thisId);
					
					//mark this item with "already viewed" 
					//marking needed, otherwise the item will be left unmarked when backbutton is hit
					//priv.markItems(personalItems.Load("alreadyviewed"), "already-viewed", priv.lastViewedTimestamp); 
										
					//now direct to new url
					//get the url to direct to
					var url = $("#" + $(this).attr("id") + " " + priv.resultListAnchorElement).attr("href");
					var rel = $("#" + $(this).attr("id") + " " + priv.resultListAnchorElement).attr("rel");
					if(typeof(rel) != "undefined" && rel != null && rel != ""){
					    var separatorChar = '?';
					    if(url.indexOf('?') != -1){
					        separatorChar = '&';
					    } 
					    var urlSplit = url.split('#');
					    if(urlSplit.length > 1){
					        url = urlSplit[0] + separatorChar + "objectIndex=" + rel + "#" + urlSplit[1];
					    } else {
					       url += separatorChar + "objectIndex=" + rel;
					    }
					}
					
					document.location.href = url;
					//prevent bubbling
					return false;
				}
			);
			
			$(priv.resultListElements + " a.favorite, " + priv.resultListElements + " a.is-favorite").bind("click", function() {
			    var accoId = $(this).attr("rel").replace("id","");
			    
			    if($(this).hasClass("is-favorite")){
					//add a new item
					$(this).removeClass("is-favorite");
					$(this).html(resources.add_favorite);
					personalItems.Remove("favorites", accoId);
				}
				else {
				    $(this).addClass("is-favorite");
				    $(this).html(resources.is_favorite);
					personalItems.Add("favorites", accoId);
				}
					
				//update the personal item links
				personalItems.ShowItemLinks();
			    
			    //update favourite and viewed item box
			    $('#favourite-and-viewed .content').trigger('change');
			    return false;
			});
				
			$(priv.resultListElements + " div.price-block").hover(
				function(){
					//mouseover
					$(this).parent().find(".acco-name").css({"background-color":"transparent","color":"#0055B4"});
				},
				function(){
					//mouseout
					$(this).parent().find(".acco-name").removeAttr("style");
				}
			);
				
			/**
			 * Hover on list element
			 */
			$(priv.resultListElements).hover(
				function(){
					//mouseover
					$(this).addClass("hover");
				},
				function(){
					//mouseout
					$(this).removeClass("hover");
				}
			);
			
			/**
			 * Hover on favorite button
			 */
//			$(priv.resultListElements + " " + priv.favoritesTrigger).hover(
//				function(){
//					//mouseover
//					$(this).addClass("hover");
//				},
//				function(){
//					//mouseout
//					$(this).removeClass("hover");
//				}
//			);
			
			/**
			 * sorting event
			 */
//    		$(priv.sortDropDownElement).bind("change",
//				function(){
//					priv.changeSorting(this);
//				}
//			);
			
			/**
			 * free text search event
			 */
			if($(priv.freeTextInputElement).length){
			    $(priv.freeTextSubmitElement).bind("click", priv.textSearch);
			    if($(priv.freeTextInputElement).val() != resources.emptysearch){
			        $(priv.freeTextSubmitElement).get(0).disabled=false;
			    }
			    $(priv.freeTextInputElement).bind("focus", 
			        function(){
			            $(priv.freeTextSubmitElement).get(0).disabled=false;
			            if(this.value==resources.emptysearch){
			                this.value='';
			            }else{
			                this.select();
			            }
			        }
			    );
			    $(priv.freeTextInputElement).bind("keydown", 
			        function(evt){
			            if(evt.keyCode == 13){
			                priv.textSearch();
			            }
			        }
			    );
			}
						
			//logic.toolTip($('.acco-userrating'), 2, resources.path_prefix + '/html/ratings-hover.aspx #ratings-hover');
			
			/*
			*   More info popups
			*/
			$('a.moreinfo').bind("click",
				function(){
				    logic.resizePopup();
	                logic.showPopup('pMoreInfo', true, 500, 0);
	                return false;
				}
			);
			$('a.moreinfounknown').bind("click",
				function(){
				    logic.resizePopup();
	                logic.showPopup('pMoreInfoUnknown', true, 500, 0);
	                return false;
				}
			);
			
			/* location popups */
//			$('a.country').each(function (i) {
//			    logic.toolTip($(this), 2, resources.path_prefix + '/html/location-block.aspx?theme=country&id='+this.rel+' #location-block', 15);
//            });
//            $('a.region').each(function (i) {
//			    logic.toolTip($(this), 2, resources.path_prefix + '/html/location-block.aspx?theme=region&id='+this.rel+' #location-block', 15);
//            });
//            $('a.city').each(function (i) {
//			    logic.toolTip($(this), 2, resources.path_prefix + '/html/location-block.aspx?theme=city&id='+this.rel+' #location-block', 15);
//            });
            
            // compare events
            if(location.href.indexOf('personal=') != -1){
                $('div.compare').bind("click",
				    function(){
	                    return false;
				    }
			    );
                $('div.compareCheck').bind("click",
				    function(){
				        if($(this).hasClass("checked")){
				            $(this).removeClass("checked");
				        } else {
				            $(this).addClass("checked");
	                    }
	                    return false;
				    }
			    );
			    $('div.compare a').bind("click",
				    function(){
				        if($('div.compareCheck.checked').length < 2){
				            alert('Selecteer minimaal 2 items om te vergelijken');
				        } else {
				            var compareUrl = '';
				            $('div.compareCheck.checked').each(function (i) {
				                compareUrl += compareUrl == '' ? 'id='+this.id.replace('check_','') : '&id='+this.id.replace('check_','');
                            });
				            var extraUrl = $('div.compare a').get(0).className;
                            compareUrl = resources.path_prefix + '/compare.aspx?personal='+ extraUrl + '&' +compareUrl;
                            location.href = compareUrl;
				        }
				    }
			    );
			}
			
			//Load accommodation content
			$('#favourite-and-viewed .content').change(function(ev){			
			        $(this).load(resources.path_prefix + '/utilpages/GetPersonalAccommodations.aspx?max=5&personal=' + $(this).attr('rel').toString(),
			                
			                function(){	
			                
			                //remove loader
			                $(this).removeClass('loading');
			                		            
			                //click on acco and goto accommodation page
			                $('#favourite-and-viewed .content div.acco').click(function(){    			        			                 
			                 document.location.href = $(this).attr('rel');	
			                 return false;			                 
			                });        
			                //click on save-button and put accommodation in favourits
			                $('#favourite-and-viewed .content div.acco .save-button').click(function() {
			                    var accoId = $(this).attr('rel');
			                    personalItems.Add("favorites", accoId);
			                    
			                    //remove favourite from result-list
			                    $('#result-list .favorite[rel=id' + accoId + ']').triggerHandler('click');
			                    
			                    $(this).css({display:'none'});
			                    $('.is-favorite',$(this).parent()).css({display:'block'});
			                    $('.delete-button',$(this).parent()).css({display:'block'});
			                    return false;
			                });
			                
			                //click on delete-button and remove accommodation from favourits
			                $('#favourite-and-viewed .content div.acco .delete-button').click(function() {
			                    //remove from cookie
			                    var accoId = $(this).attr('rel');
			                    personalItems.Remove("favorites", accoId);			                    
			                    
			                    //remove favourite from result-list
			                    $('#result-list .is-favorite[rel=id' + accoId + ']').triggerHandler('click');
			                    
			                    //change html states
			                    if ($(this).parent().parent().attr('rel').toString() == 'alreadyviewed')
			                    {   
			                        //remove delete button
			                        $(this).css({display:'none'});   
			                        //add save-button
			                        $('.save-button',$(this).parent()).css({display:'block'});
			                        $('.is-favorite',$(this).parent()).css({display:'none'});
			                        return false;
			                    }
			                    else
			                    {
			                        
			                        $('#favourite-and-viewed .content').trigger('change');
			                        return false;
			                    }
			                });			                
                    });
              });
		},
		
		setCompareChecked : function() {
             var checkIds = logic.getURLParam("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;
                            }    
                        }
                    }
                );
             }
		},
		
		toolTip : function($element) {           
            var leftMargin = 10;
            
            $element.mousemove(function(e){
                var toolTipId = '#info_tooltip';	
			    
			    var left = 0;
		        if(priv.toolTipBodyWidth < (e.pageX+leftMargin+priv.toolTipWidth)){
                   left = (e.pageX-leftMargin-priv.toolTipWidth);
                } else {
                   left = (e.pageX+leftMargin);
                }
                var top = 0;
                if(priv.toolTipBodyHeight < (e.pageY+10+priv.toolTipHeight)){
                   top = (e.pageY-10-priv.toolTipHeight);
                } else {
                   top = (e.pageY+10);
                }
                
                $(toolTipId).css({'top':top+'px','left':left+'px'});
            });
            
            $element.hover(
                function () {
                    priv.toolTipBodyHeight = logic.getBottomPage();
                    priv.toolTipBodyWidth = $('body').width();

                    // normal tooltip
                    var countNr = $(this).attr('rel').split(',')[0];
                    if(location.href.indexOf('search.aspx') != -1){
                            priv.tooltipText = countNr;
                    } else {
                        if((countNr+'|').indexOf('- 1|') != -1)
                            priv.tooltipText = countNr + ' aanbieding';
                        else
                            priv.tooltipText = countNr + ' aanbiedingen';
                    }
                    
                    if(priv.tooltipText != ''){
                        if($('#info_tooltip').length == 0){
		                    $('#site-container').append($('<div id="info_tooltip">').css({'position':'absolute','width':'auto','z-index':'1000'}));
		                    $('#info_tooltip').html(priv.tooltipText);
		                } else {
		                    $('#info_tooltip').html(priv.tooltipText);
		                    $('#info_tooltip').show();
		                }
		            }
		            
		            priv.toolTipWidth = $('#info_tooltip').width();
		            priv.toolTipHeight = $('#info_tooltip').height();
                },
                function () {
                    // normal tooltip
                    $('#info_tooltip').hide();
                }
            );
        },
        
		bindLocationRefineEvents    : function(){
		    var $hiddenLinks = $("#location-drilldowns div.hidden-links");
		    $("#location-drilldowns a.show-hidden-links").bind("click",
		        function(){
		            var $slideDiv = $(this).parent().parent().siblings("div.hidden-links");
		            //hide all that is not under the current link
		            $hiddenLinks.not($slideDiv).hide();
		            $hiddenLinks.css('left',$(this).parent().get(0).offsetLeft);
		            
		            //check if the div has a lot of items, and wrap on two lines if so
		            if($slideDiv.find("li").length > 12){
		                $slideDiv.addClass("bigger");
		            }
		            //now toggle the current div
		            $slideDiv.toggle();
		            return false;
		        }
		    );
		    $("body").bind("click",
		        function(){
		            //bind hide to the body
		            $hiddenLinks.hide();
		        }
		    );
		    $hiddenLinks.bind("click",
		        function(){
		            //make sure that onclick on the div does not bubble down to the body
		            return false;
		        }
		    );
	         $hiddenLinks.find("a").bind("click",
		        function(){
		            document.location.href = this.href;
		            return false;
		        }
		    );
	    },
	    
	    buildDepartureCalendar : function(){
	        $('div.result-selected .remove').each(function (i) {
                if (this.href.indexOf('daterange=-1') != -1) {
                    this.href = 'javascript:void(0);';
                    $(this).click(function () {
                        resultList.changeDateRange('-1');
                    });
                }
            });
	    
            // get the number of days to select before and after the selected date
		    var daterange = logic.getURLParam('daterange');
		    var addDays = 3;
            if(daterange == '1') {
                addDays = 0;
            } 
            else if(daterange == '3') {
                addDays = 7;
            } else if(daterange == '-1'){
                resultList.changeDateRange();
            }
            // get the selected date and get the mindate and maxdate in the range
            var curMinDate = 0;
            var curMaxDate = 0;
            var curSelDate = logic.getURLParam('seldate');
            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');
				                                        //$td.addClass('disabled');
				                                    }
				                                }
				                                // disable the dates the aren't departuredays
					                            if (departDates['d'+thisDate.asString2()] == null ||
					                                departDates['d'+thisDate.asString2()] == '') {
						                            $td.addClass('disabled');
					                            } else if(location.href.indexOf('search.aspx') == -1){
					                                // set the tooltip with the number of offers or accommodations
					                                if(departDates['d'+thisDate.asString2()].indexOf(' - 0,') == -1){	
					                                    $td.addClass('tooltip');
					                                    priv.toolTip($td);
					                                }
					                                $td.attr('rel', departDates['d'+thisDate.asString2()]);
					                            }
				                            }});
			
			// bind the action when a date is clicked
			$('#start-date').bind(
			    'dateSelected',
			    function(e, selectedDate, $td)
			    {
			        // get the information from the rel (<countnr>,<querystring>,<nvalue>)
		            //var rel = $td.attr('rel');
		            // do not fire click when clicked on a date that is already selected
		            //if(rel.substring(0,2) != '0,'){
		            //if(curSelDate == null || curSelDate == ''){
		                if(daterange == '-1') {
		                    $('select.daterange').val('2');
		                }
		                
		                // 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 nValue = departDates[key].split(',')[2];
		                    if(selectQuery.indexOf('|'+nValue+'|') != -1){
		                        selectQuery = selectQuery.replace(new RegExp('/|'+nValue+'|/','g'),'');
		                    }
		                }
		                
		                // combine the to selected departuredays nvalues with the other selected nvalues
		                var splitOtherNvalues = selectQuery.split('|');
		                for(var i=0;i<splitOtherNvalues.length;i++){
		                    if(splitOtherNvalues[i] != '' && ('+'+selNValues+'+').indexOf('+'+splitOtherNvalues[i]+'+') == -1){
		                        selNValues += '+'+splitOtherNvalues[i];
		                    }
		                }
		                
		                // submit the selected date range
		                var strUrl = location.href;
		                if(strUrl.indexOf('?') == -1){
		                    location.href = location.href + '?N='+selNValues+'&seldate='+selectedDate.asString2();
		                } else {
		                    var params = logic.removeURLParam(location.href.split('?')[1],'seldate');
		                    params = logic.removeURLParam(params,'No');
		                    params = logic.removeURLParam(params,'N');
		                    if(params != '' && params.substring(0,1) != '&') params = '&'+params; 
		                    location.href = location.href.split('?')[0] + '?N='+selNValues+'&seldate='+selectedDate.asString2()+params;
		                }
//		            } else {
//		                // deselect range, when clicked on a currently selected date
//		                resultList.changeDateRange(-1);
//		            }
			    }
		    );
        
        }
	}; 
	
	return {
	
	    selectDirectTo : function(){
	        var destLength = $('#divDirectto').length;
			if(destLength){
			    var destinationName = $('#ctl00_phBreadCrumb_hBreadcrumb').get(destLength-1).value;
				if (destinationName != "") {
					var breadLength = $('.directto').length;
					if(breadLength == 2){
						$("select.directto option[class='c']:contains('"+destinationName+"')").attr('selected', 'selected');
					} else if (breadLength == 3){
						$("select.directto option[class='r']:contains('"+destinationName+"')").attr('selected', 'selected');
					} else {
						$("select.directto option:contains('"+destinationName+"')").attr('selected', 'selected');
					}
			    }
			}
	    },
	
	    changeDateRange : function(parDaterange){
	        if(reloadDates == 'True'){
	            $.getJSON(resources.path_prefix+'/js/data/departure-dates.aspx?'+location.href.split('?')[1],
                function(data){
                  firstDate = data.firstDate;
                  lastDate = data.lastDate;
                  departDates = data.departDates;
                  resultList.doChangeDateRange(parDaterange);
                });
	            reloadDates = 'False';
	        } else {
	            resultList.doChangeDateRange(parDaterange);
	        }
	    },
	    
	    doChangeDateRange : function(parDaterange, reloadDates){
	        var daterangeVal = parDaterange;
	        if(daterangeVal == null)
	            daterangeVal = $('select.daterange').val();
	        var nValues = logic.getURLParam('N');
	        if(daterangeVal == '-1'){
                location.href = location.href.split('?')[0] + resultList.getQueryStringWithoutDates();
	        } else {
	            if(location.href.indexOf('?') == -1){
	                location.href = location.href + '?daterange='+daterangeVal;
	            } else {
	                var curSelDate = logic.getURLParam('seldate');
	                if(curSelDate != '' && nValues != ''){
	                    var addDays = 3;
                        if(daterangeVal == '1') {
                            addDays = 0;
                        } 
                        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 nValue = departDates[key].split(',')[2];
		                    if(selectQuery.indexOf('|'+nValue+'|') != -1){
		                        selectQuery = selectQuery.replace(new RegExp('/|'+nValue+'|/','g'),'');
		                    }
		                }
		                
		                // combine the to selected departuredays nvalues with the other selected nvalues
		                var splitOtherNvalues = selectQuery.split('|');
		                for(var i=0;i<splitOtherNvalues.length;i++){
		                    if(splitOtherNvalues[i] != '' && ('+'+selNValues+'+').indexOf('+'+splitOtherNvalues[i]+'+') == -1){
		                        selNValues += '+'+splitOtherNvalues[i];
		                    }
		                }
    
                        newNvalues = selNValues;
	                    if(newNvalues == ''){
	                        newNvalues = '0';
	                    }
	                    var queryString = location.href.split('?')[1];
	                    queryString = logic.removeURLParam(queryString,'daterange');
	                    queryString = logic.removeURLParam(queryString,'No');
	                    queryString = logic.removeURLParam(queryString,'N');
	                    location.href = location.href.split('?')[0] + '?N='+newNvalues+'&daterange='+daterangeVal+queryString;
	                } else {
	                    location.href = location.href.split('?')[0] + '?'+logic.removeURLParam(location.href.split('?')[1],'daterange')+'&daterange='+daterangeVal;
	                }
	            } 
	        }
	    },
	    
	    getQueryStringWithoutDates : function (){
	        var nValues = logic.getURLParam('N');
            if(location.href.indexOf('?') != -1){
                // undo departure filter
                var queryString = location.href.split('?')[1];
                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 i=0;i<arrnValues.length;i++){
                    if(arrnValues[i] != ''){
                        newNvalues += newNvalues == '' ? arrnValues[i] : '+'+arrnValues[i];
                    }
                }
                if(newNvalues == ''){
                    newNvalues = '0';
                }
                queryString = logic.removeURLParam(queryString,'seldate');
                //queryString = logic.removeURLParam(queryString,'daterange');
                queryString = logic.removeURLParam(queryString,'No');
                queryString = logic.removeURLParam(queryString,'N');
                if(queryString != '' && queryString.substring(0,1) != '&') queryString = '&'+queryString;
                return '?N='+newNvalues+queryString;
            }
	    },
                
		/**
		 * To be called on $(document).ready()
		 * Initializes all client side events and logic for the resultlist 
		 */
		OnReady	: function(){
		    var OnreadyTimer = new Timer();
		    //mark the items from the list with already-viewed class
//			$(window).bind("load",
//				function() {
//					priv.markItems(personalItems.Load("alreadyviewed"), "already-viewed", priv.lastViewedTimestamp);
//				}
//			);
			
//		    priv.bindLocationRefineEvents();
		    $('a.btnSelectDate,a.btnSelectDateAnimate').bind('click', function(e){
		        if(typeof(curYear) != "undefined" && $('#start-date').html() == '') {
		            priv.buildDepartureCalendar();
		        }
		        $('a.btnSelectDate').css({color:'#ccc'});
		        if($(this).attr('class').indexOf('Animate') != -1){
		            var oldTop = logic.findPosY($('a.btnSelectDateAnimate').get(0))+12;
                    var oldLeft = logic.findPosX($('a.btnSelectDateAnimate').get(0));
		            $('#jHelperTipContainer').css({"top": (oldTop)+ "px", "left": (oldLeft)+ "px"});
                    var newTop = logic.findPosY($('a.btnSelectDate').get(0))+12;
                    var newLeft = logic.findPosX($('a.btnSelectDate').get(0))+($('a.btnSelectDate').width()-5);
                    $('#jHelperTipContainer').animate({"top": newTop+"px"}, { duration: 300 }).animate({"left": newLeft+"px"}, { duration: 600 });;
                }
		        if(reloadDates == 'True'){
		            $('#start-date').css({'height':'154px', 'width':'157px'});
		            $('#start-date').html('');
		            var type = 'type=search&';
		            if(location.href.indexOf('lastminutes.aspx') != -1){
		                type = 'type=offers&';
		            }
		            $.getJSON(resources.path_prefix+'/js/data/departure-dates.aspx',type+location.href.split('?')[1],
                    function(data){
                      firstDate = data.firstDate;
                      lastDate = data.lastDate;
                      departDates = data.departDates;
                      priv.buildDepartureCalendar();
                    });
		            reloadDates = 'False';
		        }
		    }).jHelperTip({
	            trigger: "click",
	            dC:"#date-popup",
	            leftOff: -75,	            	            
	            topOff:-173,
	            initializeOnce: true,
	            autoClose: true
	            
            });
		    
			//mark the items from the list with favorite class -> no longer needed in the lister
			//priv.markItems(personalItems.Load("favorites"), "favorite");	
												
			if(location.href.indexOf('personal=') != -1){
			    $('#center-right-border-left').css({'background':'transparent url('+resources.skin_path+'images/fadingborder-small.gif) no-repeat scroll left top'});
			    priv.setCompareChecked();
			}
			
			//check country for bg-image
			priv.setCountryImage();
			logic.writeDebug("setCountryImage between time: " + OnreadyTimer.ShowIntermediate() + " ms", -1);
				
			priv.bindEvents();	//binds the events for the list items
			
			//show favourites and viewed
			//set tab state
			$('#favourite-and-viewed .tabs li').click(function(){
			     
			    if (!$(this).hasClass('selected'))
			    {			    
			        $('#favourite-and-viewed .tabs li').removeClass('selected');
			        $(this).addClass('selected');
			        $('#favourite-and-viewed .content').attr('rel',$(this).attr('id'));
			        $('#favourite-and-viewed .content').empty().addClass('loading');
			        $('#favourite-and-viewed .content').triggerHandler('change');			        
			    }			
			});
				 			 
			//load accommodations for first time
			 $('#favourite-and-viewed .tabs li.selected').removeClass('selected').trigger('click').addClass('selected'); 
			
			logic.writeDebug("Total result onready time: " + OnreadyTimer.Stop() + " ms", -1);
		}
		
	}
}(jQuery);
