﻿/**
 * @author isavar
 */
/*
 * fuer ausfuehrlicherere Fehlermeldungen
 */
var debugMode = false;
/*
 * moegliche werte: 
 * 'coords'   : Feld mit den Geokoordinaten wird ausgelesen, Ort angezeigt
 * 'geocoder' : Straße und Ort werden aus der Adresse extrahiert, per GeoCoder angefragt und Ort angezeigt
 */
var addressMode = 'coords';
var reasons=[];   
    reasons[G_GEO_SUCCESS]            = "Success";
    reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
    reasons[G_GEO_MISSING_QUERY]      = "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.";
    reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
    reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
    reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
    reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
    reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
    reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Unknown directions. There is no route available between the two points";
    
var map;
var geocoder;
var errorDiv;
    
/************************************
 *
 * Modul Standortkarte
 * 
 ************************************/   
    function mapload() {
      if (GBrowserIsCompatible()) {
          panel = document.getElementById("googlepanel");
        mapdiv = document.getElementById("googlemap");
        errorDiv = document.getElementById('maperror');
        map = new GMap2(document.getElementById("googlemap"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        //uebersichtskarte initial einklappen
        omc = new GOverviewMapControl();
        map.addControl(omc);
        omc.hide(true);
        
        if(addressMode == 'geocoder') {
            geocoder = new GClientGeocoder();
            geocoder.setBaseCountryCode('de');
            
            address = getAddress();
            getCoordsForAddress(address);
            //getAddressDetails(address);
        }
        else if(addressMode == 'coords') {
            coords = getCoords();
            
            map.setCenter(new GLatLng(coords['lat'],coords['lng']),13);
            fullAddress = document.getElementById('targetAddress').innerHTML;
            map.addOverlay(createMarker(new GLatLng(coords['lat'],coords['lng']), fullAddress));
        }
        
    
      }
    }
    
function getCoords() {
    var coordElement = $('startcoords');
    var coords = new Array;
        coords['lat'] = coordElement.down('.latitude').innerHTML;
        coords['lng'] = coordElement.down('.longitude').innerHTML;
    
    return coords;
}
function createMarker(point, info) {
      var marker = new GMarker(point);
      GEvent.addListener(marker, "click", function() {
       marker.openInfoWindowHtml(info);
      });
      return marker;
}
function getAddress() {
    addressTag = document.getElementById('targetAddress');
    street = $(addressTag).down('.street').innerHTML;
    city = $(addressTag).down('.city').innerHTML;
    return street+', '+city;
}
function getCoordsForAddress(address) {
  geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        return false;
      } 
      else {
        map.setCenter(new GLatLng(point.lat(),point.lng()),13);
        fullAddress = document.getElementById('targetAddress').innerHTML;
        map.addOverlay(createMarker(new GLatLng(point.lat(),point.lng()), fullAddress));
      }
    }
  );
}    
function getAddressDetails(address) {
  geocoder.getLocations(
    address,
    function(response) {
        if (response.Status.code == G_GEO_SUCCESS) {
            var p = response.Placemark[0].Point.coordinates;
            map.setCenter(new GLatLng(p[1],p[0]),13);
            fullAddress = document.getElementById('targetAddress').innerHTML;
            map.addOverlay(createMarker(new GLatLng(p[1],p[0]), fullAddress));
        }
        else {
            if(debugMode) {
                if (reasons[response.Status.code]) {
                    showError(reasons[response.Status.code] + ' ('+response.Status.code+")");
                }
                 else {
                    showError(response.Status.code);
                }
            }
            else {
                showError("Bitte überprüfen Sie Ihre Eingabe.");
            }
        }
    }
  );
}            
/************************************
 *
 * Modul Routenplaner
 * 
 ************************************/
var dir;
var mapdiv;
var panel;
var fromAddress;
var toAddress;    
var fieldvalues = new Array();
function routesMapload() {
  if (GBrowserIsCompatible()) {
      panel = document.getElementById("googlepanel");
    mapdiv = document.getElementById("googlemap");
    errorDiv = document.getElementById('maperror');
    map = new GMap2(mapdiv);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    omc = new GOverviewMapControl();
    map.addControl(omc);
    omc.hide(true);
    
    dir = new GDirections(map, panel);
    
    fromAddress = $('fromAddress').value;
    toAddress = $('toAddress').value;
    if(fromAddress!='' && toAddress!='') {
        setDirections(dir, fromAddress, toAddress);
    }
    else {
        showError("Bitte geben Sie Start- und Zieladresse an.");
    }        
  }
}
function extractParameters(search) {
/* 
    if(search == '') {
        showError('Bitte überprüfen Sie Ihre Eingabe.')
        return;
    };
  */    
  
    var wertestring = search;
    wertestring = wertestring.replace(/\+/g, " "); 
    /* replace encoding errors */
    wertestring=wertestring.replace(/%C3%A4/g,'ä');
    wertestring=wertestring.replace(/%C3%B6/g,'ö');
    wertestring=wertestring.replace(/%C3%BC/g,'ü');
    wertestring=wertestring.replace(/%C3%84/g,'Ä');
    wertestring=wertestring.replace(/%C3%96/g,'Ö');
    wertestring=wertestring.replace(/%C3%9C/g,'Ü');
    wertestring=wertestring.replace(/%C3%9F/g,'&');
    wertestring=wertestring.replace(/&/g,'&amp;');
    wertestring = wertestring.slice(1);
    var paare = wertestring.split("&amp;");
    
    for (var i=0; i < paare.length; i++) {
        var name = paare[i].substring(0, paare[i].indexOf("="));
        var wert = paare[i].substring(paare[i].indexOf("=")+1, paare[i].length);
        fieldvalues[name] = wert;
    }
    
    /*  
    $('fromAddress').value = fieldvalues['fromAddress'];
    $('toAddress').value = fieldvalues['toAddress'];
    */
    
    routesMapload();    
}
function setDirections(dir, fromAddr, toAddr) {
    dir.load("from: " + fromAddr + " to: " + toAddr, {getSteps:true, locale:'de_DE'});
    
    //eventhandler don't work in opera
    GEvent.addListener(dir,"load", onDirectionsLoad);
    GEvent.addListener(dir, "error", onDirectionsError);
}
function onDirectionsLoad() {
    // launch the custom Panel creator a millisecond after the GDirections finishes loading 
    //The delay is required in case we rely on GDirections to perform the initial setCenter 
    setTimeout('customPanel(map,"map",dir,panel)', 1);
}
function onDirectionsError() {
    response = dir.getStatus();
    if(debugMode) {
        if (reasons[response.code]) {
            showError(reasons[response.code] + ' ('+response.code+")");
        }
         else {
            showError(response.code);
        }
    }
    else {
        showError("Bitte überprüfen Sie Ihre Eingabe.");
    }
}
function showRoute() {
    fromAddress = $('fromAddress').value;
    toAddress = $('toAddress').value;
    
    if(fromAddress!='' && toAddress!='') {            
        clearRoute();
        routesMapload();
    }
    else if(fromAddress=='' || toAddress=='') {
        showError("Bitte geben Sie Start- und Zieladresse an.");
    }
    return false;    
}
function clearRoute() {
    if(dir) {
        dir.clear();
    }
    
    Element.hide(errorDiv);
    mapdiv.innerHTML = '';
    panel.innerHTML = '';
}
function showError(error) {
    errorDiv.innerHTML = error;
    Element.show(errorDiv);
}
/*
 * Custom Direction Panel, based on  
 * http://econym.googlepages.com/steps.htm
 *   
 * @param {Object} map            The map object.
 * @param {Object} mapname         A string containing the name of the global variable that points to your map.            
 * @param {Object} dirn            The GDirections() object.
 * @param {Object} div            The div into which the directions are to be placed. 
 */
 
function customPanel(map,mapname,dirn,div) {
    var html = "";
    // ===== local functions =====
    // === waypoint banner ===
    function waypoint(point, type, address) {
      var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
      html += '<table class="startend">';
      html += '  <tr style="cursor: pointer;" onclick='+target+'>';
      html += '    <td class="icon">';
      html += '      <img src="http://www.google.com/intl/en_ALL/mapfiles/icon-dd-' +type+ '-trans.png">'
      html += '    </td>';
      html += '    <td>';
      html +=        address;
      html += '    </td>';
      html += '  </tr>';
      html += '</table>';
    }
    // === route distance ===
    function routeDistance(dist) {
      html += '<div class="distance">Fahrt: ' + dist + '</div>';
    }      
    // === step detail ===
    function detail(point, num, description, dist) {
      var target = '"' + mapname+".showMapBlowup(new GLatLng("+point.toUrlValue(6)+"))"  +'"';
      //html += '<table class="directions">';
      html += '  <tr style="cursor: pointer;" onclick='+target+'>';
      html += '    <td class="number">';
      html += '      <a href="javascript:void(0)"> '+num+'. </a>';
      html += '    </td>';
      html += '    <td class="desc">';
      html +=        description;
      html += '    </td>';
      html += '    <td class="dist">';
      html +=        dist;
      html += '    </td>';
      html += '  </tr>';
      //html += '</table>';
    }
    
    // === Copyright tag ===
    function copyright(text) {
      html += '<div class="copyright"><p>Diese Wegbeschreibung dient nur zu Planungszwecken. Es ist möglich, dass die Verkehrsverhältnisse aufgrund von Baustellen, hohem Verkehrsaufkommen oder anderen Ereignissen von denen auf der Karte abweichen.</p><p>' + text + "</p></div>";
    }
    
    // === read through the GRoutes and GSteps ===
    for (var i=0; i<dirn.getNumRoutes(); i++) {
      if (i==0) {
        var type="play";
      } else {
        var type="pause";
      }
      var route = dirn.getRoute(i);
      var geocode = route.getStartGeocode();
      var point = route.getStep(0).getLatLng();
      // === Waypoint at the start of each GRoute
      waypoint(point, type, geocode.address);
      routeDistance(route.getDistance().html+"  - ca. "+route.getDuration().html);
    
      html += '<table class="directions">';
      for (var j=0; j<route.getNumSteps(); j++) {
        var step = route.getStep(j);
        // === detail lines for each step ===
        detail(step.getLatLng(), j+1, step.getDescriptionHtml(), step.getDistance().html);
      }
      html += '</table>';
    }
    
    // === the final destination waypoint ===   
    var geocode = route.getEndGeocode();
    var point = route.getEndLatLng();
    waypoint(point, "stop", geocode.address);
             
    // === the copyright text ===
    copyright(dirn.getCopyrightsHtml());
    
    // === drop the whole thing into the target div
    div.innerHTML = html;
} // ============ end of customPanel function ===========
