var default_location = 'New York';
        var latlng;
        var address;
        var dist = 0;
        var Sgeocoder = (typeof google!=='undefined' && typeof google.maps!=='undefined') ? new google.maps.Geocoder() : {};

		function geodir_setup_submit_search() {
            jQuery('.geodir_submit_search').unbind('click');// unbind any other click events
			jQuery('.geodir_submit_search').click(function(e) {

                e.preventDefault();

				var s = ' ';
				var $form = jQuery(this).closest('form');

				if (jQuery("#sdist input[type='radio']:checked").length != 0) dist = jQuery("#sdist input[type='radio']:checked").val();
				if (jQuery('.search_text', $form).val() == '' || jQuery('.search_text', $form).val() == 'Search for') jQuery('.search_text', $form).val(s);
				
				// Disable location based search for disabled location post type.
				if (jQuery('.search_by_post', $form).val() != '' && typeof gd_cpt_no_location == 'function') {
					if (gd_cpt_no_location(jQuery('.search_by_post', $form).val())) {
						jQuery('.snear', $form).remove();
						jQuery('.sgeo_lat', $form).remove();
						jQuery('.sgeo_lon', $form).remove();
						jQuery('select[name="sort_by"]', $form).remove();
						jQuery($form).submit();
						return;
					}
				}
				
				if (dist > 0 || (jQuery('select[name="sort_by"]').val() == 'nearest' || jQuery('select[name="sort_by"]', $form).val() == 'farthest') || (jQuery(".snear", $form).val() != '' && jQuery(".snear", $form).val() != 'Near')) {
					geodir_setsearch($form);
				} else {
					jQuery(".snear", $form).val('');
					jQuery($form).submit();
				}
			});
		}

        jQuery(document).ready(function() {
            geodir_setup_submit_search();
            //setup advanced search form on form ajax load
            jQuery("body").on("geodir_setup_search_form", function(){
                geodir_setup_submit_search();
            });
        });
        
		function geodir_setsearch($form) {
			if ((dist > 0 || (jQuery('select[name="sort_by"]', $form).val() == 'nearest' || jQuery('select[name="sort_by"]', $form).val() == 'farthest')) && (jQuery(".snear", $form).val() == '' || jQuery(".snear", $form).val() == 'Near')) jQuery(".snear", $form).val(default_location);
			geocodeAddress($form);
		}

        function updateSearchPosition(latLng, $form) {
            if (window.gdMaps === 'google') {
                jQuery('.sgeo_lat').val(latLng.lat());
                jQuery('.sgeo_lon').val(latLng.lng());
            } else if (window.gdMaps === 'osm') {
                jQuery('.sgeo_lat').val(latLng.lat);
                jQuery('.sgeo_lon').val(latLng.lon);
            }
            jQuery($form).submit(); // submit form after insering the lat long positions
        }

        function geocodeAddress($form) {
            // Call the geocode function
            Sgeocoder = window.gdMaps == 'google' ? new google.maps.Geocoder() : null;

            if (jQuery('.snear', $form).val() == '' || ( jQuery('.sgeo_lat').val() != '' && jQuery('.sgeo_lon').val() != ''  ) || jQuery('.snear', $form).val().match("^In:")) {
                if (jQuery('.snear', $form).val().match("^In:")) {
                    jQuery(".snear", $form).val('');
                }
                jQuery($form).submit();
            } else {
                var address = jQuery(".snear", $form).val();

                if (jQuery('.snear', $form).val() == 'Near') {
                    initialise2();
                } else {
                                        if (window.gdMaps === 'google') {
                        Sgeocoder.geocode({'address': address},
                            function (results, status) {
                                if (status == google.maps.GeocoderStatus.OK) {
                                    updateSearchPosition(results[0].geometry.location, $form);
                                } else {
                                    alert("Search was not successful for the following reason :" + status);
                                }
                            });
                    } else if (window.gdMaps === 'osm') {
                        geocodePositionOSM(false, address, false, false, 
                            function(geo) {
                                if (typeof geo !== 'undefined' && geo.lat && geo.lon) {
                                    updateSearchPosition(geo, $form);
                                } else {
                                    alert("Search was not successful for the requested address.");
                                }
                            });
                    } else {
                        jQuery($form).submit();
                    }
                }
            }
        }

        function initialise2() {
            if (!window.gdMaps) {
                return;
            }
            
            if (window.gdMaps === 'google') {
                var latlng = new google.maps.LatLng(56.494343, -4.205446);
                var myOptions = {
                    zoom: 4,
                    mapTypeId: google.maps.MapTypeId.TERRAIN,
                    disableDefaultUI: true
                }
            } else if (window.gdMaps === 'osm') {
                var latlng = new L.LatLng(56.494343, -4.205446);
                var myOptions = {
                    zoom: 4,
                    mapTypeId: 'TERRAIN',
                    disableDefaultUI: true
                }
            }
            try { prepareGeolocation(); } catch (e) {}
            doGeolocation();
        }

        function doGeolocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(positionSuccess, positionError);
            } else {
                positionError(-1);
            }
        }

        function positionError(err) {
            var msg;
            switch (err.code) {
                case err.UNKNOWN_ERROR:
                    msg = "Unable to find your location";
                    break;
                case err.PERMISSION_DENINED:
                    msg = "Permission denied in finding your location";
                    break;
                case err.POSITION_UNAVAILABLE:
                    msg = "Your location is currently unknown";
                    break;
                case err.BREAK:
                    msg = "Attempt to find location took too long";
                    break;
                default:
                    msg = "Location detection not supported in browser";
            }
            jQuery('#info').html(msg);
        }

        function positionSuccess(position) {
            var coords = position.coords || position.coordinate || position;
            jQuery('.sgeo_lat').val(coords.latitude);
            jQuery('.sgeo_lon').val(coords.longitude);

            jQuery('.geodir-listing-search').submit();
        }

        /**
         * On unload page do some cleaning so back button cache does not store these values.
         */
        window.onunload = function(){
            if(jQuery('.sgeo_lat').length ){
                jQuery('.sgeo_lat').val('');
                jQuery('.sgeo_lon').val('');
            }
        };