// editmap.js
//

var mw = '540px';
var mh = '400px';
var map;
var marker;
var polylineClick;
var gss;


function newPos() {
    var lat = document.edform.lat.value;
    var lon = document.edform.lon.value;
    if (Math.abs(lat) > 90) {
        alert("Latitude must be no greater than +/- 90 degrees");
	return;
    }
    if (Math.abs(lon) > 180) {
        lon = 0;
        alert("Longitude must be no greater than +/- 180 degrees");
	return;
    }
    var np = new GLatLng(lat,lon);
    marker.setPoint(np);
    setGrid();
}


function newGrid(grid) {
       var pos = grid2ll(grid);
       var np = new GLatLng(pos.lat+0.02,pos.lon+0.04);
       marker.setPoint(np);
       setGrid();
}


function toGrid(mpLat,mpLon) {

       /* Long/Lat to QTH locator conversion largely        */
       /* inspired from the DL4MFM code found here :        */
       /* http://members.aol.com/mfietz/ham/calcloce.html   */
     
       var ychr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
       var ynum = "0123456789";
       var yqth, yi, yk, ydiv, yres, ylp, y;
       var y     = 0;
       var ycalc = new Array(0,0,0);
       var yn    = new Array(0,0,0,0,0,0,0);

       ycalc[1] = mpLon + 180;
       ycalc[2] = mpLat +  90;

       for (yi = 1; yi < 3; ++yi) {
	for (yk = 1; yk < 4; ++yk) {
	  if (yk != 3) {
	    if (yi == 1) {
	      if (yk == 1) ydiv = 20;
	      if (yk == 2) ydiv = 2;
	    }
	    if (yi == 2) {
	      if (yk == 1) ydiv = 10;
	      if (yk == 2) ydiv = 1;
	    }

	    yres = ycalc[yi] / ydiv;
	    ycalc[yi] = yres;
	    if (ycalc[yi]>0)
	      ylp = Math.floor(yres)
	    else
	      ylp = Math.ceil(yres);
	    ycalc[yi] = (ycalc[yi] - ylp) * ydiv;
	  }
	  else {
	    if (yi == 1)
	      ydiv = 12
	    else
	      ydiv = 24;

	    yres = ycalc[yi] * ydiv;
	    ycalc[yi] = yres;
	    if (ycalc[yi] > 0)
	      ylp = Math.floor(yres)
	    else
	      ylp = Math.ceil(yres);
	  }

	++y;
	yn[y] = ylp;
	}
       }

       yqth = ychr.charAt(yn[1]) + ychr.charAt(yn[4]) + ynum.charAt(yn[2]);
       yqth += ynum.charAt(yn[5]) + ychr.charAt(yn[3]).toLowerCase() + ychr.charAt(yn[6]).toLowerCase();

       return(yqth);
}


function toDMS(mpLat,mpLon) {
    var Result = new Object;
    var longDir = "E";
    var longDeg;
    var longMin;
    var latDir = "N";
    var latDeg;
    var latMin;

    if (mpLon < 0) longDir = "W";
    if (mpLat < 0)  latDir = "S";

    if (mpLon > 0) {
	longDeg = Math.floor(mpLon);
	longMin = (mpLon - longDeg) * 100;
    } else {
	longDeg = Math.ceil(mpLon);
	longMin = (longDeg - mpLon) * 100;
    }
    if (mpLat > 0) {
	latDeg = Math.floor(mpLat);
	latMin = (mpLat - latDeg) * 100;
    } else {
	latDeg = Math.ceil(mpLat);
	latMin = (latDeg - mpLat) * 100;
    }

    var longMin2 = longMin * 60 / 100;
    var longSec = Math.round((longMin2 - Math.floor(longMin2)) * 60);
    var latMin2 = latMin * 60 / 100;
    var latSec = Math.round((latMin2 - Math.floor(latMin2)) * 60);

    Result.lonDMS = longDeg + "&deg; " + Math.floor(longMin2) + "' " + longSec + "'' "+ longDir;
    Result.latDMS = latDeg + "&deg; " + Math.floor(latMin2) + "' " + latSec + "'' "+ latDir;

    return Result;
}


function setGrid() {

    var mPoint = marker.getPoint();

    var mpLat = Math.round(mPoint.lat() * 1000000)/1000000;
    var mpLon = Math.round(mPoint.lng() * 1000000)/1000000;

    e("lat").value = mpLat;
    e("lon").value = mpLon;
    e("grid").value = toGrid(mpLat,mpLon);

    var li = e('locInfo');
    var dms = toDMS(mpLat,mpLon);

    li.innerHTML = dms.latDMS + '&nbsp; &nbsp; &nbsp;' + dms.lonDMS;

    map.removeOverlay(polylineClick);
    map.setCenter(mPoint);

    // Square limits

    var bottomLeftLong = Math.floor(mpLon / 0.0833333333) * 0.0833333333;
    var bottomLeftLat = Math.floor(mpLat / 0.0416666666) * 0.0416666666;

    polylineClick = new GPolyline([
	new GLatLng(bottomLeftLat, bottomLeftLong),
	new GLatLng(bottomLeftLat, bottomLeftLong + 0.0833333333),
	new GLatLng(bottomLeftLat + 0.0416666666, bottomLeftLong + 0.0833333333),
	new GLatLng(bottomLeftLat + 0.0416666666, bottomLeftLong),
	new GLatLng(bottomLeftLat, bottomLeftLong)
	], "#FF0000", 3);

    map.addOverlay(polylineClick);
}


function setMS(oldz,newz) {
    if (ms = e('mapscale')) ms.value = newz;
}
    

function loadG(mapkey) {
    gss = mapkey;
    if (GBrowserIsCompatible()) {
	var panel = e('map');
	panel.style.height = mh;
	panel.style.width = mw;
	var zoom = 12;

	if (ms = e('mapscale')) zoom = parseInt(ms.value);

	point = new GLatLng(e("lat").value, e("lon").value);
	marker = new GMarker(point, {draggable: true});

	/* Portions of this script were inspired by Laurent Haas, F6FVY and DL4MFM */

	/**********************************************************/
	/*                                                        */
	/*  Adapted for QRZ by AA7BQ - Aug 2007                   */
	/*                                                        */
	/**********************************************************/

	map = new GMap2(e("map"));
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	  
	map.setCenter(point, zoom);
	map.addOverlay(marker);

	setGrid();

	GEvent.addListener(marker, 'dragend', setGrid);
	GEvent.addListener(map, 'zoomend', setMS);

    } else {
	// Display a warning if the browser is not compatible
	alert("Sorry, the Google Maps API is not compatible with your browser.");
    }
} 


function grid2ll(grid) {
    var result = new Object;
    grid = grid.toUpperCase();

    result.lon = (20*(grid.charCodeAt(0)-65) + 2*(grid.charCodeAt(2)-48) + 5*(grid.charCodeAt(4)-65)/60) - 180;
    result.lat = (10*(grid.charCodeAt(1)-65) +   (grid.charCodeAt(3)-48) + 5*(grid.charCodeAt(5)-65)/120) - 90;

    return(result);
}



var xmlHttp;

function getGeo() { 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null) {
     alert ("Browser does not support HTTP Request")
     return;
    } 
    var url="/geo/";
    xmlHttp.onreadystatechange=stateChanged ;
    xmlHttp.open("post",url,true);
    xmlHttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');

    var data = 'id=' + gss + "&";
    data += 'addr1=' + e("addr1").value + "&";
    data += 'addr2=' + e("addr2").value + "&";
    data += 'state=' + e("state").value + "&";
    data += 'zip=' + e("zip").value + "&";
    data += 'country=' + e("country").value;

    xmlHttp.send(data);
}


function stateChanged() { 
    var e;

    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
	xmlDoc=xmlHttp.responseXML;

	e = xmlDoc.getElementsByTagName("lat");
	if (e.length) e("lat").value = e[0].childNodes[0].nodeValue;

	e = xmlDoc.getElementsByTagName("lon");
	if (e.length) e("lon").value = e[0].childNodes[0].nodeValue;

	e = xmlDoc.getElementsByTagName("grid");
	if (e.length) e("grid").value = e[0].childNodes[0].nodeValue;

	e = xmlDoc.getElementsByTagName("county");
	if (e.length) e("county").value = e[0].childNodes[0].nodeValue;

	e = xmlDoc.getElementsByTagName("accuracy");
	if (e.length) e("accuracy").innerHTML = "Accuracy: " + e[0].childNodes[0].nodeValue;

	newPos();
    }
} 


function GetXmlHttpObject() { 
    var objXMLHttp=null;
    if (window.XMLHttpRequest) {
	 objXMLHttp=new XMLHttpRequest();

    } else if (window.ActiveXObject) {
	 objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    return objXMLHttp;
}


function locateHelp() {
    window.open("http://www.qrz.com/locatehelp.html","_blank","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=no, copyhistory=no, width=450, height=400");
}


