var map;
var geo;
var reasons=[];

function getY(g_rest){

var str = g_rest.match(/[0-9]{1}.[0-9]{4,}/g)
return str[1];
}

// getZoomLevel by Ted Timmons, perljam.net. Please leave this comment
//  intact, and send modifications/corrections to google-zoom@perljam.net.
function getZoomLevel(y, maptype) {
  var zoomOffset = 0;
  if (y > 0) {
    zoomOffset = Math.round(Math.log(y*432) / Math.LN2);
    if (zoomOffset < 0) { zoom = 0; }
  }

  var zoom = maptype.getMaximumResolution(0) - zoomOffset;
  return zoom;
}

function load(lat, lon, g_rest) {

  if (GBrowserIsCompatible()) {

    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    new GKeyboardHandler(map);

    map.enableDoubleClickZoom();
    map.enableContinuousZoom();

    var z = g_rest.match(/z=([0-9]{1,2})/);


    if(z == null){
        zoom = getY(g_rest);
        var myzoom = getZoomLevel(zoom, G_SATELLITE_MAP);
    } else {
        if(z[1] != ''){
          var myzoom = parseInt(z[1]);
        }else{
          var myzoom = 4;
        }
    }

    map.setCenter(new GLatLng(lat, lon), myzoom, G_SATELLITE_MAP);


    // == Create a Client Geocoder ==
    geo = new GClientGeocoder();

    // == Array for decoding the failure codes ==
    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_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.";

  }
}

function getWindowHeight(){
  if (window.self && self.innerHeight) {
    return self.innerHeight;
  }
  if (document.documentElement && document.documentElement.clientHeight) {
    return document.documentElement.clientHeight;
  }
  return 0;
}


function resizeMap(){
  var offset = 0;
  var windowHeight = getWindowHeight();

  for (var elem = document.getElementById("map"); elem != null; elem = elem.offsetParent){
    offset += elem.offsetTop;
  }
  var height = windowHeight - offset -10;
  if (height >= 0) {
    document.getElementById("map").style.height = height + "px";
    document.getElementById("desc").style.height = height + "px";
  }
}


// wyswietla liste markerow pobranych przy uzyciu AJAX
function updateMarkers() {

  setField(); //ustawienie wartosci ze wspolrzednymi

  //"przywrócenie wyświetlania formularza" - formularz jest wczesniej "wylaczany" po pomyslnym wyslaniu danych
  document.getElementById('npForm').style.display = 'block';

  //"schowanie przycisku [Zgłoś znalezione miejsce]"
//   document.getElementById('LNewPlaceButton').style.display = 'none';


  //wyczyszczenie "starego" info
  document.getElementById("forminfo").innerHTML = ''

  //na razie tak - potem uzaleznic to od ilosci markerow
  if(map.getZoom() < 14) map.setZoom(14);

  //remove the existing points
  map.clearOverlays();
  //create the boundary for the data
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var getVars = 'ne=' + northEast.toUrlValue()
  + '&sw=' + southWest.toUrlValue()
  + '&latlng=' + map.getCenter().toUrlValue()

  //log the URL for testing
  //GLog.writeUrl('givePlaces.php?'+getVars);






/* ******* COUNTRY START ********  */
  var request2 = GXmlHttp.create();
  var latlng = 'latlng=' + map.getCenter().toUrlValue(); //43.604262,21.577146
  request2.open('GET', 'http://mapy.pomocnik.com/tools/snewplace/giveCountry.php?'+latlng, true);
  request2.onreadystatechange = function() {
  if (request2.readyState != 4) {
    document.getElementById("message3").innerHTML = 'Pobieram nazwę kraju &nbsp;&nbsp;<img src=http://mapy.pomocnik.com/tools/loading2.gif />';
  }
    if (request2.readyState == 4) {
      if (request2.status == 200) {
        result = request2.responseText;
        if(result != ''){
          document.getElementById("message3").innerHTML = 'Kraj: <strong>'+result+'</strong>';
          document.forms.NewPlace.npPlaceName.value = ' ,' +result ;
        }
      }
    }
  }
  request2.send(null);
/* ******* COUNTRY STOP ********  */





  //retrieve the points using Ajax
  var request = GXmlHttp.create();
  request.open('GET', 'http://mapy.pomocnik.com/tools/snewplace/givePlaces.php?'+getVars, true);
  request.onreadystatechange = function() {
  if (request.readyState != 4) {
    document.getElementById("message2").innerHTML = '<p style="margin: 5px 0 8px 8px;">Pobieram dane &nbsp;&nbsp;<img src=http://mapy.pomocnik.com/tools/loading2.gif /></p';
  }
    if (request.readyState == 4) {
      if (request.status == 200) {
        document.getElementById("message2").innerHTML = '<p style="margin: 11px 0 8px 8px;"><strong>Kontynuować zgłoszenie?</strong> <a href="#" onclick="javascript:setField(); Effect.toggle(\'LNewPlaceCheck\', \'appear\'); Effect.toggle(\'LNewPlaceForm\', \'appear\'); return false;">Tak</a> / <a href="#" onclick="Effect.toggle(\'LNewPlaceCheck\', \'appear\'); return false;">Nie</a></p>';
  
        var jscript = request.responseText;
        var points;
        eval(jscript);
        //create each point from the list
        for (i in points) {
          var point = new GLatLng(points[i].lat,points[i].lng);
          var info = '<br /><a href=' + points[i].plink + '/>' + points[i].place + '</a>';
          var marker = createMarker(point,info);
          map.addOverlay(marker);
        }
      }else{
        document.getElementById("message2").innerHTML = '<p style="margin: 5px 0 8px 8px; color: red;">Błąd ['+request.statusText+'], proszę spróbować ponownie za jakiś czas ... <span style="color: black; font-weight: bolder;">[<a href="#" onclick="Effect.toggle(\'LNewPlaceCheck\', \'appear\'); return false;">ZAMKNIJ</a>]</span></p>';
      }
    }
  }

  request.send(null);
}

function createMarker(point, html) {
  var marker = new GMarker(point);
  GEvent.addListener(marker, 'click', function() {
    var markerHTML = html;
    marker.openInfoWindowHtml(markerHTML);
  });
  return marker;
}


// == Geocoding ==
function showAddress() {
  var search = document.getElementById("search").value;
  // == Perform the Geocoding ==
  geo.getLocations(search, function (result){
    // If that was successful
    if (result.Status.code == G_GEO_SUCCESS) {
      // How many resuts were found
//       document.getElementById("message").innerHTML = "Liczba znalezionych wyników: " +result.Placemark.length;
      // Loop through the results, placing markers
      for (var i=0; i<result.Placemark.length; i++) {
        var p = result.Placemark[i].Point.coordinates;
        var marker = new GMarker(new GLatLng(p[1],p[0]));
//         document.getElementById("message").innerHTML += "<br>"+(i+1)+": "+ result.Placemark[i].address + marker.getPoint();
//         map.addOverlay(marker);
      }
      // centre the map on the first result
      var p = result.Placemark[0].Point.coordinates;
      map.setCenter(new GLatLng(p[1],p[0]),14);
    }
    // == Decode the error status ==
    else {
      var reason="Code "+result.Status.code;
      if (reasons[result.Status.code]) {
        reason = reasons[result.Status.code]
      } 
      alert('Could not find "'+search+ '" ' + reason);
    }
  });
}


function myGetLatLng(){
  var search = document.getElementById("searchLink").value;

  // http://maps.google.com/maps?ll=40.106371,-4.324493&z=15&t=k
  // http://maps.google.com/maps?f=q&hl=en&ie=UTF8&om=1&z=14&ll=54.527507,18.516426&spn=0.032376,0.080338&t=k
  // sprawdzenie czy link zawiera wspolrzedne
  var maplink = search.match(/http:\/\/[a-z]+.google.com\/[a-z]*[?]{1}[^\s]*ll=[-]?[0-9]{1,3}\.?[0-9]{0,8},[-]?[0-9]{1,3}\.?[0-9]{0,8}[^\s]*/);

  // komunikat - jesli sa skopane wspolrzedne
  if(maplink == null){
    alert("Podany link nie zawiera współrzędnych lub podane są one w nieprawidłowej formie.\nProszę sprawdzić czy w we wklejonym linku jest fragment, który wygląda mniej więcej tak:\nll=54.527507,18.516426 ");
  } else {

    var tmplatlng = maplink[0].match(/ll=[-]?[0-9]{1,3}\.?[0-9]{0,8},[-]?[0-9]{1,3}\.?[0-9]{0,8}/);
    var latlng = tmplatlng[0].match(/([-]?[0-9]{1,3}\.?[0-9]{0,8}),([-]?[0-9]{1,3}\.?[0-9]{0,8})/);
    var lat = latlng[1];
    var lng = latlng[2];

    var z = maplink[0].match(/z=([0-9]{1,2})/);

    if(z == null){
      //&spn=28.400864,67.148438&z=4
      spn = maplink[0].match(/&spn=[0-9]{1,3}\.?[0-9]{0,8},[0-9]{1,3}\.?[0-9]{0,8}/);
      zoom = getY(spn[0]);
      var myzoom = getZoomLevel(zoom, G_SATELLITE_MAP);

      map.setCenter(new GLatLng(lat, lng), myzoom);
    }else{
      myzoom = parseInt(z[1]);
      map.setCenter(new GLatLng(lat, lng), myzoom);
    }
  }
}


// *** js - formularz zgloszenia nowego miejsca START ***
function setField() {
  document.forms.NewPlace.npCoord.value = map.getCenter().toUrlValue()+","+map.getZoom();
}

function setField2() {
  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var getVars = 'ne=' + northEast.toUrlValue() + '&sw=' + southWest.toUrlValue() + '&latlng=' + map.getCenter().toUrlValue();
  document.forms.NewPlace.npWebsite.value = getVars;
}

function submitNPlace(){
  document.NewPlace.submit();
}
// *** js - formularz zgloszenia nowego miejsca END ***

// *** ajax - formularz zgloszenia nowego miejsca START ***
var http_request = false;
function makePOSTRequest(url, parameters) {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
    http_request = new XMLHttpRequest();
    if (http_request.overrideMimeType) {
      // set type accordingly to anticipated content type
      //http_request.overrideMimeType('text/xml');
      http_request.overrideMimeType('text/html');
    }
  } else if (window.ActiveXObject) { // IE
    try {
      http_request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http_request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {}
    }
  }
  if (!http_request) {
    alert('Cannot create XMLHTTP instance');
    return false;
  }


  http_request.onreadystatechange = alertContents;
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}


function alertContents() {

  if (http_request.readyState != 4) {
    document.getElementById("forminfo").innerHTML = '<p style="margin: 5px 0 8px 8px; text-align: center; color: blue; font-weight: bolder">Wysyłam dane &nbsp;&nbsp;<img src=http://mapy.pomocnik.com/tools/loading2.gif /></p';
  }

  if (http_request.readyState == 4) {
    if (http_request.status == 200) {
      //alert(http_request.responseText);
      result = http_request.responseText;

//       document.getElementById('infoinfo').innerHTML = result;
//       document.getElementById('message').innerHTML = '';

      document.getElementById('npForm').style.display = 'none';

      document.getElementById("forminfo").innerHTML = '<p style="margin: 30px 0 30px 8px; text-align: center; color: blue; font-weight: bolder">Dziękuję za przesłane zgłoszenie. <span style="color: black; font-weight: bolder;">[<a href="#" onclick="document.getElementById(\'LNewPlaceForm\').style.display = \'none\'; return false;">ZAMKNIJ</a>]</span></p>'
      +'<p style="margin-left: 30px;">'+result+'</p>';
    
    } else {
      alert('There was a problem with the request.');
    }
  }
}


function get(obj){
  var poststr = "npName=" + encodeURI( document.getElementById("npName").value ) +
                "&npEmail=" + encodeURI( document.getElementById("npEmail").value ) +
                "&npWebsite=" + encodeURI( document.getElementById("npWebsite").value ) +
                "&npCoord=" + encodeURI( document.getElementById("npCoord").value ) +
                "&npPlaceName=" + encodeURI( document.getElementById("npPlaceName").value ) +
                "&npDesc=" + encodeURI( document.getElementById("npDesc").value );

  makePOSTRequest('http://mapy.pomocnik.com/tools/snewplace/getNewPlace.php', poststr);
}

// *** ajax - formularz zgloszenia nowego miejsca END ***

// ie ssie, ssie so much
function infoON(id){
  document.getElementById(id).style.display = 'block';
}

function infoOFF(id){
  document.getElementById(id).style.display = 'none';
}
