﻿var PushpinHelper = function(map, geocoder) {
    this.pushpins = [];
    this.zoomCorrection = -1;
    delete this.pushpins;
    this.bounds = new GLatLngBounds();
    this.refresh = function() {
        this.nextPushpin(this, 0);
    };

    this.nextPushpin = function(ph, pos) {
        if (ph.pushpins.length <= pos) return;
        setTimeout(function() {
            ph.showPushpin(ph.pushpins[pos].address, ph.pushpins[pos].html, pos == (ph.pushpins.length - 1))
            ph.nextPushpin(ph, ++pos)
        }, 100);
    };

    this.showPushpin = function(address, html, isLast, isCorrected) {
        var ph = this;
        geocoder.getLatLng(address, function(point) {
            if (isLast)
                ph.setLast(point, address, html, isLast, isCorrected)
            else ph.set(point, address, html, isLast, isCorrected);
        });
    };
    this.set = function(point, address, html, isLast, isCorrected) {
        if (!point) {
            address = address.substring(0, address.indexOf(',')) + address.substring(address.lastIndexOf(','));
            address = address.replace(' ', '');
            if (!isCorrected)
                this.showPushpin(address, html, isLast, true);
        }
        else {
            var marker = this.createPushpin(point);
            map.addOverlay(marker);
            this.bounds.extend(point);
            GEvent.addListener(marker, "mouseover", function() {
                marker.openInfoWindowHtml(html);
            });
            return marker;
        }
    };
    this.setLast = function(point, address, html, isLast, isCorrected) {
        this.set(point, address, html, isLast, isCorrected);
        var bounds = this.bounds;
        var zoomCorrection = this.zoomCorrection;
        setTimeout(function() {
            var zoom = map.getBoundsZoomLevel(bounds) + zoomCorrection;
            if (zoom > 13) zoom = 13;
            map.setCenter(bounds.getCenter(), zoom);
        }, 200);
    };

    this.createPushpin = function(point) {
        var icon = new GIcon();
        icon.image = rootUrl + "Assets/img/pushpin_orange.png";
        icon.iconSize = new GSize(42, 44);
        /*icon.shadowSize = new GSize(22, 20);*/
        icon.iconAnchor = new GPoint(15, 40);
        icon.infoWindowAnchor = new GPoint(15, 1);

        return new GMarker(point, icon);
    }
}
