/*
 * spherical mercator WMS for google maps - thanks to John Deck for wms236.js on which this is based,
 * and OpenLayers (esp Tim Schaub) for Spherical Mercator examples

 * Use:
 * This script is used by creating a new GTileLayer, setting the required
 * and any desired optional variables, and setting the functions here to
 * override the appropriate GTileLayer ones.
 *
 * At the very least you will need:
 * var myTileLayer= new GTileLayer(new GCopyrightCollection(""),1,17);
 *     myTileLayer.myBaseURL='http://yourserver.org/wms?'
 *     myTileLayer.myLayers='myLayerName';
 *     myTileLayer=CustomGetTileUrl
 *
 * After that you can override the format (myFormat), the level at
 * which the zoom switches (myMercZoomLevel), and the style (myStyles)
 * - be sure to put one style for each layer (both are separated by
 * commas).  You can also override the Opacity:
 *     myTileLayer.myOpacity=0.69
 *     myTileLayer.getOpacity=customOpacity
 *
 * Then you can overlay on google maps with something like:
 * var layer=[G_SATELLITE_MAP.getTileLayers()[0],tileCountry];
 * var custommap = new GMapType(layer, G_SATELLITE_MAP.getProjection(), "WMS");
 * var map = new GMap(document.getElementById("map"));
 *     map.addMapType(custommap);
 */


//Default image format, used if none is specified
var FORMAT_DEFAULT="image/png";

function dd2MercMetersLng(p_lng) {
    return p_lng * 20037508.34 / 180;
}

function dd2MercMetersLat(p_lat) {
    var y = Math.log(Math.tan((90 + p_lat) * Math.PI / 360)) / (Math.PI / 180);
    y = y * 20037508.34 / 180;
    return y
}

CustomGetTileUrl=function(a,b,c) {
  
    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=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
    
    var lSRS="EPSG:900913";

    var lURL=this.myBaseURL;
    if (Math.random() < .5) {lURL = 'http://tc2.activetools.org/wildfish/tilecache.py?';}
    lURL+="&SERVICE=WMS&REQUEST=GetMap&VERSION=1.1.1";
    lURL+="&LAYERS="+this.myLayers;
    lURL+="&STYLES="+this.myStyles;
    lURL+="&FORMAT="+this.myFormat;
    lURL+="&BGCOLOR=0xFFFFFF";
    lURL+="&TRANSPARENT=TRUE";
    lURL+="&SRS="+lSRS;
    lURL+="&BBOX="+lBbox;
    lURL+="&WIDTH=256";
    lURL+="&HEIGHT=256";
    lURL+="&reaspect=false";
    return lURL;
}

function customOpacity() { return this.myOpacity; }
