﻿
var geocoder;
var map;
var marker;

$(window).load(function() {

    initialize();

    $(function () {
        $("#searchbox").autocomplete({
            minLength: 4,
            // + ', UK'
            //This bit uses the geocoder to fetch address values
            source: function (request, response) {               
                geocoder.geocode({ 'address': request.term, 'region': 'UK' }, function (results, status) {
                    response($.map(results, function (item) {

                        var country;
                        if (item.geometry != undefined) {
                            for (var i = 0; i < item.address_components.length; i++) {
                                for (var j = 0; j < item.address_components[i].types.length; j++) {
                                    if (item.address_components[i].types[j].toUpperCase() == 'COUNTRY')
                                    {
                                        country = item.address_components[i].short_name;
                                    }
                                }
                            }
                        }
                        return {
                            label: item.formatted_address,
                            value: item.formatted_address,
                            latitude: item.geometry.location.lat(),
                            longitude: item.geometry.location.lng(),
                            country: country
                        }
                    }));
                })
            },
            //This bit is executed upon selection of an address
            select: function (event, ui) {
                $("#latitude").val(ui.item.latitude);
                $("#longitude").val(ui.item.longitude);
                $("#country").val(ui.item.country);
                var pos = ui.item.position;
                var lct = ui.item.locType;
                var bounds = ui.item.bounds;
                if (bounds) {
                    map.fitBounds(bounds);
                }
                var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
                marker.setPosition(location);
                map.setCenter(location);
            }
        });
    })

    /*
    *   Handles keypress of searchbox.  Clears lat long values if not enter key
    */
    $('input[id$="searchbox"]').keypress(function (e) {
        var keyCode;
        if (window.event) keyCode = window.event.keyCode;
        else if (e) keyCode = e.which;
        else return true;

        if (keyCode == 13) {
            $('[id$="btnSearch"]').click();
            return false;
        }
        else {
            $("#latitude").val('');
            $("#longitude").val('');
            $("#country").val('');
            return true;
        }
    });

});


function initialize() {
    //MAP
    //41.659, -4.714
    var latlng = new google.maps.LatLng(54.30,-2.10);
    var options = {
        zoom: 5,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    map = new google.maps.Map(document.getElementById("map"), options);

    //GEOCODER
    geocoder = new google.maps.Geocoder();

    marker = new google.maps.Marker({
        map: map,
        draggable: true
    });

}

//google.maps.event.addListener(marker, 'drag', function () {
//    geocoder.geocode({ 'latLng': marker.getPosition() }, function (results, status) {
//        if (status == google.maps.GeocoderStatus.OK) {
//            if (results[0]) {
//                $('#searchbox').val(results[0].formatted_address);
//                $('#latitude').val(marker.getPosition().lat());
//                $('#longitude').val(marker.getPosition().lng());
//            }
//        }
//    });
//});
