/**
 * (c) Copyright SECRA GmbH
 */

var secra;
if(!secra)
{
  secra = {};
}
else if(typeof secra != "object")
{
  throw new Error("secra ist kein Objekt!");
}
if(secra.GoogleMaps)
{
  throw new Error("secra.GoogleMaps existiert bereits!");
}

secra.GoogleMaps = function(mapContId, outputLatId, outputLonId, mode) {
  this.compatible = false;
  this.mode = mode || "read";
  this.cache = null;
  this.container = document.getElementById(mapContId);
  this.outputLat = document.getElementById(outputLatId) || null;
  this.outputLon = document.getElementById(outputLonId) || null;
  this.container.that = this;
  this.inputLat = null;
  this.inputLon = null;
  this.submit = null;
  this.str = "";
  this.plz = "";
  this.ort = "";
  this.kreis = "";
  this.bland = "";
  this.land = "Deutschland";
  this.map = null;
  this.geocoder = null;
  this.marker = null;
  this.markers = null;
  this.point = null;
  this.z1 = 6;
  this.z2 = 17;
  this.adresse = "";
  this.p1 = false;
  this.p2 = false;
  this.p3 = false;
  this.p4 = false;
  this.debug = false;
  this.geolat = null;
  this.geolon = null;
  this.images = null;
  this.iconimage = null;
  this.iconshadow = null;
  this.iconXSize = null;
  this.iconYSize = null;
  this.shadowXSize = null;
  this.shadowYSize = null;
  this.iconXAnchor = null;
  this.iconYAnchor = null;
  this.iconEckpunkte = null;
};

/**
 * Anwendungsschnittstelle
 * 
 * Hinzufügen und cachen eines Icons bestehend aus:
 * @param imagePath - Pfad des eigentlichen Bildes
 * @param shadowPath - Pfad des Schattenbildes
 * @param transPath - Pfad des Transparents (optional oder "")
 * @param iW - IMG-width
 * @param iH - IMG-height
 * @param sW - IMG-width
 * @param sH - IMG-height
 * @param aX - Ankerpunkt
 * @param aY - Ankerpunkt
 * @param arrP - Klick-Grenzen z.B. [x1,y1,x2,y2,...,xn,yn]
 */
secra.GoogleMaps.prototype.addIcon = function(imagePath, shadowPath, transPath, iW, iH, sW, sH, aX, aY, arrP) {
  if(this.images === null) {
    this.images = [];
  }
  var imgObj = {};
  if(imagePath !== "") {
    imgObj.image = new Image();
    imgObj.image.src = imagePath;
  }
  if(shadowPath !== "") {
    imgObj.shadow = new Image();
    imgObj.shadow.src = shadowPath;
  }
  if(transPath !== "") {
    imgObj.trans = new Image();
    imgObj.trans.src = transPath;
  }
  imgObj.iXSize = iW || 0;
  imgObj.iYSize = iH || 0;
  imgObj.sXSize = sW || 0;
  imgObj.sYSize = sH || 0;
  imgObj.iXAnc  = aX || 0;
  imgObj.iYAnc  = aY || 0;
  imgObj.iEdges = arrP || [0,0,0,iH,iW,iH,iW,0];
  this.images.push(imgObj);
};

/**
 * Anwendungsschnittstelle
 */
secra.GoogleMaps.prototype.showMap = function() {
  if(this.isCompatible){
    this.container.onmousewheel = this.wheel;
    if(this.container.addEventListener) {
      this.container.addEventListener('DOMMouseScroll', this.wheel, false);
    }
    this.map = new GMap2(this.container);
    this.map.setCenter(new GLatLng(50.0, 10.0), this.z1);
    this.map.setMapType(G_HYBRID_MAP); // Nach setCenter
    this.map.addControl(new GLargeMapControl());
    this.map.addControl(new GMapTypeControl());
    this.map.addControl(new GOverviewMapControl());
    this.map.addControl(new GScaleControl());
    this.map.enableDoubleClickZoom();
    this.map.enableContinuousZoom();
    var that = this;
    if(this.mode === "write") {
      // write-Modus -> Click-Listener mit Icon, Geocodierung
      var glat = this.inputLat !== null ? this.inputLat.value : 0.0;
      var glon = this.inputLon !== null ? this.inputLon.value : 0.0;
      if(glat !== "") {
      	this.callbackPoint(new GLatLng(glat,glon));
      	this.createMarker(this.point, true);
      	this.showIcon(this.marker, this.point);
      } else {
        if(!this.debug && this.outputLat !== null) {
          this.outputLat.innerHTML += "Suche Adresse, ";
          this.outputLon.innerHTML += "bitte warten Sie ...";
  			}
    		this.geocoder = new GClientGeocoder();
    		this.geocoder.that = this;
      	this.holePoint(this.str, this.plz, this.ort, "", "", this.land);
      }
      GEvent.addListener(this.map, "click", function(o,p){that.clickListener(o,p);});
    }
    else
    {
      //GEvent.addListener(this.map, "zoomend", function(o,p){that.zoomendListener(o,p);});
      this.showMarkers();
    }
  }
};

secra.GoogleMaps.prototype.showSmallMap = function() {
  if(this.isCompatible){
    this.container.onmousewheel = this.wheel;
    if(this.container.addEventListener) {
      this.container.addEventListener('DOMMouseScroll', this.wheel, false);
    }
    this.map = new GMap2(this.container);
    this.map.setCenter(new GLatLng(50.0, 10.0), this.z1);
    this.map.setMapType(G_HYBRID_MAP); // Nach setCenter
    this.map.addControl(new GLargeMapControl());
    this.map.addControl(new GMapTypeControl());
    //this.map.addControl(new GOverviewMapControl());
    this.map.addControl(new GScaleControl());
    this.map.enableDoubleClickZoom();
    this.map.enableContinuousZoom();
    var that = this;
    if(this.mode === "write") {
      // write-Modus -> Click-Listener mit Icon, Geocodierung
      var glat = this.inputLat !== null ? this.inputLat.value : 0.0;
      var glon = this.inputLon !== null ? this.inputLon.value : 0.0;
      if(glat !== "") {
      	this.callbackPoint(new GLatLng(glat,glon));
      	this.createMarker(this.point, true);
      	this.showIcon(this.marker, this.point);
      } else {
        if(!this.debug && this.outputLat !== null) {
          this.outputLat.innerHTML += "Suche Adresse, ";
          this.outputLon.innerHTML += "bitte warten Sie ...";
  			}
    		this.geocoder = new GClientGeocoder();
    		this.geocoder.that = this;
      	this.holePoint(this.str, this.plz, this.ort, "", "", this.land);
      }
      GEvent.addListener(this.map, "click", function(o,p){that.clickListener(o,p);});
    }
    else
    {
      //GEvent.addListener(this.map, "zoomend", function(o,p){that.zoomendListener(o,p);});
      //this.showMarkers();
    }
  }
};

/**
 * Anwendungsschnittstelle
 */
secra.GoogleMaps.prototype.setCache = function(cacheObj) {
  this.cache = cacheObj;
  this.markers = [];
  var sf = 1;
  var sfm = 1;
  for(var los in this.cache) {
    var losObj = this.cache[los];
    var icon = losObj.icon > 0 ? losObj.icon - 1 : 0;
    if(this.images.length - 1 < icon)
    {
      icon = 0;
    }
/*
    var text = "<table>"+
               "<tr>"+
               "<td>Bezeichnung:</td>"+
               "<td>"+losObj.bez+
               "</td>"+
               "</tr>"+
               "<tr><td>Waldplatz:</td>"+
               "<td>"+losObj.wplatz+
               "</td></tr><tr><td>Soll Festmeter:</td>"+
               "<td>"+losObj.sfm+"</td>"+
               "</tr></table>";
*/

//    sfm = Number(losObj.sfm);
//    if(sfm > 200.0)
//    {
//      sf = 1.5;
//    }
//    else if(sfm > 100.0)
//    {
//      sf = 1;
//    }
//    else if(sfm > 50.0)
//    {
//      sf = 0.8;
//    }
//    else
//    {
//      sf = 0.6;
//    }
    var text = losObj.text === null || losObj.text === "NULL" ? "" : losObj.text;
    sf = Number(losObj.sfak);
    this.addMarker(new GLatLng(losObj.lat,losObj.lon), text, icon, sf);
  }
};

secra.GoogleMaps.prototype.showMarkers = function() {
  var la1 = null, la2 = null, la = null;
  var lo1 = null, lo2 = null, lo = null;
  var m = this.markers[0];
	this.map.clearOverlays();
  this.map.addOverlay(this.markers[0]);
  la = la1 = la2 = Number(m.getPoint().lat());
  lo = lo1 = lo2 = Number(m.getPoint().lng());

  for(var i=1, j=this.markers.length; i < j; i++) {
    m = this.markers[i];
    la = Number(m.getPoint().lat());
    lo = Number(m.getPoint().lng());
    if(la < la1)
    {
      la1 = la;
    }
    else if(la > la2)
    {
      la2 = la;
    }
    if(lo < lo1)
    {
      lo1 = lo;
    }
    else if(lo > lo2)
    {
      lo2 = lo;
    }
    this.map.addOverlay(this.markers[i]);
  }
  this.map.setCenter(new GLatLng((la1 + la2) * 0.5, (lo1 + lo2) * 0.5), this.map.getBoundsZoomLevel(new GLatLngBounds(new GLatLng(la1, lo1), new GLatLng(la2,lo2))));
};

secra.GoogleMaps.prototype.addMarker = function(p, text, iconNr, sizeFactor) {
  var pArr = [], tArr = this.images[iconNr].iEdges;
  // Array-Copy mit SizeFaktor-Anpassung
  for(var i = 0, j = tArr.length; i < j; i++) {
    pArr[i] = tArr[i] * sizeFactor;
  }
  var icon = new GIcon();
  if(this.images[iconNr].image)
  {
    icon.image = this.images[iconNr].image.src;
    icon.transparent = this.images[iconNr].image.src;
  }
  if(this.images[iconNr].shadow)
  {
    icon.shadow = this.images[iconNr].shadow.src;
  }
  if(this.images[iconNr].trans)
  {
    icon.transparent = this.images[iconNr].trans.src;
  }
  icon.iconSize          = new GSize(this.images[iconNr].iXSize * sizeFactor,this.images[iconNr].iYSize * sizeFactor);
  icon.shadowSize        = new GSize(this.images[iconNr].sXSize * sizeFactor,this.images[iconNr].sYSize * sizeFactor);
  icon.iconAnchor        = new GPoint(this.images[iconNr].iXAnc * sizeFactor,this.images[iconNr].iYAnc * sizeFactor);
  icon.imageMap          = pArr;
  icon.infoWindowAnchor  = new GPoint(16 * sizeFactor,16 * sizeFactor);
  var m = new GMarker(p, {"draggable": false,
                      "bouncy": true,
                      "icon":icon,
                      "dragCrossMove": false,
                      "bounceGravity": 1});

	if(this.mode === "read") {
    GEvent.addListener(m, "click", function() {
    m.openInfoWindowHtml(text,
    {"maxWidth":400});
    });
	}
	this.markers.push(m);
	return m;
};

secra.GoogleMaps.prototype.createMarker = function(p, ziehbar) {
	this.map.clearOverlays();
	var sizeFactor = 1;
	var attrObj = {"draggable":     ziehbar,
                 "bouncy":        true,
                 "dragCrossMove": false,
                 "bounceGravity": 1};
	if(this.images && this.images[0]) {
    var icon = new GIcon();
    var pArr = [], tArr = this.images[0].iEdges;
    // Array-Copy mit SizeFaktor-Anpassung
    for(var i = 0, j = tArr.length; i < j; i++) {
    pArr[i] = tArr[i] * sizeFactor;
    }
    if(this.images[0].image)
    {
      icon.image = this.images[0].image.src;
      icon.transparent = this.images[0].image.src;
    }
    if(this.images[0].shadow)
    {
      icon.shadow = this.images[0].shadow.src;
    }
    if(this.images[0].trans)
    {
      icon.transparent = this.images[0].trans.src;
    }
    icon.iconSize          = new GSize(this.images[0].iXSize * sizeFactor,this.images[0].iYSize * sizeFactor);
    icon.shadowSize        = new GSize(this.images[0].sXSize * sizeFactor,this.images[0].sYSize * sizeFactor);
    icon.iconAnchor        = new GPoint(this.images[0].iXAnc * sizeFactor,this.images[0].iYAnc * sizeFactor);
    icon.imageMap          = pArr;
    icon.infoWindowAnchor  = new GPoint(16 * sizeFactor,16 * sizeFactor);
    attrObj.icon = icon;
	}
  this.marker = new GMarker(p, attrObj);

	if(ziehbar) {
	  var that = this;
  	GEvent.addListener(this.marker, "drag", function(){ that.dragListener();} );
		GEvent.addListener(this.marker, "dragend", function(){ that.dragendListener();} );
	}
	this.map.addOverlay(this.marker);
};

secra.GoogleMaps.prototype.showIcon = function(o, p) {
  if(p) {
    if(this.outputLat !== null) {
   	  this.outputLat.innerHTML = this.getLatText(p.lat());
   	  this.outputLon.innerHTML = this.getLonText(p.lng());
    }
  }
  if(!o) {this.createMarker(p, true);}
};

secra.GoogleMaps.prototype.getBounds = function() {
  var bounds = this.map.getBounds();
  
  if(!this.debug && this.outputLat !== null) {
    //this.outputLat.innerHTML = bounds.getSouthWest().lat()+" "+bounds.getSouthWest().lng();
    //this.outputLon.innerHTML = bounds.getNorthEast().lat()+" "+bounds.getNorthEast().lng();
	}
	return {"swlat":bounds.getSouthWest().lat(), "swlng":bounds.getSouthWest().lng(),
	        "nelat":bounds.getNorthEast().lat(), "nelng":bounds.getNorthEast().lng()};
};

secra.GoogleMaps.prototype.clickListener = function(o, p) {
  if(p) {
    if(this.outputLat !== null) {
   	  this.outputLat.innerHTML = this.getLatText(p.lat());
   	  this.outputLon.innerHTML = this.getLonText(p.lng());
    }
    if(this.inputLat !== null) {
     	this.inputLat.value = this.geolat;
     	this.inputLon.value = this.geolon;
    }
    if(this.submit !== null) {
      this.submit.disabled = false;
    }
  }
  if(!o) {this.createMarker(p, true);}
};

secra.GoogleMaps.prototype.zoomendListener = function(ozl, nzl) {
  //alert(ozl+" "+nzl);
  if(nzl > 15)
  {
    
  }
  else if(nzl > 12)
  {
    
  }
  else if(nzl > 9)
  {
    
  }
  else if(nzl > 6)
  {
    
  }
  else
  {
    
  }
};

secra.GoogleMaps.prototype.dragListener = function() {
  this.clickListener(this.marker, this.marker.getPoint());
};

secra.GoogleMaps.prototype.dragendListener = function() {
  this.dragListener();
  this.map.setCenter(this.marker.getPoint());
};

secra.GoogleMaps.prototype.callbackPoint = function(p){
  if(p) {
  	this.point = new GLatLng(p.lat(), p.lng());
    this.map.setCenter(p, this.z2);
    if(this.outputLat) {
      this.outputLat.innerHTML = " ";
		  this.outputLon.innerHTML = " ";
    }
    return;
  }
  if(!this.p1){
  	this.p1=true;this.z2 -= 3;
  	this.holePoint("", this.plz, this.ort, "", "", this.land);
    return;
  }
  if(!this.p2){
  	this.p2=true;this.z2 -= 0;
  	this.holePoint("", this.plz, "", "", this.bland, this.land);
    return;
  }
  if(!this.p3){
  	this.p3=true;this.z2 -= 3;
  	this.holePoint("", "", "", this.kreis, this.bland, this.land);
    return;
  }
  if(!this.p3){
  	this.p3=true;this.z2 -= 3;
  	this.holePoint("", "", "", "", this.bland, this.land);
    return;
  }
};

secra.GoogleMaps.prototype.holePoint = function(str, plz, ort, kreis, bl, l) {
	this.adresse = "";
	if(str !== "") {
  	this.adresse += str + " ";
  }
	if(plz !== "") {
  	this.adresse += plz + " ";
  }
	if(ort !== "") {
  	this.adresse += ort + ", ";
  }
	if(kreis !== "") {
  	this.adresse += kreis + ", ";
  }
	if(bl !== "") {
  	this.adresse += bl + ", ";
  }
  this.adresse += l;
  if(this.adresse == l) {
    this.z2=5;
  }
  var that = this;
  this.geocoder.getLatLng( this.adresse, function(p){ that.callbackPoint(p);});
};

secra.GoogleMaps.prototype.zoomIt = function(delta) {
  if (delta < 0) {
    this.map.zoomOut();
  } else {
    this.map.zoomIn();
  }
  if(this.mode === "read") {
    //this.showMarkers();
  }
};

secra.GoogleMaps.prototype.wheel = function(e){
  var delta = 0;
  if(!e) {
    e = window.event;
  }
  if(e.wheelDelta) {
    delta = e.wheelDelta/120; 
    if(window.opera) {
      delta = -delta;
    }
  } else if(e.detail) {
  delta = -e.detail/3;
  }
  if(delta) {
    this.that.zoomIt(delta);
  }
  if(e.preventDefault) {
    e.preventDefault();
  }
  e.returnValue = false;
};

/**
 * Anwendungsschnittstelle
 */
secra.GoogleMaps.prototype.isCompatible = function() {
  if( typeof GBrowserIsCompatible !== "undefined" && GBrowserIsCompatible() === true ) {
    this.compatible = true;
  }
  return this.compatible;
};

/**
 * Anwendungsschnittstelle
 */
secra.GoogleMaps.prototype.setIcon = function(iconImagePath, iconShadowPath, iX, iY, sX, sY, aX, aY, arrP) {
	this.iconimage  = iconImagePath;
  this.iconshadow = iconShadowPath;
  this.iconXSize = iX;
  this.iconYSize = iY;
  this.shadowXSize = sX;
  this.shadowYSize = sY;
  this.iconXAnchor = aX;
  this.iconYAnchor = aY;
  this.iconEckpunkte = arrP;
};

/**
 * Anwendungsschnittstelle
 */
secra.GoogleMaps.prototype.setFormParameterByName = function(formName, inputLatName, inputLonName, submitName) {
  this.inputLat = document.forms[formName].elements[inputLatName];
  this.inputLon = document.forms[formName].elements[inputLonName];
  this.submit   = document.forms[formName].elements[submitName];
  this.submit.disabled = true;
};

/**
 * Anwendungsschnittstelle
 */
secra.GoogleMaps.prototype.setFormParameterById = function(inputLatId, inputLonId, submitId) {
  this.inputLat = document.getElementById(inputLatId) || null;
  this.inputLon = document.getElementById(inputLonId) || null;
  this.submit   = document.getElementById(submitId);
  this.submit.disabled = true;
};

/**
 * Anwendungsschnittstelle
 */
secra.GoogleMaps.prototype.setAddress = function(str, plz, ort, kreis, bland, land) {
  if(str && str !== "") {
    this.str = str;
  }
  if(plz && plz !== "") {
    this.plz = plz;
  }
  if(ort && ort !== "") {
    this.ort = ort;
  }
  if(kreis && kreis !== "") {
    this.kreis = kreis;
  }
  if(bland && bland !== "") {
    this.bland = bland;
  }
  if(land && land !== "") {
    this.land = land;
  }
};

secra.GoogleMaps.prototype.getLatText = function(lat) {
 	var latrichtung = 'N', latText = "";
	if(lat < 0.0) {latrichtung = 'S';}
	this.geolat = Math.abs(lat);var latgrd = Math.floor(this.geolat);if(latgrd <10) {latgrd = "0"+latgrd;} var latmin = (this.geolat-latgrd)*60;
	var latsek = ((latmin-Math.floor(latmin))*60).toFixed(2);if(latsek <10) {latsek = "0"+latsek;} else if(latsek >= 60) {latsek = 59.99;}
	latmin = Math.floor(latmin);if(latmin <10) {latmin = "0"+latmin;}
	latText = latgrd + "° " + latmin + "' " + latsek + "\" " + latrichtung;
  return latText;
};

secra.GoogleMaps.prototype.getLonText = function(lng) {
 	var lonrichtung = 'E', lonText = "";
	if(lng < 0.0) {lonrichtung = 'W';}
	this.geolon = Math.abs(lng);var longrd = Math.floor(this.geolon);if(longrd <10) {longrd = "0"+longrd;} var lonmin = (this.geolon-longrd)*60;
	var lonsek = ((lonmin-Math.floor(lonmin))*60).toFixed(2);if(lonsek <10) {lonsek = "0"+lonsek;} else if(lonsek >= 60) {lonsek = 59.99;}
	lonmin = Math.floor(lonmin);if(lonmin <10) {lonmin = "0"+lonmin;}
	lonText = longrd + "° " + lonmin + "' " + lonsek + "\" " + lonrichtung;
  return lonText;
};

