var dealers = new Object();

var selectedCountry = '';
var selectedCity = '';

var gm_map = '';
var gm_gd = '';
var gm_gc = '';
// var gm_locale = '';

var config = new Object();
var texts = new Object();
   
$(document).ready( function () {
  
  // Configuration
  config.mapLanguage = $("#mapLanguage").text();
  config.selectedCountry = $("#selectedCountry").text();
  config.dealerType = $("#dealerType").text();
  
  // Translations
  texts.showOnMap = $("#showOnMap").text();
  texts.telephonePrefix = $("#telephonePrefix").text();
  texts.showDirectionsFrom = $("#showDirectionsFrom").text();
  texts.addressCity = $("#addressCity").text();
  texts.showButton = $("#showButton").text();
  
  // Google Maps
  gm_map = new GMap2( document.getElementById("dealer_map") );
  gm_map.setCenter(new GLatLng(61.482323, 23.914168), 2);
  gm_map.enableScrollWheelZoom();
  gm_map.addControl(new GSmallMapControl());
  // gm_map.addControl(new GMapTypeControl());  
  gm_map.addControl(new GOverviewMapControl());
  // gm_gd = new GDirections(map, document.getElementById("directions"));
  gm_gc = new GClientGeocoder();

  /* 
  GEvent.addListener(gm_map, "addoverlay", function (overlay) {});
  
  GEvent.addListener(map, "click", function (overlay, point) { if (point != undefined) alert(point) });
  */
  //
  // Dealer form
  //
  
  // Use predefined country
  if (config.selectedCountry) {
    selectedCountry = config.selectedCountry;
    selectCountry();
  }
  // Use country-select
  else {
    getDealers();
  }
  
  $("#dealermap .country").change( function () {
    selectedCountry = $(this).val();
    selectedCity = '';
    if (!selectedCountry) return false;
    selectCountry();
  });
   
  // City-select
  $("#dealermap .city").change( function () {
    selectedCity = $(this).val();
    if (!selectedCity) return false;
    
    // Clear all overlays
    gm_map.clearOverlays();
    
    // Load dealers
    getDealers("city");
    
    // Focus on city
    gm_gc.getLatLng(selectedCity +", "+ selectedCountry, function (gLatLng) {
      gm_map.setCenter(gLatLng);
      gm_map.setZoom(10);
    });
  });

});


function selectCountry () {
  // Clear all overlays
  gm_map.clearOverlays();
  
  // Load cities
  getDealers("country");
  
  // Focus on country
  gm_gc.getLatLng(selectedCountry, function (gLatLng) {
    gm_map.setCenter(gLatLng);
    gm_map.setZoom(5);
  });
  
  // Enable city-select
  $(".city").removeAttr("disabled");
}


function getDealers (mode) {

  var params = new Object();
  if (selectedCountry)   params['country'] = selectedCountry;
  if (selectedCity)      params['city'] = selectedCity; 
  if (config.dealerType) params['type'] = config.dealerType;
  
  $.get("/dealer_xml", params, function (data) {
  
    var countryOptions = '';
    var cityOptions = '';
  
    // Countries
    if (!mode) {
      $("country", data).each( function () {
        var country = $(this).text();
        countryOptions += '<option value="'+ country +'">'+ country +'</option>';
      });
    }
    
    // Cities
    if (mode == "country") {
      $(".city optgroup option").remove();
      $("city", data).each( function () {
        var city = $(this).text();
        cityOptions += '<option value="'+ city +'">'+ city +'</option>';
      });
    }
    
    // Dealers
    if (mode == "city") {
    
      // Remove previous dealers
      var dealerHtml = '';
      dealers = new Object();
      $("#dealer_list .dealer").remove();
      
      $("dealer", data).each( function () {
        var id = $(this).find("id").text();
        var dealer = new Object({
          "name":        $(this).find("name").text(),
          "name_extra":  $(this).find("name_extra").text(), 
          "address":     $(this).find("address").text(),
          "zip":         $(this).find("zip").text(),
          "city":        $(this).find("city").text(),
          "country":     $(this).find("country").text(),
          "telephone":   $(this).find("telephone").text(),
          "coordinates": $(this).find("coordinates").text()
        });
        dealers[ id ] = dealer;
        
        // Dealer html
        dealerHtml += '<div class="dealer">';
        dealerHtml += createDealerHtml(id);
        dealerHtml += '<a class="maplink" id="maplink_'+ id +'" onclick="showDealer('+ id +')">'+ texts.showOnMap +'</a>';
      
        // Dealer coordinates not set, get with getLatLng()
        if (!dealer.coordinates) {
          var address = dealer.address +", "+ dealer.city +", "+ dealer.country;
          gm_gc.getLatLng(address, function (gLatLng) {
            if (gLatLng) {
              createDealerMarker(id, gLatLng);
              // Store coordinates
              var coordinates = gLatLng.lat() +","+ gLatLng.lng();
              setDealerCoordinates(id, coordinates);
            } 
            
            // Set coordinates to "x" (skips next getLatLng check)
            else {
              setDealerCoordinates(id, "x");
            }
          });
        }
        
        // Use stored coordinates
        else if (dealer.coordinates != 'x') {
          var latLng = dealer.coordinates.split(",");
          createDealerMarker(id, new GLatLng(latLng[0], latLng[1]));
        }
        
        dealerHtml += '</div>';
      });
      
      // Append dealer html
      $("#dealer_list").append(dealerHtml)
      $.scrollTo( $("#dealer_list") );
      
      // Show dealers
      $("#dealer_list .dealer").each( function () {
        $(this).fadeIn("slow");
      });
      
      // Show maplinks
      setTimeout( function () {
        $.each(dealers, function (id, dealer) {
          if (dealer.marker) {
            $("#maplink_"+ id).show();
          }
        });
      }, 2500);
    }
    
    // Append country/city options to selects, select first option
    if (countryOptions) {
      $(".country optgroup").append(countryOptions);
      $(".country option:eq(0)").attr("selected", "selected");
    }
    if (cityOptions) {
      $(".city optgroup").append(cityOptions);
      $(".city option:eq(0)").attr("selected", "selected");
    }
  });
}


function createDealerMarker (id, gLatLng) {
  var dealer = dealers[ id ];
  if (!gLatLng) return false;
  dealers[ id ].marker = new GMarker(
    gLatLng, 
    new Object({title: dealer.name})
  );
  gm_map.addOverlay( dealers[ id ].marker );
  dealers[ id ].marker.bindInfoWindowHtml( createDealerHtml(id) + createDirectionHtml(id) );
}


function createDealerHtml (id) {
  var dealer = dealers[ id ];
  if (!dealer) return false;
  var html = 
    "<b>"+ dealer.name +"</b><br />"+
    (selectedCountry == "Germany" ? (dealer.name_extra ? dealer.name_extra +"<br />" : "") : "") +
    dealer.address +"<br />"+
    dealer.zip +" "+ dealer.city +"<br />"+
    texts.telephonePrefix + dealer.telephone +"<br />";
  return html;
}


function setDealerCoordinates (id, coordinates) {
  if (!id || !coordinates) return false;
  var url = '/dealer_setcoordinates';
  $.post(url, {
    "cmf_op": "edit",
    "cmf_pids": id,
    "id": id,
    "cmf_0_19": coordinates
  }, 
  function () {
  });
}


function showDealer (id) {
  var dealer = dealers[ id ];
  if (!dealer) return false;
  $.scrollTo({top: 300, left: 0}, 500);
  dealer.marker.openInfoWindowHtml( createDealerHtml(id) + createDirectionHtml(id) );
  gm_map.setZoom(15);
}


function createDirectionHtml (id) {
  var html = 
    texts.showDirectionsFrom +
    '<form method="get" class="directions" id="directions_'+ id +'" name="directions_'+ id +'" onsubmit="showDirections('+ id +', this); return false" action="#">'+
    '<input type="text" name="from" class="from" value="" />'+
    '<input type="submit" name="submit" class="show" value="'+ texts.showButton +'" /><br />'+
    texts.addressCity +
    '</form>';
  return html;
}


function showDirections (id, form) {
  var dealer = dealers[ id ];
  var from = $(form).find("input[@name=from]").val();
  var to = dealer.address +", "+ dealer.city +", "+ dealer.country;
  if (!from || !to) return false;
  var url = 'http://maps.google.com/maps?f=d&hl='+ config.mapLanguage +'&saddr='+ from +'&daddr='+ to;
  window.open(url);
  return false;
}


$(window).unload( function () {
  GUnload();
});

 