﻿
var map;
var geocoder;
var gmarkers = [];
var centralLocation;

var visibleInfoWindow = null;

var directionsDisplay = null;
var directionsService = null;

var defaultLocation = "Geben Sie ein wo Sie suchen wollen, z.B Frankfurt, Hochstrasse 16";

$(document).ready(function () {
    $("#txtLocationSearch").Watermark(defaultLocation);
});

function Initialize() {

    TogglePanel('location');

    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    var myLatLng = new google.maps.LatLng(50.776666799022095, 9.503069751806397);
    var myOptions = {
        scaleControl: true,
        zoom: 6,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    geocoder = new google.maps.Geocoder();
    var zoomLevel;

// Suche ueber die karte deaktiviert
//    google.maps.event.addListener(map, 'click', function(event) {
//        if (event.latLng) {
//            ClearAllMarkers();
//            SearchChurches(event.latLng.lat(), event.latLng.lng());
//        }
    //    });



    SearchHttpGet();
}


function SearchHttpGet() {
    var loc = GeocodeAddress(document.getElementById('ctl00_MainContentPlaceholer_txtLocationHidden').value);
    if (loc != null && loc != "") {
        document.getElementById('txtLocationSearch').value = document.getElementById('ctl00_MainContentPlaceholer_txtLocationHidden').value;
        ChurchesNearAddress();
    }
}

function GenerateTriggerCallback(object, eventType) {
    return function() {
        google.maps.event.trigger(object, eventType);
    };
}

function OpenInfoWindow(marker, infoWindow) {
    // Close the last selected marker before opening this one.
    if (visibleInfoWindow) {
        visibleInfoWindow.close();
    }

    infoWindow.open(map, marker);
    visibleInfoWindow = infoWindow;

}

function EnsureAllMarkersVisible(markers) {
    var bounds = new google.maps.LatLngBounds(null, null);
    for (var i = 0; i < markers.length; i++) {
        var currentMarker = markers[i];
        bounds.extend(currentMarker.getPosition());
    }
    map.fitBounds(bounds);
}

function AttachInfowindow(marker, content) {

    var infowindow = new google.maps.InfoWindow(
            {
                content: content,
                size: new google.maps.Size(50, 50)
            });

    google.maps.event.addListener(marker, 'click', function() {
        OpenInfoWindow(marker, infowindow);
    });
}

function GeocodeAddress(address) {
    if (geocoder) {
        geocoder.geocode({ 'address': address }, function(results, status) {

            HideMessage("addressnotFound");
            if (status == google.maps.GeocoderStatus.OK
                && status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                centralLocation = results[0].geometry.location;
                map.setCenter(centralLocation);
                SearchChurches(centralLocation.lat(), centralLocation.lng());
            } else {
                ShowMessage("addressnotFound", "Die eingegebene Adresse konnte nicht gefunden werden.", "errormsg");
            }
        });
    }
}

function ShowMessage(id, text, cssClass) {
    msgDiv = document.getElementById("messages");
    var msg = document.createElement("div");
    msg.innerHTML = text;
    msg.setAttribute("id", id);
    if (cssClass != null && cssClass != '') { msg.setAttribute("class", cssClass); }
    msgDiv.appendChild(msg);
    $('#' + id).hide();
    $('#' + id).fadeIn(250)
}

function HideMessage(id) {
    id = '#' + id;
    $(id).fadeOut(100);
    $(id).remove();
}

function ChurchesNearAddress() {
    var loc = GeocodeAddress(document.getElementById('txtLocationSearch').value);
}

function SearchChurches(lat, lng) {
    ResetSearch();
    var image = 'http://maps.google.com/mapfiles/arrow.png';
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        title: "Ausgangspunkt",
        clickable: true,
        icon: image
    });
    gmarkers.push(marker);
    var radius = 75000;
    PageMethods.ProximitySearch(lat, lng, radius, SearchChurches_Callback, SearchChurches_OnFailed);
}

function SearchChurches_Callback(result) {
    HideMessage("proximityFailed");
    if (result.length == 0) {
        ShowMessage("proximityFailed", "Es wurden keine Gemeinden im Umkreis gefunden.", "warningmsg");
    }
    else {
        SetMarkers(map, result);
        EnsureAllMarkersVisible(gmarkers);
    }
}

function SearchChurches_OnFailed(error) {
    ShowMessage("proximityFailed", "Aufgrund eines Programmfehlers wurden keine Ergebnisse gefunden. Bleibt der Fehler bestehen probieren Sie es bitte später noch einmal.", "errormsg");
}

function ClearAllMarkers() {
    for (var i = 0; i < this.gmarkers.length; i++) {
        this.gmarkers[i].setMap(null);
    }
    gmarkers = [];
}

function ResetSearch() {
    ClearAllMarkers();
    if (visibleInfoWindow) {
        visibleInfoWindow.close();
    }
    visibleInfoWindow = null;

    if (directionsDisplay != null) {
        directionsDisplay.setMap(null);
        directionsDisplay.setPanel(null);
    }

    $("#locationPanel").hide();
}

function ZoomToMarker(index) {
    var marker = gmarkers[index];
    map.setCenter(marker.getPosition());
    var currentZoomLevel = map.getZoom();
    if (currentZoomLevel < 19) {
        if (currentZoomLevel < 14) {
            map.setZoom(14);
        }
        else {
            map.setZoom(currentZoomLevel + 1);
        }
    }

}

function ShowDirection(index) {
    var marker = gmarkers[index];
    sidebarUl = document.getElementById("directionPanel");
    sidebarUl.innerHTML = '';
    CalculateRoute(centralLocation, marker.getPosition());
}

function DevineServiceElement(services) {

    var daysOfWeek = new Array("So.", "Mo.", "Di.", "Mi.", "Do.", "Fr.", "Sa.");

    var p = document.createElement("p");
    p.setAttribute("class", "devineService");


    var shedule = '';

    for (var y = 0; y < services.length; y++) {
        var currentService = services[y];
        shedule = shedule + daysOfWeek[currentService['Day']] + " " + currentService.Time.format("HH:mm") + " ";
    }

    p.innerHTML = shedule;

    return p;
}

function SetMarkers(map, churches) {

    sidebarUl = document.getElementById("locationPanel");
    sidebarUl.innerHTML = '';

    for (var i = 0; i < churches.length; i++) 
    {
        var currentChurch = churches[i];
        var letter = String.fromCharCode("A".charCodeAt(0) + i);
        var iconPath = "http://www.google.com/mapfiles/marker" + letter + ".png";
        var pos = new google.maps.LatLng(currentChurch['Coordinate']['Latitude'], currentChurch['Coordinate']['Longitude']);
        var marker = new google.maps.Marker({
            position: pos,
            map: map,
            title: currentChurch['Name'],
            icon: iconPath,
            clickable: true
        });


        var infoText = "<div class='infowindow'><h4>Gemeinde: " + currentChurch['Name'] + "</h4>"
             + "<p>" + currentChurch['Adress']['Street'] + "<br\>"
             + currentChurch['Adress']['Postcode'] + " " + currentChurch['Adress']['City'] + "<br\>"
             + currentChurch['Adress']['CountryName'] + "</p>"
             ;

        var zoomlink = '<a href="javascript:ZoomToMarker(' + (i + 1) + ');">heranzoomen</a>';
        var directionsLink = '<a href="javascript:ShowDirection(' + (i + 1) + ');">Anfahrt</a>';
        infoText += zoomlink + " " + directionsLink + "</div>";


        gmarkers.push(marker);
        AttachInfowindow(marker, infoText);


        //sidebar
        var addres = currentChurch['Adress']['Street'] + ', ' + currentChurch['Adress']['Postcode'] + ', ' + currentChurch['Adress']['City'];
        var li = document.createElement("li");

        //marker image
        var img = document.createElement("img");
        img.setAttribute("src", iconPath);
        img.setAttribute("class", "markerimage");

        //link
        var gemeinde = currentChurch['Name'];
        var markerA = document.createElement("a");
        markerA.onclick = GenerateTriggerCallback(marker, 'click');
        markerA.setAttribute("href", "#");
        markerA.appendChild(img);
        markerA.appendChild(document.createTextNode(gemeinde));
        markerA.setAttribute("class", "location");

        var service = DevineServiceElement(currentChurch['DevineServices']);

        //address
        li.appendChild(markerA);
        li.appendChild(document.createElement("br"));
        li.appendChild(document.createTextNode(addres));
        li.appendChild(service);

        sidebarUl.appendChild(li);
    }
    TogglePanel("location");
}

function CalculateRoute(start,end) {
    var request = {
    language:'de',
    origin:start, 
    destination:end,
    travelMode: google.maps.DirectionsTravelMode.DRIVING
};
  
  directionsService.route(request, function(response, status) {
      HideMessage("directionnotFound");
      if (status == google.maps.DirectionsStatus.OK) {
          directionsDisplay.setMap(map);
          directionsDisplay.setPanel(document.getElementById("directionPanel"));
          directionsDisplay.setDirections(response);
          TogglePanel('direction');
      }
      else {
          ShowMessage("directionnotFound", "Bei der Routenerstellung ist ein Fehler aufgetreten.", "errormsg");
      }
  });
}

function TogglePanel(idToActivate) {
    var panels = new Array('#direction', '#location');
    for (var i = 0; i < panels.length; i++) {
        var id = panels[i];
        $(id + "Panel").hide(0,null);
        $(id + "Tab").removeClass("current");
    }
    $("#" + idToActivate + "Panel").show();
    $("#" + idToActivate + "Tab").addClass("current");
}
