var QualityMap = {
    mapPoints: [],
    mapPointsDetails: [],
    markerBound: null,
	
    openMap: function(countryCode, bol) {
        var that = this;
        //Init
        if (jQuery("#QualityMapLayer").size()==0) {
            jQuery("#cartinaHome").append(jQuery('<div id="QualityMapLayer"></div>'));
        }
        this.map = new google.maps.Map(document.getElementById("QualityMapLayer"), {
            zoom: 1,
            minZoom: 1,
            center: new google.maps.LatLng(0,0),
            mapTypeId: google.maps.MapTypeId.TERRAIN,
            scrollwheel: false,
            backgroundColor: '#e9ecf3'
        });
        this.mapPoints = [];
        this.markerBound = new google.maps.LatLngBounds();
        this.map.setZoom(1);

        //Create markers
        var image = new google.maps.MarkerImage(
            '/sites/all/themes/quality/images/marker.png',
            //Dimensioni dell'immagine
            new google.maps.Size(40, 40),
            //Inizio dell'immagine (utile solo per le immagini sprite)
            new google.maps.Point(0,0),
            //Anchor: base della bandiera
            new google.maps.Point(12, 38)
            );

        var shadow = new google.maps.MarkerImage(
            '/sites/all/themes/quality/images/marker-shadow.png',
            //Dimensioni dell'immagine
            new google.maps.Size(40, 40),
            new google.maps.Point(0,0),
            new google.maps.Point(12, 38)
            );
        // Shapes define the clickable region of the icon.
        var shape = {
            coord: [8,4,15,4,20,9,20,16,15,21,12,36,11,36,10,31,10,25,9,25,9,21,6,19,4,16,3,14,3,10,4,8,7,5,8,4],
            type: 'poly'
        };
		
        jQuery.each(this.mapPointsDetails, function(k, point) {
            var obj = {};
            
            var contentString = '<div class="mappa_infowindow" style="min-height:140px;">';
            contentString += '<h1><a style="color:#e21585; width:280px;" href="' + point.node_url + '">' + point.name + '</a></h1><br />';
            //contentString += 'Informazioni su questa destinazione</a><br><br>';
            //contentString += '<a href="' + point.marchio_url + '"><img src="' + point.marchio_logo + '" style="max-height:50px; max-width: 200px;"/></a>';
            contentString += '<br /><div id="proposte'+point.country_code+'" style="margin-top:-50px;" ></div>';
            contentString += '</div>';

            var sw = new google.maps.LatLng(point.geo.bounds.s, point.geo.bounds.w);
            var ne = new google.maps.LatLng(point.geo.bounds.n, point.geo.bounds.e);
            obj.bound = new google.maps.LatLngBounds(sw, ne);

            obj.point = new google.maps.LatLng(point.geo.lat, point.geo.lng);
	
            var marker = new google.maps.Marker({
                shadow: shadow,
                icon: image,
                shape: shape,
                map: that.map,
                position: obj.point,
                //title: point.name,
                animation: google.maps.Animation.DROP
            });

            that.markerBound.extend(obj.point);

            if (point.name) {
                var infowindow = new google.maps.InfoWindow({
                    content: contentString
                });
                google.maps.event.addListener(infowindow, 'domready', function() {
                    countryCode = point.country_code;
                    $.ajax({
                        url: '/products/index/services',
                        data: {
                            country: countryCode
                        },
                        success: function(data) {
                            $('#proposte'+countryCode).empty();
                            for (var x in data) {
                                var q = data[x];
								$('#proposte'+countryCode).append($('<a class="listing" style="color:#027ac6" href="/products/'+x+'?country='+countryCode+'">'+q+'</a><br>'));
                            }
                            $('#proposte'+countryCode).append($('<div class="clear"></div>'));
                        },
                        dataType: 'json',
                        type: 'GET'
                    });
                });
                google.maps.event.addListener(marker, 'click', function() {
                    that.closeAllInfoWindow();
                    infowindow.open(that.map, marker);
                });
                obj.infoWindow = infowindow;
            }

            obj.marker = marker;
            that.mapPoints[point.country_code] = obj;
        });
		
		
        //Open first info window
        if (countryCode) {
            var point = this.mapPoints[countryCode];
            this.map.fitBounds(point.bound);
            this.map.setCenter(point.point);
            point.marker.setVisible(true);
            if (point.infoWindow) {
                this.closeAllInfoWindow();
                point.infoWindow.open(this.map, point.marker);
            }
            this.map.setZoom(3);
        }
        else {
        	this.map.fitBounds(this.markerBound);
        }
    },

    addPoint: function(point) {
        this.mapPointsDetails.push(point);
    },

    closeMap: function() {
		
    },
	
    closeAllInfoWindow: function() {
        for (var k in this.mapPoints) {
            if (this.mapPoints[k].infoWindow) {
                this.mapPoints[k].infoWindow.close();
            }
        }
    },
    showOrHidePoints: function(showOrHide, list) {
        if (list) { //show or hide markers specified in list
            for (var k in this.mapPoints) {
                go = false;
                for(var x in list) {
                    if (k == list[x]) {
                        go = true;
                    }
                }
                if (go) {
                    this.mapPoints[k]['marker'].setVisible(showOrHide);
                }
            
            }
        } else { //show or hide all markers
            for (var k in this.mapPoints) {
                this.mapPoints[k]['marker'].setVisible(showOrHide);
            }
        }
    }
};

jQuery(function() {
    jQuery("#mapSearchField").keyup(function() {
        var field = jQuery(this).val().toLowerCase();
        var foundNodes = [];
        jQuery("#paesi span.file a").each(function() {
            if (jQuery(this).text().toLowerCase().indexOf(field) !== -1) {
                jQuery(this).parents('li:eq(0)').show();
                foundNodes.push(jQuery(this));
            } else {
                jQuery(this).parents('li:eq(0)').hide();
            }
        });
	
        jQuery("#paesi li.collapsable span.folder").click();
        if (foundNodes.length === 1) {
            var node = jQuery(foundNodes[0]).parents('li');
            jQuery("span.folder", node).click();
        }
    });
});

function openMap(countryCode) {
    jQuery('#layerCartinaHome').show();
    jQuery('#apriMappa, #slides').hide();
    jQuery('#chiudiMappa').show();
    QualityMap.openMap(countryCode);
}

function closeMap() {
    jQuery('#layerCartinaHome').hide();
    jQuery('#apriMappa, #slides').show();
    jQuery('#chiudiMappa').hide();
    QualityMap.closeMap();
}

function toggleMap() {
    if (jQuery('#layerCartinaHome:visible').length) {
        closeMap();
    } else {
        openMap();
    }
}

function showOrHidePoints(showOrHide, list) {
    QualityMap.showOrHidePoints(showOrHide, list);
}

