define(['jquery', 'underscore', 'backbone', 'text!modules/maps/mapsViewTemplate.html', 'text!modules/maps/infoWindowTemplate.html', 'modules/base/baseView', 'classes/profile'],
        function ($, _, Backbone, mapsViewTemplate, infoWindowTemplate, BaseView, Profile) {

            var MapsView = BaseView.extend({

                map: null,
                markers: [],
                //initialize template
                template: _.template(mapsViewTemplate),
                infoWindowtemplate: _.template(infoWindowTemplate),
                defaultLatLng: new google.maps.LatLng(45.4654219, 9.1859243),  // Default to Milan
                iconPM: {
                        url: "http://app.gruppolapastamadre.it/icon.png",
                        scaledSize: new google.maps.Size(24, 24)
                    },
                iconPMGF: {
                        url: "http://app.gruppolapastamadre.it/iconGreen.png",
                        scaledSize: new google.maps.Size(24, 24)
                    },
                initialize: function () {
                    this.id = "MapsView";
                    this.markers = [];
                    MapsView.__super__.initialize.call(this);
                },
                _centerControl: function(controlDiv, map) {
                    var self = this;
                  // Set CSS for the control border.
                  var controlUI = document.createElement('div');
                  controlUI.style.backgroundColor = '#fff';
                  controlUI.style.border = '2px solid #fff';
                  controlUI.style.borderRadius = '3px';
                  controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
                  controlUI.style.cursor = 'pointer';
                  controlUI.style.marginTop = '10px';
                  controlUI.style.marginLeft = '15px';
                  controlUI.style.textAlign = 'center';
                  controlUI.title = 'Click to recenter the map';
                  controlDiv.appendChild(controlUI);

                  // Set CSS for the control interior.
                  var controlText = document.createElement('div');
                  controlText.style.color = 'rgb(25,25,25)';
                  controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
                  controlText.style.fontSize = '16px';
                  //controlText.style.lineHeight = '32px';
                  controlText.style.padding = '4px';
                  // controlText.style.paddingRight = '5px';
                  controlText.innerHTML = 'Mia Posizione';
                  controlUI.appendChild(controlText);

                  // Setup the click event listeners: simply set the map to Chicago.
                  controlUI.addEventListener('click', function() {
                    if ( navigator.geolocation ) {
                        function success(pos) {
                            // Location found, show map with these coordinates
                            self.map.setCenter(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
                        }
                        function fail(error) {
                            self.map.setCenter(self.defaultLatLng);  // Failed to find location, show default map
                        }
                        // Find the users current position.  Cache the location for 5 minutes, timeout after 6 seconds
                        navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
                    } else {
                        self.map.setCenter(self.defaultLatLng);  // Failed to find location, show default map
                    }
                    
                  });
                },
                _drawMap: function(LatLng){
                    var self = this;
                    var myOptions = {
                        zoom: 10,
                        center: LatLng,
                        mapTypeId: google.maps.MapTypeId.ROADMAP,
                        streetViewControl: false,
                        mapTypeControl: false,
                        zoomControlOptions: {
                            position: google.maps.ControlPosition.RIGHT_CENTER
                        },
                    };
                    $("#map-canvas").width(document.documentElement.clientWidth - 32/*Padding content*/);
                    $("#map-canvas").height(document.documentElement.clientHeight - 151 - self.$el.find('#searchPanel').height());
                    self.map = new google.maps.Map($("#map-canvas")[0], myOptions);

                    // Create the search box and link it to the UI element.
                    var input = $('<input id="pac-input" data-role="none" class="controls" type="text" placeholder="Ricerca località..." style="display:none;">')[0];
                    self.$el.find('div[data-role="content"]')[0].appendChild(input);
                    var searchBox = new google.maps.places.SearchBox(input);
                    self.map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);
                    var centerControlDiv = document.createElement('div');
                    var centerControl = self._centerControl(centerControlDiv, self.map);

                    //centerControlDiv.index = 4;
                    self.map.controls[google.maps.ControlPosition.LEFT_BOTTOM].push(centerControlDiv);
                    var markers = [];
                    // [START region_getplaces]
                    // Listen for the event fired when the user selects a prediction and retrieve
                    // more details for that place.
                    searchBox.addListener('places_changed', function() {
                        var places = searchBox.getPlaces();

                        if (places.length == 0) {
                          return;
                        }

                        // Clear out the old markers.
                        markers.forEach(function(marker) {
                          marker.setMap(null);
                        });
                        markers = [];

                        // For each place, get the icon, name and location.
                        var bounds = new google.maps.LatLngBounds();
                        places.forEach(function(place) {
                            var icon = {
                                url: place.icon,
                                size: new google.maps.Size(71, 71),
                                origin: new google.maps.Point(0, 0),
                                anchor: new google.maps.Point(17, 34),
                                scaledSize: new google.maps.Size(25, 25)
                            };

                            // Create a marker for each place.
                            markers.push(new google.maps.Marker({
                                map: self.map,
                                icon: icon,
                                title: unescape(place.name),
                                position: place.geometry.location
                            }));

                            if (place.geometry.viewport) {
                                // Only geocodes have viewport.
                                bounds.union(place.geometry.viewport);
                            } else {
                                bounds.extend(place.geometry.location);
                            }
                        });
                        self.map.fitBounds(bounds);
                    });

                    self.map.addListener('bounds_changed', function() {
                        var bound = self.map.getBounds();
                        searchBox.setBounds(bound);
                        var latLngFrom = bound.getNorthEast();
                        var latLngTo = bound.getSouthWest();
                        $.ajax({
                            url: myManifest.Settings.DefaultURL + "/api/spacciatori/bound/" + latLngFrom.lat() + "/"+ latLngFrom.lng() + "/" + latLngTo.lat() + "/"+ latLngTo.lng(),
                            //dataType: "json",
                            //async: false,
                            type: 'GET',
                            success: function (resp) {                                
                                resp.forEach(function(ele, index){
                                    var key = "|" + ele.Latitudine+ "|" + ele.Longitudine+ "|";
                                    if(!self.markers[key])
                                    {
                                        self._makeMarker(ele, key);
                                    }
                                    else if(!self.markers[key][ele.ID])
                                    {
                                        ele.Latitudine = parseFloat(ele.Latitudine) + (Math.random() / 500);
                                        ele.Longitudine = parseFloat(ele.Longitudine) + (Math.random() / 500);
                                        self._makeMarker(ele, key);
                                    }
                                });
                            }
                        });
                    });
                    $("#pac-input").show();
                },
                _makeMarker: function(ele,key){
                    var self = this;
                    var marker = new google.maps.Marker({
                        position: new google.maps.LatLng(ele.Latitudine, ele.Longitudine),
                        icon: ele.TipoPM == "4"?self.iconPMGF:self.iconPM,
                        //label: ele.Name,
                        title: $("<div/>").html(unescape(ele.Name)).text(),
                        map: self.map
                      });
                    
                    if(!self.markers[key])
                        self.markers[key] = [];

                    self.markers[key][ele.ID] = marker;

                    var infowindow = new google.maps.InfoWindow({
                        content: self.infoWindowtemplate({item: ele})
                      });

                    marker.addListener('click', function() {
                        infowindow.open(self.map, marker);
                    });
                },
                onShowed: function(){
                    if(this.map)
                        return;

                    var self = this;

                    $( window ).resize( function(){
                        $("#map-canvas").width(document.documentElement.clientWidth - 32/*Padding content*/);
                        $("#map-canvas").height(document.documentElement.clientHeight - 151 - self.$el.find('#searchPanel').height());
                    });
                    
                    if ( navigator.geolocation ) {
                        function success(pos) {
                            // Location found, show map with these coordinates
                            self._drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
                        }
                        function fail(error) {
                            self._drawMap(self.defaultLatLng);  // Failed to find location, show default map
                        }
                        // Find the users current position.  Cache the location for 5 minutes, timeout after 6 seconds
                        navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
                    } else {
                        self._drawMap(self.defaultLatLng);  // No geolocation support, show default map
                    }
                },
                onClosing: function(){
                    var self = this;
                    Object.keys(self.markers).forEach(function(key, i){
                        Object.keys(self.markers[key]).forEach(function(ID, k){
                            self.markers[key][ID].setMap(null);
                        });
                    });

                    self.markers = [];
                },
                //render the content into div of view 
                render: function () {
                    if (this.created === true)
                    {
                        //this.header.title = "pippo";
                        MapsView.__super__.render.call(this);
                        //this.el is the root element of Backbone.View. By default, it is a div.    
                        //$el is cached jQuery object for the view's element.
                        //append the compiled template into view div container
                        this.$el.append(this.header.$el);
                        this.$el.append(this.template({app: myManifest, profile: Profile}));
                        this.$el.append(this.footer.$el);
                        this.$el.find("#infoBtn").addClass("ui-btn-active");
                    }
                    //$("#homeBtn").addClass("ui-btn-active");        
                    //return to enable chained calls
                    return this;
                }
            });
            return MapsView;
        });