// ******************************************************************************
// Global Constants and Variables
// ******************************************************************************

var baseURL = document.getElementsByTagName('base')[0].href;



// ******************************************************************************
// Main Classes
// ******************************************************************************

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

	// ******************************************************************************
	// Constants
	// ******************************************************************************
	Version : '0.8',

	// dom ids
	mapCanvasId : 'dfgooglemap_canvas',

	searchFormId : 'dfgooglemap_searchForm',
	searchInputId : 'dfgooglemap_fromAddress',
	directionsWrapId : 'dfgooglemap_directionsWrap',
	directionsId : 'dfgooglemap_directions',
	printLinkId : 'dfgooglemap_printLink',

	// ******************************************************************************
	// vars
	// ******************************************************************************
	resPath : '',

	map : null,

	mapCenterLatDefault : 50.248961,
	mapCenterLngDefault : 8.069458,
	mapZoomDefault : 11,

	mapCenterLat : null,
	mapCenterLng : null,
	mapCenter : null,
	mapZoom : null,

	mapTypes : {
	    normal : true,
	    satelite : true,
	    hybrid : true,
	    physical : false
	},


	geocoder : null,
	geocoderBounds : {
	    sw : {lat : 47.33882269482199, lng : 5.6689453125},
	    ne : {lat : 47.33882269482199, lng : 5.6689453125}
	},

	icons : {
	    icon_center : {}
	},

	gdir : {},



	// dom Elements
	form : null,
	searchForm : null,

	sword : '',
	fromAddress : '',
	toAddress : '',

	// ******************************************************************************
	// Constructor
	// ******************************************************************************
	initialize: function(options) {
       	if((typeof Prototype=='undefined') ||
	    	(typeof Element == 'undefined') ||
	   	    (typeof Element.Methods=='undefined') ||
        	parseFloat(Prototype.Version.split(".")[0] + "." +
	           Prototype.Version.split(".")[1]) < 1.6)
	   		    throw('Google Maps benötigt das Prototype JavaScript framework >= 1.6.0');

		if (GBrowserIsCompatible() == false) {
			throw('Google Maps kann nicht Initialiert werden');
		}

		Object.extend(this, options);

//		document.observe('dom:loaded', this.pageLoadHandler.bind(this), false);
	    Event.observe(window, 'load', this.pageLoadHandler.bind(this), false);
   	},




	pageLoadHandler: function() {


	    // init Map
	    this.map = new GMap2($(this.mapCanvasId));
	    //GEvent.addListener(this.map, 'load', this.mapLoadHandler.bind(this));


            this.map.addControl(new GSmallMapControl());
            //this.map.addControl(new GOverviewMapControl());


	    if(this.mapTypes.normal == true) {
		this.map.addMapType(G_NORMAL_MAP);
	    } else {
		this.map.removeMapType(G_NORMAL_MAP);
	    }
	    if(this.mapTypes.satelite == true) {
		this.map.addMapType(G_SATELLITE_MAP);
	    } else {
		this.map.removeMapType(G_SATELLITE_MAP);
	    }
	    if(this.mapTypes.hybrid == true) {
		this.map.addMapType(G_HYBRID_MAP);
	    } else {
		this.map.removeMapType(G_HYBRID_MAP);
	    }
	    if(this.mapTypes.physical == true) {
		this.map.addMapType(G_PHYSICAL_MAP);
	    } else {
		this.map.removeMapType(G_PHYSICAL_MAP);
	    }
	    this.map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5, 5)));

	    this.map.setMapType(G_HYBRID_MAP);


	    this.mapCenterLat = this.mapCenterLatDefault;
	    this.mapCenterLng = this.mapCenterLngDefault;
      	    this.mapZoom = this.mapZoomDefault;
	    this.center = new GLatLng(this.mapCenterLat, this.mapCenterLng);
      	    this.map.setCenter(this.center, this.mapZoom);


	    this.map.enableScrollWheelZoom();
	    this.map.enableContinuousZoom();



	    // init geocoder
	    /*
	     * wird nur bei addresssuchen benötigt
	    var sw = new GLatLng(this.geocoderBounds.sw.lat , this.geocoderBounds.sw.lng);
	    var ne = new GLatLng(this.geocoderBounds.ne.lat , this.geocoderBounds.ne.lng);
	    var bounds = new GLatLngBounds(sw, ne);
	    this.geocoder = new GClientGeocoder();
	    this.geocoder.setBaseCountryCode('de');
	    this.geocoder.setViewport(bounds);
	     */


	    // init center icon
	    icon_center = new GIcon();
	    icon_center.image = baseURL + this.resPath  + 'pix/DFIcon.png';
            icon_center.iconSize = new GSize(28, 28);
            icon_center.iconAnchor = new GPoint(14, 14);
            icon_center.infoWindowAnchor = new GPoint(14, 14);
	    icon_center.shadow = baseURL + this.resPath  + 'pix/DFIconShadow.png';
    	    icon_center.shadowSize = new GSize(37, 37);
    	    this.icons.icon_center = icon_center;


	    // add Marker
	    var marker = new GMarker(new GLatLng(50.086005, 8.234993), this.icons.icon_center);
	    GEvent.addListener(marker, "click", function() {
              var html = '<div style="font-weight: bold; font-size: medium; margin-bottom: 0em;">Die Firma GmbH</div>';

              marker.openInfoWindow(html);
            });
	    this.map.addOverlay(marker);


            //var geoXml = new GGeoXml(baseURL + this.resPath  + 'df.kml');


            this.geoXml = new GGeoXml('http://www.diefirma.de/' + this.resPath +'df.kml');
            this.map.addOverlay(this.geoXml);



	    // directions object
	    this.gdir = new GDirections(this.map, $(this.directionsId));
	    GEvent.addListener(this.gdir, 'error', this.gdirHandleErrors.bindAsEventListener(this));
	    GEvent.addListener(this.gdir, 'load', this.gdirLoad.bindAsEventListener(this));


	    GEvent.addListener(this.map, 'zoomend', this.zoomHandler.bind(this));


	    // ******************************************************************************
	    // Search und filter form
	    this.searchForm = $(this.searchFormId);
	    Event.observe(this.searchForm, 'submit', this.submitHandler.bindAsEventListener(this), false);
	    Event.observe(this.printLinkId, 'click', this.printMap.bindAsEventListener(this), false);

    },

    iconHandler : function(){


        this.map.removeOverlay(this.geoXml);

    },


    zoomHandler : function(oldLevel,  newLevel){

	if (newLevel < 16) {
            this.map.removeOverlay(this.geoXml);
	} else {
            this.map.addOverlay(this.geoXml);
	}

    },


    mapLoadHandler : function(){
    },


    submitHandler : function(ev){
	ev.stop();


	this.fromAddress = $(this.searchInputId).value;

	if(this.fromAddress != '')
	{

	    // Adress optimierung
	    //this.fromAddress = this.fromAddress.replace(/ ?deutschland ?| ?germany ?/gi, '') + ', Germany';
	    //this.geocoder.getLocations(address, this.getLocations.bind(this));

	    dirString = 'from: ' + this.fromAddress + ' to: ' + this.toAddress;
	    this.gdir.load(dirString, {'locale' :'de_DE'});

	} else {

	    alert('Bitte geben Sie in das Feld "Startadresse" Ihre Startadresse ein und klicken Sie zum Berechnen der Route auf die Schaltfläche "Anfahrt anzeigen".');
	}

    },


    gdirHandleErrors : function(ev){

	$(this.directionsWrapId).hide();

	   if (this.gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("Ihre Startadresse konnte leider nicht gefunden werden. Entweder ist ihre Startadresse relativ neu oder sie ist inkorrekt.");
	   else if (this.gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + this.gdir.getStatus().code);

	   else if (this.gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + this.gdir.getStatus().code);

	   else if (this.gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + this.gdir.getStatus().code);

	   else if (this.gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + this.gdir.getStatus().code);

	   else alert("An unknown error occurred.");

    },


    gdirLoad : function(ev){
	$(this.directionsWrapId).show();
    },


    printMap : function(ev) {
	ev.stop();
	var url = "http://maps.google.de/maps" + "?saddr=" + escape(this.utf8encode(this.fromAddress)) + "&daddr=" + escape(this.utf8encode(this.toAddress)) + "&z=" + this.map.getZoom() + "&ie=UTF8&pw=2";
	window.open(url, "map", "width=800,height=800,toolbar=no,scrollbars=yes,addressbar=yes,status=no");
    },



    utf8encode : function(string) {
	string = string.replace(/\r\n/g,"\n");
	var utftext = "";
	for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
		utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
		utftext += String.fromCharCode((c >> 6) | 192);
		utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
		utftext += String.fromCharCode((c >> 12) | 224);
		utftext += String.fromCharCode(((c >> 6) & 63) | 128);
		utftext += String.fromCharCode((c & 63) | 128);
            }
	}
	return utftext;
    }
};







