// JavaScript Document

// EDIT THESE VALUES IF REQUIRED
var alertText = 'Are you sure you wish to perform this action' + "\n"; //DEFAULT TEXT DISPLAYED ON CONFIRM BUTTONS/LINKS WHEN NO ALT/TITLE
var newWindowLink = false; //OPEN EXTERNAL LINKS BY DEFAULT IN A NEW WINDOW (TRUE/FALSE)?


var woms = new Array(); //CREATE ARRAY OF FUNCTIONS TO LAUNCH ONLOAD

//ONLOAD MANAGER
function womOn(){
  window.onload = womGo;
}

function womGo(){
  for(var i = 0;i < woms.length;i++)
    eval(woms[i]);
}

function womAdd(func){
  woms[woms.length] = func;
}

//BROWSER HEIGHT (available height allowing for browser toolbars etc.)

 var viewportwidth;
 var viewportheight;

function getBrowserSizes(){
	 
	 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	 
	 if (typeof window.innerWidth != 'undefined')
	 {
		  viewportwidth = window.innerWidth,
		  viewportheight = window.innerHeight
	 }
	 
	// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
	
	 else if (typeof document.documentElement != 'undefined'
		 && typeof document.documentElement.clientWidth !=
		 'undefined' && document.documentElement.clientWidth != 0)
	 {
		   viewportwidth = document.documentElement.clientWidth,
		   viewportheight = document.documentElement.clientHeight
	 }
	 
	 // older versions of IE
	 
	 else
	 {
		   viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		   viewportheight = document.getElementsByTagName('body')[0].clientHeight
	 }
	
	//-->
	
}

function bookmark()
{
	if($('#bookmark').length == 0) return false;
	
	$('#bookmark').css("display","block");

	$("#bookmark").click(function()
	{
		CreateBookmarkLink();
		return false;
	});
}

function printpage()
{
	if($('#printpage').length == 0) return false;
	
	$('#printpage').css("display","block");

	$("#printpage").click(function()
	{
		window.print();
	});
}

function CreateBookmarkLink() 
{

	//title = document.title;
	title = $('#logotext').html();
	url = window.location.href;
	
	if (window.sidebar) 
	{ 
		window.sidebar.addPanel(title, url,"");
	} 
	else if(window.external) 
	{
		window.external.AddFavorite( url, title); 
	} 
	else if(window.opera && window.print) 
	{
		return true;
	}
	
}

function objToggle(obj) { 

	var obj = document.getElementById(obj);

	if(obj.style.display == "block") { 
		obj.style.display = "none";
	} else { 
		obj.style.display = "block";
	}

}


function adminmap()
{
	if($('#adminmap').length == 0) return false; //Check for the map canvas on the page
	
	var map_canvas = document.getElementById('adminmap'); //Get the canvas
	var map = new GMap2(map_canvas); //Create a new map object
	//var point = new GLatLng(54.277691, -2.45404);  
	//map.setCenter(point, 9); //Set the centre point of the maps and the zoom level
	
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	var baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "images/maps/msmarker.shadow.png";
	baseIcon.image = "images/maps/stayin_pin.png";
	baseIcon.iconSize = new GSize(37, 32);
	baseIcon.shadowSize = new GSize(37, 32);
	baseIcon.iconAnchor = new GPoint(13, 31);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	
	var propertyid = $('#propertyid').val();
	var type = $('#type').val();
	
	url = window.location.pathname.split('maintain');
	
	if(url[1] == '/edit.php')
	{
		var path = '../libs/includes/ajax.get_locations.php?propertyid='+propertyid+'&type='+type;
	}
	else
	{
		var path = 'libs/includes/ajax.get_locations.php?propertyid='+propertyid+'&type='+type;
	}
	
	$.ajax({
		type: 'GET',
		url: path,
		success: function(html) {

			eval(html);
			//User the response from AJAX to set the user's location
			//var user_location = cleanCoords(String(html));
			if(locations.length > 0 )
			{
				if(locations[0][0] !='')
				{
					var lat = locations[0][0];
					var long = locations[0][1];
					
					//Get the point of the user's co-ordinates
					var point = new GLatLng(lat, long);
					
					var customIcon = new GIcon(baseIcon);
					customIcon.image = "images/maps/stayin_pin.png";
					
					//Create a new marker for the user
					var marker = new GMarker(point, {draggable: true, bouncy: false, icon:customIcon});
					
					map.setCenter(point, 9); //Set the centre point of the maps and the zoom level
					map.addOverlay(marker); //Add the user's marker to the map
					
					var mgr = new MarkerManager(map, {trackMarkers:true}); //Create a new marker manager
					
					
					dragListener(marker, 'dragend', map, mgr); //Create a listener on the end of a drag for this marker
					
					mgr.addMarker(marker, 1);
					
					var markerContent = locations[0][2]
					
					addMarkerListener(map, marker, markerContent);
	
					mgr.refresh();
					map.setUIToDefault(); //Set the map to look like maps.google.com
					postcodeSearch(map, mgr);
				}
				
			}
			
			
		}
		
	});
}

//Lauch the map
function launchMap()
{
	
	if($('#map').length == 0) return false; //Check for the map canvas on the page

	var map_canvas = document.getElementById('map'); //Get the canvas
	var map = new GMap2(map_canvas); //Create a new map object
	
	var url = String(document.location);
	var spliturl = url.split('/');
	
	var correctcount = spliturl.length - 2;
	var accommodationcount = spliturl.length - 1;
	
	for(i = 0; i < spliturl.length; i++)
	{
		if(i == correctcount)
		{
			var correctsection = spliturl[i];
		}
		
		if(i == accommodationcount)
		{
			var accommodationsection = spliturl[i];
		}
	}
	//alert(correctsection);
	//alert(accommodationsection);
	
	var preview = false;	
	var spliturl = url.split('&');
	for(i = 0; i < spliturl.length; i++)
	{
		//alert(spliturl[i]);
		if(spliturl[i] == 'preview=true')
		{
			preview = true;
		}
		
		var suburl = spliturl[i].split('=');
		if(suburl.length > 0)
		{
			if(suburl[0] == 'section')
			{
				var previewproperty = suburl[1];
			}
		}
		
	}
	
	//Look for a location to add
	$.ajax({
		type: 'GET',
		url: 'libs/includes/ajax.get_locations.php?section='+correctsection+'&page='+accommodationsection+'&preview='+ preview + '&previewproperty='+previewproperty,
		success: function(html) {
			
			//alert('before: '+html);
			
			eval(html);
			
			//alert(locations.length);
			/**
			* do we have any results
			*/
			//alert('after: '+html);
			
			if(locations.length > 0)
			{
				/*for(var i = 0; i <locations.length; i++)
				{
					//User the response from AJAX to set the user's location
					//var user_location = cleanCoords(String(html));
					
					var lat = locations[i][0];
					var long = locations[i][1];
					
					//Get the point of the user's co-ordinates
					var point = new GLatLng(lat, long);
					
					//Create a new marker for the user
					var marker = new GMarker(point, {draggable: false, bouncy: false});
					
					map.setCenter(point, 9); //Set the centre point of the maps and the zoom level
					map.addOverlay(marker); //Add the user's marker to the map
					
					var mgr = new MarkerManager(map, {trackMarkers:true}); //Create a new marker manager
					
					mgr.addMarker(marker, 1);
					var markerContent = locations[i][2]
					
					addMarkerListener(map, marker, markerContent);
					
					mgr.refresh();
					
				}*/
				
				//alert(locations.length);
				
				if(accommodationsection == 'map-view' || preview == true)
				{
					var centre = new GLatLng(54.203232, -2.19684);	
					map.setCenter(centre, 8); //Set the centre point of the maps and the zoom level
				}
				else
				{
					var centre = new GLatLng(56.203232, -5.5000);
					map.setCenter(centre, 7); //Set the centre point of the maps and the zoom level
				}
				
				//alert(point);

				//var point = new GLatLng(56.203232, -5.5000);
				//map.setCenter(centre, 7); //Set the centre point of the maps and the zoom level
				
				var mgr = new MarkerManager(map, {trackMarkers:true}); //Create a new marker manager
				
				/**
				* if we have more than one result then we can cluster it
				* if we only have one result then don't cluster it or it will error
				*/
				if(locations.length > 1)
				{
					mgr.addMarkers(setMarkers(10, locations, map), 4);
					mgr.addMarkers(setMarkers(Math.round((locations.length/4)), locations, map), 5);
					mgr.addMarkers(setMarkers(Math.round((locations.length/2)), locations, map), 10);
					mgr.addMarkers(setMarkers(locations.length, locations, map), 13);
				}
				else
				{
					mgr.addMarkers(setMarkers(locations.length, locations, map), 1);
				}
				
				mgr.refresh();
				
			}
			
			
			
			
			//getLocations(mgr, map, point); //Get and put the markers down on the map
			
			map.setUIToDefault(); //Set the map to look like maps.google.com
			
			//dragListener(marker, 'dragend', map, mgr); //Create a listener on the end of a drag for this marker
			//clickListener(map, 'click'); //Create a listener for clicking on the map
			
			//Postcode search
			//postcodeSearch(map, mgr);
			//distanceUpdate(map, mgr, point);
			
		}
		
	});
	
	//Add controls to the map
	addControls(map);

}

function setMarkers(n, locations, map) {

	if(n > locations.length) {
		n = locations.length;	
	}

	var batch = new Array;
	
	for (var i = 0; i < n; ++i) {

		var lat = locations[i][0];
		var long = locations[i][1];
		
		//Get the point of the user's co-ordinates
		var point = new GLatLng(lat, long);
		
		// Create a base icon for all of our markers that specifies the
		// shadow, icon dimensions, etc.
		var baseIcon = new GIcon(G_DEFAULT_ICON);
		baseIcon.shadow = "images/maps/msmarker.shadow.png";
		baseIcon.iconSize = new GSize(37, 32);
		baseIcon.shadowSize = new GSize(37, 32);
		baseIcon.iconAnchor = new GPoint(13, 31);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		
		var customIcon = new GIcon(baseIcon);
		customIcon.image = "images/maps/stayin_pin.png";
		
		//Create a new marker for the user
		var marker = new GMarker(point, {draggable: false, bouncy: false, icon:customIcon});
		
		//map.setCenter(point, 9); //Set the centre point of the maps and the zoom level
		//map.addOverlay(marker); //Add the user's marker to the map
		
		//var mgr = new MarkerManager(map, {trackMarkers:true}); //Create a new marker manager
		//mgr.addMarker(marker, 1);
		var markerContent = locations[i][2]
		
		addMarkerListener(map, marker, markerContent);
		
		batch.push(marker);
		
	}
	
	return batch;

}

function distanceUpdate(map, mgr, point) {
	
	$('#distance').submit(function() {
								   
		
		mgr.clearMarkers(); //Remove the markers from the map
		mgr.refresh();
		
		var marker = new GMarker(point, {draggable: true, bouncy: false}); //Create a new marker
		map.addOverlay(marker); //Add the user's marker to the map
		mgr.addMarker(marker, 1); //Add the marker to the manager
		
		mgr.refresh();
		
		getLocations(mgr, map, point); //Get new locations
		dragListener(marker, 'dragend', map, mgr); //Create a listener on the end of a drag for this marker
		
		return false;
	
	});
	
}

//Listens out for the user searching for a postcode
function postcodeSearchsignup() 
{
	
	if($('#signupfromintro').length == 0) return false; //Check for the map canvas on the page
	
	var location_form = document.getElementById('signupfromintro'); //Set the form variable
	
	location_form.onsubmit = function() 
	{
	
		var locationSearch = new GlocalSearch(); //Initialise the class
	
			locationSearch.setSearchCompleteCallback(null,
																	  
				function() 
				{
					//alert(locationSearch.results.length);
					//Are there results to show
					if (locationSearch.results.length > 0) 
					{ 
						var latitude = locationSearch.results[0].lat; //Get tha latitude
						var longitude = locationSearch.results[0].lng; //Get the longitude
						
						//dont ask but keep them like this!
						$('#lat').val(longitude);
						$('#long').val(latitude);
									
					} 
					else 
					{ 
					
					//No results found for this postcode
						
						//$('#new_search').prepend('<p class="error">Sorry but we couldn\'t find your postcode</p>');
					
					}
				
				}); 
			
			//alert($('#propertypostcode').val());
			
			//Do the search for the postcode
			locationSearch.execute($('#propertypostcode').val() + ", UK");
			
			setTimeout(function()
			{ 
				$('#signupfromintro').submit(); 
			
			}, 1500);
			
			
			return false;
	}
}


//Listens out for the user searching for a postcode
function postcodeSearch(map, mgr) {
	
	$('#findpostcode').click(function() { //Form submitted
		
		mgr.clearMarkers(); //Remove the markers from the map
		mgr.refresh();
	
		var locationSearch = new GlocalSearch(); //Initialise the class

		locationSearch.setSearchCompleteCallback(null,
																  
			function() {
		
				//Are there results to show
				if (locationSearch.results.length > 0) { 
				
					mgr.clearMarkers();
				
					var latitude = locationSearch.results[0].lat; //Get tha latitude
					var longitude = locationSearch.results[0].lng; //Get the longitude

					var point = new GLatLng(latitude,longitude); //Find the point the postcode
					
					//Update the users location so we can show them later
					var propertyid = $('#propertyid').val();
					var type = $('#type').val();
					
					url = window.location.pathname.split('maintain');
		
					if(url[1] == '/edit.php')
					{
						var path = '../libs/includes/ajax.update_long_lat.php?latitude=' + longitude + '&longitude=' + latitude + '&propertyid='+propertyid+'&type='+type;
					}
					else
					{
						var path = 'libs/includes/ajax.update_long_lat.php?latitude=' + longitude + '&longitude=' + latitude + '&propertyid='+propertyid+'&type='+type;
					}
					
					
					$.ajax({
						type: 'GET',
						url: path,
						success: function(html) {
						}
					
					});
					
					var marker = new GMarker(point, {draggable: true, bouncy: false}); //Create a new marker
					map.setCenter(point, 11); //Set the centre point of the maps
					map.addOverlay(marker); //Add the user's marker to the map
					mgr.addMarker(marker, 1); //Add the marker to the manager
					map.panTo(point, 1000);
					mgr.refresh();
					
					dragListener(marker, 'dragend', map, mgr); //Create a listener on the end of a drag for this marker
			
				} else { //No results found for this postcode
					
					$('#new_search').prepend('<p class="error">Sorry but we couldn\'t find your postcode</p>');
				
				}
			
		}); 
		
		//Do the search for the postcode
		locationSearch.execute($('#zip').val() + ", UK");
		
		return false;
		
	});
	
}

//Listen out for the user clicking the map
//map: The map object
//mapEvent: String 'click' in this case
function clickListener(map, mapEvent) {

	//Create an object that listens out for a click on the map
	GEvent.addListener(map, mapEvent, function(overlay, latlng) {
		
		var points = cleanCoords(String(latlng)); //Clean the co-ordinates
		
		//Do some ajax when the user has clicked on the map
		$.ajax({
			type: 'GET',
			url: 'libs/includes/ajax.create_location.php?latitude=' + points[0] + '&longitude=' + points[1],
			success: function(html) {
				
				var point = new GLatLng(points[0], points[1]); //Get the point from the location of the click
				var marker = new GMarker(point, {draggable: false}); //Create a new marker
				map.addOverlay(marker); //Add the user's marker to the map
				
			}
		});
		
	});

}

//Function to attach listeners to a marker
function dragListener(marker, mapEvent, map, mgr) {
	
	//Create an object that listens out for a drag on the marker
	GEvent.addListener(marker, mapEvent, function() {

		var new_point = cleanCoords(String(marker.getLatLng())); //Get the new point and clean up the co-ordinates
		var propertyid = $('#propertyid').val();
		var type = $('#type').val();
		//Update the users location so we can show them later
		
		url = window.location.pathname.split('maintain');
		
		if(url[1] == '/edit.php')
		{
			var path = '../libs/includes/ajax.update_long_lat.php?latitude=' + new_point[1] + '&longitude=' + new_point[0] + '&propertyid='+propertyid+'&type='+type;
		}
		else
		{
			var path = 'libs/includes/ajax.update_long_lat.php?latitude=' + new_point[1] + '&longitude=' + new_point[0] + '&propertyid='+propertyid+'&type='+type;
		}
		
		$.ajax({
			type: 'GET',
			url: path,
			success: function(html) {
				
				mgr.clearMarkers(); //Remove the markers from the map
				mgr.refresh();
				
				var point = new GLatLng(new_point[0], new_point[1]); //Get the new location of the marker
				map.panTo(point); //Move the map so it centres over the new centre point
				
				var marker = new GMarker(point, {draggable: true, bouncy: false}); //Create a new marker
				map.addOverlay(marker); //Put the new marker down on the map
				dragListener(marker, 'dragend', map, mgr); //Create a listener on the end of a drag for this marker
				mgr.addMarker(marker, 1); //Add the new point of the users location to the manager
				mgr.refresh();
				
			}
		
		});
	
	});

}

//Function to attach listeners to a marker
function addMarkerListener(map, marker, markerContent) {

	GEvent.addListener(marker, 'click', function() { //Listen out for a click on an info window
												 
		map.openInfoWindowHtml(marker.getLatLng(), markerContent); //Display the markers information
		
	});

}

//Removes the open and close brackets and splits the string on comma
function cleanCoords(point) {

	if(point != '') { //Has a point been passed through

		var dirty_points = point.split(','); //Split the string in 2
		var clean_lat    = dirty_points[0].substring(1, dirty_points[0].length); //Remove open bracket at the start of the string
		var clean_long   = dirty_points[1].substring(1, (dirty_points[1].length-1)); //Remove the space from the start and close bracket at the end of the string
		
		var clean_point = new Array(); //Create an array to store the new points in
		clean_point [0]= clean_lat; //Set latitude
		clean_point [1]= clean_long; //Set longitude
		
		return clean_point; //Return the array of clean co-ordinates
	
	} else {
	
		alert(point);
	
	}

}

//Get the locations we need to show
function getLocations(mgr, map, point) {
	
	var user_location = cleanCoords(String(point)); //Use the maps centre point to get the start lat and long
	
	//Update the users location so we can show them later
	$.ajax({
		type: 'GET',
		url: 'libs/includes/ajax.get_locations.php?&start_latitude=' + user_location[0] + '&start_longitude=' + user_location[1] + '&distance=' + $('#within').val(),
		success: function(html) {
		
			//html is the result which is echoed out on libs/includes/ajax.get_locations.php
			eval(html); //Turn the HTML returned from the AJAX url in to a javascript array
			
			var markers = new Array;
			
			for(var i=0; i<locations.length; i++) { //Loop through the locations
				
				centreIcon = new GIcon(baseIcon); //Use the base icon information and add custom marker stuff
				
				var icon = ''; //Set which icon should be displayed
				
				//Check the type of the location and select the appropriate marker
				if(locations[i][3] == 'dead') {
				
					icon = 'orange-dot.png';	
				
				} else if(locations[i][3] == 'sick') {
					
					icon = 'green-dot.png';
					
				} else {
					
					icon = 'blue-dot.png';
					
				}
				
				centreIcon.image = 'http://www.google.com/intl/en_us/mapfiles/ms/micons/' + icon;
				var markerOptions = { icon:centreIcon }; //Set the marker's options
				
				var point = new GLatLng(locations[i][0], locations[i][1]); //Get the point of the marker
				var marker = new GMarker(point, markerOptions); //Create the new marker
				
				var markerContent = locations[i][4]; //Set the message for the info window
				
				addMarkerListener(map, marker, markerContent); //Add a listener to the marker for more information
				
				mgr.addMarker(marker, 11); //Add the marker to the marker manager
			
			}
			
			mgr.refresh(); //Refresh the marker manager to display the new markers just created
		
		}
	
	});
	
}

//Add Controls to the map
function addControls(map) {

	map.addControl(new GLargeMapControl3D()); // zoom controls
	map.addControl(new GScaleControl()); // zoom controls

}

$(document).ready(function(){

	launchMap();
	
	/**
	* homepage tabs and maybe others
	*/
	homepagetab();
	
	/**
	* left hand tabs
	*/
	lefttabs();
	
	/**
	* second tabs
	*/
	
	secondtab();
	
	/**
	* crop images
	*/
	crop();
	
	/**
	* show more on search
	*/
	
	showmore();
	
	/**
	* gallery
	*/
	
	gallery();
	
	/**
	* admin map
	*/
	 
	adminmap();
	
	/**
	* homepage lightwindow
	*/
	
	homepagelightwindow();
	
	/**
	* date picker on the rates page
	*/
	
	datepicker();
	
	/**
	* geo code the sign up form
	*/
	
	postcodeSearchsignup();
	
	/**
	* featured property tracking
	*/
	
	featuredproperty();
	
	/**
	* spotlight tracking
	*/
	
	spotlight();
	
	/**
	* featured partner
	*/
	
	featuredpartner();
	
	/**
	* recommended homepage
	*/
	
	recommendedhome();
	
	/**
	* location
	*/
	
	recommendedlocation();
	
	/**
	* bookmark
	*/
	
	bookmark();
	
	
	/**
	* printpage
	*/
	
	printpage();
	
	
	/**
	* featured partner
	*/
	
	leftfeaturedpartners()
	
	/**
	* expand text
	*/
	
	expandabletext();
	
	
	/**
	* confirmation on delete email button
	*/
	
	confirmdelete();
	
	
	/**
	* advanced search
	*/
	advancedsearch();
	
	villagesearch();
	
	townsearch();
	
	regionsearch();
	
	specialitysearch();
	
	accommodationsearch();
	
	/**
	* auto submit
	*/
	
	advancedsearchsubmit();
	
	sleepsupto();
	
	
	/**
	* map view
	*/
	
	mapviewtab();
	
	/**
	* if we are on the search page the we need to submit the form automatically
	*/
	refinesearchsubmit();
	
	/**
	* limit textbox
	*/
	limittextarea();
	limitcaption();
	
	
	/**
	* scrolling photo
	*/
	photoscroll();
	displaylargeimage();
	
	/**
	* website tracking
	*/
	websitereferrals();
	touristwebsitereferrals();
	
	/**
	* number of calendars
	*/
	getnumcalendars();
});


function getnumcalendars()
{
	
	if($('#numcalendar').length == 0) return false;
	
	
	
	$('#numbercalendars').change(function () 
	{
		//alert($('#numbercalendars').val());	
		$("#numcalendar").html($('#numbercalendars').val()); 
	})

	
}


function refinesearchsubmit()
{
	
	if($('#results_per_page').length == 0) return false;
	
	$('#results_per_page').change(function () 
	{
		$("#sortbyform").submit();
	})
	
	$('#filter').change(function () 
	{
		$("#sortbyform").submit();
	})
	
}


function mapviewtab()
{
	
	url = String(window.location);
	
	spliturl = url.split('/'); 
	
	if(spliturl[spliturl.length-1] == 'map-view')
	{
		$('#tabs').tabs('option', 'selected', 1);
	}
}

function sleepsupto()
{
	if($('#sleeps_up_to').length == 0) return false;

	$('#sleeps_up_to').change(function () 
	{
		$("#adsearchform").submit();
	})


}

function advancedsearchsubmit()
{
	
	if($('#adsearchform').length == 0) return false;

	$(".adsearch").each(function()
	{  
		$(this).click(function()
		{
			$("#adsearchform").submit();
		});
	});

	
}

function accommodationsearch()
{   
	
	if($('#accommodationtitle').length == 0) return false;
	
	var a = $('#accommodationtitle').addClass("btn-slidefive");
	
	
	$(".btn-slidefive").click(function()
	{
		if ($("#accommodationwrapper").is(":hidden")) 
		{
			$("#accommodationwrapper").slideDown("slow");
			$(this).addClass("activefive");
			$.cookie('showTopfive', 'collapsed');
			
			$('#accommodationtitle').removeClass("down");
			
			return false;
		} 
		else 
		{
			$("#accommodationwrapper").slideUp("slow");
			$(this).removeClass("activefive");
			$.cookie('showTopfive', 'expanded');
			
			$('#accommodationtitle').addClass("down");
			
			return false;
		}
	});
	
	// COOKIES
	// Header State
	var showTopfive = $.cookie('showTopfive');
	
	// Set the user's selection for the Header State
	if (showTopfive == 'collapsed') 
	{
		$("#accommodationwrapper").show();
		$(".btn-slidefive").addClass("activefive");
		$('#accommodationtitle').removeClass("down");
	}
	else
	{
		if(showTopfive == null )
		{
			$("#accommodationwrapper").show();
			$(".btn-slidefive").addClass("activefive");
			$('#accommodationtitle').removeClass("down");
		}
		else
		{
			$("#accommodationwrapper").hide();
			$('#accommodationtitle').addClass("down");
		}
	};
 
}

function specialitysearch()
{   
	
	if($('#specialitytitle').length == 0) return false;
	
	var a = $('#specialitytitle').addClass("btn-slidefour");
	
	$("#specialitywrapper").hide();
	
	$(".btn-slidefour").click(function()
	{
		if ($("#specialitywrapper").is(":hidden")) 
		{
			$("#specialitywrapper").slideDown("slow");
			$(this).addClass("activefour");
			$.cookie('showTopfour', 'collapsed');
			
			$('#specialitytitle').removeClass("down");
			
			return false;
		} 
		else 
		{
			$("#specialitywrapper").slideUp("slow");
			$(this).removeClass("activefour");
			$.cookie('showTopfour', 'expanded');
			
			$('#specialitytitle').addClass("down");
			
			return false;
		}
	});
	
	// COOKIES
	// Header State
	var showTopfour = $.cookie('showTopfour');
	// Set the user's selection for the Header State
	if (showTopfour == 'collapsed') 
	{
		$("#specialitywrapper").show();
		$(".btn-slidefour").addClass("activefour");
		$('#specialitytitle').removeClass("down");
	}
	else
	{
		if(showTopfour == null )
		{
			$("#specialitywrapper").show();
			$(".btn-slidefour").addClass("activefour");
			$('#specialitytitle').removeClass("down");
		}
		else
		{
			$("#specialitywrapper").hide();
			$('#specialitytitle').addClass("down");
		}
	};
 
}


function regionsearch()
{   
	
	if($('#regiontitle').length == 0) return false;
	
	var a = $('#regiontitle').addClass("btn-slidethree");
	
	$("#regionwrapper").hide();
	
	$(".btn-slidethree").click(function()
	{
		if ($("#regionwrapper").is(":hidden")) 
		{
			$("#regionwrapper").slideDown("slow");
			$(this).addClass("activethree");
			$.cookie('showTopthree', 'collapsed');
			
			$('#regiontitle').removeClass("down");
			
			return false;
		} 
		else 
		{
			$("#regionwrapper").slideUp("slow");
			$(this).removeClass("activethree");
			$.cookie('showTopthree', 'expanded');
			
			$('#regiontitle').addClass("down");
			
			return false;
		}
	});
	
	// COOKIES
	// Header State
	var showTopthree = $.cookie('showTopthree');
	// Set the user's selection for the Header State
	
	if (showTopthree == 'collapsed') 
	{
		$("#regionwrapper").show();
		$(".btn-slidethree").addClass("activethree");
		$('#regiontitle').removeClass("down");
	}
	else
	{
		if(showTopthree == null )
		{
			$("#regionwrapper").show();
			$(".btn-slidethree").addClass("activethree");
			$('#regiontitle').removeClass("down");
		}
		else
		{
			$("#regionwrapper").hide();
			$('#regiontitle').addClass("down");
		}
	};
 
}

function townsearch()
{   
	
	if($('#towntitle').length == 0) return false;
	
	var a = $('#towntitle').addClass("btn-slidetwo");
	
	$("#townwrapper").hide();
	
	$(".btn-slidetwo").click(function()
	{
		if ($("#townwrapper").is(":hidden")) 
		{
			$("#townwrapper").slideDown("slow");
			$(this).addClass("activetwo");
			$.cookie('showToptwo', 'collapsed');
			
			$('#towntitle').removeClass("down");
			
			return false;
		} 
		else 
		{
			$("#townwrapper").slideUp("slow");
			$(this).removeClass("activetwo");
			$.cookie('showToptwo', 'expanded');
			
			$('#towntitle').addClass("down");
			
			return false;
		}
	});
	
	// COOKIES
	// Header State
	var showToptwo = $.cookie('showToptwo');
	// Set the user's selection for the Header State
	if (showToptwo == 'collapsed') 
	{
		$("#townwrapper").show();
		$(".btn-slidetwo").addClass("activetwo");
		$('#towntitle').removeClass("down");
	}
	else
	{
		if(showToptwo == null )
		{
			$("#townwrapper").show();
			$(".btn-slidetwo").addClass("activetwo");
			$('#towntitle').removeClass("down");
		}
		else
		{
			$("#townwrapper").hide();
			$('#towntitle').addClass("down");
		}
	};
 
}

function villagesearch()
{   
	
	if($('#villagetitle').length == 0) return false;
	
	var a = $('#villagetitle').addClass("btn-slideone");
	
	$("#villagewrapper").hide();
	
	$(".btn-slideone").click(function()
	{
		if ($("#villagewrapper").is(":hidden")) 
		{
			$("#villagewrapper").slideDown("slow");
			$(this).addClass("activeone");
			$.cookie('showTopone', 'collapsed');
			
			$('#villagetitle').removeClass("down");
			
			return false;
		} 
		else 
		{
			$("#villagewrapper").slideUp("slow");
			$(this).removeClass("activeone");
			$.cookie('showTopone', 'expanded');
			
			$('#villagetitle').addClass("down");
			
			return false;
		}
	});
	
	// COOKIES
	// Header State
	var showTopone = $.cookie('showTopone');
	// Set the user's selection for the Header State
	
	if (showTopone == 'collapsed') 
	{
		$("#villagewrapper").show();
		$(".btn-slideone").addClass("activeone");
		$('#villagetitle').removeClass("down");
	}
	else
	{
		if(showTopone == null )
		{
			$("#villagewrapper").show();
			$(".btn-slideone").addClass("activeone");
			$('#villagetitle').removeClass("down");
		}
		else
		{
			$("#villagewrapper").hide();
			$('#villagetitle').addClass("down");
		}
	};
 
}

function advancedsearch()
{   
	
	if($('#optionwarpper').length == 0) return false;
	
	/*
	var showTop = $.cookie('showTop');
	
	
	if(showTop !='')
	{
		if($('#expandsearch').length == 0)
		{
			$("#optionwarpper").hide();
			$.cookie('showTop', 'expanded');
		}
		else
		{
			$("#optionwarpper").show();
			$.cookie('showTop', 'collapsed');
		}
	}
	*/
	
	$("#optionwarpper").hide();
	
	var a = $('#moreoptions').addClass("btn-slide");
	
	
	$(".btn-slide").click(function()
	{
		if ($("#optionwarpper").is(":hidden")) 
		{
			$("#optionwarpper").slideDown("slow");
			$(this).addClass("active");
			$.cookie('showTop', 'collapsed');
			
			//$('#moreoptions').removeClass("down");
			//moreoptions
			$('#moreoptions').attr("src", 'images/bk-more-options.gif');
			
			return false;
		} 
		else 
		{
			$("#optionwarpper").slideUp("slow");
			$(this).removeClass("active");
			$.cookie('showTop', 'expanded');
			
			//$('#moreoptions').addClass("down");
			$('#moreoptions').attr("src", 'images/bk-more-options-up.gif');
			
			return false;
		}
	});
	
	// COOKIES
	// Header State
	var showTop = $.cookie('showTop');
	// Set the user's selection for the Header State
	
	if (showTop == 'collapsed') 
	{
		$("#optionwarpper").show();
		$(".btn-slide").addClass("activeone");
		$('#moreoptions').attr("src", 'images/bk-more-options.gif');
	}
	else
	{
		if(showTop == null )
		{
			$("#optionwarpper").show();
			$(".btn-slide").addClass("activeone");
			$('#moreoptions').attr("src", 'images/bk-more-options.gif');
		}
		else
		{
			$("#optionwarpper").hide();
			$('#moreoptions').attr("src", 'images/bk-more-options-up.gif');
		}
	};
	
 
}



function confirmdelete()
{
	if($('.deleteemail').length == 0) return false;
	
	$('.deleteemail').click(function(){

		var confirmdelete = confirm("Are you sure you want to delele this enquiry?")
		if(confirmdelete)
		{
			return true;
		}
		else
		{
			return false;
		}

	});							
			
}

/**
* expand or contract the text
*/
function expandabletext()
{
	if($('.expandable').length == 0) return false;

	$('.expandable').toggle();
	
	$('.expand').click(function(){
								
		var elements = $(this).attr('id').split('_');
		var id = elements[1];
		
		$('#span_'+id).toggle();
		
		if($(this).html() == 'Expand') {
			
			$(this).html('Collaspe');
			
		} else {
			
				$(this).html('Expand');
			
		}
		
		return false;							
		
	});
		
}

function datepicker()
{
	if($('.dateinput').length == 0) return false;
	$('.dateinput').datepicker({	showButtonPanel: true });
}

/*
var baseIcon = new GIcon();
baseIcon.shadow = "http://www.google.com/intl/en_us/mapfiles/ms/micons/msmarker.shadow.png";
baseIcon.iconSize = new GSize(32, 32);
baseIcon.shadowSize = new GSize(59, 32);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
*/


function homepagelightwindow()
{
	if($('.enlargeImage').length == 0) return false;
	$('a.enlargeImage').lightBox();
	
}

function lefttabs()
{
	if($('#spotLightsInner').length == 0) return false;
	var $tabs = $('#spotLightsInner').tabs();
	/**
	* make sure we only show the first tab as default
	*/
	var selected = $tabs.tabs('select', 0);
}

function secondtab()
{
	if($('#secondtab').length == 0) return false;
	$("#secondtab").tabs();
}

function homepagetab()
{
	if($('#tabs').length == 0) return false;
	$("#tabs").tabs();
	
}

function crop()
{
	/**
	* http://deepliquid.com/content/Jcrop_Manual.html
	*/
	
	if($('#cropbox').length == 0) return false;
	

	jQuery('#cropbox').Jcrop({
            aspectRatio: 7/5,
			/*minSize: [288,212],
			maxSize: [288,212],*/
			onSelect: updateCoords
        });

	
}

function updateCoords(c)
{
	$('#x').val(c.x);
	$('#y').val(c.y);
	$('#w').val(c.w);
	$('#h').val(c.h);
};

function checkCoords()
{
	if (parseInt($('#w').val())) return true;
	alert('Please select a crop region then press submit.');
	return false;
};


function showmore()
{
	if($(".showmore").length == 0) return false;
	
	$(".showmore").click(function (){
	
		var elementlist = $(this).siblings(); //Get the ul next to the link just clicked
		
		elementlist.each(function() { //Loop through the ul
		
			var lis = $(this).children(); //Get the list elements within the ul
			
			lis.each(function() { //Loop through the list elements
							  
				if($(this).is(':hidden') && $(this).attr('class') == 'noshow') { //Check to see if the element is already hidden
				
					$(this).css('display', 'block');
					//$(this).slideDown();
				
				} else if($(this).attr('class') == 'noshow') {
				
					$(this).css('display', 'none');
					//$(this).slideUp();
				
				}
				
		  	});
		 
		});
		
		var text = $(this).text();
		
		if(text == 'Choose more...') {
			
			$(this).text('Show less...');
			
		} else {
		
			$(this).text('Choose more...');
		
		}
		
		return false;
		
	});
	
}


	/**
	* http://pikachoose.com/versions/
	*/
	
	function gallery()
	{
		if($("#photogallery").length == 0) return false;
		
		$("#photogallery").PikaChoose({show_prev_next:false});

	}

/**
* tracking
*/

function leftfeaturedpartners()
{
	if($(".featpartn").length == 0) return false;
	$(".featpartn").click(function()
	{
	
		var id = $(this).attr('id');
	
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.trackingpartner.php?id='+id,
				success: function(html) {}
			
			});
	
	});
}

/**
* tracking
*/

function featuredproperty()
{
	if($(".featuredproperty").length == 0) return false;
	
	$(".featuredproperty").click(function()
	{
	
		var id = $(this).attr('id');
	
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.tracking.php?id='+id,
				success: function(html) {}
			
			});
	
	});
}

function spotlight()
{
	if($(".spotlight").length == 0) return false;
	
	$(".spotlight").click(function()
	{
	
		var id = $(this).attr('id');
	
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.tracking.php?id='+id,
				success: function(html) {}
			
			});
	
	});
}

function featuredpartner()
{
	if($(".featuredpartner").length == 0) return false;
	
	$(".featuredpartner").click(function()
	{
		var id = $(this).attr('id');
		
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.tracking.php?id='+id,
				success: function(html) {}
			
			});
	
	});
}

function recommendedhome()
{
	if($(".recommendedhome").length == 0) return false;
	
	$(".recommendedhome").click(function()
	{
		var id = $(this).attr('id');
		
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.tracking.php?id='+id,
				success: function(html) {}
			
			});
	
	});
}

function recommendedlocation()
{
	
	
	if($(".location").length == 0) return false;

	$(".location").click(function()
	{
		var id = $(this).attr('id');
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.tracking.php?id='+id,
				success: function(html) {}
			
			});
	
	});
}


function websitereferrals()
{
	
	if($(".viewwebsite").length == 0) return false;

	$(".viewwebsite").click(function()
	{
		var id = $(this).attr('id');
		
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.websitereferral.php?id='+id+'&area=accom',
				success: function(html) {}
			
			});
	
	});
}


function touristwebsitereferrals()
{
	
	if($(".tviewwebsite").length == 0) return false;

	$(".tviewwebsite").click(function()
	{
		var id = $(this).attr('id');
		
		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.websitereferral.php?id='+id+'&area=tourist',
				success: function(html) {}
			
			});
	
	});
}

/**
* end tracking
*/


/**
* limit textarea
*/


function limittextarea()
{
	if($("#limittext").length == 0) return false;
	
	$('#limittext').maxlength({
		'feedback' : '.charsLeft',
		'hardLimit' : 'true',
		'words' : 'true' 
	});
}

function limitcaption()
{
	if($(".caption").length == 0) return false;
	
	$('.caption').maxlength({
		'feedback' : '.charsLeft',
		'hardLimit' : 'true',
		'words' : 'true' 
	});
}




$.fn.maxlength = function (settings) {

    if (typeof settings == 'string') {
        settings = { feedback : settings };
    }

    settings = $.extend({}, $.fn.maxlength.defaults, settings);

    function length(el) {
    	var parts = el.value;
    	if ( settings.words )
    		parts = el.value.length ? parts.split(/\s+/) : { length : 0 };
    	return parts.length;
    }
    
    return this.each(function () {
        var field = this,
        	$field = $(field),
        	$form = $(field.form),
        	limit = settings.useInput ? $form.find('input[name=maxlength]').val() : $field.attr('maxlength'),
        	$charsLeft = $form.find(settings.feedback);

    	function limitCheck(event) {
        	var len = length(this),
        	    exceeded = len >= limit,
        		code = event.keyCode;

        	if ( !exceeded )
        		return;

            switch (code) {
                case 8:  // allow delete
                case 9:
                case 17:
                case 36: // and cursor keys
                case 35:
                case 37: 
                case 38:
                case 39:
                case 40:
                case 46:
                case 65:
                    return;

                default:
                    return settings.words && code != 32 && code != 13 && len == limit;
            }
        }


        var updateCount = function () {
            var len = length(field),
            	diff = limit - len;

            $charsLeft.html( diff || "0" );

            // truncation code
            if (settings.hardLimit && diff < 0) {
            	field.value = settings.words ? 
            	    // split by white space, capturing it in the result, then glue them back
            		field.value.split(/(\s+)/, (limit*2)-1).join('') :
            		field.value.substr(0, limit);

                updateCount();
            }
        };

        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
            $field.keydown(limitCheck);
        }

        updateCount();
    });
};

$.fn.maxlength.defaults = {
    useInput : false,
    hardLimit : true,
    feedback : '.charsLeft',
    words : false
};


function displaylargeimage()
{
	if($("#newPhotoNav").length == 0) return false;
	
	var elementlist = $("#newPhotoNav").children().children().children('img'); 
		
		elementlist.each(function() 
		{
			
			$(this).click(function()
		    {
				var src = $(this).attr('src');
				var alt = $(this).attr('alt');
				var sourcebits = src.split('/');
				var filename = sourcebits[(sourcebits.length-1)];
				
				
				elementlist.each(function() 
				{
					$(this).removeClass("selected");
					$(this).addClass("notselected");
				});
				
				$(this).removeClass("notselected");
				$(this).addClass("selected");

				
				var path = 'uploads/images/properties/orginal/' + filename;
				$('#largeimg').attr('alt', alt);
				$('#largeimg').attr('src', path);
				$('#largeimgcaption').text(alt);
				
				return false;
				
		    });
			
		}

	);
}



function photoscroll()
{
	
	if($("#newPhotoNav").length == 0) return false;

	
	
	
	// id of the container element 
	var id = "newPhotoNav";
	
	// navigation buttons text
	var nav = ["", "", "Reset"];
	
	//	id for each navigation button (OPTIONAL)
	// Determine how many photos in set - if less than 4, lose the scroll arrows
	var elementlist = $("#newPhotoNav").children().children().children('img'); 
	var navId = ["btnUp", "btnDown", "btnReset"];
	if (elementlist.length<4) {
		navId = ["btndddUp", "ddbtnDown", "btnReset"];
	}
	


	// movement speed
	var speed = 5;
	
	// desired height of the container element (in pixels)
	var height = 280;
	
	//
	// END CONFIG
	// do not edit below this line (unless you want to of course :) )
	//

	var obj = document.getElementById(id);
	
	obj.up = false;
	obj.down = false;
	obj.fast = false;

	var container = document.createElement("div");
	var parent = obj.parentNode;
	container.id="easyscroll";
	parent.insertBefore(container,obj);
	parent.removeChild(obj);	
	
	container.style.position = "relative";
	container.style.height = height + "px";
	container.style.overflow = "hidden";
	obj.style.position = "absolute";
	obj.style.top = "0";
	obj.style.left = "0";
	container.appendChild(obj);
	
	var btns = new Array();
	var ul = document.createElement("ul");
	ul.id="easyscrollnav";
	for (var i=0;i<nav.length;i++){
		var li = document.createElement("li");
		li.innerHTML = nav[i];
		li.id = navId[i];
		btns.push(li);
		ul.appendChild(li);
	};
	parent.insertBefore(ul,container);
	
	btns[0].onmouseover = function(){
		obj.up = true;
		this.className = "over";
	};
	btns[0].onmouseout = function(){
		obj.up = false;
		this.className = "";
	};		
	btns[1].onmouseover = function(){
		obj.down = true;
		this.className = "over";		
	};
	btns[1].onmouseout = function(){
		obj.down = false;
		this.className = "";
	};		
	btns[0].onmousedown = btns[1].onmousedown = function(){
		obj.fast = true;
	};	
	btns[0].onmouseup = btns[1].onmouseup = function(){
		obj.fast = false;
	};		
	btns[2].onmouseover = function(){ 		
		this.className = "over";
	};	
	btns[2].onmouseout = function(){ 		
		this.className = "";
	};		
	btns[2].onclick = function(){ 		
		obj.style.top = "0px";
	};		
		
	this.start = function(){				
		var newTop;
		var objHeight = obj.offsetHeight;
		var top = obj.offsetTop;
		var fast = (obj.fast) ? 2 : 1;
		if(obj.down){		 
			newTop = ((objHeight+top) > height) ? top-(speed*fast) : top;	
			obj.style.top = newTop + "px";
		};	
		if(obj.up){		 
			//alert("up");
			newTop = (top < 0) ? top+(speed*fast) : top;
			obj.style.top = newTop + "px";
		};
	};	
	obj.interval = setInterval("start()",50);		
		
};





