  var MM_JSONSERVER = "extra.musik-meyer.net";
  var path = "/fileadmin/config/_walden/dealersearch/";
  var MM_ZOOM_START = 5;
  var MM_ICON_START_MARKER = path + "fadenkreuz32.png";
  var MM_ICON_START_MARKER_WITH = 32;
  var MM_ICON_START_MARKER_HEIGHT = 32;
  var MM_ICON_RESULT_MARKER_WITH = 35;
  var MM_ICON_RESULT_MARKER_HEIGHT = 50;
  var MM_ICON_AJAX_PROZESSING = path + "ajax-loader.gif";
  var MM_TEXT_AJAX_PROZESSING = '<span id="searchrotation">Suche l&auml;uft</span><br><br>';
  var MM_LONGITUTE_START = "10.13";
  var MM_LATITUTE_START = "50.8";
  var MM_ICON_MAP_CENTER = path + "lupe.jpg";
  var MM_ICON_MAP_ZOOM_IN = path + "lupe_.jpg";
  var MM_ICON_MAP_ZOOM_OUT = path + "lupe-.jpg";
  var MM_ICON_MAP_ROUTE = path + "route.jpg";    
  var MM_ICON_MAP_CENTER_TITLE = "In Karte anfahren";
  var MM_ICON_MAP_ZOOM_IN_TITLE = "vergrößern";
  var MM_ICON_MAP_ZOOM_OUT_TITLE = "verkleinern";
  var MM_ICON_MAP_ROUTE_TITLE = "Route berechnen";
  var key = "WA";
  var lon = MM_LONGITUTE_START;
  var lat = MM_LATITUTE_START;
  var rad = "40";
  var map;
  var geocoder = null;

function init() {
  initApp();
  initMap();
  initApp(key);
  updateResults(null,null,"800");
}

function initMap() {
  document.frm_dealersearch.key.value = key.toUpperCase();
  map = new GMap2(document.getElementById("map"));
  map.enableScrollWheelZoom();
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  GEvent.addListener(map, "click", function(overlay, point) {
    if (point) {
      lon = point.lng();
      lat = point.lat();
      drawMap("search");
      updateResults();
    }
  });
  GEvent.addListener(map, "dragend", function(overlay, point) {
    lon = map.getCenter().lng();
    lat = map.getCenter().lat();
  });
  drawMap("start");
  geocoder = new GClientGeocoder();
}

function showAddress(adress) {
  var countrycode = "DE";
  
  if (geocoder) {  
    geocoder.setBaseCountryCode(countrycode);
    geocoder.getLatLng(adress,function(point) {
      if (!point) {
        alert("\"" + adress + "\"" + " nicht gefunden!");
      } else {
        lat = point.lat();
        lon = point.lng();
        map.setCenter(point);
        updateResults();
      }
    });
  } 
}

function initApp(newKey) {
  if (newKey != null){
    key = newKey;
    document.frm_dealersearch.key.value = key.toUpperCase();
    drawMap("start");
  }
  $.ajax({
    type :'GET',
    url :'http://' + MM_JSONSERVER + '/jsonservice/dealersearch.do?action=init&searchKey=' + key,
    dataType :'jsonp',
    jsonp :'jsonp_callback',
    success : function(data) {
      $('div#hiddenfields').html('');
      var html_select = '';
      html_select += 'Radius:<br><select name="rad" onChange="void(updateResults())">';
      var counter = 0;
      $.each(data, function(i, item) {
        name = i;
        if (name == "radius") {
          for (i = 0; i < item.length; i++) {
            html_select += '<option value="' + item[i] + '">' + item[i] + '</option>';
          }
        }
        if (name.indexOf("service_") == 0) {
          $('div#hiddenfields').append(
          '<div id="' + i + '">' + item + '</div>');
        }
        counter += 1;
      });
      html_select += '</select>km';
      $('div#radius').html(html_select);
    }
  });
}

function lowerZindex(marker, b) {
  return -180000000;
}

function createMarker(point, html, tooltip, system) {
  var marker = null;
  if (html == null) {
    icon = new GIcon(G_DEFAULT_ICON, MM_ICON_START_MARKER);
    icon.iconSize = new GSize(MM_ICON_START_MARKER_WITH,MM_ICON_START_MARKER_HEIGHT);
    icon.iconAnchor = new GPoint(MM_ICON_START_MARKER_WITH / 2,MM_ICON_START_MARKER_HEIGHT / 2);
    icon.shadow = '';
    marker = new GMarker(point, {
      icon :icon,
      zIndexProcess :lowerZindex
    });
    marker.clickable = false;
  } else {
    icon = new GIcon(G_DEFAULT_ICON, system);
    icon.iconSize = new GSize(MM_ICON_RESULT_MARKER_WITH,MM_ICON_RESULT_MARKER_HEIGHT);
    icon.iconAnchor = new GPoint(MM_ICON_RESULT_MARKER_WITH / 2,MM_ICON_RESULT_MARKER_HEIGHT / 2);
    icon.shadow = '';                
    marker = new GMarker(point,{icon :icon,title :tooltip});
    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml(html);
    });
  }
  return marker;
}

function drawMap(method) {
  if (method == "start") {
    $('div#hlResults').html('');
    $('div#listResults').html('');
    lat = MM_LATITUTE_START;
    lon = MM_LONGITUTE_START;
  }
  map.clearOverlays();
  map.setCenter(new GLatLng(lat, lon), MM_ZOOM_START);
}

function updateResults(){
  updateResults(null);
}

function updateResults(plon,plat,radius) {
  if(plon != null){
    lon=plon;
    lat=plat;
  }
  if(radius==null){
    rad = document.frm_dealersearch.rad.value;
  }else{
    rad = radius;
  }
  var bounds;
  drawMap("search");
  $('div#listResults').html('<div class="ajaxprozessing" align="center">' + MM_TEXT_AJAX_PROZESSING + '<img border="0" src="' + MM_ICON_AJAX_PROZESSING + '"></div>');
  $.ajax( {
    type :'GET',
    url :'http://' + MM_JSONSERVER + '/jsonservice/dealersearch.do?action=search&lon=' + lon + '&lat=' + lat + '&radius=' + rad + '&searchKey=' + key,
    dataType :'jsonp',
    jsonp :'jsonp_callback',
    success : function(data) {
      bounds = new GLatLngBounds();
      latlng = new GLatLng(lat, lon);
      var marker = createMarker(latlng);
      bounds.extend(latlng);
      map.addOverlay(marker);
      $('div#listResults').html('');
      var counter = 0;
      $.each(data,function(i, item) {
        href = '';
        email = '';
        resultitem_weblink = ''
        resultitem_emaillink = ''
        var markerText = item.name + '<br>('
                         + item.landShort + ') '
                         + item.plz + ' ' + item.city
                         + ' (' + item.distance + 'km) '
                         + '<br>Tel.' + '+' + item.phonepreint + ' ' + item.phonepre + '-' + item.phone;

        if (item.url.length > 10) {
          href = 'javascript:void(window.open("' + item.url + '","_new"))';
          markerText += '<br>Website: <a class="markerlink" href=' + href + '>' + item.url + '</a>';
          resultitem_weblink = '<br>Website: <a class="resultlink" href=' + href + '>' + item.url + '</a>';
        }
        if (item.email.length > 10) {
          resultitem_emaillink += '<br>E-Mail: <a class="resultlink" href="mailto:' + item.email + '">' + item.email + '</a>';
        }

        markerText = '<div class="dealerMarker">' + markerText + '</div>';
        var html_services = '';
        var icon = '';
        if (item.services != "") {
          services = item.services.split(',');
          services.sort();
          for (n = 0; n < services.length; n++) {
            icon = document.getElementById("service_icon_" + services[n]).innerHTML;
            if (icon != "") {
              html_services += '<img src="' + icon + '" border="0">';
            }
          }
        }
        
        center = '<img class="mag" title="' + MM_ICON_MAP_CENTER_TITLE
                 + '" src="' + MM_ICON_MAP_CENTER + '" onClick=centerMap('
                 + item.lat + ',' + item.lon + ',' + i + ')>';
        zoom_in = '<img class="mag" title="' + MM_ICON_MAP_ZOOM_IN_TITLE
                  + '" src="' + MM_ICON_MAP_ZOOM_IN + '" onClick=zoomMap(1)>';
        zoom_out = '<img class="mag" title="' + MM_ICON_MAP_ZOOM_OUT_TITLE
                   + '" src="' + MM_ICON_MAP_ZOOM_OUT + '" onClick=zoomMap(-1)>';
        routelink = '<a href="http://maps.google.com/maps?saddr='
                    + lat + ',' + lon + '&daddr=' + item.street + ','
                    + item.landShort + ',' + item.plz + ',' + item.city
                    + '" target="_new"><img class="mag" title="' + MM_ICON_MAP_ROUTE_TITLE
                    + '" src="' + MM_ICON_MAP_ROUTE + '"></a>';
                  
        routelink = routelink.replace("\u00df","ss").replace("\u00e4","ae").replace("\u00f6","oe").replace("\u00fc","ue").replace("\u00c4","Ae").replace("\u00d6","Oe").replace("\u00dc","Ue");
        resultItem = '<table cellpadding="3" cellspacing="0" class="dealerItem"><tr><td width="100%" valign="top">'
                     + ' (<small>' + item.distance + 'km)</small> ' + '<b><span class="dealerName">' + item.name + '</span></b>' + '<br>';

        if(item.name2 != ""){
          resultItem += item.name2 + '<br>';
        }

        resultItem += item.street + '<br><br>(' + item.landShort + ') ' + item.plz + ' ' + item.city
                      + '<br>Tel.' + '+' + item.phonepreint + ' ' + item.phonepre + '-' + item.phone + '<br>'
                      + resultitem_emaillink + resultitem_weblink + '<br>'
                      + center + zoom_in + zoom_out + routelink + '</td></tr></table><hr class="dealerSeperator">';
								
        $('div#listResults').append(resultItem);

        var latlng = new GLatLng(item.lat,item.lon);
        var marker = createMarker(latlng, '<div>' + markerText + '</div>',
                     (counter + 1) + '. ' + item.name + ' (' + item.distance + 'km) ',icon);
                     bounds.extend(latlng);
                     map.addOverlay(marker);
                     counter += 1;
      });

      $('div#hlResults').html(counter + ' H&auml;ndler gefunden:');
    
      if (counter > 0) {
        map.setZoom(map.getBoundsZoomLevel(bounds));
        var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
        var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
        map.setCenter(new GLatLng(clat, clng));
      }
    }
  });
};

function centerMap(lat, lng, i) {
  map.setCenter(new GLatLng(lat, lng));
  if (map.getMarkers != null) {
    map.getMarkers[i].openInfoWindow();
  }
}
function zoomMap(z) {
  var zoom = map.getZoom();
  if (z != null) {
    zoom += z;
  }
  map.setZoom(zoom);
}
