/// <reference path="../_references.js" />


function isMobile() {
    var isMobile = false;
    if (navigator.userAgent.match(/iPhone/i)) { isMobile = true; }
    if (navigator.userAgent.match(/iPod/i)) { isMobile = true; }
    if (navigator.userAgent.match(/iPad/i)) { isMobile = true; }
    if (navigator.userAgent.match(/Android/i)) { isMobile = true; }
    return isMobile
}

var mapBuilder = function () {
    this.id = "";
    this.mapContainer = $();
    this.map = null;
    this.markers = [];
    this.distance = 20;

    this.initComplete = false;

    this.monitorBounds = true;

    this.activeData = null;
    this.activeOptions = null;

    this.categorySearch = null;
    this.locationSearch = null;

    this.initFunctions = [];

    this.listmode = false;

    this.category = null;   // Aktive Kategorie Id
    this.location = null;   // Aktiver Standort (kann LatLng, GeoId oder Suchbegriff sein)
}

mapBuilder.prototype.init = function (id, options) {
    var base = this;
    this.id = id;
    this.mapContainer = $("#" + id);

    $(document).ready(function () {
        base.ensureGoogleFrameworkLoaded(function () {
            base.initMap();
            base.loadData(options);
            //google.load("maps", "3", {
            //    callback: function () {
            //        base.initMap();
            //        base.loadData(options);
            //    }
            //});
        });
    });

}


function thisTouchStart(e) {
    dragFlag = true;
    start = e.touches[0].pageY;
}

function thisTouchEnd() {
    dragFlag = false;
}

function thisTouchMove(e) {
    if (!dragFlag) return;
    end = e.touches[0].pageY;
    window.scrollBy(0, (start - end));
}


mapBuilder.prototype.ensureGoogleFrameworkLoaded = function (callback) {
    if (typeof google == "undefined") {
        googleLoaded = function () {
            callback();
        }
        $.getScript("https://maps.googleapis.com/maps/api/js?key=AIzaSyCRG3JVUuge5FdgFxQrmtitvotYeFXOj0A&callback=googleLoaded");

        //$.getScript("https://www.google.com/jsapi?key=AIzaSyCRG3JVUuge5FdgFxQrmtitvotYeFXOj0A&callback=googleLoaded");
    } else {
        callback();
    }
}

mapBuilder.prototype.initMap = function () {
    //console.log("initmap: ")
    var base = this;
    //var centerDefault = new google.maps.LatLng(51.041433, 9.5103863);
    var centerDefault = new google.maps.LatLng(49.934441, 7.89449);
    base.loadExtensions();

    var myOptions = {
        gestureHandling: 'cooperative',
        zoom: 16,
        center: centerDefault,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        //scrollwheel: true,
        panControl: true,
        //zoomControl: true,
        mapTypeControl: true,
        scaleControl: true,
        streetViewControl: false,
        gestureHandling: 'cooperative',
        overviewMapControl: true,
        styles:
            //[{ "featureType": "administrative", "elementType": "all", "stylers": [{ "visibility": "on" }, { "lightness": 33 }] }, { "featureType": "landscape", "elementType": "all", "stylers": [{ "color": "#f2e5d4" }] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [{ "color": "#c5dac6" }] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [{ "visibility": "on" }, { "lightness": 20 }] }, { "featureType": "road", "elementType": "all", "stylers": [{ "lightness": 20 }] }, { "featureType": "road.highway", "elementType": "geometry", "stylers": [{ "color": "#c5c6c6" }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "color": "#e4d7c6" }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "color": "#fbfaf7" }] }, { "featureType": "water", "elementType": "all", "stylers": [{ "visibility": "on" }, { "color": "#acbcc9" }] }]

            [
  {
  	"stylers": [
      {
      	"saturation": 90
      }
  	]
  },
  {
  	"elementType": "geometry",
  	"stylers": [
      {
      	"color": "#ffffff"
      }
  	]
  },
  {
  	"elementType": "labels.icon",
  	"stylers": [
      {
      	"visibility": "off"
      }
  	]
  },
  {
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#616161"
      }
  	]
  },
  {
  	"elementType": "labels.text.stroke",
  	"stylers": [
      {
      	"color": "#f5f5f5"
      }
  	]
  },
  {
  	"featureType": "administrative",
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#512a86"
      }
  	]
  },
  {
  	"featureType": "administrative",
  	"elementType": "labels.text.stroke",
  	"stylers": [
      {
      	"color": "#ffffff"
      }
  	]
  },
  {
  	"featureType": "poi",
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#757575"
      }
  	]
  },
  {
  	"featureType": "poi.park",
  	"elementType": "geometry",
  	"stylers": [
      {
      	"color": "#e5e5e5"
      }
  	]
  },
  {
  	"featureType": "poi.park",
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#9e9e9e"
      }
  	]
  },
  {
  	"featureType": "road",
  	"elementType": "geometry",
  	"stylers": [
      {
      	"color": "#edd6de"
      }
  	]
  },
  {
  	"featureType": "road",
  	"elementType": "geometry.stroke",
  	"stylers": [
      {
      	"weight": 0.5
      }
  	]
  },
  {
  	"featureType": "road.arterial",
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#757575"
      }
  	]
  },
  {
  	"featureType": "road.highway",
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#616161"
      }
  	]
  },
  {
  	"featureType": "road.local",
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#9e9e9e"
      }
  	]
  },
  {
  	"featureType": "transit.line",
  	"elementType": "geometry",
  	"stylers": [
      {
      	"color": "#e5e5e5"
      }
  	]
  },
  {
  	"featureType": "transit.station",
  	"elementType": "geometry",
  	"stylers": [
      {
      	"color": "#eeeeee"
      }
  	]
  },
  {
  	"featureType": "water",
  	"elementType": "geometry",
  	"stylers": [
      {
      	"color": "#a3c7db"
      }
  	]
  },
  {
  	"featureType": "water",
  	"elementType": "labels.text.fill",
  	"stylers": [
      {
      	"color": "#9e9e9e"
      }
  	]
  }
            ]

        //[{ "elementType": "labels.text", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape.natural", "elementType": "geometry.fill", "stylers": [{ "color": "#f5f5f2" }, { "visibility": "on" }] }, { "featureType": "administrative", "stylers": [{ "visibility": "off" }] }, { "featureType": "transit", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.attraction", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape.man_made", "elementType": "geometry.fill", "stylers": [{ "color": "#ffffff" }, { "visibility": "on" }] }, { "featureType": "poi.business", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.medical", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.place_of_worship", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.school", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi.sports_complex", "stylers": [{ "visibility": "off" }] }, { "featureType": "road.highway", "elementType": "geometry", "stylers": [{ "color": "#ffffff" }, { "visibility": "simplified" }] }, { "featureType": "road.arterial", "stylers": [{ "visibility": "simplified" }, { "color": "#ffffff" }] }, { "featureType": "road.highway", "elementType": "labels.icon", "stylers": [{ "color": "#ffffff" }, { "visibility": "off" }] }, { "featureType": "road.highway", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "road.arterial", "stylers": [{ "color": "#ffffff" }] }, { "featureType": "road.local", "stylers": [{ "color": "#ffffff" }] }, { "featureType": "poi.park", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "poi", "elementType": "labels.icon", "stylers": [{ "visibility": "off" }] }, { "featureType": "water", "stylers": [{ "color": "#71c8d4" }] }, { "featureType": "landscape", "stylers": [{ "color": "#e5e8e7" }] }, { "featureType": "poi.park", "stylers": [{ "color": "#8ba129" }] }, { "featureType": "road", "stylers": [{ "color": "#ffffff" }] }, { "featureType": "poi.sports_complex", "elementType": "geometry", "stylers": [{ "color": "#c7c7c7" }, { "visibility": "off" }] }, { "featureType": "water", "stylers": [{ "color": "#a0d3d3" }] }, { "featureType": "poi.park", "stylers": [{ "color": "#91b65d" }] }, { "featureType": "poi.park", "stylers": [{ "gamma": 1.51 }] }, { "featureType": "road.local", "stylers": [{ "visibility": "off" }] }, { "featureType": "road.local", "elementType": "geometry", "stylers": [{ "visibility": "on" }] }, { "featureType": "poi.government", "elementType": "geometry", "stylers": [{ "visibility": "off" }] }, { "featureType": "landscape", "stylers": [{ "visibility": "off" }] }, { "featureType": "road", "elementType": "labels", "stylers": [{ "visibility": "off" }] }, { "featureType": "road.arterial", "elementType": "geometry", "stylers": [{ "visibility": "simplified" }] }, { "featureType": "road.local", "stylers": [{ "visibility": "simplified" }] }, { "featureType": "road" }, { "featureType": "road" }, {}, { "featureType": "road.highway" }]

        //,
        //styles: [
        //    {
        //        featureType: "landscape",
        //        stylers: [{ "visibility": "on" }, { "lightness": 100 }]
        //    }, {
        //        featureType: "poi",
        //        elementType: "geometry",
        //        stylers: [{ "visibility": "on" }, { "saturation": -100 }, { "lightness": 100 }]
        //    }, {
        //        featureType: "road",
        //        stylers: [{ "weight": 0.3 }, { "lightness": 50 }, { "saturation": -100 }, { "hue": "#ef4d57" }, { "visibility": "on" }]
        //    }, {
        //        featureType: "transit",
        //        stylers: [{ "visibility": "on" }, { "saturation": -100 }]
        //    }, {
        //        featureType: "water",
        //        stylers: [{ "saturation": -84 }, { "hue": "#9e9890" }]
        //    }, {
        //        featureType: "administrative.country",
        //        stylers: [{ "visibility": "on" }, { "hue": "#ef4d57" }, { "saturation": -100 }, { "lightness": 50 }]
        //    }, {
        //        featureType: "administrative.province",
        //        stylers: [{ "visibility": "off" }]
        //    }, {
        //        featureType: "administrative.locality",
        //        stylers: [{ "visibility": "on" }, { "hue": "#ef4d57" }, { "lightness": 28 }, { "saturation": -100 }]
        //    }, {
        //        featureType: "poi",
        //        elementType: "labels", "stylers": [{ "saturation": -100 }]
        //    }
        //]

    }

    var map = new google.maps.Map(document.getElementById(base.id), myOptions);
    base.map = map;

    //if (isMobile()) {
    //    document.getElementById(base.id).addEventListener("touchstart", thisTouchStart, true);
    //    document.getElementById(base.id).addEventListener("touchend", thisTouchEnd, true);
    //    document.getElementById(base.id).addEventListener("touchmove", thisTouchMove, true);
    //}

    base.initComplete = true;

    $.each(base.initFunctions, function (idx, func) {
        func();
    });

    base.initFunctions = [];
}

mapBuilder.prototype.ready = function (func) {
    if (!this.initComplete) {
        this.initFunctions.push(func);
    } else {
        setTimeout(func, 200);
    }
}

mapBuilder.prototype.loadData = function (options) {
    var base = this;

    options = $.extend({
        center: true
    }, options);

    base.activeOptions = options;

    if (options.remoteMode) {

        // Remote Data
        base.getData("/locationData/GetLocations", options, function (data) {
            base.activeData = data;
            base.loadMarkers(data.locations);
        });

    } else {
        //console.log("local")
        // Local Data
        base.activeData = options.data;
        base.loadMarkers(options.data);

    }
}

mapBuilder.prototype.loadMarkers = function (results) {
    var base = this;
    var map = base.map;

    base.monitorBounds = false;

    $.each(base.markers, function (mIdx, m) {
        m.setMap(null);
    });
    base.markers = [];
	console.log("loadmarker")
    if (results.length > 0) {
        // Marker laden
        var bounds = new google.maps.LatLngBounds();
        var markers = [];
        $.each(results, function (rIdx, r) {
            var marker = base.setMarker(r);
            bounds.extend(marker.getPosition());
            markers.push(marker);
        });
		
        if (results.length > 1) {
        	//map.fitBounds(bounds);
        	//map.setZoom(5);

            google.maps.event.addDomListener(window, 'resize', function () {
                map.setCenter(map.fitBounds(bounds));
            });

            $("#imgMap").css("display", "none");

        } else {
            map.setCenter(markers[0].getPosition());
            //map.setZoom(10);

            google.maps.event.addDomListener(window, 'resize', function () {
                map.setCenter(markers[0].getPosition());
            });

        }

    }

    base.monitorBounds = true;
}

mapBuilder.prototype.setMarker = function (result) {
    var base = this;
    var map = base.map;
    var makerLatLng = new google.maps.LatLng(result.lat, result.lng);

    var markerIcon = "/frontend/images/marker-red.png";
    var markerIcon2 = "/frontend/images/marker-red2.png";

	//if (base.activeOptions.useAreaIcons) {
    //    if (result.typ == '22d3503d-9d67-4427-9340-ca804343b1c8') {
    //        // Bauplatz
    //        markerIcon = "/frontend/images/mapicon_bauplatz.gif";
    //    }
    //    else if (result.typ == '3b5c1783-1108-46a5-b102-24641b7be0ef') {
    //        // Freifläche
    //        markerIcon = "/frontend/images/mapicon_feiflaeche.gif";
    //    }
    //    else if (result.typ == '7de04f5b-decc-466b-97e7-8f653794cec5') {
    //        // Immobilie
    //        markerIcon = "/frontend/images/mapicon_immobilie.gif";
    //    }        
    //}

    $("#imgMap").attr("src", "https://maps.googleapis.com/maps/api/staticmap?center=" + result.lat + "," + result.lng + "&zoom=20&size=700x330&maptype=roadmap&markers=color:blue|" + result.lat + "," + result.lng + "&key=AIzaSyCRG3JVUuge5FdgFxQrmtitvotYeFXOj0A")

    var marker = new google.maps.Marker({
        position: makerLatLng,
        icon: result.icon,
        map: map
    });
    base.markers.push(marker);


    var url;
    var infoWindow;

    if (result.ort == "Parkplatz") {
    	url = "https://www.google.de/maps/dir//Rheinstra%C3%9Fe,+55424+M%C3%BCnster-Sarmsheim/@49.9340394,7.8934203,255m/data=!3m1!1e3!4m8!4m7!1m0!1m5!1m1!1s0x47bdefed607b2269:0x741e26067d45f484!2m2!1d7.8939759!2d49.9340385";
        infoWindow = new google.maps.InfoWindow({
            content:
                '<div>Parkplatz</div><div>55424 Münster-Sarmsheim</div>' +
                '<a class="map-link" href="' + url + '" target="_blank">Navigation starten</a>',
            padding: 20
        });
      
    }
    else {
    	url = "https://www.google.de/maps/place/CULTBETTEN/@49.9348009,7.8949099,257m/data=!3m2!1e3!4b1!4m15!1m9!4m8!1m0!1m6!1m2!1s0x47bdefed48b04b5f:0x8dd3a5b55db13690!2sUnnamed+Road,+55424+M%C3%BCnster-Sarmsheim!2m2!1d7.8952565!2d49.9346678!3m4!1s0x47bdefed49a64785:0x1d2920151a118146!8m2!3d49.9348!4d7.89547";
        infoWindow = new google.maps.InfoWindow({
            content:
                '<div>Das Wasserwerk</div><div>55424 Münster-Sarmsheim</div>' ,
                //'<a class="map-link" href="' + url + '" target="_blank">Navigation starten</a>',
            padding: 20
        });
    }

    marker.addListener('click', function () {
        infoWindow.open(map, marker);
    });
    //google.maps.event.addListener(marker, 'click', function () {
    //    //var detailUrl = "/stm/GetDetails";
    //    //if (base.activeOptions.detailUrl) {
    //    //    detailUrl = base.activeOptions.detailUrl;
    //    //}

    //    //base.getData(detailUrl, {
    //    //    id: result.id
    //    //}, function (details) {
    //    //    base.infoWindow.setContent(details.content);
    //    //    base.infoWindow.open(map, marker);

    //    //    map.panToWithOffset(marker, 0, -100);
    //    //});
    //    base.infoWindow.open(map, marker);

    //    map.panToWithOffset(marker, 0, -100);
    //});


    return marker;
}

mapBuilder.prototype.geoLocationSuccess = function (e) {
    var base = this;

    var latLng = e.coords.latitude + "," + e.coords.longitude;

    // Location ermittelt, Position in Text umwandeln und in Suchfeld schreiben
    base.getData("/locationData/ResolvePosition", { q: latLng }, function (result) {
        base.locationSearch.txt.val(result.name);
        base.locationSearch.txt.attr("data-text", result.postcode);

        // Suche mit LatLng durchführen
        base.location = result.id;
        base.doSearch();
    });

}

mapBuilder.prototype.getData = function (url, data, callback) {
    $.ajax({
        url: url,
        method: "POST",
        data: data,
        datatype: "json",
        success: callback
    });
}

mapBuilder.prototype.loadExtensions = function () {

    google.maps.Map.prototype.panToWithOffset = function (marker, offsetX, offsetY) {
        var map = this;
        var ov = new google.maps.OverlayView();
        ov.onAdd = function () {
            var proj = this.getProjection();
            var latlng = marker.getPosition();
            var aPoint = proj.fromLatLngToContainerPixel(latlng);
            aPoint.x = aPoint.x + offsetX;
            aPoint.y = aPoint.y + offsetY;
            map.panTo(proj.fromContainerPixelToLatLng(aPoint));
        };
        ov.draw = function () { };
        ov.setMap(this);
    };


}

mapBuilder.prototype.isMobile = function () {
    return $("#mobilenavButton").is(":visible");
}