// JavaScript Document


		var map;
		var marker;

		function initialize() {
		  if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map_canvas"));
			var center = new GLatLng(51.5087, -0.1538);
			map.setCenter(center, 6);
			map.addControl(new GSmallMapControl());
	
			marker = new GMarker(center, {draggable: true});
	
			GEvent.addListener(marker, "dragstart", function() {
				oldPosition = marker.getLatLng();
				oldCenter = map.getCenter();
				map.closeInfoWindow();
			});
	
			GEvent.addListener(marker, "drag", function() {
				// Restrict marker position
				var position = marker.getLatLng();
				
				if (((position.distanceFrom(niche_location)/1000) / 1.609344) > niche_distance && niche_distance > 0) {
					marker.setLatLng(oldPosition); 
					map.setCenter(oldCenter);
				}
				
				oldPosition = marker.getLatLng();
				oldCenter = map.getCenter();
			});
	
			GEvent.addListener(marker, "dragend", function() {
			  	var position = marker.getLatLng();
			  	$("input[name='lat']").val(position.lat());
				$("input[name='lng']").val(position.lng());
				map.panTo(position);
			});
	
			map.addOverlay(marker);
			
					
			if (niche_distance > 0) {
				var aMkr2 = new BDCCCircle(niche_location, (1.609344 * niche_distance),"#0000FF",5,0,false,"#0000FF",0.1,"Area covered");
				map.addOverlay(aMkr2);	
			}
			
			
	
		  }
		}
		

		
		$(document).ready(function(){
		
			// Initialise Google maps
			// <body onLoad="initialize()" onUnload="GUnload()" />
			initialize();
		
			// Enable DatePicker
			$('.datepicker').datePicker({ 
                            clickInput: true,
                            showYearNavigation: false,
                            endDate: (new Date()).addYears(1).asString()
                       });

		
		
			// Hide map
			$('#map_canvas, #marker-info').hide();
			

            // Show help when description box has focus
            $('#description').focus(function(){
                $('#desc_help').show();
            }).blur(function(){
                $('#desc_help').hide();
            });

            $('#desc_help').hide();
			
			// Set validation
			
	
			$.validity.setup({
				outputMode:"custom",
				scrollTo:true,
				raiseCustomError:function(obj, msg) {
					$(obj)
						.addClass("error")
						.after('<span class="error">' + msg + '</span>');
				},
				raiseCustomAggregateError:function(obj, msg) {
					$(obj)
						.addClass("error")
						.after('<span class="error">' + msg + '</span>');
				},
				customClear:function() {
					$("span.error").remove();
					$(".error").removeClass("error");
				},
				firstCustomErrorId:function() { 
					if (typeof($(".error:first").attr("id")) != "undefined")
						$.scrollTo($("#" + $(".error:first").attr("id")),1000,{offset:-150});
				}
			});
	
			
			// Custom validation
			
			function minLength(value,min) {		
				return value.length >= min;
			};
	
	
			function location() {													   
				if ($("input[name='lat']").val() != '') {
					return true;
				} else {
					return false;
				}
			}
			
			function passwordConfirm() {													   
				if ($("#password").val() == $("#confirm_password").val()) {
					return true;
				} else {
					return false;
				}
			}
			
			
			// Validation rules

			$("#register").validity(function() { 
								
				$("#available_from, #first_name, #last_name")
			  		.require("&nbsp;");
			  
				$("#parking_cost, #utility, #deposit, #rent")
			  		.require("&nbsp;")
					.match("number","&nbsp;");	
					
				$("#description")
			  		.require(msg_1_2)
					.assert(minLength($("#description").val(),100),msg_1_2);
					
				$("#location")
					.assert(location(),msg_1_1);
			  
			  	// Email
			  	$("#email")
			  		.require("&nbsp;")
					.match("email","&nbsp;");
					
			  	// Password
				$("#password")
					.require(msg_1_3)
					.assert(minLength($("#password").val(),5),msg_1_4);
				
				$("#confirm_password")
					.assert(passwordConfirm(),msg_1_5);
			  
				// Terms
				$("#terms")
					.assert($("#terms").attr("checked"),msg_1_6);

			});
	
		
		
		
			// Enable AJAX query
			
			$("input#location").keypress(function (e) {
				if (e.which == 13) {
					findLocation();
					return false;
				}
			});
			
			$("#locationButton").click(function() {findLocation();return false; }); 

	
			if ($("#location").val()) {
				findLocation();	
			}



		});
		
		
		function findLocation() { 

			$.post("/geocoder",
				{ location: $("#location").val() }, 
				function(data) { 
					if (data.found) {

                         // Did the geocoder return more than 1 place?
                        if (data.found > 1) {
                            multi_places(data);
                            return;
                        }


                        check_and_add_location(data.lat,data.lng)


					 } else {
						 // Show not found message
						 $("#location").val(msg_1_8);
						 $("#location").addClass('location-error');
						 setTimeout("$('#location').val($(\"input[name='location_desc']\").val()); $('#location').removeClass('location-error');",1000);
					 }
				}
			,"json");
		}



        function reset_location_note() {

            var note_text = "E.g. <b>EC1Y 1BD</b> or <b>Angel London</b>";

            $('#register-property-details .note:last').html(note_text);

        }


        function multi_places(data) {
            
            // Create links for the user to chose the correct location

            var note_text = "<b>Please click the area you were looking for...</b>";

            $('#register-property-details .note:last').html(note_text);

            for (var i=0; i<data.places.length; i++) {

                // Create place name

                var loc_name = "";

                if (!isObject(data.places[i].locality2))
                    loc_name = data.places[i].locality2 + ", ";

                if (!isObject(data.places[i].locality1))
                    loc_name = loc_name + data.places[i].locality1 + ", ";

                loc_name = loc_name + data.places[i].admin2;

                if (!isObject(data.places[i].postal))
                    loc_name = loc_name + ", " + data.places[i].postal;


                // Create link

                var loc_link = "<p><a href=\"#\" onclick=\"check_and_add_location(" + data.places[i].centroid.latitude + "," + data.places[i].centroid.longitude + ", '" + escape(data.places[i].name) + "'); return false;\">" + loc_name + "</a>";

                $('#register-property-details .note:last').append(loc_link);

            }
            

        }



        // Checks for an object
        function isObject(obj) {
            if (typeof(obj) == "object")
                return true;

            return false;
        }


        function check_and_add_location(lat,lng) {

            reset_location_note();

             var center = new GLatLng(lat,lng);

             // Check Niche
             if (((center.distanceFrom(niche_location)/1000) / 1.609344) > niche_distance && niche_distance > 0) {
                 // Show not in area covered message
                 $("#location").val(msg_1_9);
                 $("#location").addClass('location-error');
                 setTimeout("$('#location').val(''); $('#location').removeClass('location-error');",2000);
             } else {
                 $('#map_canvas, #marker-info, #slider, #miles-counter').show();
                 map.checkResize();
                 map.setCenter(center,15);
                 marker.setLatLng(center);
                 $("input[name='location_desc']").val($("#location").val());
                 $("input[name='lat']").val(lat);
                 $("input[name='lng']").val(lng);

                 $('#register-property-details .note:last').html('');
             }

             

        }
