function SubmarketMap(containerEl, propertyType) {
    this._container = containerEl;
    this._propertyType = propertyType;

    this._gmap = null;
    this._polygons = new Array();
    
    this._refresh();
}
SubmarketMap.prototype._refresh = function() {
    for (var i = 0; i < this._polygons.length; i++) {
        this._polygons[i].setMap(null);
    }
    this._polygons = new Array();

    SubmarketMap._COLORS.pointer = 0;
    
    var self = this;
    var caller = new AJAXMethodCaller('com.catylist.ajax.SubmarketPolygonProvider', 'getSubmarketsInTerritory');
    caller.addParameter('java.lang.Integer', this._propertyType);
    caller.setSuccessfulResponseXMLHandler(function(xml) { 
        var submarkets = eval(xml.documentElement.childNodes[0].nodeValue);

        if (!self._gmap) {
            var myOptions = {
                    zoom: 8,
                    center: new google.maps.LatLng(41.890773,-87.632978),
                    disableDefaultUI:true,
                    zoomControl: true,
                    zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL },
                    mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            self._gmap = new google.maps.Map(self._container, myOptions);
            self._gmap.mapTypes.set(google.maps.MapTypeId.ROADMAP, new google.maps.StyledMapType([{ 
                featureType: "all", 
                elementType: "all", 
                stylers: [  { saturation: -70 } ] 
            }]));
        }

        var nesw = [-90, -180, 90, 180];
        for (var i = 0; i < submarkets.length; i++) {
            var path = new Array();
            for (var j = 0; j < submarkets[i].coords.length; j++) {
                var lat = submarkets[i].coords[j++];
                var lng = submarkets[i].coords[j];

                if (lat > nesw[0]) nesw[0] = lat;
                if (lng > nesw[1]) nesw[1] = lng;
                if (lat < nesw[2]) nesw[2] = lat;
                if (lng < nesw[3]) nesw[3] = lng;
                
                path.push(new google.maps.LatLng(lat, lng));
            }
            
            if (path.length > 0) {
                var color = SubmarketMap._COLORS.getNextColor();
                var polygon = new google.maps.Polygon({
                    clickable: true,
                    fillColor: color, 
                    fillOpacity: 0.2, 
                    strokeColor: color, 
                    strokeOpacity: 0.7, 
                    strokeWeight: 2,
                    map: self._gmap,
                    paths: path
                });
                polygon.submarketValue = submarkets[i].value;
                polygon.label = new SubmarketLabel(submarkets[i].name);
                polygon.label.setVisible(false);
                polygon.label.setMap(self._gmap);
                
                google.maps.event.addListener(polygon, 'click', function(evt) {
                    self.onSubmarketSelect(this.submarketValue);
                });
                google.maps.event.addListener(polygon, 'mouseover', function(evt) { 
                    if (evt.latLng) {
                        this.label.setPosition(evt.latLng);
                        this.label.setVisible(true);
                        
                        this.setOptions({
                            fillOpacity: 0.3,
                            strokeOpacity: 1,
                            strokeWeight: 4
                        });
                    }
                });
                google.maps.event.addListener(polygon, 'mousemove', function(evt) {
                    if (evt.latLng) {
                        this.label.setPosition(evt.latLng);
                        this.label.setVisible(true);
                    }
                });
                google.maps.event.addListener(polygon, 'mouseout', function(evt) { 
                    this.label.setVisible(false);
                    
                    this.setOptions({
                        fillOpacity: 0.2,
                        strokeOpacity: 0.7,
                        strokeWeight: 2
                    });
                });
                
                self._polygons.push(polygon);
            }
        }
        
        if (nesw[0] > -90 && nesw[1] > -180 && nesw[2] < 90 && nesw[3] < 180) {
            self._gmap.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(nesw[2],nesw[3]), new google.maps.LatLng(nesw[0],nesw[1])));
        }
    });
    caller.call();
}
SubmarketMap.prototype.setPropertyType = function(propertyType) {
    if (this._propertyType != propertyType) {
        this._propertyType = propertyType;
        this._refresh();
    }
}

SubmarketMap.prototype.onSubmarketSelect = function(submarketValue) {}

SubmarketMap._COLORS = ['#f00', '#0a0', '#00f', '#660', '#0aa', '#a0a', '#666', '#f60', '#390', '#960', '#366', '#636', '#c3c', '#06c', '#0f9', '#360', '#69f'];
SubmarketMap._COLORS.pointer = 0;
SubmarketMap._COLORS.getNextColor = function() {
    SubmarketMap._COLORS.pointer++;
    if (SubmarketMap._COLORS.pointer >= SubmarketMap._COLORS.length) {
        SubmarketMap._COLORS.pointer = 0;
    }
    return SubmarketMap._COLORS[SubmarketMap._COLORS.pointer];
}

function SubmarketLabel(text) {
    this._div = $('<div class="submarket-label" style="position:absolute;">' + text + '</div>');
    this._position = null;
}
SubmarketLabel.prototype = new google.maps.OverlayView;
SubmarketLabel.prototype.onAdd = function() {
    this.getPanes().floatPane.appendChild(this._div[0]);
}
SubmarketLabel.prototype.onRemove = function() {
    this._div.remove();
};

SubmarketLabel.prototype.setPosition = function(latLng) {
    this._position = latLng;
    this.draw();
}
SubmarketLabel.prototype.setVisible = function(visible) {
    this._div.css('visibility', visible ? 'visible' : 'hidden' );
}
SubmarketLabel.prototype.draw = function() {
    if (this._position) {
        var projection = this.getProjection();
        var position = projection.fromLatLngToDivPixel(this._position);
        
        this._div.css({'left':(position.x - 20) + 'px', 'top':(position.y - 24) + 'px'});
    }
};

