
var map;
var centerX;
var centerY;

this.goToPoint = goToPoint;
this.hideSubmitButton = hideSubmitButton;
this.zoomTo = zoomTo;
this.map;

function mapLoad(lat, lon) {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    
    
    myPoint = new GPoint(lat, lon);
    myMarker = new GMarker(myPoint, {draggable: true});
    map.setCenter(new GLatLng(this.myPoint.y, this.myPoint.x), 1);
    
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    var mini=new GOverviewMapControl(new GSize(200, 150));
    map.addControl(mini);
    var omap=document.getElementById("map_overview");
    var place=document.getElementById("map");
    place.appendChild(omap); 
    //omap.style.position = "absolute";
    //omap.style.right = "0px";
    //omap.style.bottom = "8px";
    
    map.setMapType(G_HYBRID_TYPE);
    
    if ((document.getElementById('glat').value != "") && (document.getElementById('glon').value != ""))  {
      goToPoint(document.getElementById('glat').value, document.getElementById('dir_lat').selectedIndex, document.getElementById('glon').value, document.getElementById('dir_lon').selectedIndex);
      if (document.getElementById('dir_lat').selectedIndex == 2) {
        centerY = document.getElementById('glat').value * -1;
      } else {
        centerY = document.getElementById('glat').value;
      }
      if (document.getElementById('dir_lon').selectedIndex == 2) {
        centerX = document.getElementById('glon').value * -1;
      } else {
        centerX = document.getElementById('glon').value
      }
      map.setCenter(new GLatLng(centerY, centerX), 14);
    } else {
      
    }
    
    GEvent.addListener(map, 'click', function(overlay, point) {
      if (overlay) { 
        i = map.getZoomLevel();
        alert('zoomlevel');
      } else if (point) {       
        myPoint.x = point.x;
        myPoint.y = point.y;
        map.removeOverlay(myMarker); 
        myMarker = new GMarker(myPoint, {draggable: true});              
        map.addOverlay(myMarker);
        myMarker.enableDragging(); 
        if (document.getElementById("send_maps_button")) {     
          document.getElementById("send_maps_button").style.display = "block";
          document.getElementById("send_maps_button_grayed_out").style.display = "none";
        }
        
        GEvent.addListener(myMarker, 'drag', function() {
          update_input_fields(myMarker.getPoint().y, myMarker.getPoint().x);      
        });
        
        GEvent.addListener(myMarker, 'dragend', function() {
          update_input_fields(myMarker.getPoint().y, myMarker.getPoint().x); 
          myPoint.y = myMarker.getPoint().y;
          myPoint.x = myMarker.getPoint().x;
          centerY = myMarker.getPoint().y;
          centerX = myMarker.getPoint().x;
          map.setCenter(new GLatLng(myPoint.y, myPoint.x));
        });

        myMarker.getPoint().x
        map.setCenter(new GLatLng(myPoint.y, myPoint.x));
        update_input_fields(myPoint.y, myPoint.x);

      }
    });
    
  } 
}

function switchElementVisibility(id)
{
	if (document.getElementById(id).style.display == "block") {
		document.getElementById(id).style.display = "none";
    document.getElementById("map").style.height = "0px";
    map.checkResize();
	}
	else {
		document.getElementById(id).style.display = "block";	
    document.getElementById("map").style.height = "420px";
    map.checkResize();
    //map.setCenter(new GLatLng(15.28418511, 7.734375), 2);
	}

}



function trim_decimals(val, decimals) {
	myFactor =  Math.pow(10, decimals);
	myRoundedVar =  Math.round(val * myFactor) / myFactor;
  return myRoundedVar;
}

function isValidNumber(val) {
  str = val.toString();
  regExp = /[^+\-,.\d]/;
  if (str.match(regExp) == null) {

    return(true);
  } else {
    return(false);
  }
}

function zoomTo(level) {
  this.map.setZoomLevel(level);

}




function update_input_fields(y,x) {
  y = trim_decimals(y, 6);
  document.getElementById("glat").value = Math.abs(y);
  if (y >= 0) {
    document.getElementById("dir_lat").selectedIndex = 1;
  } else {
    document.getElementById("dir_lat").selectedIndex = 2;
  }
  x = trim_decimals(x, 6);
  document.getElementById("glon").value = Math.abs(x);
  if (x >= 0) {
    document.getElementById("dir_lon").selectedIndex = 1;
  } else {
    document.getElementById("dir_lon").selectedIndex = 2;
  }
}
    
function replace_comma(val) {
  if (isValidNumber(val)) {
    new_val = val.toString();
    new_val = new_val.replace(/,/, "."); //kommas durch Punkt ersetzen
    val = parseFloat(new_val)
  }
  return(val);  
}

function check_data (lat, lon, mode) { //mode true: fehlermeldungen und warnungen ausgeben. mode false: nicht ausgeben
  var warnString = "";
  var errorString = "";
  
  lat = replace_comma(lat);
  lon = replace_comma(lon);
   
  if ((document.getElementById("glon").value != "") && (document.getElementById("glat").value != "")) {
  
    if (!isValidNumber(lat)) {
      errorString +=  error_invalid_lat;    
    } else {
      document.getElementById("glat").value = document.getElementById("glat").value.replace( /\+/, ""); //pluszeichen killen
      if (document.getElementById("dir_lat").selectedIndex == 0) { // Himmelsrichtung gewaehlt? NEIN -> erraten
        if ((lat >= -90 ) && (lat <= 90)) { //lat im richtigen Wertebereich?
          if (lat > 0) { // wenn pos Himmelsrichtung = Norden
            document.getElementById("dir_lat").selectedIndex = 1; 

          } else { // wenn lat negativ Himmelsrichtung = Sueden
            document.getElementById("dir_lat").selectedIndex = 2;
            document.getElementById("glat").value = Math.abs(lat);
          } //Ende Himmelsrichtung setzen
        } else { //wenn lat ausserhalb des Wertebereichs
          errorString +=  error_out_of_range_lat;
        } //Ende Pruefung Wertebereich lat      
        
      } else { //ja Himmelsrichtung gewaehlt -> konsitent?
        var dir = document.getElementById("dir_lat").selectedIndex;
        if ((lat >= -90 ) && (lat <= 90)) { 
          if (lat < 0) {
            document.getElementById("glat").value = Math.abs(lat);              
            warnString +=  warning_sign_removed_lat;  
          }
        } else {
          errorString +=  error_out_of_range_lat;
        } //ende if if ((lat >= -90 ) && (lat <= 90)) (im wertebereich)
      } //Ende Himmelsrichtung gwaehlt ja/nein?    
    }
    
    if (!isValidNumber(lon)) {
      errorString += error_invalid_lon;    
    } else {
      document.getElementById("glon").value = document.getElementById("glon").value.replace( /\+/, "");
      if (document.getElementById("dir_lon").selectedIndex == 0) { // Himmelsrichtung gewaehlt? NEIN -> erraten
        if ((lon >= -180 ) && (lon <= 180)) { //lat im richtigen Wertebereich?
          if (lon > 0) { // wenn pos Himmelsrichtung = Norden
            document.getElementById("dir_lon").selectedIndex = 1; 
          } else { // wenn lat negativ Himmelsrichtung = Sueden
            document.getElementById("dir_lon").selectedIndex = 2;
            document.getElementById("glon").value = Math.abs(lon);
          } //Ende Himmelsrichtung setzen
        } else { //wenn lat ausserhalb des Wertebereichs
          errorString += error_out_of_range_lon;
        } //Ende Pruefung Wertebereich lat      
        
      } else { //ja Himmelsrichtung gewaehlt -> konsitent?
        var dir = document.getElementById("dir_lon").selectedIndex;
        if ((lon >= -180 ) && (lon <= 180)) { //lat im richtigen Wertebereich?
          if (lon < 0) {
            document.getElementById("glon").value = Math.abs(lon);              
            warnString += warning_sign_removed_lon;  
          }
        } else {
          errorString += error_out_of_range_lon;
        } //ende  if ((lon >= -180 ) && (lon <= 180)) (im Wertebereich?)
        
      } //Ende Himmelsrichtung gwaehlt ja/nein?    
    }
  
  } else {
    errorString = error_values_missing;
  }
  
  //if ((errorString != "") || (warnString != "")) {
    var output = "";
    if (errorString != "") {
      output += error_init + errorString;
    } else {
      document.getElementById("map").style.display = "block";	
      document.getElementById("map").style.height = "420px";
      map.checkResize();
    }; 
    if (warnString != "") {
      output += warning + warnString;
      output += please_check;
    };
    
  if (output != "" && mode == true) {
    alert (output);
  }
  
  if (errorString != "") {
    return (false); 
  } else {
    return (true);
  }  
}

function addDraggableMarker(lon, lat) {
    check_data(lat,lon, false);
    map.removeOverlay(myMarker); 
    myPoint = new GPoint(lon, lat);
    myMarker = new GMarker(myPoint, {draggable: true});
  	map.addOverlay(myMarker);
    myMarker.enableDragging();      
        
    GEvent.addListener(myMarker, 'drag', function() {
      update_input_fields(myMarker.getPoint().y, myMarker.getPoint().x);      
    });
  
    GEvent.addListener(myMarker, 'dragend', function() {
      update_input_fields(myMarker.getPoint().y, myMarker.getPoint().x); 
      myPoint.y = myMarker.getPoint().y;
      myPoint.x = myMarker.getPoint().x;
      map.setCenter(new GLatLng(myPoint.y, myPoint.x));
      document.getElementById("send_maps_button").style.display = "block";
      document.getElementById("send_maps_button_grayed_out").style.display = "none";
    });
    
    map.setCenter(new GLatLng(myPoint.y, myPoint.x));
    if (document.getElementById("send_maps_button")) {
      document.getElementById("send_maps_button").style.display = "block";
      document.getElementById("send_maps_button_grayed_out").style.display = "none";
    }
}

function goToPoint(lat, dir_lat, lon, dir_lon) {
  
  if (check_data(lat,lon, true) == true) {
  
    //lon = document.getElementById("glon").value;
    //lat = document.getElementById("glat").value
    
    lat = replace_comma(lat);
    lon = replace_comma(lon);
   
    //ready.setFlyTo(true);
      
     /*   
    if (document.getElementById("dir_lon").selectedIndex == 1 || document.getElementById("dir_lon").selectedIndex == 0) {  
      lon = lon;
    } else {
      lon = (-1) * lon;
    }
    */
    
    /*alert ('1. lon :' + lon);
    alert ('2. selected Index (dir_lon): ' + dir_lon);
    alert ('3. '+ (document.getElementById("glon").value * 1));
    */
    if (dir_lon == 2 && lon > 0) { 
      lon = (-1) * lon;
    }
    //alert ('4. lon :' + lon);
    /*
    if (document.getElementById("dir_lat").selectedIndex == 1 || document.getElementById("dir_lat").selectedIndex == 0) { 
       lat = lat;
    } else {
       lat = (-1) * lat;
    }
    */
    
    if (dir_lat == 2 && lat > 0) {
      lat = (-1) * lat;
    }


    addDraggableMarker(lon, lat);

    /*
    map.removeOverlay(myMarker); 
    myMarker = new GMarker(myPoint, {draggable: true});
  	map.addOverlay(myMarker);
    myMarker.enableDragging();      
        
    GEvent.addListener(myMarker, 'drag', function() {
      update_input_fields(myMarker.getPoint().y, myMarker.getPoint().x);      
    });
  
    GEvent.addListener(myMarker, 'dragend', function() {
      update_input_fields(myMarker.getPoint().y, myMarker.getPoint().x); 
      myPoint.y = myMarker.getPoint().y;
      myPoint.x = myMarker.getPoint().x;
      map.setCenter(new GLatLng(myPoint.y, myPoint.x));
      document.getElementById("send_maps_button").style.display = "block";
      document.getElementById("send_maps_button_grayed_out").style.display = "none";
    });
    */
  /*
    map.setCenter(new GLatLng(lat, lon));
    document.getElementById("send_maps_button").style.display = "block";
    document.getElementById("send_maps_button_grayed_out").style.display = "none";
    */
  }
}

function hideSubmitButton() {
  //window.document.getElementById("send_maps_button").style.display = "none";  
  //window.document.getElementById("send_maps_button_grayed_out").style.display = "block";
  document.getElementById("send_maps_button").style.display = "none";  
  document.getElementById("send_maps_button_grayed_out").style.display = "block";
}




function searchFor(str) {
  var geocoder = new GClientGeocoder();  
  /*
  geocoder.getLatLng(
    str,
    function(point) {
      if (!point) {
        alert(str + error_not_found);
      } else {
        //document.getElementById('glon').value = point.x;
        //document.getElementById('glat').value = point.y;
        
        update_input_fields(point.y, point.x);
        goToPoint(document.getElementById("glat").value, document.getElementById("glon").value);
        map.setCenter(new GLatLng(point.y, point.x), 11);        
      }
    }
  );
  */
  // hier Code f&uuml;r einen an den Accuracy Level angepassten Zoomfaktor....
  geocoder.getLocations(
    str, 
    function(response) {
      if (!response || response.Status.code != 200) {
        alert(str + error_not_found);
      } else {
        document.getElementById("dir_lat").selectedIndex = 0;
        document.getElementById("dir_lon").selectedIndex = 0;
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                        place.Point.coordinates[0]);
        
        //update_input_fields(point.y, point.x);
        
        y = trim_decimals(place.Point.coordinates[1], 6);
        document.getElementById("glat").value = (y);
        
        x = trim_decimals(place.Point.coordinates[0], 6);
        document.getElementById("glon").value = (x);
 
        
        //alert('update_input_fields ausgefuehrt. y: ' + y + '/x : ' + x);
        addDraggableMarker(x,y);
        //alert('go to point ausgefuehrt. Koordinaten: ' + y + '/ ' + x);
        zoomLevel = place.AddressDetails.Accuracy + 5;
        map.setCenter(new GLatLng(y, x), zoomLevel);
        //alert('setCenter ausgefuehrt: koordinaten: ' + y + '/ ' + x);
        //alert ('accuracy: ' + place.AddressDetails.Accuracy + ' -- zoomlevel: ' + zoomLevel);
      }
    
    }
  );
  
}

function send_valid(button) {
 if (button.style.display == 'block') {
   return(true);
 } else {
   return(false);
 }
}



function readyState(type) { //Objekt, dass Absendestatus der Freischaltmaske ueberwacht
  function check() {
    if ((this.flyTo == true) && (this.krbGiven == true)) {     document.getElementById('confirm_button').removeAttributeNode(document.getElementById('confirm_button').getAttributeNode('disabled'));  document.getElementById('reject_button').removeAttributeNode(document.getElementById('reject_button').getAttributeNode('disabled'));
      document.getElementById('confirm_button').style.border = '3px solid green';
      document.getElementById('reject_button').style.border = '3px solid red';


    } else {
      if (document.getElementById('confirm_button')) {
        document.getElementById('confirm_button').setAttribute("disabled", 'disabled');
        document.getElementById('reject_button').setAttribute("disabled", 'disabled');
        document.getElementById('confirm_button').style.border = '3px solid #90D490';
        document.getElementById('reject_button').style.border = '3px solid #D49090';
      }
    }

  }
  
  function setFlyTo(val) {
    this.flyTo = val;
    this.check();
  }
  
  function setKrbGiven(val) {
    this.krbGiven = val;
    this.check();
  }
  
  this.flyTo = true;  
  this.check = check;
  this.setFlyTo = setFlyTo;
  this.setKrbGiven = setKrbGiven;
  this.krbGiven;
  
  if (type == 3) {
    this.setKrbGiven(true);
    //this.check();
  } else {
    this.setKrbGiven(false);
    //this.check();
  }
}
  
function openConverter() {  
  this.conv = window.open('converter.php', 'Converter', 'width=500,height=150,scrollbar=no,resizable=yes,status=no');
  if (this.conv.opener == null) { //fuer browser die opener Objekt nicht automatisch uebergeben
    this.conv.opener = window;
  }
  
  this.conv.opener.name = "openerWindow";
}

var conv;

function closeConverter() {
  this.conv.close();
}
var ready = new readyState();




