// 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 = true; //OPEN EXTERNAL LINKS BY DEFAULT IN A NEW WINDOW (TRUE/FALSE)?


var woms = new Array(); //CREATE ARRAY OF FUNCTIONS TO LAUNCH ONLOAD

function imageclicky()
{

	var back_img = $('.pika_back_img');
	var main_img = $('.pika_main_img');

	if($('.pika_main_img').length == 0) alert('no image');

	//var image_source = $('.pika_first').attr('src');

	var image_source = $("#photogallery li:first .thumbs").attr('src');

	main_img.attr("src",image_source.replace('thumbs','large'));
	//main_link.attr("href", image_link);

}//end image_click function


function checktitle()
{
	var site = '';
	var title = '';


	if($('#site').val() == '' || $('#site').val() == null)
	{
		var site = 'Please select a site' + "\n";
	}

	if( $('#title').val() == '' )
	{
		var title = 'Please enter a title/name for the advert' + "\n";
	}

	if(site !='' || title !='')
	{
		alert(site+''+title);
		return false;
	}


}


function checksite()
{
	var site = '';


	if($('#site').val() == '' || $('#site').val() == null)
	{
		var site = 'Please select a site' + "\n";
	}

	if(site !='')
	{
		alert(site);
		return false;
	}


}


//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();
	});
}

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.chrome) {
    alert('Press ctrl+D to bookmark (Command+D for macs) after you click Ok');
	}	else if (window.sidebar)	{
		window.sidebar.addPanel(title, url,"");
	}	else if (window.external)	{
		window.external.AddFavorite( url, title);
	}	else if (window.opera && window.print) 	{
		window.external.AddFavorite(url, name);
	} else {
    alert("Sorry! Your browser doesn't appear to support this function.");
  }

}

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);

						url = window.location.pathname.split('maintain');
						if(url[1] == '/edit.php')
						{
							customIcon.image = "../images/maps/stayin_pin.png";
						}
						else
						{
							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);


						/*document.body.style.zoom = 2;
						document.body.style.zoom = 0;
						GUnload();*/

					}

				}


			}

		});




}

//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 - 3;
	var accommodationcount = spliturl.length - 2;

	for(i = 0; i < spliturl.length; i++)
	{
		if(i == correctcount)
		{
			var correctsection = spliturl[i];
		}

		if(i == accommodationcount)
		{
			var accommodationsection = spliturl[i];
		}
	}

	var leveltwopage = spliturl[spliturl.length - 4];
	//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];
			}
		}

	}



	//var page = document.getElementById('page').value;
	var page =  $('#mapform #page').val()

	if($('#id').length > 0)
	{
		var propertyid = document.getElementById('id').value;
	}
	else
	{
		var propertyid = '';
	}


	if($('#pagetype').length > 0)
	{
		var pagetype = document.getElementById('pagetype').value;
	}
	else
	{
		var pagetype = '';
	}

	if($('#number').length > 0)
	{
		var pagenumber = document.getElementById('number').value;
	}
	else
	{
		var pagenumber = '';
	}

	//Look for a location to add
	$.ajax({
		type: 'GET',
		url: 'libs/includes/ajax.get_locations.php?section='+correctsection+'&page='+page+'&preview='+ preview + '&previewproperty='+previewproperty+'&leveltwopage='+leveltwopage+'&propertyid='+propertyid+'&pagetype='+pagetype+'&pagenumber='+pagenumber,
		success: function(html) {
			eval(html);


			//Set the icon details for the single marker
			var icon      = new GIcon(G_DEFAULT_ICON);
			icon.image    = 'images/maps/stayin_pin.png';
			icon.shadow	  = 'images/maps/msmarker.shadow.png';
			icon.iconSize = new GSize(37, 32);
			var markers = []; //Start the array of markers
			var lats = []; //Start the array of latitudes
			var longs = []; //Start the array of longitudes
			for (var i = 0; i < locations.length; ++i) { //Loop through the locations fully

				var latlng        = new GLatLng(locations[i][0], locations[i][1]); //Set the co ordinates of the location
				var marker        = new GMarker(latlng, {icon: icon}); //Create the marker
				var markerContent = locations[i][2]; //Set the message for the info window
				addMarkerListener(map, marker, markerContent); //Add a listener for the marker

				markers.push(marker);
				lats.push(locations[i][0]);
				longs.push(locations[i][1]);

			}

      Array.max = function( array ){
          return Math.max.apply( Math, array );
      };

      Array.min = function( array ){
          return Math.min.apply( Math, array );
      };

      var LatMax = Array.max(lats);
      var LatMin = Array.min(lats);
      var LongMax = Array.max(longs);
      var LongMin = Array.min(longs);

      var LatCentre = LatMax - ((LatMax - LatMin) / 2);
      var LongCentre = LongMax - ((LongMax - LongMin) / 2);

      var centre = new GLatLng(LatCentre, LongCentre);

			if(locations.length > 0)
			{

				if(accommodationsection == 'map-view' || preview == true)
				{
					map.setCenter(centre, 8); //Set the centre point of the maps and the zoom level
				}
				else
				{

					if($('#extended').length > 0)
					{
						map.setCenter(centre, 8); //Set the centre point of the maps and the zoom level
					}
					else
					{
						map.setCenter(centre, 7); //Set the centre point of the maps and the zoom level
					}
				}

			}

			//Set the location of the image
			var imageLocation = 'https://';

			if (document.domain == 'xblocal') {

				imageLocation += 'xblocal/yorkshiredales-stay.co.uk/httpdocs';

			} else if (document.domain == 'stayin.9xb.com') {

				imageLocation += 'stayin.9xb.com';

			}
			else
			{
				imageLocation += 'www.yorkshiredales-stay.co.uk/';
			}


			//Set the styles for the clusters
			//The smallest number appears 1st
			//The reason for 2 being the same is so we can align the text centrally for 1 and 2 digit clusters
			var styles = [[{
				url: imageLocation + '/images/maps/stayin_cluster_pin.png',
				height: 33,
				width: 37,
				opt_anchor: [3, 7],
				opt_textColor: '#000000'
			  },
			  {
				url: imageLocation + '/images/maps/stayin_cluster_pin.png',
				height: 33,
				width: 37,
				opt_anchor: [3, 5],
				opt_textColor: '#000000'
			  }]];

			var clusterOptions = { maxZoom: 15, styles:styles[0] }; //Set the cluster options and the level of zoom at which the clusters explode

			var markerCluster = new MarkerClusterer(map, markers, clusterOptions);


			map.setUIToDefault(); //Set the map to look like maps.google.com




		}

	});

	//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

		if($('#zip').val() == '')
		{
			$('#new_search').html('<p class="error">Please enter your postcode</p>');
			return false;
		}

		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)
				{

					$('#new_search').html('');

					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').html('<p class="error">Sorry but we couldn\'t find your postcode</p>');
					return false;

				}

		});

		//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 = 'https://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(){

	/**
	*
	* PAGES: accommodation, tourist, search, map-view-search, region, location, village
	*/
	launchMap();

	/**
	* homepage tabs and maybe others
	*/
	homepagetab();

	/**
	* left hand tabs
	*/
	lefttabs();

	/**
	* second tabs
	*/
	secondtab();

	/**
	* crop images
	* PAGES: view-images
	* crop();
	*/


	/**
	* show more on search
	* PAGES: accommodation, tourist, search, map-view-search, region, location, village
	*/
	showmore();

	/**
	* gallery
	* PAGES: photo-gallery

	gallery();
	*/

	/**
	* admin map
	* PAGES: edit-property,edit-tourist
	*/
	adminmap();

	/**
	* homepage lightwindow
	*
	*/
	//homepagelightwindow();

	/**
	* date picker on the rates page
	* PAGES: edit-tourist,edit-property
	*/
	datepicker();

	/**
	* geo code the sign up form
	*/
	postcodeSearchsignup();

	/**
	* featured property tracking
	* PAGES homepage
	* featuredproperty();
	*/

	/**
	* left cta tracking
	*/
	leftnav();

	/**
	* spotlight tracking
	*/
	spotlight();

	/**
	* featured partner
	*/
	featuredpartner();

	/**
	* recommended homepage
	*/
	recommendedhome();

	/**
	* location
	*/
	recommendedlocation();

	/**
	* bookmark
	*/
	bookmark();


	/**
	* printpage
	*/
	printpage();


	/**
	* featured partner
	*/
	leftfeaturedpartners()

	/**
	* expand text
	* PAGES: accommodation, tourist, news
	* expandabletext();
	*/



	/**
	* confirmation on delete email button
	* PAGES: view-all-enquires, view-enquires
	* confirmdelete();
	*/



	/**
	* advanced search
	* PAGES: search, map-view-search, region, location, village
	* advancedsearch();
	* villagesearch();
	* townsearch();
	* regionsearch();
	* specialitysearch();
	* accommodationsearch();
	*/


	/**
	* if we are on the search page the we need to submit the form automatically
	* refinesearchsubmit();
	*/

	/**
	* auto submit
	* advancedsearchsubmit();
	* sleepsupto();
	*/

	/**
	* map view
	*/
	mapviewtab();


	/**
	* limit textbox
	* PAGES: edit-property, view-rates
	* limitcaption();
	*/



	/**
	* scrolling photo
	* PAGES: accommodation, tourist

	photoscroll();
	displaylargeimage();
	*/

	/**
	* website tracking
	* PAGES: accommodation, tourist
	* websitereferrals();
	* touristwebsitereferrals();
	*/


	/**
	* number of calendars
	* PAGES: view-availability

	getnumcalendars();
	*/

	/**
	* update the availability page dropdown
	* PAGES: view-availability

	availabilitypage();
	*/

	/**
	* rates pages
	* PAGES: view-rates

	ratestab();
	ratetemplate();
	*/
	/**
	* clears the sleeps up to
	* PAGES: search, map-view-search

	clearsleepsupto();

	ADMIN
	*/
	adminMenu();
	userMatrix();
	/**
	* Ensure that no more than the given number of specialities are checked
	*/
	specialityChecked();

});

function adminMenu() {

	if ($('.submenu').length == 0) return false;

	$('.expandMenu').mouseover(function() {

		$(this).children('ul').show();

	});

	$('.expandMenu').mouseout(function() {

		$(this).children('ul').hide();

	});

}

function userMatrix() {

	if ($('.usermatrix').length == 0) return false;

	$('.usermatrix').click(function() {

		var ul = $(this).next('ul');
		var inputs = ul.children('li').children('ul').children('li').children('input');

		if ($(this).is(':checked')) {

			ul.show();

			/*inputs.each(function() {

				 $(this).attr('checked', 'checked');

			 });*/


		} else {

			ul.hide();

			/*inputs.each(function() {

				 $(this).attr('checked', '');

			 });*/

		}

	});

}

function specialityChecked() {

	if ($('.speciality').length == 0) return false;

	$('.speciality').click(function() {

		if ($(this).is(':checked')) {
      if($('.speciality:checked').length == 10) { // We want only a maximum of 10 elements to be checked
				$('.speciality').each(function() { // Loop through the checkbox elements
  				if(this.checked == false) { // Check to see if the element is unchecked
            this.disabled = true;
          }
        });
      // We want only a maximum of 10 elements to be checked but the legacy means that more than
      } else if($('.speciality:checked').length > 10) {
        var checkLength = $('.speciality:checked').length;
				$('.speciality').each(function() { // Loop through the checkbox elements
  				if(this.checked == true && checkLength > 10) { // Check to see if the element is checked
  				  checkLength--;
            this.checked = false;
            this.disabled = true;
          } else if(this.checked == false) {
            this.disabled = true;
          }
        });
      }
		} else {
			$('.speciality').each(function() { // Loop through the checkbox elements and remove disabled
        this.disabled = false;
      });
		}

	});

}

function clearsleepsupto()
{
	if($('#clearsleepsupto').length == 0) return false;

	$("#clearsleepsupto").removeClass("hidden");

	$('#clearsleepsupto').click(function ()
	{
		$("#sleeps_up_to").val('clear');
		$("#adsearchform").submit();
		return false;
	})
}

/*
function getnumcalendars()
{

	if($('#numcalendar').length == 0) return false;

	$('#numbercalendars').change(function ()
	{
		//alert($('#numbercalendars').val());
		$("#numcalendar").html($('#numbercalendars').val());
	})

}*/


function getnumcalendars()
{

	if($('#numbercalendars').length == 0) return false;


	$('#numbercalendars').change(function ()
	{

		var height = (($('#numbercalendars').val() / 3) * 250) + 100;

		var content = '<iframe src="'+$('#calendarsitepath').val()+'calendar.php?id='+$('#calendarsection').val()+'&numbercalendars='+$('#numbercalendars').val()+'&site='+$('#calendarsite').val()+'" frameborder="0" width="600px" height="'+height+'px" ></iframe>';
		$("#iframecontent").val(content);
	})

}

/**
* update the rates tab
*/
function ratestab()
{
	if($('#showrates').length == 0) return false;

	$('#showrates').change(function ()
	{
		$("#ratestab").submit();
	})
}


/**
* update the edit property/tourist advert
*/
function editadvert()
{

	if($('#status').length == 0) return false;

	$('#status').change(function ()
	{
		$("#edit_listing").submit();
	})
}


/**
* update the rates template
*/
function ratetemplate()
{
	if($('#ratetemplateform').length == 0) return false;

	$("input[name='ratetemplate']").click(function()
	{
		$("#ratetemplateform").submit();
	})
}



function availabilitypage()
{

	if($('#availabilityform').length == 0) return false;

	$('#availability').change(function ()
	{
		$("#availabilityform").submit();
	})
}



function refinesearchsubmit()
{

	if($('#results_per_page').length == 0) return false;

	$('#results_per_page').change(function ()
	{
		$("#sortbyform2").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)
	{
		if($('.newsarticleexpand').length != 0 )
		{
			$('.newsarticleexpand').addClass("hidden");
		}

		return false;
	}

	$('.expandable').hide();

	$('.expand').click(function()
	{

		var elements = $(this).attr('id').split('_');
		var id = elements[1];


		if($(this).html() == 'Expand')
		{

			$(this).html('Collapse');
			$('#span_'+id).show();

			$(this).parent().removeClass('newsarticleexpand');
			$(this).parent().addClass('newsarticlecollapse');

			$('#dotspan_'+id).hide();

		}
		else
		{

			$(this).html('Expand');
			$('#span_'+id).hide();

			$(this).parent().removeClass('newsarticlecollapse');
			$(this).parent().addClass('newsarticleexpand');

			$('#dotspan_'+id).show();

		}

		return false;

	});

}


/**
* expand or contract the text
*/
function expandrenewals()
{


	if($('.renew').length == 0) return false;

	$('.renew').click(function()
	{

		var id = $(this).attr('id')

		$('#'+id+'list li').each(function(i)
		{

			if($(this).attr('class') == 'bluelink hidden' || $(this).attr('class') == 'bluelink show')
			{
				if($('#'+id).html() == 'Show All')
				{
					$(this).removeClass('hidden');
					$(this).addClass('show');

				}
				else
				{
					$(this).removeClass('show');
					$(this).addClass('hidden');
				}
			}
		});

		if($(this).html() == 'Show All')
		{
			$(this).html('Show Less');
		}
		else
		{
			$(this).html('Show All');
		}


		return false;
	});

	return false;

}


function datepicker()
{
	if($('.dateinput').length == 0) return false;
	$(".dateinput").datepicker({showOn: 'button', buttonImage: 'images/icons/calendar.gif', buttonImageOnly: true, dateFormat: 'dd-mm-yy' });
}

/*
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});
		$("#photogallery").css("visibility","visible");

		//imageclicky();

	}

/**
* 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,
				async : false,
				success: function(html) {}

			});

	});
}


/**
* left nav tracking
*/

function leftnav()
{
	if($(".leftnavadvert").length == 0) return false;
	$(".leftnavadvert").click(function()
	{

		var id = $(this).attr('id');

		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.trackingpartner.php?id='+id,
				async : false,
				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,
				async : false,
				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,
				async : false,
				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,
				async : false,
				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,
				async : false,
				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,
				async : false,
				success: function(html) {}

			});

	});
}


function websitereferrals()
{

	if($(".viewwebsite").length == 0 && $(".accviewwebsite").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',
				async : false,
				success: function(html) {}

			});

	});

  // TODO amalgamate with the click event above - need 2 different classes for styling (mouse image) purposes
	$(".accviewwebsite").click(function()
	{
		var id = $(this).attr('id');

		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.websitereferral.php?id='+id+'&area=accom',
				async : false,
				success: function(html) {}

			});

	});

}

function touristwebsitereferrals()
{

	if($(".tviewwebsite").length == 0 && $(".touviewwebsite").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',
				async : false,
				success: function(html) {}

			});

	});

  // TODO amalgamate with the click event above - need 2 different classes for styling (mouse image) purposes
	$(".touviewwebsite").click(function()
	{
		var id = $(this).attr('id');

		$.ajax({
				type: 'GET',
				url: 'libs/includes/ajax.websitereferral.php?id='+id+'&area=tourist',
				async : false,
				success: function(html) {}

			});

	});
}

/**
* end tracking
*/


/**
* limit textarea
*/


function limitcaptionchar()
{

	if($(".captionchar").length == 0) return false;

	$('.captionchar').maxlengthwords({
		'feedback' : '.charsLeft',
		'hardLimit' : 'true'
	});
}


function limitcaption()
{
	if($(".caption").length == 0) return false;

	$(".caption").keypress
	(
		function()
		{
			limitLengthInWords($(this).attr('id'));
		}
	);

	/*$(".caption").focus
	(
		function()
		{
			limitLengthInWords($(this).attr('id'));
		}
	);

	$(".caption").blur
	(
		function()
		{
			limitLengthInWords($(this).attr('id'));
		}
	);*/


	$(".caption").bind('paste',
		function()
		{
			var id = $(this).attr('id');

			setTimeout(function()
			{
				limitLengthInWords(id);
			}, 2);

		}
	);


	$("textarea.caption").each(
		function()
		{
			limitLengthInWords($(this).attr('id'));
		}
	);


	/*
	$('.caption').maxlength({
		'feedback' : '.charsLeft',
		'hardLimit' : 'false',
		'words' : 'false'
	});
	*/
}


function limitLengthInWords(id)
{

	var maxWords = $("#"+id).attr('maxlengthwords');
	var string = $("#"+id).val();

	var whitespace = string.match(/\s+/g);
	var words = string.split(/\s+/);

	var finished = [];
	for(var i = 0; i < maxWords && words.length > 0; i++)
	{
		if (words[0] == "") { i--; }
		finished.push(words.shift());
		if (whitespace&&whitespace.length>0) {
			finished.push(whitespace.shift());
		}
	}

	if (i>=maxWords) {
		$("#"+id).val(finished.join(''));
	}
	$("#"+id+"Remaining").html(maxWords -i);
}



$.fn.maxlengthwords = function (settings) {

    if (typeof settings == 'string') {
        settings = { feedback : settings };
    }

    settings = $.extend({}, $.fn.maxlengthwords.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=maxlengthwords]').val() : $field.attr('maxlengthwords');
        	//$charsLeft = $form.find(settings.feedback); //REMOVED BY M. VAN ROOYEN TO ALLOW MULTIPLE INSTANCES ON A PAGE
			//charsLeftId = '#' + String($field.attr('id')) + 'Remaining';
			//$charsLeft = $form.find(charsLeftId);
			//alert(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;
            $('#' + $field.attr('id') + 'Remaining').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(' ', (limit*2)-1).join('|') :
            		field.value.substr(0, limit);

				/*var browser    = navigator.appName;
				var pattern    = /\|/g;
				var replaceStr = '';

				if (browser.indexOf('Microsoft') == 0) {

					replaceStr = ' ';

				}

				field.value = field.value.split(' ');
				field.value = field.value.replace(pattern, replaceStr);
				field.value = field.value.substr(0, limit);*/

                updateCount();
            }
        };

        $field.keyup(updateCount).change(updateCount);
        if (settings.hardLimit) {
            $field.keydown(limitCheck);
        }

        updateCount();
    });
};

$.fn.maxlengthwords.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;
				var path =  $(this).parent().attr('href');

				$('#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);

};


/* Hide show additional text for SEO */
$(document).ready(function() {
  var adjustheight = 48;
  $("#adjust").toggle(function() {
    $('#searchText').css('height', 'auto').css('overflow', 'visible');
    $(this).text("less <<");
  }, function() {
    $('#searchText').css('height', adjustheight).css('overflow', 'hidden');
    $(this).text("more >>");
  });
});


