function initialize() {
    if (GBrowserIsCompatible()) {
        document.gmap = new GMap2(document.getElementById("map_canvas"));
        document.gmap.addMapType(G_PHYSICAL_MAP);
        document.gmap.enableScrollWheelZoom();
        document.gmap.addControl(new GSmallMapControl());
        document.gmap.addControl(new GMapTypeControl());
        var box = [new GLatLng(49.5041618347, 2.5416662693),new GLatLng(51.5036087036, 6.39820432663)];
        var bounds = new GLatLngBounds();
        var data = false;
        for (var i = 0; i < box.length; i++) {
            bounds.extend(box[i]);
            data = true;
        }
        if (data) {
            var lngCenter = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;
            var latCenter = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
            var center = new GLatLng(latCenter, lngCenter);
            document.gmap.setCenter(center, document.gmap.getBoundsZoomLevel(bounds), G_NORMAL_MAP);
        } else {
            document.gmap.setCenter(new GPoint(150, 500).toLatLng(), 6, G_NORMAL_MAP);
        };
        GEvent.addListener(document.gmap, 'click', onMapClick);
    }
}

function onCertaintyChange(obj)
{
	if(obj.options[obj.options.selectedIndex].value == 0)  // more than 1 bird
  {
  	$("#amount").val('');
  	$("#amount").enable(true);
  	document.getElementById("amount").style.background="#FFFFFF";
  } else {
  	$("#amount").val('');
  	$("#amount").enable(false);
  	document.getElementById("amount").style.background="#E0E0E0";
  }
}

function checkAmount(field)
{
	var regExpr = new RegExp("^[1-9][0-9]*$");
  if (!regExpr.test(field.value)) {
    field.value = "";
  }
}

function checkLatLng(pnt)
{
    var lat = pnt.lat();
    var lng = pnt.lng();

    // exclude southern hemisphere
    // exclude western hemisphere
    // exclude eastern hemisphere >= 100 lng
    if ((lat < 0) || (lng < 0) || (lng >= 100))
    {
      return false;
    } else {
    	return true;
    }
}

function onMapClick(overlay, ll) {
	  if (!overlay) {
        if (checkLatLng(ll)) {
	  	      markLatLng(ll, true);
	  	      curZoom = document.gmap.getZoom();
	  	      if (curZoom <= 13) {
	  	  	    document.gmap.setCenter(ll, curZoom+1);
	  	      }
	  	  } else {
	  	  	$.get("/translate.php?txt=staynearbelgium",
                  function (data) { alert(data);});
	  	  }
	  }
}

function markLatLng(ll, update) {
    setMarker(ll);
    if (update) newLatLng(ll);
}

function setMarker(ll) {
    document.gmap.clearOverlays();
    var marker = new GMarker(ll, {draggable:true});
    GEvent.addListener(marker, "dragend", function() { newLatLng(marker.getPoint()); });
    document.gmap.addOverlay(marker);
}

function encode_utf8( s )
{
  return unescape( encodeURIComponent( s ) );
}

function decode_utf8( s )
{
  return decodeURIComponent( escape( s ) );
} 

function newLatLng(ll, noNewArea) {
    setLatLgn(ll);
    if (!noNewArea) {
  	  $.get("/proxy/proxy.txt.gebied.php?lat=" + ll.lat() + "&lng=" + ll.lng(),
  	    function (data) {
  	  	  if ($.trim(data)) {
  	  	    var areas = data.split("\n");
  	  	    for (i=0;i<areas.length;i++) {
  	  	      var info = areas[i].split("|");
  	  	  	  if (i==0) { // first area is selected
                $("#location_name").val(info[0]);
                $.get("/proxy/proxy.txt.province.php?area=" + encode_utf8(info[0]) + "&id=" + info[1],
                  function (data) {
               	    if ($.trim(data)) {
                	    var info = data.split("|");
                	    $("#province").val(info[0]);
                    } else {  // area is known but province is not
     	                $("#province").val("");
                    }
                  });
              }
            }
          } else {  // no area name found, reset to empty fields
          	$("#location_name").val("GPS code");
     	      $("#province").val("");
          }
        });
    }
}
           
function setLatLgn(ll)
{
	  $("#location").val(convertDecimalToMin(ll));
}

function selectGebied(li) {
  if (li && li.extra && li.extra[1] && li.extra[2]) {
    var ll = new GLatLng(li.extra[1], li.extra[2]);
    var z = document.gmap.getZoom() < 14 ? 14 : document.gmap.getZoom();
    document.gmap.setCenter(ll, z);
    markLatLng(ll, true, true);
  }
}

function selectSoort(li) {
  if (li && li.extra && li.extra[1]) {
  	$("#soort").val($("<div></div>").html(li.extra[0]).html());  // trick to convert htmlentities
  	$("#species_beepcode").val(li.extra[1]);
  } else {
  	$("#soort").val('');
  	$("#species_beepcode").val('');
  }
}

function convertDecimalToMin(pnt) {
    /*
      Input:  GPoint Or GLatLng
      Output: String with Latitude & Longitude in Degree Minute Second
              Compass format
    */
    var lat = pnt.lat();
    var lng = pnt.lng();
    var dirLat;
    var dirLng;
    if (lat > 0) {
       dirLat = "N";
    }
    else {
       dirLat = "S";
       lat = Math.abs(lat);
    }
    if (lng > 0) {
       dirLng = "E";
    }
    else {
       dirLng = "W";
       lng = Math.abs(lng);
    }

    var degLat = parseInt(lat);               // degrees N, e.g. 51
    if (degLat < 10) degLat = "0" + degLat;   // add leading zero if necessary
    
    var degLng = parseInt(lng);               // degrees E, e.g. 4
    if (degLng < 10) degLng = "0" + degLng;   // add leading zero if necessary
    
    var decLat = lat - degLat;                // get N digits behind comma
    var decLng = lng - degLng;                // get E digits behind comma

    var dmnLat = 60 * decLat;                 // convert N to minutes
    var dmnLng = 60 * decLng;                 // convert E to minutes
    var minLat = parseInt(dmnLat);            // minutes N, e.g. 5
    if (minLat < 10) minLat = "0" + minLat;   // add leading zero if necessary
    var minLng = parseInt(dmnLng);            // minutes E, e.g. 20
    if (minLng < 10) minLng = "0" + minLng;   // add leading zero if necessary
    
    var dscLat = dmnLat - minLat;             
    var dscLng = dmnLng - minLng;
    var secLat = parseInt(60 * dscLat);
    if (secLat < 10) secLat = "0" + secLat;
    var secLng = parseInt(60 * dscLng);
    if (secLng < 10) secLng = "0" + secLng;

    $("#pointx").val(String(degLat)+String(minLat)+String(secLat));
    $("#pointy").val(String(degLng)+String(minLng)+String(secLng));

    var sDeg = degLat + "°" + minLat + "'" + secLat
        + "\"" + dirLat + " " + degLng + "°" + minLng + "'"
        + secLng + "\"" + dirLng;
    return sDeg;
}

function formatItem(row, index, num) {
    return "<div>" + row[1] + "<\/div>";
}

function submitForm() {
  // check soort
	if (($("#soort").val() == "") || ($("#species_beepcode").val() == "")) { 
	  $.get("/translate.php?txt=selectspecies",
          function (data) { alert(data);});
		return false;
	}
	
	// check GPS coordinates
	if (($("#pointx").val() == "") || ($("#pointy").val() == "") || ($("#location").val() == "") || ($("#location_name").val() == "")) {
	  $.get("/translate.php?txt=selectlocation",
          function (data) { alert(data);});
		return false;
	}

	extra_info = $("#extra_info").val();
	if (extra_info.length > 250) {
	  $.get("/translate.php?txt=extrainfotoolong",
          function (data) { alert(data);});
		return false;
	}

  var httpRequest = new XMLHttpRequest();
  httpRequest.open('GET', '/translate.php?txt=confirmbeep', false);
  httpRequest.send(null); // this blocks as request is synchronous
  if (httpRequest.status == 200) {
    // use response here e.g. access
    return confirm(httpRequest.responseText);
  } else {
  	alert("unexpected error");
  	return false;
  }
}

function submit_result(responseText, statusText)
{
	if (responseText == "OK") {
    var httpRequest = new XMLHttpRequest();
    httpRequest.open('GET', '/translate.php?txt=beepsuccess', false);
    httpRequest.send(null); // this blocks as request is synchronous
    if (httpRequest.status == 200) {
      // use response here e.g. access
      alert(httpRequest.responseText);
    } else {
  	  return false;
    }		
	  window.location = "http://www.rarebirdalert.be/add_observation.php";
	} else {
		alert(responseText);
	}
}

$(document).ready(function() {
	  $('#addobsform').ajaxForm({success:submit_result, beforeSubmit:submitForm});	  

    var soort = $("#soort");
    soort.autocomplete("/data/txt.soort.php", { minChars:3, matchSubset:1, matchContains:1, cacheLength:10, mustMatch:1, formatItem:formatItem, onItemSelect:selectSoort});
    var gebied = $("#location_name");
    gebied.autocomplete("/proxy/proxy.txt.gebied.ac.php", { minChars:3, mustMatch:1, matchSubset:1, matchContains:1, cacheLength:10, onItemSelect:selectGebied});
  }
);