// -------------------------------------------------------------------------------------
// getLastSearchResults (for Last Search Results tab)

function getLastSearchResults(section,id,startAt,show,shown) {
	//alert ( 'hi' +  {$smarty.session.lastSearch_url} );
	$.ajax({
		type: "POST",
		url: "http://www.rentfortheholidays.com/vacation-rentals-search/"+lastSearchUrl+"&format=more&startAt="+startAt+"&limit="+show+"&current_id="+id,
		//data: "section=" + section + "&pid=" + id + "&startAt= " + startAt + "&show= " + show,
		cache: false,
		success: function(html){
			//alert ( {smarty.session.lastSearch_url} );
			$("#more_updates-"+section).append('<div id="'+startAt+'-'+section+'" style="display:none;">'+html+'</div>');
			$("#"+startAt+"-"+section).show();
			//$("#"+startAt+"-"+section).slideDown(500);
			$("#morebutton-"+section).html('&nbsp;&nbsp;<a id="'+section+'-'+id+'-'+shown+'-'+show+'" class="more" href="#">More results from your last search</a> <img style="visibility:hidden;" class="ajaxLoader" src="/adam.more.ajaxloader.gif" />');
			//alert ('hi');
			//$(".more").remove();
			//vacation-rentals-search/min:100/max:200/
		}
	});	
}// end getLastSearchResults (for Last Search Results tab)

// -------------------------------------------------------------------------------------
// getLastSearchResults (for any location link [i.e. if Canada is clicked])

function getLastSearchResults2(searchString,type,startAt,show,shown) {
	
	// ---------------------------------------------------------------------------------
	// combine cookie settings and url (or newly chosen) settings
	
	//alert ( searchString );
	
	// get the cookie
	var cookieSettings = $.cookie("searchSettings");
	
	// if 'searchSettings' cookie exists (and isn't empty)
	if (cookieSettings!=null && cookieSettings!='') {
		
		// 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);
		
		//alert ( searchString );
		
	} // end if 'searchSettings' cookie exists (and isn't empty)
	
	
	var theUrl = "http://www.rentfortheholidays.com/vacation-rentals#"+searchString;
	
	window.location=theUrl;
	
	//return false;


} // end the getLastSearchResults function





// -------------------------------------------------------------------------------------
// hide review form

function hideReviewFormShowMsg() {
	$("#reviewSubmitbutton").hide();
	$("#confirmSend").show();
}
	

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

$(document).ready(function() {
    // Get VAR
    currentPid = $('#pid').val();
    currentSid = $('#sid').val();
    currentLat = $('#lat').val();
    currentLng = $('#lng').val();
    
    
	 // Send Booking form
	$("#formSendBookingReq").livequery("submit",function() {
		var form = $(this);

		// set sid	
		alert('sid' + Base64.encode(currentSid));
		form.find("input[name='sid']").val(Base64.encode(currentSid));
		// Serialize data
		var dataf = form.serialize();
		// TODO: do some test etc... and if ti's fine return true
		return true;
	}); // End sending book form
	
	// Send Review Form
    $("#reviewForm").validationEngine({
	    ajaxSubmit: true,
	    ajaxSubmitMessage: "Your review has been sent!",
	    ajaxSubmitFile: "/review-add.php",
	    success: function() { 
	    	
	    	hideReviewFormShowMsg();
	    	return false;
    	 }
    });
    
	
	// ---------------------------------------------------------------------------------
	// when links that go to search page are clicked
	
	$('.searchLink').click(function() {
								   
		// get value from the link
		var theLocation = $(this).attr('href');
		
		// remove the excess (everything before '/location')
		theLocation = theLocation.replace(/\/vacation-rentals\/#/, '');
		
		// turn spaces into '+'
		theLocation = theLocation.replace(/ /g, '+');
		
		// set the search string and modify the hash
		var searchString = theLocation;
		
		// search and ajax the results
		getLastSearchResults2(searchString,'fromSearchNow','0','10','10');
		
		return false;
	});
	
	
	
	
    $('#linkEnquiry').live('click',function() {
		//to keep it from firing twice
		var alreadyRan = false;
		
		//if it hasn't run (this just keeps it from firing twice, which it likes to do)
		if(alreadyRan==false){
			//if we're in tab view
			if(listView==false){
				//set the target, fade the correct tab in
				var $target = $(".middleTabs");
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					// Set variables
					var checkin = $('.enqStartDate').val();
					var checkout = $('.enqEndDate').val();
					var total = $('#facebox .booking_total').text();
					
					// Fill out enquiry form
					$("#checkfrom").val(checkin);
					$("#checkto").val(checkout);
					$("#tresc").val("\n\nTotal price: "+total);
					// Facebox close
					$.facebox.close();
					 
					var targetOffset = $target.offset().top-14;
					$('html,body').animate({scrollTop: targetOffset}, 500, function(){ 
						$(".middleTabs ul.tabs li").removeClass("active"); //Remove any "active" class
						$(".middleTabs ul.tabs li:eq(5)").addClass("active"); //Add "active" class to selected tab
						//$(".middleTabs .tabContent").fadeOut("fast", function(){
							$(".middleTabs #contactOwnerTab").fadeIn("fast"); //Fade in the active ID content
						//});
					
					});
					return false;
				}
			}//end if we're in tab view
			
			//if we're in list view
			else if(listView==true){
				//set the target, scroll down the page
				var $target = $("#propertyDetailsTab");
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 500);
					return false;
				}
			}//end if we're in list view
			
			//so it won't run twice
			alreadyRan = true;
		}//end if hasn't run
		return false;    	
    });
    
	// More Search result
	$(".moreSearch").click(function() {
		var element = $(this);
		var elementId = element.attr('id');
		if ( elementId.indexOf("morebutton-") > -1 ) { element = element.find('a'); }
		var infoFromId = element.attr("id");
		var infoFromId = infoFromId.split('-');
		var section = 'lastSearchResults';
		var id = infoFromId[1];
		var startAt = infoFromId[2];
		var show = infoFromId[3];
		// First lauch
		if (startAt == '') {
			var startAt = '0';
			var show = '4';
		}
		var shown = parseInt(startAt) + parseInt(show);
		
		getLastSearchResults(section,id,startAt,show,shown);
		
	});
	
	
	// Top tabs, middle tabs, and bottom tabs
	var listView = false; // so the read more link knows we're in tabView
	$.fn.simpleTabs = function(){ 
		// do this right away
		$(this).find(".tabContent").hide(); //Hide all content
		$(this).find("ul.tabs li:first").addClass("active").show(); //Activate first tab
		$(this).find(".tabContent:first").show(); //Show first tab content
	
		// if any tab clicked (including List View, which counts as a tab)
		$("ul.tabs li").click(function() {
			
			// if Switch to List View button clicked
			if( $(this).find("a").attr("href") == '#listView' ) {
				// figure out which tab we're on and give it the class 'current'
				var $setOfTabs = $(this).parent().parent().attr('class').split(' ').slice(-1); //Figure out which set of tabs was clicked
				$('.current').removeClass('current');
				$("."+$setOfTabs+" .tabContent").each(function(){
					if( $(this).css('display') === 'block' ){
						$(this).addClass('current');
					};
				});
				var $target = $(".current");
				
				//hide the blue gradient in the background
				$(".middleTabs .tabContent").css('background','white');
				
				// show content and hide tabs
				$(".middleTabs .tabContent, .bottomTabs .tabContent").show(); //Show all content
				$(".middleTabs .tabContent, .bottomTabs .tabContent").find("h2").show(); //Show all h2s
				$(".middleTabs ul.tabs, .bottomTabs ul.tabs").hide(); //Hide the tabs
				$(".middleTabs .tabContainer").css({ border: "none", width: "928px" });
				$(".bottomTabs .tabContainer").css({ borderTop: "solid 1px #cccccc", borderLeft: "solid 1px #cccccc", borderRight: "solid 1px #cccccc", borderBottom: "solid 1px #cccccc", width: "926px" });//middleTabs and bottomTabs differ here
				$(".middleTabs .tabContent").css({ padding: "0" });
				$(".bottomTabs .tabContent").css({ padding: "7px" });//middleTabs and bottomTabs differ here
				
				// use target to send down the page
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 500);
				}
				
				// final steps
				listView=true;
				makeCookie();
				return false;

			}// end if List View button clicked
			
			// if any tab other than List View clicked
			else {
				$(this).parent().parent().find("ul.tabs li").removeClass("active"); //Remove any "active" class
				$(this).addClass("active"); //Add "active" class to selected tab
				$(this).parent().parent().find(".tabContent").fadeOut("fast", function(){
					$(activeTab).fadeIn("fast"); //Fade in the active ID content
				}); //Hide all tab content
				var activeTab = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content (this must go after it's called above or it flashes twice)
			}
			
			return false;
		});//end tab clicked function
		
	};//end simpleTabs function
	
	
	// Read more
	$("a.readMore[href*=#]").click(function() {

		//to keep it from firing twice
		var alreadyRan = false;
		
		//if it hasn't run (this just keeps it from firing twice, which it likes to do)
		if(alreadyRan==false){
			//if we're in tab view
			if(listView==false){
				//set the target, fade the correct tab in
				var $target = $(".middleTabs");
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top-14;
					$('html,body').animate({scrollTop: targetOffset}, 500, function(){ 
						$(".middleTabs ul.tabs li").removeClass("active"); //Remove any "active" class
						$(".middleTabs ul.tabs li:eq(1)").addClass("active"); //Add "active" class to selected tab
						$(".middleTabs .tabContent").fadeOut("fast", function(){
							$(".middleTabs #propertyDetailsTab").show(); //show (because fade in made it happen twice; I don't think the alreadyRan is necessary any more - test then remove eventually (Apr 13 2010)
						});
					
					});
					return false;
				}
			}//end if we're in tab view
			
			//if we're in list view
			else if(listView==true){
				//set the target, scroll down the page
				var $target = $("#propertyDetailsTab");
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 500);
					return false;
				}
			}//end if we're in list view
			
			//so it won't run twice
			alreadyRan = true;
		}//end if hasn't run
		return false;
	});//end Read more clicked
	
	
	// Book now (this should be combined with the Read more function above, but for now it's separate)
	$("a.bookNow[href*=#]").click(function() {
										   
		var theTarget = $(this).attr('href');
		
		//to keep it from firing twice
		var alreadyRan = false;
		
		//if it hasn't run (this just keeps it from firing twice, which it likes to do)
		if(alreadyRan==false){

			//if we're in tab view
			if(listView==false){
				
				//set the target, fade the correct tab in
				if(theTarget=='#availabilityAndBookingsTab') { var $target = $('#middleTabs'); }
				else { var $target = $(theTarget); }
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top-14;
					var alreadyRan2 = false;
					$('html,body').animate({scrollTop: targetOffset}, 500, function(){ 
						
						if(theTarget=='#availabilityAndBookingsTab') { 
							$(".middleTabs ul.tabs li").removeClass("active"); //Remove any "active" class
							$(".middleTabs ul.tabs li:eq(4)").addClass("active"); //Add "active" class to selected tab
							$(".middleTabs .tabContent").fadeOut("fast", function(){
								$(theTarget).show(); //show (because fade in made it happen twice; I don't think the alreadyRan is necessary any more - test then remove eventually (Apr 13 2010)
							});
						}//end if target = availability and bookings
					
					});//end animate
					return false;
				}
			}//end if we're in tab view
			
			//if we're in list view
			else if(listView==true){
				//set the target, scroll down the page
				var $target = $(theTarget);
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 500);
					return false;
				}
			}//end if we're in list view
			
			//so it won't run twice
			alreadyRan = true;
		}//end if hasn't run
		return false;
	});//end Book now clicked
					
					
					
	// send enquiry (this should be combined with the Read more function above, but for now it's separate)
	$('.sendEnquiryToOwner').live('click',function() {
	
		//alert ( listView );

		//to keep it from firing twice
		var alreadyRan = false;
		
		//if it hasn't run (this just keeps it from firing twice, which it likes to do)
		if(alreadyRan==false){
			//if we're in tab view
			if(listView==false){
				//set the target, fade the correct tab in
				var $target = $(".middleTabs");
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top-14;
					$('html,body').animate({scrollTop: targetOffset}, 500, function(){ 
						$(".middleTabs ul.tabs li").removeClass("active"); //Remove any "active" class
						$(".middleTabs ul.tabs li:eq(5)").addClass("active"); //Add "active" class to selected tab
						$(".middleTabs .tabContent").fadeOut("fast", function(){
							$(".middleTabs #contactOwnerTab").show(); //show (because fade in made it happen twice; I don't think the alreadyRan is necessary any more - test then remove eventually (Apr 13 2010)
						});
					
					});
					return false;
				}
			}//end if we're in tab view
			
			//if we're in list view
			else if(listView==true){
				//set the target, scroll down the page
				var $target = $("#contactOwnerTab");
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 500);
					return false;
				}
			}//end if we're in list view
			
			//so it won't run twice
			alreadyRan = true;
		}//end if hasn't run
		return false;
	});//end Send enquiry clicked
	
	
	// Switch to Tab View
	$(".tabView").click(function() {

		//get info about selected set of tabs, selected tab button, selected tab content
		var $setOfTabs = $(this).parent().parent().parent().parent().attr('class').split(' ').slice(-1);
		if( $setOfTabs=='middleTabs' ) { var $otherSetOfTabs = 'bottomTabs' } else { var $otherSetOfTabs = 'middleTabs' }
		var $selectedTabButtonId = $(this).parent().parent().attr('id'); // get the selected container's id
		var $selectedTabContent = $(this).parent().parent(); // get the selected container div
		//alert ( $setOfTabs );
		
		//show the blue gradient in the background again
		$(".middleTabs .tabContent").css('background','url(/includes/images/behindTabContent.png) top repeat-x #f5f7f9');

		//do this for the middle and bottom sets of tabs
		$(".middleTabs .tabContent, .bottomTabs .tabContent").hide(); //Hide all content
		$(".middleTabs .tabContent, .bottomTabs .tabContent").find("h2").hide(); //Hide H2s
		$(".middleTabs ul.tabs li, .bottomTabs ul.tabs li").removeClass("active"); //Remove any "active" class
		$(".middleTabs ul.tabs, .bottomTabs ul.tabs").show(); //Activate first tab

		//do this for just the selected set of tabs
		$("."+$setOfTabs+" ul.tabs li a[href*="+$selectedTabButtonId+"]").parent().addClass("active").show(); //Activate selected tab buttton
		$selectedTabContent.fadeIn(); //Show selected tab content

		//for the other (non-selected) set of tabs
		$("."+$otherSetOfTabs+" ul.tabs li:first").addClass("active").show(); //Activate first tab button
		$("."+$otherSetOfTabs+" .tabContent:first").fadeIn(); //Activate first tab content

		//for middle and bottom sets again	
		$(".middleTabs .tabContainer, .bottomTabs .tabContainer").css({ border: "1px solid #ccc", width: "934px" });
		$(".middleTabs .tabContent, .bottomTabs .tabContent").css({ padding: "20px 10px 20px 10px" });
		$(".middleTabs ul.tabs, .bottomTabs ul.tabs").css({ marginBottom: "-1px" });
		
		//set view type
		listView=false;
		
		//scroll up
		$target = $("."+$setOfTabs);
		$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
		if ($target.length) {
			var targetOffset = $target.offset().top-14;
			$('html,body').animate({scrollTop: targetOffset}, 500);
		}
		
		//final steps
		makeCookie();
		return false;
	});
	
	
	
	// Related properties (in the bottomTabs) rollover - NOTE: this is repeated in templates/includes/search-more.tpl, so if you change this change that as well
	$('.relatedProperty').mouseover(function() {
		$(this).css({ background : 'white', cursor : 'pointer' });
	});
	$('.relatedProperty').mouseout(function() {
		$(this).css({ background : 'inherit', cursor : 'arrow' });
	});
	
	
	//Things to fire
	$("div[class^='simpleTabs']").simpleTabs(); //Run function on any div with class name of "Simple Tabs"
	$('#virtualTourSelector0').find('img').css({ border : 'solid 1px white' });
	
	
	// Cookie maker for list view / tab view preference
	function makeCookie() {
		var cookieName = 'propertyPageViewPreference';
		var currentCookieValue = $.cookie(cookieName);//get the current cookie value
		if ( listView == false ) { var cookieValue = 'tabView'; } else { var cookieValue = 'listView'; }
		$.cookie(cookieName, null);//clear the old cookie
		$.cookie(cookieName, cookieValue, { path: '/', expires: 365 });//create the new cookie
	}//end makeCookie function
	
	
	// Cookie reader for list view / tab view preference
	if($.cookie('propertyPageViewPreference')=='listView') {
		//hide the blue gradient in the background
		$(".middleTabs .tabContent").css('background','white');
		//show content and hide tabs ----------------------------------->
		$(".middleTabs .tabContent, .bottomTabs .tabContent").show(); //Show all content
		$(".middleTabs .tabContent, .bottomTabs .tabContent").find("h2").show(); //Show all h2s
		$(".middleTabs ul.tabs, .bottomTabs ul.tabs").hide(); //Hide the tabs
		$(".middleTabs .tabContainer, .bottomTabs .tabContainer").css({ border: "none", width: "928px" });
		$(".bottomTabs .tabContainer").css({ borderTop: "solid 1px #cccccc", borderLeft: "solid 1px #cccccc", borderRight: "solid 1px #cccccc", borderBottom: "solid 1px #cccccc", width: "934px" });//middleTabs and bottomTabs differ here
		$(".middleTabs .tabContent").css({ padding: "0" });
		$(".bottomTabs .tabContent").css({ padding: "7px" });//middleTabs and bottomTabs differ here
		listView=true;
	}
	
	
	
	
	

	// Calendar - Send Enquiry
    $("#checkfrom").datepicker({ dateFormat: 'yy-mm-dd',
                                    showOn: 'both',
                                    minDate: 0,
                                    beforeShow: customRange,
                                    buttonImage: '/images/calendar.gif'});
	$("#checkto").datepicker({ dateFormat: 'yy-mm-dd',
                                    beforeShow: customRange,
                                    showOn: 'both',
                                    buttonImage: '/images/calendar.gif'});
	// Function customRange for datepicker
	function customRange(input)
	{
			var min = new Date(); //Set this to your absolute minimum date
			var dateMin = min;
			var dateMax = null;
			var dayRange = 6; // Set this to the range of days you want to restrict to
			var today = new Date();
	
			if (input.id == "checkfrom")
			{
				if ($("#checkto").datepicker("getDate") != null)
				{
					dateMax = $("#checkto").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 == "checkto")
			{
					
					if ($("#checkfrom").datepicker("getDate") != null)
					{
							dateMin = $("#checkfrom").datepicker("getDate");
							dateMax = new Date(); //Set this to today
							dateMax.setDate(dateMin + 365);
					}
			}
		return {
					minDate: dateMin,
					maxDate: dateMax
				};
	
	}
	
	$('.dt').colorbox({width:"960px", height:"540px", iframe:true});
	
	$('.liveBookingOn').qtip({ style: { name: 'green', tip: true },
								content: '<span style="font-size:16px;">Live bookings accepted</span><br /><span style="font-size:12px;">This property can be reserved instantly. Major credit cards accepted.</span>',
								show: 'mouseover',
								hide: 'mouseout',
								position: {
      								corner: {
									 target: 'bottomMiddle',
									 tooltip: 'topRight'
								  }
							   }
	}) // end liveBookingOn qtip
	
	$('.houseSwapOn').qtip({ style: {
						   		background: '#ded7fc',
								border: {
									 width: 3,
									 color: '#b4a5f6'
							    },
								color: '#5846a8',
								tip: true },
								content: $('#text-hs-icon').html(),
								show: 'mouseover',
								hide: 'mouseout',
								position: {
      								corner: {
									 target: 'bottomMiddle',
									 tooltip: 'topRight'
								  }
							   }
	}) // end liveBookingOn qtip

	

}); // end pageLoaded





//--- Map --------------------------------------------------
//----------------------------------------------------------
$(function(){

	
    // MAP
    map = new GMap2(document.getElementById('map_googlemap'));
	var burnsvilleMN = new GLatLng(currentLat,currentLng);
    map.setCenter(burnsvilleMN, 8);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    var bounds = new GLatLngBounds();
    var geo = new GClientGeocoder();
    var markerArray = new Array();
    var homeMarker,homePoint;
    var directions;
    // Add House Marker
    addHomeMarker(currentLat,currentLng);

    $.getJSON("/maps/get_landmarks.php?pid="+currentPid, function(json) {
            if (json.length > 0) {
                    for (i=0; i<json.length; i++) {
                            var location = json[i];
                            addLocation(location);
                    }
                    zoomToBounds();
            }
    });

    function addHomeMarker(lat,lng) {
        var blueIcon = new GIcon(G_DEFAULT_ICON);
        blueIcon.image = "http://google-maps-icons.googlecode.com/files/home.png";
        markerOptions = { icon:blueIcon };
        homePoint = new GLatLng(lat, lng);
        homeMarker = new GMarker(homePoint, markerOptions);
        markerArray.push(homeMarker);
        map.addOverlay(homeMarker);
    }
    // Zoom
    function zoomToBounds() {
        bounds = new GLatLngBounds();
        for (var i=0; i<markerArray.length ; i++) {
            bounds.extend(markerArray[i].getPoint());
        }
        map.setCenter(bounds.getCenter());
        map.setZoom(map.getBoundsZoomLevel(bounds)-1);
    }
    // Display info
    function showMessage(marker, hloc) {
            var markerOffset = map.fromLatLngToDivPixel(marker.getPoint());
            marker.openInfoWindowHtml('<strong>'+hloc.name+'</strong><br />  <strong>Descrition: </strong>'+hloc.description+'<br /><strong>Distance: </strong>'+hloc.kmdistance+' Km ('+hloc.miledistance+' miles)' );
    }
    // Add location
    addLocation = function(location) {
            var point = new GLatLng(location.lat, location.lng);
            var marker = new GMarker(point);
            // Keep all markers in a array
            markerArray.push(marker);
            // Add marker on map
            map.addOverlay(marker);
            // parse the array to extend bounds and then zoom
            zoomToBounds();

            // Get distance from home
            var miledistance = homePoint.distanceFrom(point, 3959).toFixed(1);
            var kmdistance = (miledistance * 1.609344).toFixed(1);
            location.miledistance = miledistance;
            location.kmdistance = kmdistance;

            // Add li
            $("#list").append('<li id="loc'+location.landmark_id+'" />');
            $('<span />').append(location.name)
                     .click(function(){
                            showMessage(marker, location);
                    }).appendTo('#loc'+location.landmark_id);
            GEvent.addListener(marker, "click", function(){
                    showMessage(this, location);
            });
            $('<span />').append(' '+location.kmdistance+' Km ').appendTo('#loc'+location.landmark_id);
            $('<span />').append('<a href="javascript:getDirections('+location.lat+','+location.lng+');" title="Get directions"><img src="/images/directions-transparentBg.png" width="68px" height="15px;" /></a>').appendTo('#loc'+location.landmark_id);
    }
lastDirLat = '';
lastDirLng = '';
  getDirections = function(lat,lng)
	{
    directionsPanel = $("#directions");
        
        if (lastDirLat == lat && lastDirLng == lng) {
        	directionsPanel.html('');
        	directions.clear();
        	clearDirMarker();
        	
        	// Set default
        	lastDirLat = '';
			lastDirLng = '';
			die();
        } else {
        	// Set var for remembering
        	lastDirLat = lat;
			lastDirLng = lng;
			
			dir = "from: "+currentLat+", "+currentLng+" to: "+lat+", "+lng;
        	
			directionsPanel.html('');
			if(!directions) {
				directions = new GDirections( map , directionsPanel[0] );
				
			} else {
				directions.clear();
			}
	        
			directions.load( dir );
			setTimeout("clearDirMarker()",800);
			dir = '';
		}
	}
	
    clearDirMarker = function()
	{
		if( directions.getMarker(0) ){
			map.removeOverlay( directions.getMarker(0) );
			map.removeOverlay( directions.getMarker(1) );
		}else{
			setTimeout("clearDirMarker()",200);
		}
	}
});





	
	// Comfirm/Error msg
//	lauchCalendar = function (sid) {
//		var divIframe = $('.pcalendar');
//		
//		//divIframe.hide();
//		divIframe.append('<iframe class="iframeSuite'+sid+' autoHeight" frameborder="no" scrolling="no" style="width:100%;height:100%;">');
//		$('.iframeSuite'+sid).attr('src','/calendar.php?sid='+sid);//
//
//		$('.iframeSuite'+sid).load(function() {
//			var ifrheight = $(this).height();
//			
//			var nsize = ifrheight+343;
//			divIframe.css({height:nsize+'px'});
//			
//			$(this).width('100%');
//			 divIframe.show();//

//		})
//	}	