/**
	 * Google Maps
 */
IGDATAPOOLFE.plugins.add('map', {
    form: null,
    initFields: function(form) {
	this.init(form);
    },
    init: function(form) {
	let $form = $(form);
	this.form = $form;
	$('.dp-map-input', $form).each(function() {
	    var $this = $(this);
	    var position = $this.data('lat');
	    var hasMarker = $this.data('hasmarker');

	    var autosearch = $this.data('autosearch');

	    var mapOptions = {
		center : {
		    lat : parseFloat($this.data('lat')),
		    lng : parseFloat($this.data('lng'))
		},
		zoom : $this.data('zoom'),
		panControl: $this.data('panControl'),
		zoomControl: $this.data('zoomControl'),
		scaleControl: $this.data('scaleControl'),
		mapTypeControl: $this.data('mapTypeControl'),
		streetViewControl: $this.data('streetViewControl'),
		overviewMapControl: $this.data('overviewMapControl'),
		scrollwheel: $this.data('scrollwheel')
	    };
	    var map = new google.maps.Map($this.children('.gmap')[0], mapOptions);
	    var marker = new google.maps.Marker({
		position : new google.maps.LatLng(mapOptions.center.lat, mapOptions.center.lng),
		draggable : true
	    });

	    if (hasMarker == 1) {
		marker.setMap(map);
	    }

	    // bind events
	    google.maps.event.addListener(map, 'click', function(event) {
		marker.setPosition(event.latLng);
		marker.setMap(map);
	    });
	    google.maps.event.addListener(marker, 'position_changed', function(event) {
		$('input[type=hidden]', $this).val(this.getPosition().lat() + ',' + this.getPosition().lng());
	    });
	    $form.on('tab_changed smartresize', function(event) {
		var center = map.getCenter();
		google.maps.event.trigger(map, "resize");
		map.setCenter(center);
	    });

	    /*>
	     */
	    var geocoder = new google.maps.Geocoder();

	    var geoSearch = function() {
		geocoder.geocode({
		    'address' : $('.geoCoderWrapper input', $this).val()
		}, function(results, status) {
		    if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			marker.setPosition(results[0].geometry.location);
			marker.setMap(map);
		    }
		});
	    };

	    //bind the click event on the button and enter event on the field
	    $('.geoCoderWrapper button', $this).on('click', geoSearch);
	    $('.geoCoderWrapper input', $this).on('keypress keyup', function(e) {
		if (e.which == 13) {
		    geoSearch();
		    e.preventDefault();
		}
	    });

	    // if autosearch fields are provided, bind the events
	    if (autosearch != '') {
		$(autosearch).on('change', function() {
		    var txt = [];
		    $(autosearch).each(function() {
			if ($(this).val() != '')
			    txt.push($(this).val());
		    });
		    $('.geoCoderWrapper input', $this).val(txt.join(', '));
		}).last().trigger('change').on('change', function() {
		    geoSearch();
		});
	    }

	});
    }
});