//<![CDATA[

/*
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);
}
var i = 0;
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) {

	var myMercZoomLevel = 5;

	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);
	
	// switch between Mercator and DD if merczoomlevel is set
	if (myMercZoomLevel != 0 && map.getZoom() < myMercZoomLevel) {
		var lBbox = dd2MercMetersLng(lUL.lng()) + "," + dd2MercMetersLat(lUL.lat()) + "," + dd2MercMetersLng(lLR.lng()) + "," + dd2MercMetersLat(lLR.lat());
		var lSRS = "epsg:900913";//epsg:3395
	} else {
		var lBbox = lUL.x + "," + lUL.y + "," + lLR.x + "," + lLR.y;//EPSG:4326
		var lSRS = "EPSG:4326";
	}
	var lURL = this.myBaseURL;
	lURL += "&SRS=" + lSRS;
	lURL += "&BBOX=" + lBbox;
	
	return lURL;
}


/** Create WMS type spec as a GMap Spec. */
function createWMSSpec(wmsURL, gName, gShortName) {
	var tile = new GTileLayer(new GCopyrightCollection(""), 1, 17);
	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);

}

//]]>
