/*
 * Create GoogleMap WMS (transparent) layers on any GoogleMap.
 *
 * Just van den Broecke - just AT justobjects.nl - www.justobjects.nl - www.geoskating.com
 * version: $Id: gmap-wms.js,v 1.11 2008-12-16 11:19:26 just Exp $
 *
 * This (experimental) code can be downloaded from
 * http://www.geotracing.com/gt/script/gmap.js
 *
 * CREDITS
 * This code is based on and inspired by:
 * Brian Flood - http://www.spatialdatalogic.com/cs/blogs/brian_flood/archive/2005/07/11/39.aspx and
 * Kyle Mulka - http://blog.kylemulka.com/?p=287
 * I have merely merged the two approaches taken by each of these great minds !
 *
 * EXAMPLE
 *   // Fake WMS server to be used for overlaying map with transparent GIF
 *   // Use a real WMS server here.
 *   var WMS_URL_ROUTE='http://www.geoskating.com/gmap/route-wms.jsp?';
 *
 *   // Create WMSSpec
 *   // need: wmsURL, gName, gShortName, wmsLayers, wmsStyles, wmsFormat, [wmsVersion], [wmsBgColor], [wmsSrs]
 *   var G_MAP_WMS_SPEC = createWMSSpec(WMS_URL_ROUTE, "MyWMS", "MyWMS", "routes", "default", "image/gif", "1.0.0");
 *
 *   // Use WMSSpec to create transparent overlay on a standard Google MapSpec
 *   var G_MAP_WMS_OVERLAY_SPEC = createWMSOverlaySpec(G_SATELLITE_MAP, G_MAP_WMS_SPEC, "MyOvWMS", "MyOvWMS");
 *
 *   // Setup the map
 *   var map = new GMap2(document.getElementById("map"));
 *   // Create mapspecs array
 *	 map.addMapType(G_NORMAL_MAP);
 *	 map.addMapType(G_SATELLITE_MAP);
 * 	 map.addMapType(G_MAP_WMS_SPEC);
 *	 map.addMapType(G_MAP_WMS_OVERLAY_SPEC);
 *   map.addControl(new GMapTypeControl());
 *   map.setCenter(new GLatLon(52.35, 4.9), 10, G_MAP_WMS_OVERLAY_SPEC);
 */



/*
 Call generic wms service for GoogleMaps v2
 John Deck, UC Berkeley
 Inspiration & Code from:
 Mike Williams http://www.econym.demon.co.uk/googlemaps2/ V2 Reference & custommap code
 Brian Flood http://www.spatialdatalogic.com/cs/blogs/brian_flood/archive/2005/07/11/39.aspx V1 WMS code
 Kyle Mulka http://blog.kylemulka.com/?p=287  V1 WMS code modifications
 http://search.cpan.org/src/RRWO/GPS-Lowrance-0.31/lib/Geo/Coordinates/MercatorMeters.pm
 */

var MAGIC_NUMBER = 6356752.3142;
var DEG2RAD = 0.0174532922519943;
var PI = 3.14159267;
function dd2MercMetersLng(p_lng) {
    return MAGIC_NUMBER * (p_lng * DEG2RAD);
}

function dd2MercMetersLat(p_lat) {
    if (p_lat >= 85) p_lat = 85;
    if (p_lat <= -85) p_lat = -85;
    return MAGIC_NUMBER * Math.log(Math.tan(((p_lat * DEG2RAD) + (PI / 2)) / 2));
}

CustomGetTileUrl=function(a,b,c) {
	if (this.myMercZoomLevel == undefined) {
    	this.myMercZoomLevel = 5;
	}

	if (this.myFormat == undefined) {
    	this.myFormat = FORMAT_DEFAULT;
	}

	if (typeof(window['this.myStyles'])=="undefined") this.myStyles="";
	var lULP = new GPoint(a.x*256,(a.y+1)*256);
	var lLRP = new GPoint((a.x+1)*256,a.y*256);
	var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
	var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);


	var lBbox = 0.0;
	var lSRS = "";

	if (map.getZoom() < this.myMercZoomLevel) {
		// use mercator projection when viewimg large areas
		lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
		lSRS="EPSG:3395";
	}
	else {
		// use geographic projection when viewing details
		lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y;
		lSRS="EPSG:4326";

	}

	var lURL=this.myBaseURL;
	lURL+="&REQUEST=GetMap";
	lURL+="&SERVICE=WMS";
	lURL+="&VERSION=1.1.1";
	lURL+="&LAYERS="+this.myLayers;
	lURL+="&STYLES="+this.myStyles;
	lURL+="&FORMAT="+this.myFormat;
    lURL+="&BGCOLOR="+this.myBgColor;
	lURL+="&TRANSPARENT=TRUE";
	lURL+="&SRS="+lSRS;
	lURL+="&BBOX="+lBbox;
	lURL+="&WIDTH=256";
	lURL+="&HEIGHT=256";
	lURL+="&reaspect=false";
	//document.write("<br>"+lURL + "<br/>")
	//alert(" url is " + lURL);
	return lURL;
}

/** Create WMS type spec as a GMap Spec. */
function createWMSSpec(wmsURL, gName, gShortName, wmsLayers, wmsStyles, wmsFormat, wmsVersion, wmsBgColor, wmsSrs) {
    var d = new Date();
    var copyright = new GCopyright(1,
        new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0,
        "Bathymetry &copy;"+d.getFullYear()+" <a href='http://www.marine-geo.org'>MGDS</a>");
    var copyrightCollection = new GCopyrightCollection("");
    copyrightCollection.addCopyright(copyright);
    var tile = new GTileLayer(copyrightCollection,1,17);

    tile.myLayers = wmsLayers;
    tile.myStyles = (wmsStyles ? wmsStyles : "");
    ;
    tile.myFormat = (wmsFormat ? wmsFormat : "image/gif");
    ;
    tile.myVersion = (wmsVersion ? wmsVersion : "1.1.1");
    tile.myBgColor = (wmsBgColor ? wmsBgColor : "0xFFFFFF");
    tile.myBaseURL = wmsURL;
    tile.getTileUrl = CustomGetTileUrl;

    var layer = [tile];

    var mapType = new GMapType(layer, G_SATELLITE_MAP.getProjection(), gName, G_SATELLITE_MAP);

    return mapType;
}

/** Create transparent WMS overlay layer on standard GMap Spec. */
function createWMSOverlaySpec(gSpec, wmsSpec, gName, gShortName) {
    wmsSpec.getTileLayers()[0].getOpacity = function() {
        return 1.0;
    }
    var layers = [gSpec.getTileLayers()[0], wmsSpec.getTileLayers()[0]];
    return new GMapType(layers, gSpec.getProjection(), gShortName);
}

/** Create transparent WMS overlay layer on another WMS overlay. */
function createWMS2OverlaySpec(gSpec, wmsSpec, wmsSpec2, gName, gShortName) {
    wmsSpec.getTileLayers()[0].getOpacity = function() {
        return 1.0;
    }
    wmsSpec2.getTileLayers()[0].getOpacity = function() {
        return 1.0;
    }
    var layers = [gSpec.getTileLayers()[0], wmsSpec.getTileLayers()[0], wmsSpec2.getTileLayers()[0]];
    return new GMapType(layers, gSpec.getProjection(), gShortName);

}

function createWMS3OverlaySpec(gSpec, wmsSpec, wmsSpec2, wmsSpec3, gName, gShortName) {
    wmsSpec.getTileLayers()[0].getOpacity = function() {
        return 1.0;
    }
    wmsSpec2.getTileLayers()[0].getOpacity = function() {
        return 1.0;
    }
    wmsSpec3.getTileLayers()[0].getOpacity = function() {
        return 1.0;
    }
    var layers = [gSpec.getTileLayers()[0], wmsSpec.getTileLayers()[0], wmsSpec2.getTileLayers()[0], wmsSpec3.getTileLayers()[0]];
    return new GMapType(layers, gSpec.getProjection(), gShortName);

}

// Clickable tracks - Function will not work until the mapserv program is run under the www.rvdata.us url. Otherwise, a cross-domain issue occurs.
function select_point(overlay, point, bounds, core_href)
{
    if (point)
    {
        map.clearOverlays();

        var getVars = '?long='+point.x + "&lat=" + point.y;

        //var request = GXmlHttp.create();
        var request = new XMLHttpRequest();

        // Create our "tiny" marker icon
        var tinyIcon = new GIcon();
        tinyIcon.image = "/files/mm_20_red.png";
        tinyIcon.shadow = "/files/mm_20_shadow.png";
        tinyIcon.iconSize = new GSize(12, 20);
        tinyIcon.shadowSize = new GSize(22, 20);
        tinyIcon.iconAnchor = new GPoint(6, 20);
        tinyIcon.infoWindowAnchor = new GPoint(5, 1);
        
        request.onreadystatechange = function() {
            if(request.readyState == 4) {
                if (request.responseText.indexOf('no results') == -1) {
                    var lines = request.responseText.split('\n');
                    //entry = lines[5].replace("entry_id = '","").replace("'","").replace(/^\s*|\s*$/g,'');
                    //entry = lines[4].replace(/ = '\d*'/g,"").replace(/-id/i,"").replace(/-/g,"").replace(/^\s*|\s*$/g,'').toUpperCase();
                    entry = lines[2].replace("Layer '","").replace("'","").replace("_anno","").replace(/^\s*|\s*$/g,'');
                                
                    markerOptions = { icon:tinyIcon };
                    var marker = new GMarker(point, markerOptions);
                    map.addOverlay(marker);
                    
                    var httpRequest;
                    var type = arguments[0];  // get type of call
                    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
                        httpRequest = new XMLHttpRequest();
                        if (httpRequest.overrideMimeType) {
                            httpRequest.overrideMimeType('text/xml');
                        }
                    }
                    else if (window.ActiveXObject) { // IE
                        try {
                            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                            }
                        catch (e) {
                            try {
                                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                            }
                            catch (e) {}
                        }
                    }
                    var data = "id="+entry;
                    GEvent.addListener(marker, 'click', function (){map.setCenter(point); marker.openInfoWindowHtml(infoWindowHtml)});
                    httpRequest.open('POST', '/work/entry.php', true);
                    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    httpRequest.onreadystatechange = function()
                    {
                        if (httpRequest.readyState == 4)
                        {
                            if (httpRequest.status == 200)
                            {
                                infoWindowHtml = "<div style='font-size:.80em;'>"+httpRequest.responseText+"</div>";
                                marker.openInfoWindowHtml(infoWindowHtml);
                            }
                        }
                    };
                    httpRequest.send(data);
                }
            }
        }
        
        var z=map.getZoom();  // zoom level at which to calculate the tile
        
        var proj = map.getCurrentMapType().getProjection();
        var pt = proj.fromLatLngToPixel(point,z);
        
        var lULP = new GPoint(pt.x,(pt.y+10));
        var lLRP = new GPoint((pt.x+10),pt.y);
        
        var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,z,false);
        var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,z,false);
        
        var lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y; 

        request.open('GET','http://www.rvdata.us/cgi-bin/mapserv?map=/local/home/mgds/web/ws.rvdata.us/htdocs/gis/wms_'+vessel_prefix+'.map&version=1.1.1&service=WMS&request=GetFeatureInfo&layers=Tracks&query_layers=Tracks&srs=EPSG:4326&transparent=TRUE&exceptions=application%2Fvnd.ogc.se_xml&feature_count=1&styles=default&width=10&height=10&x=5&y=5&radius=10&INFO_FORMAT=text/plain&bbox='+lBbox);
        request.send(null);
    }
}