//initialization code
window.onload = function() {
    initGeoPositioning();
    initGeoCoder();
};

function initGeoPositioning() {
    try {
        if (geo_position_js.init()) {
            $("#searchNearbyLink").click(function() {
                geo_position_js.getCurrentPosition(
                                                  function(pos) {
                                                      $("#position").val(pos.coords.latitude + "," + pos.coords.longitude);
                                                      $("#searchNearbyForm").submit();
                                                  },
                                                  function(error) {
                                                      window.location = "__mobileStoreSearch.nhtml?error=" + error.code;
                                                  });
                return false;
            });

            $("#searchNearbyLinkContainer").show();
        }
    } catch (e) {
        //client is probably not able to handle jquery. silently ignore and do not display search nearby link.
    }
}

/*
 We use the Geocoder service in the Google Maps API to get results on search queries:
 http://code.google.com/intl/sv-SE/apis/maps/documentation/javascript/services.html#Geocoding
 */

var geocoder = null;

function initGeoCoder() {
    //create geocoder instance
    try {
        geocoder = new google.maps.Geocoder();

        /*
         prevent form submit when enter key is pressed in search input field, send a request to
         google instead
         */
        $("#query").keydown(function(event) {
            if (event.keyCode == 13) {
                event.preventDefault();
                searchGeoLocations();
                return false;
            }
        });

        //handle search button click
        $("#searchButton").click(function() {
            searchGeoLocations();
        });

        //reset NO_SCRIPT status
		$("#geoLocationStatus").val(null);

        //show button
        $("#searchButtonContainer").show();

    } catch(e) {
        handleClientSideException(e);
    }
}

//use a regular submit button if javascript code fails
function handleClientSideException(e) {
    //get elements
	var container = document.getElementById('searchButtonContainer');
	var button = document.getElementById('searchButton');

	//create a submit
	var submit = button.cloneNode(true);
	submit.setAttribute('type', 'submit');

	//replace and display
	container.replaceChild(submit, button);
	container.removeAttribute('style');
}

function searchGeoLocations() {
    var query = $("#query").val();

    if (geocoder == null) {
        //google maps api failed to initialize
        postSearchQueryForm("NO_SCRIPT", null);
    } else if (query === "") {
        //do not query google with an empty string
        postSearchQueryForm(google.maps.GeocoderStatus.OK, "");
    } else if (query) {
        geocoder.geocode({ 'address': query}, handleGeoCoderResponse);
    }
}

function handleGeoCoderResponse(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        //convert response object to json string
        var geoLocations = convertToJson(results);

        //post form with geocoder response as a post parameter and reload page
        postSearchQueryForm(status, geoLocations);
    } else {
        //post form with geocoder response as a post parameter and reload page
        postSearchQueryForm(status, null);
    }
}

function convertToJson(results) {
    var geoLocations = [];

	//get relevant data from geocoding response
    $.each(results, function(index, gLocation) {
        var geoLocation = {
			formatted_address: gLocation.formatted_address,
			location_type: gLocation.geometry.location_type,
			location: gLocation.geometry.location.toUrlValue(),
			bounds: gLocation.geometry.bounds ? gLocation.geometry.bounds.toUrlValue() : ''
        };

        geoLocations.push(geoLocation);
    });

	//json:ify
    return $.toJSON(geoLocations);
}

function postSearchQueryForm(status, geoLocations) {
    //set values in hidden form input elements
    $("#geoLocationStatus").val(status);

    if (geoLocations != null) {
        $("#geoLocationResult").val(geoLocations);
    }

    //post form
    $("#searchQueryForm").submit();
}
