var Map;
(function($) {
    'use strict';
    Map = {
        map: null,
        markers: [],
        init: function (config) {
            'use strict';
            var settings = {
                input: null,
                lat_selector: '#lat',
                long_selector: '#long',
                onComplete: false,
                starting_query: null
            },
                zoom = 13,
                coord_lat = 40.96174791270287,
                coord_long = -95.25148110961912,
                coords_from_input,
                coords_from_input_arr,
                coord_regex,
                latlng,
                options,
                geocoderService,
                coords;

            if (
                window.parent.$.coordinate_picker[$('#input').val()] &&
                window.parent.$.coordinate_picker[$('#input').val()].settings
            ) {
                $.extend(settings, window.parent.$.coordinate_picker[$('#input').val()].settings);
            }

            $('#search_map').val("");

             if (google.maps.ClientLocation) {
                coord_lat = google.maps.ClientLocation.latitude;
                coord_long = google.maps.ClientLocation.longitude;
            }

            coords_from_input = window.parent.$.coordinate_picker[$('#input').val()].settings.input.val();
            coords_from_input_arr = coords_from_input.split(",");

            coord_regex = new RegExp("^-?[0-9]+\.[0-9]+$");
            if (coords_from_input_arr[0].search(coord_regex) !== -1 && coords_from_input_arr[1].search(coord_regex) !== -1) {
                coord_lat = coords_from_input_arr[0];
                coord_long = coords_from_input_arr[1];
            }

            latlng = new google.maps.LatLng(coord_lat, coord_long);

            options = {
                zoom: zoom,
                center: latlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            Map.map = new google.maps.Map($('#map_canvas').get(0), options);

            geocoderService = new google.maps.Geocoder();
            Map.add_marker(latlng);
            Map.update();

            $('#search_address_button').click(function () {
                $(this).parents('form').submit();
            });

            $('#search_map').val("");

            $('#search_map_form').submit(function (e) {
                e.preventDefault();
                geocoderService.geocode({address: $('#search_map').val()}, function (results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        latlng = results[0].geometry.location;
                        Map.add_marker(latlng);
                        Map.update();
                        Map.map.fitBounds(results[0].geometry.viewport);
                    } else if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
                        alert('Address not found');
                    } else {
                        alert('Address lookup failed');
                    }
                });

            });

            $('#select_coords_button').click(function (e) {

                zoom = 13,
                coord_lat = 40.96174791270287,
                coord_long = -95.25148110961912;

                // or if we know client location
                if (google.maps.ClientLocation) {
                    coord_lat = google.maps.ClientLocation.latitude;
                    coord_long = google.maps.ClientLocation.longitude;
                }

                coords_from_input = window.parent.$.coordinate_picker[$('#input').val()].settings.input.val();
                coords_from_input_arr = coords_from_input.split(",");

                coord_regex = new RegExp("^-?[0-9]+\.[0-9]+$");
                if (coords_from_input_arr[0].search(coord_regex) !== -1 && coords_from_input_arr[1].search(coord_regex) !== -1) {

                    coord_lat = coords_from_input_arr[0];
                    coord_long = coords_from_input_arr[1];
                }

                coords = {
                    lat: $('#lat').val(),
                    long: $('#long').val()
                };

                settings.onComplete(coords);
                window.parent.$.coordinate_picker[$('#input').val()].settings.input.val(coords.lat + "," + coords.long);

                // If using smodal box, close it.
                if (window.parent.$.smodal) {
                    window.parent.$.smodal.close();
                } else {
                    window.self.close();
                }
            });
        },

        add_marker: function (latlng) {
            'use strict';
            Map.reset_markers();

            var marker = new google.maps.Marker({
                map: Map.map,
                position: latlng,
                draggable: true
            });

            Map.markers.push(marker);
            google.maps.event.addListener(marker, 'dragend', function (e) {
                Map.map.panTo(e.latLng);
                Map.update();
            });

            return marker;
        },

        reset_markers: function () {
            'use strict';
            if (Map.markers) {
            	var i;
                for (i in Map.markers) {
                    Map.markers[i].setMap(null);
                }
                Map.markers = [];
            }
        },

        update_marker: function () {
            'use strict';
            var latlng = Map.map.getCenter();
            Map.add_marker(latlng);
            Map.update();
        },

        update: function () {
            'use strict';
            var marker = Map.markers[0],
                markerLatLng = marker.getPosition(),
                lat = markerLatLng.lat(),
                lng = markerLatLng.lng();
            $('#long').val(lng);
            $('#lat').val(lat);
            $('#on_long').text(lng.toFixed(3));
            $('#on_lat').text(lat.toFixed(3));
        }

    }
})(jQuery);

jQuery(function ($) {
    'use strict';
    Map.init();
});
