$(function () {
	
// 	if($('#search_by_ref_input').val()=='') {
// 		$('#search_by_ref_input').val('Ref. no.').css('color','#777').click(function() {
// 			if($(this).val()=='Ref. no.') {
// 				$(this).css('color','#000').val('');
// 			}
// 		});
// 	}


	// lettings first time visit
	
	if(!($.cookie("lettings_first_time_visit")|| $.cookie("lettings_advanced_search"))) {
		$('#browse_lettings_box .box_header').replaceWith('<div id="first_time_visitor_lettings"></div>');
	}

	$('#browse_lettings_box ul li a').click(function () {
		$.cookie("lettings_first_time_visit", 'false', {expires:365, path: '/'});
	});

	// sales first time visit - browse

	$('#browse_sales_box ul li a').click(function () {
		$.cookie("sales_first_time_visit", 'false', {expires:365, path: '/'});
	});

	// advanced search, hide and show toggles

	// show is used interactively and at page load
	show_advanced_search = function(slide) {
		if(slide) {
			$('#lettings_search_box').slideDown();
			$('a#show_advanced_lettings_search').slideUp();
		}
		else {
			$('#lettings_search_box').show();
			$('a#show_advanced_lettings_search').hide();
		}
	}

	// hide is used only interactively
	hide_advanced_search = function(slide) {
		// zap the advanced search cookie to make the form disappear
		$.cookie("lettings_advanced_search", '', {expires:-1, path: '/'});
		$('#lettings_search_box').slideUp();
		$('a#show_advanced_lettings_search').slideDown();
	}

	$('a#show_advanced_lettings_search').click(function () { show_advanced_search(true); return false; });
	$('a#hide_advanced_lettings_search').click(function () { hide_advanced_search(); return false; });

	// enable fancybox
	if($('div.epc_fp a').length > 0) { $("div.epc_fp a").fancybox(); }

	// map icons
	
	var icons = {
		"0": '/images/maps/available.png',
		"1":  '/images/maps/saleagreed.png',
		"2":  '/images/maps/sold.png',
		'lettings': 'http://maps.gstatic.com/mapfiles/marker_green.png'
	};
	
	// generate a marker appropriate for the property status
	marker_options = function(status) {
		return {
			icon: new google.maps.MarkerImage(icons[status],
				new google.maps.Size(20, 34), new google.maps.Point(0,0), new google.maps.Point(10,34)
	    ),
			shadow: new google.maps.MarkerImage(
				'http://maps.google.com/mapfiles/shadow50.png',
				new google.maps.Size(37, 34), new google.maps.Point(0,0),new google.maps.Point(10,34)
			),
			draggable: false
		};
	};
	
	// multi marker map info window
	infowindow_content = function(prop) {
		var preview = 
			'<div class="infowindow_preview"><div class="infowindow_preview_thumb">' + 
				'<a href="/p/' + prop['id'] + '"><img src="' + prop['thumbnail'] + '"/></a>' +
				'<br/><a href="/p/' + prop['id'] + '">view full details</a></div>' +
		 		'<div class="title">' + prop['address'] + '</div>' +
		 		'<p>Bedrooms: <strong>' + prop['bedrooms'] +'</strong>&nbsp;&nbsp;&nbsp;Receptions: <strong>' + prop['receptions'] + '</strong>&nbsp;&nbsp;&nbsp;Bathrooms: <strong>' + prop['bathrooms'] + '</strong></p>' +
		 		'<div class="price">' + prop['price'] + ' ' + prop['tenure'] +'</div>';

		if(prop['website_status'] == '1') {
			preview += '<p class="status_underoffer">' + prop['status']  +'</p>';
		}

		if(prop['website_status'] == '2') {
			preview += '<p class="status_sold">' + prop['status']  +'</p>';
		}
		
		// preview += '<p class="branch">' + prop['branch_town'] + ' branch</p>';

		preview += "</div>";
		return preview;
	};

	// render the multiple marker map
	if($('#all_properties_map').length > 0) {
		
		$('#all_properties_map').show();
		
		if(window.location.pathname=='/allproperties') {
			url = '/sales.json';
		}
		else {
			sep = ((window.location + "").indexOf('?') == -1) ? '?' : '&';
			url = window.location + sep + 'json=true';
		}
		
		$.getJSON(url, function(data) {
			
		  var props = [ [], [], [] ];

		  $.each(data, function(idx,prop) {
				props[parseInt(prop['website_status'])].push(
					{lat: prop['lat'], lng: prop['lng'], data: infowindow_content(prop)}
				);
			});
			
			var infowindow, map;
			
			// show the infowindow on click
			marker_click = function(marker, event, data){
				map = $(this).gmap3('get');
			  infowindow = $(this).gmap3({action:'get', name:'infowindow'});
				if (infowindow) {
					infowindow.open(map, marker);
					infowindow.setContent(data);
				} else {
					$(this).gmap3({action:'addinfowindow', anchor:marker, options:{content: data}});
				  infowindow = $(this).gmap3({action:'get', name:'infowindow'});
				}
			};
			
			$('#all_properties_map').gmap3(
				{ action:'init',
				 	options:{
					  zoomControl: true,
			      navigationControl: false,
					  zoomControlOptions: {
					    style: google.maps.ZoomControlStyle.LARGE
					  },
						scrollwheel: false,
			      streetViewControl: false,
						scaleControl: true
		    	}, 
					callback: function() {
						var map = $(this).gmap3('get');
						
						// event handler to clear the infowindow if the map is clicked
						google.maps.event.addListener(map, 'click', function(event) {
							if (infowindow) {
						    infowindow.close();
							};
				    });
					}
		    },
		
				// install markers in three groups - available, under offer, sold
				{ action: 'addMarkers',
					markers: props[0],
					marker: { options: marker_options(0), events:{ click: marker_click } }
				},
				{ action: 'addMarkers',
					markers: props[1],
					marker: { options: marker_options(1), events:{ click: marker_click } }
				},
				{ action: 'addMarkers',
					markers: props[2],
					marker: { options: marker_options(2), events:{ click: marker_click } }
				},
				{ action: 'autofit', maxZoom: 14 }
			);
		
		});
		
	}
		
	// detail map - single marker
	if($('#google_map').length > 0) {
		
		$('img#static_map').hide();
		$('#google_map').show();
		
		var spec = $('#static_map').attr('title').split(':');
		var maploc = spec[0];
		var status = spec[1];
				
		$('#google_map').gmap3(
		  {action: 'init',
		    options:{
		      mapTypeControl: true,
		      navigationControl: true,
		      scrollwheel: false,
		      streetViewControl: false,
					scaleControl: true
		    }
		  },
			{action: 'addMarker',
				address: maploc,
				map: {
		      zoom:14,
					center: true
				},
				marker: { options: marker_options(spec[1]) }
	    }
		);
		
	}

	// sales search functionality
	if($('form#sales_search').length > 0) {
		
		// sales search submit
		$('form#sales_search').submit(function() {
			$.cookie("sales_search", 
				[ $('#price_low').val(), $('#price_high').val(), $('#price_order').val(), $('#outcode').val(), $('#min_bedrooms').val() ].join('|'),
				{expires:365, path: '/'}
			);
		});
		
		// sales search cookie load
		var ck;
		if(ck= $.cookie("sales_search")) {
			var ckv = ck.split('|');
			$('#price_low').val(ckv[0]);
			$('#price_high').val(ckv[1]);
			$('#price_order').val(ckv[2]);
			$('#outcode').val(ckv[3]);
			$('#min_bedrooms').val(ckv[4]);
		}
		else {
			// no cookie, show the first time visitor box
			
			if(!$.cookie("sales_first_time_visit")) {
				$('#sales_search_box .box_header').replaceWith('<div id="first_time_visitor_sales"></div>');
			}
		}

	}
	
	// lettings search
	if($('form#lettings_search').length > 0) {
		
		// un-disable unused form elements when the window is unloaded
		$(window).unload(function() {
			$('#price_low, #price_high, #price_order, #bedrooms').removeAttr('disabled');
		});
		
		// autoset the appropriate search type radio button when fields are clicked
		
		// price search fields
		$('#price_low, #price_high, #price_order').click(function() {
			$('input[name$="search_type"][value$="price"]').attr('checked', 'checked');
		});

		// bedrooms field
		$('#bedrooms').click(function() {
			$('input[name$="search_type"][value$="bedrooms"]').attr('checked', 'checked');
		});
		
		// lettings form submit
		$('form#lettings_search').submit(function() {
			var search_type = $('input[name=search_type]:radio:checked').val();

			// searches save cookie but also disable the fields for the other search type
			
			if(search_type == 'price') {
				$('#bedrooms').attr('disabled', 'disabled');
				$.cookie("lettings_advanced_search", [ 
					search_type, $('#price_low').val(), $('#price_high').val(), $('#price_order').val()
				].join('|'), {expires:365, path: '/'});
			}

			if(search_type == 'bedrooms') {
				$('#price_low, #price_high, #price_order').attr('disabled', 'disabled');
				$.cookie("lettings_advanced_search", [ search_type, $('#bedrooms').val()].join('|'), {expires:365, path: '/'});
			}

		});
		
		// lettings search load cookie
		var ck;
		if(ck= $.cookie("lettings_advanced_search")) {
			
			// show the advanced search form if the cookie is present
			show_advanced_search();
			
			var ckv = ck.split('|');
			var search_type = ckv[0];
			if(search_type == 'price') {
				$('#price_low').val(ckv[1]);
				$('#price_high').val(ckv[2]);
				$('#price_order').val(ckv[3]);
			}
			if(search_type == 'bedrooms') {
				$('#bedrooms').val(ckv[1]);
			}
			$('input[name$="search_type"][value$="' + search_type +'"]').attr('checked', 'checked');
		}
		
	}
	
	// both sales and lettings search use this function to make sure the price bands are never the wrong way round
	$('#price_high, #price_low').change(function() {
		
		if($('#price_high').attr("selectedIndex") < $('#price_low').attr("selectedIndex")) {
			$('#price_high').attr("selectedIndex", $('#price_low').attr("selectedIndex"));
		}
		return true;
	});
	
	
	// Orbit slideshow
	if(!window.ie6) {
		if($('#featured').length > 0) {
			$(window).load(function() {
				$('#featured').orbit({bullets: true, advanceSpeed: 6000 });
			});
		}

		if($('#property_slideshow').length > 0) {
			$(window).load(function() {
				$('#property_slideshow').orbit({
					bullets: true,
				  bulletThumbs: true,
			    bulletThumbLocation: slideshow_thumb_dir,
					advanceSpeed: 6000
				});
			});
		}
  }
	else {
		// alternative IE6 slideshow
		$(window).load(function() {

			// property slideshow replacement
			var photos = $('#property_slideshow > img');
			var thumb_links = $('#property_slideshow_fallback_thumbs a');
			animation_timeout = 12000;

			// add the thumb click functions and 'click' the initial thumb
			thumb_links.click(function () {
			  clearTimeout(animator);
			  thumb_links.removeClass('selected');
			  $(this).addClass('selected');
			  photos.filter(':visible').hide();
			  photos.filter('[src$="' + $(this).attr('href') + '"]').show();
			  return false;
			});

			$('#property_slideshow').addClass('animated');

			photos.hide().click(function() { clearTimeout(animator); }).filter(':first').show();

			thumb_links.filter(':first').addClass('selected');

			animator_action = function() {
				var p = photos.filter(':visible').eq(0);
				var n = p.next('img');
				if(n.length == 0) n = photos.filter(':first');
				p.hide();
				n.show();
			  thumb_links.removeClass('selected').filter('[href="' + n.attr('src') + '"]').addClass('selected');	
				animator = setTimeout(animator_action, animation_timeout);
			};
			animator = setTimeout(animator_action, animation_timeout);

		});
	}
	
	
});



