function getLastSearchResults(searchString,type) {
	//alert ( 'hi' +  {$smarty.session.lastSearch_url} );

	//alert ( searchString );
	// ---------------------------------------------------------------------------------
	// fade out old criteria
	//$('#resultsContainer .hideUntilRolled').stop(true, true).fadeOut('slow');
	
	// so the ben alman hash change function won't fire when we change the hash below
	window.thinking = true;
	
	// ---------------------------------------------------------------------------------
	// combine cookie settings and url (or newly chosen) settings
	
	// get the cookie
	var cookieSettings = $.cookie("searchSettings");
	
	// if 'searchSettings' cookie exists (and isn't empty)
	if (cookieSettings!=null && cookieSettings!='') {

		// get rid of the #/ and turn & into -
		var urlSettings = window.location.hash.replace(/#\//, '');
		
		// if coming from paginate, get rid of format=var and next=var (otherwise they'll be seen as urlSettings below)
		if( searchString.match(/format/) ) {
			
			// split it at format= to separate the criteria and settings (now in [0]) from the paginate (in [1])
			var urlCriteriaAndSettingsAndPaginate = searchString.split('&format');
			var urlCriteriaAndSettings = urlCriteriaAndSettingsAndPaginate[0];
			var paginateStuff = '&format' + urlCriteriaAndSettingsAndPaginate[1];

		} else {
			var paginateStuff = '';
		}
		
		// separate the criteria (location, dates, sleeps) from the settings (sort, per page view)
		var urlCriteriaAndSettings = searchString.split('?');
		var urlCriteria = urlCriteriaAndSettings[0];
		var urlSettings = urlCriteriaAndSettings[1];
		
		// create some arrays
		var cookieSetting = new Array();
		var urlSetting = new Array();
		var finalSetting = new Array();
		
		// put all of the cookie settings into separate array items (empty array items if there's no cookie setting)
		if( cookieSettings.match(/sort/) ) { cookieSetting[0] = cookieSettings.replace(/.*(sort=[\w]*[^-]).*/,'$1'); }
		else { cookieSetting[0] = ''; }
		
		if( cookieSettings.match(/limit/) ) { cookieSetting[1] = cookieSettings.replace(/.*(limit=[\d]*[^-]).*/,'$1'); }
		else { cookieSetting[1] = ''; }
			
		if( cookieSettings.match(/view/) ) { cookieSetting[2] = cookieSettings.replace(/.*(view=[\w]*[^-]).*/,'$1'); }
		else { cookieSetting[2] = ''; }
			
		if( cookieSettings.match(/images/) ) { cookieSetting[3] = cookieSettings.replace(/.*(images=[\w]*[^-]).*/,'$1'); }
		else { cookieSetting[3] = ''; }
		
		// if there are some url settings as well, they should override any cookie settings
		if( urlSettings ) {
			
			// put all of the url settings into separate array items (if we don't find this, use the cookie instead)
			if( urlSettings.match(/sort/) ) { finalSetting[0] = urlSettings.replace(/.*(sort=[\w]*[^&]).*/,'$1'); }
			else if ( cookieSetting[0] != '' ) { finalSetting[0] = cookieSetting[0]; }
			else { finalSetting[0] = ''; }
			
			if( urlSettings.match(/limit/) ) { finalSetting[1] = urlSettings.replace(/.*(limit=[\d]*[^&]).*/,'$1'); }
			else if ( cookieSetting[1] != '' ) { finalSetting[1] = cookieSetting[1]; }
			else { finalSetting[1] = ''; }
				
			if( urlSettings.match(/view/) ) { finalSetting[2] = urlSettings.replace(/.*(view=[\w]*[^&]).*/,'$1'); }
			else if ( cookieSetting[2] != '' ) { finalSetting[2] = cookieSetting[2]; }
			else { finalSetting[2] = ''; }
				
			if( urlSettings.match(/images/) ) { finalSetting[3] = urlSettings.replace(/.*(images=[\w]*[^&]).*/,'$1'); }
			else if ( cookieSetting[3] != '' ) { finalSetting[3] = cookieSetting[3]; }
			else { finalSetting[3] = ''; }
		
		// if there aren't any url settings, just use the cookie settings as final
		} else {
			
			finalSetting[0] = cookieSetting[0];
			finalSetting[1] = cookieSetting[1];
			finalSetting[2] = cookieSetting[2];
			finalSetting[3] = cookieSetting[3];
			
		}
		
		
		var finalSettings = finalSetting[0] + '-' + finalSetting[1] + '-' + finalSetting[2] + '-' + finalSetting[3];
		
		finalSettings = finalSettings.replace(/[-]{2,}/g,'-');
		finalSettings = finalSettings.replace(/^-/,'');
		finalSettings = finalSettings.replace(/-$/,'');
		finalSettings = finalSettings.replace(/[-]/g, '&');
		
		
		searchString = urlCriteria + '?' + finalSettings + paginateStuff;
		//alert ( 'final settings ' +  urlCriteria + '?' + finalSettings);
		
		
		
		
	} // end if 'searchSettings' cookie exists (and isn't empty)
		
		
		
		
		
		
		
		


	
	// update the hash to show the new sort method (starts w/ slash so format is #/string i/o #string)
	parent.location.hash = "/"+searchString;
	
	// move up or down the page
	if(type=='fromSearchNow') {
		var target = $(".bodyWrapper");
		var targetOffset = 114;
	} else {
		var target = $("#resultsVisible");
		target = target.length && target || $('[name=' + this.hash.slice(1) +']');
		var targetOffset = target.offset().top-$('#paginate').height()-9;
	}
	$('html,body').animate({scrollTop: targetOffset}, 500);



	// ---------------------------------------------------------------------------------
	// format the search string depending on where this request came from
	
	if(type=='fromPaginate') {
		var theUrl = "http://www.rentfortheholidays.com/vacation-rentals-search/"+searchString;
		//alert ( 'blah ' + theUrl );
		//$('#resultsVisible').css({ height : $('#resultsVisible').css('height') }); // keeps it from jumping
		//var oldHeight = $('#resultsVisible').css('height');
	}
	
	if(type=='fromSort') {
		var theUrl = "http://www.rentfortheholidays.com/vacation-rentals-search/"+searchString+"&format=results";
	}
	
	if(type=='fromSearchNow') {
		var theUrl = "http://www.rentfortheholidays.com/vacation-rentals-search/"+searchString+"&format=results";
		//alert ( theUrl );
	}
	
	else if(type!='fromPaginate' && type!='fromSort') {
		//var theUrl = "http://www.rentfortheholidays.com/vacation-rentals-search/"+searchString+"?format=results&startAt="+startAt+"&limit="+show;
		var theUrl = "http://www.rentfortheholidays.com/vacation-rentals-search/"+searchString+"&format=results";
	}
	
	//alert ( theUrl );

	
	// ---------------------------------------------------------------------------------
	// ajax it!
	
	$.ajax({
		type: "POST",
		url: theUrl,
		data: "", //this must be here, even if blank, for this to work in Ffox 2.0 and 3.0
		cache: false,
		success: function(html){
			
			$("#resultsHidden").html(html);
			var num = $("#resultsHidden #cutAndPaste1").html();
			var pag = $("#resultsHidden #cutAndPaste").html();
			var res = $("#resultsHidden #cutAndPaste2").html();
			$("#num").html(num);
			$("#paginationContainer").html(pag);
			$("#paginate").css({ visibility : 'visible' });
			$("#resultsFromAjax").html(res);
			
			$("#resultsVisible").slideDown(500);
			$('#resultsFromAjax').fadeIn();
			
			/*$('.relatedProperty').mouseover(function() {
				$(this).css({ background : '#dddddd', cursor : 'pointer' });
			});
			$('.relatedProperty').mouseout(function() {
				$(this).css({ background : '#ededed', cursor : 'arrow' });
			});*/
			
			
			// ---------------------------------------------------------------------------------
			// if there's hash info and the searchSettings cookie isn't empty
			
			/* var cookieSearchSettings = $.cookie("searchSettings");
			
			if (window.location.hash && cookieSearchSettings!=null) {
				
				var allCurrentSearchSettings = window.location.hash.replace(/#\//, '');
				if( allCurrentSearchSettings.match(/sort/) || allCurrentSearchSettings.match(/limit/) || allCurrentSearchSettings.match(/view/) || allCurrentSearchSettings.match(/images/) ) {
					// do nothing
				} else {
					//cookieSearchSettings = cookieSearchSettings.replace(/-/, '?')
					cookieSearchSettings = cookieSearchSettings.replace(/-/g, '&')
					var addCookieToHash = window.location.hash + '?' + cookieSearchSettings;
					parent.location.hash = addCookieToHash;
				}
				
			}*/
				

			
			
			
			// ---------------------------------------------------------------------------------
			// pagination button clicked 
			
			$('#paginationContainer .page').click(function(){
				//show the ajax loading gif
				$(this).css({ backgroundColor: '#2575AD' }).html('<img src="/adam.more.ajaxloader.rev.gif" />');
				
				// IE6 and 7 see the http:// stuff when grabbing the href, so remove this first
				searchString = $(this).attr('href').replace(/http:\/\/www\.rentfortheholidays\.com/, '');

				// remove the double-slash that was added (//canada) then remove 'vacation-rentals-search'
				searchString = searchString.replace(/\/\//, '/');
				searchString = searchString.replace(/\/vacation-rentals-search\//, '');
				
				// perform the ajax
				getLastSearchResults(searchString,'fromPaginate');
				
				return false;
			}); // end pagination button clicked
			
			
			// ---------------------------------------------------------------------------------
			// sort button clicked 
			
			$('#paginationContainer .sort').click(function(){
				// show the ajax loading gif				
				showAjaxLoadingGif($(this));

				// set the sort type
				if ($(this).attr('id')=='sortByAvail') { var sortBy = 'avail'; }
				if ($(this).attr('id')=='sortByNameA') { var sortBy = 'name_asc'; }
				if ($(this).attr('id')=='sortByNameZ') { var sortBy = 'name_desc'; }
				if ($(this).attr('id')=='sortByDate') { var sortBy = 'date_desc'; }
				if ($(this).attr('id')=='sortByLowPrice') { var sortBy = 'price_asc'; }
				if ($(this).attr('id')=='sortByHighPrice') { var sortBy = 'price_desc'; }

				// performs the clean search string function, which creates a friendly search string			
				searchString = cleanSearchString('sort',sortBy);
				
				// perform the ajax
				getLastSearchResults(searchString,'fromSort');

				return false;
			 }); // end sort button clicked
			
			
			// ---------------------------------------------------------------------------------
			// per page button clicked
			
			$('#paginationContainer .show').click(function(){
				// show the ajax loading gif				
				showAjaxLoadingGif($(this));

				// set the sort type
				if ($(this).attr('id')=='show6') { var limit = '6'; }
				if ($(this).attr('id')=='show12') { var limit = '12'; }
				if ($(this).attr('id')=='show24') { var limit = '24'; }
				if ($(this).attr('id')=='show48') { var limit = '48'; }
				
				// performs the clean search string function, which creates a friendly search string	
				searchString = cleanSearchString('show',limit);

				// perform the ajax
				getLastSearchResults(searchString,'fromSort');

				return false;
			 }); // end per page button clicked
			
			
			// ---------------------------------------------------------------------------------
			// view button clicked (grid or list)
			
			$('#paginationContainer .view').click(function(){
				// show the ajax loading gif
				showAjaxLoadingGif($(this));

				// set the sort type
				if ($(this).attr('id')=='grid') { var view = 'grid'; }
				if ($(this).attr('id')=='list') { var view = 'list'; }
				
				// performs the clean search string function, which creates a friendly search string	
				searchString = cleanSearchString('view',view);
				
				// perform the ajax
				getLastSearchResults(searchString,'fromSort');
				
				return false;
			 }); // end view button clicked
			
			
			// ---------------------------------------------------------------------------------
			// images button clicked (small or large)
			
			$('#paginationContainer .images').click(function(){
				// show the ajax loading gif
				showAjaxLoadingGif($(this));

				// set the sort type
				if ($(this).attr('id')=='large') { var images = 'large'; }
				if ($(this).attr('id')=='small') { var images = 'small'; }
				
				// performs the clean search string function, which creates a friendly search string	
				searchString = cleanSearchString('images',images);
				
				// perform the ajax
				getLastSearchResults(searchString,'fromSort');
				
				return false;
			 }); // end view button clicked
			
			
			// ---------------------------------------------------------------------------------
			// the options slide-down (found @ http://javascript-array.com/scripts/jquery_simple_drop_down_menu)
			
			var timeout    = 500;
			var closetimer = 0;
			var ddmenuitem = 0;
			
			function jsddm_open()
			{  jsddm_canceltimer();
			   jsddm_close();
			   ddmenuitem = $(this).find('ul').css('visibility', 'visible');
			   $(this).find('a').css({ '-moz-border-radius-bottomleft' : '0', '-moz-border-radius-bottomright' : '0', '-webkit-border-bottom-left-radius' : '0', '-webkit-border-bottom-right-radius' : '0' });
			   $(this).find('a:last').css({ '-moz-border-radius-bottomleft' : '5px', '-moz-border-radius-bottomright' : '5px', '-webkit-border-bottom-left-radius' : '5px', '-webkit-border-bottom-right-radius' : '5px' });}
			
			function jsddm_close()
			{  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');
				$('#jsddm').find('a.active').css({ '-moz-border-radius' : '5px', '-webkit-border-radius' : '5px' });}
			
			function jsddm_timer()
			{  closetimer = window.setTimeout(jsddm_close, timeout);}
			
			function jsddm_canceltimer()
			{  if(closetimer)
			   {  window.clearTimeout(closetimer);
				  closetimer = null;}}
			
			$(document).ready(function()
			{  $('#jsddm > li').bind('mouseover', jsddm_open)
			   $('#jsddm > li').bind('mouseout',  jsddm_timer)});
			
			document.onclick = jsddm_close;

			
			
			// ---------------------------------------------------------------------------------
			// the options toggle (not used as of feb 6)
			
			/*$('#paginationContainer #optionsToggle').click(function(){
				
				
				if( $('#optionsContainer').css('display') == 'none' ) {
					$('#optionsContainer').slideDown();	
				} else {
					$('#optionsContainer').slideUp();	
				}
				
				
				return false;
			 });*/
			
			
			// ---------------------------------------------------------------------------------
			// so nothing happens if they click an already-active link
			
			$('#paginationContainer .active').click(function(){
				return false;
			 });
			
			
			// ---------------------------------------------------------------------------------
			// thumbnail moused over (the iTunes effect)
			
			// create an array to preload pictures
			var picPreload = new Array;
			
			// when image rolled over
			$('.image').mousemove(function(e){

				// figure out the container element
				var theContainer = $(this);
				// get the property id 
				var thePropertyId = $(this).attr('id');
				// get imageArrayHolder id (which is 'img1.jpg-img2.jpg-img3.jpg...') and split it into an array
				var imageArray = $(this).find('.imageArrayHolder').attr('id').split('-');
				// get imageSizeHolder id (which is '140-100' or '276-197') and split it into an array
				var imageSizeArray = $(this).find('.imageSizeHolder').attr('id').split('-');
				// figure out array length
				var numOfPictures = imageArray.length;
				// figure out width of each division (divisions are wider if there are fewer pictures)
				var division = $(this).width()/numOfPictures;
				
				// figure out where the mouse is in relation to the image
				var x = e.pageX - $(this).offset().left;
				
				// for each picture in the array
				for(var num = 0; num < numOfPictures; num++) {

					// preload this image if it isn't already preloaded
					if(picPreload[thePropertyId+num]==undefined){
						picPreload[thePropertyId+num] = document.createElement('img');
						picPreload[thePropertyId+num].src = '/uimages/'+thePropertyId+'/'+imageArray[num];
						//if(num==0) { alert ( 'preloading' ); } // to make sure it only preloads once
					}
					//alert ( picPreload );
					
					// needed for the math below
					var numPlusOne = num+1;
					
					// if we've crossed into a new section
					if ( x > division*num && x < division*numPlusOne ) {
						
						// get the old image to compare
						var theOldImage = $(theContainer).find('.imageContainer').html();
						
						// because different browsers see the img different ways (IE sees IMG but Ffox sees img), strip out the <img src=""> (or <IMG src="">) so we're left w/ just the source, which we can properly compare
						var theOldImage = theOldImage.replace(/<img src="/,'');
						var theOldImage = theOldImage.replace(/<IMG src="/,'');
						var theOldImage = theOldImage.replace(/">/,'');
						var theNewImage = '/uimages/'+thePropertyId+'/'+imageArray[num];

						// if the new image is different than the old image, replace it (this prevents it from repeatedly replacing the image on every mouse move; this way, it only replaces if we've switched sections, not if we've just moved a bit on this section)
						if( theNewImage != theOldImage ) {
							//$(theContainer).find('.imageContainer').html('<img src="'+theNewImage+'" width="'+imageSizeArray[0]+'" height="'+imageSizeArray[1]+'" />'); //setting width and height here makes a placeholder image (with a red dot) show up in Firefox; don't set width and height (like below) and the red dot disappears!
							$(theContainer).find('.imageContainer').html('<img src="'+theNewImage+'" />'); // remove the width and height when Adrien gives me med_ images!
						}// end if new image is different than old
						
					}// end if we've crossed into a new section
					
				}// end for each picture in array
				
		   }); // end thumbnail moused over (the iTunes effect)
			
			
			
			// turn on to view generated source in IE:
			// (found at http://sergeb.com/blog/post/Tip-View-Generated-Source-in-IE-or-any-other-browser.aspx)
			// window.open("javascript:'<xmp>' + opener.window.document.documentElement.outerHTML + '</xmp>'");
			
			
			// ---------------------------------------------------------------------------------
			// add the 'Your criteria' links
			
			//format
			searchStringArray = searchString.replace(/\/vacation-rentals-search\//,'');
			searchStringArray = searchStringArray.replace(/\?.*/,''); //remove anything after '?'
			searchStringArray = searchStringArray.replace(/\&.*/,''); //remove anything after '&'
			searchStringArray = searchStringArray.replace(/^\//,''); //remove '/' if string starts with one
			searchStringArray = searchStringArray.replace(/all/,'all locations'); //remove 'all' if it exists
			searchStringArray = searchStringArray.replace(/swap:1/,''); //remove 'house swap' if it exists
			//specialId = searchStringArray.replace(/?:period:([\d-]+)\_([\d-]+)/,''); //format the ugly period:date_date string
			searchStringArray = searchStringArray.replace(/period:([\d-]+)\_([\d-]+)/,'from $1 to $2'); //format the ugly period:date_date string

			//alert ( specialId );
			
			//split into array
			searchStringArray = searchStringArray.split('/');
			
			//bring back together
			for (var i=0; i<searchStringArray.length; i++) {
				//if the location is 'all locations' or empty, don't make it a link
				//if(searchStringArray[i]=='all locations' /*|| searchStringArray[i]==''*/) { searchStringArray[i] = '<span class="allLocations">all locations</span>'; }
				if(searchStringArray[i]=='all locations' || searchStringArray[i]=='') { searchStringArray[i] = ''; }
				//if the location is anything else, make it a link
				else { searchStringArray[i] = '<a class="removeCriteria" id="'+searchStringArray[i]+'" href="#">'+searchStringArray[i].replace(/\+/,' ')+'</a>'; } // 25/03/2010: Replace '+' (url encoded) by white space
				//if this is the first time through, start variable
				if(i==0) { searchStringCombined = searchStringArray[i]; }
				//if this is not the first time through, append variable
				//else { searchStringCombined = searchStringCombined + ' | ' + searchStringArray[i]; }
				else { searchStringCombined = searchStringCombined + searchStringArray[i]; }
			}
			
			//add the links to the page
			$('#criteria').html( searchStringCombined );
			
			
			// ---------------------------------------------------------------------------------
			// Criteria remover
			
			var thinking = false;
			
			// moused over
			$('#criteria > a').mouseover(function(){
				/*var beforeWidth = $(this).width(); - unhide if we center 'We found' header */
				$(this).append(' (x)');
				/*var afterWidth = $(this).width(); - unhide these 3 rows if we center 'We found' header
				var differenceInWidth = afterWidth-beforeWidth;
				$(this).parent().parent().parent().css({ paddingLeft: differenceInWidth/2+'px' });*/
			});
			
			// moused out
			$('#criteria > a').mouseout(function(){
				var theHtml = $(this).html();
				theHtml = theHtml.replace(/\s\(x\)/,'');
				$(this).html(theHtml);
//				alert ( $(this).css('background-color')='');
				//check to see if there's an image in this <a>; if not, set padding-left back to 0
				if(!$(this).find('img').width()) { $(this).parent().parent().parent().css({ paddingLeft: '0px' }); }
			});
			
			// clicked
			$('#criteria > a').click(function(){
				var currentWidth = $(this).width();
				var currentWidth = currentWidth+'px';
				//alert ( $(this).attr('class') );
				//$(this).css({ display: 'block', float: 'left', width : currentWidth });
				
				// remove the '(x)' and show the ajax loading gif
				var theHtml = $(this).html();
				theHtml = theHtml.replace(/\s\(x\)/,'');
				$(this).html(theHtml);
				$(this).css({ backgroundColor: 'red', color: 'white' }).append(' <img src="/adam.more.ajaxloader.red.gif" style="margin-bottom:-3px;" />');

				//clean the searchString
				searchString = cleanSearchString('','');
				toReplace = $(this).attr('id'); //figure out what to replace

				//if there's a 'from', change format from 'from date to date' to 'period:date_date'
				if ( toReplace.match(/from/) ){
					toReplace = toReplace.replace(/from ([\d-]+) to ([\d-]+)/, 'period:$1_$2');
				}
				
				//continue to clean searchString
				searchString = searchString.replace(toReplace,'');
				searchString = searchString.replace(/^\//,''); //remove '/' if string starts with one
				searchString = searchString.replace(/\/$/,''); //remove '/' if string ends with one
				searchString = searchString.replace(/\/\//g,'/'); //replace all '//' with '/'
				
				// update the hash to show the new sort method (starts w/ slash so format is #/string i/o #string)
				//parent.location.hash = "/"+searchString;
				
				// set the search string for ajax
				//searchString = '/vacation-rentals-search/'+searchString;
				
				
				// perform the ajax
				getLastSearchResults(searchString,'fromSort');

				
				return false;

			});
			
			
			// ---------------------------------------------------------------------------------
			// Hover effects for individual properties
			
			//for list view
			$('.searchResultContainer').mouseover(function(){
				$(this).css({ backgroundColor : 'white' });
		   	});
			
			$('.searchResultContainer').mouseout(function(){
				$(this).css({ backgroundColor : '#ededed' });
		   	});
			
			//for grid view
			$('.searchResultContainerGrid').hover(
				function(){
					$('.searchResultContainerGrid').css({ backgroundColor : '#ededed' });
					$(this).css({ backgroundColor : '#ffffff' });
				},
				function(){
					$(this).css({ backgroundColor : '#ededed' });
				}
		   	);
			
			
			/* ugly fix to use later (remember to decide on border) ...
			
			//for grid view
			//it's a little more complex than I'd like (it 'watches' the parent td for the hover, then finds the child div to animate; this is needed b/c the hover sometimes gets stuck on otherwise)
			$('.searchResultContainerGrid').parent().hover(
				function(){
					$(this).find('.searchResultContainerGrid').css({ backgroundColor : '#ffffff', border : 'solid 1px #dddddd' });
				},
				function(){
					$(this).find('.searchResultContainerGrid').css({ backgroundColor : '#ededed', border : 'solid 1px #ededed' });
				}
		   	);
			*/
			
			
			// ---------------------------------------------------------------------------------
			// If there's a favourites cookie, show dark hearts for favourites
			
			var allFavourites = $.cookie("favourites");
			if(allFavourites){
				var allFavourites = allFavourites.split('-');
				for(var i=0, len = allFavourites.length; i<len; ++i) {
					$('#resultsVisible #fav'+allFavourites[i]).hide().parent().append('<a class="goToFav" title="Click to view your favourites" href="#"></a>');
				}// end for each favourited property
			}
			
			
			// ---------------------------------------------------------------------------------
			// Add to favourites

			// make addToFavOn buttons work (in a function so can be re-fired when necessary)
			function turnOnGoToFavBtn(){
				$('.goToFav').click(function() {
					// set searchString and type for ajax
					var searchString = 'favourites';
					var theType = 'fromHash';
					
					//perform the ajax
					getLastSearchResults(searchString,theType);
					
					return false;
				});
			}
			turnOnGoToFavBtn();
			
			// add to favourites cookie maker
			$('.addToFav').click(function() {
				$(this).hide();
				$(this).css({ backgroundPosition: 'bottom' });//make the heart dark
				var propertyID = $(this).attr('id').replace(/fav/,'');//this comes from overall-header.tpl
				$(this).parent().append('<a class="goToFav" title="Click to view your favourites" href="#"></a>');
				var dash = "-";//so we can kill the dash later if it isn't necessary
				var cookieName = 'favourites';//name the cookie
				var currentCookieValue = $.cookie(cookieName);//get the current cookie value
				var alreadyExists = false;//set already exists to false as the default
				if(currentCookieValue!=null) {//if a cookie is set
					var cookieArray = currentCookieValue.split("-");//split the cookie into an array
					for ( var i=0, len=cookieArray.length; i<len; ++i ) {//loop through the array
						if(propertyID==cookieArray[i]) {//if the property already exists in the cookie
							return false; //so it isn't added again (so the rest of the script doesn't run)
						}// end inner if
					}//end for
				}//end if

				// it'll keep running and add the property if this doesn't already exist in the cookie
				if(currentCookieValue==null || currentCookieValue=="-" || currentCookieValue=="") { currentCookieValue=""; dash=""; }//do the dash doesn't show if this is 1st added property
				var cookieValue = currentCookieValue+dash+propertyID;//set the cookie value
				$.cookie(cookieName, null);//clear the old cookie
				$.cookie(cookieName, cookieValue, { path: '/', expires: 365 });//create the new cookie
				
				// change the heart to on
				$('#resultsVisible #fav'+propertyID).removeClass('addToFav').addClass('addToFavOn');
				
				// instantly show the 'My Favourites' link in the header
				$('#myFavouritesLink').html('<a href="#" onclick="window.location=\'/vacation-rentals/#/favourites\'; return false;" class=""><strong>My Favourites</strong></a>');
				
				// fire the function to turn this goToFav button on
				turnOnGoToFavBtn();
				
				return false;
			});//end add to favourites cookie maker (end addToFav clicked)
			
			
			// add to favourites on clicked (if they click an add to fav that's on, it'll take them to favourites)
			// not used?
			$('.addToFavOn').click(function() {
				$('.addToFav').qtip("destroy");
				$('.addToFavOn').qtip("destroy");
				window.location='/vacation-rentals/#/favourites';
				return false;
			});
			
			
			
			// ---------------------------------------------------------------------------------
			// If we're looking at favourites, show the remove favourite buttons
			
			if( window.location.hash.match(/favourites/) ) {
				
				// show the (x)s i/o the hearts
				$('.goToFav').hide().parent().append('<a class="removeFromFav" href="#" title="Remove favourite"></a>');
				
				// if removeFromFav clicked
				$('.removeFromFav').click(function() {
					
					// turn red x on so they can see which is going to go while the confirm box is on
					$(this).addClass('removeFromFavOn');
					
					// if they click yes
					var confirmed = confirm('Are you sure you want to remove this from your list of favourites?');
					if(confirmed) {
						var propertyID =  $(this).parent().parent().parent().find('.left').attr('id');//get prop id
						var cookieName = 'favourites';//name the cookie
						var currentCookieValue = $.cookie(cookieName);//get the current cookie value
						var cookieArray = currentCookieValue.split("-");//split the cookie into an array
						for ( var i=0, len=cookieArray.length; i<len; ++i )//loop through the array
							{
							if(propertyID==cookieArray[i])//if the property already exists in the cookie
								{
								var cookieToDelete = i;
								}//end if
							}//end for
						var newCookieValue = "";
						var dash = "";
						for ( var i=0, len=cookieArray.length; i<len; ++i )//loop through the array
							{
							if(cookieToDelete!=i)
								{
								var newCookieValue = newCookieValue + dash + cookieArray[i];
								dash = "-";
								}
							}//end for
						var cookieValue = newCookieValue;//set the cookie value
						$.cookie(cookieName, null, { path: '/', expires: 365 });//clear the old cookie
						if(cookieValue!=null) $.cookie(cookieName, cookieValue, { path: '/', expires: 365 });//create the new cookie
						//if(len<=2) $('.addBreaksIfNecessary').append("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />");
						
						var dad = $(this).parent().parent().parent().parent().parent();//gets the surrounding div
						dad.slideUp(function() {
							if(len==1) {
								$('#myFavouritesLink').html('');
								//$('.addBreaksIfNecessary').prepend("<strong>You don't yet have any favourites</strong>");
							}
						});
					}//end if confirmed
					
					// if they click no
					else {
						// turn red x off
						$(this).removeClass('removeFromFavOn');
					}
					return false;//so the # isn't added to the url
				});//end removeFromFav click

			} // end cookieDeleter
			
			
			
			// ---------------------------------------------------------------------------------
			// location link clicked (any Country > State > City)
			
			$('.goToLocation').click(function() {
				// set and format the search string 
				var searchString = $(this).html();
				searchString = searchString.toLowerCase().replace(/ /g,'+');
				//alert ( searchString );
				var theType = 'fromHash';
				
				//perform the ajax
				getLastSearchResults(searchString,theType);
				
				return false;
			});
		
			
			// ---------------------------------------------------------------------------------
			// reset toolbar location (because IE messes this up if the page gets shorter) (don't fire if IE6)
			
			if( (!jQuery.browser.msie) || (jQuery.browser.msie && jQuery.browser.version != 6) ) {
				toolbar.checkPosition();
			}
			
			
			// ---------------------------------------------------------------------------------
			// turn 'Searching ->' button back into 'Search now ->'
			
			$('.searchBtn').removeClass('searching');
			
			
			
			// so the ben alman hash change function can fire again (in case back/forward hit)
			window.thinking = false;
			
			
			// ---------------------------------------------------------------------------------
			// fade in new criteria
			
			//$('#resultsContainer .hideUntilRolled').stop(true, true).fadeIn('slow');
			/* temp  $('.blueBox').css({ '-moz-border-radius-bottomleft' : '0', '-moz-border-radius-bottomright' : '0' }); */

		

		} // end the success
	});	// end the ajax
} // end the getLastSearchResults function
	

// ---------------------------------------------------------------------------------
// when the page has loaded

$(document).ready(function() {
						   
	window.thinking = false;		   
						   
	// ---------------------------------------------------------------------------------
	// when search now is clicked
	
	$('.searchBtn').click(function() {

		// just for house swap page ----------
		if( $('#house_swap').val()==1 ){

			// set houseSwap to true
			var houseSwap=true;
			
			// grab (then modify) the client's location
			var theClientLocation = getLocationString($('#locationClientString').val());
			if (theClientLocation=='' || theClientLocation=='your property location') { theClientLocation = ''; }
			theClientLocation = theClientLocation.replace(/ /g,'+');
			
			// if client location isn't empty, add /my-location: before
			if(theClientLocation!='') {
				theClientLocation = '';
			}
			
			// get the data from the hidden fields
			var theCity = $('#hs_city').val();
			var theState =  $('#hs_state').val();
			var theCountry = $('#hs_country').val();
			
			// only include hidden data if it's not empty
			if (theCity!='') { theCity = '/hs-city:' + theCity; }
			if (theState!='') { theState =  '/hs-state:' + theState; }
			if (theCountry!='') { theCountry =  '/hs-country:' + theCountry; }
			
			// set the house swap info
			var houseSwapInfo = '/swap:1' + theCity + theState + theCountry;


		}
		// end just for house swap page ----------
		
		// if not house swap page, set var to be empty (goes with the if above)
		else { var theClientLocation = ''; var houseSwapInfo = ''; }
												   
		// get values from the form
		//var theLocation = "/" + $('#locationString').val();
		var theLocation = getLocationString($('#locationString').val());
        var theCheckIn = $('#checkInDate').val();
		var theCheckOut =  $('#checkOutDate').val();
		var thePriceRange = "/" + $('#amount').val();
		var theSleepsRange = "/" + $('#sleeps').val();
		var basedOnLocation = $('#basedOnLocation').val();
		var theKeywords = '';
		var theKeyWordsFinal = '';
			
		//alert ( theLocation );
		
		// if values are empty don't add them to hash or search string (check in/out done later)
		if (theLocation=='' || theLocation=='destination or keywords') { theLocation = 'all'; }
		if (theCheckIn=='' || theCheckIn=='undefined' || theCheckIn=='Check In') { theCheckIn = ''; }
		if (theCheckOut=='' || theCheckOut=='undefined' || theCheckOut=='Check Out') { theCheckOut = ''; }
		if (thePriceRange=='/' || thePriceRange=='/Any price') { thePriceRange = ''; }
		if (theSleepsRange=='/' || theSleepsRange=='/Any number') { theSleepsRange = ''; }
		
		// Search by PID
		if (is_numeric(theLocation)) {
			window.location = "http://www.rentfortheholidays.com/property-redirect.php?pid=" + theLocation;
			die;
		}

		
		// check basedOnLocation field - if true, perform a normal location search else keyworks search...
		if (basedOnLocation=='true') { 
			theLocation = theLocation.replace(/ /g,'+'); //g modifier means replace all i/o just first instance
		} 
		if (basedOnLocation!='true' && theLocation != '' && theLocation != 'all')  {
			theLocation = 'all';
			theKeyWords =  $('#locationString').val();
			theKeyWords = theKeyWords.replace(/ /g,'+');
			theKeyWordsFinal = '/terms:' + theKeyWords;	
		}

		
		// if check in/out aren't empty, create string
		if(theCheckIn!='' && theCheckOut!='') {
			theCheckInOut = '/period:' + theCheckIn + '_' + theCheckOut;
		} else {
			theCheckInOut = '';
		}
		
		// change price range string
		thePriceRange = thePriceRange.replace(/ /g,'');
		thePriceRange = thePriceRange.replace(/\$/,'min:');
		thePriceRange = thePriceRange.replace(/-/g,'/max:');
		thePriceRange = thePriceRange.replace(/\$/,'');
		
		//change sleeps string
		if(theSleepsRange!=''){
			theSleepsRange = theSleepsRange.replace(/[\s\/]/g,'');
			theSleepsRangeArray = theSleepsRange.split('-');
			theSleepsRange = '/bedrooms:' + theSleepsRangeArray[0] + '-'+theSleepsRangeArray[1];
		}
		
		
		// ---------------------------------------------------------------------------------
		// if there's hash info and the searchSettings cookie isn't empty
		
		/* var cookieSearchSettings = $.cookie("searchSettings");
		
		if (window.location.hash && cookieSearchSettings!=null) {
			
			var allCurrentSearchSettings = window.location.hash.replace(/#\//, '');
			if( allCurrentSearchSettings.match(/sort/) || allCurrentSearchSettings.match(/limit/) || allCurrentSearchSettings.match(/view/) || allCurrentSearchSettings.match(/images/) ) {
				// do nothing
			} else {
				//cookieSearchSettings = cookieSearchSettings.replace(/-/, '?')
				cookieSearchSettings = cookieSearchSettings.replace(/-/g, '&')
				var addCookieToHash = window.location.hash + '?' + cookieSearchSettings;
				parent.location.hash = addCookieToHash;
			}
			
		}*/
		
		// Reset basedOnLocation
		$('#basedOnLocation').val('false');
		
		// set the search string and modify the hash
		var searchString = theLocation + theClientLocation + houseSwapInfo + theCheckInOut + thePriceRange + theSleepsRange + theKeyWordsFinal;
		//parent.location.hash = searchString;
		
		// search and ajax the results
		getLastSearchResults(searchString,'fromSearchNow');
		
		// turn 'Search ->' into 'Searching 0' (unless IE ... this will cause it to melt down)
		if(!$.browser.msie) {
			$('.searchBtn').addClass('searching');
		}

		return false;
	});
	
	
	// ---------------------------------------------------------------------------------
	// function to show results based on hash info (used when page visited via bookmark or back/forward)
	
	function loadResultsBasedOnHash(){
		
		// grab the search string from the hash
		var searchString = window.location.hash;
		
		// if there's nothing in the hash, hide results and stop the search (b/c we're back to vacation-rentals/)
		if(!searchString) { return false; }
		
		// delete the # from the search string
		searchString = searchString.replace(/#/g,'');
		
		// stop everything if they're on favourites but don't have any favourites
		if( searchString.match(/favourites/) && ( $.cookie("favourites") == null || $.cookie("favourites") == "-" ||  $.cookie("favourites") == "" ) ) {
			return false;
		}
		
		// if there's a sort method
		if( searchString.match(/view/) || searchString.match(/limit/) || searchString.match(/images/) || searchString.match(/sort/) ) {
			// set the search string with the sort method and proper format
			searchString = searchString.replace(/\//,'');
			// if there's a sort, this is a special search string, so set type to paginate
			var theType = 'fromSort';
		} else {
			// set the search string with the sort method and proper format
			searchString = searchString.replace(/\//,'');
			// if there's no sort method, set type to from hash
			var theType = 'fromHash';
		}
		
		// search and ajax the results
		getLastSearchResults(searchString,theType);
		
		// turn 'Search ->' into 'Searching 0' (unless IE ... this will cause it to melt down)
		if(!$.browser.msie) {
			$('.searchBtn').addClass('searching');
		}	
		
	}
	
	
	// ---------------------------------------------------------------------------------
	// if user comes from bookmark
	
	if (window.location.hash) {
		loadResultsBasedOnHash();
	}
	
	
	// ---------------------------------------------------------------------------------
	// if user hits back or forward (http://benalman.com/projects/jquery-hashchange-plugin/)
	
	$(window).bind( 'hashchange', function(){
		if(window.thinking==false) {
			//alert ( window.thinking );
    		loadResultsBasedOnHash();
		}
	});

	
	
	// ---------------------------------------------------------------------------------
	// the tips that don't show up until you hover
	
	$('#quickSearchContainer').hover(
		function(){
			$(this).find('.hideUntilRolled').stop(true, true).fadeIn('slow');
		},
		function(){
			$(this).find('.hideUntilRolled').stop(true, true).fadeOut('slow');
		}
	);
	
	/* maybe use later (this is the Move your mouse over...)
	$('#resultsFromAjax').hover(
		function(){
			$('.hideUntilRolled2').stop(true, true).fadeIn('slow');
		},
		function(){
			$('.hideUntilRolled2').stop(true, true).fadeOut('slow');
		}
	);*/
		
            
       // --------------------------------------------------------------------------------
       // Datepicker
        $("#checkInDate").datepicker({ dateFormat: 'yy-mm-dd',
                                    minDate: 0,
                                    beforeShow: customRange
                                    });
        $("#checkOutDate").datepicker({ dateFormat: 'yy-mm-dd',
                                    beforeShow: customRange
                                    });




	

}); // end document ready function




// ---------------------------------------------------------------------------------
// function that cleans the search string

function cleanSearchString(remove,add){

	// get the search string from the hash
	var searchString = window.location.hash;
	
	// delete any #/ from the search string
	searchString = searchString.replace(/#\//g,'');

	// turn all '?' and '&' into '|'
	searchString = searchString.replace(/[\?\&]/g,'|');
	
	//alert ( searchString );
	searchString = searchString.replace(/format=[a-z]+/gi,'');
	searchString = searchString.replace(/next=[0-9]+/g,'');
	searchString = searchString.replace(/startAt=[0-9\/]{1,}/gi,'');

	if(remove=='show'){
		searchString = searchString.replace(/limit=[0-9]+/g,'');
		searchString = searchString + '|limit='+add;
	}
	
	if(remove=='sort'){
		searchString = searchString.replace(/sort=[a-z\_]+/g,'');
		searchString = searchString + '|sort='+add;
	}
	
	if(remove=='view'){
		searchString = searchString.replace(/view=[a-z]+/g,'');
		searchString = searchString + '|view='+add;
	}
	
	if(remove=='images'){
		searchString = searchString.replace(/images=[a-z]+/g,'');
		searchString = searchString + '|images='+add;
	}
	
	//turn any '||', '|||', '||||' etc into '|'
	searchString = searchString.replace(/[\|]{2,}/g,'|'); // now our search string is clean: location/period/min/max/bedroomms/sort=var|limit=var|view=var|images=var
	
	//alert ( searchString );
	
	// set the cookie that remembers their preferences
	var searchStringForCookie = '';//create the empty var
	var searchStringArray = searchString.split("|");//split the searchString

	for ( var i=0, len=searchStringArray.length; i<len; ++i ) {//loop through the array
		if( !searchStringArray[i].match(/\=/) ) {//if there's no =, this must be the country name; we don't want this...
			//so do nothing
		} else { //if there is an =, we want this
			if( searchStringForCookie == '' ) {//if it's the first time through
				var searchStringForCookie = searchStringArray[i];//add the value
			} else {//if it's the second or more time through
				searchStringForCookie = searchStringForCookie + "-" + searchStringArray[i];//append a dash and the value
			}
		}
	}

	var cookieName = 'searchSettings';//name the cookie
	$.cookie(cookieName, null);//clear the old cookie
	$.cookie(cookieName, searchStringForCookie, { path: '/', expires: 365 });//create the new cookie*/
	
	//alert ( searchString );
	
	// now replace the first '|' with a '?'
	searchString = searchString.replace(/\|/,'?');
	// replace the rest of the '/' with '&'
	searchString = searchString.replace(/\|/g,'&'); // now our string is back to GET format
	
	return searchString;
	//alert ( searchString );


} // end clean search string function


// ---------------------------------------------------------------------------------
// function that shows the ajax loading gif (b/c the sort dropdowns are complex)

function showAjaxLoadingGif(target){
	$(target).parent().parent().parent().find('ul').css({ visibility: 'hidden' });
	$(target).parent().parent().parent().find('.active').css({ backgroundColor: '#2575AD', '-moz-border-radius' : '5px', '-webkit-border-radius' : '5px' }).html('<img src="/adam.more.ajaxloader.rev.gif" />');
}



// ---------------------------------------------------------------------------------
// the floating 'Your search crietia produced...' bar

var toolbar = {
	
	state: "static",
	
	// setup - initialises the window.onscroll handler
  
	setup: function() {
		//var toolbarType = perldoc.getFlag('toolbar_position');
		//if (toolbarType != 'standard') {
			toolbar.checkPosition();
			/*if (toolbar.state == 'fixed') {
				// If an internal link was called (x.html#y) the link position will be
				// behind the toolbar so the page needs to be scrolled 90px down
				anchor = location.hash.substr(1);
				if (anchor) {
					var allLinks = $(document.body).getElements('a');
					allLinks.each(function(link) {
						if (link.get('name') == anchor) {
							window.scrollTo(0,link.offsetTop + 100);
						}
					});
				}
			}*/
		
			//toolbar.rewriteLinks();
			window.addEvent('scroll', toolbar.checkPosition); // addEvent needs mootools js to work
		//}
	},

	
	// checkPosition - checks the scroll position and updates toolbar
	
	checkPosition: function() {
		var paginateOffset = $('#getOffset').offset().top;
		//alert (paginateOffset);
		if ((toolbar.state == 'static') && (toolbar.getCurrentYPos() > paginateOffset)) {
			//alert ( $('#paginate').height() );
			var theMarginTop = $('#paginate').height(); // must get this before changing the css of #paginate
			theMarginTop = theMarginTop + 10;
			theMarginTop = [theMarginTop+'px'];
			//alert ( theMarginTop );
			$('#paginate').css({ position : 'fixed' , top : '0' });
			$('#resultsVisible').css({ marginTop  : theMarginTop });
			toolbar.state = 'fixed';
		}
		
		if ((toolbar.state == 'fixed') && (toolbar.getCurrentYPos() <= paginateOffset)) {
			$('#paginate').css({ position : 'static' });
			$('#resultsVisible').css({ marginTop  : "0px" });
			toolbar.state = 'static';
		}    
	},
	
	// getCurrentYPos - returns the vertical scroll offset
  
	getCurrentYPos: function() {
		if (document.body && document.body.scrollTop)
			return document.body.scrollTop;
		if (document.documentElement && document.documentElement.scrollTop)
			return document.documentElement.scrollTop;
		if (window.pageYOffset)
			return window.pageYOffset;
		return 0;
	},
	
	// goToTop - scroll to the top of the page
  
	goToTop: function() {
		$('content_header').style.position = "static";
		$('content_body').style.marginTop  = "0px";
		toolbar.state = 'static';
		window.scrollTo(0,0);
	},
	
	// getDocHeight - return the height of the document
  
	getDocHeight: function() {
		var D = document;
		return Math.max(
			Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
			Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
			Math.max(D.body.clientHeight, D.documentElement.clientHeight)
		);
	}

}

// set up the floating toolbar (unless browser is IE6)
if( (!jQuery.browser.msie) || (jQuery.browser.msie && jQuery.browser.version != 6) ) {
	toolbar.setup();
	window.addEvent('scroll', toolbar.checkPosition());
}



// ---------------------------------------------------------------------------------
// not used, maybe in future

function changeText(id, newString) {
	var para = document.getElementById(id);
	var theText = newString;
	para.innerHTML = theText;
}

function textChanged(target, source) {
	//var target = 'location';
	//var source = document.quickSearchForm.locationName.value;
	changeText(target, source);
	//changeText('warningText', '');
	//changeDisplayStyle('undoTextClearBtn', 'none');
	return document.textForm.bandName.value;
}


// ---------------------------------------------------------------------------------
// Datepicker

function customRange(input)
{
        var min = new Date(); //Set this to your absolute minimum date
        var dateMin = min;
        var dateMax = null;
        var today = new Date();

        if (input.id == "checkInDate") // Click on checkIn field | Min Date: Today - Max Date: Current Checkout date or today+1year
        {
            if ($("#checkOutDate").datepicker("getDate") != null && $("#checkOutDate").val() != "Check Out")
            {
                dateMax = $("#checkOutDate").datepicker("getDate");
                dateMin = today;
                if (dateMin < min)
                {
                        dateMin = min;
                }
             }
             else
             {
                dateMin = 0;
                dateMax = today; //Set this to today
                dateMax.setDate(today + 365);

             }
        }
        else if (input.id == "checkOutDate" && $("#checkInDate").val() != "Check In")
        {

                if ($("#checkInDate").datepicker("getDate") != null)
                {
                        dateMin = $("#checkInDate").datepicker("getDate");
                        dateMax = new Date(); //Set this to today
                        dateMax.setDate(dateMin + 365);
                }
        }
    return {
                minDate: dateMin,
                maxDate: dateMax
            };

}


// ---------------------------------------------------------------------------------
// Get the location in a proper formet: Country, states, city -> Country/states/city

function getLocationString(string) {
    // Split string: delimiter ","

    var data = string.split(",").reverse();
    var nbArg = data.length;
    var location = '';
    var loc;
    if (string != "Where do you want to go?") {
        // 3 differents cases
        for (var i=0;i < nbArg;i++ ) {
            loc = trim(data[i]).toLowerCase(); // .replace(/ /,"-") .. seo url?
            location = location + loc;
            if (i != nbArg-1) {
                location = location + '/';
            }
        }
    }
    return location;
}


// ---------------------------------------------------------------------------------
// Javascript trim, ltrim, rtrim (http://webtoolkit.info)

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}
function is_numeric (mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}

function clear_loc_form() {
	$('#hs_city').val('');
	$('#hs_state').val('');
	$('#hs_country').val('');
}