// Map Function: require google maps api and mootools

/* USAGE:
<div id="map" style="width: 600px; height: 400px"></div>
<script type="text/javascript">
var map = new MapClass('map');

map.hook_.... = function(...) {
    this.map.xxx...
};

HOOKS:
 hook_map_changedbounds()     ... after pan-ing or zooming
 hook_map_click(marker,point) ... when clicking on map (not on marker!)
 hook_marker_click(marker)    ... when clicking on marker
 hook_marker_dragend(marker)  ... after dragging marker
 hook_markers_loaded(json)    ... after ajax_load_mappoints finishes

*/

var MapClass = Class.create();
MapClass.prototype = {

    initialize: function(element_id, x, y, z) {
      if( x == undefined ) x=16.3543;
      if( y == undefined ) y=48.2284;
      if( z == undefined ) z=12;
      if (GBrowserIsCompatible()) {
        this.element_id = element_id;
        this.map_markers = Array();
        //this.mm = GMarkerManager(this);
        this.geocoder = new GClientGeocoder();
        this.map = new GMap2(document.getElementById(this.element_id));
        window.onunload = GUnload;
        this.map.enableContinuousZoom();
        this.geocoder = new GClientGeocoder();
        this.map.setCenter(new GLatLng(y,x), z);
        this.map.addControl(new GSmallMapControl());
        //map.addControl(new GMapTypeControl());

        GEvent.addListener(this.map, "moveend", this.event_map_moveend.bind(this) );
        GEvent.addListener(this.map, "click", this.event_map_click.bind(this) );
        GEvent.addDomListener($(this.element_id), "DOMMouseScroll", this.wheelZoom.bind(this)); // Firefox
        GEvent.addDomListener($(this.element_id), "mousewheel", this.wheelZoom.bind(this)); // IE 
      }
    },

    event_map_moveend: function() {
        this.center = this.map.getCenter();
        if (this.hook_map_changedbounds) this.hook_map_changedbounds();
    },
    
    event_map_click: function(marker, point) {
        if (!marker) {
            if (this.hook_map_click) this.hook_map_click(marker,point);
        }
    },
    
    event_marker_click: function(marker) {
            //marker.openInfoWindowHtml('<div class="MarkerInfoWindow"><h1>'+marker.mytitle+'</h1>'+marker.mydescription);
            $('pop_title').innerHTML = marker.mytitle;
            $('pop_description').innerHTML = marker.mydescription;
            for(i=0; i<this.map_markers.length; i++) {
               this.map_markers[i].setImage('http://labs.google.com/ridefinder/images/mm_20_blue.png');
            }
            marker.setImage('http://labs.google.com/ridefinder/images/mm_20_green.png');
            //    '<div class="mappointDescription">'+marker.mydescription+'</div>'+
            //    '<div class="mappointActions">Aktion: '+
            //    '<a href="javascript:void(0);">L&ouml;schen</a> | '+
            //    '<a href="javascript:void(0);" onclick="GMarker.openInfoWindowHtml(\'bla\').bind(marker);">Bearbeiten</a>'+
            //    '</div>');
            if (this.hook_marker_click) this.hook_marker_click(marker);
    },
    
    event_marker_dragstart: function(marker) {
        this.map.closeInfoWindow();
    },
    
    event_marker_dragend: function(marker) {
        if (this.hook_marker_dragend) this.hook_marker_dragend(marker);
    },

    showAddress: function(address) {
        this.geocoder.getLatLng( address, this.showAddress_cb.bind(this,address) );
    },
    showAddress_cb: function(address,point) {
            if (!point) {
                alert("Adresse '"+address + "' wurde leider nicht gefunden.");
            } else {
                this.map.setCenter(point, 13);
                if (this.search_address_marker==undefined) {
                    this.search_address_marker = new GMarker(point,{icon:this.get_marker_icon("purple")});
                }
                this.map.addOverlay(this.search_address_marker);
                this.search_address_marker.openInfoWindowHtml(address);
            }
    },

    saveMarker: function(dict) {
        this.ajax_save_mappoint(dict);
    },
    
    createMarker: function(p, text) {
        // create and save new marker
        var dict = { 'fields': {id:0, title:text, x:p.lng(), y:p.lat()}, own:1 };
        this.ajax_save_mappoint(dict,this.createMarker_cb.bind(this));
    },
    createMarker_cb: function(dict) {
        this.placeMarker(dict);
    },
    
    get_marker_icon: function(color) {
        var icon = new GIcon(G_DEFAULT_ICON)
        /*
	icon.image = "http://www.google.com/mapfiles/ms/icons/"+name+".png";
        icon.shadow = "http://www.google.com/mapfiles/ms/icons/msmarker.shadow.png";
        icon.iconSize = new GSize(32, 32);
        icon.shadowSize = new GSize(59, 32);
        icon.iconAnchor = new GPoint(15, 32);
        icon.imageMap = Array(8,2,24,2,24,30,8,30);
        icon.infoWindowAnchor = new GPoint(15, 12);
	*/
	icon.image = "http://labs.google.com/ridefinder/images/mm_20_"+color+".png";
	icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1); 
        return icon
    },

    placeMarker: function(dict,ico,drg) {
        // http://www.google.com/mapfiles/ms/icons/<coler><suffix>.png
        // suffixes: <none> -dot -pushpin
        // colors: red green blue ltblu purple pink
        if (ico==undefined) { ico='auto'; }
        if (drg==undefined) { drg=false; }
         
        var id = parseInt(dict['fields']['id']);
        var x = parseFloat(dict['fields']['x']);
        var y = parseFloat(dict['fields']['y']);
        var title = dict['fields']['title'];
        var description = dict['fields']['description'];
        var own = parseInt(dict['own']);
        if (ico=='auto') {
            if (own==1) {
                ico = "green";
                drg = true;
            } else {
                ico = "yellow";
                drg = false;
            }
            if (dict['fields']['ico']!=undefined) {
                ico = dict['fields']['ico'];
            }
        }
        var marker = new GMarker(new GLatLng(y,x), {draggable: drg, icon: this.get_marker_icon(ico) } );
        GEvent.addListener(marker, "click", this.event_marker_click.bind(this,marker) );
        if (own==1) {
            GEvent.addListener(marker, "dragstart", this.event_marker_dragstart.bind(this,marker) );
            GEvent.addListener(marker, "dragend", this.event_marker_dragend.bind(this,marker) );
        }
        marker.myid=id;
        marker.mytitle=title;
	marker.mydescription=description;
        marker.myown=own;
        if (dict['data']) marker.mydata = dict['data'];
        this.map_markers.push(marker);
        //this.mm.addMarker(marker);
        this.map.addOverlay(marker);
        return marker;
    },

    removeMarkers: function() {
        for(i=0; i<this.map_markers.length; i++) {
            this.map.removeOverlay(this.map_markers[i]);
        }
        this.map_markers = Array();
    },

    wheelZoom: function(e) {
        // Verhindern, dass beim Zoomen der Map die Seite gescrollt wird
        if(window.event) { event.returnValue = false; } // IE
        if(e.cancelable) { e.preventDefault(); } // DOM-Standard
        if (!e) { e = window.event; } // Event-Objekt für IE
        if (e.detail) { // Firefox
            if (e.detail < 0) { this.map.zoomIn(null, null, true); }
            else { this.map.zoomOut( null, true); }
        } else if (e.wheelDelta) { // IE
            if (e.wheelDelta > 0) { this.map.zoomIn(null, null, true); }
            else { this.map.zoomOut( null, true); }
        }
        if (this.hook_map_changedbounds) this.hook_map_changedbounds();
    },

    ajax_save_mappoint: function(dict,cb) {
        var req = new Ajax.Request('/maps/savepoint',{
            method: 'post',
            parameters: 'data='+ $H(dict).toJSON(),
            onSuccess: this.ajax_save_mappoint_cb.bind(this,cb,dict),
            onFailure: this.ajax_eb.bind(this)
            });
    },
    ajax_save_mappoint_cb: function(cb, dict, transport) {
        var json = transport.responseText.evalJSON(true);
        dict['fields']['id']=json['object_id']
        if (cb) { cb(dict); }
    },
    
    load_kml: function(url) {
        var kml = new GGeoXml(url,function() {
        	this.map.addOverlay(kml);
		}.bind(this));
    },
    
    ajax_load_mappoints: function(url) {
        var marker;
        var req = new Ajax.Request(url,{
            method: 'get',
            onSuccess: this.ajax_load_mappoints_cb.bind(this),
            onFailure: this.ajax_eb.bind(this)
            });
    },
    ajax_load_mappoints_cb: function(transport) {
        var json = transport.responseText.evalJSON(true);
        this.removeMarkers();
        for(i=0; i<json['points'].length; i++) {
            this.placeMarker(json['points'][i]);
        }
        if (this.hook_markers_loaded) this.hook_markers_loaded(json);
    },
    
    ajax_eb: function(transport) {
        alert(transport.responseText);
        // $('debug').setHTML(transport.responseText);
    }


}; // MapClass

function get_window_size() {
    var x,y;
    if (self.innerHeight) // all except Explorer
    {
        x = self.innerWidth;
        y = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
    {
        x = document.documentElement.clientWidth;
        y = document.documentElement.clientHeight;
    }
    else if (document.body) // other Explorers
    {
        x = document.body.clientWidth;
        y = document.body.clientHeight;
    }
    //document.getElementById("map").style.width = x - 250 + 'px';
    //document.getElementById("map").style.width = '540px';
    //document.getElementById("map").style.height = y - 120 + 'px';
    //document.getElementById("map").style.height = '375px';
    return([x,y])
}

