/**
 * @rewriten-by Michal Pomaskow
 */

var map = null; //zdefiniowane aby zachowac wsteczna kompatybilnosc ze starszymi projektami
var allpolys = new Array();
var alllines = new Array();
var allcats = new Array();
var alldesc = new Array();
var cluster = false;
var edit = false;
var geocoder = false;

/* Funkcje pomocnicze */
Array.prototype.in_array = function(p_val) {
    for(var i = 0, l = this.length; i < l; i++) {
        if(this[i] == p_val) {
            return true;
        }
    }
    return false;
}

function rand (n) {
    return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

function pause(millis) {
    var date = new Date();
    var curDate = null;
    do {
        curDate = new Date();
    }
    while(curDate-date < millis)
}

var gmap_user = {
    map: null,
    map_div: null,
    controls: [
        //new GMapTypeControl(),
        new GLargeMapControl(),
        new GScaleControl()
    ],
    admin_controls: [
        new GSmallMapControl(),
        new GMapTypeControl(),
        new GScaleControl()
    ],

    geocoder: null,
    dragzoomc: null,
    bounds_limit: null,
    cluster_icons: null,
    maps_array: null,
    bound_limit_coordinates: null,
    prev_coords: null,
    prev_zoom: null,
    step_limit: 0,

    dragzoom_enable: false, //wlaczane w system/config/app.yml app->map->drag_zoom_control
    bound_limit_enable: false, //wlaczane w panelu administracyjnym Informator i Mapa->Konfiguracja->Inne opcje

    //tworze obiekt mapy
    init: function(map_div_id) {
        if(isNull(map_div_id)) {
            this.map_div = $("map");
        } else {
            this.map_div = $(map_div_id);
        }

        this.setMap(this.map_div);
        
        /* Problemy z zoomem? Czy actz na pewno jest Number()? */
        this.getMap().setCenter(new GLatLng(actx,acty), actz);
        this.getMap().enableScrollWheelZoom();
        this.getMap().enableContinuousZoom();
        this.getMap().addControl(new GOverviewMapControl());

        this.setGeocoder();

        GEvent.addListener(gmap_user.getMap(), 'mouseover', function(){
            gmap_user.addControls();
        })
        GEvent.addListener(gmap_user.getMap(), 'mouseout', function(){
            gmap_user.removeControls();
        })

        /* Moduły dodatkowe */
        if(this.dragzoom_enable) {
            this.setupDragZoom();
        }
    
        //ustawiam limit obszaru [do zrobienia]
        if (this.bound_limit_enable) {
            GEvent.addListener(map, "moveend", function(){
                gmap_user.checkBoundsLimit(gmap_user.bound_limit_coordinates);
            });
        }

        //this.map_div.setAttribute('style','position: relative; background-color: rgb(255, 255, 255);');

        this.setMapTypes();
    },

    initAdmin: function(map_div_id) {
        if(!this.getMap()) {
            if(isNull(map_div_id)) {
                this.map_div = $("map");
            } else {
                this.map_div = $(map_div_id);
            }

            this.setMap(this.map_div);

            this.getMap().setCenter(new GLatLng(actx,acty), actz);
            this.getMap().enableScrollWheelZoom();
            this.getMap().enableContinuousZoom();

            this.addControlsAdmin();

            geocoder = new GClientGeocoder();
            this.setMapTypes();            
        }
        
    },

    checkMap: function() {
        // Czy istnieje obiekt mapy?
        if(!this.map) {
            this.setMap($("map"));
        }
    },

    setMap: function(map_div) {
        this.map = new GMap2(map_div);
        map = this.map;
    },

    getMap: function() {
        return this.map;
    },

    addControls: function() {
        gmap_user.controls._each(function(control){
            gmap_user.getMap().addControl(control);
        })
    },

    addControlsAdmin: function() {
        gmap_user.admin_controls._each(function(control){
            gmap_user.getMap().addControl(control);
        })
    },

    removeControls: function() {
        gmap_user.controls._each(function(control){
            gmap_user.getMap().removeControl(control);
        })
    },

    setGeocoder: function() {
        this.geocoder = new GClientGeocoder();
		geocoder = new GClientGeocoder();
    },
    
    getGeocoder: function() {
        return this.geocoder;
    },

    /* Funkcje Zoomu i położenia */
    setupDragZoom: function() {
        /* first set of options is for the visual overlay.*/
        var boxStyleOpts = {
            opacity: .2,
            border: "2px solid red"
        };

        /* second set of options is for everything else */
        var otherOpts = {
            buttonHTML: "<img src='"+absUrl+"images/mapa/zoom-button.gif' />",
            buttonZoomingHTML: "<img src='"+absUrl+"images/mapa/zoom-button-activated.gif' />",
            buttonStartingStyle: {
                width: '24px',
                height: '24px'
            },
            overlayRemoveTime: 500
        };

        //gmap_user.controls.push
        var drag_zoom_object = new DragZoomControl(boxStyleOpts, otherOpts, {});
        //var drag_zoom_position = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(22, 286));

        //gmap_user.getMap().addControl(drag_zoom_object,drag_zoom_position);
        gmap_user.controls.push(drag_zoom_object); //dodaje obiekt drag_zoom do arraya controls
    },

    setMapsArray: function(maps_array) {
        this.maps_array = maps_array;
    },

    getMapsArray: function() {
        return this.maps_array;
    },

    setMapTypes: function() {
        if (this.getMapsArray().in_array('osm')) {
            startOSM();
        }

        if (this.getMapsArray().in_array('ump')) {
            startUMP();
        //map.setMapType(UMP_MAP);
        }
        if (this.getMapsArray().in_array('google')) {
            this.getMap().setMapType(G_NORMAL_MAP);
            this.getMap().addMapType(G_SATELLITE_3D_MAP);
        } else {
            this.getMap().removeMapType(G_NORMAL_MAP);
            this.getMap().removeMapType(G_HYBRID_MAP);
            this.getMap().removeMapType(G_SATELLITE_MAP);
        }
        if (this.getMapsArray().in_array('karto')) {
            startKarto('Kartogr.','Concept Intermedia');
        }
        if (this.getMapsArray().in_array('lotnicza')) {
            startLotnicza('Lotnicza','Concept Intermedia');
        }
    },

    checkBoundsLimit: function(map_bounds_limit) {
        var map_limit = this.getMap().getBounds();
        if(map_bounds_limit.containsBounds(map_limit)) {
            this.step_limit = 0;
            return true;
        } else {
            //jestesmy poza dozwolonym obszarem wracamy na poprzednia pozycje
            var map_bounds = this.getMap().getBounds();

            if (map_bounds.containsBounds(map_bounds_limit)) {
                this.getMap().zoomIn();
            } else {
                var ne = map_bounds.getNorthEast();
                var lne = map_bounds_limit.getNorthEast();
                var sw = map_bounds.getSouthWest();
                var lsw = map_bounds_limit.getSouthWest();
                var dx = 0;
                var dy = 0;

                if (ne.x > lne.x){
                    dx = +0.2;
                } else if (sw.x < lsw.x) {
                    dx = -0.2;
                }

                if (ne.y > lne.y){
                    dy = -0.2;
                } else if (sw.y < lsw.y) {
                    dy = +0.2;
                }
                this.getMap().panDirection(dx,dy);

                if(this.step_limit==1) {
                    this.getMap().zoomIn();
                } else {
                    this.step_limit=1;
                }
            }
            return false;
        }
    },

    mapChange: function(type) {
        this.getMap().setMapType(type);
    },

    resizeMap: function() {
        this.getMap().checkResize();
        return true;
    }
}

function wskaz(x,y,z) {
    if (map.getZoom() != Number(z)) {
        //map.setZoom(Number(z));
    }
    map.panTo(new GLatLng(x,y));
    // Umieszczenie markera
    if (mark) map.removeOverlay(mark);
    var posn = new GLatLng(x,y);
    var ico = new GIcon(G_DEFAULT_ICON);
    ico.image = "http://www.google.com/mapfiles/marker_green.png";
    var opts = {
        draggable:false,
        icon: ico
    };
    mark = new GMarker(posn,opts);
    map.addOverlay(mark, 0, 17);
}

var mPrinted = false;

function print_map() {
    if (!mPrinted) {
        $('map_print').appendChild($('map').childNodes[0].childNodes[0]);
        $('map_print').style.width = $('map').clientWidth+"px";
        $('map_print').style.height = $('map').clientHeight+"px";
        if ($('map_print').style.display == 'none') {
            $('map_print').show();
        }
        mPrinted = true;
        print();
        setTimeout(function() {
            //alert('Zakończono drukowanie');
            print_map();
        }, 100);
    } else {
        //Element.remove($('map_print').childNodes[0]);
        $('map').childNodes[0].appendChild($('map_print').childNodes[0]);
        if ($('map_print').style.display != 'none') {
            $('map_print').hide();
        }
        mPrinted = false;
    }
}

//function checkMap() {
//    // Czy istnieje obiekt mapy?
//    if(typeof(map)!='object') {
//        initAdmin();
//    // Czy div w którym jest to na pewno ten który widzimy?
//    } else if (map.getContainer() != $('map')) {
//        // Jeżeli nie to restart (optymalne było by przepięcie).
//        initAdmin();
//    }
//}
