var mtcMap;
(function($) {
    'use strict';
    mtcMap = {
        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
            };

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

            geocoderService = new google.maps.Geocoder();
            mtcMap.add_marker(latlng);
            mtcMap.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;
                        mtcMap.add_marker(latlng);
                        mtcMap.update();
                        mtcMap.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';
            mtcMap.reset_markers();

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

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

            return marker;
        },

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

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

        update: function () {
            'use strict';
            var marker = mtcMap.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';
    mtcMap.init();
});