var map;
var markers = [];
var markers_latlng = [];
var searchBox;

function initMap() {
	var mapOptions = {
		zoom: 6,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		center: new google.maps.LatLng(28.25681, 83.95470),
		mapTypeControl: false,
		streetViewControl: false
	};

	map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
	searchBox = new google.maps.places.SearchBox(document.getElementById('searchmap'));

	google.maps.event.addDomListener(document.getElementById('add-marker'), 'click', addMarker);
	google.maps.event.addDomListener(document.getElementById('remove-markers'), 'click', removeMarkers);
	google.maps.event.addDomListener(searchBox, 'places_changed', searchMap);
}

function addMarker() {
	map.setOptions({ draggableCursor: 'crosshair' });
	
	google.maps.event.addListener(map, 'click', function(event) {
		marker = new google.maps.Marker({position: event.latLng, map: map, draggable: true});
		markers.push(marker);

		map.setOptions({ draggableCursor: 'move' });
		google.maps.event.clearListeners(map, 'click');
		
		markers_latlng.push([event.latLng.lat(), event.latLng.lng()]);
		geocodeLatLng(event.latLng.lat(), event.latLng.lng(), markers_latlng.length);

		$.each(markers, function (index, mark) {
			google.maps.event.addListener(mark, 'position_changed', function() {
				var lat = mark.getPosition().lat();
				var lng = mark.getPosition().lng();
				
				var location = index + 1;

				$('#location-'+ location + ' .location-title-latitude').html(lat);
				$('#location-'+ location + ' .location-title-longitude').html(lng);

				$('#location-'+ location + ' .location_latitude_field').val(lat);
				$('#location-'+ location + ' .location_longitude_field').val(lng);
			});
		});
	});

	requiredCheck();
}

function searchMap() {
	var places = searchBox.getPlaces();
	var bounds = new google.maps.LatLngBounds();
	var i, place;

	for(i=0; place=places[i]; i++) {
		bounds.extend(place.geometry.location);
	}
	map.fitBounds(bounds);
	map.setZoom(10);
}

function removeMarkers() {
	for (var i = 0; i < markers.length; i++) {
		markers[i].setMap(null);
	}

	$('.location_container').html('');
	$('.location_required').prop('checked', false);
}

function geocodeLatLng(lat, lng, markers_length) {
	$.ajax({
		type: 'get', 
		url: '/backend/report/geocode-location',
		data: {lat: lat, lng: lng, markers_length: markers_length},
		success: function (res) {
			$('.no_locations').remove();
			$('.location_container').append(res);
			$('.location_required').prop('checked', true);
		} 
	})
}

$.fn.forceNumeric = function () {
     return this.each(function () {
         $(this).keydown(function (e) {
             var key = e.which || e.keyCode;

            var last_char = $(this).val().slice(-1);

            if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
             // numbers   
                key >= 48 && key <= 57 ||
             // Numeric keypad
                key >= 96 && key <= 105 ||
             // comma, period and minus, . on keypad
                key == 190 || key == 188 || key == 109 || key == 110 ||
             // Backspace and Tab and Enter
                key == 8 || key == 9 || key == 13 ||
             // Home and End
                key == 35 || key == 36 ||
             // left and right arrows
                key == 37 || key == 39 ||
             // Del and Ins
                key == 46 || key == 45) {
            	
            	if(last_char !== 'n' || last_char !== '/' || last_char !== 'a') {	
             		return true;
            	}

            } else if (key == 78 || key == 191 || key == 65) {
            	if(key == 78) {
            		$(this).val('');

            		return true;
            	} else if (last_char == 'n' && key == 191) {
            		return true;
            	} else if (last_char == '/' && key == 65) {
            		return true;
            	}

            }

            return false;
        });
    });
}

$('.impact-form-field').forceNumeric();

(function($){
    $.fn.extend({
        donetyping: function(callback,timeout){
            timeout = timeout || 1e3; // 1 second default timeout
            var timeoutReference,
                doneTyping = function(el){
                    if (!timeoutReference) return;
                    timeoutReference = null;
                    callback.call(el);
                };
            return this.each(function(i,el){
                var $el = $(el);
                // Chrome Fix (Use keyup over keypress to detect backspace)
                // thank you @palerdot
                $el.is(':input') && $el.on('keyup keypress paste',function(e){
                    // This catches the backspace button in chrome, but also prevents
                    // the event from triggering too preemptively. Without this line,
                    // using tab/shift+tab will make the focused element fire the callback.
                    if (e.type=='keyup' && e.keyCode!=8) return;
                    
                    // Check if timeout has been set. If it has, "reset" the clock and
                    // start over again.
                    if (timeoutReference) clearTimeout(timeoutReference);
                    timeoutReference = setTimeout(function(){
                        // if we made it here, our timeout has elapsed. Fire the
                        // callback
                        doneTyping(el);
                    }, timeout);
                }).on('blur',function(){
                    // If we can, fire the event since we're leaving the field
                    doneTyping(el);
                });
            });
        }
    });
})(jQuery);

$('.search-location').donetyping(function(){
	if($(this).val().length) {
		$.ajax({
			type: 'get',
			url: '/backend/report/search-location',
			data: { search: $(this).val() },
			success: function (res) {
				$('.search-location-results').html(res);
			}
		})
	} else {
		$('.search-location-results').html('');
	}
});

$('body').on('click', '.location-result', function() {
	var latitude = $(this).data('latitude');
	var longitude = $(this).data('longitude');
	var latLng = new google.maps.LatLng(latitude, longitude);
    

    map.setCenter(latLng);
    map.setZoom(13);
});