var ds_Plugin_Gmaps = ds_Base.extend({
					   
    options: {
        zoomlevel: 11,
        mapSizeX: 658,
        mapSizeY: 526,
        initCenterLat: 52.388932,
        initCenterLng: 5.315405
    },
	
    map: null,
    mapControl: null,
    mapControlPosition: null,
    mapTypeControl: null,
    mapTypeControlPosition: null,
    geocoder: null,
    reverseGeocoder: null,
    locationMarker: null,
    markerManager: null,
    allGMarkers: [],
    allMarkerRegistry: [],
    currentMarkerRegistry: [],
    numMarkers: 0,
    polyGons: [],
    bounds: null,
    point: null,
    points: [],
    formHolder: null,
    mode: null,
    currentProject: null,
	
	
    initialize: function(options) {
        this.setOptions(options);
        this.geocoder = new GClientGeocoder();
        this.markerBaseIcon = new GIcon(G_DEFAULT_ICON);
        this.markerBaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        this.markerBaseIcon.iconSize = new GSize(24, 34);
        this.markerBaseIcon.shadowSize = new GSize(41, 34);
    },
	
    initMap: function() {
		
		
        if (GBrowserIsCompatible()) {
            this.map = new GMap2($("mapContainer"), {
                size: new GSize(this.options.mapSizeX,this.options.mapSizeY)
            });
            this.map.setMapType(G_NORMAL_MAP);

            this.map.setCenter(new GLatLng(this.options.initCenterLat, this.options.initCenterLng), this.options.zoomlevel);
	    
            this.mapControl = new ExtLargeMapControl();
            this.mapControlPosition = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10));
            this.map.addControl(this.mapControl, this.mapControlPosition);
	        
            this.mapTypeControl = new GMapTypeControl();
            this.mapTypeControlPosition = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
            this.map.addControl(this.mapTypeControl, this.mapTypeControlPosition);
	        
            this.map.enableDoubleClickZoom();
	        
            this.markerManager = new MarkerManager(this.map, {
                borderPadding: 50,
                maxZoom: 15,
                trackMarkers: true
            });
	        
            if (this.mode === 'edit') {
                this.map.setZoom(this.formHolder.getElement('input[name=zoomlevel]').value);
        		
                //this.placeMarker(this.formHolder.getElement('input[name=title_from]').value, new GLatLng(this.formHolder.getElement('input[name=latitude_from]').value, this.formHolder.getElement('input[name=longitude_from]').value));
                //this.placeMarker(this.formHolder.getElement('input[name=title_to]').value, new GLatLng(this.formHolder.getElement('input[name=latitude_to]').value, this.formHolder.getElement('input[name=longitude_to]').value));
                $('totalDistanceInput').value = this.formHolder.getElement('input[name=amount_km]').value;

            //console.log(this.formHolder.getElement('input[name=latitude_from]').value);
            //console.log(this.formHolder.getElement('input[name=longitude_from]').value);
            //console.log(this.formHolder.getElement('input[name=title_from]').value);
            //console.log(this.formHolder.getElement('input[name=latitude_to]').value);
            //console.log(this.formHolder.getElement('input[name=maptype]').value);
            }
        } else {
            alert('Helaas is uw browser niet geschikt voor Google Maps.');
        }
		
		
        
    },


    setMapPoint: function(point) {

        if (!point) {
            var icon = new Element('span').addClass('errorIcon').inject($('message'));
            var message = new Element('p').setText("Het adres kon helaas niet worden gevonden, probeer een plaats in de buurt").inject($('message'));
            $('mapContainer').setStyle('display','none');
        } else {
            this.initMap();

            this.map.removeControl(this.mapControl);
            this.map.removeControl(this.mapTypeControl);

            this.mapControl = new ExtLargeMapControl();
            this.map.addControl(this.mapControl);

            this.mapTypeControl = new GMapTypeControl();
            this.map.addControl(this.mapTypeControl);

            this.point = point;

            var icon = new Element('span').addClass('infoIcon').inject($('message'));
            var message = new Element('p').setText("Het adres is gevonden, controleer of dit juist is.").inject($('message'));

            this.map.clearOverlays();
            this.map.setCenter(this.point, this.options.zoomlevel.toInt());
            this.locationMarker = new GMarker(this.point, {
                draggable:true,
                bouncy:true
            });
            this.map.addOverlay(this.locationMarker);

            /*var ed = tinyMCE.get('gmaps_text');
			if (ed.getContent() !== '') {
		    	this.locationMarker.openInfoWindowHtml(ed.getContent());
		    }*/

            //GEvent.addListener(this.locationMarker, "dragend", this.onMarkerDragEnd.bind(this));

            $('Latitude').setProperty('value', this.locationMarker.getPoint().lat().toFixed(14));
            $('Longitude').setProperty('value', this.locationMarker.getPoint().lng().toFixed(14));
        }

    },

    setMapPointSimple: function(point) {

        if (!point) {
            var icon = new Element('span').addClass('errorIcon').inject($('message'));
            var message = new Element('p').setText("Het adres kon helaas niet worden gevonden, probeer een plaats in de buurt").inject($('message'));
            $('mapContainer').setStyle('display','none');
        } else {
            this.initMap();

            this.map.removeControl(this.mapControl);
            this.map.removeControl(this.mapTypeControl);

            //this.mapControl = new ExtLargeMapControl();
            //this.map.addControl(this.mapControl);

            this.mapTypeControl = new GMapTypeControl();
            this.map.addControl(this.mapTypeControl);

            this.point = point;

            this.map.clearOverlays();
            this.map.setCenter(this.point, this.options.zoomlevel.toInt());
            this.locationMarker = new GMarker(this.point, {
                draggable:true,
                bouncy:true
            });
            this.map.addOverlay(this.locationMarker);
        }
    },

    removeControls: function () {
        this.map.removeControl(this.mapTypeControl);
    },
	
    initWizardMap: function() {
		
		
        if (GBrowserIsCompatible()) {
            this.map = null;
            this.map = new GMap2($("mapContainer"), {
                size: new GSize(this.options.mapSizeX,this.options.mapSizeY)
            });
            this.map.setMapType(G_HYBRID_MAP);

            this.map.setCenter(new GLatLng(51.49198,3.618816), this.options.zoomlevel);
	        
            this.mapControl = new ExtLargeMapControl();
            this.mapControlPosition = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10));
            this.map.addControl(this.mapControl, this.mapControlPosition);
	        
            this.mapTypeControl = new GMapTypeControl();
            this.mapTypeControlPosition = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));
            this.map.addControl(this.mapTypeControl, this.mapTypeControlPosition);
	        
            this.map.enableDoubleClickZoom();
            this.map.enableScrollWheelZoom();
	        
            this.markerManager = new MarkerManager(this.map, {
                borderPadding: 50,
                maxZoom: 15,
                trackMarkers: true
            });
	        
        } else {
            alert('Helaas is uw browser niet geschikt voor Google Maps.');
        }
		
		
        
    },
	
	
	
	
    loadGeocoder: function (sAddress) {
		
		
		
        var divContainer	= new Element('div').setProperty('id','container');
        var divMessage 		= new Element('div').setProperty('id','message').inject(divContainer);
        var divContent 		= new Element('div').setProperty('id','content').inject(divContainer);
        var divMapContainer = new Element('div').setProperty('id','mapContainer').inject(divContent);
		
        if (!this.geocoder) {
            alert('Er is een probleem met de verbinding met Google.');
        } else {
            this.geocoder.getLatLng(sAddress, this.setMapPoint.bind(this));
        }
		
        return divContainer;
    },

    loadGeocoderSimple: function (sAddress) {
		
		
		
        var divContainer	= new Element('div').setProperty('id','container');
        var divMessage 		= new Element('div').setProperty('id','message').inject(divContainer);
        var divContent 		= new Element('div').setProperty('id','content').inject(divContainer);
        var divMapContainer = new Element('div').setProperty('id','mapContainer').inject(divContent);
		
        if (!this.geocoder) {
            alert('Er is een probleem met de verbinding met Google.');
        } else {
            this.geocoder.getLatLng(sAddress, this.setMapPointSimple.bind(this));
        }
		
        return divContainer;
    },

    placeMarker: function (overlay, latlng) {
        var iSubtotalFlight = 0;
        /* create base marker */
		
        
        if(this.numMarkers === 0) {
            this.numMarkers = this.markerManager.getMarkerCount(1);
        }
		
        if (latlng) {
            
            if(this.numMarkers === 0) {
                /* create icon */
                this.markerBaseIcon.image = '/images/front/plane_up.png';
            	
                this.startLocationMarker = new GMarker(latlng, {
                    draggable: true,
                    icon: this.markerBaseIcon,
                    bouncy: true,
                    autopan:true
                });
            	
                this.markerManager.addMarker(this.startLocationMarker, this.options.zoomlevel);
            	
                this.geocoder.getLocations(latlng, this.setFlightFrom.bind(this));
            	
                GEvent.addListener(this.startLocationMarker, "dragend", this.onDistanceMarkerDragEnd.bind(this));
            	
                this.bounds.extend(this.startLocationMarker.getPoint());
            	
                $('locationFinderLabel').setText('Geef uw aankomst luchthaven op');
                $('locationFinderInput').setProperty('value', 'plaatsnaam, land').blur();
            	
            	
            } else {
                this.markerBaseIcon.image = '/images/front/plane_down.png';
                this.endLocationMarker = new GMarker(latlng, {
                    draggable: true,
                    icon: this.markerBaseIcon,
                    bouncy: true,
                    autopan:true
                });
            	
                this.markerManager.addMarker(this.endLocationMarker, this.options.zoomlevel);
            	
                this.geocoder.getLocations(latlng, this.setFlightTo.bind(this));
            	
                GEvent.addListener(this.endLocationMarker, "dragend", this.onDistanceMarkerDragEnd.bind(this));
            	
                this.bounds.extend(this.endLocationMarker.getPoint());
            	
                this.distancePlot = new GPolyline([
                    this.startLocationMarker.getLatLng(),
                    this.endLocationMarker.getLatLng()
                    ], "#00A5D9", 4, 1, {});
		        
                this.map.addOverlay(this.distancePlot);
                this.totalDistanceKM = this.distancePlot.getLength()  / 1000;
                $('totalDistanceInput').setProperty('value', this.totalDistanceKM.round() + 'KM.');
		        
                this.formHolder.getElement('input[name=amount_km]').setProperty('value', this.totalDistanceKM.round());
                iSubtotalFlight = this.getAmountCC(this.totalDistanceKM.round());
                this.formHolder.getElement('input[name=amount_cc]').setProperty('value', iSubtotalFlight);
                this.calculatorObject.calculateVliegtuigCoins();
		        
		        
                this.map.setZoom(this.map.getBoundsZoomLevel(this.bounds));
                var clat = (this.bounds.getNorthEast().lat() + this.bounds.getSouthWest().lat()) / 2;
                var clng = (this.bounds.getNorthEast().lng() + this.bounds.getSouthWest().lng()) / 2;
                this.map.setCenter(this.bounds.getCenter());
				
								
            }
            this.markerManager.refresh();
            this.numMarkers = this.numMarkers + 1;
        }
			    
    },
	
	
    onZoom: function(oldZoomlevel, newZoomlevel) {
   		
        if (newZoomlevel !== 'NaN') {
            this.options.zoomlevel = newZoomlevel.toInt();
            $('zoomlevel').setProperty('value', this.options.zoomlevel.toInt());
        } else {
            this.options.zoomlevel = newZoomlevel.toInt();
            $('zoomlevel').setProperty('value', 11);
        }
	    
        
   	
    },
   
    fit: function() {
    	
        this.map.panTo(this.bounds.getCenter());
        this.map.setZoom(2);
        this.options.zoomlevel = 2;
		
    },
	
    zoomOut: function() {
		
        //GLog.write(paragraphs);
        //if(this.numMarkers > 6){
        this.map.zoomOut();
		
    },
	
    getZoomLevel: function() {
        return this.options.zoomlevel;
    },
	
    getMapType: function() {
        return this.map.getCurrentMapType();
    },
	
    setFormHolder: function(elm) {
        this.formHolder = elm;
    },
	
    addMarkers: function(aMarkers) {
        this.allMarkerRegistry = [];
        this.currentMarkerRegistry = [];
        this.allGMarkers = [];
        this.markerBaseIcon = new GIcon(G_DEFAULT_ICON);
        this.markerBaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        this.markerBaseIcon.iconSize = new GSize(24, 34);
        this.markerBaseIcon.shadowSize = new GSize(41, 34);
        this.markerManager.clearMarkers();
        this.markerManager.refresh();
        $each(aMarkers, function(location, index) {
            
            var latlng = new GLatLng(location.Latitude,location.Longitude);
            var newMarker = new GMarker(latlng, {
                draggable: false,
                icon: this.markerBaseIcon,
                bouncy: true,
                autopan:true
            });
            GEvent.addListener(newMarker, "click", function() {
                newMarker.openInfoWindowHtml( '<div style="width:250px;">' +
                    '<div class="blocktTitle"><h3>' + location.title + ' </h3></div>' +
                    '<div class="block content"><p> ' +
                    '<img src="/Files/Image/get/hash/'+location.image_hash+'/width/50/height/50" width="50" border="0" style="float:left; padding:0px 5px 5px 0;" />' +
                    location.gmaps_text +
                    '</p>' +
                    '<p class="buttonFront"><span><a href="'+location.url_segment+'" title="Klik hier om het profiel te openen">Open profiel</a></span></p>' +
                    '</div>' + location.categories + '</div>');
            });
            
            this.allMarkerRegistry.push(location);
            this.currentMarkerRegistry.push(location);
            this.allGMarkers.push(newMarker);
            
        }, this);
        this.markerManager.addMarkers(this.allGMarkers, 0);
        this.markerManager.refresh();
    },

    addMarker: function(location) {
        this.markerBaseIcon = new GIcon(G_DEFAULT_ICON);
        this.markerBaseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        this.markerBaseIcon.iconSize = new GSize(24, 34);
        this.markerBaseIcon.shadowSize = new GSize(41, 34);

        var latlng = new GLatLng(location.Latitude,location.Longitude);
        var newMarker = new GMarker(latlng, {
            draggable: false,
            icon: this.markerBaseIcon,
            bouncy: true,
            autopan:true
        });
        GEvent.addListener(newMarker, "click", function() {
            newMarker.openInfoWindowHtml( '<div style="width:250px;">' +
                '<div class="blocktTitle"><h3>' + location.title + ' </h3></div>' +
                '<div class="block content"><p> ' +
                '<img src="/Files/Image/get/hash/'+location.image_hash+'/width/50/height/50" width="50" border="0" style="float:left; padding:0px 5px 5px 0;" />' +
                location.gmaps_text +
                '</p>' +
                '<p class="buttonFront"><span><a href="'+location.url_segment+'" title="Klik hier om het profiel te openen">Open profiel</a></span></p>' +
                '</div>' + location.categories + '</div>');
        });
        this.currentMarkerRegistry.push(location);
        this.allGMarkers.push(newMarker);
        this.markerManager.addMarker(newMarker, 0);
        this.markerManager.refresh();
    },
	
    generateMap: function() {
        var divContainer	= new Element('div').setProperty('id','container');
        var divMessage 		= new Element('div').setProperty('id','message').inject(divContainer);
        var divContent 		= new Element('div').setProperty('id','MapContent').inject(divContainer);
        var divMapContainer = new Element('div').setProperty('id','mapContainer').inject(divContent);
		
        return divContainer;
    },
	
    resize: function() {
        this.map.checkResize();
    }
	
});

ds_Plugin_Gmaps.implement(new Options);
