/*****************************
 Handles campaign browsing on Google Map.

 Places are loaded with ajax and positioned on the map.

 *****************************/
CampaignBrowser.prototype = new PlacesMap();
function CampaignBrowser(options) {
    PlacesMap.call(this, $.extend({
        getPlaceUrl: function(place){return place.url}
    }, options));
    this.tooltipCache = {};
}

CampaignBrowser.prototype.init = function() {
    PlacesMap.prototype.init.apply(this);
    var self = this,
        defaultPlaceRequest = null,
        timeout = null;

    function cancelTimer() {
        if(timeout) clearTimeout(timeout);
        if (defaultPlaceRequest) defaultPlaceRequest.abort();
    }
    self.cancelTimer = cancelTimer;

    GEvent.addListener(self.map, 'mousemove', function(latlng){
        self.tooltip.hide();
        cancelTimer();
        timeout = setTimeout(function() {
            defaultPlaceRequest = self.getDefaultPlace(latlng, function(place) {
                if (place) {
                    self.tooltip.html(self.getTooltipHtml(place));
                    self.tooltip.show();
                };
            });
        }, 400);
    });
    GEvent.addListener(self.map, 'mouseout', cancelTimer);
    GEvent.addListener(self.map, 'zoomend', cancelTimer);
    GEvent.addListener(self.map, 'moveend', cancelTimer);

    GEvent.addListener(self.map, "click", function(overlay, latlng, overlaylatlng) {
        if (!overlay) {
            defaultPlaceRequest = self.getDefaultPlace(latlng, function(place) {
                if (place) {
                    self.redirectToPlacePage(place);
                };
            });
        }
    });
};

CampaignBrowser.prototype.getDefaultPlace = function(latlng, callback) {
    var self = this;
        return $.get(self.opts.placesGetURL, $.extend({
            lat: latlng.lat(),
            lng: latlng.lng()
        }, self.getTileBounds()), function(data) {
            if (data && data.places) {
                var matched = data.places;
                matched.sort(function(place1, place2){
                    return place2.admin_level - place1.admin_level;
                });
                callback(matched[0]);
            } else {
                callback(null);
            }
        });
};

CampaignBrowser.prototype.initPlaceHandlers = function(place) {
    var self = this;
    PlacesMap.prototype.initPlaceHandlers.apply(this, [place]);

    GEvent.addListener(place.polygon, 'mouseover', function() {
        self.cancelTimer();
    });
    GEvent.addListener(place.polygon, 'click', function(latlng) {
        self.redirectToPlacePage(place);
    });
};

CampaignBrowser.prototype.redirectToPlacePage = function(place) {
    window.location.href =  this.opts.getPlaceUrl(place);
};

CampaignBrowser.prototype.getTooltipHtml = function(place) {
    var self = this,
        simpleHtml = $(PlacesMap.prototype.getTooltipHtml.apply(this, [place]));
    self.currentPlace = place.id;

    simpleHtml.append("<div class=\"meta\">" + gettext('loading..') + "</div>").removeClass("small");

	if (simpleHtml.hasClass("inline-huge")) {
           simpleHtml.addClass("huge").removeClass("inline-huge");
        }
	if (simpleHtml.find('.place').text().length > 42) {
		simpleHtml.removeClass("small").addClass('huge');
	}

    if (place.id in self.tooltipCache) {
        return self.tooltipCache[place.id];
    }

    $.getJSON(
        this.opts.placesGetURL + place.id + "/",
        {},
        function(data) {
            // this check is to make prevent race condition in multiple concurrent info requests.
            if (self.currentPlace != place.id) return;

            self.tooltip.find('.map-pointer .meta').html('<span>' + data.campaigns + '</span> ' + ngettext('campaign', 'campaigns', data.campaigns) + '<span>'
                                + data.calls + '</span> '+ ngettext('Request for Solution', 'Requests for Solution', data.calls));
            self.tooltipCache[place.id] = self.tooltip.html();
        }
    );

    return simpleHtml;
};

CampaignBrowser.prototype.loadPlace = function(id, callback) {
    var self = this;

    $.getJSON(
        this.opts.placesGetURL + id + "/", {geometry: true},
        function(data) {
            var place = self.initPlace(data);
            if (callback) callback(place);
        }
    );
}


